From 2d95bf9f7fa234dcfa33c8d5821b73c6f89e9137 Mon Sep 17 00:00:00 2001 From: Oleksandr Gorkun Date: Fri, 8 Jun 2018 14:39:20 +0300 Subject: [PATCH 0001/2092] MAGETWO-92172: [Backport for 2.2.x] Redundant File Names for Quote Attachments --- lib/internal/Magento/Framework/File/Uploader.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/internal/Magento/Framework/File/Uploader.php b/lib/internal/Magento/Framework/File/Uploader.php index 07de9941271c3..1c6e933020fb2 100644 --- a/lib/internal/Magento/Framework/File/Uploader.php +++ b/lib/internal/Magento/Framework/File/Uploader.php @@ -197,20 +197,22 @@ public function save($destinationFolder, $newFileName = null) $this->_result = false; $destinationFile = $destinationFolder; $fileName = isset($newFileName) ? $newFileName : $this->_file['name']; - $fileName = self::getCorrectFileName($fileName); + $fileName = static::getCorrectFileName($fileName); if ($this->_enableFilesDispersion) { $fileName = $this->correctFileNameCase($fileName); $this->setAllowCreateFolders(true); - $this->_dispretionPath = self::getDispersionPath($fileName); + $this->_dispretionPath = static::getDispersionPath($fileName); $destinationFile .= $this->_dispretionPath; $this->_createDestinationFolder($destinationFile); } if ($this->_allowRenameFiles) { - $fileName = self::getNewFileName(self::_addDirSeparator($destinationFile) . $fileName); + $fileName = static::getNewFileName( + static::_addDirSeparator($destinationFile) . $fileName + ); } - $destinationFile = self::_addDirSeparator($destinationFile) . $fileName; + $destinationFile = static::_addDirSeparator($destinationFile) . $fileName; try { $this->_result = $this->_moveFile($this->_file['tmp_name'], $destinationFile); From 8287053417093ad684343e8558d5e5c8e7e5c368 Mon Sep 17 00:00:00 2001 From: Oleksandr Gorkun Date: Fri, 8 Jun 2018 16:29:32 +0300 Subject: [PATCH 0002/2092] MAGETWO-92172: [Backport for 2.2.x] Redundant File Names for Quote Attachments --- nginx.conf.sample | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nginx.conf.sample b/nginx.conf.sample index 1e20a51a511d3..a252d2aea0ffb 100644 --- a/nginx.conf.sample +++ b/nginx.conf.sample @@ -162,7 +162,7 @@ location /media/import/ { } # PHP entry point for main application -location ~ (index|get|static|report|404|503|health_check)\.php$ { +location ~ ^/(index|get|static|errors/report|errors/404|errors/503|health_check)\.php$ { try_files $uri =404; fastcgi_pass fastcgi_backend; fastcgi_buffers 1024 4k; From 607773051b9a7c409d69be3578909de114295749 Mon Sep 17 00:00:00 2001 From: Roman Leshchenko Date: Wed, 11 Jul 2018 14:34:50 +0300 Subject: [PATCH 0003/2092] MAGETWO-90468: Added posibility to use captcha on share wishlist page --- .../Wishlist/Controller/Index/Send.php | 41 ++++++++++++++++++- app/code/Magento/Wishlist/etc/config.xml | 22 ++++++++++ .../frontend/layout/wishlist_index_share.xml | 17 +++++++- .../view/frontend/templates/sharing.phtml | 1 + 4 files changed, 79 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Wishlist/Controller/Index/Send.php b/app/code/Magento/Wishlist/Controller/Index/Send.php index c2389af6a2282..780f4d94f04d9 100644 --- a/app/code/Magento/Wishlist/Controller/Index/Send.php +++ b/app/code/Magento/Wishlist/Controller/Index/Send.php @@ -8,11 +8,15 @@ use Magento\Framework\App\Action; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\Exception\NotFoundException; use Magento\Framework\Session\Generic as WishlistSession; use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\View\Result\Layout as ResultLayout; +use Magento\Captcha\Helper\Data as CaptchaHelper; +use Magento\Captcha\Observer\CaptchaStringResolver; +use Magento\Framework\App\ObjectManager; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -69,6 +73,16 @@ class Send extends \Magento\Wishlist\Controller\AbstractIndex */ protected $storeManager; + /** + * @var CaptchaHelper|null + */ + protected $captchaHelper; + + /** + * @var CaptchaStringResolver|null + */ + protected $captchaStringResolver; + /** * @param Action\Context $context * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator @@ -81,6 +95,8 @@ class Send extends \Magento\Wishlist\Controller\AbstractIndex * @param WishlistSession $wishlistSession * @param ScopeConfigInterface $scopeConfig * @param StoreManagerInterface $storeManager + * @param CaptchaHelper $captchaHelper|null + * @param CaptchaStringResolver $captchaStringResolver|null * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -94,7 +110,9 @@ public function __construct( \Magento\Customer\Helper\View $customerHelperView, WishlistSession $wishlistSession, ScopeConfigInterface $scopeConfig, - StoreManagerInterface $storeManager + StoreManagerInterface $storeManager, + CaptchaHelper $captchaHelper = null, + CaptchaStringResolver $captchaStringResolver = null ) { $this->_formKeyValidator = $formKeyValidator; $this->_customerSession = $customerSession; @@ -106,6 +124,9 @@ public function __construct( $this->wishlistSession = $wishlistSession; $this->scopeConfig = $scopeConfig; $this->storeManager = $storeManager; + $this->captchaHelper = $captchaHelper ?: ObjectManager::getInstance()->get(CaptchaHelper::class); + $this->captchaStringResolver = $captchaStringResolver ? + : ObjectManager::getInstance()->get(CaptchaStringResolver::class); parent::__construct($context); } @@ -117,16 +138,34 @@ public function __construct( * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + * @throws \Zend_Validate_Exception */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); + $captchaFormName = 'share_wishlist_form'; + /** @var \Magento\Captcha\Model\DefaultModel $captchaModel */ + $captchaModel = $this->captchaHelper->getCaptcha($captchaFormName); + if (!$this->_formKeyValidator->validate($this->getRequest())) { $resultRedirect->setPath('*/*/'); return $resultRedirect; } + if ($captchaModel->isRequired()) { + $word = $this->captchaStringResolver->resolve( + $this->getRequest(), + $captchaFormName + ); + + if (!$captchaModel->isCorrect($word)) { + $this->messageManager->addErrorMessage(__('Incorrect CAPTCHA')); + $resultRedirect->setPath('*/*/share'); + return $resultRedirect; + } + } + $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); diff --git a/app/code/Magento/Wishlist/etc/config.xml b/app/code/Magento/Wishlist/etc/config.xml index 1fec2d1baf9d4..d0e7354df41ac 100644 --- a/app/code/Magento/Wishlist/etc/config.xml +++ b/app/code/Magento/Wishlist/etc/config.xml @@ -17,6 +17,28 @@ 10 255 + + + 1 + + + + + + + + + + + + + + + + 1 + + + diff --git a/app/code/Magento/Wishlist/view/frontend/layout/wishlist_index_share.xml b/app/code/Magento/Wishlist/view/frontend/layout/wishlist_index_share.xml index 09d8675f6b37e..08e1da699e2cb 100644 --- a/app/code/Magento/Wishlist/view/frontend/layout/wishlist_index_share.xml +++ b/app/code/Magento/Wishlist/view/frontend/layout/wishlist_index_share.xml @@ -9,7 +9,22 @@ - + + + + share_wishlist_form + + 230 + + + 50 + + + + + + + diff --git a/app/code/Magento/Wishlist/view/frontend/templates/sharing.phtml b/app/code/Magento/Wishlist/view/frontend/templates/sharing.phtml index 430ebd384c82b..ff01cb4532cc7 100644 --- a/app/code/Magento/Wishlist/view/frontend/templates/sharing.phtml +++ b/app/code/Magento/Wishlist/view/frontend/templates/sharing.phtml @@ -40,6 +40,7 @@ + getChildHtml('captcha'); ?>
- \ No newline at end of file + From 66f06398a11841df014464f77cca94fe01678e4e Mon Sep 17 00:00:00 2001 From: Roman Leshchenko Date: Thu, 26 Jul 2018 14:11:30 +0300 Subject: [PATCH 0026/2092] MAGETWO-90516: Wrong custom option behavior --- .../Product/View/Options/View/Checkable.php | 2 +- .../fieldset/options/view/checkable.phtml | 98 +++++++++---------- 2 files changed, 50 insertions(+), 50 deletions(-) diff --git a/app/code/Magento/Catalog/Block/Product/View/Options/View/Checkable.php b/app/code/Magento/Catalog/Block/Product/View/Options/View/Checkable.php index 45d7531a83623..6adaf56296439 100644 --- a/app/code/Magento/Catalog/Block/Product/View/Options/View/Checkable.php +++ b/app/code/Magento/Catalog/Block/Product/View/Options/View/Checkable.php @@ -57,4 +57,4 @@ public function getCurrencyByStore(ProductCustomOptionValuesInterface $value) : false ); } -} \ No newline at end of file +} diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/composite/fieldset/options/view/checkable.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/composite/fieldset/options/view/checkable.phtml index 827843c8a58bc..99f7018846d0a 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/composite/fieldset/options/view/checkable.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/composite/fieldset/options/view/checkable.phtml @@ -4,39 +4,38 @@ */ $option = $this->getOption(); -if ($option): ?> - getProduct()->getPreconfiguredValues()->getData('options/' . $option->getId()); - $optionType = $option->getType(); - $arraySign = $optionType === 'checkbox' ? '[]' : ''; - $count = 1; - ?> - -
+if ($option) : ?> +getProduct()->getPreconfiguredValues()->getData('options/' . $option->getId()); +$optionType = $option->getType(); +$arraySign = $optionType === 'checkbox' ? '[]' : ''; +$count = 1; +?> - -
- - +
getValues() as $value) : ?> From 3b3edd930f4bf5a05c500dcb4722d1389f309f45 Mon Sep 17 00:00:00 2001 From: Roman Leshchenko Date: Wed, 29 Aug 2018 22:55:18 +0300 Subject: [PATCH 0048/2092] MAGETWO-90516: Wrong custom option behavior --- .../Catalog/Block/Product/View/Options/Select/Multiple.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Catalog/Block/Product/View/Options/Select/Multiple.php b/app/code/Magento/Catalog/Block/Product/View/Options/Select/Multiple.php index 6395a493f7b44..56702919da5d5 100644 --- a/app/code/Magento/Catalog/Block/Product/View/Options/Select/Multiple.php +++ b/app/code/Magento/Catalog/Block/Product/View/Options/Select/Multiple.php @@ -12,7 +12,7 @@ use Magento\Framework\View\Element\Html\Select; /** - * CLass represents necessary logic for dropdown and multiselect option types + * Class represents necessary logic for dropdown and multiselect option types */ class Multiple extends AbstractOptions { From c5cbfc0da9786b67a6908f9df377a2a020f54272 Mon Sep 17 00:00:00 2001 From: Roman Leshchenko Date: Fri, 31 Aug 2018 16:45:53 +0300 Subject: [PATCH 0049/2092] MAGETWO-92728: Fixed wrong admin notifications behavior --- .../Block/Grid/Renderer/Actions.php | 35 +++++++++++-------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php b/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php index 6f0e42bdcbef1..3c4549ba8017c 100644 --- a/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php +++ b/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php @@ -37,28 +37,35 @@ public function __construct( */ public function render(\Magento\Framework\DataObject $row) { - $readDetailsHtml = $row->getUrl() ? '' . + $readDetailsHtml = $row->getUrl() ? '' . __('Read Details') . '' : ''; - $markAsReadHtml = !$row->getIsRead() ? '' . __( - 'Mark as Read' - ) . '' : ''; + $markAsReadHtml = !$row->getIsRead() ? '' . __( + 'Mark as Read' + ) . '' : ''; $encodedUrl = $this->_urlHelper->getEncodedUrl(); return sprintf( '%s%s%s', $readDetailsHtml, $markAsReadHtml, - $this->getUrl( - '*/*/remove/', - [ - '_current' => true, - 'id' => $row->getId(), - \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED => $encodedUrl - ] + $this->escapeHtml( + $this->getUrl( + '*/*/remove/', + [ + '_current' => true, + 'id' => $row->getId(), + \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED => $encodedUrl + ] + ) ), __('Are you sure?'), __('Remove') From c155cf4bfddb75c0f302c73fb38ae4ea77851e07 Mon Sep 17 00:00:00 2001 From: roman Date: Thu, 6 Sep 2018 12:34:38 +0300 Subject: [PATCH 0050/2092] MAGETWO-92728: Fixed wrong admin notifications behavior --- .../AdminNotification/Block/Grid/Renderer/Actions.php | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php b/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php index 3c4549ba8017c..bc25f56faaf53 100644 --- a/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php +++ b/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php @@ -38,16 +38,14 @@ public function __construct( public function render(\Magento\Framework\DataObject $row) { $readDetailsHtml = $row->getUrl() ? '' . __('Read Details') . '' : ''; $markAsReadHtml = !$row->getIsRead() ? '' . __( 'Mark as Read' ) . '' : ''; @@ -57,7 +55,6 @@ public function render(\Magento\Framework\DataObject $row) '%s%s%s', $readDetailsHtml, $markAsReadHtml, - $this->escapeHtml( $this->getUrl( '*/*/remove/', [ @@ -65,8 +62,7 @@ public function render(\Magento\Framework\DataObject $row) 'id' => $row->getId(), \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED => $encodedUrl ] - ) - ), + ), __('Are you sure?'), __('Remove') ); From f854982410be60c809549d1aa052a3fce14dc041 Mon Sep 17 00:00:00 2001 From: roman Date: Thu, 6 Sep 2018 12:36:40 +0300 Subject: [PATCH 0051/2092] MAGETWO-92728: Fixed wrong admin notifications behavior --- .../Block/Grid/Renderer/Actions.php | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php b/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php index bc25f56faaf53..e3ebd8c16fe3a 100644 --- a/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php +++ b/app/code/Magento/AdminNotification/Block/Grid/Renderer/Actions.php @@ -44,8 +44,8 @@ public function render(\Magento\Framework\DataObject $row) $markAsReadHtml = !$row->getIsRead() ? '' . __( 'Mark as Read' ) . '' : ''; @@ -55,14 +55,14 @@ public function render(\Magento\Framework\DataObject $row) '%s%s%s', $readDetailsHtml, $markAsReadHtml, - $this->getUrl( - '*/*/remove/', - [ - '_current' => true, - 'id' => $row->getId(), - \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED => $encodedUrl - ] - ), + $this->getUrl( + '*/*/remove/', + [ + '_current' => true, + 'id' => $row->getId(), + \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED => $encodedUrl + ] + ), __('Are you sure?'), __('Remove') ); From 4daa54d98229cd4bca4835b044c5c2ca1f50c98d Mon Sep 17 00:00:00 2001 From: OlgaVasyltsun Date: Thu, 6 Sep 2018 14:48:16 +0300 Subject: [PATCH 0052/2092] MAGETWO-71157: Servers Configurations Needs Update --- .htaccess | 9 +++++++++ .htaccess.sample | 9 +++++++++ nginx.conf.sample | 5 +++++ pub/.htaccess | 10 ++++++++++ 4 files changed, 33 insertions(+) diff --git a/.htaccess b/.htaccess index 4298b10d9ca7a..ad123614ae08e 100644 --- a/.htaccess +++ b/.htaccess @@ -364,6 +364,15 @@ Require all denied + + + order allow,deny + deny from all + + = 2.4> + Require all denied + + # For 404s and 403s that aren't handled by the application, show plain 404 response ErrorDocument 404 /pub/errors/404.php diff --git a/.htaccess.sample b/.htaccess.sample index a521a347232f5..b405fd3a22b75 100644 --- a/.htaccess.sample +++ b/.htaccess.sample @@ -341,6 +341,15 @@ Require all denied + + + order allow,deny + deny from all + + = 2.4> + Require all denied + + # For 404s and 403s that aren't handled by the application, show plain 404 response ErrorDocument 404 /pub/errors/404.php diff --git a/nginx.conf.sample b/nginx.conf.sample index 6f87a9a076666..856066e0ba72a 100644 --- a/nginx.conf.sample +++ b/nginx.conf.sample @@ -33,6 +33,11 @@ charset UTF-8; error_page 404 403 = /errors/404.php; #add_header "X-UA-Compatible" "IE=Edge"; +# Deny access to sensitive files +location /.user.ini { + deny all; +} + # PHP entry point for setup application location ~* ^/setup($|/) { root $MAGE_ROOT; diff --git a/pub/.htaccess b/pub/.htaccess index 8ba04ff4415f3..9f07f3319837e 100644 --- a/pub/.htaccess +++ b/pub/.htaccess @@ -220,6 +220,16 @@ ErrorDocument 403 /errors/404.php Require all denied +## Deny access to .user.ini## + + + order allow,deny + deny from all + + = 2.4> + Require all denied + + ############################################ From ad1bdacd5f760771ebecab40bbfa237dbd6cea99 Mon Sep 17 00:00:00 2001 From: Viktor Sevch Date: Tue, 11 Sep 2018 09:17:05 +0300 Subject: [PATCH 0053/2092] MAGETWO-94468: Wrong session messages behavior --- .../Model/System/Config/Backend/Ttl.php | 46 +++++++- .../Model/System/Config/Backend/TtlTest.php | 106 ++++++++++++++++++ 2 files changed, 148 insertions(+), 4 deletions(-) create mode 100644 app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/TtlTest.php diff --git a/app/code/Magento/PageCache/Model/System/Config/Backend/Ttl.php b/app/code/Magento/PageCache/Model/System/Config/Backend/Ttl.php index dab8d7be16dd7..95b0ebe72ecd1 100644 --- a/app/code/Magento/PageCache/Model/System/Config/Backend/Ttl.php +++ b/app/code/Magento/PageCache/Model/System/Config/Backend/Ttl.php @@ -6,15 +6,49 @@ namespace Magento\PageCache\Model\System\Config\Backend; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Escaper; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Exception\LocalizedException; + /** - * Backend model for processing Public content cache lifetime settings + * Backend model for processing Public content cache lifetime settings. * * Class Ttl */ class Ttl extends \Magento\Framework\App\Config\Value { /** - * Throw exception if Ttl data is invalid or empty + * @var Escaper + */ + private $escaper; + + /** + * @param \Magento\Framework\Model\Context $context + * @param \Magento\Framework\Registry $registry + * @param ScopeConfigInterface $config + * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList + * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource + * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection + * @param array $data + * @param Escaper|null $escaper + */ + public function __construct( + \Magento\Framework\Model\Context $context, + \Magento\Framework\Registry $registry, + ScopeConfigInterface $config, + \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, + \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, + \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, + array $data = [], + Escaper $escaper = null + ) { + parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); + $this->escaper = $escaper ?: ObjectManager::getInstance()->create(Escaper::class); + } + + /** + * Throw exception if Ttl data is invalid or empty. * * @return $this * @throws \Magento\Framework\Exception\LocalizedException @@ -23,10 +57,14 @@ public function beforeSave() { $value = $this->getValue(); if ($value < 0 || !preg_match('/^[0-9]+$/', $value)) { - throw new \Magento\Framework\Exception\LocalizedException( - __('Ttl value "%1" is not valid. Please use only numbers equal or greater than zero.', $value) + throw new LocalizedException( + __( + 'Ttl value "%1" is not valid. Please use only numbers equal or greater than zero.', + $this->escaper->escapeHtml($value) + ) ); } + return $this; } } diff --git a/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/TtlTest.php b/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/TtlTest.php new file mode 100644 index 0000000000000..f940564ecf34e --- /dev/null +++ b/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/TtlTest.php @@ -0,0 +1,106 @@ +getMockForAbstractClass(ScopeConfigInterface::class); + $configMock->expects($this->any()) + ->method('getValue') + ->with('system/full_page_cache/default') + ->willReturn(['ttl' => 86400]); + + $this->escaperMock = $this->getMockBuilder(Escaper::class)->disableOriginalConstructor()->getMock(); + + $this->ttl = $objectManager->getObject( + Ttl::class, + [ + 'config' => $configMock, + 'data' => ['field' => 'ttl'], + 'escaper' => $this->escaperMock, + ] + ); + } + + /** + * @return array + */ + public function getValidValues(): array + { + return [ + ['3600', '3600'], + ['10000', '10000'], + ['100000', '100000'], + ['1000000', '1000000'], + ]; + } + + /** + * @param string $value + * @param string $expectedValue + * @return void + * @dataProvider getValidValues + */ + public function testBeforeSave(string $value, string $expectedValue) + { + $this->ttl->setValue($value); + $this->ttl->beforeSave(); + $this->assertEquals($expectedValue, $this->ttl->getValue()); + } + + /** + * @return array + */ + public function getInvalidValues(): array + { + return [ + [''], + ['apple'], + ['123 street'], + ['-123'], + ]; + } + + /** + * @param string $value + * @return void + * @expectedException \Magento\Framework\Exception\LocalizedException + * @expectedExceptionMessageRegExp /Ttl value ".+" is not valid. Please .+ only numbers equal or greater than zero./ + * @dataProvider getInvalidValues + */ + public function testBeforeSaveInvalid(string $value) + { + $this->ttl->setValue($value); + $this->escaperMock->expects($this->any())->method('escapeHtml')->with($value)->willReturn($value); + $this->ttl->beforeSave(); + } +} From 226aebf1caf9239c0c9f08dcaa65bd150a862eb4 Mon Sep 17 00:00:00 2001 From: Viktor Sevch Date: Mon, 17 Sep 2018 12:07:50 +0300 Subject: [PATCH 0054/2092] MAGETWO-94468: Wrong session messages behavior --- .../Test/Unit/Model/System/Config/Backend/TtlTest.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/TtlTest.php b/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/TtlTest.php index f940564ecf34e..6fd3307de726c 100644 --- a/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/TtlTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Model/System/Config/Backend/TtlTest.php @@ -15,6 +15,9 @@ use Magento\Framework\Exception\LocalizedException; use PHPUnit\Framework\TestCase; +/** + * Class for tesing backend model for processing Public content cache lifetime settings. + */ class TtlTest extends TestCase { /** From 6066468579f99abf6e1785a5df1b8e6d5ebb3a84 Mon Sep 17 00:00:00 2001 From: Oleksandr Miroshnichenko Date: Mon, 17 Sep 2018 13:39:05 -0500 Subject: [PATCH 0055/2092] MAGETWO-92187: [Backport for 2.2.x] Setup Application uses version of AngularJS with known vulnerabilities --- .../angular-ng-storage.min.js | 2 +- .../pub/angular-sanitize/angular-sanitize.js | 927 +- .../angular-sanitize/angular-sanitize.min.js | 25 +- .../angular-sanitize.min.js.map | 12 +- .../angular-ui-bootstrap.min.js | 2 +- .../angular-ui-router.min.js | 4 +- setup/pub/angular/angular.js | 39722 ++++++++++------ setup/pub/angular/angular.min.js | 543 +- setup/pub/magento/setup/add-database.js | 10 +- setup/pub/magento/setup/app.js | 3 +- setup/pub/magento/setup/complete-backup.js | 8 +- .../pub/magento/setup/create-admin-account.js | 10 +- .../pub/magento/setup/customize-your-store.js | 35 +- setup/pub/magento/setup/data-option.js | 6 +- setup/pub/magento/setup/extension-grid.js | 10 +- .../magento/setup/install-extension-grid.js | 6 +- setup/pub/magento/setup/install.js | 8 +- setup/pub/magento/setup/main.js | 61 +- .../magento/setup/marketplace-credentials.js | 11 +- setup/pub/magento/setup/module-grid.js | 6 +- setup/pub/magento/setup/readiness-check.js | 12 +- setup/pub/magento/setup/select-version.js | 18 +- setup/pub/magento/setup/start-updater.js | 11 +- setup/pub/magento/setup/system-config.js | 3 + .../magento/setup/update-extension-grid.js | 8 +- setup/pub/magento/setup/web-configuration.js | 11 +- .../magento/setup/customize-your-store.phtml | 2 +- 27 files changed, 27358 insertions(+), 14118 deletions(-) diff --git a/setup/pub/angular-ng-storage/angular-ng-storage.min.js b/setup/pub/angular-ng-storage/angular-ng-storage.min.js index f5526bbace8ef..54891ebb4087f 100644 --- a/setup/pub/angular-ng-storage/angular-ng-storage.min.js +++ b/setup/pub/angular-ng-storage/angular-ng-storage.min.js @@ -1 +1 @@ -/*! ngStorage 0.3.0 | Copyright (c) 2013 Gias Kay Lee | MIT License */"use strict";!function(){function a(a){return["$rootScope","$window",function(b,c){for(var d,e,f,g=c[a]||(console.warn("This browser does not support Web Storage!"),{}),h={$default:function(a){for(var b in a)angular.isDefined(h[b])||(h[b]=a[b]);return h},$reset:function(a){for(var b in h)"$"===b[0]||delete h[b];return h.$default(a)}},i=0;ib;b++)(a=p.key(b))&&e===a.slice(0,n)&&(q[a.slice(n)]=g(p.getItem(a)))},$apply:function(){var b;if(m=null,!a.equals(q,l)){b=a.copy(l),a.forEach(q,function(c,d){a.isDefined(c)&&"$"!==d[0]&&(p.setItem(e+d,f(c)),delete b[d])});for(var c in b)p.removeItem(e+c);l=a.copy(q)}},$supported:function(){return!!o}};return q.$sync(),l=a.copy(q),d.$watch(function(){m||(m=j(q.$apply,100,!1))}),h.addEventListener&&h.addEventListener("storage",function(b){if(b.key){var c=k[0];c.hasFocus&&c.hasFocus()||e!==b.key.slice(0,n)||(b.newValue?q[b.key.slice(n)]=g(b.newValue):delete q[b.key.slice(n)],l=a.copy(q),d.$apply())}}),h.addEventListener&&h.addEventListener("beforeunload",function(){q.$apply()}),q}]}}return a=a&&a.module?a:window.angular,a.module("ngStorage",[]).provider("$localStorage",c("localStorage")).provider("$sessionStorage",c("sessionStorage"))}); \ No newline at end of file diff --git a/setup/pub/angular-sanitize/angular-sanitize.js b/setup/pub/angular-sanitize/angular-sanitize.js index 6004460cd17eb..8faa84315009f 100644 --- a/setup/pub/angular-sanitize/angular-sanitize.js +++ b/setup/pub/angular-sanitize/angular-sanitize.js @@ -1,76 +1,79 @@ /** - * @license AngularJS v1.2.14 - * (c) 2010-2014 Google, Inc. http://angularjs.org + * @license AngularJS v1.6.9 + * (c) 2010-2018 Google, Inc. http://angularjs.org * License: MIT */ -(function(window, angular, undefined) {'use strict'; +(function(window, angular) {'use strict'; + + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Any commits to this file should be reviewed with security in mind. * + * Changes to this file can potentially create security vulnerabilities. * + * An approval from 2 Core members with history of modifying * + * this file is required. * + * * + * Does the change somehow allow for arbitrary javascript to be executed? * + * Or allows for someone to change the prototype of built-in objects? * + * Or gives undesired access to variables likes document or window? * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ var $sanitizeMinErr = angular.$$minErr('$sanitize'); + var bind; + var extend; + var forEach; + var isDefined; + var lowercase; + var noop; + var nodeContains; + var htmlParser; + var htmlSanitizeWriter; /** * @ngdoc module * @name ngSanitize * @description * - * # ngSanitize - * * The `ngSanitize` module provides functionality to sanitize HTML. * - * - *
- * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ - /* - * HTML Parser By Misko Hevery (misko@hevery.com) - * based on: HTML Parser By John Resig (ejohn.org) - * Original code by Erik Arvidsson, Mozilla Public License - * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js - * - * // Use like so: - * htmlParser(htmlString, { - * start: function(tag, attrs, unary) {}, - * end: function(tag) {}, - * chars: function(text) {}, - * comment: function(text) {} - * }); - * - */ - - /** * @ngdoc service * @name $sanitize - * @function + * @kind function * * @description - * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are + * Sanitizes an html string by stripping all potentially dangerous tokens. + * + * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make - * it into the returned string, however, since our parser is more strict than a typical browser - * parser, it's possible that some obscure input, which would be recognized as valid HTML by a - * browser, won't make it through the sanitizer. - * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and - * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. + * it into the returned string. * - * @param {string} html Html input. - * @returns {string} Sanitized html. + * The whitelist for URL sanitization of attribute values is configured using the functions + * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider + * `$compileProvider`}. + * + * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}. + * + * @param {string} html HTML input. + * @returns {string} Sanitized HTML. * * @example - + -
+
Snippet: @@ -105,410 +108,538 @@ it('should sanitize the html snippet by default', function() { - expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). + expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('

an html\nclick here\nsnippet

'); }); + it('should inline raw snippet if bound to a trusted value', function() { - expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()). + expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')). toBe("

an html\n" + "click here\n" + "snippet

"); }); + it('should escape snippet without any filter', function() { - expect(element(by.css('#bind-default div')).getInnerHtml()). + expect(element(by.css('#bind-default div')).getAttribute('innerHTML')). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); + it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new text'); - expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). + expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('new text'); - expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe( + expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).toBe( 'new text'); - expect(element(by.css('#bind-default div')).getInnerHtml()).toBe( + expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).toBe( "new <b onclick=\"alert(1)\">text</b>"); });
*/ + + + /** + * @ngdoc provider + * @name $sanitizeProvider + * @this + * + * @description + * Creates and configures {@link $sanitize} instance. + */ function $SanitizeProvider() { + var svgEnabled = false; + this.$get = ['$$sanitizeUri', function($$sanitizeUri) { + if (svgEnabled) { + extend(validElements, svgElements); + } return function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { - return !/^unsafe/.test($$sanitizeUri(uri, isImage)); + return !/^unsafe:/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; - } - function sanitizeText(chars) { - var buf = []; - var writer = htmlSanitizeWriter(buf, angular.noop); - writer.chars(chars); - return buf.join(''); - } - - -// Regular Expressions for parsing tags and attributes - var START_TAG_REGEXP = - /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, - END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, - ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, - BEGIN_TAG_REGEXP = /^/g, - DOCTYPE_REGEXP = /]*?)>/i, - CDATA_REGEXP = //g, - // Match everything outside of normal chars and " (quote character) - NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; - - -// Good source of info about elements and attributes -// http://dev.w3.org/html5/spec/Overview.html#semantics -// http://simon.html5.org/html-elements - -// Safe Void Elements - HTML5 -// http://dev.w3.org/html5/spec/Overview.html#void-elements - var voidElements = makeMap("area,br,col,hr,img,wbr"); - -// Elements that you can, intentionally, leave open (and which close themselves) -// http://dev.w3.org/html5/spec/Overview.html#optional-tags - var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), - optionalEndTagInlineElements = makeMap("rp,rt"), - optionalEndTagElements = angular.extend({}, - optionalEndTagInlineElements, - optionalEndTagBlockElements); - -// Safe Block Elements - HTML5 - var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + - "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + - "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); - -// Inline Elements - HTML5 - var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + - "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + - "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); - - -// Special Elements (can contain anything) - var specialElements = makeMap("script,style"); - - var validElements = angular.extend({}, - voidElements, - blockElements, - inlineElements, - optionalEndTagElements); - -//Attributes that have href and hence need to be sanitized - var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); - var validAttrs = angular.extend({}, uriAttrs, makeMap( - 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ - 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ - 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ - 'scope,scrolling,shape,size,span,start,summary,target,title,type,'+ - 'valign,value,vspace,width')); - - function makeMap(str) { - var obj = {}, items = str.split(','), i; - for (i = 0; i < items.length; i++) obj[items[i]] = true; - return obj; - } + /** + * @ngdoc method + * @name $sanitizeProvider#enableSvg + * @kind function + * + * @description + * Enables a subset of svg to be supported by the sanitizer. + * + *
+ *

By enabling this setting without taking other precautions, you might expose your + * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned + * outside of the containing element and be rendered over other elements on the page (e.g. a login + * link). Such behavior can then result in phishing incidents.

+ * + *

To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg + * tags within the sanitized content:

+ * + *
+ * + *

+         *   .rootOfTheIncludedContent svg {
+         *     overflow: hidden !important;
+         *   }
+         *   
+ *
+ * + * @param {boolean=} flag Enable or disable SVG support in the sanitizer. + * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called + * without an argument or self for chaining otherwise. + */ + this.enableSvg = function(enableSvg) { + if (isDefined(enableSvg)) { + svgEnabled = enableSvg; + return this; + } else { + return svgEnabled; + } + }; - /** - * @example - * htmlParser(htmlString, { - * start: function(tag, attrs, unary) {}, - * end: function(tag) {}, - * chars: function(text) {}, - * comment: function(text) {} - * }); - * - * @param {string} html string - * @param {object} handler - */ - function htmlParser( html, handler ) { - var index, chars, match, stack = [], last = html; - stack.last = function() { return stack[ stack.length - 1 ]; }; - - while ( html ) { - chars = true; + ////////////////////////////////////////////////////////////////////////////////////////////////// + // Private stuff + ////////////////////////////////////////////////////////////////////////////////////////////////// - // Make sure we're not in a script or style element - if ( !stack.last() || !specialElements[ stack.last() ] ) { + bind = angular.bind; + extend = angular.extend; + forEach = angular.forEach; + isDefined = angular.isDefined; + lowercase = angular.lowercase; + noop = angular.noop; - // Comment - if ( html.indexOf("", index) === index) { - if (handler.comment) handler.comment( html.substring( 4, index ) ); - html = html.substring( index + 3 ); - chars = false; - } - // DOCTYPE - } else if ( DOCTYPE_REGEXP.test(html) ) { - match = html.match( DOCTYPE_REGEXP ); + nodeContains = window.Node.prototype.contains || /** @this */ function(arg) { + // eslint-disable-next-line no-bitwise + return !!(this.compareDocumentPosition(arg) & 16); + }; - if ( match ) { - html = html.replace( match[0] , ''); - chars = false; - } - // end tag - } else if ( BEGIN_END_TAGE_REGEXP.test(html) ) { - match = html.match( END_TAG_REGEXP ); - - if ( match ) { - html = html.substring( match[0].length ); - match[0].replace( END_TAG_REGEXP, parseEndTag ); - chars = false; - } + // Regular Expressions for parsing tags and attributes + var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, + // Match everything outside of normal chars and " (quote character) + NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g; + + + // Good source of info about elements and attributes + // http://dev.w3.org/html5/spec/Overview.html#semantics + // http://simon.html5.org/html-elements + + // Safe Void Elements - HTML5 + // http://dev.w3.org/html5/spec/Overview.html#void-elements + var voidElements = toMap('area,br,col,hr,img,wbr'); + + // Elements that you can, intentionally, leave open (and which close themselves) + // http://dev.w3.org/html5/spec/Overview.html#optional-tags + var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'), + optionalEndTagInlineElements = toMap('rp,rt'), + optionalEndTagElements = extend({}, + optionalEndTagInlineElements, + optionalEndTagBlockElements); + + // Safe Block Elements - HTML5 + var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' + + 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + + 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul')); + + // Inline Elements - HTML5 + var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' + + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' + + 'samp,small,span,strike,strong,sub,sup,time,tt,u,var')); + + // SVG Elements + // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements + // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted. + // They can potentially allow for arbitrary javascript to be executed. See #11290 + var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' + + 'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' + + 'radialGradient,rect,stop,svg,switch,text,title,tspan'); + + // Blocked Elements (will be stripped) + var blockedElements = toMap('script,style'); + + var validElements = extend({}, + voidElements, + blockElements, + inlineElements, + optionalEndTagElements); + + //Attributes that have href and hence need to be sanitized + var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href,xml:base'); + + var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + + 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + + 'valign,value,vspace,width'); + + // SVG attributes (without "id" and "name" attributes) + // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes + var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + + 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' + + 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' + + 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' + + 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' + + 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' + + 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' + + 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' + + 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' + + 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' + + 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' + + 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' + + 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' + + 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' + + 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true); + + var validAttrs = extend({}, + uriAttrs, + svgAttrs, + htmlAttrs); + + function toMap(str, lowercaseKeys) { + var obj = {}, items = str.split(','), i; + for (i = 0; i < items.length; i++) { + obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true; + } + return obj; + } - // start tag - } else if ( BEGIN_TAG_REGEXP.test(html) ) { - match = html.match( START_TAG_REGEXP ); + /** + * Create an inert document that contains the dirty HTML that needs sanitizing + * Depending upon browser support we use one of three strategies for doing this. + * Support: Safari 10.x -> XHR strategy + * Support: Firefox -> DomParser strategy + */ + var getInertBodyElement /* function(html: string): HTMLBodyElement */ = (function(window, document) { + var inertDocument; + if (document && document.implementation) { + inertDocument = document.implementation.createHTMLDocument('inert'); + } else { + throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document'); + } + var inertBodyElement = (inertDocument.documentElement || inertDocument.getDocumentElement()).querySelector('body'); - if ( match ) { - html = html.substring( match[0].length ); - match[0].replace( START_TAG_REGEXP, parseStartTag ); - chars = false; - } + // Check for the Safari 10.1 bug - which allows JS to run inside the SVG G element + inertBodyElement.innerHTML = ''; + if (!inertBodyElement.querySelector('svg')) { + return getInertBodyElement_XHR; + } else { + // Check for the Firefox bug - which prevents the inner img JS from being sanitized + inertBodyElement.innerHTML = '

'; + if (inertBodyElement.querySelector('svg img')) { + return getInertBodyElement_DOMParser; + } else { + return getInertBodyElement_InertDocument; } + } - if ( chars ) { - index = html.indexOf("<"); - - var text = index < 0 ? html : html.substring( 0, index ); - html = index < 0 ? "" : html.substring( index ); - - if (handler.chars) handler.chars( decodeEntities(text) ); + function getInertBodyElement_XHR(html) { + // We add this dummy element to ensure that the rest of the content is parsed as expected + // e.g. leading whitespace is maintained and tags like `` do not get hoisted to the `` tag. + html = '' + html; + try { + html = encodeURI(html); + } catch (e) { + return undefined; } + var xhr = new window.XMLHttpRequest(); + xhr.responseType = 'document'; + xhr.open('GET', 'data:text/html;charset=utf-8,' + html, false); + xhr.send(null); + var body = xhr.response.body; + body.firstChild.remove(); + return body; + } - } else { - html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), - function(all, text){ - text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); + function getInertBodyElement_DOMParser(html) { + // We add this dummy element to ensure that the rest of the content is parsed as expected + // e.g. leading whitespace is maintained and tags like `` do not get hoisted to the `` tag. + html = '' + html; + try { + var body = new window.DOMParser().parseFromString(html, 'text/html').body; + body.firstChild.remove(); + return body; + } catch (e) { + return undefined; + } + } - if (handler.chars) handler.chars( decodeEntities(text) ); + function getInertBodyElement_InertDocument(html) { + inertBodyElement.innerHTML = html; - return ""; - }); + // Support: IE 9-11 only + // strip custom-namespaced attributes on IE<=11 + if (document.documentMode) { + stripCustomNsAttrs(inertBodyElement); + } - parseEndTag( "", stack.last() ); + return inertBodyElement; } - - if ( html == last ) { - throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + - "of html: {0}", html); + })(window, window.document); + + /** + * @example + * htmlParser(htmlString, { + * start: function(tag, attrs) {}, + * end: function(tag) {}, + * chars: function(text) {}, + * comment: function(text) {} + * }); + * + * @param {string} html string + * @param {object} handler + */ + function htmlParserImpl(html, handler) { + if (html === null || html === undefined) { + html = ''; + } else if (typeof html !== 'string') { + html = '' + html; } - last = html; - } - // Clean up any remaining tags - parseEndTag(); + var inertBodyElement = getInertBodyElement(html); + if (!inertBodyElement) return ''; - function parseStartTag( tag, tagName, rest, unary ) { - tagName = angular.lowercase(tagName); - if ( blockElements[ tagName ] ) { - while ( stack.last() && inlineElements[ stack.last() ] ) { - parseEndTag( "", stack.last() ); + //mXSS protection + var mXSSAttempts = 5; + do { + if (mXSSAttempts === 0) { + throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable'); + } + mXSSAttempts--; + + // trigger mXSS if it is going to happen by reading and writing the innerHTML + html = inertBodyElement.innerHTML; + inertBodyElement = getInertBodyElement(html); + } while (html !== inertBodyElement.innerHTML); + + var node = inertBodyElement.firstChild; + while (node) { + switch (node.nodeType) { + case 1: // ELEMENT_NODE + handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes)); + break; + case 3: // TEXT NODE + handler.chars(node.textContent); + break; } - } - if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { - parseEndTag( "", tagName ); + var nextNode; + if (!(nextNode = node.firstChild)) { + if (node.nodeType === 1) { + handler.end(node.nodeName.toLowerCase()); + } + nextNode = getNonDescendant('nextSibling', node); + if (!nextNode) { + while (nextNode == null) { + node = getNonDescendant('parentNode', node); + if (node === inertBodyElement) break; + nextNode = getNonDescendant('nextSibling', node); + if (node.nodeType === 1) { + handler.end(node.nodeName.toLowerCase()); + } + } + } + } + node = nextNode; } - unary = voidElements[ tagName ] || !!unary; + while ((node = inertBodyElement.firstChild)) { + inertBodyElement.removeChild(node); + } + } - if ( !unary ) - stack.push( tagName ); + function attrToMap(attrs) { + var map = {}; + for (var i = 0, ii = attrs.length; i < ii; i++) { + var attr = attrs[i]; + map[attr.name] = attr.value; + } + return map; + } - var attrs = {}; - rest.replace(ATTR_REGEXP, - function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { - var value = doubleQuotedValue - || singleQuotedValue - || unquotedValue - || ''; + /** + * Escapes all potentially dangerous characters, so that the + * resulting string can be safely inserted into attribute or + * element text. + * @param value + * @returns {string} escaped text + */ + function encodeEntities(value) { + return value. + replace(/&/g, '&'). + replace(SURROGATE_PAIR_REGEXP, function(value) { + var hi = value.charCodeAt(0); + var low = value.charCodeAt(1); + return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; + }). + replace(NON_ALPHANUMERIC_REGEXP, function(value) { + return '&#' + value.charCodeAt(0) + ';'; + }). + replace(//g, '>'); + } - attrs[name] = decodeEntities(value); - }); - if (handler.start) handler.start( tagName, attrs, unary ); + /** + * create an HTML/XML writer which writes to buffer + * @param {Array} buf use buf.join('') to get out sanitized html string + * @returns {object} in the form of { + * start: function(tag, attrs) {}, + * end: function(tag) {}, + * chars: function(text) {}, + * comment: function(text) {} + * } + */ + function htmlSanitizeWriterImpl(buf, uriValidator) { + var ignoreCurrentElement = false; + var out = bind(buf, buf.push); + return { + start: function(tag, attrs) { + tag = lowercase(tag); + if (!ignoreCurrentElement && blockedElements[tag]) { + ignoreCurrentElement = tag; + } + if (!ignoreCurrentElement && validElements[tag] === true) { + out('<'); + out(tag); + forEach(attrs, function(value, key) { + var lkey = lowercase(key); + var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); + if (validAttrs[lkey] === true && + (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { + out(' '); + out(key); + out('="'); + out(encodeEntities(value)); + out('"'); + } + }); + out('>'); + } + }, + end: function(tag) { + tag = lowercase(tag); + if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) { + out(''); + } + // eslint-disable-next-line eqeqeq + if (tag == ignoreCurrentElement) { + ignoreCurrentElement = false; + } + }, + chars: function(chars) { + if (!ignoreCurrentElement) { + out(encodeEntities(chars)); + } + } + }; } - function parseEndTag( tag, tagName ) { - var pos = 0, i; - tagName = angular.lowercase(tagName); - if ( tagName ) - // Find the closest opened tag of the same type - for ( pos = stack.length - 1; pos >= 0; pos-- ) - if ( stack[ pos ] == tagName ) - break; - if ( pos >= 0 ) { - // Close all the open elements, up the stack - for ( i = stack.length - 1; i >= pos; i-- ) - if (handler.end) handler.end( stack[ i ] ); + /** + * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare + * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want + * to allow any of these custom attributes. This method strips them all. + * + * @param node Root element to process + */ + function stripCustomNsAttrs(node) { + while (node) { + if (node.nodeType === window.Node.ELEMENT_NODE) { + var attrs = node.attributes; + for (var i = 0, l = attrs.length; i < l; i++) { + var attrNode = attrs[i]; + var attrName = attrNode.name.toLowerCase(); + if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) { + node.removeAttributeNode(attrNode); + i--; + l--; + } + } + } - // Remove the open elements from the stack - stack.length = pos; + var nextNode = node.firstChild; + if (nextNode) { + stripCustomNsAttrs(nextNode); + } + + node = getNonDescendant('nextSibling', node); } } - } - var hiddenPre=document.createElement("pre"); - var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; - /** - * decodes all entities into regular string - * @param value - * @returns {string} A string with decoded entities. - */ - function decodeEntities(value) { - if (!value) { return ''; } - - // Note: IE8 does not preserve spaces at the start/end of innerHTML - // so we must capture them and reattach them afterward - var parts = spaceRe.exec(value); - var spaceBefore = parts[1]; - var spaceAfter = parts[3]; - var content = parts[2]; - if (content) { - hiddenPre.innerHTML=content.replace(//g, '>'); } - /** - * create an HTML/XML writer which writes to buffer - * @param {Array} buf use buf.jain('') to get out sanitized html string - * @returns {object} in the form of { - * start: function(tag, attrs, unary) {}, - * end: function(tag) {}, - * chars: function(text) {}, - * comment: function(text) {} - * } - */ - function htmlSanitizeWriter(buf, uriValidator){ - var ignore = false; - var out = angular.bind(buf, buf.push); - return { - start: function(tag, attrs, unary){ - tag = angular.lowercase(tag); - if (!ignore && specialElements[tag]) { - ignore = tag; - } - if (!ignore && validElements[tag] === true) { - out('<'); - out(tag); - angular.forEach(attrs, function(value, key){ - var lkey=angular.lowercase(key); - var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); - if (validAttrs[lkey] === true && - (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { - out(' '); - out(key); - out('="'); - out(encodeEntities(value)); - out('"'); - } - }); - out(unary ? '/>' : '>'); - } - }, - end: function(tag){ - tag = angular.lowercase(tag); - if (!ignore && validElements[tag] === true) { - out(''); - } - if (tag == ignore) { - ignore = false; - } - }, - chars: function(chars){ - if (!ignore) { - out(encodeEntities(chars)); - } - } - }; + function sanitizeText(chars) { + var buf = []; + var writer = htmlSanitizeWriter(buf, noop); + writer.chars(chars); + return buf.join(''); } // define ngSanitize module and register $sanitize service - angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); - - /* global sanitizeText: false */ + angular.module('ngSanitize', []) + .provider('$sanitize', $SanitizeProvider) + .info({ angularVersion: '1.6.9' }); /** * @ngdoc filter * @name linky - * @function + * @kind function * * @description - * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and + * Finds links in text input and turns them into html links. Supports `http/https/ftp/sftp/mailto` and * plain email address links. * * Requires the {@link ngSanitize `ngSanitize`} module to be installed. * * @param {string} text Input text. - * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. - * @returns {string} Html-linkified text. + * @param {string} [target] Window (`_blank|_self|_parent|_top`) or named frame to open links in. + * @param {object|function(url)} [attributes] Add custom attributes to the link element. + * + * Can be one of: + * + * - `object`: A map of attributes + * - `function`: Takes the url as a parameter and returns a map of attributes + * + * If the map of attributes contains a value for `target`, it overrides the value of + * the target parameter. + * + * + * @returns {string} Html-linkified and {@link $sanitize sanitized} text. * * @usage * * @example - + - -

+
Snippet:
- - - + + + @@ -522,10 +653,19 @@ + + + + + @@ -535,6 +675,18 @@
FilterSourceRenderedFilterSourceRendered
linky filter
linky target -
<div ng-bind-html="snippetWithTarget | linky:'_blank'">
</div>
+
<div ng-bind-html="snippetWithSingleURL | linky:'_blank'">
</div>
-
+
+
linky custom attributes +
<div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}">
</div>
+
+
+ + angular.module('linkyExample', ['ngSanitize']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.snippet = + 'Pretty text with some links:\n' + + 'http://angularjs.org/,\n' + + 'mailto:us@somewhere.org,\n' + + 'another@somewhere.org,\n' + + 'and one more: ftp://127.0.0.1/.'; + $scope.snippetWithSingleURL = 'http://angularjs.org/'; + }]); + it('should linkify the snippet with urls', function() { expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). @@ -542,12 +694,14 @@ 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); + it('should not linkify snippet without the linky filter', function() { expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); + it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new http://link.'); @@ -557,22 +711,43 @@ expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) .toBe('new http://link.'); }); + it('should work with the target property', function() { expect(element(by.id('linky-target')). - element(by.binding("snippetWithTarget | linky:'_blank'")).getText()). + element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); + + it('should optionally add custom attributes', function() { + expect(element(by.id('linky-custom-attributes')). + element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()). + toBe('http://angularjs.org/'); + expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow'); + }); */ angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { var LINKY_URL_REGEXP = - /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/, - MAILTO_REGEXP = /^mailto:/; + /((s?ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, + MAILTO_REGEXP = /^mailto:/i; + + var linkyMinErr = angular.$$minErr('linky'); + var isDefined = angular.isDefined; + var isFunction = angular.isFunction; + var isObject = angular.isObject; + var isString = angular.isString; + + return function(text, target, attributes) { + if (text == null || text === '') return text; + if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text); + + var attributesFn = + isFunction(attributes) ? attributes : + isObject(attributes) ? function getAttributesObject() {return attributes;} : + function getEmptyAttributesObject() {return {};}; - return function(text, target) { - if (!text) return text; var match; var raw = text; var html = []; @@ -581,8 +756,10 @@ while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; - // if we did not match ftp/http/mailto then assume mailto - if (match[2] == match[3]) url = 'mailto:' + url; + // if we did not match ftp/http/www/mailto then assume mailto + if (!match[2] && !match[4]) { + url = (match[3] ? 'http://' : 'mailto:') + url; + } i = match.index; addText(raw.substr(0, i)); addLink(url, match[0].replace(MAILTO_REGEXP, '')); @@ -599,15 +776,21 @@ } function addLink(url, text) { + var key, linkAttributes = attributesFn(url); html.push(''); + html.push('href="', + url.replace(/"/g, '"'), + '">'); addText(text); html.push(''); } diff --git a/setup/pub/angular-sanitize/angular-sanitize.min.js b/setup/pub/angular-sanitize/angular-sanitize.min.js index 4fc586065be2f..991dd00987a8c 100644 --- a/setup/pub/angular-sanitize/angular-sanitize.min.js +++ b/setup/pub/angular-sanitize/angular-sanitize.min.js @@ -1,14 +1,17 @@ /* - AngularJS v1.2.14 - (c) 2010-2014 Google, Inc. http://angularjs.org + AngularJS v1.6.9 + (c) 2010-2018 Google, Inc. http://angularjs.org License: MIT - */ -(function(p,h,q){'use strict';function E(a){var e=[];s(e,h.noop).chars(a);return e.join("")}function k(a){var e={};a=a.split(",");var d;for(d=0;d=c;d--)e.end&&e.end(f[d]);f.length=c}}var b,g,f=[],l=a;for(f.last=function(){return f[f.length-1]};a;){g=!0;if(f.last()&&x[f.last()])a=a.replace(RegExp("(.*)<\\s*\\/\\s*"+f.last()+"[^>]*>","i"),function(b,a){a=a.replace(H,"$1").replace(I,"$1");e.chars&&e.chars(r(a));return""}),c("",f.last());else{if(0===a.indexOf("\x3c!--"))b=a.indexOf("--",4),0<=b&&a.lastIndexOf("--\x3e",b)===b&&(e.comment&&e.comment(a.substring(4,b)),a=a.substring(b+3),g=!1);else if(y.test(a)){if(b=a.match(y))a= - a.replace(b[0],""),g=!1}else if(J.test(a)){if(b=a.match(z))a=a.substring(b[0].length),b[0].replace(z,c),g=!1}else K.test(a)&&(b=a.match(A))&&(a=a.substring(b[0].length),b[0].replace(A,d),g=!1);g&&(b=a.indexOf("<"),g=0>b?a:a.substring(0,b),a=0>b?"":a.substring(b),e.chars&&e.chars(r(g)))}if(a==l)throw L("badparse",a);l=a}c()}function r(a){if(!a)return"";var e=M.exec(a);a=e[1];var d=e[3];if(e=e[2])n.innerHTML=e.replace(//g,">")}function s(a,e){var d=!1,c=h.bind(a,a.push);return{start:function(a,g,f){a=h.lowercase(a);!d&&x[a]&&(d=a);d||!0!==C[a]||(c("<"),c(a),h.forEach(g,function(d,f){var g=h.lowercase(f),k="img"===a&&"src"===g||"background"===g;!0!==O[g]||!0===D[g]&&!e(d,k)||(c(" "),c(f),c('="'),c(B(d)),c('"'))}),c(f?"/>":">"))},end:function(a){a=h.lowercase(a);d||!0!==C[a]||(c(""));a==d&&(d=!1)},chars:function(a){d|| -c(B(a))}}}var L=h.$$minErr("$sanitize"),A=/^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,z=/^<\s*\/\s*([\w:-]+)[^>]*>/,G=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,K=/^]*?)>/i,I=/]/,d=/^mailto:/;return function(c,b){function g(a){a&&m.push(E(a))}function f(a,c){m.push("');g(c);m.push("")}if(!c)return c;for(var l,k=c,m=[],n,p;l=k.match(e);)n=l[0],l[2]==l[3]&&(n="mailto:"+n),p=l.index,g(k.substr(0,p)),f(n,l[0].replace(d,"")),k=k.substring(p+l[0].length);g(k);return a(m.join(""))}}])})(window,window.angular); +*/ +(function(s,d){'use strict';function J(d){var k=[];w(k,B).chars(d);return k.join("")}var x=d.$$minErr("$sanitize"),C,k,D,E,p,B,F,G,w;d.module("ngSanitize",[]).provider("$sanitize",function(){function g(a,e){var c={},b=a.split(","),f;for(f=0;f/g,">")}function I(a){for(;a;){if(a.nodeType===s.Node.ELEMENT_NODE)for(var e=a.attributes,c=0,b=e.length;c"))},end:function(a){a=p(a);c||!0!==n[a]||!0===h[a]||(b(""));a==c&&(c=!1)},chars:function(a){c||b(H(a))}}};F=s.Node.prototype.contains||function(a){return!!(this.compareDocumentPosition(a)&16)};var L=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,M=/([^#-~ |!])/g,h=g("area,br,col,hr,img,wbr"),q=g("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),l=g("rp,rt"),r=k({},l,q),q=k({},q,g("address,article,aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul")), + l=k({},l,g("a,abbr,acronym,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var")),z=g("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,stop,svg,switch,text,title,tspan"),A=g("script,style"),n=k({},h,q,l,r),m=g("background,cite,href,longdesc,src,xlink:href,xml:base"),r=g("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,valign,value,vspace,width"), + l=g("accent-height,accumulate,additive,alphabetic,arabic-form,ascent,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan", + !0),v=k({},m,l,r),u=function(a,e){function c(b){b=""+b;try{var c=(new a.DOMParser).parseFromString(b,"text/html").body;c.firstChild.remove();return c}catch(e){}}function b(a){d.innerHTML=a;e.documentMode&&I(d);return d}var h;if(e&&e.implementation)h=e.implementation.createHTMLDocument("inert");else throw x("noinert");var d=(h.documentElement||h.getDocumentElement()).querySelector("body");d.innerHTML='';return d.querySelector("svg")? + (d.innerHTML='

',d.querySelector("svg img")?c:b):function(b){b=""+b;try{b=encodeURI(b)}catch(c){return}var e=new a.XMLHttpRequest;e.responseType="document";e.open("GET","data:text/html;charset=utf-8,"+b,!1);e.send(null);b=e.response.body;b.firstChild.remove();return b}}(s,s.document)}).info({angularVersion:"1.6.9"});d.module("ngSanitize").filter("linky",["$sanitize",function(g){var k=/((s?ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, + p=/^mailto:/i,s=d.$$minErr("linky"),t=d.isDefined,y=d.isFunction,w=d.isObject,x=d.isString;return function(d,q,l){function r(a){a&&m.push(J(a))}function z(a,d){var c,b=A(a);m.push("');r(d);m.push("")}if(null==d||""===d)return d;if(!x(d))throw s("notstring",d);for(var A=y(l)?l:w(l)?function(){return l}:function(){return{}},n=d,m=[],v,u;d=n.match(k);)v=d[0],d[2]|| +d[4]||(v=(d[3]?"http://":"mailto:")+v),u=d.index,r(n.substr(0,u)),z(v,d[0].replace(p,"")),n=n.substring(u+d[0].length);r(n);return g(m.join(""))}}])})(window,window.angular); //# sourceMappingURL=angular-sanitize.min.js.map \ No newline at end of file diff --git a/setup/pub/angular-sanitize/angular-sanitize.min.js.map b/setup/pub/angular-sanitize/angular-sanitize.min.js.map index 0310ddce9c937..8ce8290b2b387 100644 --- a/setup/pub/angular-sanitize/angular-sanitize.min.js.map +++ b/setup/pub/angular-sanitize/angular-sanitize.min.js.map @@ -1,8 +1,8 @@ { -"version":3, -"file":"angular-sanitize.min.js", -"lineCount":13, -"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkBC,CAAlB,CAA6B,CAiJtCC,QAASA,EAAY,CAACC,CAAD,CAAQ,CAC3B,IAAIC,EAAM,EACGC,EAAAC,CAAmBF,CAAnBE,CAAwBN,CAAAO,KAAxBD,CACbH,MAAA,CAAaA,CAAb,CACA,OAAOC,EAAAI,KAAA,CAAS,EAAT,CAJoB,CAmE7BC,QAASA,EAAO,CAACC,CAAD,CAAM,CAAA,IAChBC,EAAM,EAAIC,EAAAA,CAAQF,CAAAG,MAAA,CAAU,GAAV,CAAtB,KAAsCC,CACtC,KAAKA,CAAL,CAAS,CAAT,CAAYA,CAAZ,CAAgBF,CAAAG,OAAhB,CAA8BD,CAAA,EAA9B,CAAmCH,CAAA,CAAIC,CAAA,CAAME,CAAN,CAAJ,CAAA,CAAgB,CAAA,CACnD,OAAOH,EAHa,CAmBtBK,QAASA,EAAU,CAAEC,CAAF,CAAQC,CAAR,CAAkB,CAiFnCC,QAASA,EAAa,CAAEC,CAAF,CAAOC,CAAP,CAAgBC,CAAhB,CAAsBC,CAAtB,CAA8B,CAClDF,CAAA,CAAUrB,CAAAwB,UAAA,CAAkBH,CAAlB,CACV,IAAKI,CAAA,CAAeJ,CAAf,CAAL,CACE,IAAA,CAAQK,CAAAC,KAAA,EAAR,EAAwBC,CAAA,CAAgBF,CAAAC,KAAA,EAAhB,CAAxB,CAAA,CACEE,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CAICG,EAAA,CAAwBT,CAAxB,CAAL,EAA0CK,CAAAC,KAAA,EAA1C,EAA0DN,CAA1D,EACEQ,CAAA,CAAa,EAAb,CAAiBR,CAAjB,CAKF,EAFAE,CAEA,CAFQQ,CAAA,CAAcV,CAAd,CAER,EAFmC,CAAC,CAACE,CAErC,GACEG,CAAAM,KAAA,CAAYX,CAAZ,CAEF,KAAIY,EAAQ,EAEZX,EAAAY,QAAA,CAAaC,CAAb,CACE,QAAQ,CAACC,CAAD,CAAQC,CAAR,CAAcC,CAAd,CAAiCC,CAAjC,CAAoDC,CAApD,CAAmE,CAMzEP,CAAA,CAAMI,CAAN,CAAA,CAAcI,CAAA,CALFH,CAKE,EAJTC,CAIS,EAHTC,CAGS,EAFT,EAES,CAN2D,CAD7E,CASItB,EAAAwB,MAAJ,EAAmBxB,CAAAwB,MAAA,CAAerB,CAAf,CAAwBY,CAAxB,CAA+BV,CAA/B,CA5B+B,CA+BpDM,QAASA,EAAW,CAAET,CAAF,CAAOC,CAAP,CAAiB,CAAA,IAC/BsB,EAAM,CADyB,CACtB7B,CAEb,IADAO,CACA,CADUrB,CAAAwB,UAAA,CAAkBH,CAAlB,CACV,CAEE,IAAMsB,CAAN,CAAYjB,CAAAX,OAAZ,CAA2B,CAA3B,CAAqC,CAArC,EAA8B4B,CAA9B,EACOjB,CAAA,CAAOiB,CAAP,CADP,EACuBtB,CADvB,CAAwCsB,CAAA,EAAxC;AAIF,GAAY,CAAZ,EAAKA,CAAL,CAAgB,CAEd,IAAM7B,CAAN,CAAUY,CAAAX,OAAV,CAAyB,CAAzB,CAA4BD,CAA5B,EAAiC6B,CAAjC,CAAsC7B,CAAA,EAAtC,CACMI,CAAA0B,IAAJ,EAAiB1B,CAAA0B,IAAA,CAAalB,CAAA,CAAOZ,CAAP,CAAb,CAGnBY,EAAAX,OAAA,CAAe4B,CAND,CATmB,CAhHF,IAC/BE,CAD+B,CACxB1C,CADwB,CACVuB,EAAQ,EADE,CACEC,EAAOV,CAG5C,KAFAS,CAAAC,KAEA,CAFamB,QAAQ,EAAG,CAAE,MAAOpB,EAAA,CAAOA,CAAAX,OAAP,CAAsB,CAAtB,CAAT,CAExB,CAAQE,CAAR,CAAA,CAAe,CACbd,CAAA,CAAQ,CAAA,CAGR,IAAMuB,CAAAC,KAAA,EAAN,EAAuBoB,CAAA,CAAiBrB,CAAAC,KAAA,EAAjB,CAAvB,CAmDEV,CASA,CATOA,CAAAiB,QAAA,CAAiBc,MAAJ,CAAW,kBAAX,CAAgCtB,CAAAC,KAAA,EAAhC,CAA+C,QAA/C,CAAyD,GAAzD,CAAb,CACL,QAAQ,CAACsB,CAAD,CAAMC,CAAN,CAAW,CACjBA,CAAA,CAAOA,CAAAhB,QAAA,CAAaiB,CAAb,CAA6B,IAA7B,CAAAjB,QAAA,CAA2CkB,CAA3C,CAAyD,IAAzD,CAEHlC,EAAAf,MAAJ,EAAmBe,CAAAf,MAAA,CAAesC,CAAA,CAAeS,CAAf,CAAf,CAEnB,OAAO,EALU,CADd,CASP,CAAArB,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CA5DF,KAAyD,CAGvD,GAA8B,CAA9B,GAAKV,CAAAoC,QAAA,CAAa,SAAb,CAAL,CAEER,CAEA,CAFQ5B,CAAAoC,QAAA,CAAa,IAAb,CAAmB,CAAnB,CAER,CAAc,CAAd,EAAKR,CAAL,EAAmB5B,CAAAqC,YAAA,CAAiB,QAAjB,CAAwBT,CAAxB,CAAnB,GAAsDA,CAAtD,GACM3B,CAAAqC,QAEJ,EAFqBrC,CAAAqC,QAAA,CAAiBtC,CAAAuC,UAAA,CAAgB,CAAhB,CAAmBX,CAAnB,CAAjB,CAErB,CADA5B,CACA,CADOA,CAAAuC,UAAA,CAAgBX,CAAhB,CAAwB,CAAxB,CACP,CAAA1C,CAAA,CAAQ,CAAA,CAHV,CAJF,KAUO,IAAKsD,CAAAC,KAAA,CAAoBzC,CAApB,CAAL,CAGL,IAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAYqB,CAAZ,CAER,CACExC,CACA;AADOA,CAAAiB,QAAA,CAAcE,CAAA,CAAM,CAAN,CAAd,CAAyB,EAAzB,CACP,CAAAjC,CAAA,CAAQ,CAAA,CAFV,CAHK,IAQA,IAAKwD,CAAAD,KAAA,CAA4BzC,CAA5B,CAAL,CAGL,IAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAYwB,CAAZ,CAER,CACE3C,CAEA,CAFOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CAEP,CADAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkB0B,CAAlB,CAAkC/B,CAAlC,CACA,CAAA1B,CAAA,CAAQ,CAAA,CAHV,CAHK,IAUK0D,EAAAH,KAAA,CAAsBzC,CAAtB,CAAL,GACLmB,CADK,CACGnB,CAAAmB,MAAA,CAAY0B,CAAZ,CADH,IAIH7C,CAEA,CAFOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CAEP,CADAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkB4B,CAAlB,CAAoC3C,CAApC,CACA,CAAAhB,CAAA,CAAQ,CAAA,CANL,CAUFA,EAAL,GACE0C,CAKA,CALQ5B,CAAAoC,QAAA,CAAa,GAAb,CAKR,CAHIH,CAGJ,CAHmB,CAAR,CAAAL,CAAA,CAAY5B,CAAZ,CAAmBA,CAAAuC,UAAA,CAAgB,CAAhB,CAAmBX,CAAnB,CAG9B,CAFA5B,CAEA,CAFe,CAAR,CAAA4B,CAAA,CAAY,EAAZ,CAAiB5B,CAAAuC,UAAA,CAAgBX,CAAhB,CAExB,CAAI3B,CAAAf,MAAJ,EAAmBe,CAAAf,MAAA,CAAesC,CAAA,CAAeS,CAAf,CAAf,CANrB,CAzCuD,CA+DzD,GAAKjC,CAAL,EAAaU,CAAb,CACE,KAAMoC,EAAA,CAAgB,UAAhB,CAC4C9C,CAD5C,CAAN,CAGFU,CAAA,CAAOV,CAvEM,CA2EfY,CAAA,EA/EmC,CA2IrCY,QAASA,EAAc,CAACuB,CAAD,CAAQ,CAC7B,GAAI,CAACA,CAAL,CAAc,MAAO,EAIrB,KAAIC,EAAQC,CAAAC,KAAA,CAAaH,CAAb,CACRI,EAAAA,CAAcH,CAAA,CAAM,CAAN,CAClB,KAAII,EAAaJ,CAAA,CAAM,CAAN,CAEjB,IADIK,CACJ,CADcL,CAAA,CAAM,CAAN,CACd,CACEM,CAAAC,UAKA,CALoBF,CAAApC,QAAA,CAAgB,IAAhB,CAAqB,MAArB,CAKpB,CAAAoC,CAAA,CAAU,aAAA,EAAiBC,EAAjB,CACRA,CAAAE,YADQ,CACgBF,CAAAG,UAE5B,OAAON,EAAP,CAAqBE,CAArB,CAA+BD,CAlBF,CA4B/BM,QAASA,EAAc,CAACX,CAAD,CAAQ,CAC7B,MAAOA,EAAA9B,QAAA,CACG,IADH;AACS,OADT,CAAAA,QAAA,CAEG0C,CAFH,CAE4B,QAAQ,CAACZ,CAAD,CAAO,CAC9C,MAAO,IAAP,CAAcA,CAAAa,WAAA,CAAiB,CAAjB,CAAd,CAAoC,GADU,CAF3C,CAAA3C,QAAA,CAKG,IALH,CAKS,MALT,CAAAA,QAAA,CAMG,IANH,CAMS,MANT,CADsB,CAoB/B7B,QAASA,EAAkB,CAACD,CAAD,CAAM0E,CAAN,CAAmB,CAC5C,IAAIC,EAAS,CAAA,CAAb,CACIC,EAAMhF,CAAAiF,KAAA,CAAa7E,CAAb,CAAkBA,CAAA4B,KAAlB,CACV,OAAO,OACEU,QAAQ,CAACtB,CAAD,CAAMa,CAAN,CAAaV,CAAb,CAAmB,CAChCH,CAAA,CAAMpB,CAAAwB,UAAA,CAAkBJ,CAAlB,CACD2D,EAAAA,CAAL,EAAehC,CAAA,CAAgB3B,CAAhB,CAAf,GACE2D,CADF,CACW3D,CADX,CAGK2D,EAAL,EAAsC,CAAA,CAAtC,GAAeG,CAAA,CAAc9D,CAAd,CAAf,GACE4D,CAAA,CAAI,GAAJ,CAcA,CAbAA,CAAA,CAAI5D,CAAJ,CAaA,CAZApB,CAAAmF,QAAA,CAAgBlD,CAAhB,CAAuB,QAAQ,CAAC+B,CAAD,CAAQoB,CAAR,CAAY,CACzC,IAAIC,EAAKrF,CAAAwB,UAAA,CAAkB4D,CAAlB,CAAT,CACIE,EAAmB,KAAnBA,GAAWlE,CAAXkE,EAAqC,KAArCA,GAA4BD,CAA5BC,EAAyD,YAAzDA,GAAgDD,CAC3B,EAAA,CAAzB,GAAIE,CAAA,CAAWF,CAAX,CAAJ,EACsB,CAAA,CADtB,GACGG,CAAA,CAASH,CAAT,CADH,EAC8B,CAAAP,CAAA,CAAad,CAAb,CAAoBsB,CAApB,CAD9B,GAEEN,CAAA,CAAI,GAAJ,CAIA,CAHAA,CAAA,CAAII,CAAJ,CAGA,CAFAJ,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAIL,CAAA,CAAeX,CAAf,CAAJ,CACA,CAAAgB,CAAA,CAAI,GAAJ,CANF,CAHyC,CAA3C,CAYA,CAAAA,CAAA,CAAIzD,CAAA,CAAQ,IAAR,CAAe,GAAnB,CAfF,CALgC,CAD7B,KAwBAqB,QAAQ,CAACxB,CAAD,CAAK,CACdA,CAAA,CAAMpB,CAAAwB,UAAA,CAAkBJ,CAAlB,CACD2D,EAAL,EAAsC,CAAA,CAAtC,GAAeG,CAAA,CAAc9D,CAAd,CAAf,GACE4D,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAI5D,CAAJ,CACA,CAAA4D,CAAA,CAAI,GAAJ,CAHF,CAKI5D,EAAJ,EAAW2D,CAAX,GACEA,CADF,CACW,CAAA,CADX,CAPc,CAxBb,OAmCE5E,QAAQ,CAACA,CAAD,CAAO,CACb4E,CAAL;AACEC,CAAA,CAAIL,CAAA,CAAexE,CAAf,CAAJ,CAFgB,CAnCjB,CAHqC,CAha9C,IAAI4D,EAAkB/D,CAAAyF,SAAA,CAAiB,WAAjB,CAAtB,CAwJI3B,EACG,4FAzJP,CA0JEF,EAAiB,2BA1JnB,CA2JEzB,EAAc,yEA3JhB,CA4JE0B,EAAmB,IA5JrB,CA6JEF,EAAyB,SA7J3B,CA8JER,EAAiB,qBA9JnB,CA+JEM,EAAiB,qBA/JnB,CAgKEL,EAAe,yBAhKjB,CAkKEwB,EAA0B,gBAlK5B,CA2KI7C,EAAetB,CAAA,CAAQ,wBAAR,CAIfiF,EAAAA,CAA8BjF,CAAA,CAAQ,gDAAR,CAC9BkF,EAAAA,CAA+BlF,CAAA,CAAQ,OAAR,CADnC,KAEIqB,EAAyB9B,CAAA4F,OAAA,CAAe,EAAf,CACeD,CADf,CAEeD,CAFf,CAF7B,CAOIjE,EAAgBzB,CAAA4F,OAAA,CAAe,EAAf,CAAmBF,CAAnB,CAAgDjF,CAAA,CAAQ,4KAAR,CAAhD,CAPpB;AAYImB,EAAiB5B,CAAA4F,OAAA,CAAe,EAAf,CAAmBD,CAAnB,CAAiDlF,CAAA,CAAQ,2JAAR,CAAjD,CAZrB,CAkBIsC,EAAkBtC,CAAA,CAAQ,cAAR,CAlBtB,CAoBIyE,EAAgBlF,CAAA4F,OAAA,CAAe,EAAf,CACe7D,CADf,CAEeN,CAFf,CAGeG,CAHf,CAIeE,CAJf,CApBpB,CA2BI0D,EAAW/E,CAAA,CAAQ,0CAAR,CA3Bf,CA4BI8E,EAAavF,CAAA4F,OAAA,CAAe,EAAf,CAAmBJ,CAAnB,CAA6B/E,CAAA,CAC1C,ySAD0C,CAA7B,CA5BjB;AA0LI8D,EAAUsB,QAAAC,cAAA,CAAuB,KAAvB,CA1Ld,CA2LI5B,EAAU,wBAsGdlE,EAAA+F,OAAA,CAAe,YAAf,CAA6B,EAA7B,CAAAC,SAAA,CAA0C,WAA1C,CA7UAC,QAA0B,EAAG,CAC3B,IAAAC,KAAA,CAAY,CAAC,eAAD,CAAkB,QAAQ,CAACC,CAAD,CAAgB,CACpD,MAAO,SAAQ,CAAClF,CAAD,CAAO,CACpB,IAAIb,EAAM,EACVY,EAAA,CAAWC,CAAX,CAAiBZ,CAAA,CAAmBD,CAAnB,CAAwB,QAAQ,CAACgG,CAAD,CAAMd,CAAN,CAAe,CAC9D,MAAO,CAAC,SAAA5B,KAAA,CAAeyC,CAAA,CAAcC,CAAd,CAAmBd,CAAnB,CAAf,CADsD,CAA/C,CAAjB,CAGA,OAAOlF,EAAAI,KAAA,CAAS,EAAT,CALa,CAD8B,CAA1C,CADe,CA6U7B,CAuGAR,EAAA+F,OAAA,CAAe,YAAf,CAAAM,OAAA,CAAoC,OAApC,CAA6C,CAAC,WAAD,CAAc,QAAQ,CAACC,CAAD,CAAY,CAAA,IACzEC,EACE,mEAFuE,CAGzEC,EAAgB,UAEpB,OAAO,SAAQ,CAACtD,CAAD,CAAOuD,CAAP,CAAe,CAoB5BC,QAASA,EAAO,CAACxD,CAAD,CAAO,CAChBA,CAAL,EAGAjC,CAAAe,KAAA,CAAU9B,CAAA,CAAagD,CAAb,CAAV,CAJqB,CAOvByD,QAASA,EAAO,CAACC,CAAD,CAAM1D,CAAN,CAAY,CAC1BjC,CAAAe,KAAA,CAAU,KAAV,CACIhC,EAAA6G,UAAA,CAAkBJ,CAAlB,CAAJ;CACExF,CAAAe,KAAA,CAAU,UAAV,CAEA,CADAf,CAAAe,KAAA,CAAUyE,CAAV,CACA,CAAAxF,CAAAe,KAAA,CAAU,IAAV,CAHF,CAKAf,EAAAe,KAAA,CAAU,QAAV,CACAf,EAAAe,KAAA,CAAU4E,CAAV,CACA3F,EAAAe,KAAA,CAAU,IAAV,CACA0E,EAAA,CAAQxD,CAAR,CACAjC,EAAAe,KAAA,CAAU,MAAV,CAX0B,CA1B5B,GAAI,CAACkB,CAAL,CAAW,MAAOA,EAMlB,KALA,IAAId,CAAJ,CACI0E,EAAM5D,CADV,CAEIjC,EAAO,EAFX,CAGI2F,CAHJ,CAII9F,CACJ,CAAQsB,CAAR,CAAgB0E,CAAA1E,MAAA,CAAUmE,CAAV,CAAhB,CAAA,CAEEK,CAMA,CANMxE,CAAA,CAAM,CAAN,CAMN,CAJIA,CAAA,CAAM,CAAN,CAIJ,EAJgBA,CAAA,CAAM,CAAN,CAIhB,GAJ0BwE,CAI1B,CAJgC,SAIhC,CAJ4CA,CAI5C,EAHA9F,CAGA,CAHIsB,CAAAS,MAGJ,CAFA6D,CAAA,CAAQI,CAAAC,OAAA,CAAW,CAAX,CAAcjG,CAAd,CAAR,CAEA,CADA6F,CAAA,CAAQC,CAAR,CAAaxE,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAiBsE,CAAjB,CAAgC,EAAhC,CAAb,CACA,CAAAM,CAAA,CAAMA,CAAAtD,UAAA,CAAc1C,CAAd,CAAkBsB,CAAA,CAAM,CAAN,CAAArB,OAAlB,CAER2F,EAAA,CAAQI,CAAR,CACA,OAAOR,EAAA,CAAUrF,CAAAT,KAAA,CAAU,EAAV,CAAV,CAlBqB,CAL+C,CAAlC,CAA7C,CAzjBsC,CAArC,CAAA,CA0mBET,MA1mBF,CA0mBUA,MAAAC,QA1mBV;", -"sources":["angular-sanitize.js"], -"names":["window","angular","undefined","sanitizeText","chars","buf","htmlSanitizeWriter","writer","noop","join","makeMap","str","obj","items","split","i","length","htmlParser","html","handler","parseStartTag","tag","tagName","rest","unary","lowercase","blockElements","stack","last","inlineElements","parseEndTag","optionalEndTagElements","voidElements","push","attrs","replace","ATTR_REGEXP","match","name","doubleQuotedValue","singleQuotedValue","unquotedValue","decodeEntities","start","pos","end","index","stack.last","specialElements","RegExp","all","text","COMMENT_REGEXP","CDATA_REGEXP","indexOf","lastIndexOf","comment","substring","DOCTYPE_REGEXP","test","BEGIN_END_TAGE_REGEXP","END_TAG_REGEXP","BEGIN_TAG_REGEXP","START_TAG_REGEXP","$sanitizeMinErr","value","parts","spaceRe","exec","spaceBefore","spaceAfter","content","hiddenPre","innerHTML","textContent","innerText","encodeEntities","NON_ALPHANUMERIC_REGEXP","charCodeAt","uriValidator","ignore","out","bind","validElements","forEach","key","lkey","isImage","validAttrs","uriAttrs","$$minErr","optionalEndTagBlockElements","optionalEndTagInlineElements","extend","document","createElement","module","provider","$SanitizeProvider","$get","$$sanitizeUri","uri","filter","$sanitize","LINKY_URL_REGEXP","MAILTO_REGEXP","target","addText","addLink","url","isDefined","raw","substr"] + "version":3, + "file":"angular-sanitize.min.js", + "lineCount":16, + "mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkB,CAykB3BC,QAASA,EAAY,CAACC,CAAD,CAAQ,CAC3B,IAAIC,EAAM,EACGC,EAAAC,CAAmBF,CAAnBE,CAAwBC,CAAxBD,CACbH,MAAA,CAAaA,CAAb,CACA,OAAOC,EAAAI,KAAA,CAAS,EAAT,CAJoB,CA5jB7B,IAAIC,EAAkBR,CAAAS,SAAA,CAAiB,WAAjB,CAAtB,CACIC,CADJ,CAEIC,CAFJ,CAGIC,CAHJ,CAIIC,CAJJ,CAKIC,CALJ,CAMIR,CANJ,CAOIS,CAPJ,CAQIC,CARJ,CASIZ,CA4jBJJ,EAAAiB,OAAA,CAAe,YAAf,CAA6B,EAA7B,CAAAC,SAAA,CACY,WADZ,CAhcAC,QAA0B,EAAG,CA4J3BC,QAASA,EAAK,CAACC,CAAD,CAAMC,CAAN,CAAqB,CAAA,IAC7BC,EAAM,EADuB,CACnBC,EAAQH,CAAAI,MAAA,CAAU,GAAV,CADW,CACKC,CACtC,KAAKA,CAAL,CAAS,CAAT,CAAYA,CAAZ,CAAgBF,CAAAG,OAAhB,CAA8BD,CAAA,EAA9B,CACEH,CAAA,CAAID,CAAA,CAAgBR,CAAA,CAAUU,CAAA,CAAME,CAAN,CAAV,CAAhB,CAAsCF,CAAA,CAAME,CAAN,CAA1C,CAAA,CAAsD,CAAA,CAExD,OAAOH,EAL0B,CAwJnCK,QAASA,EAAS,CAACC,CAAD,CAAQ,CAExB,IADA,IAAIC,EAAM,EAAV,CACSJ,EAAI,CADb,CACgBK,EAAKF,CAAAF,OAArB,CAAmCD,CAAnC,CAAuCK,CAAvC,CAA2CL,CAAA,EAA3C,CAAgD,CAC9C,IAAIM,EAAOH,CAAA,CAAMH,CAAN,CACXI,EAAA,CAAIE,CAAAC,KAAJ,CAAA,CAAiBD,CAAAE,MAF6B,CAIhD,MAAOJ,EANiB,CAiB1BK,QAASA,EAAc,CAACD,CAAD,CAAQ,CAC7B,MAAOA,EAAAE,QAAA,CACG,IADH,CACS,OADT,CAAAA,QAAA,CAEGC,CAFH,CAE0B,QAAQ,CAACH,CAAD,CAAQ,CAC7C,IAAII,EAAKJ,CAAAK,WAAA,CAAiB,CAAjB,CACLC,EAAAA,CAAMN,CAAAK,WAAA,CAAiB,CAAjB,CACV,OAAO,IAAP,EAAgC,IAAhC,EAAiBD,CAAjB;AAAsB,KAAtB,GAA0CE,CAA1C,CAAgD,KAAhD,EAA0D,KAA1D,EAAqE,GAHxB,CAF1C,CAAAJ,QAAA,CAOGK,CAPH,CAO4B,QAAQ,CAACP,CAAD,CAAQ,CAC/C,MAAO,IAAP,CAAcA,CAAAK,WAAA,CAAiB,CAAjB,CAAd,CAAoC,GADW,CAP5C,CAAAH,QAAA,CAUG,IAVH,CAUS,MAVT,CAAAA,QAAA,CAWG,IAXH,CAWS,MAXT,CADsB,CAgF/BM,QAASA,EAAkB,CAACC,CAAD,CAAO,CAChC,IAAA,CAAOA,CAAP,CAAA,CAAa,CACX,GAAIA,CAAAC,SAAJ,GAAsB7C,CAAA8C,KAAAC,aAAtB,CAEE,IADA,IAAIjB,EAAQc,CAAAI,WAAZ,CACSrB,EAAI,CADb,CACgBsB,EAAInB,CAAAF,OAApB,CAAkCD,CAAlC,CAAsCsB,CAAtC,CAAyCtB,CAAA,EAAzC,CAA8C,CAC5C,IAAIuB,EAAWpB,CAAA,CAAMH,CAAN,CAAf,CACIwB,EAAWD,CAAAhB,KAAAkB,YAAA,EACf,IAAiB,WAAjB,GAAID,CAAJ,EAAoE,CAApE,GAAgCA,CAAAE,YAAA,CAAqB,MAArB,CAA6B,CAA7B,CAAhC,CACET,CAAAU,oBAAA,CAAyBJ,CAAzB,CAEA,CADAvB,CAAA,EACA,CAAAsB,CAAA,EAN0C,CAYhD,CADIM,CACJ,CADeX,CAAAY,WACf,GACEb,CAAA,CAAmBY,CAAnB,CAGFX,EAAA,CAAOa,CAAA,CAAiB,aAAjB,CAAgCb,CAAhC,CAnBI,CADmB,CAwBlCa,QAASA,EAAgB,CAACC,CAAD,CAAWd,CAAX,CAAiB,CAExC,IAAIW,EAAWX,CAAA,CAAKc,CAAL,CACf,IAAIH,CAAJ,EAAgBvC,CAAA2C,KAAA,CAAkBf,CAAlB,CAAwBW,CAAxB,CAAhB,CACE,KAAM9C,EAAA,CAAgB,QAAhB,CAA2FmC,CAAAgB,UAA3F,EAA6GhB,CAAAiB,UAA7G,CAAN,CAEF,MAAON,EANiC,CA5a1C,IAAIO,EAAa,CAAA,CAEjB,KAAAC,KAAA;AAAY,CAAC,eAAD,CAAkB,QAAQ,CAACC,CAAD,CAAgB,CAChDF,CAAJ,EACElD,CAAA,CAAOqD,CAAP,CAAsBC,CAAtB,CAEF,OAAO,SAAQ,CAACC,CAAD,CAAO,CACpB,IAAI/D,EAAM,EACVa,EAAA,CAAWkD,CAAX,CAAiB9D,CAAA,CAAmBD,CAAnB,CAAwB,QAAQ,CAACgE,CAAD,CAAMC,CAAN,CAAe,CAC9D,MAAO,CAAC,UAAAC,KAAA,CAAgBN,CAAA,CAAcI,CAAd,CAAmBC,CAAnB,CAAhB,CADsD,CAA/C,CAAjB,CAGA,OAAOjE,EAAAI,KAAA,CAAS,EAAT,CALa,CAJ8B,CAA1C,CA4CZ,KAAA+D,UAAA,CAAiBC,QAAQ,CAACD,CAAD,CAAY,CACnC,MAAIzD,EAAA,CAAUyD,CAAV,CAAJ,EACET,CACO,CADMS,CACN,CAAA,IAFT,EAIST,CAL0B,CAarCnD,EAAA,CAAOV,CAAAU,KACPC,EAAA,CAASX,CAAAW,OACTC,EAAA,CAAUZ,CAAAY,QACVC,EAAA,CAAYb,CAAAa,UACZC,EAAA,CAAYd,CAAAc,UACZR,EAAA,CAAON,CAAAM,KAEPU,EAAA,CAsLAwD,QAAuB,CAACN,CAAD,CAAOO,CAAP,CAAgB,CACxB,IAAb,GAAIP,CAAJ,EAA8BQ,IAAAA,EAA9B,GAAqBR,CAArB,CACEA,CADF,CACS,EADT,CAE2B,QAF3B,GAEW,MAAOA,EAFlB,GAGEA,CAHF,CAGS,EAHT,CAGcA,CAHd,CAMA,KAAIS,EAAmBC,CAAA,CAAoBV,CAApB,CACvB,IAAKS,CAAAA,CAAL,CAAuB,MAAO,EAG9B,KAAIE,EAAe,CACnB,GAAG,CACD,GAAqB,CAArB,GAAIA,CAAJ,CACE,KAAMrE,EAAA,CAAgB,QAAhB,CAAN,CAEFqE,CAAA,EAGAX,EAAA,CAAOS,CAAAG,UACPH,EAAA,CAAmBC,CAAA,CAAoBV,CAApB,CARlB,CAAH,MASSA,CATT,GASkBS,CAAAG,UATlB,CAYA,KADInC,CACJ,CADWgC,CAAApB,WACX,CAAOZ,CAAP,CAAA,CAAa,CACX,OAAQA,CAAAC,SAAR,EACE,KAAK,CAAL,CACE6B,CAAAM,MAAA,CAAcpC,CAAAqC,SAAA7B,YAAA,EAAd;AAA2CvB,CAAA,CAAUe,CAAAI,WAAV,CAA3C,CACA,MACF,MAAK,CAAL,CACE0B,CAAAvE,MAAA,CAAcyC,CAAAsC,YAAd,CALJ,CASA,IAAI3B,CACJ,IAAM,EAAAA,CAAA,CAAWX,CAAAY,WAAX,CAAN,GACwB,CAIjBD,GAJDX,CAAAC,SAICU,EAHHmB,CAAAS,IAAA,CAAYvC,CAAAqC,SAAA7B,YAAA,EAAZ,CAGGG,CADLA,CACKA,CADME,CAAA,CAAiB,aAAjB,CAAgCb,CAAhC,CACNW,CAAAA,CAAAA,CALP,EAMI,IAAA,CAAmB,IAAnB,EAAOA,CAAP,CAAA,CAAyB,CACvBX,CAAA,CAAOa,CAAA,CAAiB,YAAjB,CAA+Bb,CAA/B,CACP,IAAIA,CAAJ,GAAagC,CAAb,CAA+B,KAC/BrB,EAAA,CAAWE,CAAA,CAAiB,aAAjB,CAAgCb,CAAhC,CACW,EAAtB,GAAIA,CAAAC,SAAJ,EACE6B,CAAAS,IAAA,CAAYvC,CAAAqC,SAAA7B,YAAA,EAAZ,CALqB,CAU7BR,CAAA,CAAOW,CA3BI,CA8Bb,IAAA,CAAQX,CAAR,CAAegC,CAAApB,WAAf,CAAA,CACEoB,CAAAQ,YAAA,CAA6BxC,CAA7B,CAvDmC,CArLvCvC,EAAA,CA0RAgF,QAA+B,CAACjF,CAAD,CAAMkF,CAAN,CAAoB,CACjD,IAAIC,EAAuB,CAAA,CAA3B,CACIC,EAAM7E,CAAA,CAAKP,CAAL,CAAUA,CAAAqF,KAAV,CACV,OAAO,CACLT,MAAOA,QAAQ,CAACU,CAAD,CAAM5D,CAAN,CAAa,CAC1B4D,CAAA,CAAM3E,CAAA,CAAU2E,CAAV,CACDH,EAAAA,CAAL,EAA6BI,CAAA,CAAgBD,CAAhB,CAA7B,GACEH,CADF,CACyBG,CADzB,CAGKH,EAAL,EAAoD,CAAA,CAApD,GAA6BtB,CAAA,CAAcyB,CAAd,CAA7B,GACEF,CAAA,CAAI,GAAJ,CAcA,CAbAA,CAAA,CAAIE,CAAJ,CAaA,CAZA7E,CAAA,CAAQiB,CAAR,CAAe,QAAQ,CAACK,CAAD,CAAQyD,CAAR,CAAa,CAClC,IAAIC,EAAO9E,CAAA,CAAU6E,CAAV,CAAX,CACIvB,EAAmB,KAAnBA,GAAWqB,CAAXrB,EAAqC,KAArCA,GAA4BwB,CAA5BxB,EAAyD,YAAzDA;AAAgDwB,CAC3B,EAAA,CAAzB,GAAIC,CAAA,CAAWD,CAAX,CAAJ,EACsB,CAAA,CADtB,GACGE,CAAA,CAASF,CAAT,CADH,EAC8B,CAAAP,CAAA,CAAanD,CAAb,CAAoBkC,CAApB,CAD9B,GAEEmB,CAAA,CAAI,GAAJ,CAIA,CAHAA,CAAA,CAAII,CAAJ,CAGA,CAFAJ,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAIpD,CAAA,CAAeD,CAAf,CAAJ,CACA,CAAAqD,CAAA,CAAI,GAAJ,CANF,CAHkC,CAApC,CAYA,CAAAA,CAAA,CAAI,GAAJ,CAfF,CAL0B,CADvB,CAwBLL,IAAKA,QAAQ,CAACO,CAAD,CAAM,CACjBA,CAAA,CAAM3E,CAAA,CAAU2E,CAAV,CACDH,EAAL,EAAoD,CAAA,CAApD,GAA6BtB,CAAA,CAAcyB,CAAd,CAA7B,EAAkF,CAAA,CAAlF,GAA4DM,CAAA,CAAaN,CAAb,CAA5D,GACEF,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAIE,CAAJ,CACA,CAAAF,CAAA,CAAI,GAAJ,CAHF,CAMIE,EAAJ,EAAWH,CAAX,GACEA,CADF,CACyB,CAAA,CADzB,CARiB,CAxBd,CAoCLpF,MAAOA,QAAQ,CAACA,CAAD,CAAQ,CAChBoF,CAAL,EACEC,CAAA,CAAIpD,CAAA,CAAejC,CAAf,CAAJ,CAFmB,CApClB,CAH0C,CAxRnDa,EAAA,CAAehB,CAAA8C,KAAAmD,UAAAC,SAAf,EAA8D,QAAQ,CAACC,CAAD,CAAM,CAE1E,MAAO,CAAG,EAAA,IAAAC,wBAAA,CAA6BD,CAA7B,CAAA,CAAoC,EAApC,CAFgE,CAtEjD,KA4EvB7D,EAAwB,iCA5ED,CA8EzBI,EAA0B,cA9ED,CAuFvBsD,EAAe3E,CAAA,CAAM,wBAAN,CAvFQ,CA2FvBgF,EAA8BhF,CAAA,CAAM,gDAAN,CA3FP,CA4FvBiF,EAA+BjF,CAAA,CAAM,OAAN,CA5FR,CA6FvBkF,EAAyB3F,CAAA,CAAO,EAAP,CACe0F,CADf,CAEeD,CAFf,CA7FF,CAkGvBG,EAAgB5F,CAAA,CAAO,EAAP,CAAWyF,CAAX,CAAwChF,CAAA,CAAM,qKAAN,CAAxC,CAlGO;AAuGvBoF,EAAiB7F,CAAA,CAAO,EAAP,CAAW0F,CAAX,CAAyCjF,CAAA,CAAM,2JAAN,CAAzC,CAvGM,CA+GvB6C,EAAc7C,CAAA,CAAM,wNAAN,CA/GS,CAoHvBsE,EAAkBtE,CAAA,CAAM,cAAN,CApHK,CAsHvB4C,EAAgBrD,CAAA,CAAO,EAAP,CACeoF,CADf,CAEeQ,CAFf,CAGeC,CAHf,CAIeF,CAJf,CAtHO,CA6HvBR,EAAW1E,CAAA,CAAM,uDAAN,CA7HY,CA+HvBqF,EAAYrF,CAAA,CAAM,kTAAN,CA/HW;AAuIvBsF,EAAWtF,CAAA,CAAM,guCAAN;AAcoE,CAAA,CAdpE,CAvIY,CAuJvByE,EAAalF,CAAA,CAAO,EAAP,CACemF,CADf,CAEeY,CAFf,CAGeD,CAHf,CAvJU,CA0KvB7B,EAAqE,QAAQ,CAAC7E,CAAD,CAAS4G,CAAT,CAAmB,CAyClGC,QAASA,EAA6B,CAAC1C,CAAD,CAAO,CAG3CA,CAAA,CAAO,mBAAP,CAA6BA,CAC7B,IAAI,CACF,IAAI2C,EAAOC,CAAA,IAAI/G,CAAAgH,UAAJD,iBAAA,CAAuC5C,CAAvC,CAA6C,WAA7C,CAAA2C,KACXA,EAAAtD,WAAAyD,OAAA,EACA,OAAOH,EAHL,CAIF,MAAOI,CAAP,CAAU,EAR+B,CAa7CC,QAASA,EAAiC,CAAChD,CAAD,CAAO,CAC/CS,CAAAG,UAAA,CAA6BZ,CAIzByC,EAAAQ,aAAJ,EACEzE,CAAA,CAAmBiC,CAAnB,CAGF,OAAOA,EATwC,CArDjD,IAAIyC,CACJ,IAAIT,CAAJ,EAAgBA,CAAAU,eAAhB,CACED,CAAA,CAAgBT,CAAAU,eAAAC,mBAAA,CAA2C,OAA3C,CADlB,KAGE,MAAM9G,EAAA,CAAgB,SAAhB,CAAN,CAEF,IAAImE,EAAmB4C,CAACH,CAAAI,gBAADD,EAAkCH,CAAAK,mBAAA,EAAlCF,eAAA,CAAoF,MAApF,CAGvB5C,EAAAG,UAAA,CAA6B,sDAC7B,OAAKH,EAAA4C,cAAA,CAA+B,KAA/B,CAAL;CAIE5C,CAAAG,UACA,CAD6B,kEAC7B,CAAIH,CAAA4C,cAAA,CAA+B,SAA/B,CAAJ,CACSX,CADT,CAGSM,CARX,EAYAQ,QAAgC,CAACxD,CAAD,CAAO,CAGrCA,CAAA,CAAO,mBAAP,CAA6BA,CAC7B,IAAI,CACFA,CAAA,CAAOyD,SAAA,CAAUzD,CAAV,CADL,CAEF,MAAO+C,CAAP,CAAU,CACV,MADU,CAGZ,IAAIW,EAAM,IAAI7H,CAAA8H,eACdD,EAAAE,aAAA,CAAmB,UACnBF,EAAAG,KAAA,CAAS,KAAT,CAAgB,+BAAhB,CAAkD7D,CAAlD,CAAwD,CAAA,CAAxD,CACA0D,EAAAI,KAAA,CAAS,IAAT,CACInB,EAAAA,CAAOe,CAAAK,SAAApB,KACXA,EAAAtD,WAAAyD,OAAA,EACA,OAAOH,EAf8B,CAvB2D,CAA5B,CAiErE9G,CAjEqE,CAiE7DA,CAAA4G,SAjE6D,CA1K7C,CAgc7B,CAAAuB,KAAA,CAEQ,CAAEC,eAAgB,OAAlB,CAFR,CAmIAnI,EAAAiB,OAAA,CAAe,YAAf,CAAAmH,OAAA,CAAoC,OAApC,CAA6C,CAAC,WAAD,CAAc,QAAQ,CAACC,CAAD,CAAY,CAAA,IACzEC,EACE,2FAFuE;AAGzEC,EAAgB,WAHyD,CAKzEC,EAAcxI,CAAAS,SAAA,CAAiB,OAAjB,CAL2D,CAMzEI,EAAYb,CAAAa,UAN6D,CAOzE4H,EAAazI,CAAAyI,WAP4D,CAQzEC,EAAW1I,CAAA0I,SAR8D,CASzEC,EAAW3I,CAAA2I,SAEf,OAAO,SAAQ,CAACC,CAAD,CAAOC,CAAP,CAAe9F,CAAf,CAA2B,CA6BxC+F,QAASA,EAAO,CAACF,CAAD,CAAO,CAChBA,CAAL,EAGA1E,CAAAsB,KAAA,CAAUvF,CAAA,CAAa2I,CAAb,CAAV,CAJqB,CAOvBG,QAASA,EAAO,CAACC,CAAD,CAAMJ,CAAN,CAAY,CAAA,IACtBjD,CADsB,CACjBsD,EAAiBC,CAAA,CAAaF,CAAb,CAC1B9E,EAAAsB,KAAA,CAAU,KAAV,CAEA,KAAKG,CAAL,GAAYsD,EAAZ,CACE/E,CAAAsB,KAAA,CAAUG,CAAV,CAAgB,IAAhB,CAAuBsD,CAAA,CAAetD,CAAf,CAAvB,CAA6C,IAA7C,CAGE,EAAA9E,CAAA,CAAUgI,CAAV,CAAJ,EAA2B,QAA3B,EAAuCI,EAAvC,EACE/E,CAAAsB,KAAA,CAAU,UAAV,CACUqD,CADV,CAEU,IAFV,CAIF3E,EAAAsB,KAAA,CAAU,QAAV,CACUwD,CAAA5G,QAAA,CAAY,IAAZ,CAAkB,QAAlB,CADV,CAEU,IAFV,CAGA0G,EAAA,CAAQF,CAAR,CACA1E,EAAAsB,KAAA,CAAU,MAAV,CAjB0B,CAnC5B,GAAY,IAAZ,EAAIoD,CAAJ,EAA6B,EAA7B,GAAoBA,CAApB,CAAiC,MAAOA,EACxC,IAAK,CAAAD,CAAA,CAASC,CAAT,CAAL,CAAqB,KAAMJ,EAAA,CAAY,WAAZ,CAA8DI,CAA9D,CAAN,CAYrB,IAVA,IAAIM,EACFT,CAAA,CAAW1F,CAAX,CAAA,CAAyBA,CAAzB,CACA2F,CAAA,CAAS3F,CAAT,CAAA,CAAuBoG,QAA4B,EAAG,CAAC,MAAOpG,EAAR,CAAtD,CACAqG,QAAiC,EAAG,CAAC,MAAO,EAAR,CAHtC,CAMIC,EAAMT,CANV,CAOI1E,EAAO,EAPX,CAQI8E,CARJ,CASItH,CACJ,CAAQ4H,CAAR,CAAgBD,CAAAC,MAAA,CAAUhB,CAAV,CAAhB,CAAA,CAEEU,CAQA,CARMM,CAAA,CAAM,CAAN,CAQN,CANKA,CAAA,CAAM,CAAN,CAML;AANkBA,CAAA,CAAM,CAAN,CAMlB,GALEN,CAKF,EALSM,CAAA,CAAM,CAAN,CAAA,CAAW,SAAX,CAAuB,SAKhC,EAL6CN,CAK7C,EAHAtH,CAGA,CAHI4H,CAAAC,MAGJ,CAFAT,CAAA,CAAQO,CAAAG,OAAA,CAAW,CAAX,CAAc9H,CAAd,CAAR,CAEA,CADAqH,CAAA,CAAQC,CAAR,CAAaM,CAAA,CAAM,CAAN,CAAAlH,QAAA,CAAiBmG,CAAjB,CAAgC,EAAhC,CAAb,CACA,CAAAc,CAAA,CAAMA,CAAAI,UAAA,CAAc/H,CAAd,CAAkB4H,CAAA,CAAM,CAAN,CAAA3H,OAAlB,CAERmH,EAAA,CAAQO,CAAR,CACA,OAAOhB,EAAA,CAAUnE,CAAA3D,KAAA,CAAU,EAAV,CAAV,CA3BiC,CAXmC,CAAlC,CAA7C,CArtB2B,CAA1B,CAAD,CA2xBGR,MA3xBH,CA2xBWA,MAAAC,QA3xBX;", + "sources":["angular-sanitize.js"], + "names":["window","angular","sanitizeText","chars","buf","htmlSanitizeWriter","writer","noop","join","$sanitizeMinErr","$$minErr","bind","extend","forEach","isDefined","lowercase","nodeContains","htmlParser","module","provider","$SanitizeProvider","toMap","str","lowercaseKeys","obj","items","split","i","length","attrToMap","attrs","map","ii","attr","name","value","encodeEntities","replace","SURROGATE_PAIR_REGEXP","hi","charCodeAt","low","NON_ALPHANUMERIC_REGEXP","stripCustomNsAttrs","node","nodeType","Node","ELEMENT_NODE","attributes","l","attrNode","attrName","toLowerCase","lastIndexOf","removeAttributeNode","nextNode","firstChild","getNonDescendant","propName","call","outerHTML","outerText","svgEnabled","$get","$$sanitizeUri","validElements","svgElements","html","uri","isImage","test","enableSvg","this.enableSvg","htmlParserImpl","handler","undefined","inertBodyElement","getInertBodyElement","mXSSAttempts","innerHTML","start","nodeName","textContent","end","removeChild","htmlSanitizeWriterImpl","uriValidator","ignoreCurrentElement","out","push","tag","blockedElements","key","lkey","validAttrs","uriAttrs","voidElements","prototype","contains","arg","compareDocumentPosition","optionalEndTagBlockElements","optionalEndTagInlineElements","optionalEndTagElements","blockElements","inlineElements","htmlAttrs","svgAttrs","document","getInertBodyElement_DOMParser","body","parseFromString","DOMParser","remove","e","getInertBodyElement_InertDocument","documentMode","inertDocument","implementation","createHTMLDocument","querySelector","documentElement","getDocumentElement","getInertBodyElement_XHR","encodeURI","xhr","XMLHttpRequest","responseType","open","send","response","info","angularVersion","filter","$sanitize","LINKY_URL_REGEXP","MAILTO_REGEXP","linkyMinErr","isFunction","isObject","isString","text","target","addText","addLink","url","linkAttributes","attributesFn","getAttributesObject","getEmptyAttributesObject","raw","match","index","substr","substring"] } \ No newline at end of file diff --git a/setup/pub/angular-ui-bootstrap/angular-ui-bootstrap.min.js b/setup/pub/angular-ui-bootstrap/angular-ui-bootstrap.min.js index fa6a8613174cf..2676e0ae9dd18 100644 --- a/setup/pub/angular-ui-bootstrap/angular-ui-bootstrap.min.js +++ b/setup/pub/angular-ui-bootstrap/angular-ui-bootstrap.min.js @@ -6,5 +6,5 @@ * License: MIT */ angular.module("ui.bootstrap",["ui.bootstrap.tpls","ui.bootstrap.transition","ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.bindHtml","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]),angular.module("ui.bootstrap.tpls",["template/accordion/accordion-group.html","template/accordion/accordion.html","template/alert/alert.html","template/carousel/carousel.html","template/carousel/slide.html","template/datepicker/datepicker.html","template/datepicker/day.html","template/datepicker/month.html","template/datepicker/popup.html","template/datepicker/year.html","template/modal/backdrop.html","template/modal/window.html","template/pagination/pager.html","template/pagination/pagination.html","template/tooltip/tooltip-html-unsafe-popup.html","template/tooltip/tooltip-popup.html","template/popover/popover.html","template/progressbar/bar.html","template/progressbar/progress.html","template/progressbar/progressbar.html","template/rating/rating.html","template/tabs/tab.html","template/tabs/tabset.html","template/timepicker/timepicker.html","template/typeahead/typeahead-match.html","template/typeahead/typeahead-popup.html"]),angular.module("ui.bootstrap.transition",[]).factory("$transition",["$q","$timeout","$rootScope",function(a,b,c){function d(a){for(var b in a)if(void 0!==f.style[b])return a[b]}var e=function(d,f,g){g=g||{};var h=a.defer(),i=e[g.animation?"animationEndEventName":"transitionEndEventName"],j=function(){c.$apply(function(){d.unbind(i,j),h.resolve(d)})};return i&&d.bind(i,j),b(function(){angular.isString(f)?d.addClass(f):angular.isFunction(f)?f(d):angular.isObject(f)&&d.css(f),i||h.resolve(d)}),h.promise.cancel=function(){i&&d.unbind(i,j),h.reject("Transition cancelled")},h.promise},f=document.createElement("trans"),g={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd",transition:"transitionend"},h={WebkitTransition:"webkitAnimationEnd",MozTransition:"animationend",OTransition:"oAnimationEnd",transition:"animationend"};return e.transitionEndEventName=d(g),e.animationEndEventName=d(h),e}]),angular.module("ui.bootstrap.collapse",["ui.bootstrap.transition"]).directive("collapse",["$transition",function(a){return{link:function(b,c,d){function e(b){function d(){j===e&&(j=void 0)}var e=a(c,b);return j&&j.cancel(),j=e,e.then(d,d),e}function f(){k?(k=!1,g()):(c.removeClass("collapse").addClass("collapsing"),e({height:c[0].scrollHeight+"px"}).then(g))}function g(){c.removeClass("collapsing"),c.addClass("collapse in"),c.css({height:"auto"})}function h(){if(k)k=!1,i(),c.css({height:0});else{c.css({height:c[0].scrollHeight+"px"});{c[0].offsetWidth}c.removeClass("collapse in").addClass("collapsing"),e({height:0}).then(i)}}function i(){c.removeClass("collapsing"),c.addClass("collapse")}var j,k=!0;b.$watch(d.collapse,function(a){a?h():f()})}}}]),angular.module("ui.bootstrap.accordion",["ui.bootstrap.collapse"]).constant("accordionConfig",{closeOthers:!0}).controller("AccordionController",["$scope","$attrs","accordionConfig",function(a,b,c){this.groups=[],this.closeOthers=function(d){var e=angular.isDefined(b.closeOthers)?a.$eval(b.closeOthers):c.closeOthers;e&&angular.forEach(this.groups,function(a){a!==d&&(a.isOpen=!1)})},this.addGroup=function(a){var b=this;this.groups.push(a),a.$on("$destroy",function(){b.removeGroup(a)})},this.removeGroup=function(a){var b=this.groups.indexOf(a);-1!==b&&this.groups.splice(b,1)}}]).directive("accordion",function(){return{restrict:"EA",controller:"AccordionController",transclude:!0,replace:!1,templateUrl:"template/accordion/accordion.html"}}).directive("accordionGroup",function(){return{require:"^accordion",restrict:"EA",transclude:!0,replace:!0,templateUrl:"template/accordion/accordion-group.html",scope:{heading:"@",isOpen:"=?",isDisabled:"=?"},controller:function(){this.setHeading=function(a){this.heading=a}},link:function(a,b,c,d){d.addGroup(a),a.$watch("isOpen",function(b){b&&d.closeOthers(a)}),a.toggleOpen=function(){a.isDisabled||(a.isOpen=!a.isOpen)}}}}).directive("accordionHeading",function(){return{restrict:"EA",transclude:!0,template:"",replace:!0,require:"^accordionGroup",link:function(a,b,c,d,e){d.setHeading(e(a,function(){}))}}}).directive("accordionTransclude",function(){return{require:"^accordionGroup",link:function(a,b,c,d){a.$watch(function(){return d[c.accordionTransclude]},function(a){a&&(b.html(""),b.append(a))})}}}),angular.module("ui.bootstrap.alert",[]).controller("AlertController",["$scope","$attrs",function(a,b){a.closeable="close"in b}]).directive("alert",function(){return{restrict:"EA",controller:"AlertController",templateUrl:"template/alert/alert.html",transclude:!0,replace:!0,scope:{type:"@",close:"&"}}}),angular.module("ui.bootstrap.bindHtml",[]).directive("bindHtmlUnsafe",function(){return function(a,b,c){b.addClass("ng-binding").data("$binding",c.bindHtmlUnsafe),a.$watch(c.bindHtmlUnsafe,function(a){b.html(a||"")})}}),angular.module("ui.bootstrap.buttons",[]).constant("buttonConfig",{activeClass:"active",toggleEvent:"click"}).controller("ButtonsController",["buttonConfig",function(a){this.activeClass=a.activeClass||"active",this.toggleEvent=a.toggleEvent||"click"}]).directive("btnRadio",function(){return{require:["btnRadio","ngModel"],controller:"ButtonsController",link:function(a,b,c,d){var e=d[0],f=d[1];f.$render=function(){b.toggleClass(e.activeClass,angular.equals(f.$modelValue,a.$eval(c.btnRadio)))},b.bind(e.toggleEvent,function(){var d=b.hasClass(e.activeClass);(!d||angular.isDefined(c.uncheckable))&&a.$apply(function(){f.$setViewValue(d?null:a.$eval(c.btnRadio)),f.$render()})})}}}).directive("btnCheckbox",function(){return{require:["btnCheckbox","ngModel"],controller:"ButtonsController",link:function(a,b,c,d){function e(){return g(c.btnCheckboxTrue,!0)}function f(){return g(c.btnCheckboxFalse,!1)}function g(b,c){var d=a.$eval(b);return angular.isDefined(d)?d:c}var h=d[0],i=d[1];i.$render=function(){b.toggleClass(h.activeClass,angular.equals(i.$modelValue,e()))},b.bind(h.toggleEvent,function(){a.$apply(function(){i.$setViewValue(b.hasClass(h.activeClass)?f():e()),i.$render()})})}}}),angular.module("ui.bootstrap.carousel",["ui.bootstrap.transition"]).controller("CarouselController",["$scope","$timeout","$transition",function(a,b,c){function d(){e();var c=+a.interval;!isNaN(c)&&c>=0&&(g=b(f,c))}function e(){g&&(b.cancel(g),g=null)}function f(){h?(a.next(),d()):a.pause()}var g,h,i=this,j=i.slides=a.slides=[],k=-1;i.currentSlide=null;var l=!1;i.select=a.select=function(e,f){function g(){if(!l){if(i.currentSlide&&angular.isString(f)&&!a.noTransition&&e.$element){e.$element.addClass(f);{e.$element[0].offsetWidth}angular.forEach(j,function(a){angular.extend(a,{direction:"",entering:!1,leaving:!1,active:!1})}),angular.extend(e,{direction:f,active:!0,entering:!0}),angular.extend(i.currentSlide||{},{direction:f,leaving:!0}),a.$currentTransition=c(e.$element,{}),function(b,c){a.$currentTransition.then(function(){h(b,c)},function(){h(b,c)})}(e,i.currentSlide)}else h(e,i.currentSlide);i.currentSlide=e,k=m,d()}}function h(b,c){angular.extend(b,{direction:"",active:!0,leaving:!1,entering:!1}),angular.extend(c||{},{direction:"",active:!1,leaving:!1,entering:!1}),a.$currentTransition=null}var m=j.indexOf(e);void 0===f&&(f=m>k?"next":"prev"),e&&e!==i.currentSlide&&(a.$currentTransition?(a.$currentTransition.cancel(),b(g)):g())},a.$on("$destroy",function(){l=!0}),i.indexOfSlide=function(a){return j.indexOf(a)},a.next=function(){var b=(k+1)%j.length;return a.$currentTransition?void 0:i.select(j[b],"next")},a.prev=function(){var b=0>k-1?j.length-1:k-1;return a.$currentTransition?void 0:i.select(j[b],"prev")},a.isActive=function(a){return i.currentSlide===a},a.$watch("interval",d),a.$on("$destroy",e),a.play=function(){h||(h=!0,d())},a.pause=function(){a.noPause||(h=!1,e())},i.addSlide=function(b,c){b.$element=c,j.push(b),1===j.length||b.active?(i.select(j[j.length-1]),1==j.length&&a.play()):b.active=!1},i.removeSlide=function(a){var b=j.indexOf(a);j.splice(b,1),j.length>0&&a.active?i.select(b>=j.length?j[b-1]:j[b]):k>b&&k--}}]).directive("carousel",[function(){return{restrict:"EA",transclude:!0,replace:!0,controller:"CarouselController",require:"carousel",templateUrl:"template/carousel/carousel.html",scope:{interval:"=",noTransition:"=",noPause:"="}}}]).directive("slide",function(){return{require:"^carousel",restrict:"EA",transclude:!0,replace:!0,templateUrl:"template/carousel/slide.html",scope:{active:"=?"},link:function(a,b,c,d){d.addSlide(a,b),a.$on("$destroy",function(){d.removeSlide(a)}),a.$watch("active",function(b){b&&d.select(a)})}}}),angular.module("ui.bootstrap.dateparser",[]).service("dateParser",["$locale","orderByFilter",function(a,b){function c(a,b,c){return 1===b&&c>28?29===c&&(a%4===0&&a%100!==0||a%400===0):3===b||5===b||8===b||10===b?31>c:!0}this.parsers={};var d={yyyy:{regex:"\\d{4}",apply:function(a){this.year=+a}},yy:{regex:"\\d{2}",apply:function(a){this.year=+a+2e3}},y:{regex:"\\d{1,4}",apply:function(a){this.year=+a}},MMMM:{regex:a.DATETIME_FORMATS.MONTH.join("|"),apply:function(b){this.month=a.DATETIME_FORMATS.MONTH.indexOf(b)}},MMM:{regex:a.DATETIME_FORMATS.SHORTMONTH.join("|"),apply:function(b){this.month=a.DATETIME_FORMATS.SHORTMONTH.indexOf(b)}},MM:{regex:"0[1-9]|1[0-2]",apply:function(a){this.month=a-1}},M:{regex:"[1-9]|1[0-2]",apply:function(a){this.month=a-1}},dd:{regex:"[0-2][0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a}},d:{regex:"[1-2]?[0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a}},EEEE:{regex:a.DATETIME_FORMATS.DAY.join("|")},EEE:{regex:a.DATETIME_FORMATS.SHORTDAY.join("|")}};this.createParser=function(a){var c=[],e=a.split("");return angular.forEach(d,function(b,d){var f=a.indexOf(d);if(f>-1){a=a.split(""),e[f]="("+b.regex+")",a[f]="$";for(var g=f+1,h=f+d.length;h>g;g++)e[g]="",a[g]="$";a=a.join(""),c.push({index:f,apply:b.apply})}}),{regex:new RegExp("^"+e.join("")+"$"),map:b(c,"index")}},this.parse=function(b,d){if(!angular.isString(b))return b;d=a.DATETIME_FORMATS[d]||d,this.parsers[d]||(this.parsers[d]=this.createParser(d));var e=this.parsers[d],f=e.regex,g=e.map,h=b.match(f);if(h&&h.length){for(var i,j={year:1900,month:0,date:1,hours:0},k=1,l=h.length;l>k;k++){var m=g[k-1];m.apply&&m.apply.call(j,h[k])}return c(j.year,j.month,j.date)&&(i=new Date(j.year,j.month,j.date,j.hours)),i}}}]),angular.module("ui.bootstrap.position",[]).factory("$position",["$document","$window",function(a,b){function c(a,c){return a.currentStyle?a.currentStyle[c]:b.getComputedStyle?b.getComputedStyle(a)[c]:a.style[c]}function d(a){return"static"===(c(a,"position")||"static")}var e=function(b){for(var c=a[0],e=b.offsetParent||c;e&&e!==c&&d(e);)e=e.offsetParent;return e||c};return{position:function(b){var c=this.offset(b),d={top:0,left:0},f=e(b[0]);f!=a[0]&&(d=this.offset(angular.element(f)),d.top+=f.clientTop-f.scrollTop,d.left+=f.clientLeft-f.scrollLeft);var g=b[0].getBoundingClientRect();return{width:g.width||b.prop("offsetWidth"),height:g.height||b.prop("offsetHeight"),top:c.top-d.top,left:c.left-d.left}},offset:function(c){var d=c[0].getBoundingClientRect();return{width:d.width||c.prop("offsetWidth"),height:d.height||c.prop("offsetHeight"),top:d.top+(b.pageYOffset||a[0].documentElement.scrollTop),left:d.left+(b.pageXOffset||a[0].documentElement.scrollLeft)}},positionElements:function(a,b,c,d){var e,f,g,h,i=c.split("-"),j=i[0],k=i[1]||"center";e=d?this.offset(a):this.position(a),f=b.prop("offsetWidth"),g=b.prop("offsetHeight");var l={center:function(){return e.left+e.width/2-f/2},left:function(){return e.left},right:function(){return e.left+e.width}},m={center:function(){return e.top+e.height/2-g/2},top:function(){return e.top},bottom:function(){return e.top+e.height}};switch(j){case"right":h={top:m[k](),left:l[j]()};break;case"left":h={top:m[k](),left:e.left-f};break;case"bottom":h={top:m[j](),left:l[k]()};break;default:h={top:e.top-g,left:l[k]()}}return h}}}]),angular.module("ui.bootstrap.datepicker",["ui.bootstrap.dateparser","ui.bootstrap.position"]).constant("datepickerConfig",{formatDay:"dd",formatMonth:"MMMM",formatYear:"yyyy",formatDayHeader:"EEE",formatDayTitle:"MMMM yyyy",formatMonthTitle:"yyyy",datepickerMode:"day",minMode:"day",maxMode:"year",showWeeks:!0,startingDay:0,yearRange:20,minDate:null,maxDate:null}).controller("DatepickerController",["$scope","$attrs","$parse","$interpolate","$timeout","$log","dateFilter","datepickerConfig",function(a,b,c,d,e,f,g,h){var i=this,j={$setViewValue:angular.noop};this.modes=["day","month","year"],angular.forEach(["formatDay","formatMonth","formatYear","formatDayHeader","formatDayTitle","formatMonthTitle","minMode","maxMode","showWeeks","startingDay","yearRange"],function(c,e){i[c]=angular.isDefined(b[c])?8>e?d(b[c])(a.$parent):a.$parent.$eval(b[c]):h[c]}),angular.forEach(["minDate","maxDate"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(a){i[d]=a?new Date(a):null,i.refreshView()}):i[d]=h[d]?new Date(h[d]):null}),a.datepickerMode=a.datepickerMode||h.datepickerMode,a.uniqueId="datepicker-"+a.$id+"-"+Math.floor(1e4*Math.random()),this.activeDate=angular.isDefined(b.initDate)?a.$parent.$eval(b.initDate):new Date,a.isActive=function(b){return 0===i.compare(b.date,i.activeDate)?(a.activeDateId=b.uid,!0):!1},this.init=function(a){j=a,j.$render=function(){i.render()}},this.render=function(){if(j.$modelValue){var a=new Date(j.$modelValue),b=!isNaN(a);b?this.activeDate=a:f.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'),j.$setValidity("date",b)}this.refreshView()},this.refreshView=function(){if(this.element){this._refreshView();var a=j.$modelValue?new Date(j.$modelValue):null;j.$setValidity("date-disabled",!a||this.element&&!this.isDisabled(a))}},this.createDateObject=function(a,b){var c=j.$modelValue?new Date(j.$modelValue):null;return{date:a,label:g(a,b),selected:c&&0===this.compare(a,c),disabled:this.isDisabled(a),current:0===this.compare(a,new Date)}},this.isDisabled=function(c){return this.minDate&&this.compare(c,this.minDate)<0||this.maxDate&&this.compare(c,this.maxDate)>0||b.dateDisabled&&a.dateDisabled({date:c,mode:a.datepickerMode})},this.split=function(a,b){for(var c=[];a.length>0;)c.push(a.splice(0,b));return c},a.select=function(b){if(a.datepickerMode===i.minMode){var c=j.$modelValue?new Date(j.$modelValue):new Date(0,0,0,0,0,0,0);c.setFullYear(b.getFullYear(),b.getMonth(),b.getDate()),j.$setViewValue(c),j.$render()}else i.activeDate=b,a.datepickerMode=i.modes[i.modes.indexOf(a.datepickerMode)-1]},a.move=function(a){var b=i.activeDate.getFullYear()+a*(i.step.years||0),c=i.activeDate.getMonth()+a*(i.step.months||0);i.activeDate.setFullYear(b,c,1),i.refreshView()},a.toggleMode=function(b){b=b||1,a.datepickerMode===i.maxMode&&1===b||a.datepickerMode===i.minMode&&-1===b||(a.datepickerMode=i.modes[i.modes.indexOf(a.datepickerMode)+b])},a.keys={13:"enter",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down"};var k=function(){e(function(){i.element[0].focus()},0,!1)};a.$on("datepicker.focus",k),a.keydown=function(b){var c=a.keys[b.which];if(c&&!b.shiftKey&&!b.altKey)if(b.preventDefault(),b.stopPropagation(),"enter"===c||"space"===c){if(i.isDisabled(i.activeDate))return;a.select(i.activeDate),k()}else!b.ctrlKey||"up"!==c&&"down"!==c?(i.handleKeyDown(c,b),i.refreshView()):(a.toggleMode("up"===c?1:-1),k())}}]).directive("datepicker",function(){return{restrict:"EA",replace:!0,templateUrl:"template/datepicker/datepicker.html",scope:{datepickerMode:"=?",dateDisabled:"&"},require:["datepicker","?^ngModel"],controller:"DatepickerController",link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f)}}}).directive("daypicker",["dateFilter",function(a){return{restrict:"EA",replace:!0,templateUrl:"template/datepicker/day.html",require:"^datepicker",link:function(b,c,d,e){function f(a,b){return 1!==b||a%4!==0||a%100===0&&a%400!==0?i[b]:29}function g(a,b){var c=new Array(b),d=new Date(a),e=0;for(d.setHours(12);b>e;)c[e++]=new Date(d),d.setDate(d.getDate()+1);return c}function h(a){var b=new Date(a);b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();return b.setMonth(0),b.setDate(1),Math.floor(Math.round((c-b)/864e5)/7)+1}b.showWeeks=e.showWeeks,e.step={months:1},e.element=c;var i=[31,28,31,30,31,30,31,31,30,31,30,31];e._refreshView=function(){var c=e.activeDate.getFullYear(),d=e.activeDate.getMonth(),f=new Date(c,d,1),i=e.startingDay-f.getDay(),j=i>0?7-i:-i,k=new Date(f);j>0&&k.setDate(-j+1);for(var l=g(k,42),m=0;42>m;m++)l[m]=angular.extend(e.createDateObject(l[m],e.formatDay),{secondary:l[m].getMonth()!==d,uid:b.uniqueId+"-"+m});b.labels=new Array(7);for(var n=0;7>n;n++)b.labels[n]={abbr:a(l[n].date,e.formatDayHeader),full:a(l[n].date,"EEEE")};if(b.title=a(e.activeDate,e.formatDayTitle),b.rows=e.split(l,7),b.showWeeks){b.weekNumbers=[];for(var o=h(b.rows[0][0].date),p=b.rows.length;b.weekNumbers.push(o++)f;f++)c[f]=angular.extend(e.createDateObject(new Date(d,f,1),e.formatMonth),{uid:b.uniqueId+"-"+f});b.title=a(e.activeDate,e.formatMonthTitle),b.rows=e.split(c,3)},e.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth())-new Date(b.getFullYear(),b.getMonth())},e.handleKeyDown=function(a){var b=e.activeDate.getMonth();if("left"===a)b-=1;else if("up"===a)b-=3;else if("right"===a)b+=1;else if("down"===a)b+=3;else if("pageup"===a||"pagedown"===a){var c=e.activeDate.getFullYear()+("pageup"===a?-1:1);e.activeDate.setFullYear(c)}else"home"===a?b=0:"end"===a&&(b=11);e.activeDate.setMonth(b)},e.refreshView()}}}]).directive("yearpicker",["dateFilter",function(){return{restrict:"EA",replace:!0,templateUrl:"template/datepicker/year.html",require:"^datepicker",link:function(a,b,c,d){function e(a){return parseInt((a-1)/f,10)*f+1}var f=d.yearRange;d.step={years:f},d.element=b,d._refreshView=function(){for(var b=new Array(f),c=0,g=e(d.activeDate.getFullYear());f>c;c++)b[c]=angular.extend(d.createDateObject(new Date(g+c,0,1),d.formatYear),{uid:a.uniqueId+"-"+c});a.title=[b[0].label,b[f-1].label].join(" - "),a.rows=d.split(b,5)},d.compare=function(a,b){return a.getFullYear()-b.getFullYear()},d.handleKeyDown=function(a){var b=d.activeDate.getFullYear();"left"===a?b-=1:"up"===a?b-=5:"right"===a?b+=1:"down"===a?b+=5:"pageup"===a||"pagedown"===a?b+=("pageup"===a?-1:1)*d.step.years:"home"===a?b=e(d.activeDate.getFullYear()):"end"===a&&(b=e(d.activeDate.getFullYear())+f-1),d.activeDate.setFullYear(b)},d.refreshView()}}}]).constant("datepickerPopupConfig",{datepickerPopup:"yyyy-MM-dd",currentText:"Today",clearText:"Clear",closeText:"Done",closeOnDateSelection:!0,appendToBody:!1,showButtonBar:!0}).directive("datepickerPopup",["$compile","$parse","$document","$position","dateFilter","dateParser","datepickerPopupConfig",function(a,b,c,d,e,f,g){return{restrict:"EA",require:"ngModel",scope:{isOpen:"=?",currentText:"@",clearText:"@",closeText:"@",dateDisabled:"&"},link:function(h,i,j,k){function l(a){return a.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()})}function m(a){if(a){if(angular.isDate(a)&&!isNaN(a))return k.$setValidity("date",!0),a;if(angular.isString(a)){var b=f.parse(a,n)||new Date(a);return isNaN(b)?void k.$setValidity("date",!1):(k.$setValidity("date",!0),b)}return void k.$setValidity("date",!1)}return k.$setValidity("date",!0),null}var n,o=angular.isDefined(j.closeOnDateSelection)?h.$parent.$eval(j.closeOnDateSelection):g.closeOnDateSelection,p=angular.isDefined(j.datepickerAppendToBody)?h.$parent.$eval(j.datepickerAppendToBody):g.appendToBody;h.showButtonBar=angular.isDefined(j.showButtonBar)?h.$parent.$eval(j.showButtonBar):g.showButtonBar,h.getText=function(a){return h[a+"Text"]||g[a+"Text"]},j.$observe("datepickerPopup",function(a){n=a||g.datepickerPopup,k.$render()});var q=angular.element("

");q.attr({"ng-model":"date","ng-change":"dateSelection()"});var r=angular.element(q.children()[0]);j.datepickerOptions&&angular.forEach(h.$parent.$eval(j.datepickerOptions),function(a,b){r.attr(l(b),a)}),angular.forEach(["minDate","maxDate"],function(a){j[a]&&(h.$parent.$watch(b(j[a]),function(b){h[a]=b}),r.attr(l(a),a))}),j.dateDisabled&&r.attr("date-disabled","dateDisabled({ date: date, mode: mode })"),k.$parsers.unshift(m),h.dateSelection=function(a){angular.isDefined(a)&&(h.date=a),k.$setViewValue(h.date),k.$render(),o&&(h.isOpen=!1,i[0].focus())},i.bind("input change keyup",function(){h.$apply(function(){h.date=k.$modelValue})}),k.$render=function(){var a=k.$viewValue?e(k.$viewValue,n):"";i.val(a),h.date=m(k.$modelValue)};var s=function(a){h.isOpen&&a.target!==i[0]&&h.$apply(function(){h.isOpen=!1})},t=function(a){h.keydown(a)};i.bind("keydown",t),h.keydown=function(a){27===a.which?(a.preventDefault(),a.stopPropagation(),h.close()):40!==a.which||h.isOpen||(h.isOpen=!0)},h.$watch("isOpen",function(a){a?(h.$broadcast("datepicker.focus"),h.position=p?d.offset(i):d.position(i),h.position.top=h.position.top+i.prop("offsetHeight"),c.bind("click",s)):c.unbind("click",s)}),h.select=function(a){if("today"===a){var b=new Date;angular.isDate(k.$modelValue)?(a=new Date(k.$modelValue),a.setFullYear(b.getFullYear(),b.getMonth(),b.getDate())):a=new Date(b.setHours(0,0,0,0))}h.dateSelection(a)},h.close=function(){h.isOpen=!1,i[0].focus()};var u=a(q)(h);p?c.find("body").append(u):i.after(u),h.$on("$destroy",function(){u.remove(),i.unbind("keydown",t),c.unbind("click",s)})}}}]).directive("datepickerPopupWrap",function(){return{restrict:"EA",replace:!0,transclude:!0,templateUrl:"template/datepicker/popup.html",link:function(a,b){b.bind("click",function(a){a.preventDefault(),a.stopPropagation()})}}}),angular.module("ui.bootstrap.dropdown",[]).constant("dropdownConfig",{openClass:"open"}).service("dropdownService",["$document",function(a){var b=null;this.open=function(e){b||(a.bind("click",c),a.bind("keydown",d)),b&&b!==e&&(b.isOpen=!1),b=e},this.close=function(e){b===e&&(b=null,a.unbind("click",c),a.unbind("keydown",d))};var c=function(a){a&&a.isDefaultPrevented()||b.$apply(function(){b.isOpen=!1})},d=function(a){27===a.which&&(b.focusToggleElement(),c())}}]).controller("DropdownController",["$scope","$attrs","$parse","dropdownConfig","dropdownService","$animate",function(a,b,c,d,e,f){var g,h=this,i=a.$new(),j=d.openClass,k=angular.noop,l=b.onToggle?c(b.onToggle):angular.noop;this.init=function(d){h.$element=d,b.isOpen&&(g=c(b.isOpen),k=g.assign,a.$watch(g,function(a){i.isOpen=!!a}))},this.toggle=function(a){return i.isOpen=arguments.length?!!a:!i.isOpen},this.isOpen=function(){return i.isOpen},i.focusToggleElement=function(){h.toggleElement&&h.toggleElement[0].focus()},i.$watch("isOpen",function(b,c){f[b?"addClass":"removeClass"](h.$element,j),b?(i.focusToggleElement(),e.open(i)):e.close(i),k(a,b),angular.isDefined(b)&&b!==c&&l(a,{open:!!b})}),a.$on("$locationChangeSuccess",function(){i.isOpen=!1}),a.$on("$destroy",function(){i.$destroy()})}]).directive("dropdown",function(){return{restrict:"CA",controller:"DropdownController",link:function(a,b,c,d){d.init(b)}}}).directive("dropdownToggle",function(){return{restrict:"CA",require:"?^dropdown",link:function(a,b,c,d){if(d){d.toggleElement=b;var e=function(e){e.preventDefault(),b.hasClass("disabled")||c.disabled||a.$apply(function(){d.toggle()})};b.bind("click",e),b.attr({"aria-haspopup":!0,"aria-expanded":!1}),a.$watch(d.isOpen,function(a){b.attr("aria-expanded",!!a)}),a.$on("$destroy",function(){b.unbind("click",e)})}}}}),angular.module("ui.bootstrap.modal",["ui.bootstrap.transition"]).factory("$$stackedMap",function(){return{createNew:function(){var a=[];return{add:function(b,c){a.push({key:b,value:c})},get:function(b){for(var c=0;c0),i()})}function i(){if(k&&-1==g()){var a=l;j(k,l,150,function(){a.$destroy(),a=null}),k=void 0,l=void 0}}function j(c,d,e,f){function g(){g.done||(g.done=!0,c.remove(),f&&f())}d.animate=!1;var h=a.transitionEndEventName;if(h){var i=b(g,e);c.bind(h,function(){b.cancel(i),g(),d.$apply()})}else b(g,0)}var k,l,m="modal-open",n=f.createNew(),o={};return e.$watch(g,function(a){l&&(l.index=a)}),c.bind("keydown",function(a){var b;27===a.which&&(b=n.top(),b&&b.value.keyboard&&(a.preventDefault(),e.$apply(function(){o.dismiss(b.key,"escape key press")})))}),o.open=function(a,b){n.add(a,{deferred:b.deferred,modalScope:b.scope,backdrop:b.backdrop,keyboard:b.keyboard});var f=c.find("body").eq(0),h=g();h>=0&&!k&&(l=e.$new(!0),l.index=h,k=d("
")(l),f.append(k));var i=angular.element("
");i.attr({"template-url":b.windowTemplateUrl,"window-class":b.windowClass,size:b.size,index:n.length()-1,animate:"animate"}).html(b.content);var j=d(i)(b.scope);n.top().value.modalDomEl=j,f.append(j),f.addClass(m)},o.close=function(a,b){var c=n.get(a).value;c&&(c.deferred.resolve(b),h(a))},o.dismiss=function(a,b){var c=n.get(a).value;c&&(c.deferred.reject(b),h(a))},o.dismissAll=function(a){for(var b=this.getTop();b;)this.dismiss(b.key,a),b=this.getTop()},o.getTop=function(){return n.top()},o}]).provider("$modal",function(){var a={options:{backdrop:!0,keyboard:!0},$get:["$injector","$rootScope","$q","$http","$templateCache","$controller","$modalStack",function(b,c,d,e,f,g,h){function i(a){return a.template?d.when(a.template):e.get(a.templateUrl,{cache:f}).then(function(a){return a.data})}function j(a){var c=[];return angular.forEach(a,function(a){(angular.isFunction(a)||angular.isArray(a))&&c.push(d.when(b.invoke(a)))}),c}var k={};return k.open=function(b){var e=d.defer(),f=d.defer(),k={result:e.promise,opened:f.promise,close:function(a){h.close(k,a)},dismiss:function(a){h.dismiss(k,a)}};if(b=angular.extend({},a.options,b),b.resolve=b.resolve||{},!b.template&&!b.templateUrl)throw new Error("One of template or templateUrl options is required.");var l=d.all([i(b)].concat(j(b.resolve)));return l.then(function(a){var d=(b.scope||c).$new();d.$close=k.close,d.$dismiss=k.dismiss;var f,i={},j=1;b.controller&&(i.$scope=d,i.$modalInstance=k,angular.forEach(b.resolve,function(b,c){i[c]=a[j++]}),f=g(b.controller,i)),h.open(k,{scope:d,deferred:e,content:a[0],backdrop:b.backdrop,keyboard:b.keyboard,windowClass:b.windowClass,windowTemplateUrl:b.windowTemplateUrl,size:b.size})},function(a){e.reject(a)}),l.then(function(){f.resolve(!0)},function(){f.reject(!1)}),k},k}]};return a}),angular.module("ui.bootstrap.pagination",[]).controller("PaginationController",["$scope","$attrs","$parse",function(a,b,c){var d=this,e={$setViewValue:angular.noop},f=b.numPages?c(b.numPages).assign:angular.noop;this.init=function(f,g){e=f,this.config=g,e.$render=function(){d.render()},b.itemsPerPage?a.$parent.$watch(c(b.itemsPerPage),function(b){d.itemsPerPage=parseInt(b,10),a.totalPages=d.calculateTotalPages()}):this.itemsPerPage=g.itemsPerPage},this.calculateTotalPages=function(){var b=this.itemsPerPage<1?1:Math.ceil(a.totalItems/this.itemsPerPage);return Math.max(b||0,1)},this.render=function(){a.page=parseInt(e.$viewValue,10)||1},a.selectPage=function(b){a.page!==b&&b>0&&b<=a.totalPages&&(e.$setViewValue(b),e.$render())},a.getText=function(b){return a[b+"Text"]||d.config[b+"Text"]},a.noPrevious=function(){return 1===a.page},a.noNext=function(){return a.page===a.totalPages},a.$watch("totalItems",function(){a.totalPages=d.calculateTotalPages()}),a.$watch("totalPages",function(b){f(a.$parent,b),a.page>b?a.selectPage(b):e.$render()})}]).constant("paginationConfig",{itemsPerPage:10,boundaryLinks:!1,directionLinks:!0,firstText:"First",previousText:"Previous",nextText:"Next",lastText:"Last",rotate:!0}).directive("pagination",["$parse","paginationConfig",function(a,b){return{restrict:"EA",scope:{totalItems:"=",firstText:"@",previousText:"@",nextText:"@",lastText:"@"},require:["pagination","?ngModel"],controller:"PaginationController",templateUrl:"template/pagination/pagination.html",replace:!0,link:function(c,d,e,f){function g(a,b,c){return{number:a,text:b,active:c}}function h(a,b){var c=[],d=1,e=b,f=angular.isDefined(k)&&b>k;f&&(l?(d=Math.max(a-Math.floor(k/2),1),e=d+k-1,e>b&&(e=b,d=e-k+1)):(d=(Math.ceil(a/k)-1)*k+1,e=Math.min(d+k-1,b)));for(var h=d;e>=h;h++){var i=g(h,h,h===a);c.push(i)}if(f&&!l){if(d>1){var j=g(d-1,"...",!1);c.unshift(j)}if(b>e){var m=g(e+1,"...",!1);c.push(m)}}return c}var i=f[0],j=f[1];if(j){var k=angular.isDefined(e.maxSize)?c.$parent.$eval(e.maxSize):b.maxSize,l=angular.isDefined(e.rotate)?c.$parent.$eval(e.rotate):b.rotate;c.boundaryLinks=angular.isDefined(e.boundaryLinks)?c.$parent.$eval(e.boundaryLinks):b.boundaryLinks,c.directionLinks=angular.isDefined(e.directionLinks)?c.$parent.$eval(e.directionLinks):b.directionLinks,i.init(j,b),e.maxSize&&c.$parent.$watch(a(e.maxSize),function(a){k=parseInt(a,10),i.render()});var m=i.render;i.render=function(){m(),c.page>0&&c.page<=c.totalPages&&(c.pages=h(c.page,c.totalPages))}}}}}]).constant("pagerConfig",{itemsPerPage:10,previousText:"« Previous",nextText:"Next »",align:!0}).directive("pager",["pagerConfig",function(a){return{restrict:"EA",scope:{totalItems:"=",previousText:"@",nextText:"@"},require:["pager","?ngModel"],controller:"PaginationController",templateUrl:"template/pagination/pager.html",replace:!0,link:function(b,c,d,e){var f=e[0],g=e[1];g&&(b.align=angular.isDefined(d.align)?b.$parent.$eval(d.align):a.align,f.init(g,a))}}}]),angular.module("ui.bootstrap.tooltip",["ui.bootstrap.position","ui.bootstrap.bindHtml"]).provider("$tooltip",function(){function a(a){var b=/[A-Z]/g,c="-"; -return a.replace(b,function(a,b){return(b?c:"")+a.toLowerCase()})}var b={placement:"top",animation:!0,popupDelay:0},c={mouseenter:"mouseleave",click:"click",focus:"blur"},d={};this.options=function(a){angular.extend(d,a)},this.setTriggers=function(a){angular.extend(c,a)},this.$get=["$window","$compile","$timeout","$parse","$document","$position","$interpolate",function(e,f,g,h,i,j,k){return function(e,l,m){function n(a){var b=a||o.trigger||m,d=c[b]||b;return{show:b,hide:d}}var o=angular.extend({},b,d),p=a(e),q=k.startSymbol(),r=k.endSymbol(),s="
';return{restrict:"EA",scope:!0,compile:function(){var a=f(s);return function(b,c,d){function f(){b.tt_isOpen?m():k()}function k(){(!y||b.$eval(d[l+"Enable"]))&&(b.tt_popupDelay?v||(v=g(p,b.tt_popupDelay,!1),v.then(function(a){a()})):p()())}function m(){b.$apply(function(){q()})}function p(){return v=null,u&&(g.cancel(u),u=null),b.tt_content?(r(),t.css({top:0,left:0,display:"block"}),w?i.find("body").append(t):c.after(t),z(),b.tt_isOpen=!0,b.$digest(),z):angular.noop}function q(){b.tt_isOpen=!1,g.cancel(v),v=null,b.tt_animation?u||(u=g(s,500)):s()}function r(){t&&s(),t=a(b,function(){}),b.$digest()}function s(){u=null,t&&(t.remove(),t=null)}var t,u,v,w=angular.isDefined(o.appendToBody)?o.appendToBody:!1,x=n(void 0),y=angular.isDefined(d[l+"Enable"]),z=function(){var a=j.positionElements(c,t,b.tt_placement,w);a.top+="px",a.left+="px",t.css(a)};b.tt_isOpen=!1,d.$observe(e,function(a){b.tt_content=a,!a&&b.tt_isOpen&&q()}),d.$observe(l+"Title",function(a){b.tt_title=a}),d.$observe(l+"Placement",function(a){b.tt_placement=angular.isDefined(a)?a:o.placement}),d.$observe(l+"PopupDelay",function(a){var c=parseInt(a,10);b.tt_popupDelay=isNaN(c)?o.popupDelay:c});var A=function(){c.unbind(x.show,k),c.unbind(x.hide,m)};d.$observe(l+"Trigger",function(a){A(),x=n(a),x.show===x.hide?c.bind(x.show,f):(c.bind(x.show,k),c.bind(x.hide,m))});var B=b.$eval(d[l+"Animation"]);b.tt_animation=angular.isDefined(B)?!!B:o.animation,d.$observe(l+"AppendToBody",function(a){w=angular.isDefined(a)?h(a)(b):w}),w&&b.$on("$locationChangeSuccess",function(){b.tt_isOpen&&q()}),b.$on("$destroy",function(){g.cancel(u),g.cancel(v),A(),s()})}}}}}]}).directive("tooltipPopup",function(){return{restrict:"EA",replace:!0,scope:{content:"@",placement:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-popup.html"}}).directive("tooltip",["$tooltip",function(a){return a("tooltip","tooltip","mouseenter")}]).directive("tooltipHtmlUnsafePopup",function(){return{restrict:"EA",replace:!0,scope:{content:"@",placement:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-html-unsafe-popup.html"}}).directive("tooltipHtmlUnsafe",["$tooltip",function(a){return a("tooltipHtmlUnsafe","tooltip","mouseenter")}]),angular.module("ui.bootstrap.popover",["ui.bootstrap.tooltip"]).directive("popoverPopup",function(){return{restrict:"EA",replace:!0,scope:{title:"@",content:"@",placement:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover.html"}}).directive("popover",["$tooltip",function(a){return a("popover","popover","click")}]),angular.module("ui.bootstrap.progressbar",[]).constant("progressConfig",{animate:!0,max:100}).controller("ProgressController",["$scope","$attrs","progressConfig",function(a,b,c){var d=this,e=angular.isDefined(b.animate)?a.$parent.$eval(b.animate):c.animate;this.bars=[],a.max=angular.isDefined(b.max)?a.$parent.$eval(b.max):c.max,this.addBar=function(b,c){e||c.css({transition:"none"}),this.bars.push(b),b.$watch("value",function(c){b.percent=+(100*c/a.max).toFixed(2)}),b.$on("$destroy",function(){c=null,d.removeBar(b)})},this.removeBar=function(a){this.bars.splice(this.bars.indexOf(a),1)}}]).directive("progress",function(){return{restrict:"EA",replace:!0,transclude:!0,controller:"ProgressController",require:"progress",scope:{},templateUrl:"template/progressbar/progress.html"}}).directive("bar",function(){return{restrict:"EA",replace:!0,transclude:!0,require:"^progress",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/bar.html",link:function(a,b,c,d){d.addBar(a,b)}}}).directive("progressbar",function(){return{restrict:"EA",replace:!0,transclude:!0,controller:"ProgressController",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/progressbar.html",link:function(a,b,c,d){d.addBar(a,angular.element(b.children()[0]))}}}),angular.module("ui.bootstrap.rating",[]).constant("ratingConfig",{max:5,stateOn:null,stateOff:null}).controller("RatingController",["$scope","$attrs","ratingConfig",function(a,b,c){var d={$setViewValue:angular.noop};this.init=function(e){d=e,d.$render=this.render,this.stateOn=angular.isDefined(b.stateOn)?a.$parent.$eval(b.stateOn):c.stateOn,this.stateOff=angular.isDefined(b.stateOff)?a.$parent.$eval(b.stateOff):c.stateOff;var f=angular.isDefined(b.ratingStates)?a.$parent.$eval(b.ratingStates):new Array(angular.isDefined(b.max)?a.$parent.$eval(b.max):c.max);a.range=this.buildTemplateObjects(f)},this.buildTemplateObjects=function(a){for(var b=0,c=a.length;c>b;b++)a[b]=angular.extend({index:b},{stateOn:this.stateOn,stateOff:this.stateOff},a[b]);return a},a.rate=function(b){!a.readonly&&b>=0&&b<=a.range.length&&(d.$setViewValue(b),d.$render())},a.enter=function(b){a.readonly||(a.value=b),a.onHover({value:b})},a.reset=function(){a.value=d.$viewValue,a.onLeave()},a.onKeydown=function(b){/(37|38|39|40)/.test(b.which)&&(b.preventDefault(),b.stopPropagation(),a.rate(a.value+(38===b.which||39===b.which?1:-1)))},this.render=function(){a.value=d.$viewValue}}]).directive("rating",function(){return{restrict:"EA",require:["rating","ngModel"],scope:{readonly:"=?",onHover:"&",onLeave:"&"},controller:"RatingController",templateUrl:"template/rating/rating.html",replace:!0,link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f)}}}),angular.module("ui.bootstrap.tabs",[]).controller("TabsetController",["$scope",function(a){var b=this,c=b.tabs=a.tabs=[];b.select=function(a){angular.forEach(c,function(b){b.active&&b!==a&&(b.active=!1,b.onDeselect())}),a.active=!0,a.onSelect()},b.addTab=function(a){c.push(a),1===c.length?a.active=!0:a.active&&b.select(a)},b.removeTab=function(a){var d=c.indexOf(a);if(a.active&&c.length>1){var e=d==c.length-1?d-1:d+1;b.select(c[e])}c.splice(d,1)}}]).directive("tabset",function(){return{restrict:"EA",transclude:!0,replace:!0,scope:{type:"@"},controller:"TabsetController",templateUrl:"template/tabs/tabset.html",link:function(a,b,c){a.vertical=angular.isDefined(c.vertical)?a.$parent.$eval(c.vertical):!1,a.justified=angular.isDefined(c.justified)?a.$parent.$eval(c.justified):!1}}}).directive("tab",["$parse",function(a){return{require:"^tabset",restrict:"EA",replace:!0,templateUrl:"template/tabs/tab.html",transclude:!0,scope:{active:"=?",heading:"@",onSelect:"&select",onDeselect:"&deselect"},controller:function(){},compile:function(b,c,d){return function(b,c,e,f){b.$watch("active",function(a){a&&f.select(b)}),b.disabled=!1,e.disabled&&b.$parent.$watch(a(e.disabled),function(a){b.disabled=!!a}),b.select=function(){b.disabled||(b.active=!0)},f.addTab(b),b.$on("$destroy",function(){f.removeTab(b)}),b.$transcludeFn=d}}}}]).directive("tabHeadingTransclude",[function(){return{restrict:"A",require:"^tab",link:function(a,b){a.$watch("headingElement",function(a){a&&(b.html(""),b.append(a))})}}}]).directive("tabContentTransclude",function(){function a(a){return a.tagName&&(a.hasAttribute("tab-heading")||a.hasAttribute("data-tab-heading")||"tab-heading"===a.tagName.toLowerCase()||"data-tab-heading"===a.tagName.toLowerCase())}return{restrict:"A",require:"^tabset",link:function(b,c,d){var e=b.$eval(d.tabContentTransclude);e.$transcludeFn(e.$parent,function(b){angular.forEach(b,function(b){a(b)?e.headingElement=b:c.append(b)})})}}}),angular.module("ui.bootstrap.timepicker",[]).constant("timepickerConfig",{hourStep:1,minuteStep:1,showMeridian:!0,meridians:null,readonlyInput:!1,mousewheel:!0}).controller("TimepickerController",["$scope","$attrs","$parse","$log","$locale","timepickerConfig",function(a,b,c,d,e,f){function g(){var b=parseInt(a.hours,10),c=a.showMeridian?b>0&&13>b:b>=0&&24>b;return c?(a.showMeridian&&(12===b&&(b=0),a.meridian===p[1]&&(b+=12)),b):void 0}function h(){var b=parseInt(a.minutes,10);return b>=0&&60>b?b:void 0}function i(a){return angular.isDefined(a)&&a.toString().length<2?"0"+a:a}function j(a){k(),o.$setViewValue(new Date(n)),l(a)}function k(){o.$setValidity("time",!0),a.invalidHours=!1,a.invalidMinutes=!1}function l(b){var c=n.getHours(),d=n.getMinutes();a.showMeridian&&(c=0===c||12===c?12:c%12),a.hours="h"===b?c:i(c),a.minutes="m"===b?d:i(d),a.meridian=n.getHours()<12?p[0]:p[1]}function m(a){var b=new Date(n.getTime()+6e4*a);n.setHours(b.getHours(),b.getMinutes()),j()}var n=new Date,o={$setViewValue:angular.noop},p=angular.isDefined(b.meridians)?a.$parent.$eval(b.meridians):f.meridians||e.DATETIME_FORMATS.AMPMS;this.init=function(c,d){o=c,o.$render=this.render;var e=d.eq(0),g=d.eq(1),h=angular.isDefined(b.mousewheel)?a.$parent.$eval(b.mousewheel):f.mousewheel;h&&this.setupMousewheelEvents(e,g),a.readonlyInput=angular.isDefined(b.readonlyInput)?a.$parent.$eval(b.readonlyInput):f.readonlyInput,this.setupInputEvents(e,g)};var q=f.hourStep;b.hourStep&&a.$parent.$watch(c(b.hourStep),function(a){q=parseInt(a,10)});var r=f.minuteStep;b.minuteStep&&a.$parent.$watch(c(b.minuteStep),function(a){r=parseInt(a,10)}),a.showMeridian=f.showMeridian,b.showMeridian&&a.$parent.$watch(c(b.showMeridian),function(b){if(a.showMeridian=!!b,o.$error.time){var c=g(),d=h();angular.isDefined(c)&&angular.isDefined(d)&&(n.setHours(c),j())}else l()}),this.setupMousewheelEvents=function(b,c){var d=function(a){a.originalEvent&&(a=a.originalEvent);var b=a.wheelDelta?a.wheelDelta:-a.deltaY;return a.detail||b>0};b.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementHours():a.decrementHours()),b.preventDefault()}),c.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementMinutes():a.decrementMinutes()),b.preventDefault()})},this.setupInputEvents=function(b,c){if(a.readonlyInput)return a.updateHours=angular.noop,void(a.updateMinutes=angular.noop);var d=function(b,c){o.$setViewValue(null),o.$setValidity("time",!1),angular.isDefined(b)&&(a.invalidHours=b),angular.isDefined(c)&&(a.invalidMinutes=c)};a.updateHours=function(){var a=g();angular.isDefined(a)?(n.setHours(a),j("h")):d(!0)},b.bind("blur",function(){!a.invalidHours&&a.hours<10&&a.$apply(function(){a.hours=i(a.hours)})}),a.updateMinutes=function(){var a=h();angular.isDefined(a)?(n.setMinutes(a),j("m")):d(void 0,!0)},c.bind("blur",function(){!a.invalidMinutes&&a.minutes<10&&a.$apply(function(){a.minutes=i(a.minutes)})})},this.render=function(){var a=o.$modelValue?new Date(o.$modelValue):null;isNaN(a)?(o.$setValidity("time",!1),d.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')):(a&&(n=a),k(),l())},a.incrementHours=function(){m(60*q)},a.decrementHours=function(){m(60*-q)},a.incrementMinutes=function(){m(r)},a.decrementMinutes=function(){m(-r)},a.toggleMeridian=function(){m(720*(n.getHours()<12?1:-1))}}]).directive("timepicker",function(){return{restrict:"EA",require:["timepicker","?^ngModel"],controller:"TimepickerController",replace:!0,scope:{},templateUrl:"template/timepicker/timepicker.html",link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f,b.find("input"))}}}),angular.module("ui.bootstrap.typeahead",["ui.bootstrap.position","ui.bootstrap.bindHtml"]).factory("typeaheadParser",["$parse",function(a){var b=/^\s*(.*?)(?:\s+as\s+(.*?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+(.*)$/;return{parse:function(c){var d=c.match(b);if(!d)throw new Error('Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_" but got "'+c+'".');return{itemName:d[3],source:a(d[4]),viewMapper:a(d[2]||d[1]),modelMapper:a(d[1])}}}}]).directive("typeahead",["$compile","$parse","$q","$timeout","$document","$position","typeaheadParser",function(a,b,c,d,e,f,g){var h=[9,13,27,38,40];return{require:"ngModel",link:function(i,j,k,l){var m,n=i.$eval(k.typeaheadMinLength)||1,o=i.$eval(k.typeaheadWaitMs)||0,p=i.$eval(k.typeaheadEditable)!==!1,q=b(k.typeaheadLoading).assign||angular.noop,r=b(k.typeaheadOnSelect),s=k.typeaheadInputFormatter?b(k.typeaheadInputFormatter):void 0,t=k.typeaheadAppendToBody?i.$eval(k.typeaheadAppendToBody):!1,u=b(k.ngModel).assign,v=g.parse(k.typeahead),w=i.$new();i.$on("$destroy",function(){w.$destroy()});var x="typeahead-"+w.$id+"-"+Math.floor(1e4*Math.random());j.attr({"aria-autocomplete":"list","aria-expanded":!1,"aria-owns":x});var y=angular.element("
");y.attr({id:x,matches:"matches",active:"activeIdx",select:"select(activeIdx)",query:"query",position:"position"}),angular.isDefined(k.typeaheadTemplateUrl)&&y.attr("template-url",k.typeaheadTemplateUrl);var z=function(){w.matches=[],w.activeIdx=-1,j.attr("aria-expanded",!1)},A=function(a){return x+"-option-"+a};w.$watch("activeIdx",function(a){0>a?j.removeAttr("aria-activedescendant"):j.attr("aria-activedescendant",A(a))});var B=function(a){var b={$viewValue:a};q(i,!0),c.when(v.source(i,b)).then(function(c){var d=a===l.$viewValue;if(d&&m)if(c.length>0){w.activeIdx=0,w.matches.length=0;for(var e=0;e=n?o>0?(C&&d.cancel(C),C=d(function(){B(a)},o)):B(a):(q(i,!1),z()),p?a:a?void l.$setValidity("editable",!1):(l.$setValidity("editable",!0),a)}),l.$formatters.push(function(a){var b,c,d={};return s?(d.$model=a,s(i,d)):(d[v.itemName]=a,b=v.viewMapper(i,d),d[v.itemName]=void 0,c=v.viewMapper(i,d),b!==c?b:a)}),w.select=function(a){var b,c,e={};e[v.itemName]=c=w.matches[a].model,b=v.modelMapper(i,e),u(i,b),l.$setValidity("editable",!0),r(i,{$item:c,$model:b,$label:v.viewMapper(i,e)}),z(),d(function(){j[0].focus()},0,!1)},j.bind("keydown",function(a){0!==w.matches.length&&-1!==h.indexOf(a.which)&&(a.preventDefault(),40===a.which?(w.activeIdx=(w.activeIdx+1)%w.matches.length,w.$digest()):38===a.which?(w.activeIdx=(w.activeIdx?w.activeIdx:w.matches.length)-1,w.$digest()):13===a.which||9===a.which?w.$apply(function(){w.select(w.activeIdx)}):27===a.which&&(a.stopPropagation(),z(),w.$digest()))}),j.bind("blur",function(){m=!1});var D=function(a){j[0]!==a.target&&(z(),w.$digest())};e.bind("click",D),i.$on("$destroy",function(){e.unbind("click",D)});var E=a(y)(w);t?e.find("body").append(E):j.after(E)}}}]).directive("typeaheadPopup",function(){return{restrict:"EA",scope:{matches:"=",query:"=",active:"=",position:"=",select:"&"},replace:!0,templateUrl:"template/typeahead/typeahead-popup.html",link:function(a,b,c){a.templateUrl=c.templateUrl,a.isOpen=function(){return a.matches.length>0},a.isActive=function(b){return a.active==b},a.selectActive=function(b){a.active=b},a.selectMatch=function(b){a.select({activeIdx:b})}}}}).directive("typeaheadMatch",["$http","$templateCache","$compile","$parse",function(a,b,c,d){return{restrict:"EA",scope:{index:"=",match:"=",query:"="},link:function(e,f,g){var h=d(g.templateUrl)(e.$parent)||"template/typeahead/typeahead-match.html";a.get(h,{cache:b}).success(function(a){f.replaceWith(c(a.trim())(e))})}}}]).filter("typeaheadHighlight",function(){function a(a){return a.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}return function(b,c){return c?(""+b).replace(new RegExp(a(c),"gi"),"$&"):b}}),angular.module("template/accordion/accordion-group.html",[]).run(["$templateCache",function(a){a.put("template/accordion/accordion-group.html",'
\n
\n

\n {{heading}}\n

\n
\n
\n
\n
\n
')}]),angular.module("template/accordion/accordion.html",[]).run(["$templateCache",function(a){a.put("template/accordion/accordion.html",'
')}]),angular.module("template/alert/alert.html",[]).run(["$templateCache",function(a){a.put("template/alert/alert.html",'\n')}]),angular.module("template/carousel/carousel.html",[]).run(["$templateCache",function(a){a.put("template/carousel/carousel.html",'\n')}]),angular.module("template/carousel/slide.html",[]).run(["$templateCache",function(a){a.put("template/carousel/slide.html","
\n")}]),angular.module("template/datepicker/datepicker.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/datepicker.html",'
\n \n \n \n
')}]),angular.module("template/datepicker/day.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/day.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
{{label.abbr}}
{{ weekNumbers[$index] }}\n \n
\n')}]),angular.module("template/datepicker/month.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/month.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n
\n')}]),angular.module("template/datepicker/popup.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/popup.html",'\n')}]),angular.module("template/datepicker/year.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/year.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n
\n')}]),angular.module("template/modal/backdrop.html",[]).run(["$templateCache",function(a){a.put("template/modal/backdrop.html",'\n')}]),angular.module("template/modal/window.html",[]).run(["$templateCache",function(a){a.put("template/modal/window.html",'')}]),angular.module("template/pagination/pager.html",[]).run(["$templateCache",function(a){a.put("template/pagination/pager.html",'')}]),angular.module("template/pagination/pagination.html",[]).run(["$templateCache",function(a){a.put("template/pagination/pagination.html",'')}]),angular.module("template/tooltip/tooltip-html-unsafe-popup.html",[]).run(["$templateCache",function(a){a.put("template/tooltip/tooltip-html-unsafe-popup.html",'
\n
\n
\n
\n')}]),angular.module("template/tooltip/tooltip-popup.html",[]).run(["$templateCache",function(a){a.put("template/tooltip/tooltip-popup.html",'
\n
\n
\n
\n')}]),angular.module("template/popover/popover.html",[]).run(["$templateCache",function(a){a.put("template/popover/popover.html",'
\n
\n\n
\n

\n
\n
\n
\n')}]),angular.module("template/progressbar/bar.html",[]).run(["$templateCache",function(a){a.put("template/progressbar/bar.html",'
')}]),angular.module("template/progressbar/progress.html",[]).run(["$templateCache",function(a){a.put("template/progressbar/progress.html",'
')}]),angular.module("template/progressbar/progressbar.html",[]).run(["$templateCache",function(a){a.put("template/progressbar/progressbar.html",'
\n
\n
')}]),angular.module("template/rating/rating.html",[]).run(["$templateCache",function(a){a.put("template/rating/rating.html",'\n \n ({{ $index < value ? \'*\' : \' \' }})\n \n')}]),angular.module("template/tabs/tab.html",[]).run(["$templateCache",function(a){a.put("template/tabs/tab.html",'
  • \n {{heading}}\n
  • \n')}]),angular.module("template/tabs/tabset-titles.html",[]).run(["$templateCache",function(a){a.put("template/tabs/tabset-titles.html","
      \n
    \n")}]),angular.module("template/tabs/tabset.html",[]).run(["$templateCache",function(a){a.put("template/tabs/tabset.html",'\n
    \n \n
    \n
    \n
    \n
    \n
    \n')}]),angular.module("template/timepicker/timepicker.html",[]).run(["$templateCache",function(a){a.put("template/timepicker/timepicker.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
     
    \n \n :\n \n
     
    \n')}]),angular.module("template/typeahead/typeahead-match.html",[]).run(["$templateCache",function(a){a.put("template/typeahead/typeahead-match.html",'')}]),angular.module("template/typeahead/typeahead-popup.html",[]).run(["$templateCache",function(a){a.put("template/typeahead/typeahead-popup.html",'') + return a.replace(b,function(a,b){return(b?c:"")+a.toLowerCase()})}var b={placement:"top",animation:!0,popupDelay:0},c={mouseenter:"mouseleave",click:"click",focus:"blur"},d={};this.options=function(a){angular.extend(d,a)},this.setTriggers=function(a){angular.extend(c,a)},this.$get=["$window","$compile","$timeout","$parse","$document","$position","$interpolate",function(e,f,g,h,i,j,k){return function(e,l,m){function n(a){var b=a||o.trigger||m,d=c[b]||b;return{show:b,hide:d}}var o=angular.extend({},b,d),p=a(e),q=k.startSymbol(),r=k.endSymbol(),s="
    ';return{restrict:"EA",scope:!0,compile:function(){var a=f(s);return function(b,c,d){function f(){b.tt_isOpen?m():k()}function k(){(!y||b.$eval(d[l+"Enable"]))&&(b.tt_popupDelay?v||(v=g(p,b.tt_popupDelay,!1),v.then(function(a){a()})):p()())}function m(){b.$apply(function(){q()})}function p(){return v=null,u&&(g.cancel(u),u=null),b.tt_content?(r(),t.css({top:0,left:0,display:"block"}),w?i.find("body").append(t):c.after(t),z(),b.tt_isOpen=!0,b.$digest(),z):angular.noop}function q(){b.tt_isOpen=!1,g.cancel(v),v=null,b.tt_animation?u||(u=g(s,500)):s()}function r(){t&&s(),t=a(b,function(){}),b.$digest()}function s(){u=null,t&&(t.remove(),t=null)}var t,u,v,w=angular.isDefined(o.appendToBody)?o.appendToBody:!1,x=n(void 0),y=angular.isDefined(d[l+"Enable"]),z=function(){var a=j.positionElements(c,t,b.tt_placement,w);a.top+="px",a.left+="px",t.css(a)};b.tt_isOpen=!1,d.$observe(e,function(a){b.tt_content=a,!a&&b.tt_isOpen&&q()}),d.$observe(l+"Title",function(a){b.tt_title=a}),d.$observe(l+"Placement",function(a){b.tt_placement=angular.isDefined(a)?a:o.placement}),d.$observe(l+"PopupDelay",function(a){var c=parseInt(a,10);b.tt_popupDelay=isNaN(c)?o.popupDelay:c});var A=function(){c.unbind(x.show,k),c.unbind(x.hide,m)};d.$observe(l+"Trigger",function(a){A(),x=n(a),x.show===x.hide?c.bind(x.show,f):(c.bind(x.show,k),c.bind(x.hide,m))});var B=b.$eval(d[l+"Animation"]);b.tt_animation=angular.isDefined(B)?!!B:o.animation,d.$observe(l+"AppendToBody",function(a){w=angular.isDefined(a)?h(a)(b):w}),w&&b.$on("$locationChangeSuccess",function(){b.tt_isOpen&&q()}),b.$on("$destroy",function(){g.cancel(u),g.cancel(v),A(),s()})}}}}}]}).directive("tooltipPopup",function(){return{restrict:"EA",replace:!0,scope:{content:"@",placement:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-popup.html"}}).directive("tooltip",["$tooltip",function(a){return a("tooltip","tooltip","mouseenter")}]).directive("tooltipHtmlUnsafePopup",function(){return{restrict:"EA",replace:!0,scope:{content:"@",placement:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-html-unsafe-popup.html"}}).directive("tooltipHtmlUnsafe",["$tooltip",function(a){return a("tooltipHtmlUnsafe","tooltip","mouseenter")}]),angular.module("ui.bootstrap.popover",["ui.bootstrap.tooltip"]).directive("popoverPopup",function(){return{restrict:"EA",replace:!0,scope:{title:"@",content:"@",placement:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover.html"}}).directive("popover",["$tooltip",function(a){return a("popover","popover","click")}]),angular.module("ui.bootstrap.progressbar",[]).constant("progressConfig",{animate:!0,max:100}).controller("ProgressController",["$scope","$attrs","progressConfig",function(a,b,c){var d=this,e=angular.isDefined(b.animate)?a.$parent.$eval(b.animate):c.animate;this.bars=[],a.max=angular.isDefined(b.max)?a.$parent.$eval(b.max):c.max,this.addBar=function(b,c){e||c.css({transition:"none"}),this.bars.push(b),b.$watch("value",function(c){b.percent=+(100*c/a.max).toFixed(2)}),b.$on("$destroy",function(){c=null,d.removeBar(b)})},this.removeBar=function(a){this.bars.splice(this.bars.indexOf(a),1)}}]).directive("progress",function(){return{restrict:"EA",replace:!0,transclude:!0,controller:"ProgressController",require:"progress",scope:{},templateUrl:"template/progressbar/progress.html"}}).directive("bar",function(){return{restrict:"EA",replace:!0,transclude:!0,require:"^progress",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/bar.html",link:function(a,b,c,d){d.addBar(a,b)}}}).directive("progressbar",function(){return{restrict:"EA",replace:!0,transclude:!0,controller:"ProgressController",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/progressbar.html",link:function(a,b,c,d){d.addBar(a,angular.element(b.children()[0]))}}}),angular.module("ui.bootstrap.rating",[]).constant("ratingConfig",{max:5,stateOn:null,stateOff:null}).controller("RatingController",["$scope","$attrs","ratingConfig",function(a,b,c){var d={$setViewValue:angular.noop};this.init=function(e){d=e,d.$render=this.render,this.stateOn=angular.isDefined(b.stateOn)?a.$parent.$eval(b.stateOn):c.stateOn,this.stateOff=angular.isDefined(b.stateOff)?a.$parent.$eval(b.stateOff):c.stateOff;var f=angular.isDefined(b.ratingStates)?a.$parent.$eval(b.ratingStates):new Array(angular.isDefined(b.max)?a.$parent.$eval(b.max):c.max);a.range=this.buildTemplateObjects(f)},this.buildTemplateObjects=function(a){for(var b=0,c=a.length;c>b;b++)a[b]=angular.extend({index:b},{stateOn:this.stateOn,stateOff:this.stateOff},a[b]);return a},a.rate=function(b){!a.readonly&&b>=0&&b<=a.range.length&&(d.$setViewValue(b),d.$render())},a.enter=function(b){a.readonly||(a.value=b),a.onHover({value:b})},a.reset=function(){a.value=d.$viewValue,a.onLeave()},a.onKeydown=function(b){/(37|38|39|40)/.test(b.which)&&(b.preventDefault(),b.stopPropagation(),a.rate(a.value+(38===b.which||39===b.which?1:-1)))},this.render=function(){a.value=d.$viewValue}}]).directive("rating",function(){return{restrict:"EA",require:["rating","ngModel"],scope:{readonly:"=?",onHover:"&",onLeave:"&"},controller:"RatingController",templateUrl:"template/rating/rating.html",replace:!0,link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f)}}}),angular.module("ui.bootstrap.tabs",[]).controller("TabsetController",["$scope",function(a){var b=this,c=b.tabs=a.tabs=[];b.select=function(a){angular.forEach(c,function(b){b.active&&b!==a&&(b.active=!1,b.onDeselect())}),a.active=!0,a.onSelect()},b.addTab=function(a){c.push(a),1===c.length?a.active=!0:a.active&&b.select(a)},b.removeTab=function(a){var d=c.indexOf(a);if(a.active&&c.length>1){var e=d==c.length-1?d-1:d+1;b.select(c[e])}c.splice(d,1)}}]).directive("tabset",function(){return{restrict:"EA",transclude:!0,replace:!0,scope:{type:"@"},controller:"TabsetController",templateUrl:"template/tabs/tabset.html",link:function(a,b,c){a.vertical=angular.isDefined(c.vertical)?a.$parent.$eval(c.vertical):!1,a.justified=angular.isDefined(c.justified)?a.$parent.$eval(c.justified):!1}}}).directive("tab",["$parse",function(a){return{require:"^tabset",restrict:"EA",replace:!0,templateUrl:"template/tabs/tab.html",transclude:!0,scope:{active:"=?",heading:"@",onSelect:"&select",onDeselect:"&deselect"},controller:function(){},compile:function(b,c,d){return function(b,c,e,f){b.$watch("active",function(a){a&&f.select(b)}),b.disabled=!1,e.disabled&&b.$parent.$watch(a(e.disabled),function(a){b.disabled=!!a}),b.select=function(){b.disabled||(b.active=!0)},f.addTab(b),b.$on("$destroy",function(){f.removeTab(b)}),b.$transcludeFn=d}}}}]).directive("tabHeadingTransclude",[function(){return{restrict:"A",require:"^tab",link:function(a,b){a.$watch("headingElement",function(a){a&&(b.html(""),b.append(a))})}}}]).directive("tabContentTransclude",function(){function a(a){return a.tagName&&(a.hasAttribute("tab-heading")||a.hasAttribute("data-tab-heading")||"tab-heading"===a.tagName.toLowerCase()||"data-tab-heading"===a.tagName.toLowerCase())}return{restrict:"A",require:"^tabset",link:function(b,c,d){var e=b.$eval(d.tabContentTransclude);e.$transcludeFn(e.$parent,function(b){angular.forEach(b,function(b){a(b)?e.headingElement=b:c.append(b)})})}}}),angular.module("ui.bootstrap.timepicker",[]).constant("timepickerConfig",{hourStep:1,minuteStep:1,showMeridian:!0,meridians:null,readonlyInput:!1,mousewheel:!0}).controller("TimepickerController",["$scope","$attrs","$parse","$log","$locale","timepickerConfig",function(a,b,c,d,e,f){function g(){var b=parseInt(a.hours,10),c=a.showMeridian?b>0&&13>b:b>=0&&24>b;return c?(a.showMeridian&&(12===b&&(b=0),a.meridian===p[1]&&(b+=12)),b):void 0}function h(){var b=parseInt(a.minutes,10);return b>=0&&60>b?b:void 0}function i(a){return angular.isDefined(a)&&a.toString().length<2?"0"+a:a}function j(a){k(),o.$setViewValue(new Date(n)),l(a)}function k(){o.$setValidity("time",!0),a.invalidHours=!1,a.invalidMinutes=!1}function l(b){var c=n.getHours(),d=n.getMinutes();a.showMeridian&&(c=0===c||12===c?12:c%12),a.hours="h"===b?c:i(c),a.minutes="m"===b?d:i(d),a.meridian=n.getHours()<12?p[0]:p[1]}function m(a){var b=new Date(n.getTime()+6e4*a);n.setHours(b.getHours(),b.getMinutes()),j()}var n=new Date,o={$setViewValue:angular.noop},p=angular.isDefined(b.meridians)?a.$parent.$eval(b.meridians):f.meridians||e.DATETIME_FORMATS.AMPMS;this.init=function(c,d){o=c,o.$render=this.render;var e=d.eq(0),g=d.eq(1),h=angular.isDefined(b.mousewheel)?a.$parent.$eval(b.mousewheel):f.mousewheel;h&&this.setupMousewheelEvents(e,g),a.readonlyInput=angular.isDefined(b.readonlyInput)?a.$parent.$eval(b.readonlyInput):f.readonlyInput,this.setupInputEvents(e,g)};var q=f.hourStep;b.hourStep&&a.$parent.$watch(c(b.hourStep),function(a){q=parseInt(a,10)});var r=f.minuteStep;b.minuteStep&&a.$parent.$watch(c(b.minuteStep),function(a){r=parseInt(a,10)}),a.showMeridian=f.showMeridian,b.showMeridian&&a.$parent.$watch(c(b.showMeridian),function(b){if(a.showMeridian=!!b,o.$error.time){var c=g(),d=h();angular.isDefined(c)&&angular.isDefined(d)&&(n.setHours(c),j())}else l()}),this.setupMousewheelEvents=function(b,c){var d=function(a){a.originalEvent&&(a=a.originalEvent);var b=a.wheelDelta?a.wheelDelta:-a.deltaY;return a.detail||b>0};b.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementHours():a.decrementHours()),b.preventDefault()}),c.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementMinutes():a.decrementMinutes()),b.preventDefault()})},this.setupInputEvents=function(b,c){if(a.readonlyInput)return a.updateHours=angular.noop,void(a.updateMinutes=angular.noop);var d=function(b,c){o.$setViewValue(null),o.$setValidity("time",!1),angular.isDefined(b)&&(a.invalidHours=b),angular.isDefined(c)&&(a.invalidMinutes=c)};a.updateHours=function(){var a=g();angular.isDefined(a)?(n.setHours(a),j("h")):d(!0)},b.bind("blur",function(){!a.invalidHours&&a.hours<10&&a.$apply(function(){a.hours=i(a.hours)})}),a.updateMinutes=function(){var a=h();angular.isDefined(a)?(n.setMinutes(a),j("m")):d(void 0,!0)},c.bind("blur",function(){!a.invalidMinutes&&a.minutes<10&&a.$apply(function(){a.minutes=i(a.minutes)})})},this.render=function(){var a=o.$modelValue?new Date(o.$modelValue):null;isNaN(a)?(o.$setValidity("time",!1),d.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')):(a&&(n=a),k(),l())},a.incrementHours=function(){m(60*q)},a.decrementHours=function(){m(60*-q)},a.incrementMinutes=function(){m(r)},a.decrementMinutes=function(){m(-r)},a.toggleMeridian=function(){m(720*(n.getHours()<12?1:-1))}}]).directive("timepicker",function(){return{restrict:"EA",require:["timepicker","?^ngModel"],controller:"TimepickerController",replace:!0,scope:{},templateUrl:"template/timepicker/timepicker.html",link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f,b.find("input"))}}}),angular.module("ui.bootstrap.typeahead",["ui.bootstrap.position","ui.bootstrap.bindHtml"]).factory("typeaheadParser",["$parse",function(a){var b=/^\s*(.*?)(?:\s+as\s+(.*?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+(.*)$/;return{parse:function(c){var d=c.match(b);if(!d)throw new Error('Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_" but got "'+c+'".');return{itemName:d[3],source:a(d[4]),viewMapper:a(d[2]||d[1]),modelMapper:a(d[1])}}}}]).directive("typeahead",["$compile","$parse","$q","$timeout","$document","$position","typeaheadParser",function(a,b,c,d,e,f,g){var h=[9,13,27,38,40];return{require:"ngModel",link:function(i,j,k,l){var m,n=i.$eval(k.typeaheadMinLength)||1,o=i.$eval(k.typeaheadWaitMs)||0,p=i.$eval(k.typeaheadEditable)!==!1,q=b(k.typeaheadLoading).assign||angular.noop,r=b(k.typeaheadOnSelect),s=k.typeaheadInputFormatter?b(k.typeaheadInputFormatter):void 0,t=k.typeaheadAppendToBody?i.$eval(k.typeaheadAppendToBody):!1,u=b(k.ngModel).assign,v=g.parse(k.typeahead),w=i.$new();i.$on("$destroy",function(){w.$destroy()});var x="typeahead-"+w.$id+"-"+Math.floor(1e4*Math.random());j.attr({"aria-autocomplete":"list","aria-expanded":!1,"aria-owns":x});var y=angular.element("
    ");y.attr({id:x,matches:"matches",active:"activeIdx",select:"select(activeIdx)",query:"query",position:"position"}),angular.isDefined(k.typeaheadTemplateUrl)&&y.attr("template-url",k.typeaheadTemplateUrl);var z=function(){w.matches=[],w.activeIdx=-1,j.attr("aria-expanded",!1)},A=function(a){return x+"-option-"+a};w.$watch("activeIdx",function(a){0>a?j.removeAttr("aria-activedescendant"):j.attr("aria-activedescendant",A(a))});var B=function(a){var b={$viewValue:a};q(i,!0),c.when(v.source(i,b)).then(function(c){var d=a===l.$viewValue;if(d&&m)if(c.length>0){w.activeIdx=0,w.matches.length=0;for(var e=0;e=n?o>0?(C&&d.cancel(C),C=d(function(){B(a)},o)):B(a):(q(i,!1),z()),p?a:a?void l.$setValidity("editable",!1):(l.$setValidity("editable",!0),a)}),l.$formatters.push(function(a){var b,c,d={};return s?(d.$model=a,s(i,d)):(d[v.itemName]=a,b=v.viewMapper(i,d),d[v.itemName]=void 0,c=v.viewMapper(i,d),b!==c?b:a)}),w.select=function(a){var b,c,e={};e[v.itemName]=c=w.matches[a].model,b=v.modelMapper(i,e),u(i,b),l.$setValidity("editable",!0),r(i,{$item:c,$model:b,$label:v.viewMapper(i,e)}),z(),d(function(){j[0].focus()},0,!1)},j.bind("keydown",function(a){0!==w.matches.length&&-1!==h.indexOf(a.which)&&(a.preventDefault(),40===a.which?(w.activeIdx=(w.activeIdx+1)%w.matches.length,w.$digest()):38===a.which?(w.activeIdx=(w.activeIdx?w.activeIdx:w.matches.length)-1,w.$digest()):13===a.which||9===a.which?w.$apply(function(){w.select(w.activeIdx)}):27===a.which&&(a.stopPropagation(),z(),w.$digest()))}),j.bind("blur",function(){m=!1});var D=function(a){j[0]!==a.target&&(z(),w.$digest())};e.bind("click",D),i.$on("$destroy",function(){e.unbind("click",D)});var E=a(y)(w);t?e.find("body").append(E):j.after(E)}}}]).directive("typeaheadPopup",function(){return{restrict:"EA",scope:{matches:"=",query:"=",active:"=",position:"=",select:"&"},replace:!0,templateUrl:"template/typeahead/typeahead-popup.html",link:function(a,b,c){a.templateUrl=c.templateUrl,a.isOpen=function(){return a.matches.length>0},a.isActive=function(b){return a.active==b},a.selectActive=function(b){a.active=b},a.selectMatch=function(b){a.select({activeIdx:b})}}}}).directive("typeaheadMatch",["$http","$templateCache","$compile","$parse",function(a,b,c,d){return{restrict:"EA",scope:{index:"=",match:"=",query:"="},link:function(e,f,g){var h=d(g.templateUrl)(e.$parent)||"template/typeahead/typeahead-match.html";a.get(h,{cache:b}).success(function(a){f.replaceWith(c(a.trim())(e))})}}}]).filter("typeaheadHighlight",function(){function a(a){return a.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}return function(b,c){return c?(""+b).replace(new RegExp(a(c),"gi"),"$&"):b}}),angular.module("template/accordion/accordion-group.html",[]).run(["$templateCache",function(a){a.put("template/accordion/accordion-group.html",'
    \n
    \n

    \n {{heading}}\n

    \n
    \n
    \n
    \n
    \n
    ')}]),angular.module("template/accordion/accordion.html",[]).run(["$templateCache",function(a){a.put("template/accordion/accordion.html",'
    ')}]),angular.module("template/alert/alert.html",[]).run(["$templateCache",function(a){a.put("template/alert/alert.html",'\n')}]),angular.module("template/carousel/carousel.html",[]).run(["$templateCache",function(a){a.put("template/carousel/carousel.html",'\n')}]),angular.module("template/carousel/slide.html",[]).run(["$templateCache",function(a){a.put("template/carousel/slide.html","
    \n")}]),angular.module("template/datepicker/datepicker.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/datepicker.html",'
    \n \n \n \n
    ')}]),angular.module("template/datepicker/day.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/day.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    {{label.abbr}}
    {{ weekNumbers[$index] }}\n \n
    \n')}]),angular.module("template/datepicker/month.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/month.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n
    \n \n
    \n')}]),angular.module("template/datepicker/popup.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/popup.html",'\n')}]),angular.module("template/datepicker/year.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/year.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n
    \n \n
    \n')}]),angular.module("template/modal/backdrop.html",[]).run(["$templateCache",function(a){a.put("template/modal/backdrop.html",'\n')}]),angular.module("template/modal/window.html",[]).run(["$templateCache",function(a){a.put("template/modal/window.html",'')}]),angular.module("template/pagination/pager.html",[]).run(["$templateCache",function(a){a.put("template/pagination/pager.html",'')}]),angular.module("template/pagination/pagination.html",[]).run(["$templateCache",function(a){a.put("template/pagination/pagination.html",'')}]),angular.module("template/tooltip/tooltip-html-unsafe-popup.html",[]).run(["$templateCache",function(a){a.put("template/tooltip/tooltip-html-unsafe-popup.html",'
    \n
    \n
    \n
    \n')}]),angular.module("template/tooltip/tooltip-popup.html",[]).run(["$templateCache",function(a){a.put("template/tooltip/tooltip-popup.html",'
    \n
    \n
    \n
    \n')}]),angular.module("template/popover/popover.html",[]).run(["$templateCache",function(a){a.put("template/popover/popover.html",'
    \n
    \n\n
    \n

    \n
    \n
    \n
    \n')}]),angular.module("template/progressbar/bar.html",[]).run(["$templateCache",function(a){a.put("template/progressbar/bar.html",'
    ')}]),angular.module("template/progressbar/progress.html",[]).run(["$templateCache",function(a){a.put("template/progressbar/progress.html",'
    ')}]),angular.module("template/progressbar/progressbar.html",[]).run(["$templateCache",function(a){a.put("template/progressbar/progressbar.html",'
    \n
    \n
    ')}]),angular.module("template/rating/rating.html",[]).run(["$templateCache",function(a){a.put("template/rating/rating.html",'\n \n ({{ $index < value ? \'*\' : \' \' }})\n \n')}]),angular.module("template/tabs/tab.html",[]).run(["$templateCache",function(a){a.put("template/tabs/tab.html",'
  • \n {{heading}}\n
  • \n')}]),angular.module("template/tabs/tabset-titles.html",[]).run(["$templateCache",function(a){a.put("template/tabs/tabset-titles.html","
      \n
    \n")}]),angular.module("template/tabs/tabset.html",[]).run(["$templateCache",function(a){a.put("template/tabs/tabset.html",'\n
    \n \n
    \n
    \n
    \n
    \n
    \n')}]),angular.module("template/timepicker/timepicker.html",[]).run(["$templateCache",function(a){a.put("template/timepicker/timepicker.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
     
    \n \n :\n \n
     
    \n')}]),angular.module("template/typeahead/typeahead-match.html",[]).run(["$templateCache",function(a){a.put("template/typeahead/typeahead-match.html",'')}]),angular.module("template/typeahead/typeahead-popup.html",[]).run(["$templateCache",function(a){a.put("template/typeahead/typeahead-popup.html",'') }]); \ No newline at end of file diff --git a/setup/pub/angular-ui-router/angular-ui-router.min.js b/setup/pub/angular-ui-router/angular-ui-router.min.js index f065ecc960684..66568f91192ec 100644 --- a/setup/pub/angular-ui-router/angular-ui-router.min.js +++ b/setup/pub/angular-ui-router/angular-ui-router.min.js @@ -1,7 +1,7 @@ /** * State-based routing for AngularJS - * @version v0.2.10 + * @version v0.4.3 * @link http://angular-ui.github.com/ * @license MIT License, http://www.opensource.org/licenses/MIT */ -"undefined"!=typeof module&&"undefined"!=typeof exports&&module.exports===exports&&(module.exports="ui.router"),function(a,b,c){"use strict";function d(a,b){return I(new(I(function(){},{prototype:a})),b)}function e(a){return H(arguments,function(b){b!==a&&H(b,function(b,c){a.hasOwnProperty(c)||(a[c]=b)})}),a}function f(a,b){var c=[];for(var d in a.path){if(a.path[d]!==b.path[d])break;c.push(a.path[d])}return c}function g(a,b){if(Array.prototype.indexOf)return a.indexOf(b,Number(arguments[2])||0);var c=a.length>>>0,d=Number(arguments[2])||0;for(d=0>d?Math.ceil(d):Math.floor(d),0>d&&(d+=c);c>d;d++)if(d in a&&a[d]===b)return d;return-1}function h(a,b,c,d){var e,h=f(c,d),i={},j=[];for(var k in h)if(h[k].params&&h[k].params.length){e=h[k].params;for(var l in e)g(j,e[l])>=0||(j.push(e[l]),i[e[l]]=a[e[l]])}return I({},i,b)}function i(a,b){var c={};return H(a,function(a){var d=b[a];c[a]=null!=d?String(d):null}),c}function j(a,b,c){if(!c){c=[];for(var d in a)c.push(d)}for(var e=0;e "));if(o[c]=d,E(a))m.push(c,[function(){return b.get(a)}],h);else{var e=b.annotate(a);H(e,function(a){a!==c&&g.hasOwnProperty(a)&&k(g[a],a)}),m.push(c,a,e)}n.pop(),o[c]=f}}function l(a){return F(a)&&a.then&&a.$$promises}if(!F(g))throw new Error("'invocables' must be an object");var m=[],n=[],o={};return H(g,k),g=n=o=null,function(d,f,g){function h(){--s||(t||e(r,f.$$values),p.$$values=r,p.$$promises=!0,o.resolve(r))}function k(a){p.$$failure=a,o.reject(a)}function n(c,e,f){function i(a){l.reject(a),k(a)}function j(){if(!C(p.$$failure))try{l.resolve(b.invoke(e,g,r)),l.promise.then(function(a){r[c]=a,h()},i)}catch(a){i(a)}}var l=a.defer(),m=0;H(f,function(a){q.hasOwnProperty(a)&&!d.hasOwnProperty(a)&&(m++,q[a].then(function(b){r[a]=b,--m||j()},i))}),m||j(),q[c]=l.promise}if(l(d)&&g===c&&(g=f,f=d,d=null),d){if(!F(d))throw new Error("'locals' must be an object")}else d=i;if(f){if(!l(f))throw new Error("'parent' must be a promise returned by $resolve.resolve()")}else f=j;var o=a.defer(),p=o.promise,q=p.$$promises={},r=I({},d),s=1+m.length/3,t=!1;if(C(f.$$failure))return k(f.$$failure),p;f.$$values?(t=e(r,f.$$values),h()):(I(q,f.$$promises),f.then(h,k));for(var u=0,v=m.length;v>u;u+=3)d.hasOwnProperty(m[u])?h():n(m[u],m[u+1],m[u+2]);return p}},this.resolve=function(a,b,c,d){return this.study(a)(b,c,d)}}function m(a,b,c){this.fromConfig=function(a,b,c){return C(a.template)?this.fromString(a.template,b):C(a.templateUrl)?this.fromUrl(a.templateUrl,b):C(a.templateProvider)?this.fromProvider(a.templateProvider,b,c):null},this.fromString=function(a,b){return D(a)?a(b):a},this.fromUrl=function(c,d){return D(c)&&(c=c(d)),null==c?null:a.get(c,{cache:b}).then(function(a){return a.data})},this.fromProvider=function(a,b,d){return c.invoke(a,null,d||{params:b})}}function n(a){function b(b){if(!/^\w+(-+\w+)*$/.test(b))throw new Error("Invalid parameter name '"+b+"' in pattern '"+a+"'");if(f[b])throw new Error("Duplicate parameter name '"+b+"' in pattern '"+a+"'");f[b]=!0,j.push(b)}function c(a){return a.replace(/[\\\[\]\^$*+?.()|{}]/g,"\\$&")}var d,e=/([:*])(\w+)|\{(\w+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,f={},g="^",h=0,i=this.segments=[],j=this.params=[];this.source=a;for(var k,l,m;(d=e.exec(a))&&(k=d[2]||d[3],l=d[4]||("*"==d[1]?".*":"[^/]*"),m=a.substring(h,d.index),!(m.indexOf("?")>=0));)g+=c(m)+"("+l+")",b(k),i.push(m),h=e.lastIndex;m=a.substring(h);var n=m.indexOf("?");if(n>=0){var o=this.sourceSearch=m.substring(n);m=m.substring(0,n),this.sourcePath=a.substring(0,h+n),H(o.substring(1).split(/[&?]/),b)}else this.sourcePath=a,this.sourceSearch="";g+=c(m)+"$",i.push(m),this.regexp=new RegExp(g),this.prefix=i[0]}function o(){this.compile=function(a){return new n(a)},this.isMatcher=function(a){return F(a)&&D(a.exec)&&D(a.format)&&D(a.concat)},this.$get=function(){return this}}function p(a){function b(a){var b=/^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(a.source);return null!=b?b[1].replace(/\\(.)/g,"$1"):""}function c(a,b){return a.replace(/\$(\$|\d{1,2})/,function(a,c){return b["$"===c?0:Number(c)]})}function d(a,b,c){if(!c)return!1;var d=a.invoke(b,b,{$match:c});return C(d)?d:!0}var e=[],f=null;this.rule=function(a){if(!D(a))throw new Error("'rule' must be a function");return e.push(a),this},this.otherwise=function(a){if(E(a)){var b=a;a=function(){return b}}else if(!D(a))throw new Error("'rule' must be a function");return f=a,this},this.when=function(e,f){var g,h=E(f);if(E(e)&&(e=a.compile(e)),!h&&!D(f)&&!G(f))throw new Error("invalid 'handler' in when()");var i={matcher:function(b,c){return h&&(g=a.compile(c),c=["$match",function(a){return g.format(a)}]),I(function(a,e){return d(a,c,b.exec(e.path(),e.search()))},{prefix:E(b.prefix)?b.prefix:""})},regex:function(a,e){if(a.global||a.sticky)throw new Error("when() RegExp must not be global or sticky");return h&&(g=e,e=["$match",function(a){return c(g,a)}]),I(function(b,c){return d(b,e,a.exec(c.path()))},{prefix:b(a)})}},j={matcher:a.isMatcher(e),regex:e instanceof RegExp};for(var k in j)if(j[k])return this.rule(i[k](e,f));throw new Error("invalid 'what' in when()")},this.$get=["$location","$rootScope","$injector",function(a,b,c){function d(b){function d(b){var d=b(c,a);return d?(E(d)&&a.replace().url(d),!0):!1}if(!b||!b.defaultPrevented){var g,h=e.length;for(g=0;h>g;g++)if(d(e[g]))return;f&&d(f)}}return b.$on("$locationChangeSuccess",d),{sync:function(){d()}}}]}function q(a,e,f){function g(a){return 0===a.indexOf(".")||0===a.indexOf("^")}function l(a,b){var d=E(a),e=d?a:a.name,f=g(e);if(f){if(!b)throw new Error("No reference point given for path '"+e+"'");for(var h=e.split("."),i=0,j=h.length,k=b;j>i;i++)if(""!==h[i]||0!==i){if("^"!==h[i])break;if(!k.parent)throw new Error("Path '"+e+"' not valid for state '"+b.name+"'");k=k.parent}else k=b;h=h.slice(i).join("."),e=k.name+(k.name&&h?".":"")+h}var l=w[e];return!l||!d&&(d||l!==a&&l.self!==a)?c:l}function m(a,b){x[a]||(x[a]=[]),x[a].push(b)}function n(b){b=d(b,{self:b,resolve:b.resolve||{},toString:function(){return this.name}});var c=b.name;if(!E(c)||c.indexOf("@")>=0)throw new Error("State must have a valid name");if(w.hasOwnProperty(c))throw new Error("State '"+c+"'' is already defined");var e=-1!==c.indexOf(".")?c.substring(0,c.lastIndexOf(".")):E(b.parent)?b.parent:"";if(e&&!w[e])return m(e,b.self);for(var f in z)D(z[f])&&(b[f]=z[f](b,z.$delegates[f]));if(w[c]=b,!b[y]&&b.url&&a.when(b.url,["$match","$stateParams",function(a,c){v.$current.navigable==b&&j(a,c)||v.transitionTo(b,a,{location:!1})}]),x[c])for(var g=0;g-1}function p(a){var b=a.split("."),c=v.$current.name.split(".");if("**"===b[0]&&(c=c.slice(c.indexOf(b[1])),c.unshift("**")),"**"===b[b.length-1]&&(c.splice(c.indexOf(b[b.length-2])+1,Number.MAX_VALUE),c.push("**")),b.length!=c.length)return!1;for(var d=0,e=b.length;e>d;d++)"*"===b[d]&&(c[d]="*");return c.join("")===b.join("")}function q(a,b){return E(a)&&!C(b)?z[a]:D(b)&&E(a)?(z[a]&&!z.$delegates[a]&&(z.$delegates[a]=z[a]),z[a]=b,this):this}function r(a,b){return F(a)?b=a:b.name=a,n(b),this}function s(a,e,g,m,n,q,r,s,x){function z(){r.url()!==M&&(r.url(M),r.replace())}function A(a,c,d,f,h){var i=d?c:k(a.params,c),j={$stateParams:i};h.resolve=n.resolve(a.resolve,j,h.resolve,a);var l=[h.resolve.then(function(a){h.globals=a})];return f&&l.push(f),H(a.views,function(c,d){var e=c.resolve&&c.resolve!==a.resolve?c.resolve:{};e.$template=[function(){return g.load(d,{view:c,locals:j,params:i,notify:!1})||""}],l.push(n.resolve(e,j,h.resolve,a).then(function(f){if(D(c.controllerProvider)||G(c.controllerProvider)){var g=b.extend({},e,j);f.$$controller=m.invoke(c.controllerProvider,null,g)}else f.$$controller=c.controller;f.$$state=a,f.$$controllerAs=c.controllerAs,h[d]=f}))}),e.all(l).then(function(){return h})}var B=e.reject(new Error("transition superseded")),F=e.reject(new Error("transition prevented")),K=e.reject(new Error("transition aborted")),L=e.reject(new Error("transition failed")),M=r.url(),N=x.baseHref();return u.locals={resolve:null,globals:{$stateParams:{}}},v={params:{},current:u.self,$current:u,transition:null},v.reload=function(){v.transitionTo(v.current,q,{reload:!0,inherit:!1,notify:!1})},v.go=function(a,b,c){return this.transitionTo(a,b,I({inherit:!0,relative:v.$current},c))},v.transitionTo=function(b,c,f){c=c||{},f=I({location:!0,inherit:!1,relative:null,notify:!0,reload:!1,$retry:!1},f||{});var g,k=v.$current,n=v.params,o=k.path,p=l(b,f.relative);if(!C(p)){var s={to:b,toParams:c,options:f};if(g=a.$broadcast("$stateNotFound",s,k.self,n),g.defaultPrevented)return z(),K;if(g.retry){if(f.$retry)return z(),L;var w=v.transition=e.when(g.retry);return w.then(function(){return w!==v.transition?B:(s.options.$retry=!0,v.transitionTo(s.to,s.toParams,s.options))},function(){return K}),z(),w}if(b=s.to,c=s.toParams,f=s.options,p=l(b,f.relative),!C(p)){if(f.relative)throw new Error("Could not resolve '"+b+"' from state '"+f.relative+"'");throw new Error("No such state '"+b+"'")}}if(p[y])throw new Error("Cannot transition to abstract state '"+b+"'");f.inherit&&(c=h(q,c||{},v.$current,p)),b=p;var x,D,E=b.path,G=u.locals,H=[];for(x=0,D=E[x];D&&D===o[x]&&j(c,n,D.ownParams)&&!f.reload;x++,D=E[x])G=H[x]=D.locals;if(t(b,k,G,f))return b.self.reloadOnSearch!==!1&&z(),v.transition=null,e.when(v.current);if(c=i(b.params,c||{}),f.notify&&(g=a.$broadcast("$stateChangeStart",b.self,c,k.self,n),g.defaultPrevented))return z(),F;for(var N=e.when(G),O=x;O=x;d--)g=o[d],g.self.onExit&&m.invoke(g.self.onExit,g.self,g.locals.globals),g.locals=null;for(d=x;d1||b.ctrlKey||b.metaKey||b.shiftKey||f.attr("target")||(c(function(){a.go(i.state,j,o)}),b.preventDefault())})}}}function y(a,b,c){return{restrict:"A",controller:["$scope","$element","$attrs",function(d,e,f){function g(){a.$current.self===i&&h()?e.addClass(l):e.removeClass(l)}function h(){return!k||j(k,b)}var i,k,l;l=c(f.uiSrefActive||"",!1)(d),this.$$setStateInfo=function(b,c){i=a.get(b,w(e)),k=c,g()},d.$on("$stateChangeSuccess",g)}]}}function z(a){return function(b){return a.is(b)}}function A(a){return function(b){return a.includes(b)}}function B(a,b){function e(a){this.locals=a.locals.globals,this.params=this.locals.$stateParams}function f(){this.locals=null,this.params=null}function g(c,g){if(null!=g.redirectTo){var h,j=g.redirectTo;if(E(j))h=j;else{if(!D(j))throw new Error("Invalid 'redirectTo' in when()");h=function(a,b){return j(a,b.path(),b.search())}}b.when(c,h)}else a.state(d(g,{parent:null,name:"route:"+encodeURIComponent(c),url:c,onEnter:e,onExit:f}));return i.push(g),this}function h(a,b,d){function e(a){return""!==a.name?a:c}var f={routes:i,params:d,current:c};return b.$on("$stateChangeStart",function(a,c,d,f){b.$broadcast("$routeChangeStart",e(c),e(f))}),b.$on("$stateChangeSuccess",function(a,c,d,g){f.current=e(c),b.$broadcast("$routeChangeSuccess",e(c),e(g)),J(d,f.params)}),b.$on("$stateChangeError",function(a,c,d,f,g,h){b.$broadcast("$routeChangeError",e(c),e(f),h)}),f}var i=[];e.$inject=["$$state"],this.when=g,this.$get=h,h.$inject=["$state","$rootScope","$routeParams"]}var C=b.isDefined,D=b.isFunction,E=b.isString,F=b.isObject,G=b.isArray,H=b.forEach,I=b.extend,J=b.copy;b.module("ui.router.util",["ng"]),b.module("ui.router.router",["ui.router.util"]),b.module("ui.router.state",["ui.router.router","ui.router.util"]),b.module("ui.router",["ui.router.state"]),b.module("ui.router.compat",["ui.router"]),l.$inject=["$q","$injector"],b.module("ui.router.util").service("$resolve",l),m.$inject=["$http","$templateCache","$injector"],b.module("ui.router.util").service("$templateFactory",m),n.prototype.concat=function(a){return new n(this.sourcePath+a+this.sourceSearch)},n.prototype.toString=function(){return this.source},n.prototype.exec=function(a,b){var c=this.regexp.exec(a);if(!c)return null;var d,e=this.params,f=e.length,g=this.segments.length-1,h={};if(g!==c.length-1)throw new Error("Unbalanced capture group in route '"+this.source+"'");for(d=0;g>d;d++)h[e[d]]=c[d+1];for(;f>d;d++)h[e[d]]=b[e[d]];return h},n.prototype.parameters=function(){return this.params},n.prototype.format=function(a){var b=this.segments,c=this.params;if(!a)return b.join("");var d,e,f,g=b.length-1,h=c.length,i=b[0];for(d=0;g>d;d++)f=a[c[d]],null!=f&&(i+=encodeURIComponent(f)),i+=b[d+1];for(;h>d;d++)f=a[c[d]],null!=f&&(i+=(e?"&":"?")+c[d]+"="+encodeURIComponent(f),e=!0);return i},b.module("ui.router.util").provider("$urlMatcherFactory",o),p.$inject=["$urlMatcherFactoryProvider"],b.module("ui.router.router").provider("$urlRouter",p),q.$inject=["$urlRouterProvider","$urlMatcherFactoryProvider","$locationProvider"],b.module("ui.router.state").value("$stateParams",{}).provider("$state",q),r.$inject=[],b.module("ui.router.state").provider("$view",r),b.module("ui.router.state").provider("$uiViewScroll",s),t.$inject=["$state","$injector","$uiViewScroll"],u.$inject=["$compile","$controller","$state"],b.module("ui.router.state").directive("uiView",t),b.module("ui.router.state").directive("uiView",u),x.$inject=["$state","$timeout"],y.$inject=["$state","$stateParams","$interpolate"],b.module("ui.router.state").directive("uiSref",x).directive("uiSrefActive",y),z.$inject=["$state"],A.$inject=["$state"],b.module("ui.router.state").filter("isState",z).filter("includedByState",A),B.$inject=["$stateProvider","$urlRouterProvider"],b.module("ui.router.compat").provider("$route",B).directive("ngView",t)}(window,window.angular); \ No newline at end of file +"undefined"!=typeof module&&"undefined"!=typeof exports&&module.exports===exports&&(module.exports="ui.router"),function(a,b,c){"use strict";function d(a,b){return T(new(T(function(){},{prototype:a})),b)}function e(a){return S(arguments,function(b){b!==a&&S(b,function(b,c){a.hasOwnProperty(c)||(a[c]=b)})}),a}function f(a,b){var c=[];for(var d in a.path){if(a.path[d]!==b.path[d])break;c.push(a.path[d])}return c}function g(a){if(Object.keys)return Object.keys(a);var b=[];return S(a,function(a,c){b.push(c)}),b}function h(a,b){if(Array.prototype.indexOf)return a.indexOf(b,Number(arguments[2])||0);var c=a.length>>>0,d=Number(arguments[2])||0;for(d=d<0?Math.ceil(d):Math.floor(d),d<0&&(d+=c);d=0||(k.push(e[m]),j[e[m]]=a[e[m]]);return T({},j,b)}function j(a,b,c){if(!c){c=[];for(var d in a)c.push(d)}for(var e=0;e "));if(t[c]=d,P(a))r.push(c,[function(){return b.get(a)}],j);else{var e=b.annotate(a);S(e,function(a){a!==c&&i.hasOwnProperty(a)&&n(i[a],a)}),r.push(c,a,e)}s.pop(),t[c]=f}}function o(a){return Q(a)&&a.then&&a.$$promises}if(!Q(i))throw new Error("'invocables' must be an object");var q=g(i||{}),r=[],s=[],t={};return S(i,n),i=s=t=null,function(d,f,g){function h(){--v||(w||e(u,f.$$values),s.$$values=u,s.$$promises=s.$$promises||!0,delete s.$$inheritedValues,n.resolve(u))}function i(a){s.$$failure=a,n.reject(a)}function j(c,e,f){function j(a){l.reject(a),i(a)}function k(){if(!N(s.$$failure))try{l.resolve(b.invoke(e,g,u)),l.promise.then(function(a){u[c]=a,h()},j)}catch(a){j(a)}}var l=a.defer(),m=0;S(f,function(a){t.hasOwnProperty(a)&&!d.hasOwnProperty(a)&&(m++,t[a].then(function(b){u[a]=b,--m||k()},j))}),m||k(),t[c]=p(l.promise)}if(o(d)&&g===c&&(g=f,f=d,d=null),d){if(!Q(d))throw new Error("'locals' must be an object")}else d=k;if(f){if(!o(f))throw new Error("'parent' must be a promise returned by $resolve.resolve()")}else f=l;var n=a.defer(),s=p(n.promise),t=s.$$promises={},u=T({},d),v=1+r.length/3,w=!1;if(p(s),N(f.$$failure))return i(f.$$failure),s;f.$$inheritedValues&&e(u,m(f.$$inheritedValues,q)),T(t,f.$$promises),f.$$values?(w=e(u,m(f.$$values,q)),s.$$inheritedValues=m(f.$$values,q),h()):(f.$$inheritedValues&&(s.$$inheritedValues=m(f.$$inheritedValues,q)),f.then(h,i));for(var x=0,y=r.length;x=0));)s=f(r.id,r.type,r.cfg,"path"),l+=g(r.segment,s.type.pattern.source,s.squash,s.isOptional),n.push(r.segment),m=j.lastIndex;t=a.substring(m);var u=t.indexOf("?");if(u>=0){var v=this.sourceSearch=t.substring(u);if(t=t.substring(0,u),this.sourcePath=a.substring(0,m+u),v.length>0)for(m=0;i=k.exec(v);)r=h(i,!0),s=f(r.id,r.type,r.cfg,"search"),m=j.lastIndex}else this.sourcePath=a,this.sourceSearch="";l+=g(t)+(!1===b.strict?"/?":"")+"$",n.push(t),this.regexp=new RegExp(l,b.caseInsensitive?"i":c),this.prefix=n[0],this.$$paramNames=q}function u(a){T(this,a)}function v(){function a(a){return null!=a?a.toString().replace(/(~|\/)/g,function(a){return{"~":"~~","/":"~2F"}[a]}):a}function e(a){return null!=a?a.toString().replace(/(~~|~2F)/g,function(a){return{"~~":"~","~2F":"/"}[a]}):a}function f(){return{strict:p,caseInsensitive:m}}function i(a){return O(a)||R(a)&&O(a[a.length-1])}function j(){for(;w.length;){var a=w.shift();if(a.pattern)throw new Error("You cannot override a type's .pattern at runtime.");b.extend(r[a.name],l.invoke(a.def))}}function k(a){T(this,a||{})}W=this;var l,m=!1,p=!0,q=!1,r={},s=!0,w=[],x={string:{encode:a,decode:e,is:function(a){return null==a||!N(a)||"string"==typeof a},pattern:/[^\/]*/},int:{encode:a,decode:function(a){return parseInt(a,10)},is:function(a){return a!==c&&null!==a&&this.decode(a.toString())===a},pattern:/-?\d+/},bool:{encode:function(a){return a?1:0},decode:function(a){return 0!==parseInt(a,10)},is:function(a){return!0===a||!1===a},pattern:/0|1/},date:{encode:function(a){return this.is(a)?[a.getFullYear(),("0"+(a.getMonth()+1)).slice(-2),("0"+a.getDate()).slice(-2)].join("-"):c},decode:function(a){if(this.is(a))return a;var b=this.capture.exec(a);return b?new Date(b[1],b[2]-1,b[3]):c},is:function(a){return a instanceof Date&&!isNaN(a.valueOf())},equals:function(a,b){return this.is(a)&&this.is(b)&&a.toISOString()===b.toISOString()},pattern:/[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,capture:/([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/},json:{encode:b.toJson,decode:b.fromJson,is:b.isObject,equals:b.equals,pattern:/[^\/]*/},any:{encode:b.identity,decode:b.identity,equals:b.equals,pattern:/.*/}};v.$$getDefaultValue=function(a){if(!i(a.value))return a.value;if(!l)throw new Error("Injectable functions cannot be called at configuration time");return l.invoke(a.value)},this.caseInsensitive=function(a){return N(a)&&(m=a),m},this.strictMode=function(a){return N(a)&&(p=a),p},this.defaultSquashPolicy=function(a){if(!N(a))return q;if(!0!==a&&!1!==a&&!P(a))throw new Error("Invalid squash policy: "+a+". Valid policies: false, true, arbitrary-string");return q=a,a},this.compile=function(a,b){return new t(a,T(f(),b))},this.isMatcher=function(a){if(!Q(a))return!1;var b=!0;return S(t.prototype,function(c,d){O(c)&&(b=b&&N(a[d])&&O(a[d]))}),b},this.type=function(a,b,c){if(!N(b))return r[a];if(r.hasOwnProperty(a))throw new Error("A type named '"+a+"' has already been defined.");return r[a]=new u(T({name:a},b)),c&&(w.push({name:a,def:c}),s||j()),this},S(x,function(a,b){r[b]=new u(T({name:b},a))}),r=d(r,{}),this.$get=["$injector",function(a){return l=a,s=!1,j(),S(x,function(a,b){r[b]||(r[b]=new u(a))}),this}],this.Param=function(a,d,e,f){function j(a){var b=Q(a)?g(a):[];return-1===h(b,"value")&&-1===h(b,"type")&&-1===h(b,"squash")&&-1===h(b,"array")&&(a={value:a}),a.$$fn=i(a.value)?a.value:function(){return a.value},a}function k(c,d,e){if(c.type&&d)throw new Error("Param '"+a+"' has two type configurations.");return d||(c.type?b.isString(c.type)?r[c.type]:c.type instanceof u?c.type:new u(c.type):"config"===e?r.any:r.string)}function m(){var b={array:"search"===f&&"auto"},c=a.match(/\[\]$/)?{array:!0}:{};return T(b,c,e).array}function p(a,b){var c=a.squash;if(!b||!1===c)return!1;if(!N(c)||null==c)return q;if(!0===c||P(c))return c;throw new Error("Invalid squash policy: '"+c+"'. Valid policies: false, true, or arbitrary string")}function s(a,b,d,e){var f,g,i=[{from:"",to:d||b?c:""},{from:null,to:d||b?c:""}];return f=R(a.replace)?a.replace:[],P(e)&&f.push({from:e,to:c}),g=o(f,function(a){return a.from}),n(i,function(a){return-1===h(g,a.from)}).concat(f)}function t(){if(!l)throw new Error("Injectable functions cannot be called at configuration time");var a=l.invoke(e.$$fn);if(null!==a&&a!==c&&!x.type.is(a))throw new Error("Default value ("+a+") for parameter '"+x.id+"' is not an instance of Type ("+x.type.name+")");return a}function v(a){function b(a){return function(b){return b.from===a}}function c(a){var c=o(n(x.replace,b(a)),function(a){return a.to});return c.length?c[0]:a}return a=c(a),N(a)?x.type.$normalize(a):t()}function w(){return"{Param:"+a+" "+d+" squash: '"+A+"' optional: "+z+"}"}var x=this;e=j(e),d=k(e,d,f);var y=m();d=y?d.$asArray(y,"search"===f):d,"string"!==d.name||y||"path"!==f||e.value!==c||(e.value="");var z=e.value!==c,A=p(e,z),B=s(e,y,z,A);T(this,{id:a,type:d,location:f,array:y,squash:A,replace:B,isOptional:z,value:v,dynamic:c,config:e,toString:w})},k.prototype={$$new:function(){return d(this,T(new k,{$$parent:this}))},$$keys:function(){for(var a=[],b=[],c=this,d=g(k.prototype);c;)b.push(c),c=c.$$parent;return b.reverse(),S(b,function(b){S(g(b),function(b){-1===h(a,b)&&-1===h(d,b)&&a.push(b)})}),a},$$values:function(a){var b={},c=this;return S(c.$$keys(),function(d){b[d]=c[d].value(a&&a[d])}),b},$$equals:function(a,b){var c=!0,d=this;return S(d.$$keys(),function(e){var f=a&&a[e],g=b&&b[e];d[e].type.equals(f,g)||(c=!1)}),c},$$validates:function(a){var d,e,f,g,h,i=this.$$keys();for(d=0;d=0)throw new Error("State must have a valid name");if(A.hasOwnProperty(c))throw new Error("State '"+c+"' is already defined");var e=-1!==c.indexOf(".")?c.substring(0,c.lastIndexOf(".")):P(b.parent)?b.parent:Q(b.parent)&&P(b.parent.name)?b.parent.name:"";if(e&&!A[e])return n(e,b.self);for(var f in D)O(D[f])&&(b[f]=D[f](b,D.$delegates[f]));return A[c]=b,!b[C]&&b.url&&a.when(b.url,["$match","$stateParams",function(a,c){z.$current.navigable==b&&j(a,c)||z.transitionTo(b,a,{inherit:!0,location:!1})}]),q(c),b}function s(a){return a.indexOf("*")>-1}function t(a){for(var b=a.split("."),c=z.$current.name.split("."),d=0,e=b.length;d=G;d--)g=q[d],g.self.onExit&&h.invoke(g.self.onExit,g.self,g.locals.globals),g.locals=null;for(d=G;d2?k.enter(a,null,c).then(d):k.enter(a,null,c,d)},leave:function(a,c){b.version.minor>2?k.leave(a).then(c):k.leave(a,c)}};if(j){var e=j&&j(c,a);return{enter:function(a,b,c){e.enter(a,null,b),c()},leave:function(a,b){e.leave(a),b()}}}return d()}var i=g(),j=i("$animator"),k=i("$animate");return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",compile:function(c,g,i){return function(c,g,j){function k(){if(m&&(m.remove(),m=null),o&&(o.$destroy(),o=null),n){var a=n.data("$uiViewAnim");s.leave(n,function(){a.$$animLeave.resolve(),m=null}),m=n,n=null}}function l(h){var l,m=C(c,j,g,e),t=m&&a.$current&&a.$current.locals[m];if(h||t!==p){l=c.$new(),p=a.$current.locals[m],l.$emit("$viewContentLoading",m);var u=i(l,function(a){var e=f.defer(),h=f.defer(),i={$animEnter:e.promise,$animLeave:h.promise,$$animLeave:h};a.data("$uiViewAnim",i),s.enter(a,g,function(){e.resolve(),o&&o.$emit("$viewContentAnimationEnded"),(b.isDefined(r)&&!r||c.$eval(r))&&d(a)}),k()});n=u,o=l,o.$emit("$viewContentLoaded",m),o.$eval(q)}}var m,n,o,p,q=j.onload||"",r=j.autoscroll,s=h(j,c);g.inheritedData("$uiView");c.$on("$stateChangeSuccess",function(){l(!1)}),l(!0)}}}}function B(a,c,d,e){return{restrict:"ECA",priority:-400,compile:function(f){var g=f.html();return f.empty?f.empty():f[0].innerHTML=null,function(f,h,i){var j=d.$current,k=C(f,i,h,e),l=j&&j.locals[k];if(!l)return h.html(g),void a(h.contents())(f);h.data("$uiView",{name:k,state:l.$$state}),h.html(l.$template?l.$template:g);var m=b.extend({},l);f[l.$$resolveAs]=m;var n=a(h.contents());if(l.$$controller){l.$scope=f,l.$element=h;var o=c(l.$$controller,l);l.$$controllerAs&&(f[l.$$controllerAs]=o,f[l.$$controllerAs][l.$$resolveAs]=m),O(o.$onInit)&&o.$onInit(),h.data("$ngControllerController",o),h.children().data("$ngControllerController",o)}n(f)}}}}function C(a,b,c,d){var e=d(b.uiView||b.name||"")(a),f=c.inheritedData("$uiView");return e.indexOf("@")>=0?e:e+"@"+(f?f.state.name:"")}function D(a,b){var c,d=a.match(/^\s*({[^}]*})\s*$/);if(d&&(a=b+"("+d[1]+")"),!(c=a.replace(/\n/g," ").match(/^([^(]+?)\s*(\((.*)\))?$/))||4!==c.length)throw new Error("Invalid state ref '"+a+"'");return{state:c[1],paramExpr:c[3]||null}}function E(a){var b=a.parent().inheritedData("$uiView");if(b&&b.state&&b.state.name)return b.state}function F(a){var b="[object SVGAnimatedString]"===Object.prototype.toString.call(a.prop("href")),c="FORM"===a[0].nodeName;return{attr:c?"action":b?"xlink:href":"href",isAnchor:"A"===a.prop("tagName").toUpperCase(),clickable:!c}}function G(a,b,c,d,e){return function(f){var g=f.which||f.button,h=e();if(!(g>1||f.ctrlKey||f.metaKey||f.shiftKey||a.attr("target"))){var i=c(function(){b.go(h.state,h.params,h.options)});f.preventDefault();var j=d.isAnchor&&!h.href?1:0;f.preventDefault=function(){j--<=0&&c.cancel(i)}}}}function H(a,b){return{relative:E(a)||b.$current,inherit:!0}}function I(a,c){return{restrict:"A",require:["?^uiSrefActive","?^uiSrefActiveEq"],link:function(d,e,f,g){var h,i=D(f.uiSref,a.current.name),j={state:i.state,href:null,params:null},k=F(e),l=g[1]||g[0],m=null;j.options=T(H(e,a),f.uiSrefOpts?d.$eval(f.uiSrefOpts):{});var n=function(c){c&&(j.params=b.copy(c)),j.href=a.href(i.state,j.params,j.options),m&&m(),l&&(m=l.$$addStateInfo(i.state,j.params)),null!==j.href&&f.$set(k.attr,j.href)};i.paramExpr&&(d.$watch(i.paramExpr,function(a){a!==j.params&&n(a)},!0),j.params=b.copy(d.$eval(i.paramExpr))),n(),k.clickable&&(h=G(e,a,c,k,function(){return j}),e[e.on?"on":"bind"]("click",h),d.$on("$destroy",function(){e[e.off?"off":"unbind"]("click",h)}))}}}function J(a,b){return{restrict:"A",require:["?^uiSrefActive","?^uiSrefActiveEq"],link:function(c,d,e,f){function g(b){m.state=b[0],m.params=b[1],m.options=b[2],m.href=a.href(m.state,m.params,m.options),n&&n(),j&&(n=j.$$addStateInfo(m.state,m.params)),m.href&&e.$set(i.attr,m.href)}var h,i=F(d),j=f[1]||f[0],k=[e.uiState,e.uiStateParams||null,e.uiStateOpts||null],l="["+k.map(function(a){return a||"null"}).join(", ")+"]",m={state:null,params:null,options:null,href:null},n=null;c.$watch(l,g,!0),g(c.$eval(l)),i.clickable&&(h=G(d,a,b,i,function(){return m}),d[d.on?"on":"bind"]("click",h),c.$on("$destroy",function(){d[d.off?"off":"unbind"]("click",h)}))}}}function K(a,b,c){return{restrict:"A",controller:["$scope","$element","$attrs","$timeout",function(b,d,e,f){function g(b,c,e){var f=a.get(b,E(d)),g=h(b,c),i={state:f||{name:b},params:c,hash:g};return p.push(i),q[g]=e,function(){var a=p.indexOf(i);-1!==a&&p.splice(a,1)}}function h(a,c){if(!P(a))throw new Error("state should be a string");return Q(c)?a+V(c):(c=b.$eval(c),Q(c)?a+V(c):a)}function i(){for(var a=0;a0)){var c=g(a,b,o);return i(),c}},b.$on("$stateChangeSuccess",i),i()}]}}function L(a){var b=function(b,c){return a.is(b,c)};return b.$stateful=!0,b}function M(a){var b=function(b,c,d){return a.includes(b,c,d)};return b.$stateful=!0,b}var N=b.isDefined,O=b.isFunction,P=b.isString,Q=b.isObject,R=b.isArray,S=b.forEach,T=b.extend,U=b.copy,V=b.toJson;b.module("ui.router.util",["ng"]),b.module("ui.router.router",["ui.router.util"]),b.module("ui.router.state",["ui.router.router","ui.router.util"]),b.module("ui.router",["ui.router.state"]),b.module("ui.router.compat",["ui.router"]),q.$inject=["$q","$injector"],b.module("ui.router.util").service("$resolve",q),b.module("ui.router.util").provider("$templateFactory",r);var W;t.prototype.concat=function(a,b){var c={caseInsensitive:W.caseInsensitive(),strict:W.strictMode(),squash:W.defaultSquashPolicy()};return new t(this.sourcePath+a+this.sourceSearch,T(c,b),this)},t.prototype.toString=function(){return this.source},t.prototype.exec=function(a,b){function c(a){function b(a){return a.split("").reverse().join("")}function c(a){return a.replace(/\\-/g,"-")}return o(o(b(a).split(/-(?!\\)/),b),c).reverse()}var d=this.regexp.exec(a);if(!d)return null;b=b||{};var e,f,g,h=this.parameters(),i=h.length,j=this.segments.length-1,k={};if(j!==d.length-1)throw new Error("Unbalanced capture group in route '"+this.source+"'");var l,m;for(e=0;e 0; + } /** * @description * * This object provides a utility for producing rich Error messages within - * Angular. It can be called as follows: + * AngularJS. It can be called as follows: * * var exampleMinErr = minErr('example'); * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); @@ -30,140 +80,145 @@ * should all be static strings, not variables or general expressions. * * @param {string} module The namespace to use for the new minErr instance. + * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning + * error from returned function, for cases when a particular type of error is useful. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance */ - function minErr(module) { - return function () { + function minErr(module, ErrorConstructor) { + ErrorConstructor = ErrorConstructor || Error; + return function() { var code = arguments[0], - prefix = '[' + (module ? module + ':' : '') + code + '] ', template = arguments[1], - templateArgs = arguments, - stringify = function (obj) { - if (typeof obj === 'function') { - return obj.toString().replace(/ \{[\s\S]*$/, ''); - } else if (typeof obj === 'undefined') { - return 'undefined'; - } else if (typeof obj !== 'string') { - return JSON.stringify(obj); - } - return obj; - }, - message, i; + message = '[' + (module ? module + ':' : '') + code + '] ', + templateArgs = sliceArgs(arguments, 2).map(function(arg) { + return toDebugString(arg, minErrConfig.objectMaxDepth); + }), + paramPrefix, i; - message = prefix + template.replace(/\{\d+\}/g, function (match) { - var index = +match.slice(1, -1), arg; + message += template.replace(/\{\d+\}/g, function(match) { + var index = +match.slice(1, -1); - if (index + 2 < templateArgs.length) { - arg = templateArgs[index + 2]; - if (typeof arg === 'function') { - return arg.toString().replace(/ ?\{[\s\S]*$/, ''); - } else if (typeof arg === 'undefined') { - return 'undefined'; - } else if (typeof arg !== 'string') { - return toJson(arg); - } - return arg; + if (index < templateArgs.length) { + return templateArgs[index]; } + return match; }); - message = message + '\nhttp://errors.angularjs.org/1.2.16/' + - (module ? module + '/' : '') + code; - for (i = 2; i < arguments.length; i++) { - message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' + - encodeURIComponent(stringify(arguments[i])); + message += '\nhttp://errors.angularjs.org/1.6.9/' + + (module ? module + '/' : '') + code; + + for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') { + message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]); } - return new Error(message); + return new ErrorConstructor(message); }; } - /* We need to tell jshint what variables are being exported */ - /* global - -angular, - -msie, - -jqLite, - -jQuery, - -slice, - -push, - -toString, - -ngMinErr, - -_angular, - -angularModule, - -nodeName_, - -uid, - - -lowercase, - -uppercase, - -manualLowercase, - -manualUppercase, - -nodeName_, - -isArrayLike, - -forEach, - -sortedKeys, - -forEachSorted, - -reverseParams, - -nextUid, - -setHashKey, - -extend, - -int, - -inherit, - -noop, - -identity, - -valueFn, - -isUndefined, - -isDefined, - -isObject, - -isString, - -isNumber, - -isDate, - -isArray, - -isFunction, - -isRegExp, - -isWindow, - -isScope, - -isFile, - -isBlob, - -isBoolean, - -trim, - -isElement, - -makeMap, - -map, - -size, - -includes, - -indexOf, - -arrayRemove, - -isLeafNode, - -copy, - -shallowCopy, - -equals, - -csp, - -concat, - -sliceArgs, - -bind, - -toJsonReplacer, - -toJson, - -fromJson, - -toBoolean, - -startingTag, - -tryDecodeURIComponent, - -parseKeyValue, - -toKeyValue, - -encodeUriSegment, - -encodeUriQuery, - -angularInit, - -bootstrap, - -snake_case, - -bindJQuery, - -assertArg, - -assertArgFn, - -assertNotHasOwnProperty, - -getter, - -getBlockElements, - -hasOwnProperty, - - */ + /* We need to tell ESLint what variables are being exported */ + /* exported + angular, + msie, + jqLite, + jQuery, + slice, + splice, + push, + toString, + minErrConfig, + errorHandlingConfig, + isValidObjectMaxDepth, + ngMinErr, + angularModule, + uid, + REGEX_STRING_REGEXP, + VALIDITY_STATE_PROPERTY, + + lowercase, + uppercase, + manualLowercase, + manualUppercase, + nodeName_, + isArrayLike, + forEach, + forEachSorted, + reverseParams, + nextUid, + setHashKey, + extend, + toInt, + inherit, + merge, + noop, + identity, + valueFn, + isUndefined, + isDefined, + isObject, + isBlankObject, + isString, + isNumber, + isNumberNaN, + isDate, + isError, + isArray, + isFunction, + isRegExp, + isWindow, + isScope, + isFile, + isFormData, + isBlob, + isBoolean, + isPromiseLike, + trim, + escapeForRegexp, + isElement, + makeMap, + includes, + arrayRemove, + copy, + simpleCompare, + equals, + csp, + jq, + concat, + sliceArgs, + bind, + toJsonReplacer, + toJson, + fromJson, + convertTimezoneToLocal, + timezoneToOffset, + startingTag, + tryDecodeURIComponent, + parseKeyValue, + toKeyValue, + encodeUriSegment, + encodeUriQuery, + angularInit, + bootstrap, + getTestability, + snake_case, + bindJQuery, + assertArg, + assertArgFn, + assertNotHasOwnProperty, + getter, + getBlockNodes, + hasOwnProperty, + createMap, + stringify, + + NODE_TYPE_ELEMENT, + NODE_TYPE_ATTRIBUTE, + NODE_TYPE_TEXT, + NODE_TYPE_COMMENT, + NODE_TYPE_DOCUMENT, + NODE_TYPE_DOCUMENT_FRAGMENT +*/ //////////////////////////////////// @@ -171,91 +226,107 @@ * @ngdoc module * @name ng * @module ng + * @installation * @description * - * # ng (core module) * The ng module is loaded by default when an AngularJS application is started. The module itself * contains the essential components for an AngularJS application to function. The table below * lists a high level breakdown of each of the services/factories, filters, directives and testing * components available within this core module. * - *
    */ + var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; + +// The name of a form control's ValidityState property. +// This is used so that it's possible for internal tests to create mock ValidityStates. + var VALIDITY_STATE_PROPERTY = 'validity'; + + + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** * @ngdoc function * @name angular.lowercase * @module ng - * @function + * @kind function + * + * @deprecated + * sinceVersion="1.5.0" + * removeVersion="1.7.0" + * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead. * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ - var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; - var hasOwnProperty = Object.prototype.hasOwnProperty; + var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;}; /** * @ngdoc function * @name angular.uppercase * @module ng - * @function + * @kind function + * + * @deprecated + * sinceVersion="1.5.0" + * removeVersion="1.7.0" + * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead. * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ - var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; + var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { - /* jshint bitwise: false */ + /* eslint-disable no-bitwise */ return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) : s; + /* eslint-enable */ }; var manualUppercase = function(s) { - /* jshint bitwise: false */ + /* eslint-disable no-bitwise */ return isString(s) ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) : s; + /* eslint-enable */ }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods -// with correct but slower alternatives. +// with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387 if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } - var /** holds major version number for IE or NaN for real browsers */ - msie, + var + msie, // holds major version number for IE, or NaN if UA is not IE. jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, + splice = [].splice, push = [].push, toString = Object.prototype.toString, + getPrototypeOf = Object.getPrototypeOf, ngMinErr = minErr('ng'), - - _angular = window.angular, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, - nodeName_, - uid = ['0', '0', '0']; + uid = 0; +// Support: IE 9-11 only /** - * IE 11 changed the format of the UserAgent string. - * See http://msdn.microsoft.com/en-us/library/ms537503.aspx + * documentMode is an IE-only property + * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx */ - msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); - if (isNaN(msie)) { - msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); - } + msie = window.document.documentMode; /** @@ -265,39 +336,51 @@ * String ...) */ function isArrayLike(obj) { - if (obj == null || isWindow(obj)) { - return false; - } - var length = obj.length; + // `null`, `undefined` and `window` are not array-like + if (obj == null || isWindow(obj)) return false; - if (obj.nodeType === 1 && length) { - return true; - } + // arrays, strings and jQuery/jqLite objects are array like + // * jqLite is either the jQuery or jqLite constructor function + // * we have to check the existence of jqLite first as this method is called + // via the forEach method when constructing the jqLite object in the first place + if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true; + + // Support: iOS 8.2 (not reproducible in simulator) + // "length" in obj used to prevent JIT error (gh-11508) + var length = 'length' in Object(obj) && obj.length; + + // NodeList objects (with `item` method) and + // other objects with suitable length characteristics are array-like + return isNumber(length) && + (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function'); - return isString(obj) || isArray(obj) || length === 0 || - typeof length === 'number' && length > 0 && (length - 1) in obj; } /** * @ngdoc function * @name angular.forEach * @module ng - * @function + * @kind function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an - * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` - * is the value of an object property or an array element and `key` is the object property key or - * array element index. Specifying a `context` for the function is optional. + * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value` + * is the value of an object property or an array element, `key` is the object property key or + * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional. * * It is worth noting that `.forEach` does not iterate over inherited properties because it filters * using the `hasOwnProperty` method. * + * Unlike ES262's + * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18), + * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just + * return the value provided. + * ```js var values = {name: 'misko', gender: 'male'}; var log = []; - angular.forEach(values, function(value, key){ + angular.forEach(values, function(value, key) { this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender: male']); @@ -308,26 +391,42 @@ * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ + function forEach(obj, iterator, context) { - var key; + var key, length; if (obj) { - if (isFunction(obj)){ + if (isFunction(obj)) { for (key in obj) { - // Need to check if hasOwnProperty exists, - // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function - if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) { - iterator.call(context, obj[key], key); + if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) { + iterator.call(context, obj[key], key, obj); + } + } + } else if (isArray(obj) || isArrayLike(obj)) { + var isPrimitive = typeof obj !== 'object'; + for (key = 0, length = obj.length; key < length; key++) { + if (isPrimitive || key in obj) { + iterator.call(context, obj[key], key, obj); } } } else if (obj.forEach && obj.forEach !== forEach) { - obj.forEach(iterator, context); - } else if (isArrayLike(obj)) { - for (key = 0; key < obj.length; key++) - iterator.call(context, obj[key], key); - } else { + obj.forEach(iterator, context, obj); + } else if (isBlankObject(obj)) { + // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty + for (key in obj) { + iterator.call(context, obj[key], key, obj); + } + } else if (typeof obj.hasOwnProperty === 'function') { + // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed for (key in obj) { if (obj.hasOwnProperty(key)) { - iterator.call(context, obj[key], key); + iterator.call(context, obj[key], key, obj); + } + } + } else { + // Slow path for objects which do not have a method `hasOwnProperty` + for (key in obj) { + if (hasOwnProperty.call(obj, key)) { + iterator.call(context, obj[key], key, obj); } } } @@ -335,19 +434,9 @@ return obj; } - function sortedKeys(obj) { - var keys = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - keys.push(key); - } - } - return keys.sort(); - } - function forEachSorted(obj, iterator, context) { - var keys = sortedKeys(obj); - for ( var i = 0; i < keys.length; i++) { + var keys = Object.keys(obj).sort(); + for (var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; @@ -360,37 +449,21 @@ * @returns {function(*, string)} */ function reverseParams(iteratorFn) { - return function(value, key) { iteratorFn(key, value); }; + return function(value, key) {iteratorFn(key, value);}; } /** - * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric - * characters such as '012ABC'. The reason why we are not using simply a number counter is that - * the number string gets longer over time, and it can also overflow, where as the nextId - * will grow much slower, it is a string, and it will never overflow. + * A consistent way of creating unique IDs in angular. * - * @returns {string} an unique alpha-numeric string + * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before + * we hit number precision issues in JavaScript. + * + * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M + * + * @returns {number} an unique alpha-numeric string */ function nextUid() { - var index = uid.length; - var digit; - - while(index) { - index--; - digit = uid[index].charCodeAt(0); - if (digit == 57 /*'9'*/) { - uid[index] = 'A'; - return uid.join(''); - } - if (digit == 90 /*'Z'*/) { - uid[index] = '0'; - } else { - uid[index] = String.fromCharCode(digit + 1); - return uid.join(''); - } - } - uid.unshift('0'); - return uid.join(''); + return ++uid; } @@ -402,54 +475,126 @@ function setHashKey(obj, h) { if (h) { obj.$$hashKey = h; - } - else { + } else { delete obj.$$hashKey; } } + + function baseExtend(dst, objs, deep) { + var h = dst.$$hashKey; + + for (var i = 0, ii = objs.length; i < ii; ++i) { + var obj = objs[i]; + if (!isObject(obj) && !isFunction(obj)) continue; + var keys = Object.keys(obj); + for (var j = 0, jj = keys.length; j < jj; j++) { + var key = keys[j]; + var src = obj[key]; + + if (deep && isObject(src)) { + if (isDate(src)) { + dst[key] = new Date(src.valueOf()); + } else if (isRegExp(src)) { + dst[key] = new RegExp(src); + } else if (src.nodeName) { + dst[key] = src.cloneNode(true); + } else if (isElement(src)) { + dst[key] = src.clone(); + } else { + if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {}; + baseExtend(dst[key], [src], true); + } + } else { + dst[key] = src; + } + } + } + + setHashKey(dst, h); + return dst; + } + /** * @ngdoc function * @name angular.extend * @module ng - * @function + * @kind function * * @description - * Extends the destination object `dst` by copying all of the properties from the `src` object(s) - * to `dst`. You can specify multiple `src` objects. + * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s) + * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so + * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`. + * + * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use + * {@link angular.merge} for this. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ function extend(dst) { - var h = dst.$$hashKey; - forEach(arguments, function(obj){ - if (obj !== dst) { - forEach(obj, function(value, key){ - dst[key] = value; - }); - } - }); + return baseExtend(dst, slice.call(arguments, 1), false); + } - setHashKey(dst,h); - return dst; + + /** + * @ngdoc function + * @name angular.merge + * @module ng + * @kind function + * + * @description + * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s) + * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so + * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`. + * + * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source + * objects, performing a deep copy. + * + * @deprecated + * sinceVersion="1.6.5" + * This function is deprecated, but will not be removed in the 1.x lifecycle. + * There are edge cases (see {@link angular.merge#known-issues known issues}) that are not + * supported by this function. We suggest + * using [lodash's merge()](https://lodash.com/docs/4.17.4#merge) instead. + * + * @knownIssue + * This is a list of (known) object types that are not handled correctly by this function: + * - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) + * - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream) + * - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient) + * - AngularJS {@link $rootScope.Scope scopes}; + * + * @param {Object} dst Destination object. + * @param {...Object} src Source object(s). + * @returns {Object} Reference to `dst`. + */ + function merge(dst) { + return baseExtend(dst, slice.call(arguments, 1), true); } - function int(str) { + + + function toInt(str) { return parseInt(str, 10); } + var isNumberNaN = Number.isNaN || function isNumberNaN(num) { + // eslint-disable-next-line no-self-compare + return num !== num; + }; + function inherit(parent, extra) { - return extend(new (extend(function() {}, {prototype:parent}))(), extra); + return extend(Object.create(parent), extra); } /** * @ngdoc function * @name angular.noop * @module ng - * @function + * @kind function * * @description * A function that performs no operations. This function can be useful when writing code in the @@ -469,7 +614,7 @@ * @ngdoc function * @name angular.identity * @module ng - * @function + * @kind function * * @description * A function that returns its first argument. This function is useful when writing code in the @@ -477,21 +622,38 @@ * ```js function transformer(transformationFn, value) { - return (transformationFn || angular.identity)(value); - }; + return (transformationFn || angular.identity)(value); + }; + + // E.g. + function getResult(fn, input) { + return (fn || angular.identity)(input); + }; + + getResult(function(n) { return n * 2; }, 21); // returns 42 + getResult(null, 21); // returns 21 + getResult(undefined, 21); // returns 21 ``` + * + * @param {*} value to be returned. + * @returns {*} the value passed in. */ function identity($) {return $;} identity.$inject = []; - function valueFn(value) {return function() {return value;};} + function valueFn(value) {return function valueRef() {return value;};} + + function hasCustomToString(obj) { + return isFunction(obj.toString) && obj.toString !== toString; + } + /** * @ngdoc function * @name angular.isUndefined * @module ng - * @function + * @kind function * * @description * Determines if a reference is undefined. @@ -499,14 +661,14 @@ * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ - function isUndefined(value){return typeof value === 'undefined';} + function isUndefined(value) {return typeof value === 'undefined';} /** * @ngdoc function * @name angular.isDefined * @module ng - * @function + * @kind function * * @description * Determines if a reference is defined. @@ -514,14 +676,14 @@ * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ - function isDefined(value){return typeof value !== 'undefined';} + function isDefined(value) {return typeof value !== 'undefined';} /** * @ngdoc function * @name angular.isObject * @module ng - * @function + * @kind function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not @@ -530,14 +692,27 @@ * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ - function isObject(value){return value != null && typeof value === 'object';} + function isObject(value) { + // http://jsperf.com/isobject4 + return value !== null && typeof value === 'object'; + } + + + /** + * Determine if a value is an object with a null prototype + * + * @returns {boolean} True if `value` is an `Object` with a null prototype + */ + function isBlankObject(value) { + return value !== null && typeof value === 'object' && !getPrototypeOf(value); + } /** * @ngdoc function * @name angular.isString * @module ng - * @function + * @kind function * * @description * Determines if a reference is a `String`. @@ -545,29 +720,35 @@ * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ - function isString(value){return typeof value === 'string';} + function isString(value) {return typeof value === 'string';} /** * @ngdoc function * @name angular.isNumber * @module ng - * @function + * @kind function * * @description * Determines if a reference is a `Number`. * + * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`. + * + * If you wish to exclude these then you can use the native + * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite) + * method. + * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ - function isNumber(value){return typeof value === 'number';} + function isNumber(value) {return typeof value === 'number';} /** * @ngdoc function * @name angular.isDate * @module ng - * @function + * @kind function * * @description * Determines if a value is a date. @@ -575,7 +756,7 @@ * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ - function isDate(value){ + function isDate(value) { return toString.call(value) === '[object Date]'; } @@ -584,24 +765,39 @@ * @ngdoc function * @name angular.isArray * @module ng - * @function + * @kind function * * @description - * Determines if a reference is an `Array`. + * Determines if a reference is an `Array`. Alias of Array.isArray. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ - function isArray(value) { - return toString.call(value) === '[object Array]'; - } + var isArray = Array.isArray; + /** + * @description + * Determines if a reference is an `Error`. + * Loosely based on https://www.npmjs.com/package/iserror + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is an `Error`. + */ + function isError(value) { + var tag = toString.call(value); + switch (tag) { + case '[object Error]': return true; + case '[object Exception]': return true; + case '[object DOMException]': return true; + default: return value instanceof Error; + } + } /** * @ngdoc function * @name angular.isFunction * @module ng - * @function + * @kind function * * @description * Determines if a reference is a `Function`. @@ -609,7 +805,7 @@ * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ - function isFunction(value){return typeof value === 'function';} + function isFunction(value) {return typeof value === 'function';} /** @@ -632,7 +828,7 @@ * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { - return obj && obj.document && obj.location && obj.alert && obj.setInterval; + return obj && obj.window === obj; } @@ -646,6 +842,11 @@ } + function isFormData(obj) { + return toString.call(obj) === '[object FormData]'; + } + + function isBlob(obj) { return toString.call(obj) === '[object Blob]'; } @@ -656,26 +857,41 @@ } - var trim = (function() { - // native trim is way faster: http://jsperf.com/angular-trim-test - // but IE doesn't have it... :-( - // TODO: we should move this into IE/ES5 polyfill - if (!String.prototype.trim) { - return function(value) { - return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value; - }; - } - return function(value) { - return isString(value) ? value.trim() : value; - }; - })(); + function isPromiseLike(obj) { + return obj && isFunction(obj.then); + } + + + var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/; + function isTypedArray(value) { + return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value)); + } + + function isArrayBuffer(obj) { + return toString.call(obj) === '[object ArrayBuffer]'; + } + + + var trim = function(value) { + return isString(value) ? value.trim() : value; + }; + +// Copied from: +// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021 +// Prereq: s is a string. + var escapeForRegexp = function(s) { + return s + .replace(/([-()[\]{}+?*.$^|,:#=0) + var index = array.indexOf(value); + if (index >= 0) { array.splice(index, 1); - return value; - } - - function isLeafNode (node) { - if (node) { - switch (node.nodeName) { - case "OPTION": - case "PRE": - case "TITLE": - return true; - } } - return false; + return index; } /** * @ngdoc function * @name angular.copy * @module ng - * @function + * @kind function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. - * * If a destination is provided, all of its elements (for array) or properties (for objects) + * * If a destination is provided, all of its elements (for arrays) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. - * * If `source` is identical to 'destination' an exception will be thrown. + * * If `source` is identical to `destination` an exception will be thrown. + * + *
    + *
    + * Only enumerable properties are taken into account. Non-enumerable properties (both on `source` + * and on `destination`) will be ignored. + *
    * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. @@ -804,105 +962,198 @@ * @returns {*} The copy or updated `destination`, if `destination` was specified. * * @example - + -
    +
    - Name:
    - Email:
    - Gender: male - female
    +
    +
    + Gender: +
    form = {{user | json}}
    -
    master = {{master | json}}
    +
    leader = {{leader | json}}
    + + + // Module: copyExample + angular. + module('copyExample', []). + controller('ExampleController', ['$scope', function($scope) { + $scope.leader = {}; + + $scope.reset = function() { + // Example with 1 argument + $scope.user = angular.copy($scope.leader); + }; - + $scope.reset(); + }]); */ - function copy(source, destination){ - if (isWindow(source) || isScope(source)) { - throw ngMinErr('cpws', - "Can't copy! Making copies of Window or Scope instances is not supported."); + function copy(source, destination, maxDepth) { + var stackSource = []; + var stackDest = []; + maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN; + + if (destination) { + if (isTypedArray(destination) || isArrayBuffer(destination)) { + throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.'); + } + if (source === destination) { + throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.'); + } + + // Empty the destination object + if (isArray(destination)) { + destination.length = 0; + } else { + forEach(destination, function(value, key) { + if (key !== '$$hashKey') { + delete destination[key]; + } + }); + } + + stackSource.push(source); + stackDest.push(destination); + return copyRecurse(source, destination, maxDepth); } - if (!destination) { - destination = source; - if (source) { - if (isArray(source)) { - destination = copy(source, []); - } else if (isDate(source)) { - destination = new Date(source.getTime()); - } else if (isRegExp(source)) { - destination = new RegExp(source.source); - } else if (isObject(source)) { - destination = copy(source, {}); - } + return copyElement(source, maxDepth); + + function copyRecurse(source, destination, maxDepth) { + maxDepth--; + if (maxDepth < 0) { + return '...'; } - } else { - if (source === destination) throw ngMinErr('cpi', - "Can't copy! Source and destination are identical."); + var h = destination.$$hashKey; + var key; if (isArray(source)) { - destination.length = 0; - for ( var i = 0; i < source.length; i++) { - destination.push(copy(source[i])); + for (var i = 0, ii = source.length; i < ii; i++) { + destination.push(copyElement(source[i], maxDepth)); + } + } else if (isBlankObject(source)) { + // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty + for (key in source) { + destination[key] = copyElement(source[key], maxDepth); + } + } else if (source && typeof source.hasOwnProperty === 'function') { + // Slow path, which must rely on hasOwnProperty + for (key in source) { + if (source.hasOwnProperty(key)) { + destination[key] = copyElement(source[key], maxDepth); + } } } else { - var h = destination.$$hashKey; - forEach(destination, function(value, key){ - delete destination[key]; - }); - for ( var key in source) { - destination[key] = copy(source[key]); + // Slowest path --- hasOwnProperty can't be called as a method + for (key in source) { + if (hasOwnProperty.call(source, key)) { + destination[key] = copyElement(source[key], maxDepth); + } } - setHashKey(destination,h); } + setHashKey(destination, h); + return destination; } - return destination; - } - /** - * Create a shallow copy of an object - */ - function shallowCopy(src, dst) { - dst = dst || {}; + function copyElement(source, maxDepth) { + // Simple values + if (!isObject(source)) { + return source; + } + + // Already copied values + var index = stackSource.indexOf(source); + if (index !== -1) { + return stackDest[index]; + } - for(var key in src) { - // shallowCopy is only ever called by $compile nodeLinkFn, which has control over src - // so we don't need to worry about using our custom hasOwnProperty here - if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) { - dst[key] = src[key]; + if (isWindow(source) || isScope(source)) { + throw ngMinErr('cpws', + 'Can\'t copy! Making copies of Window or Scope instances is not supported.'); } + + var needsRecurse = false; + var destination = copyType(source); + + if (destination === undefined) { + destination = isArray(source) ? [] : Object.create(getPrototypeOf(source)); + needsRecurse = true; + } + + stackSource.push(source); + stackDest.push(destination); + + return needsRecurse + ? copyRecurse(source, destination, maxDepth) + : destination; } - return dst; + function copyType(source) { + switch (toString.call(source)) { + case '[object Int8Array]': + case '[object Int16Array]': + case '[object Int32Array]': + case '[object Float32Array]': + case '[object Float64Array]': + case '[object Uint8Array]': + case '[object Uint8ClampedArray]': + case '[object Uint16Array]': + case '[object Uint32Array]': + return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length); + + case '[object ArrayBuffer]': + // Support: IE10 + if (!source.slice) { + // If we're in this case we know the environment supports ArrayBuffer + /* eslint-disable no-undef */ + var copied = new ArrayBuffer(source.byteLength); + new Uint8Array(copied).set(new Uint8Array(source)); + /* eslint-enable */ + return copied; + } + return source.slice(0); + + case '[object Boolean]': + case '[object Number]': + case '[object String]': + case '[object Date]': + return new source.constructor(source.valueOf()); + + case '[object RegExp]': + var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]); + re.lastIndex = source.lastIndex; + return re; + + case '[object Blob]': + return new source.constructor([source], {type: source.type}); + } + + if (isFunction(source.cloneNode)) { + return source.cloneNode(true); + } + } } +// eslint-disable-next-line no-self-compare + function simpleCompare(a, b) { return a === b || (a !== a && b !== b); } + + /** * @ngdoc function * @name angular.equals * @module ng - * @function + * @kind function * * @description * Determines if two objects or two values are equivalent. Supports value types, regular @@ -914,7 +1165,7 @@ * * Both objects or values are of the same type and all of their properties are equal by * comparing them with `angular.equals`. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) - * * Both values represent the same regular expression (In JavasScript, + * * Both values represent the same regular expression (In JavaScript, * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual * representation matches). * @@ -926,54 +1177,171 @@ * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. - */ - function equals(o1, o2) { - if (o1 === o2) return true; - if (o1 === null || o2 === null) return false; - if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN - var t1 = typeof o1, t2 = typeof o2, length, key, keySet; - if (t1 == t2) { - if (t1 == 'object') { - if (isArray(o1)) { - if (!isArray(o2)) return false; - if ((length = o1.length) == o2.length) { - for(key=0; key + +
    +
    +

    User 1

    + Name: + Age: + +

    User 2

    + Name: + Age: + +
    +
    + +
    + User 1:
    {{user1 | json}}
    + User 2:
    {{user2 | json}}
    + Equal:
    {{result}}
    +
    +
    +
    + + angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) { + $scope.user1 = {}; + $scope.user2 = {}; + $scope.compare = function() { + $scope.result = angular.equals($scope.user1, $scope.user2); + }; + }]); + + + */ + function equals(o1, o2) { + if (o1 === o2) return true; + if (o1 === null || o2 === null) return false; + // eslint-disable-next-line no-self-compare + if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN + var t1 = typeof o1, t2 = typeof o2, length, key, keySet; + if (t1 === t2 && t1 === 'object') { + if (isArray(o1)) { + if (!isArray(o2)) return false; + if ((length = o1.length) === o2.length) { + for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) return false; - keySet[key] = true; - } - for(key in o2) { - if (!keySet.hasOwnProperty(key) && - key.charAt(0) !== '$' && - o2[key] !== undefined && - !isFunction(o2[key])) return false; } return true; } + } else if (isDate(o1)) { + if (!isDate(o2)) return false; + return simpleCompare(o1.getTime(), o2.getTime()); + } else if (isRegExp(o1)) { + if (!isRegExp(o2)) return false; + return o1.toString() === o2.toString(); + } else { + if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || + isArray(o2) || isDate(o2) || isRegExp(o2)) return false; + keySet = createMap(); + for (key in o1) { + if (key.charAt(0) === '$' || isFunction(o1[key])) continue; + if (!equals(o1[key], o2[key])) return false; + keySet[key] = true; + } + for (key in o2) { + if (!(key in keySet) && + key.charAt(0) !== '$' && + isDefined(o2[key]) && + !isFunction(o2[key])) return false; + } + return true; } } return false; } + var csp = function() { + if (!isDefined(csp.rules)) { - function csp() { - return (document.securityPolicy && document.securityPolicy.isActive) || - (document.querySelector && - !!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]'))); - } + var ngCspElement = (window.document.querySelector('[ng-csp]') || + window.document.querySelector('[data-ng-csp]')); + + if (ngCspElement) { + var ngCspAttribute = ngCspElement.getAttribute('ng-csp') || + ngCspElement.getAttribute('data-ng-csp'); + csp.rules = { + noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1), + noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1) + }; + } else { + csp.rules = { + noUnsafeEval: noUnsafeEval(), + noInlineStyle: false + }; + } + } + + return csp.rules; + + function noUnsafeEval() { + try { + // eslint-disable-next-line no-new, no-new-func + new Function(''); + return false; + } catch (e) { + return true; + } + } + }; + + /** + * @ngdoc directive + * @module ng + * @name ngJq + * + * @element ANY + * @param {string=} ngJq the name of the library available under `window` + * to be used for angular.element + * @description + * Use this directive to force the angular.element library. This should be + * used to force either jqLite by leaving ng-jq blank or setting the name of + * the jquery variable under window (eg. jQuery). + * + * Since AngularJS looks for this directive when it is loaded (doesn't wait for the + * DOMContentLoaded event), it must be placed on an element that comes before the script + * which loads angular. Also, only the first instance of `ng-jq` will be used and all + * others ignored. + * + * @example + * This example shows how to force jqLite using the `ngJq` directive to the `html` tag. + ```html + + + ... + ... + + ``` + * @example + * This example shows how to use a jQuery based library of a different name. + * The library name must be available at the top most 'window'. + ```html + + + ... + ... + + ``` + */ + var jq = function() { + if (isDefined(jq.name_)) return jq.name_; + var el; + var i, ii = ngAttrPrefixes.length, prefix, name; + for (i = 0; i < ii; ++i) { + prefix = ngAttrPrefixes[i]; + el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]'); + if (el) { + name = el.getAttribute(prefix + 'jq'); + break; + } + } + + return (jq.name_ = name); + }; function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); @@ -984,12 +1352,11 @@ } - /* jshint -W101 */ /** * @ngdoc function * @name angular.bind * @module ng - * @function + * @kind function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for @@ -1002,23 +1369,22 @@ * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ - /* jshint +W101 */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { - return arguments.length - ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) - : fn.apply(self, curryArgs); - } + return arguments.length + ? fn.apply(self, concat(curryArgs, arguments, 0)) + : fn.apply(self, curryArgs); + } : function() { - return arguments.length - ? fn.apply(self, arguments) - : fn.call(self); - }; + return arguments.length + ? fn.apply(self, arguments) + : fn.call(self); + }; } else { - // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) + // In IE, native methods are not functions so they cannot be bound (note: they don't need to be). return fn; } } @@ -1027,11 +1393,11 @@ function toJsonReplacer(key, value) { var val = value; - if (typeof key === 'string' && key.charAt(0) === '$') { + if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; - } else if (value && document === value) { + } else if (value && window.document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; @@ -1045,19 +1411,44 @@ * @ngdoc function * @name angular.toJson * @module ng - * @function + * @kind function * * @description - * Serializes input into a JSON-formatted string. Properties with leading $ characters will be - * stripped since angular uses this notation internally. + * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be + * stripped since AngularJS uses this notation internally. * - * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. - * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. + * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON. + * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace. + * If set to an integer, the JSON output will contain that many spaces per indentation. * @returns {string|undefined} JSON-ified string representing `obj`. + * @knownIssue + * + * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date` + * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the + * `Date.prototype.toJSON` method as follows: + * + * ``` + * var _DatetoJSON = Date.prototype.toJSON; + * Date.prototype.toJSON = function() { + * try { + * return _DatetoJSON.call(this); + * } catch(e) { + * if (e instanceof RangeError) { + * return null; + * } + * throw e; + * } + * }; + * ``` + * + * See https://github.com/angular/angular.js/pull/14221 for more information. */ function toJson(obj, pretty) { - if (typeof obj === 'undefined') return undefined; - return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); + if (isUndefined(obj)) return undefined; + if (!isNumber(pretty)) { + pretty = pretty ? 2 : null; + } + return JSON.stringify(obj, toJsonReplacer, pretty); } @@ -1065,13 +1456,13 @@ * @ngdoc function * @name angular.fromJson * @module ng - * @function + * @kind function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. - * @returns {Object|Array|string|number} Deserialized thingy. + * @returns {Object|Array|string|number} Deserialized JSON string. */ function fromJson(json) { return isString(json) @@ -1080,37 +1471,43 @@ } - function toBoolean(value) { - if (typeof value === 'function') { - value = true; - } else if (value && value.length !== 0) { - var v = lowercase("" + value); - value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); - } else { - value = false; - } - return value; + var ALL_COLONS = /:/g; + function timezoneToOffset(timezone, fallback) { + // Support: IE 9-11 only, Edge 13-15+ + // IE/Edge do not "understand" colon (`:`) in timezone + timezone = timezone.replace(ALL_COLONS, ''); + var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; + return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; + } + + + function addDateMinutes(date, minutes) { + date = new Date(date.getTime()); + date.setMinutes(date.getMinutes() + minutes); + return date; } + + function convertTimezoneToLocal(date, timezone, reverse) { + reverse = reverse ? -1 : 1; + var dateTimezoneOffset = date.getTimezoneOffset(); + var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); + return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset)); + } + + /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { - element = jqLite(element).clone(); - try { - // turns out IE does not let you set .html() on elements which - // are not allowed to have children. So we just ignore it. - element.empty(); - } catch(e) {} - // As Per DOM Standards - var TEXT_NODE = 3; + element = jqLite(element).clone().empty(); var elemHtml = jqLite('
    ').append(element).html(); try { - return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) : + return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) : elemHtml. - match(/^(<[^>]+>)/)[1]. - replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); - } catch(e) { + match(/^(<[^>]+>)/)[1]. + replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);}); + } catch (e) { return lowercase(elemHtml); } @@ -1130,8 +1527,8 @@ function tryDecodeURIComponent(value) { try { return decodeURIComponent(value); - } catch(e) { - // Ignore any invalid uri component + } catch (e) { + // Ignore any invalid uri component. } } @@ -1141,16 +1538,22 @@ * @returns {Object.} */ function parseKeyValue(/**string*/keyValue) { - var obj = {}, key_value, key; - forEach((keyValue || "").split('&'), function(keyValue){ - if ( keyValue ) { - key_value = keyValue.split('='); - key = tryDecodeURIComponent(key_value[0]); - if ( isDefined(key) ) { - var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; - if (!obj[key]) { + var obj = {}; + forEach((keyValue || '').split('&'), function(keyValue) { + var splitPoint, key, val; + if (keyValue) { + key = keyValue = keyValue.replace(/\+/g,'%20'); + splitPoint = keyValue.indexOf('='); + if (splitPoint !== -1) { + key = keyValue.substring(0, splitPoint); + val = keyValue.substring(splitPoint + 1); + } + key = tryDecodeURIComponent(key); + if (isDefined(key)) { + val = isDefined(val) ? tryDecodeURIComponent(val) : true; + if (!hasOwnProperty.call(obj, key)) { obj[key] = val; - } else if(isArray(obj[key])) { + } else if (isArray(obj[key])) { obj[key].push(val); } else { obj[key] = [obj[key],val]; @@ -1167,11 +1570,11 @@ if (isArray(value)) { forEach(value, function(arrayValue) { parts.push(encodeUriQuery(key, true) + - (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); }); } else { parts.push(encodeUriQuery(key, true) + - (value === true ? '' : '=' + encodeUriQuery(value, true))); + (value === true ? '' : '=' + encodeUriQuery(value, true))); } }); return parts.length ? parts.join('&') : ''; @@ -1191,9 +1594,9 @@ */ function encodeUriSegment(val) { return encodeUriQuery(val, true). - replace(/%26/gi, '&'). - replace(/%3D/gi, '='). - replace(/%2B/gi, '+'); + replace(/%26/gi, '&'). + replace(/%3D/gi, '='). + replace(/%2B/gi, '+'); } @@ -1201,7 +1604,7 @@ * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: - * query = *( pchar / "/" / "?" ) + * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG @@ -1210,13 +1613,78 @@ */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); + replace(/%40/gi, '@'). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%3B/gi, ';'). + replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); + } + + var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; + + function getNgAttribute(element, ngAttr) { + var attr, i, ii = ngAttrPrefixes.length; + for (i = 0; i < ii; ++i) { + attr = ngAttrPrefixes[i] + ngAttr; + if (isString(attr = element.getAttribute(attr))) { + return attr; + } + } + return null; + } + + function allowAutoBootstrap(document) { + var script = document.currentScript; + + if (!script) { + // Support: IE 9-11 only + // IE does not have `document.currentScript` + return true; + } + + // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack + if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) { + return false; + } + + var attributes = script.attributes; + var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')]; + + return srcs.every(function(src) { + if (!src) { + return true; + } + if (!src.value) { + return false; + } + + var link = document.createElement('a'); + link.href = src.value; + + if (document.location.origin === link.origin) { + // Same-origin resources are always allowed, even for non-whitelisted schemes. + return true; + } + // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web. + // This is to prevent angular.js bundled with browser extensions from being used to bypass the + // content security policy in web pages and other browser extensions. + switch (link.protocol) { + case 'http:': + case 'https:': + case 'ftp:': + case 'blob:': + case 'file:': + case 'data:': + return true; + default: + return false; + } + }); } +// Cached as it has to run during loading so that document.currentScript is available. + var isAutoBootstrapAllowed = allowAutoBootstrap(window.document); /** * @ngdoc directive @@ -1226,6 +1694,11 @@ * @element ANY * @param {angular.Module} ngApp an optional application * {@link angular.module module} name to load. + * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be + * created in "strict-di" mode. This means that the application will fail to invoke functions which + * do not use explicit function annotation (and are thus unsuitable for minification), as described + * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in + * tracking down the root of these bugs. * * @description * @@ -1233,13 +1706,20 @@ * designates the **root element** of the application and is typically placed near the root element * of the page - e.g. on the `` or `` tags. * - * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` - * found in the document will be used to define the root element to auto-bootstrap as an - * application. To run multiple applications in an HTML document you must manually bootstrap them using - * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. + * There are a few things to keep in mind when using `ngApp`: + * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` + * found in the document will be used to define the root element to auto-bootstrap as an + * application. To run multiple applications in an HTML document you must manually bootstrap them using + * {@link angular.bootstrap} instead. + * - AngularJS applications cannot be nested within each other. + * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`. + * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and + * {@link ngRoute.ngView `ngView`}. + * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector}, + * causing animations to stop working and making the injector inaccessible from outside the app. * * You can specify an **AngularJS module** to be used as the root module for the application. This - * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and + * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It * should contain the application code needed or have dependencies on other modules that will * contain the code. See {@link angular.module} for more information. * @@ -1247,9 +1727,13 @@ * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` * would not be resolved to `3`. * - * `ngApp` is the easiest, and most common, way to bootstrap an application. + * @example + * + * ### Simple Usage + * + * `ngApp` is the easiest, and most common way to bootstrap an application. * - +
    I can add: {{a}} + {{b}} = {{ a+b }} @@ -1263,48 +1747,118 @@ * + * @example + * + * ### With `ngStrictDi` + * + * Using `ngStrictDi`, you would see something like this: + * + + +
    +
    + I can add: {{a}} + {{b}} = {{ a+b }} + +

    This renders because the controller does not fail to + instantiate, by using explicit annotation style (see + script.js for details) +

    +
    + +
    + Name:
    + Hello, {{name}}! + +

    This renders because the controller does not fail to + instantiate, by using explicit annotation style + (see script.js for details) +

    +
    + +
    + I can add: {{a}} + {{b}} = {{ a+b }} + +

    The controller could not be instantiated, due to relying + on automatic function annotations (which are disabled in + strict mode). As such, the content of this section is not + interpolated, and there should be an error in your web console. +

    +
    +
    +
    + + angular.module('ngAppStrictDemo', []) + // BadController will fail to instantiate, due to relying on automatic function annotation, + // rather than an explicit annotation + .controller('BadController', function($scope) { + $scope.a = 1; + $scope.b = 2; + }) + // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated, + // due to using explicit annotations using the array style and $inject property, respectively. + .controller('GoodController1', ['$scope', function($scope) { + $scope.a = 1; + $scope.b = 2; + }]) + .controller('GoodController2', GoodController2); + function GoodController2($scope) { + $scope.name = 'World'; + } + GoodController2.$inject = ['$scope']; + + + div[ng-controller] { + margin-bottom: 1em; + -webkit-border-radius: 4px; + border-radius: 4px; + border: 1px solid; + padding: .5em; + } + div[ng-controller^=Good] { + border-color: #d6e9c6; + background-color: #dff0d8; + color: #3c763d; + } + div[ng-controller^=Bad] { + border-color: #ebccd1; + background-color: #f2dede; + color: #a94442; + margin-bottom: 0; + } + +
    */ function angularInit(element, bootstrap) { - var elements = [element], - appElement, + var appElement, module, - names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], - NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; + config = {}; - function append(element) { - element && elements.push(element); - } + // The element `element` has priority over any other element. + forEach(ngAttrPrefixes, function(prefix) { + var name = prefix + 'app'; - forEach(names, function(name) { - names[name] = true; - append(document.getElementById(name)); - name = name.replace(':', '\\:'); - if (element.querySelectorAll) { - forEach(element.querySelectorAll('.' + name), append); - forEach(element.querySelectorAll('.' + name + '\\:'), append); - forEach(element.querySelectorAll('[' + name + ']'), append); + if (!appElement && element.hasAttribute && element.hasAttribute(name)) { + appElement = element; + module = element.getAttribute(name); } }); + forEach(ngAttrPrefixes, function(prefix) { + var name = prefix + 'app'; + var candidate; - forEach(elements, function(element) { - if (!appElement) { - var className = ' ' + element.className + ' '; - var match = NG_APP_CLASS_REGEXP.exec(className); - if (match) { - appElement = element; - module = (match[2] || '').replace(/\s+/g, ','); - } else { - forEach(element.attributes, function(attr) { - if (!appElement && names[attr.name]) { - appElement = element; - module = attr.value; - } - }); - } + if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) { + appElement = candidate; + module = candidate.getAttribute(name); } }); if (appElement) { - bootstrap(appElement, module ? [module] : []); + if (!isAutoBootstrapAllowed) { + window.console.error('AngularJS: disabling automatic bootstrap. - *
    - * - * - * - * - * - * - * - *
    {{heading}}
    {{fill}}
    + * ```html + * + * + * + *
    + * {{greeting}} *
    - * - * - * var app = angular.module('multi-bootstrap', []) * - * .controller('BrokenTable', function($scope) { - * $scope.headings = ['One', 'Two', 'Three']; - * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]]; - * }); - * - * - * it('should only insert one table cell for each item in $scope.fillings', function() { - * expect(element.all(by.css('td')).count()) - * .toBe(9); - * }); - * - * + * + * + * + * + * ``` * - * @param {DOMElement} element DOM element which is the root of angular application. + * @param {DOMElement} element DOM element which is the root of AngularJS application. * @param {Array=} modules an array of modules to load into the application. * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. + * function that will be invoked by the injector as a `config` block. * See: {@link angular.module modules} + * @param {Object=} config an object for defining configuration options for the application. The + * following keys are supported: + * + * * `strictDi` - disable automatic function annotation for the application. This is meant to + * assist in finding bugs which break minified code. Defaults to `false`. + * * @returns {auto.$injector} Returns the newly created injector for this app. */ - function bootstrap(element, modules) { + function bootstrap(element, modules, config) { + if (!isObject(config)) config = {}; + var defaultConfig = { + strictDi: false + }; + config = extend(defaultConfig, config); var doBootstrap = function() { element = jqLite(element); if (element.injector()) { - var tag = (element[0] === document) ? 'document' : startingTag(element); - throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag); + var tag = (element[0] === window.document) ? 'document' : startingTag(element); + // Encode angle brackets to prevent input from being sanitized to empty string #8683. + throw ngMinErr( + 'btstrpd', + 'App already bootstrapped with this element \'{0}\'', + tag.replace(//,'>')); } modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); + + if (config.debugInfoEnabled) { + // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`. + modules.push(['$compileProvider', function($compileProvider) { + $compileProvider.debugInfoEnabled(true); + }]); + } + modules.unshift('ng'); - var injector = createInjector(modules); - injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate', - function(scope, element, compile, injector, animate) { - scope.$apply(function() { - element.data('$injector', injector); - compile(element)(scope); - }); - }] + var injector = createInjector(modules, config.strictDi); + injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', + function bootstrapApply(scope, element, compile, injector) { + scope.$apply(function() { + element.data('$injector', injector); + compile(element)(scope); + }); + }] ); return injector; }; + var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/; var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; + if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) { + config.debugInfoEnabled = true; + window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, ''); + } + if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { return doBootstrap(); } @@ -1399,40 +1981,104 @@ forEach(extraModules, function(module) { modules.push(module); }); - doBootstrap(); + return doBootstrap(); }; + + if (isFunction(angular.resumeDeferredBootstrap)) { + angular.resumeDeferredBootstrap(); + } + } + + /** + * @ngdoc function + * @name angular.reloadWithDebugInfo + * @module ng + * @description + * Use this function to reload the current application with debug information turned on. + * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`. + * + * See {@link ng.$compileProvider#debugInfoEnabled} for more. + */ + function reloadWithDebugInfo() { + window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name; + window.location.reload(); + } + + /** + * @name angular.getTestability + * @module ng + * @description + * Get the testability service for the instance of AngularJS on the given + * element. + * @param {DOMElement} element DOM element which is the root of AngularJS application. + */ + function getTestability(rootElement) { + var injector = angular.element(rootElement).injector(); + if (!injector) { + throw ngMinErr('test', + 'no injector found for element argument to getTestability'); + } + return injector.get('$$testability'); } var SNAKE_CASE_REGEXP = /[A-Z]/g; - function snake_case(name, separator){ + function snake_case(name, separator) { separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } + var bindJQueryFired = false; function bindJQuery() { + var originalCleanData; + + if (bindJQueryFired) { + return; + } + // bind to jQuery if present; - jQuery = window.jQuery; - // reset to jQuery or default to us. - if (jQuery) { + var jqName = jq(); + jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present) + !jqName ? undefined : // use jqLite + window[jqName]; // use jQuery specified by `ngJq` + + // Use jQuery if it exists with proper functionality, otherwise default to us. + // AngularJS 1.2+ requires jQuery 1.7+ for on()/off() support. + // AngularJS 1.3+ technically requires at least jQuery 2.1+ but it may work with older + // versions. It will not work for sure with jQuery <1.7, though. + if (jQuery && jQuery.fn.on) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, isolateScope: JQLitePrototype.isolateScope, - controller: JQLitePrototype.controller, + controller: /** @type {?} */ (JQLitePrototype).controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); - // Method signature: - // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) - jqLitePatchJQueryRemove('remove', true, true, false); - jqLitePatchJQueryRemove('empty', false, false, false); - jqLitePatchJQueryRemove('html', false, false, true); + + // All nodes removed from the DOM via various jQuery APIs like .remove() + // are passed through jQuery.cleanData. Monkey-patch this method to fire + // the $destroy event on all removed nodes. + originalCleanData = jQuery.cleanData; + jQuery.cleanData = function(elems) { + var events; + for (var i = 0, elem; (elem = elems[i]) != null; i++) { + events = jQuery._data(elem, 'events'); + if (events && events.$destroy) { + jQuery(elem).triggerHandler('$destroy'); + } + } + originalCleanData(elems); + }; } else { jqLite = JQLite; } + angular.element = jqLite; + + // Prevent double-proxying. + bindJQueryFired = true; } /** @@ -1440,7 +2086,7 @@ */ function assertArg(arg, name, reason) { if (!arg) { - throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); + throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required')); } return arg; } @@ -1451,7 +2097,7 @@ } assertArg(isFunction(arg), name, 'not a function, got ' + - (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); + (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } @@ -1462,7 +2108,7 @@ */ function assertNotHasOwnProperty(name, context) { if (name === 'hasOwnProperty') { - throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); + throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); } } @@ -1496,34 +2142,77 @@ /** * Return the DOM siblings between the first and last node in the given array. * @param {Array} array like object - * @returns {DOMElement} object containing the elements + * @returns {Array} the inputted object or a jqLite collection containing the nodes */ - function getBlockElements(nodes) { - var startNode = nodes[0], - endNode = nodes[nodes.length - 1]; - if (startNode === endNode) { - return jqLite(startNode); + function getBlockNodes(nodes) { + // TODO(perf): update `nodes` instead of creating a new object? + var node = nodes[0]; + var endNode = nodes[nodes.length - 1]; + var blockNodes; + + for (var i = 1; node !== endNode && (node = node.nextSibling); i++) { + if (blockNodes || nodes[i] !== node) { + if (!blockNodes) { + blockNodes = jqLite(slice.call(nodes, 0, i)); + } + blockNodes.push(node); + } } - var element = startNode; - var elements = [element]; + return blockNodes || nodes; + } + + + /** + * Creates a new object without a prototype. This object is useful for lookup without having to + * guard against prototypically inherited properties via hasOwnProperty. + * + * Related micro-benchmarks: + * - http://jsperf.com/object-create2 + * - http://jsperf.com/proto-map-lookup/2 + * - http://jsperf.com/for-in-vs-object-keys2 + * + * @returns {Object} + */ + function createMap() { + return Object.create(null); + } - do { - element = element.nextSibling; - if (!element) break; - elements.push(element); - } while (element !== endNode); + function stringify(value) { + if (value == null) { // null || undefined + return ''; + } + switch (typeof value) { + case 'string': + break; + case 'number': + value = '' + value; + break; + default: + if (hasCustomToString(value) && !isArray(value) && !isDate(value)) { + value = value.toString(); + } else { + value = toJson(value); + } + } - return jqLite(elements); + return value; } + var NODE_TYPE_ELEMENT = 1; + var NODE_TYPE_ATTRIBUTE = 2; + var NODE_TYPE_TEXT = 3; + var NODE_TYPE_COMMENT = 8; + var NODE_TYPE_DOCUMENT = 9; + var NODE_TYPE_DOCUMENT_FRAGMENT = 11; + /** * @ngdoc type * @name angular.Module * @module ng * @description * - * Interface for configuring angular {@link angular.module modules}. + * Interface for configuring AngularJS {@link angular.module modules}. */ function setupModuleLoader(window) { @@ -1550,18 +2239,18 @@ * @module ng * @description * - * The `angular.module` is a global place for creating, registering and retrieving Angular + * The `angular.module` is a global place for creating, registering and retrieving AngularJS * modules. - * All modules (angular core or 3rd party) that should be available to an application must be + * All modules (AngularJS core or 3rd party) that should be available to an application must be * registered using this mechanism. * - * When passed two or more arguments, a new module is created. If passed only one argument, an - * existing module (the name passed as the first argument to `module`) is retrieved. + * Passing one argument retrieves an existing {@link angular.Module}, + * whereas passing more than one argument creates a new {@link angular.Module} * * * # Module * - * A module is a collection of services, directives, filters, and configuration information. + * A module is a collection of services, directives, controllers, filters, and configuration information. * `angular.module` is used to configure the {@link auto.$injector $injector}. * * ```js @@ -1573,9 +2262,9 @@ * * // configure existing services inside initialization blocks. * myModule.config(['$locationProvider', function($locationProvider) { - * // Configure existing providers - * $locationProvider.hashPrefix('!'); - * }]); + * // Configure existing providers + * $locationProvider.hashPrefix('!'); + * }]); * ``` * * Then you can create an injector and load your modules like this: @@ -1589,13 +2278,16 @@ * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. - <<<<<* @param {!Array.=} requires If specified then new module is being created. If - >>>>>* unspecified then the module is being retrieved for further configuration. - * @param {Function} configFn Optional configuration function for the module. Same as + * @param {!Array.=} requires If specified then new module is being created. If + * unspecified then the module is being retrieved for further configuration. + * @param {Function=} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. - * @returns {module} new module with the {@link angular.Module} api. + * @returns {angular.Module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { + + var info = {}; + var assertNotHasOwnProperty = function(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); @@ -1608,42 +2300,86 @@ } return ensure(modules, name, function() { if (!requires) { - throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + - "the module name or forgot to load it. If registering a module ensure that you " + - "specify the dependencies as the second argument.", name); + throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' + + 'the module name or forgot to load it. If registering a module ensure that you ' + + 'specify the dependencies as the second argument.', name); } /** @type {!Array.>} */ var invokeQueue = []; + /** @type {!Array.} */ + var configBlocks = []; + /** @type {!Array.} */ var runBlocks = []; - var config = invokeLater('$injector', 'invoke'); + var config = invokeLater('$injector', 'invoke', 'push', configBlocks); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, + _configBlocks: configBlocks, _runBlocks: runBlocks, /** - * @ngdoc property - * @name angular.Module#requires + * @ngdoc method + * @name angular.Module#info * @module ng - * @returns {Array.} List of module names which must be loaded before this module. + * + * @param {Object=} info Information about the module + * @returns {Object|Module} The current info object for this module if called as a getter, + * or `this` if called as a setter. + * * @description - * Holds the list of modules which the injector will load before the current module is - * loaded. + * Read and write custom information about this module. + * For example you could put the version of the module in here. + * + * ```js + * angular.module('myModule', []).info({ version: '1.0.0' }); + * ``` + * + * The version could then be read back out by accessing the module elsewhere: + * + * ``` + * var version = angular.module('myModule').info().version; + * ``` + * + * You can also retrieve this information during runtime via the + * {@link $injector#modules `$injector.modules`} property: + * + * ```js + * var version = $injector.modules['myModule'].info().version; + * ``` */ - requires: requires, - + info: function(value) { + if (isDefined(value)) { + if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value'); + info = value; + return this; + } + return info; + }, + + /** + * @ngdoc property + * @name angular.Module#requires + * @module ng + * + * @description + * Holds the list of modules which the injector will load before the current module is + * loaded. + */ + requires: requires, + /** * @ngdoc property * @name angular.Module#name * @module ng - * @returns {string} Name of the module. + * * @description + * Name of the module. */ name: name, @@ -1658,7 +2394,7 @@ * @description * See {@link auto.$provide#provider $provide.provider()}. */ - provider: invokeLater('$provide', 'provider'), + provider: invokeLaterAndSetModuleName('$provide', 'provider'), /** * @ngdoc method @@ -1669,7 +2405,7 @@ * @description * See {@link auto.$provide#factory $provide.factory()}. */ - factory: invokeLater('$provide', 'factory'), + factory: invokeLaterAndSetModuleName('$provide', 'factory'), /** * @ngdoc method @@ -1680,7 +2416,7 @@ * @description * See {@link auto.$provide#service $provide.service()}. */ - service: invokeLater('$provide', 'service'), + service: invokeLaterAndSetModuleName('$provide', 'service'), /** * @ngdoc method @@ -1700,11 +2436,23 @@ * @param {string} name constant name * @param {*} object Constant value. * @description - * Because the constant are fixed, they get applied before other provide methods. + * Because the constants are fixed, they get applied before other provide methods. * See {@link auto.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), + /** + * @ngdoc method + * @name angular.Module#decorator + * @module ng + * @param {string} name The name of the service to decorate. + * @param {Function} decorFn This function will be invoked when the service needs to be + * instantiated and should return the decorated service instance. + * @description + * See {@link auto.$provide#decorator $provide.decorator()}. + */ + decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks), + /** * @ngdoc method * @name angular.Module#animation @@ -1718,37 +2466,44 @@ * * * Defines an animation hook that can be later used with - * {@link ngAnimate.$animate $animate} service and directives that use this service. + * {@link $animate $animate} service and directives that use this service. * * ```js * module.animation('.animation-name', function($inject1, $inject2) { - * return { - * eventName : function(element, done) { - * //code to run the animation - * //once complete, then run done() - * return function cancellationFunction(element) { - * //code to cancel the animation - * } - * } - * } - * }) + * return { + * eventName : function(element, done) { + * //code to run the animation + * //once complete, then run done() + * return function cancellationFunction(element) { + * //code to cancel the animation + * } + * } + * } + * }) * ``` * - * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and + * See {@link ng.$animateProvider#register $animateProvider.register()} and * {@link ngAnimate ngAnimate module} for more information. */ - animation: invokeLater('$animateProvider', 'register'), + animation: invokeLaterAndSetModuleName('$animateProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @module ng - * @param {string} name Filter name. + * @param {string} name Filter name - this must be a valid AngularJS expression identifier * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. + * + *
    + * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`. + * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace + * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores + * (`myapp_subsection_filterx`). + *
    */ - filter: invokeLater('$filterProvider', 'register'), + filter: invokeLaterAndSetModuleName('$filterProvider', 'register'), /** * @ngdoc method @@ -1760,7 +2515,7 @@ * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ - controller: invokeLater('$controllerProvider', 'register'), + controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'), /** * @ngdoc method @@ -1773,7 +2528,20 @@ * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ - directive: invokeLater('$compileProvider', 'directive'), + directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'), + + /** + * @ngdoc method + * @name angular.Module#component + * @module ng + * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp) + * @param {Object} options Component definition object (a simplified + * {@link ng.$compile#directive-definition-object directive definition object}) + * + * @description + * See {@link ng.$compileProvider#component $compileProvider.component()}. + */ + component: invokeLaterAndSetModuleName('$compileProvider', 'component'), /** * @ngdoc method @@ -1782,7 +2550,15 @@ * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description - * Use this method to register work which needs to be performed on module loading. + * Use this method to configure services by injecting their + * {@link angular.Module#provider `providers`}, e.g. for adding routes to the + * {@link ngRoute.$routeProvider $routeProvider}. + * + * Note that you can only inject {@link angular.Module#provider `providers`} and + * {@link angular.Module#constant `constants`} into this function. + * + * For more about how to configure services, see + * {@link providers#provider-recipe Provider Recipe}. */ config: config, @@ -1806,7 +2582,7 @@ config(configFn); } - return moduleInstance; + return moduleInstance; /** * @param {string} provider @@ -1814,9 +2590,24 @@ * @param {String=} insertMethod * @returns {angular.Module} */ - function invokeLater(provider, method, insertMethod) { + function invokeLater(provider, method, insertMethod, queue) { + if (!queue) queue = invokeQueue; return function() { - invokeQueue[insertMethod || 'push']([provider, method, arguments]); + queue[insertMethod || 'push']([provider, method, arguments]); + return moduleInstance; + }; + } + + /** + * @param {string} provider + * @param {string} method + * @returns {angular.Module} + */ + function invokeLaterAndSetModuleName(provider, method, queue) { + if (!queue) queue = invokeQueue; + return function(recipeName, factoryFunction) { + if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name; + queue.push([provider, method, arguments]); return moduleInstance; }; } @@ -1826,82 +2617,165 @@ } - /* global - angularModule: true, - version: true, - - $LocaleProvider, - $CompileProvider, - - htmlAnchorDirective, - inputDirective, - inputDirective, - formDirective, - scriptDirective, - selectDirective, - styleDirective, - optionDirective, - ngBindDirective, - ngBindHtmlDirective, - ngBindTemplateDirective, - ngClassDirective, - ngClassEvenDirective, - ngClassOddDirective, - ngCspDirective, - ngCloakDirective, - ngControllerDirective, - ngFormDirective, - ngHideDirective, - ngIfDirective, - ngIncludeDirective, - ngIncludeFillContentDirective, - ngInitDirective, - ngNonBindableDirective, - ngPluralizeDirective, - ngRepeatDirective, - ngShowDirective, - ngStyleDirective, - ngSwitchDirective, - ngSwitchWhenDirective, - ngSwitchDefaultDirective, - ngOptionsDirective, - ngTranscludeDirective, - ngModelDirective, - ngListDirective, - ngChangeDirective, - requiredDirective, - requiredDirective, - ngValueDirective, - ngAttributeAliasDirectives, - ngEventDirectives, - - $AnchorScrollProvider, - $AnimateProvider, - $BrowserProvider, - $CacheFactoryProvider, - $ControllerProvider, - $DocumentProvider, - $ExceptionHandlerProvider, - $FilterProvider, - $InterpolateProvider, - $IntervalProvider, - $HttpProvider, - $HttpBackendProvider, - $LocationProvider, - $LogProvider, - $ParseProvider, - $RootScopeProvider, - $QProvider, - $$SanitizeUriProvider, - $SceProvider, - $SceDelegateProvider, - $SnifferProvider, - $TemplateCacheProvider, - $TimeoutProvider, - $$RAFProvider, - $$AsyncCallbackProvider, - $WindowProvider + /* global shallowCopy: true */ + + /** + * Creates a shallow copy of an object, an array or a primitive. + * + * Assumes that there are no proto properties for objects. */ + function shallowCopy(src, dst) { + if (isArray(src)) { + dst = dst || []; + + for (var i = 0, ii = src.length; i < ii; i++) { + dst[i] = src[i]; + } + } else if (isObject(src)) { + dst = dst || {}; + + for (var key in src) { + if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { + dst[key] = src[key]; + } + } + } + + return dst || src; + } + + /* exported toDebugString */ + + function serializeObject(obj, maxDepth) { + var seen = []; + + // There is no direct way to stringify object until reaching a specific depth + // and a very deep object can cause a performance issue, so we copy the object + // based on this specific depth and then stringify it. + if (isValidObjectMaxDepth(maxDepth)) { + // This file is also included in `angular-loader`, so `copy()` might not always be available in + // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed. + obj = angular.copy(obj, null, maxDepth); + } + return JSON.stringify(obj, function(key, val) { + val = toJsonReplacer(key, val); + if (isObject(val)) { + + if (seen.indexOf(val) >= 0) return '...'; + + seen.push(val); + } + return val; + }); + } + + function toDebugString(obj, maxDepth) { + if (typeof obj === 'function') { + return obj.toString().replace(/ \{[\s\S]*$/, ''); + } else if (isUndefined(obj)) { + return 'undefined'; + } else if (typeof obj !== 'string') { + return serializeObject(obj, maxDepth); + } + return obj; + } + + /* global angularModule: true, + version: true, + + $CompileProvider, + + htmlAnchorDirective, + inputDirective, + inputDirective, + formDirective, + scriptDirective, + selectDirective, + optionDirective, + ngBindDirective, + ngBindHtmlDirective, + ngBindTemplateDirective, + ngClassDirective, + ngClassEvenDirective, + ngClassOddDirective, + ngCloakDirective, + ngControllerDirective, + ngFormDirective, + ngHideDirective, + ngIfDirective, + ngIncludeDirective, + ngIncludeFillContentDirective, + ngInitDirective, + ngNonBindableDirective, + ngPluralizeDirective, + ngRepeatDirective, + ngShowDirective, + ngStyleDirective, + ngSwitchDirective, + ngSwitchWhenDirective, + ngSwitchDefaultDirective, + ngOptionsDirective, + ngTranscludeDirective, + ngModelDirective, + ngListDirective, + ngChangeDirective, + patternDirective, + patternDirective, + requiredDirective, + requiredDirective, + minlengthDirective, + minlengthDirective, + maxlengthDirective, + maxlengthDirective, + ngValueDirective, + ngModelOptionsDirective, + ngAttributeAliasDirectives, + ngEventDirectives, + + $AnchorScrollProvider, + $AnimateProvider, + $CoreAnimateCssProvider, + $$CoreAnimateJsProvider, + $$CoreAnimateQueueProvider, + $$AnimateRunnerFactoryProvider, + $$AnimateAsyncRunFactoryProvider, + $BrowserProvider, + $CacheFactoryProvider, + $ControllerProvider, + $DateProvider, + $DocumentProvider, + $$IsDocumentHiddenProvider, + $ExceptionHandlerProvider, + $FilterProvider, + $$ForceReflowProvider, + $InterpolateProvider, + $IntervalProvider, + $HttpProvider, + $HttpParamSerializerProvider, + $HttpParamSerializerJQLikeProvider, + $HttpBackendProvider, + $xhrFactoryProvider, + $jsonpCallbacksProvider, + $LocationProvider, + $LogProvider, + $$MapProvider, + $ParseProvider, + $RootScopeProvider, + $QProvider, + $$QProvider, + $$SanitizeUriProvider, + $SceProvider, + $SceDelegateProvider, + $SnifferProvider, + $TemplateCacheProvider, + $TemplateRequestProvider, + $$TestabilityProvider, + $TimeoutProvider, + $$RAFProvider, + $WindowProvider, + $$jqLiteProvider, + $$CookieReaderProvider +*/ /** @@ -1909,8 +2783,9 @@ * @name angular.version * @module ng * @description - * An object that contains information about the current AngularJS version. This object has the - * following properties: + * An object that contains information about the current AngularJS version. + * + * This object has the following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". @@ -1919,28 +2794,32 @@ * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { - full: '1.2.16', // all of these placeholder strings will be replaced by grunt's - major: 1, // package task - minor: 2, - dot: 16, - codeName: 'badger-enumeration' + // These placeholder strings will be replaced by grunt's `build` task. + // They need to be double- or single-quoted. + full: '1.6.9', + major: 1, + minor: 6, + dot: 9, + codeName: 'fiery-basilisk' }; - function publishExternalAPI(angular){ + function publishExternalAPI(angular) { extend(angular, { + 'errorHandlingConfig': errorHandlingConfig, 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, + 'merge': merge, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, - 'noop':noop, - 'bind':bind, + 'noop': noop, + 'bind': bind, 'toJson': toJson, 'fromJson': fromJson, - 'identity':identity, + 'identity': identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, @@ -1953,17 +2832,17 @@ 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, - 'callbacks': {counter: 0}, + 'callbacks': {$$counter: 0}, + 'getTestability': getTestability, + 'reloadWithDebugInfo': reloadWithDebugInfo, '$$minErr': minErr, - '$$csp': csp + '$$csp': csp, + '$$encodeUriSegment': encodeUriSegment, + '$$encodeUriQuery': encodeUriQuery, + '$$stringify': stringify }); angularModule = setupModuleLoader(window); - try { - angularModule('ngLocale'); - } catch (e) { - angularModule('ngLocale', []).provider('$locale', $LocaleProvider); - } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { @@ -1972,88 +2851,120 @@ $$sanitizeUri: $$SanitizeUriProvider }); $provide.provider('$compile', $CompileProvider). - directive({ - a: htmlAnchorDirective, - input: inputDirective, - textarea: inputDirective, - form: formDirective, - script: scriptDirective, - select: selectDirective, - style: styleDirective, - option: optionDirective, - ngBind: ngBindDirective, - ngBindHtml: ngBindHtmlDirective, - ngBindTemplate: ngBindTemplateDirective, - ngClass: ngClassDirective, - ngClassEven: ngClassEvenDirective, - ngClassOdd: ngClassOddDirective, - ngCloak: ngCloakDirective, - ngController: ngControllerDirective, - ngForm: ngFormDirective, - ngHide: ngHideDirective, - ngIf: ngIfDirective, - ngInclude: ngIncludeDirective, - ngInit: ngInitDirective, - ngNonBindable: ngNonBindableDirective, - ngPluralize: ngPluralizeDirective, - ngRepeat: ngRepeatDirective, - ngShow: ngShowDirective, - ngStyle: ngStyleDirective, - ngSwitch: ngSwitchDirective, - ngSwitchWhen: ngSwitchWhenDirective, - ngSwitchDefault: ngSwitchDefaultDirective, - ngOptions: ngOptionsDirective, - ngTransclude: ngTranscludeDirective, - ngModel: ngModelDirective, - ngList: ngListDirective, - ngChange: ngChangeDirective, - required: requiredDirective, - ngRequired: requiredDirective, - ngValue: ngValueDirective - }). - directive({ - ngInclude: ngIncludeFillContentDirective - }). - directive(ngAttributeAliasDirectives). - directive(ngEventDirectives); + directive({ + a: htmlAnchorDirective, + input: inputDirective, + textarea: inputDirective, + form: formDirective, + script: scriptDirective, + select: selectDirective, + option: optionDirective, + ngBind: ngBindDirective, + ngBindHtml: ngBindHtmlDirective, + ngBindTemplate: ngBindTemplateDirective, + ngClass: ngClassDirective, + ngClassEven: ngClassEvenDirective, + ngClassOdd: ngClassOddDirective, + ngCloak: ngCloakDirective, + ngController: ngControllerDirective, + ngForm: ngFormDirective, + ngHide: ngHideDirective, + ngIf: ngIfDirective, + ngInclude: ngIncludeDirective, + ngInit: ngInitDirective, + ngNonBindable: ngNonBindableDirective, + ngPluralize: ngPluralizeDirective, + ngRepeat: ngRepeatDirective, + ngShow: ngShowDirective, + ngStyle: ngStyleDirective, + ngSwitch: ngSwitchDirective, + ngSwitchWhen: ngSwitchWhenDirective, + ngSwitchDefault: ngSwitchDefaultDirective, + ngOptions: ngOptionsDirective, + ngTransclude: ngTranscludeDirective, + ngModel: ngModelDirective, + ngList: ngListDirective, + ngChange: ngChangeDirective, + pattern: patternDirective, + ngPattern: patternDirective, + required: requiredDirective, + ngRequired: requiredDirective, + minlength: minlengthDirective, + ngMinlength: minlengthDirective, + maxlength: maxlengthDirective, + ngMaxlength: maxlengthDirective, + ngValue: ngValueDirective, + ngModelOptions: ngModelOptionsDirective + }). + directive({ + ngInclude: ngIncludeFillContentDirective + }). + directive(ngAttributeAliasDirectives). + directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $animate: $AnimateProvider, + $animateCss: $CoreAnimateCssProvider, + $$animateJs: $$CoreAnimateJsProvider, + $$animateQueue: $$CoreAnimateQueueProvider, + $$AnimateRunner: $$AnimateRunnerFactoryProvider, + $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, + $$isDocumentHidden: $$IsDocumentHiddenProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, + $$forceReflow: $$ForceReflowProvider, $interpolate: $InterpolateProvider, $interval: $IntervalProvider, $http: $HttpProvider, + $httpParamSerializer: $HttpParamSerializerProvider, + $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider, $httpBackend: $HttpBackendProvider, + $xhrFactory: $xhrFactoryProvider, + $jsonpCallbacks: $jsonpCallbacksProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $rootScope: $RootScopeProvider, $q: $QProvider, + $$q: $$QProvider, $sce: $SceProvider, $sceDelegate: $SceDelegateProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, + $templateRequest: $TemplateRequestProvider, + $$testability: $$TestabilityProvider, $timeout: $TimeoutProvider, $window: $WindowProvider, $$rAF: $$RAFProvider, - $$asyncCallback : $$AsyncCallbackProvider + $$jqLite: $$jqLiteProvider, + $$Map: $$MapProvider, + $$cookieReader: $$CookieReaderProvider }); } - ]); + ]) + .info({ angularVersion: '1.6.9' }); } - /* global + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Any commits to this file should be reviewed with security in mind. * + * Changes to this file can potentially create security vulnerabilities. * + * An approval from 2 Core members with history of modifying * + * this file is required. * + * * + * Does the change somehow allow for arbitrary javascript to be executed? * + * Or allows for someone to change the prototype of built-in objects? * + * Or gives undesired access to variables likes document or window? * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - -JQLitePrototype, - -addEventListenerFn, - -removeEventListenerFn, - -BOOLEAN_ATTR - */ + /* global + JQLitePrototype: true, + BOOLEAN_ATTR: true, + ALIASED_ATTR: true +*/ ////////////////////////////////// //JQLite @@ -2063,37 +2974,45 @@ * @ngdoc function * @name angular.element * @module ng - * @function + * @kind function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * * If jQuery is available, `angular.element` is an alias for the * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` - * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." + * delegates to AngularJS's built-in subset of jQuery, called "jQuery lite" or **jqLite**. + * + * jqLite is a tiny, API-compatible subset of jQuery that allows + * AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most + * commonly needed functionality with the goal of having a very small footprint. * - *
    jqLite is a tiny, API-compatible subset of jQuery that allows - * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most - * commonly needed functionality with the goal of having a very small footprint.
    + * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the + * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a + * specific version of jQuery if multiple versions exist on the page. * - * To use jQuery, simply load it before `DOMContentLoaded` event fired. + *
    **Note:** All element references in AngularJS are always wrapped with jQuery or + * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.
    * - *
    **Note:** all element references in Angular are always wrapped with jQuery or - * jqLite; they are never raw DOM references.
    + *
    **Note:** Keep in mind that this function will not find elements + * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)` + * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.
    * - * ## Angular's jqLite + * ## AngularJS's jqLite * jqLite provides only the following jQuery methods: * - * - [`addClass()`](http://api.jquery.com/addClass/) + * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument * - [`after()`](http://api.jquery.com/after/) * - [`append()`](http://api.jquery.com/append/) - * - [`attr()`](http://api.jquery.com/attr/) - * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData + * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters + * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData * - [`children()`](http://api.jquery.com/children/) - Does not support selectors * - [`clone()`](http://api.jquery.com/clone/) * - [`contents()`](http://api.jquery.com/contents/) - * - [`css()`](http://api.jquery.com/css/) + * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. + * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing. * - [`data()`](http://api.jquery.com/data/) + * - [`detach()`](http://api.jquery.com/detach/) * - [`empty()`](http://api.jquery.com/empty/) * - [`eq()`](http://api.jquery.com/eq/) * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name @@ -2101,26 +3020,26 @@ * - [`html()`](http://api.jquery.com/html/) * - [`next()`](http://api.jquery.com/next/) - Does not support selectors * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData - * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors + * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors * - [`prepend()`](http://api.jquery.com/prepend/) * - [`prop()`](http://api.jquery.com/prop/) - * - [`ready()`](http://api.jquery.com/ready/) + * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`) * - [`remove()`](http://api.jquery.com/remove/) - * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - * - [`removeClass()`](http://api.jquery.com/removeClass/) + * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes + * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument * - [`removeData()`](http://api.jquery.com/removeData/) * - [`replaceWith()`](http://api.jquery.com/replaceWith/) * - [`text()`](http://api.jquery.com/text/) - * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. - * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces + * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument + * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers + * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter * - [`val()`](http://api.jquery.com/val/) * - [`wrap()`](http://api.jquery.com/wrap/) * * ## jQuery/jqLite Extras - * Angular also provides the following additional methods and events to both jQuery and jqLite: + * AngularJS also provides the following additional methods and events to both jQuery and jqLite: * * ### Events * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event @@ -2134,31 +3053,31 @@ * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current - * element or its parent. + * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to + * be enabled. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the * current element. This getter should be used only on elements that contain a directive which starts a new isolate * scope. Calling `scope()` on this element always returns the original non-isolate scope. + * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * + * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See + * https://github.com/angular/angular.js/issues/14251 for more information. + * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ + JQLite.expando = 'ng339'; + var jqCache = JQLite.cache = {}, - jqName = JQLite.expando = 'ng-' + new Date().getTime(), - jqId = 1, - addEventListenerFn = (window.document.addEventListener - ? function(element, type, fn) {element.addEventListener(type, fn, false);} - : function(element, type, fn) {element.attachEvent('on' + type, fn);}), - removeEventListenerFn = (window.document.removeEventListener - ? function(element, type, fn) {element.removeEventListener(type, fn, false); } - : function(element, type, fn) {element.detachEvent('on' + type, fn); }); + jqId = 1; /* - * !!! This is an undocumented "private" function !!! - */ - var jqData = JQLite._data = function(node) { + * !!! This is an undocumented "private" function !!! + */ + JQLite._data = function(node) { //jQuery always returns an object on cache miss return this.cache[node[this.expando]] || {}; }; @@ -2166,70 +3085,37 @@ function jqNextId() { return ++jqId; } - var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; - var MOZ_HACK_REGEXP = /^moz([A-Z])/; + var DASH_LOWERCASE_REGEXP = /-([a-z])/g; + var MS_HACK_REGEXP = /^-ms-/; + var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' }; var jqLiteMinErr = minErr('jqLite'); /** - * Converts snake_case to camelCase. - * Also there is special case for Moz prefix starting with upper case letter. + * Converts kebab-case to camelCase. + * There is also a special case for the ms prefix starting with a lowercase letter. * @param name Name to normalize */ - function camelCase(name) { - return name. - replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { - return offset ? letter.toUpperCase() : letter; - }). - replace(MOZ_HACK_REGEXP, 'Moz$1'); + function cssKebabToCamel(name) { + return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-')); } -///////////////////////////////////////////// -// jQuery mutation patch -// -// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a -// $destroy event on all DOM nodes being removed. -// -///////////////////////////////////////////// + function fnCamelCaseReplace(all, letter) { + return letter.toUpperCase(); + } - function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) { - var originalJqFn = jQuery.fn[name]; - originalJqFn = originalJqFn.$original || originalJqFn; - removePatch.$original = originalJqFn; - jQuery.fn[name] = removePatch; - - function removePatch(param) { - // jshint -W040 - var list = filterElems && param ? [this.filter(param)] : [this], - fireEvent = dispatchThis, - set, setIndex, setLength, - element, childIndex, childLength, children; - - if (!getterIfNoArguments || param != null) { - while(list.length) { - set = list.shift(); - for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { - element = jqLite(set[setIndex]); - if (fireEvent) { - element.triggerHandler('$destroy'); - } else { - fireEvent = !fireEvent; - } - for(childIndex = 0, childLength = (children = element.children()).length; - childIndex < childLength; - childIndex++) { - list.push(jQuery(children[childIndex])); - } - } - } - } - return originalJqFn.apply(this, arguments); - } + /** + * Converts kebab-case to camelCase. + * @param name Name to normalize + */ + function kebabToCamel(name) { + return name + .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace); } - var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; + var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/; var HTML_REGEXP = /<|&#?\w+;/; - var TAG_NAME_REGEXP = /<([\w:]+)/; - var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi; + var TAG_NAME_REGEXP = /<([\w:-]+)/; + var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi; var wrapMap = { 'option': [1, ''], @@ -2238,33 +3124,46 @@ 'col': [2, '', '
    '], 'tr': [2, '', '
    '], 'td': [3, '', '
    '], - '_default': [0, "", ""] + '_default': [0, '', ''] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; + function jqLiteIsTextNode(html) { return !HTML_REGEXP.test(html); } + function jqLiteAcceptsData(node) { + // The window object can accept data but has no nodeType + // Otherwise we are only interested in elements (1) and documents (9) + var nodeType = node.nodeType; + return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT; + } + + function jqLiteHasData(node) { + for (var key in jqCache[node.ng339]) { + return true; + } + return false; + } + function jqLiteBuildFragment(html, context) { - var elem, tmp, tag, wrap, + var tmp, tag, wrap, fragment = context.createDocumentFragment(), - nodes = [], i, j, jj; + nodes = [], i; if (jqLiteIsTextNode(html)) { // Convert non-html into a text node nodes.push(context.createTextNode(html)); } else { - tmp = fragment.appendChild(context.createElement('div')); // Convert html into DOM nodes - tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase(); + tmp = fragment.appendChild(context.createElement('div')); + tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase(); wrap = wrapMap[tag] || wrapMap._default; - tmp.innerHTML = '
     
    ' + - wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1>") + wrap[2]; - tmp.removeChild(tmp.firstChild); + tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1>') + wrap[2]; // Descend through wrappers to the right content i = wrap[0]; @@ -2272,48 +3171,77 @@ tmp = tmp.lastChild; } - for (j=0, jj=tmp.childNodes.length; j 0)) { + element.removeEventListener(type, handle); delete events[type]; - } else { - arrayRemove(events[type] || [], fn); + } + }; + + forEach(type.split(' '), function(type) { + removeHandler(type); + if (MOUSE_EVENT_MAP[type]) { + removeHandler(MOUSE_EVENT_MAP[type]); } }); } } function jqLiteRemoveData(element, name) { - var expandoId = element[jqName], - expandoStore = jqCache[expandoId]; + var expandoId = element.ng339; + var expandoStore = expandoId && jqCache[expandoId]; if (expandoStore) { if (name) { - delete jqCache[expandoId].data[name]; + delete expandoStore.data[name]; return; } if (expandoStore.handle) { - expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); + if (expandoStore.events.$destroy) { + expandoStore.handle({}, '$destroy'); + } jqLiteOff(element); } delete jqCache[expandoId]; - element[jqName] = undefined; // ie does not allow deletion of attributes on elements. + element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it } } - function jqLiteExpandoStore(element, key, value) { - var expandoId = element[jqName], - expandoStore = jqCache[expandoId || -1]; - if (isDefined(value)) { - if (!expandoStore) { - element[jqName] = expandoId = jqNextId(); - expandoStore = jqCache[expandoId] = {}; - } - expandoStore[key] = value; - } else { - return expandoStore && expandoStore[key]; + function jqLiteExpandoStore(element, createIfNecessary) { + var expandoId = element.ng339, + expandoStore = expandoId && jqCache[expandoId]; + + if (createIfNecessary && !expandoStore) { + element.ng339 = expandoId = jqNextId(); + expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined}; } + + return expandoStore; } + function jqLiteData(element, key, value) { - var data = jqLiteExpandoStore(element, 'data'), - isSetter = isDefined(value), - keyDefined = !isSetter && isDefined(key), - isSimpleGetter = keyDefined && !isObject(key); + if (jqLiteAcceptsData(element)) { + var prop; - if (!data && !isSimpleGetter) { - jqLiteExpandoStore(element, 'data', data = {}); - } + var isSimpleSetter = isDefined(value); + var isSimpleGetter = !isSimpleSetter && key && !isObject(key); + var massGetter = !key; + var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter); + var data = expandoStore && expandoStore.data; - if (isSetter) { - data[key] = value; - } else { - if (keyDefined) { - if (isSimpleGetter) { - // don't create data in this case. - return data && data[key]; + if (isSimpleSetter) { // data('key', value) + data[kebabToCamel(key)] = value; + } else { + if (massGetter) { // data() + return data; } else { - extend(data, key); + if (isSimpleGetter) { // data('key') + // don't force creation of expandoStore if it doesn't exist yet + return data && data[kebabToCamel(key)]; + } else { // mass-setter: data({key1: val1, key2: val2}) + for (prop in key) { + data[kebabToCamel(prop)] = key[prop]; + } + } } - } else { - return data; } } } function jqLiteHasClass(element, selector) { if (!element.getAttribute) return false; - return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " "). - indexOf( " " + selector + " " ) > -1); + return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' '). + indexOf(' ' + selector + ' ') > -1); } function jqLiteRemoveClass(element, cssClasses) { if (cssClasses && element.setAttribute) { + var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') + .replace(/[\n\t]/g, ' '); + var newClasses = existingClasses; + forEach(cssClasses.split(' '), function(cssClass) { - element.setAttribute('class', trim( - (" " + (element.getAttribute('class') || '') + " ") - .replace(/[\n\t]/g, " ") - .replace(" " + trim(cssClass) + " ", " ")) - ); + cssClass = trim(cssClass); + newClasses = newClasses.replace(' ' + cssClass + ' ', ' '); }); + + if (newClasses !== existingClasses) { + element.setAttribute('class', trim(newClasses)); + } } } function jqLiteAddClass(element, cssClasses) { if (cssClasses && element.setAttribute) { var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') - .replace(/[\n\t]/g, " "); + .replace(/[\n\t]/g, ' '); + var newClasses = existingClasses; forEach(cssClasses.split(' '), function(cssClass) { cssClass = trim(cssClass); - if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { - existingClasses += cssClass + ' '; + if (newClasses.indexOf(' ' + cssClass + ' ') === -1) { + newClasses += cssClass + ' '; } }); - element.setAttribute('class', trim(existingClasses)); + if (newClasses !== existingClasses) { + element.setAttribute('class', trim(newClasses)); + } } } + function jqLiteAddNodes(root, elements) { + // THIS CODE IS VERY HOT. Don't make changes without benchmarking. + if (elements) { - elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) - ? elements - : [ elements ]; - for(var i=0; i < elements.length; i++) { - root.push(elements[i]); + + // if a Node (the most common case) + if (elements.nodeType) { + root[root.length++] = elements; + } else { + var length = elements.length; + + // if an Array or NodeList and not a Window + if (typeof length === 'number' && elements.window !== elements) { + if (length) { + for (var i = 0; i < length; i++) { + root[root.length++] = elements[i]; + } + } + } else { + root[root.length++] = elements; + } } } } + function jqLiteController(element, name) { - return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); + return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller'); } function jqLiteInheritedData(element, name, value) { - element = jqLite(element); - // if element is the document object work with the html element instead // this makes $(document).scope() possible - if(element[0].nodeType == 9) { - element = element.find('html'); + if (element.nodeType === NODE_TYPE_DOCUMENT) { + element = element.documentElement; } var names = isArray(name) ? name : [name]; - while (element.length) { - var node = element[0]; + while (element) { for (var i = 0, ii = names.length; i < ii; i++) { - if ((value = element.data(names[i])) !== undefined) return value; + if (isDefined(value = jqLite.data(element, names[i]))) return value; } // If dealing with a document fragment node with a host element, and no parent, use the host // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM // to lookup parent controllers. - element = jqLite(node.parentNode || (node.nodeType === 11 && node.host)); + element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host); } } function jqLiteEmpty(element) { - for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { - jqLiteDealoc(childNodes[i]); - } + jqLiteDealoc(element, true); while (element.firstChild) { element.removeChild(element.firstChild); } } + function jqLiteRemove(element, keepData) { + if (!keepData) jqLiteDealoc(element); + var parent = element.parentNode; + if (parent) parent.removeChild(element); + } + + + function jqLiteDocumentLoaded(action, win) { + win = win || window; + if (win.document.readyState === 'complete') { + // Force the action to be run async for consistent behavior + // from the action's point of view + // i.e. it will definitely not be in a $apply + win.setTimeout(action); + } else { + // No need to unbind this handler as load is only ever called once + jqLite(win).on('load', action); + } + } + + function jqLiteReady(fn) { + function trigger() { + window.document.removeEventListener('DOMContentLoaded', trigger); + window.removeEventListener('load', trigger); + fn(); + } + + // check if document is already loaded + if (window.document.readyState === 'complete') { + window.setTimeout(fn); + } else { + // We can not use jqLite since we are not done loading and jQuery could be loaded later. + + // Works for modern browsers and IE9 + window.document.addEventListener('DOMContentLoaded', trigger); + + // Fallback to window.onload for others + window.addEventListener('load', trigger); + } + } + ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { - ready: function(fn) { - var fired = false; - - function trigger() { - if (fired) return; - fired = true; - fn(); - } - - // check if document already is loaded - if (document.readyState === 'complete'){ - setTimeout(trigger); - } else { - this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 - // we can not use jqLite since we are not done loading and jQuery could be loaded later. - // jshint -W064 - JQLite(window).on('load', trigger); // fallback to window.onload for others - // jshint +W064 - } - }, + ready: jqLiteReady, toString: function() { var value = []; - forEach(this, function(e){ value.push('' + e);}); + forEach(this, function(e) { value.push('' + e);}); return '[' + value.join(', ') + ']'; }, @@ -2547,29 +3534,54 @@ }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { - BOOLEAN_ELEMENTS[uppercase(value)] = true; + BOOLEAN_ELEMENTS[value] = true; }); + var ALIASED_ATTR = { + 'ngMinlength': 'minlength', + 'ngMaxlength': 'maxlength', + 'ngMin': 'min', + 'ngMax': 'max', + 'ngPattern': 'pattern', + 'ngStep': 'step' + }; function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access - return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; + return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr; + } + + function getAliasedAttrName(name) { + return ALIASED_ATTR[name]; } + forEach({ + data: jqLiteData, + removeData: jqLiteRemoveData, + hasData: jqLiteHasData, + cleanData: function jqLiteCleanData(nodes) { + for (var i = 0, ii = nodes.length; i < ii; i++) { + jqLiteRemoveData(nodes[i]); + } + } + }, function(fn, name) { + JQLite[name] = fn; + }); + forEach({ data: jqLiteData, inheritedData: jqLiteInheritedData, scope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! - return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); + return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); }, isolateScope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! - return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate'); + return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); }, controller: jqLiteController, @@ -2578,61 +3590,50 @@ return jqLiteInheritedData(element, '$injector'); }, - removeAttr: function(element,name) { + removeAttr: function(element, name) { element.removeAttribute(name); }, hasClass: jqLiteHasClass, css: function(element, name, value) { - name = camelCase(name); + name = cssKebabToCamel(name); if (isDefined(value)) { element.style[name] = value; } else { - var val; + return element.style[name]; + } + }, - if (msie <= 8) { - // this is some IE specific weirdness that jQuery 1.6.4 does not sure why - val = element.currentStyle && element.currentStyle[name]; - if (val === '') val = 'auto'; - } + attr: function(element, name, value) { + var ret; + var nodeType = element.nodeType; + if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT || + !element.getAttribute) { + return; + } - val = val || element.style[name]; + var lowercasedName = lowercase(name); + var isBooleanAttr = BOOLEAN_ATTR[lowercasedName]; + + if (isDefined(value)) { + // setter - if (msie <= 8) { - // jquery weirdness :-/ - val = (val === '') ? undefined : val; + if (value === null || (value === false && isBooleanAttr)) { + element.removeAttribute(name); + } else { + element.setAttribute(name, isBooleanAttr ? lowercasedName : value); } + } else { + // getter - return val; - } - }, + ret = element.getAttribute(name); - attr: function(element, name, value){ - var lowercasedName = lowercase(name); - if (BOOLEAN_ATTR[lowercasedName]) { - if (isDefined(value)) { - if (!!value) { - element[name] = true; - element.setAttribute(name, lowercasedName); - } else { - element[name] = false; - element.removeAttribute(lowercasedName); - } - } else { - return (element[name] || - (element.attributes.getNamedItem(name)|| noop).specified) - ? lowercasedName - : undefined; - } - } else if (isDefined(value)) { - element.setAttribute(name, value); - } else if (element.getAttribute) { - // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code - // some elements (e.g. Document) don't have get attribute, so return undefined - var ret = element.getAttribute(name, 2); - // normalize non-existing attributes to undefined (as jQuery) + if (isBooleanAttr && ret !== null) { + ret = lowercasedName; + } + // Normalize non-existing attributes to undefined (as jQuery). return ret === null ? undefined : ret; } }, @@ -2646,36 +3647,28 @@ }, text: (function() { - var NODE_TYPE_TEXT_PROPERTY = []; - if (msie < 9) { - NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/ - NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/ - } else { - NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/ - NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/ - } getText.$dv = ''; return getText; function getText(element, value) { - var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType]; if (isUndefined(value)) { - return textProp ? element[textProp] : ''; + var nodeType = element.nodeType; + return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : ''; } - element[textProp] = value; + element.textContent = value; } })(), val: function(element, value) { if (isUndefined(value)) { - if (nodeName_(element) === 'SELECT' && element.multiple) { + if (element.multiple && nodeName_(element) === 'select') { var result = []; - forEach(element.options, function (option) { + forEach(element.options, function(option) { if (option.selected) { result.push(option.value || option.text); } }); - return result.length === 0 ? null : result; + return result; } return element.value; } @@ -2686,29 +3679,28 @@ if (isUndefined(value)) { return element.innerHTML; } - for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { - jqLiteDealoc(childNodes[i]); - } + jqLiteDealoc(element, true); element.innerHTML = value; }, empty: jqLiteEmpty - }, function(fn, name){ + }, function(fn, name) { /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; + var nodeCount = this.length; // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. // jqLiteEmpty takes no arguments but is a setter. if (fn !== jqLiteEmpty && - (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { + (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values - for (i = 0; i < this.length; i++) { + for (i = 0; i < nodeCount; i++) { if (fn === jqLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); @@ -2722,9 +3714,10 @@ return this; } else { // we are a read, so read the first child. + // TODO: do we still need this? var value = fn.$dv; // Only if we have $dv do we iterate over all, otherwise it is just the first element. - var jj = (value === undefined) ? Math.min(this.length, 1) : this.length; + var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount; for (var j = 0; j < jj; j++) { var nodeValue = fn(this[j], arg1, arg2); value = value ? value + nodeValue : nodeValue; @@ -2733,7 +3726,7 @@ } } else { // we are a write, so apply to all children - for (i = 0; i < this.length; i++) { + for (i = 0; i < nodeCount; i++) { fn(this[i], arg1, arg2); } // return self for chaining @@ -2743,61 +3736,73 @@ }); function createEventHandler(element, events) { - var eventHandler = function (event, type) { - if (!event.preventDefault) { - event.preventDefault = function() { - event.returnValue = false; //ie - }; - } + var eventHandler = function(event, type) { + // jQuery specific api + event.isDefaultPrevented = function() { + return event.defaultPrevented; + }; - if (!event.stopPropagation) { - event.stopPropagation = function() { - event.cancelBubble = true; //ie - }; - } + var eventFns = events[type || event.type]; + var eventFnsLength = eventFns ? eventFns.length : 0; - if (!event.target) { - event.target = event.srcElement || document; - } + if (!eventFnsLength) return; + + if (isUndefined(event.immediatePropagationStopped)) { + var originalStopImmediatePropagation = event.stopImmediatePropagation; + event.stopImmediatePropagation = function() { + event.immediatePropagationStopped = true; - if (isUndefined(event.defaultPrevented)) { - var prevent = event.preventDefault; - event.preventDefault = function() { - event.defaultPrevented = true; - prevent.call(event); + if (event.stopPropagation) { + event.stopPropagation(); + } + + if (originalStopImmediatePropagation) { + originalStopImmediatePropagation.call(event); + } }; - event.defaultPrevented = false; } - event.isDefaultPrevented = function() { - return event.defaultPrevented || event.returnValue === false; + event.isImmediatePropagationStopped = function() { + return event.immediatePropagationStopped === true; }; - // Copy event handlers in case event handlers array is modified during execution. - var eventHandlersCopy = shallowCopy(events[type || event.type] || []); + // Some events have special handlers that wrap the real handler + var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper; - forEach(eventHandlersCopy, function(fn) { - fn.call(element, event); - }); + // Copy event handlers in case event handlers array is modified during execution. + if ((eventFnsLength > 1)) { + eventFns = shallowCopy(eventFns); + } - // Remove monkey-patched methods (IE), - // as they would cause memory leaks in IE8. - if (msie <= 8) { - // IE7/8 does not allow to delete property on native object - event.preventDefault = null; - event.stopPropagation = null; - event.isDefaultPrevented = null; - } else { - // It shouldn't affect normal browsers (native methods are defined on prototype). - delete event.preventDefault; - delete event.stopPropagation; - delete event.isDefaultPrevented; + for (var i = 0; i < eventFnsLength; i++) { + if (!event.isImmediatePropagationStopped()) { + handlerWrapper(element, event, eventFns[i]); + } } }; + + // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all + // events on `element` eventHandler.elem = element; return eventHandler; } + function defaultHandlerWrapper(element, event, handler) { + handler.call(element, event); + } + + function specialMouseHandlerWrapper(target, event, handler) { + // Refer to jQuery's implementation of mouseenter & mouseleave + // Read about mouseenter and mouseleave: + // http://www.quirksmode.org/js/events_mouse.html#link8 + var related = event.relatedTarget; + // 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 && !jqLiteContains.call(target, related))) { + handler.call(target, event); + } + } + ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single @@ -2806,68 +3811,49 @@ forEach({ removeData: jqLiteRemoveData, - dealoc: jqLiteDealoc, - - on: function onFn(element, type, fn, unsupported){ + on: function jqLiteOn(element, type, fn, unsupported) { if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); - var events = jqLiteExpandoStore(element, 'events'), - handle = jqLiteExpandoStore(element, 'handle'); + // Do not add event handlers to non-elements because they will not be cleaned up. + if (!jqLiteAcceptsData(element)) { + return; + } + + var expandoStore = jqLiteExpandoStore(element, true); + var events = expandoStore.events; + var handle = expandoStore.handle; - if (!events) jqLiteExpandoStore(element, 'events', events = {}); - if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); + if (!handle) { + handle = expandoStore.handle = createEventHandler(element, events); + } + + // http://jsperf.com/string-indexof-vs-split + var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type]; + var i = types.length; - forEach(type.split(' '), function(type){ + var addHandler = function(type, specialHandlerWrapper, noEventListener) { var eventFns = events[type]; if (!eventFns) { - if (type == 'mouseenter' || type == 'mouseleave') { - var contains = document.body.contains || document.body.compareDocumentPosition ? - function( a, b ) { - // jshint bitwise: false - 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; - }; - - events[type] = []; + eventFns = events[type] = []; + eventFns.specialHandlerWrapper = specialHandlerWrapper; + if (type !== '$destroy' && !noEventListener) { + element.addEventListener(type, handle); + } + } - // Refer to jQuery's implementation of mouseenter & mouseleave - // Read about mouseenter and mouseleave: - // http://www.quirksmode.org/js/events_mouse.html#link8 - var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}; + eventFns.push(fn); + }; - onFn(element, eventmap[type], function(event) { - var target = this, related = event.relatedTarget; - // 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 && !contains(target, related)) ){ - handle(event, type); - } - }); - - } else { - addEventListenerFn(element, type, handle); - events[type] = []; - } - eventFns = events[type]; + while (i--) { + type = types[i]; + if (MOUSE_EVENT_MAP[type]) { + addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper); + addHandler(type, undefined, true); + } else { + addHandler(type); } - eventFns.push(fn); - }); + } }, off: jqLiteOff, @@ -2888,7 +3874,7 @@ replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; jqLiteDealoc(element); - forEach(new JQLite(replaceNode), function(node){ + forEach(new JQLite(replaceNode), function(node) { if (index) { parent.insertBefore(node, index.nextSibling); } else { @@ -2900,9 +3886,10 @@ children: function(element) { var children = []; - forEach(element.childNodes, function(element){ - if (element.nodeType === 1) + forEach(element.childNodes, function(element) { + if (element.nodeType === NODE_TYPE_ELEMENT) { children.push(element); + } }); return children; }, @@ -2912,43 +3899,48 @@ }, append: function(element, node) { - forEach(new JQLite(node), function(child){ - if (element.nodeType === 1 || element.nodeType === 11) { - element.appendChild(child); - } - }); + var nodeType = element.nodeType; + if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return; + + node = new JQLite(node); + + for (var i = 0, ii = node.length; i < ii; i++) { + var child = node[i]; + element.appendChild(child); + } }, prepend: function(element, node) { - if (element.nodeType === 1) { + if (element.nodeType === NODE_TYPE_ELEMENT) { var index = element.firstChild; - forEach(new JQLite(node), function(child){ + forEach(new JQLite(node), function(child) { element.insertBefore(child, index); }); } }, wrap: function(element, wrapNode) { - wrapNode = jqLite(wrapNode)[0]; - var parent = element.parentNode; - if (parent) { - parent.replaceChild(wrapNode, element); - } - wrapNode.appendChild(element); + jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]); }, - remove: function(element) { - jqLiteDealoc(element); - var parent = element.parentNode; - if (parent) parent.removeChild(element); + remove: jqLiteRemove, + + detach: function(element) { + jqLiteRemove(element, true); }, after: function(element, newElement) { var index = element, parent = element.parentNode; - forEach(new JQLite(newElement), function(node){ - parent.insertBefore(node, index.nextSibling); - index = node; - }); + + if (parent) { + newElement = new JQLite(newElement); + + for (var i = 0, ii = newElement.length; i < ii; i++) { + var node = newElement[i]; + parent.insertBefore(node, index.nextSibling); + index = node; + } + } }, addClass: jqLiteAddClass, @@ -2956,7 +3948,7 @@ toggleClass: function(element, selector, condition) { if (selector) { - forEach(selector.split(' '), function(className){ + forEach(selector.split(' '), function(className) { var classCondition = condition; if (isUndefined(classCondition)) { classCondition = !jqLiteHasClass(element, className); @@ -2968,20 +3960,11 @@ parent: function(element) { var parent = element.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; + return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null; }, next: function(element) { - if (element.nextElementSibling) { - return element.nextElementSibling; - } - - // IE8 doesn't have nextElementSibling - var elm = element.nextSibling; - while (elm != null && elm.nodeType !== 1) { - elm = elm.nextSibling; - } - return elm; + return element.nextElementSibling; }, find: function(element, selector) { @@ -2994,27 +3977,50 @@ clone: jqLiteClone, - triggerHandler: function(element, eventName, eventData) { - var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName]; + triggerHandler: function(element, event, extraParameters) { + + var dummyEvent, eventFnsCopy, handlerArgs; + var eventName = event.type || event; + var expandoStore = jqLiteExpandoStore(element); + var events = expandoStore && expandoStore.events; + var eventFns = events && events[eventName]; + + if (eventFns) { + // Create a dummy event to pass to the handlers + dummyEvent = { + preventDefault: function() { this.defaultPrevented = true; }, + isDefaultPrevented: function() { return this.defaultPrevented === true; }, + stopImmediatePropagation: function() { this.immediatePropagationStopped = true; }, + isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; }, + stopPropagation: noop, + type: eventName, + target: element + }; - eventData = eventData || []; + // If a custom event was provided then extend our dummy event with it + if (event.type) { + dummyEvent = extend(dummyEvent, event); + } - var event = [{ - preventDefault: noop, - stopPropagation: noop - }]; + // Copy event handlers in case event handlers array is modified during execution. + eventFnsCopy = shallowCopy(eventFns); + handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; - forEach(eventFns, function(fn) { - fn.apply(element, event.concat(eventData)); - }); + forEach(eventFnsCopy, function(fn) { + if (!dummyEvent.isImmediatePropagationStopped()) { + fn.apply(element, handlerArgs); + } + }); + } } - }, function(fn, name){ + }, function(fn, name) { /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2, arg3) { var value; - for(var i=0; i < this.length; i++) { + + for (var i = 0, ii = this.length; i < ii; i++) { if (isUndefined(value)) { value = fn(this[i], arg1, arg2, arg3); if (isDefined(value)) { @@ -3027,12 +4033,34 @@ } return isDefined(value) ? value : this; }; - - // bind legacy bind/unbind to on/off - JQLite.prototype.bind = JQLite.prototype.on; - JQLite.prototype.unbind = JQLite.prototype.off; }); +// bind legacy bind/unbind to on/off + JQLite.prototype.bind = JQLite.prototype.on; + JQLite.prototype.unbind = JQLite.prototype.off; + + +// Provider for private $$jqLite service + /** @this */ + function $$jqLiteProvider() { + this.$get = function $$jqLite() { + return extend(JQLite, { + hasClass: function(node, classes) { + if (node.attr) node = node[0]; + return jqLiteHasClass(node, classes); + }, + addClass: function(node, classes) { + if (node.attr) node = node[0]; + return jqLiteAddClass(node, classes); + }, + removeClass: function(node, classes) { + if (node.attr) node = node[0]; + return jqLiteRemoveClass(node, classes); + } + }); + }; + } + /** * Computes a hash of an 'obj'. * Hash of a: @@ -3045,73 +4073,108 @@ * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ - function hashKey(obj) { - var objType = typeof obj, - key; + function hashKey(obj, nextUidFn) { + var key = obj && obj.$$hashKey; - if (objType == 'object' && obj !== null) { - if (typeof (key = obj.$$hashKey) == 'function') { - // must invoke on object to keep the right this + if (key) { + if (typeof key === 'function') { key = obj.$$hashKey(); - } else if (key === undefined) { - key = obj.$$hashKey = nextUid(); } + return key; + } + + var objType = typeof obj; + if (objType === 'function' || (objType === 'object' && obj !== null)) { + key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)(); } else { - key = obj; + key = objType + ':' + obj; } - return objType + ':' + key; + return key; } - /** - * HashMap which can use objects as keys - */ - function HashMap(array){ - forEach(array, this.put, this); +// A minimal ES2015 Map implementation. +// Should be bug/feature equivalent to the native implementations of supported browsers +// (for the features required in Angular). +// See https://kangax.github.io/compat-table/es6/#test-Map + var nanKey = Object.create(null); + function NgMapShim() { + this._keys = []; + this._values = []; + this._lastKey = NaN; + this._lastIndex = -1; } - HashMap.prototype = { - /** - * Store key value pair - * @param key key to store can be any type - * @param value value to store can be any type - */ - put: function(key, value) { - this[hashKey(key)] = value; + NgMapShim.prototype = { + _idx: function(key) { + if (key === this._lastKey) { + return this._lastIndex; + } + this._lastKey = key; + this._lastIndex = this._keys.indexOf(key); + return this._lastIndex; + }, + _transformKey: function(key) { + return isNumberNaN(key) ? nanKey : key; }, - - /** - * @param key - * @returns {Object} the value for the key - */ get: function(key) { - return this[hashKey(key)]; + key = this._transformKey(key); + var idx = this._idx(key); + if (idx !== -1) { + return this._values[idx]; + } }, + set: function(key, value) { + key = this._transformKey(key); + var idx = this._idx(key); + if (idx === -1) { + idx = this._lastIndex = this._keys.length; + } + this._keys[idx] = key; + this._values[idx] = value; - /** - * Remove the key/value pair - * @param key - */ - remove: function(key) { - var value = this[key = hashKey(key)]; - delete this[key]; - return value; + // Support: IE11 + // Do not `return this` to simulate the partial IE11 implementation + }, + delete: function(key) { + key = this._transformKey(key); + var idx = this._idx(key); + if (idx === -1) { + return false; + } + this._keys.splice(idx, 1); + this._values.splice(idx, 1); + this._lastKey = NaN; + this._lastIndex = -1; + return true; } }; +// For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations +// are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map` +// implementations get more stable, we can reconsider switching to `window.Map` (when available). + var NgMap = NgMapShim; + + var $$MapProvider = [/** @this */function() { + this.$get = [function() { + return NgMap; + }]; + }]; + /** * @ngdoc function * @module ng * @name angular.injector - * @function + * @kind function * * @description - * Creates an injector function that can be used for retrieving services as well as for + * Creates an injector object that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * - * @param {Array.} modules A list of module functions or their aliases. See - * {@link angular.module}. The `ng` module must be explicitly added. - * @returns {function()} Injector function. See {@link auto.$injector $injector}. + * {@link angular.module}. The `ng` module must be explicitly added. + * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which + * disallows argument name annotation inference. + * @returns {injector} Injector object. See {@link auto.$injector $injector}. * * @example * Typical usage @@ -3121,15 +4184,15 @@ * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection - * $injector.invoke(function($rootScope, $compile, $document){ - * $compile($document)($rootScope); - * $rootScope.$digest(); - * }); + * $injector.invoke(function($rootScope, $compile, $document) { + * $compile($document)($rootScope); + * $rootScope.$digest(); + * }); * ``` * - * Sometimes you want to get access to the injector of a currently running Angular app - * from outside Angular. Perhaps, you want to inject and compile some markup after the - * application has been bootstrapped. You can do this using extra `injector()` added + * Sometimes you want to get access to the injector of a currently running AngularJS app + * from outside AngularJS. Perhaps, you want to inject and compile some markup after the + * application has been bootstrapped. You can do this using the extra `injector()` added * to JQuery/jqLite elements. See {@link angular.element}. * * *This is fairly rare but could be the case if a third party library is injecting the @@ -3144,9 +4207,9 @@ * $(document.body).append($div); * * angular.element(document).injector().invoke(function($compile) { - * var scope = angular.element($div).scope(); - * $compile($div)(scope); - * }); + * var scope = angular.element($div).scope(); + * $compile($div)(scope); + * }); * ``` */ @@ -3154,30 +4217,58 @@ /** * @ngdoc module * @name auto + * @installation * @description * * Implicit module which gets automatically added to each {@link auto.$injector $injector}. */ - var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; + var ARROW_ARG = /^([^(]+?)=>/; + var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var $injectorMinErr = minErr('$injector'); - function annotate(fn) { + + function stringifyFn(fn) { + return Function.prototype.toString.call(fn); + } + + function extractArgs(fn) { + var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''), + args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS); + return args; + } + + function anonFn(fn) { + // For anonymous functions, showing at the very least the function signature can help in + // debugging. + var args = extractArgs(fn); + if (args) { + return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; + } + return 'fn'; + } + + function annotate(fn, strictDi, name) { var $inject, - fnText, argDecl, last; - if (typeof fn == 'function') { + if (typeof fn === 'function') { if (!($inject = fn.$inject)) { $inject = []; if (fn.length) { - fnText = fn.toString().replace(STRIP_COMMENTS, ''); - argDecl = fnText.match(FN_ARGS); - forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ - arg.replace(FN_ARG, function(all, underscore, name){ + if (strictDi) { + if (!isString(name) || !name) { + name = fn.name || anonFn(fn); + } + throw $injectorMinErr('strictdi', + '{0} is not using explicit annotation and cannot be invoked in strict mode', name); + } + argDecl = extractArgs(fn); + forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { + arg.replace(FN_ARG, function(all, underscore, name) { $inject.push(name); }); }); @@ -3199,7 +4290,6 @@ /** * @ngdoc service * @name $injector - * @function * * @description * @@ -3212,12 +4302,12 @@ * ```js * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); - * expect($injector.invoke(function($injector){ - * return $injector; - * }).toBe($injector); + * expect($injector.invoke(function($injector) { + * return $injector; + * })).toBe($injector); * ``` * - * # Injection Function Annotation + * ## Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. @@ -3235,19 +4325,43 @@ * $injector.invoke(['serviceA', function(serviceA){}]); * ``` * - * ## Inference + * ### Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition - * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with - * minification, and obfuscation tools since these tools change the argument names. + * can then be parsed and the function arguments can be extracted. This method of discovering + * annotations is disallowed when the injector is in strict mode. + * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the + * argument names. * - * ## `$inject` Annotation - * By adding a `$inject` property onto a function the injection parameters can be specified. + * ### `$inject` Annotation + * By adding an `$inject` property onto a function the injection parameters can be specified. * - * ## Inline + * ### Inline * As an array of injection names, where the last item in the array is the function to call. */ + /** + * @ngdoc property + * @name $injector#modules + * @type {Object} + * @description + * A hash containing all the modules that have been loaded into the + * $injector. + * + * You can use this property to find out information about a module via the + * {@link angular.Module#info `myModule.info(...)`} method. + * + * For example: + * + * ``` + * var info = $injector.modules['ngAnimate'].info(); + * ``` + * + * **Do not use this property to attempt to modify the modules after the application + * has been bootstrapped.** + */ + + /** * @ngdoc method * @name $injector#get @@ -3256,6 +4370,7 @@ * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. + * @param {string=} caller An optional string to provide the origin of the function call for error messages. * @return {*} The instance. */ @@ -3266,8 +4381,8 @@ * @description * Invoke the method and supply the method arguments from the `$injector`. * - * @param {!Function} fn The function to invoke. Function parameters are injected according to the - * {@link guide/di $inject Annotation} rules. + * @param {Function|Array.} fn The injectable function to invoke. Function parameters are + * injected according to the {@link guide/di $inject Annotation} rules. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. @@ -3279,18 +4394,18 @@ * @name $injector#has * * @description - * Allows the user to query if the particular service exist. + * Allows the user to query if the particular service exists. * - * @param {string} Name of the service to query. - * @returns {boolean} returns true if injector has given service. + * @param {string} name Name of the service to query. + * @returns {boolean} `true` if injector has given service. */ /** * @ngdoc method * @name $injector#instantiate * @description - * Create a new instance of JS type. The method takes a constructor function invokes the new - * operator and supplies all of the arguments to the constructor function as specified by the + * Create a new instance of JS type. The method takes a constructor function, invokes the new + * operator, and supplies all of the arguments to the constructor function as specified by the * constructor annotation. * * @param {Function} Type Annotated constructor function. @@ -3309,7 +4424,7 @@ * function is invoked. There are three ways in which the function can be annotated with the needed * dependencies. * - * # Argument names + * #### Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done * by converting the function into a string using `toString()` method and extracting the argument @@ -3317,25 +4432,27 @@ * ```js * // Given * function MyController($scope, $route) { - * // ... - * } + * // ... + * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * + * You can disallow this method by using strict injection mode. + * * This method does not work with code minification / obfuscation. For this reason the following * annotation strategies are supported. * - * # The `$inject` property + * #### The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings * represent names of services to be injected into the function. * ```js * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { - * // ... - * } + * // ... + * } * // Define function dependencies * MyController['$inject'] = ['$scope', '$route']; * @@ -3343,7 +4460,7 @@ * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * - * # The array notation + * #### The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property * is very inconvenient. In these situations using the array notation to specify the dependencies in @@ -3352,20 +4469,20 @@ * ```js * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { - * // ... - * }); + * // ... + * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { - * // ... - * }; + * // ... + * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tmpFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { - * // ... - * }]); + * // ... + * }]); * * // Therefore * expect(injector.annotate( @@ -3376,14 +4493,53 @@ * @param {Function|Array.} fn Function for which dependent service names need to * be retrieved as described above. * + * @param {boolean=} [strictDi=false] Disallow argument name annotation inference. + * * @returns {Array.} The names of the services which the function requires. */ - - + /** + * @ngdoc method + * @name $injector#loadNewModules + * + * @description + * + * **This is a dangerous API, which you use at your own risk!** + * + * Add the specified modules to the current injector. + * + * This method will add each of the injectables to the injector and execute all of the config and run + * blocks for each module passed to the method. + * + * If a module has already been loaded into the injector then it will not be loaded again. + * + * * The application developer is responsible for loading the code containing the modules; and for + * ensuring that lazy scripts are not downloaded and executed more often that desired. + * * Previously compiled HTML will not be affected by newly loaded directives, filters and components. + * * Modules cannot be unloaded. + * + * You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded + * into the injector, which may indicate whether the script has been executed already. + * + * @example + * Here is an example of loading a bundle of modules, with a utility method called `getScript`: + * + * ```javascript + * app.factory('loadModule', function($injector) { + * return function loadModule(moduleName, bundleUrl) { + * return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); }); + * }; + * }) + * ``` + * + * @param {Array=} mods an array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a `config` block. + * See: {@link angular.module modules} + */ /** - * @ngdoc object + * @ngdoc service * @name $provide * * @description @@ -3392,7 +4548,7 @@ * with the {@link auto.$injector $injector}. Many of these functions are also exposed on * {@link angular.Module}. * - * An Angular **service** is a singleton object created by a **service factory**. These **service + * An AngularJS **service** is a singleton object created by a **service factory**. These **service * factories** are functions which, in turn, are created by a **service provider**. * The **service providers** are constructor functions. When instantiated they must contain a * property called `$get`, which holds the **service factory** function. @@ -3406,18 +4562,20 @@ * these cases the {@link auto.$provide $provide} service has additional helper methods to register * services without specifying a provider. * - * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the + * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the * {@link auto.$injector $injector} - * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by + * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by * providers and services. - * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by + * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by * services, not providers. - * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, + * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function** * that will be wrapped in a **service provider** object, whose `$get` property will contain the * given factory function. - * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` + * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function** * that will be wrapped in a **service provider** object, whose `$get` property will instantiate * a new object using the given constructor function. + * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that + * will be able to modify or replace the implementation of another service. * * See the individual methods for more information and examples. */ @@ -3442,6 +4600,9 @@ * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the * console or not. * + * It is possible to inject other providers into the provider function, + * but the injected provider must have been defined before the one that requires it. + * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: @@ -3461,60 +4622,60 @@ * ```js * // Define the eventTracker provider * function EventTrackerProvider() { - * var trackingUrl = '/track'; - * - * // A provider method for configuring where the tracked events should been saved - * this.setTrackingUrl = function(url) { - * trackingUrl = url; - * }; - * - * // The service factory function - * this.$get = ['$http', function($http) { - * var trackedEvents = {}; - * return { - * // Call this to track an event - * event: function(event) { - * var count = trackedEvents[event] || 0; - * count += 1; - * trackedEvents[event] = count; - * return count; - * }, - * // Call this to save the tracked events to the trackingUrl - * save: function() { - * $http.post(trackingUrl, trackedEvents); - * } - * }; - * }]; - * } + * var trackingUrl = '/track'; + * + * // A provider method for configuring where the tracked events should been saved + * this.setTrackingUrl = function(url) { + * trackingUrl = url; + * }; + * + * // The service factory function + * this.$get = ['$http', function($http) { + * var trackedEvents = {}; + * return { + * // Call this to track an event + * event: function(event) { + * var count = trackedEvents[event] || 0; + * count += 1; + * trackedEvents[event] = count; + * return count; + * }, + * // Call this to save the tracked events to the trackingUrl + * save: function() { + * $http.post(trackingUrl, trackedEvents); + * } + * }; + * }]; + * } * * describe('eventTracker', function() { - * var postSpy; - * - * beforeEach(module(function($provide) { - * // Register the eventTracker provider - * $provide.provider('eventTracker', EventTrackerProvider); - * })); - * - * beforeEach(module(function(eventTrackerProvider) { - * // Configure eventTracker provider - * eventTrackerProvider.setTrackingUrl('/custom-track'); - * })); - * - * it('tracks events', inject(function(eventTracker) { - * expect(eventTracker.event('login')).toEqual(1); - * expect(eventTracker.event('login')).toEqual(2); - * })); - * - * it('saves to the tracking url', inject(function(eventTracker, $http) { - * postSpy = spyOn($http, 'post'); - * eventTracker.event('login'); - * eventTracker.save(); - * expect(postSpy).toHaveBeenCalled(); - * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); - * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); - * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); - * })); - * }); + * var postSpy; + * + * beforeEach(module(function($provide) { + * // Register the eventTracker provider + * $provide.provider('eventTracker', EventTrackerProvider); + * })); + * + * beforeEach(module(function(eventTrackerProvider) { + * // Configure eventTracker provider + * eventTrackerProvider.setTrackingUrl('/custom-track'); + * })); + * + * it('tracks events', inject(function(eventTracker) { + * expect(eventTracker.event('login')).toEqual(1); + * expect(eventTracker.event('login')).toEqual(2); + * })); + * + * it('saves to the tracking url', inject(function(eventTracker, $http) { + * postSpy = spyOn($http, 'post'); + * eventTracker.event('login'); + * eventTracker.save(); + * expect(postSpy).toHaveBeenCalled(); + * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); + * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); + * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); + * })); + * }); * ``` */ @@ -3530,24 +4691,24 @@ * configure your service in a provider. * * @param {string} name The name of the instance. - * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand - * for `$provide.provider(name, {$get: $getFn})`. + * @param {Function|Array.} $getFn The injectable $getFn for the instance creation. + * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service * ```js * $provide.factory('ping', ['$http', function($http) { - * return function ping() { - * return $http.send('/ping'); - * }; - * }]); + * return function ping() { + * return $http.send('/ping'); + * }; + * }]); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { - * ping(); - * }]); + * ping(); + * }]); * ``` */ @@ -3559,14 +4720,27 @@ * * Register a **service constructor**, which will be invoked with `new` to create the service * instance. - * This is short for registering a service where its provider's `$get` property is the service - * constructor function that will be used to instantiate the service instance. + * This is short for registering a service where its provider's `$get` property is a factory + * function that returns an instance instantiated by the injector from the service constructor + * function. + * + * Internally it looks a bit like this: + * + * ``` + * { + * $get: function() { + * return $injector.instantiate(constructor); + * } + * } + * ``` + * * * You should use {@link auto.$provide#service $provide.service(class)} if you define your service * as a type/class. * * @param {string} name The name of the instance. - * @param {Function} constructor A class (constructor function) that will be instantiated. + * @param {Function|Array.} constructor An injectable class (constructor function) + * that will be instantiated. * @returns {Object} registered provider instance * * @example @@ -3574,21 +4748,21 @@ * {@link auto.$provide#service $provide.service(class)}. * ```js * var Ping = function($http) { - * this.$http = $http; - * }; + * this.$http = $http; + * }; * * Ping.$inject = ['$http']; * * Ping.prototype.send = function() { - * return this.$http.get('/ping'); - * }; + * return this.$http.get('/ping'); + * }; * $provide.service('ping', Ping); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { - * ping.send(); - * }]); + * ping.send(); + * }]); * ``` */ @@ -3599,14 +4773,13 @@ * @description * * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a - * number, an array, an object or a function. This is short for registering a service where its + * number, an array, an object or a function. This is short for registering a service where its * provider's `$get` property is a factory function that takes no arguments and returns the **value - * service**. + * service**. That also means it is not possible to inject other services into a value service. * * Value services are similar to constant services, except that they cannot be injected into a * module configuration function (see {@link angular.Module#config}) but they can be overridden by - * an Angular - * {@link auto.$provide#decorator decorator}. + * an AngularJS {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the instance. * @param {*} value The value. @@ -3620,8 +4793,8 @@ * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); * * $provide.value('halfOf', function(value) { - * return value / 2; - * }); + * return value / 2; + * }); * ``` */ @@ -3631,10 +4804,13 @@ * @name $provide#constant * @description * - * Register a **constant service**, such as a string, a number, an array, an object or a function, - * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be + * Register a **constant service** with the {@link auto.$injector $injector}, such as a string, + * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not + * possible to inject other services into a constant. + * + * But unlike {@link auto.$provide#value value}, a constant can be * injected into a module configuration function (see {@link angular.Module#config}) and it cannot - * be overridden by an Angular {@link auto.$provide#decorator decorator}. + * be overridden by an AngularJS {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. @@ -3648,8 +4824,8 @@ * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); * * $provide.constant('double', function(value) { - * return value * 2; - * }); + * return value * 2; + * }); * ``` */ @@ -3659,18 +4835,20 @@ * @name $provide#decorator * @description * - * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator - * intercepts the creation of a service, allowing it to override or modify the behaviour of the - * service. The object returned by the decorator may be the original service, or a new service - * object which replaces or wraps and delegates to the original service. + * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function + * intercepts the creation of a service, allowing it to override or modify the behavior of the + * service. The return value of the decorator function may be the original service, or a new service + * that replaces (or wraps and delegates to) the original service. + * + * You can find out more about using decorators in the {@link guide/decorators} guide. * * @param {string} name The name of the service to decorate. - * @param {function()} decorator This function will be invoked when the service needs to be - * instantiated and should return the decorated service instance. The function is called using + * @param {Function|Array.} decorator This function will be invoked when the service needs to be + * provided and should return the decorated service instance. The function is called using * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. * Local injection arguments: * - * * `$delegate` - The original service instance, which can be monkey patched, configured, + * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured, * decorated or delegated to. * * @example @@ -3678,18 +4856,19 @@ * calls to {@link ng.$log#error $log.warn()}. * ```js * $provide.decorator('$log', ['$delegate', function($delegate) { - * $delegate.warn = $delegate.error; - * return $delegate; - * }]); + * $delegate.warn = $delegate.error; + * return $delegate; + * }]); * ``` */ - function createInjector(modulesToLoad) { + function createInjector(modulesToLoad, strictDi) { + strictDi = (strictDi === true); var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], - loadedModules = new HashMap(), + loadedModules = new NgMap(), providerCache = { $provide: { provider: supportObject(provider), @@ -3701,18 +4880,32 @@ } }, providerInjector = (providerCache.$injector = - createInternalInjector(providerCache, function() { - throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); + createInternalInjector(providerCache, function(serviceName, caller) { + if (angular.isString(caller)) { + path.push(caller); + } + throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- ')); })), instanceCache = {}, - instanceInjector = (instanceCache.$injector = - createInternalInjector(instanceCache, function(servicename) { - var provider = providerInjector.get(servicename + providerSuffix); - return instanceInjector.invoke(provider.$get, provider); - })); + protoInstanceInjector = + createInternalInjector(instanceCache, function(serviceName, caller) { + var provider = providerInjector.get(serviceName + providerSuffix, caller); + return instanceInjector.invoke( + provider.$get, provider, undefined, serviceName); + }), + instanceInjector = protoInstanceInjector; + + providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) }; + instanceInjector.modules = providerInjector.modules = createMap(); + var runBlocks = loadModules(modulesToLoad); + instanceInjector = protoInstanceInjector.get('$injector'); + instanceInjector.strictDi = strictDi; + forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); }); + instanceInjector.loadNewModules = function(mods) { + forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); }); + }; - forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; @@ -3736,12 +4929,26 @@ provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { - throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); + throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name); } - return providerCache[name + providerSuffix] = provider_; + return (providerCache[name + providerSuffix] = provider_); + } + + function enforceReturnValue(name, factory) { + return /** @this */ function enforcedReturnValue() { + var result = instanceInjector.invoke(factory, this); + if (isUndefined(result)) { + throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name); + } + return result; + }; } - function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } + function factory(name, factoryFn, enforce) { + return provider(name, { + $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn + }); + } function service(name, constructor) { return factory(name, ['$injector', function($injector) { @@ -3749,7 +4956,7 @@ }]); } - function value(name, val) { return factory(name, valueFn(val)); } + function value(name, val) { return factory(name, valueFn(val), false); } function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); @@ -3770,23 +4977,30 @@ //////////////////////////////////// // Module Loading //////////////////////////////////// - function loadModules(modulesToLoad){ - var runBlocks = [], moduleFn, invokeQueue, i, ii; + function loadModules(modulesToLoad) { + assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array'); + var runBlocks = [], moduleFn; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; - loadedModules.put(module, true); + loadedModules.set(module, true); + + function runInvokeQueue(queue) { + var i, ii; + for (i = 0, ii = queue.length; i < ii; i++) { + var invokeArgs = queue[i], + provider = providerInjector.get(invokeArgs[0]); + + provider[invokeArgs[1]].apply(provider, invokeArgs[2]); + } + } try { if (isString(module)) { moduleFn = angularModule(module); + instanceInjector.modules[module] = moduleFn; runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); - - for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { - var invokeArgs = invokeQueue[i], - provider = providerInjector.get(invokeArgs[0]); - - provider[invokeArgs[1]].apply(provider, invokeArgs[2]); - } + runInvokeQueue(moduleFn._invokeQueue); + runInvokeQueue(moduleFn._configBlocks); } else if (isFunction(module)) { runBlocks.push(providerInjector.invoke(module)); } else if (isArray(module)) { @@ -3798,15 +5012,15 @@ if (isArray(module)) { module = module[module.length - 1]; } - if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { + if (e.message && e.stack && e.stack.indexOf(e.message) === -1) { // Safari & FF's stack traces don't contain error.message content // unlike those of Chrome and IE // So if stack doesn't contain message, we create a new string that contains both. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. - /* jshint -W022 */ + // eslint-disable-next-line no-ex-assign e = e.message + '\n' + e.stack; } - throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", + throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}', module, e.stack || e.message || e); } }); @@ -3819,17 +5033,19 @@ function createInternalInjector(cache, factory) { - function getService(serviceName) { + function getService(serviceName, caller) { if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { - throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- ')); + throw $injectorMinErr('cdep', 'Circular dependency found: {0}', + serviceName + ' <- ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; - return cache[serviceName] = factory(serviceName); + cache[serviceName] = factory(serviceName, caller); + return cache[serviceName]; } catch (err) { if (cache[serviceName] === INSTANTIATING) { delete cache[serviceName]; @@ -3841,52 +5057,76 @@ } } - function invoke(fn, self, locals){ + + function injectionArgs(fn, locals, serviceName) { var args = [], - $inject = annotate(fn), - length, i, - key; + $inject = createInjector.$$annotate(fn, strictDi, serviceName); - for(i = 0, length = $inject.length; i < length; i++) { - key = $inject[i]; + for (var i = 0, length = $inject.length; i < length; i++) { + var key = $inject[i]; if (typeof key !== 'string') { throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); } - args.push( - locals && locals.hasOwnProperty(key) - ? locals[key] - : getService(key) - ); + args.push(locals && locals.hasOwnProperty(key) ? locals[key] : + getService(key, serviceName)); + } + return args; + } + + function isClass(func) { + // Support: IE 9-11 only + // IE 9-11 do not support classes and IE9 leaks with the code below. + if (msie || typeof func !== 'function') { + return false; + } + var result = func.$$ngIsClass; + if (!isBoolean(result)) { + // Support: Edge 12-13 only + // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/ + result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func)); } - if (!fn.$inject) { - // this means that we must be an array. - fn = fn[length]; + return result; + } + + function invoke(fn, self, locals, serviceName) { + if (typeof locals === 'string') { + serviceName = locals; + locals = null; + } + + var args = injectionArgs(fn, locals, serviceName); + if (isArray(fn)) { + fn = fn[fn.length - 1]; } - // http://jsperf.com/angularjs-invoke-apply-vs-switch - // #5388 - return fn.apply(self, args); + if (!isClass(fn)) { + // http://jsperf.com/angularjs-invoke-apply-vs-switch + // #5388 + return fn.apply(self, args); + } else { + args.unshift(null); + return new (Function.prototype.bind.apply(fn, args))(); + } } - function instantiate(Type, locals) { - var Constructor = function() {}, - instance, returnedValue; + function instantiate(Type, locals, serviceName) { // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); - Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; - instance = new Constructor(); - returnedValue = invoke(Type, instance, locals); - - return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; + var ctor = (isArray(Type) ? Type[Type.length - 1] : Type); + var args = injectionArgs(Type, locals, serviceName); + // Empty object at position 0 is ignored for invocation with `new`, but required. + args.unshift(null); + return new (Function.prototype.bind.apply(ctor, args))(); } + return { invoke: invoke, instantiate: instantiate, get: getService, - annotate: annotate, + annotate: createInjector.$$annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } @@ -3894,108 +5134,445 @@ } } + createInjector.$$annotate = annotate; + /** - * @ngdoc service - * @name $anchorScroll - * @kind function - * @requires $window - * @requires $location - * @requires $rootScope + * @ngdoc provider + * @name $anchorScrollProvider + * @this * * @description - * When called, it checks current value of `$location.hash()` and scroll to related element, - * according to rules specified in - * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document). - * - * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor. - * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. - * - * @example - - -
    - Go to bottom - You're at the bottom! -
    -
    - - function ScrollCtrl($scope, $location, $anchorScroll) { - $scope.gotoBottom = function (){ - // set the location.hash to the id of - // the element you wish to scroll to. - $location.hash('bottom'); - - // call $anchorScroll() - $anchorScroll(); - }; - } - - - #scrollArea { - height: 350px; - overflow: auto; - } - - #bottom { - display: block; - margin-top: 2000px; - } - -
    + * Use `$anchorScrollProvider` to disable automatic scrolling whenever + * {@link ng.$location#hash $location.hash()} changes. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; + /** + * @ngdoc method + * @name $anchorScrollProvider#disableAutoScrolling + * + * @description + * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to + * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
    + * Use this method to disable automatic scrolling. + * + * If automatic scrolling is disabled, one must explicitly call + * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the + * current hash. + */ this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; + /** + * @ngdoc service + * @name $anchorScroll + * @kind function + * @requires $window + * @requires $location + * @requires $rootScope + * + * @description + * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the + * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified + * in the + * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document). + * + * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to + * match any anchor whenever it changes. This can be disabled by calling + * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}. + * + * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a + * vertical scroll-offset (either fixed or dynamic). + * + * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of + * {@link ng.$location#hash $location.hash()} will be used. + * + * @property {(number|function|jqLite)} yOffset + * If set, specifies a vertical scroll-offset. This is often useful when there are fixed + * positioned elements at the top of the page, such as navbars, headers etc. + * + * `yOffset` can be specified in various ways: + * - **number**: A fixed number of pixels to be used as offset.

    + * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return + * a number representing the offset (in pixels).

    + * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from + * the top of the page to the element's bottom will be used as offset.
    + * **Note**: The element will be taken into account only as long as its `position` is set to + * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust + * their height and/or positioning according to the viewport's size. + * + *
    + *
    + * In order for `yOffset` to work properly, scrolling should take place on the document's root and + * not some child element. + *
    + * + * @example + + +
    + Go to bottom + You're at the bottom! +
    +
    + + angular.module('anchorScrollExample', []) + .controller('ScrollController', ['$scope', '$location', '$anchorScroll', + function($scope, $location, $anchorScroll) { + $scope.gotoBottom = function() { + // set the location.hash to the id of + // the element you wish to scroll to. + $location.hash('bottom'); + + // call $anchorScroll() + $anchorScroll(); + }; + }]); + + + #scrollArea { + height: 280px; + overflow: auto; + } + + #bottom { + display: block; + margin-top: 2000px; + } + +
    + * + *
    + * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value). + * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details. + * + * @example + + + +
    + Anchor {{x}} of 5 +
    +
    + + angular.module('anchorScrollOffsetExample', []) + .run(['$anchorScroll', function($anchorScroll) { + $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels + }]) + .controller('headerCtrl', ['$anchorScroll', '$location', '$scope', + function($anchorScroll, $location, $scope) { + $scope.gotoAnchor = function(x) { + var newHash = 'anchor' + x; + if ($location.hash() !== newHash) { + // set the $location.hash to `newHash` and + // $anchorScroll will automatically scroll to it + $location.hash('anchor' + x); + } else { + // call $anchorScroll() explicitly, + // since $location.hash hasn't changed + $anchorScroll(); + } + }; + } + ]); + + + body { + padding-top: 50px; + } + + .anchor { + border: 2px dashed DarkOrchid; + padding: 10px 10px 200px 10px; + } + + .fixed-header { + background-color: rgba(0, 0, 0, 0.2); + height: 50px; + position: fixed; + top: 0; left: 0; right: 0; + } + + .fixed-header > a { + display: inline-block; + margin: 5px 15px; + } + +
    + */ this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; - // helper function to get first anchor from a NodeList - // can't use filter.filter, as it accepts only instances of Array - // and IE can't convert NodeList to an array using [].slice - // TODO(vojta): use filter if we change it to accept lists as well + // Helper function to get first anchor from a NodeList + // (using `Array#some()` instead of `angular#forEach()` since it's more performant + // and working in all supported browsers.) function getFirstAnchor(list) { var result = null; - forEach(list, function(element) { - if (!result && lowercase(element.nodeName) === 'a') result = element; + Array.prototype.some.call(list, function(element) { + if (nodeName_(element) === 'a') { + result = element; + return true; + } }); return result; } - function scroll() { - var hash = $location.hash(), elm; - - // empty hash, scroll to the top of the page - if (!hash) $window.scrollTo(0, 0); + function getYOffset() { - // element with given id - else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); + var offset = scroll.yOffset; - // first anchor with given name :-D - else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); + if (isFunction(offset)) { + offset = offset(); + } else if (isElement(offset)) { + var elem = offset[0]; + var style = $window.getComputedStyle(elem); + if (style.position !== 'fixed') { + offset = 0; + } else { + offset = elem.getBoundingClientRect().bottom; + } + } else if (!isNumber(offset)) { + offset = 0; + } - // no element and hash == 'top', scroll to the top of the page - else if (hash === 'top') $window.scrollTo(0, 0); + return offset; } - // does not scroll when user clicks on anchor link that is currently on - // (no url change, no $location.hash() change), browser native does scroll - if (autoScrollingEnabled) { - $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, - function autoScrollWatchAction() { - $rootScope.$evalAsync(scroll); - }); - } + function scrollTo(elem) { + if (elem) { + elem.scrollIntoView(); - return scroll; + var offset = getYOffset(); + + if (offset) { + // `offset` is the number of pixels we should scroll UP in order to align `elem` properly. + // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the + // top of the viewport. + // + // IF the number of pixels from the top of `elem` to the end of the page's content is less + // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some + // way down the page. + // + // This is often the case for elements near the bottom of the page. + // + // In such cases we do not need to scroll the whole `offset` up, just the difference between + // the top of the element and the offset, which is enough to align the top of `elem` at the + // desired position. + var elemTop = elem.getBoundingClientRect().top; + $window.scrollBy(0, elemTop - offset); + } + } else { + $window.scrollTo(0, 0); + } + } + + function scroll(hash) { + // Allow numeric hashes + hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash(); + var elm; + + // empty hash, scroll to the top of the page + if (!hash) scrollTo(null); + + // element with given id + else if ((elm = document.getElementById(hash))) scrollTo(elm); + + // first anchor with given name :-D + else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm); + + // no element and hash === 'top', scroll to the top of the page + else if (hash === 'top') scrollTo(null); + } + + // does not scroll when user clicks on anchor link that is currently on + // (no url change, no $location.hash() change), browser native does scroll + if (autoScrollingEnabled) { + $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, + function autoScrollWatchAction(newVal, oldVal) { + // skip the initial scroll if $location.hash is empty + if (newVal === oldVal && newVal === '') return; + + jqLiteDocumentLoaded(function() { + $rootScope.$evalAsync(scroll); + }); + }); + } + + return scroll; }]; } var $animateMinErr = minErr('$animate'); + var ELEMENT_NODE = 1; + var NG_ANIMATE_CLASSNAME = 'ng-animate'; + + function mergeClasses(a,b) { + if (!a && !b) return ''; + if (!a) return b; + if (!b) return a; + if (isArray(a)) a = a.join(' '); + if (isArray(b)) b = b.join(' '); + return a + ' ' + b; + } + + function extractElementNode(element) { + for (var i = 0; i < element.length; i++) { + var elm = element[i]; + if (elm.nodeType === ELEMENT_NODE) { + return elm; + } + } + } + + function splitClasses(classes) { + if (isString(classes)) { + classes = classes.split(' '); + } + + // Use createMap() to prevent class assumptions involving property names in + // Object.prototype + var obj = createMap(); + forEach(classes, function(klass) { + // sometimes the split leaves empty string values + // incase extra spaces were applied to the options + if (klass.length) { + obj[klass] = true; + } + }); + return obj; + } + +// if any other type of options value besides an Object value is +// passed into the $animate.method() animation then this helper code +// will be run which will ignore it. While this patch is not the +// greatest solution to this, a lot of existing plugins depend on +// $animate to either call the callback (< 1.2) or return a promise +// that can be changed. This helper function ensures that the options +// are wiped clean incase a callback function is provided. + function prepareAnimateOptions(options) { + return isObject(options) + ? options + : {}; + } + + var $$CoreAnimateJsProvider = /** @this */ function() { + this.$get = noop; + }; + +// this is prefixed with Core since it conflicts with +// the animateQueueProvider defined in ngAnimate/animateQueue.js + var $$CoreAnimateQueueProvider = /** @this */ function() { + var postDigestQueue = new NgMap(); + var postDigestElements = []; + + this.$get = ['$$AnimateRunner', '$rootScope', + function($$AnimateRunner, $rootScope) { + return { + enabled: noop, + on: noop, + off: noop, + pin: noop, + + push: function(element, event, options, domOperation) { + if (domOperation) { + domOperation(); + } + + options = options || {}; + if (options.from) { + element.css(options.from); + } + if (options.to) { + element.css(options.to); + } + + if (options.addClass || options.removeClass) { + addRemoveClassesPostDigest(element, options.addClass, options.removeClass); + } + + var runner = new $$AnimateRunner(); + + // since there are no animations to run the runner needs to be + // notified that the animation call is complete. + runner.complete(); + return runner; + } + }; + + + function updateData(data, classes, value) { + var changed = false; + if (classes) { + classes = isString(classes) ? classes.split(' ') : + isArray(classes) ? classes : []; + forEach(classes, function(className) { + if (className) { + changed = true; + data[className] = value; + } + }); + } + return changed; + } + + function handleCSSClassChanges() { + forEach(postDigestElements, function(element) { + var data = postDigestQueue.get(element); + if (data) { + var existing = splitClasses(element.attr('class')); + var toAdd = ''; + var toRemove = ''; + forEach(data, function(status, className) { + var hasClass = !!existing[className]; + if (status !== hasClass) { + if (status) { + toAdd += (toAdd.length ? ' ' : '') + className; + } else { + toRemove += (toRemove.length ? ' ' : '') + className; + } + } + }); + + forEach(element, function(elm) { + if (toAdd) { + jqLiteAddClass(elm, toAdd); + } + if (toRemove) { + jqLiteRemoveClass(elm, toRemove); + } + }); + postDigestQueue.delete(element); + } + }); + postDigestElements.length = 0; + } + + + function addRemoveClassesPostDigest(element, add, remove) { + var data = postDigestQueue.get(element) || {}; + + var classesAdded = updateData(data, add, true); + var classesRemoved = updateData(data, remove, false); + + if (classesAdded || classesRemoved) { + + postDigestQueue.set(element, data); + postDigestElements.push(element); + + if (postDigestElements.length === 1) { + $rootScope.$$postDigest(handleCSSClassChanges); + } + } + } + }]; + }; /** * @ngdoc provider @@ -4003,18 +5580,18 @@ * * @description * Default implementation of $animate that doesn't perform any animations, instead just - * synchronously performs DOM - * updates and calls done() callbacks. + * synchronously performs DOM updates and resolves the returned runner promise. * - * In order to enable animations the ngAnimate module has to be loaded. + * In order to enable animations the `ngAnimate` module has to be loaded. * - * To see the functional implementation check out src/ngAnimate/animate.js + * To see the functional implementation check out `src/ngAnimate/animate.js`. */ - var $AnimateProvider = ['$provide', function($provide) { - - - this.$$selectors = {}; + var $AnimateProvider = ['$provide', /** @this */ function($provide) { + var provider = this; + var classNameFilter = null; + var customFilter = null; + this.$$registeredAnimations = Object.create(null); /** * @ngdoc method @@ -4025,36 +5602,91 @@ * animation object which contains callback functions for each event that is expected to be * animated. * - * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` - * must be called once the element animation is complete. If a function is returned then the - * animation service will use this function to cancel the animation whenever a cancel event is - * triggered. + * * `eventFn`: `function(element, ... , doneFunction, options)` + * The element to animate, the `doneFunction` and the options fed into the animation. Depending + * on the type of animation additional arguments will be injected into the animation function. The + * list below explains the function signatures for the different animation methods: * + * - setClass: function(element, addedClasses, removedClasses, doneFunction, options) + * - addClass: function(element, addedClasses, doneFunction, options) + * - removeClass: function(element, removedClasses, doneFunction, options) + * - enter, leave, move: function(element, doneFunction, options) + * - animate: function(element, fromStyles, toStyles, doneFunction, options) + * + * Make sure to trigger the `doneFunction` once the animation is fully complete. * * ```js * return { - * eventFn : function(element, done) { - * //code to run the animation - * //once complete, then run done() - * return function cancellationFunction() { - * //code to cancel the animation - * } - * } - * } + * //enter, leave, move signature + * eventFn : function(element, done, options) { + * //code to run the animation + * //once complete, then run done() + * return function endFunction(wasCancelled) { + * //code to cancel the animation + * } + * } + * } * ``` * - * @param {string} name The name of the animation. + * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to). * @param {Function} factory The factory function that will be executed to return the animation * object. */ this.register = function(name, factory) { + if (name && name.charAt(0) !== '.') { + throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name); + } + var key = name + '-animation'; - if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', - "Expecting class selector starting with '.' got '{0}'.", name); - this.$$selectors[name.substr(1)] = key; + provider.$$registeredAnimations[name.substr(1)] = key; $provide.factory(key, factory); }; + /** + * @ngdoc method + * @name $animateProvider#customFilter + * + * @description + * Sets and/or returns the custom filter function that is used to "filter" animations, i.e. + * determine if an animation is allowed or not. When no filter is specified (the default), no + * animation will be blocked. Setting the `customFilter` value will only allow animations for + * which the filter function's return value is truthy. + * + * This allows to easily create arbitrarily complex rules for filtering animations, such as + * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc. + * Filtering animations can also boost performance for low-powered devices, as well as + * applications containing a lot of structural operations. + * + *
    + * **Best Practice:** + * Keep the filtering function as lean as possible, because it will be called for each DOM + * action (e.g. insertion, removal, class change) performed by "animation-aware" directives. + * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in + * directives that support animations. + * Performing computationally expensive or time-consuming operations on each call of the + * filtering function can make your animations sluggish. + *
    + * + * **Note:** If present, `customFilter` will be checked before + * {@link $animateProvider#classNameFilter classNameFilter}. + * + * @param {Function=} filterFn - The filter function which will be used to filter all animations. + * If a falsy value is returned, no animation will be performed. The function will be called + * with the following arguments: + * - **node** `{DOMElement}` - The DOM element to be animated. + * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass` + * etc). + * - **options** `{Object}` - A collection of options/styles used for the animation. + * @return {Function} The current filter function or `null` if there is none set. + */ + this.customFilter = function(filterFn) { + if (arguments.length === 1) { + customFilter = isFunction(filterFn) ? filterFn : null; + } + + return customFilter; + }; + /** * @ngdoc method * @name $animateProvider#classNameFilter @@ -4062,220 +5694,716 @@ * @description * Sets and/or returns the CSS class regular expression that is checked when performing * an animation. Upon bootstrap the classNameFilter value is not set at all and will - * therefore enable $animate to attempt to perform an animation on any element. - * When setting the classNameFilter value, animations will only be performed on elements + * therefore enable $animate to attempt to perform an animation on any element that is triggered. + * When setting the `classNameFilter` value, animations will only be performed on elements * that successfully match the filter expression. This in turn can boost performance * for low-powered devices as well as applications containing a lot of structural operations. + * + * **Note:** If present, `classNameFilter` will be checked after + * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns + * false, `classNameFilter` will not be checked. + * * @param {RegExp=} expression The className expression which will be checked against all animations * @return {RegExp} The current CSS className expression value. If null then there is no expression value */ this.classNameFilter = function(expression) { - if(arguments.length === 1) { - this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; + if (arguments.length === 1) { + classNameFilter = (expression instanceof RegExp) ? expression : null; + if (classNameFilter) { + var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]'); + if (reservedRegex.test(classNameFilter.toString())) { + classNameFilter = null; + throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME); + } + } } - return this.$$classNameFilter; + return classNameFilter; }; - this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) { - - function async(fn) { - fn && $$asyncCallback(fn); + this.$get = ['$$animateQueue', function($$animateQueue) { + function domInsert(element, parentElement, afterElement) { + // if for some reason the previous element was removed + // from the dom sometime before this code runs then let's + // just stick to using the parent element as the anchor + if (afterElement) { + var afterNode = extractElementNode(afterElement); + if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) { + afterElement = null; + } + } + if (afterElement) { + afterElement.after(element); + } else { + parentElement.prepend(element); + } } /** - * * @ngdoc service * @name $animate - * @description The $animate service provides rudimentary DOM manipulation functions to - * insert, remove and move elements within the DOM, as well as adding and removing classes. - * This service is the core service used by the ngAnimate $animator service which provides - * high-level animation hooks for CSS and JavaScript. + * @description The $animate service exposes a series of DOM utility methods that provide support + * for animation hooks. The default behavior is the application of DOM operations, however, + * when an animation is detected (and animations are enabled), $animate will do the heavy lifting + * to ensure that animation runs with the triggered DOM operation. + * + * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't + * included and only when it is active then the animation hooks that `$animate` triggers will be + * functional. Once active then all structural `ng-` directives will trigger animations as they perform + * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`, + * `ngShow`, `ngHide` and `ngMessages` also provide support for animations. * - * $animate is available in the AngularJS core, however, the ngAnimate module must be included - * to enable full out animation support. Otherwise, $animate will only perform simple DOM - * manipulation operations. + * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives. * - * To learn more about enabling animation support, click here to visit the {@link ngAnimate - * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service - * page}. + * To learn more about enabling animation support, click here to visit the + * {@link ngAnimate ngAnimate module page}. */ return { + // we don't call it directly since non-existant arguments may + // be interpreted as null within the sub enabled function /** * * @ngdoc method - * @name $animate#enter - * @function - * @description Inserts the element into the DOM either after the `after` element or within - * the `parent` element. Once complete, the done() callback will be fired (if provided). - * @param {DOMElement} element the element which will be inserted into the DOM - * @param {DOMElement} parent the parent element which will append the element as - * a child (if the after element is not present) - * @param {DOMElement} after the sibling element which will append the element - * after itself - * @param {Function=} done callback function that will be called after the element has been - * inserted into the DOM + * @name $animate#on + * @kind function + * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...) + * has fired on the given element or among any of its children. Once the listener is fired, the provided callback + * is fired with the following params: + * + * ```js + * $animate.on('enter', container, + * function callback(element, phase) { + * // cool we detected an enter animation within the container + * } + * ); + * ``` + * + * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...) + * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself + * as well as among its children + * @param {Function} callback the callback function that will be fired when the listener is triggered + * + * The arguments present in the callback function are: + * * `element` - The captured DOM element that the animation was fired on. + * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends). */ - enter : function(element, parent, after, done) { - if (after) { - after.after(element); - } else { - if (!parent || !parent[0]) { - parent = after.parent(); - } - parent.append(element); + on: $$animateQueue.on, + + /** + * + * @ngdoc method + * @name $animate#off + * @kind function + * @description Deregisters an event listener based on the event which has been associated with the provided element. This method + * can be used in three different ways depending on the arguments: + * + * ```js + * // remove all the animation event listeners listening for `enter` + * $animate.off('enter'); + * + * // remove listeners for all animation events from the container element + * $animate.off(container); + * + * // remove all the animation event listeners listening for `enter` on the given element and its children + * $animate.off('enter', container); + * + * // remove the event listener function provided by `callback` that is set + * // to listen for `enter` on the given `container` as well as its children + * $animate.off('enter', container, callback); + * ``` + * + * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move, + * addClass, removeClass, etc...), or the container element. If it is the element, all other + * arguments are ignored. + * @param {DOMElement=} container the container element the event listener was placed on + * @param {Function=} callback the callback function that was registered as the listener + */ + off: $$animateQueue.off, + + /** + * @ngdoc method + * @name $animate#pin + * @kind function + * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists + * outside of the DOM structure of the AngularJS application. By doing so, any animation triggered via `$animate` can be issued on the + * element despite being outside the realm of the application or within another application. Say for example if the application + * was bootstrapped on an element that is somewhere inside of the `` tag, but we wanted to allow for an element to be situated + * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind + * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association. + * + * Note that this feature is only active when the `ngAnimate` module is used. + * + * @param {DOMElement} element the external element that will be pinned + * @param {DOMElement} parentElement the host parent element that will be associated with the external element + */ + pin: $$animateQueue.pin, + + /** + * + * @ngdoc method + * @name $animate#enabled + * @kind function + * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This + * function can be called in four ways: + * + * ```js + * // returns true or false + * $animate.enabled(); + * + * // changes the enabled state for all animations + * $animate.enabled(false); + * $animate.enabled(true); + * + * // returns true or false if animations are enabled for an element + * $animate.enabled(element); + * + * // changes the enabled state for an element and its children + * $animate.enabled(element, true); + * $animate.enabled(element, false); + * ``` + * + * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state + * @param {boolean=} enabled whether or not the animations will be enabled for the element + * + * @return {boolean} whether or not animations are enabled + */ + enabled: $$animateQueue.enabled, + + /** + * @ngdoc method + * @name $animate#cancel + * @kind function + * @description Cancels the provided animation. + * + * @param {Promise} animationPromise The animation promise that is returned when an animation is started. + */ + cancel: function(runner) { + if (runner.end) { + runner.end(); } - async(done); }, /** * * @ngdoc method - * @name $animate#leave - * @function - * @description Removes the element from the DOM. Once complete, the done() callback will be - * fired (if provided). - * @param {DOMElement} element the element which will be removed from the DOM - * @param {Function=} done callback function that will be called after the element has been - * removed from the DOM + * @name $animate#enter + * @kind function + * @description Inserts the element into the DOM either after the `after` element (if provided) or + * as the first child within the `parent` element and then triggers an animation. + * A promise is returned that will be resolved during the next digest once the animation + * has completed. + * + * @param {DOMElement} element the element which will be inserted into the DOM + * @param {DOMElement} parent the parent element which will append the element as + * a child (so long as the after element is not present) + * @param {DOMElement=} after the sibling element after which the element will be appended + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Promise} the animation callback promise */ - leave : function(element, done) { - element.remove(); - async(done); + enter: function(element, parent, after, options) { + parent = parent && jqLite(parent); + after = after && jqLite(after); + parent = parent || after.parent(); + domInsert(element, parent, after); + return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options)); }, /** * * @ngdoc method * @name $animate#move - * @function - * @description Moves the position of the provided element within the DOM to be placed - * either after the `after` element or inside of the `parent` element. Once complete, the - * done() callback will be fired (if provided). + * @kind function + * @description Inserts (moves) the element into its new position in the DOM either after + * the `after` element (if provided) or as the first child within the `parent` element + * and then triggers an animation. A promise is returned that will be resolved + * during the next digest once the animation has completed. + * + * @param {DOMElement} element the element which will be moved into the new DOM position + * @param {DOMElement} parent the parent element which will append the element as + * a child (so long as the after element is not present) + * @param {DOMElement=} after the sibling element after which the element will be appended + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` * - * @param {DOMElement} element the element which will be moved around within the - * DOM - * @param {DOMElement} parent the parent element where the element will be - * inserted into (if the after element is not present) - * @param {DOMElement} after the sibling element where the element will be - * positioned next to - * @param {Function=} done the callback function (if provided) that will be fired after the - * element has been moved to its new position + * @return {Promise} the animation callback promise */ - move : function(element, parent, after, done) { - // Do not remove element before insert. Removing will cause data associated with the - // element to be dropped. Insert will implicitly do the remove. - this.enter(element, parent, after, done); + move: function(element, parent, after, options) { + parent = parent && jqLite(parent); + after = after && jqLite(after); + parent = parent || after.parent(); + domInsert(element, parent, after); + return $$animateQueue.push(element, 'move', prepareAnimateOptions(options)); }, /** - * * @ngdoc method - * @name $animate#addClass - * @function - * @description Adds the provided className CSS class value to the provided element. Once - * complete, the done() callback will be fired (if provided). - * @param {DOMElement} element the element which will have the className value - * added to it - * @param {string} className the CSS class which will be added to the element - * @param {Function=} done the callback function (if provided) that will be fired after the - * className value has been added to the element + * @name $animate#leave + * @kind function + * @description Triggers an animation and then removes the element from the DOM. + * When the function is called a promise is returned that will be resolved during the next + * digest once the animation has completed. + * + * @param {DOMElement} element the element which will be removed from the DOM + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Promise} the animation callback promise */ - addClass : function(element, className, done) { - className = isString(className) ? - className : - isArray(className) ? className.join(' ') : ''; - forEach(element, function (element) { - jqLiteAddClass(element, className); + leave: function(element, options) { + return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() { + element.remove(); }); - async(done); }, /** + * @ngdoc method + * @name $animate#addClass + * @kind function + * + * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon + * execution, the addClass operation will only be handled after the next digest and it will not trigger an + * animation if element already contains the CSS class or if the class is removed at a later step. + * Note that class-based animations are treated differently compared to structural animations + * (like enter, move and leave) since the CSS classes may be added/removed at different points + * depending if CSS or JavaScript animations are used. + * + * @param {DOMElement} element the element which the CSS classes will be applied to + * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces) + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` * + * @return {Promise} the animation callback promise + */ + addClass: function(element, className, options) { + options = prepareAnimateOptions(options); + options.addClass = mergeClasses(options.addclass, className); + return $$animateQueue.push(element, 'addClass', options); + }, + + /** * @ngdoc method * @name $animate#removeClass - * @function - * @description Removes the provided className CSS class value from the provided element. - * Once complete, the done() callback will be fired (if provided). - * @param {DOMElement} element the element which will have the className value - * removed from it - * @param {string} className the CSS class which will be removed from the element - * @param {Function=} done the callback function (if provided) that will be fired after the - * className value has been removed from the element + * @kind function + * + * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon + * execution, the removeClass operation will only be handled after the next digest and it will not trigger an + * animation if element does not contain the CSS class or if the class is added at a later step. + * Note that class-based animations are treated differently compared to structural animations + * (like enter, move and leave) since the CSS classes may be added/removed at different points + * depending if CSS or JavaScript animations are used. + * + * @param {DOMElement} element the element which the CSS classes will be applied to + * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces) + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Promise} the animation callback promise */ - removeClass : function(element, className, done) { - className = isString(className) ? - className : - isArray(className) ? className.join(' ') : ''; - forEach(element, function (element) { - jqLiteRemoveClass(element, className); - }); - async(done); + removeClass: function(element, className, options) { + options = prepareAnimateOptions(options); + options.removeClass = mergeClasses(options.removeClass, className); + return $$animateQueue.push(element, 'removeClass', options); }, /** - * * @ngdoc method * @name $animate#setClass - * @function - * @description Adds and/or removes the given CSS classes to and from the element. - * Once complete, the done() callback will be fired (if provided). - * @param {DOMElement} element the element which will it's CSS classes changed - * removed from it - * @param {string} add the CSS classes which will be added to the element - * @param {string} remove the CSS class which will be removed from the element - * @param {Function=} done the callback function (if provided) that will be fired after the - * CSS classes have been set on the element + * @kind function + * + * @description Performs both the addition and removal of a CSS classes on an element and (during the process) + * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and + * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has + * passed. Note that class-based animations are treated differently compared to structural animations + * (like enter, move and leave) since the CSS classes may be added/removed at different points + * depending if CSS or JavaScript animations are used. + * + * @param {DOMElement} element the element which the CSS classes will be applied to + * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces) + * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces) + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Promise} the animation callback promise */ - setClass : function(element, add, remove, done) { - forEach(element, function (element) { - jqLiteAddClass(element, add); - jqLiteRemoveClass(element, remove); - }); - async(done); + setClass: function(element, add, remove, options) { + options = prepareAnimateOptions(options); + options.addClass = mergeClasses(options.addClass, add); + options.removeClass = mergeClasses(options.removeClass, remove); + return $$animateQueue.push(element, 'setClass', options); }, - enabled : noop + /** + * @ngdoc method + * @name $animate#animate + * @kind function + * + * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element. + * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take + * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and + * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding + * style in `to`, the style in `from` is applied immediately, and no animation is run. + * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate` + * method (or as part of the `options` parameter): + * + * ```js + * ngModule.animation('.my-inline-animation', function() { + * return { + * animate : function(element, from, to, done, options) { + * //animation + * done(); + * } + * } + * }); + * ``` + * + * @param {DOMElement} element the element which the CSS styles will be applied to + * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation. + * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation. + * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If + * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element. + * (Note that if no animation is detected then this value will not be applied to the element.) + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Promise} the animation callback promise + */ + animate: function(element, from, to, className, options) { + options = prepareAnimateOptions(options); + options.from = options.from ? extend(options.from, from) : from; + options.to = options.to ? extend(options.to, to) : to; + + className = className || 'ng-inline-animate'; + options.tempClasses = mergeClasses(options.tempClasses, className); + return $$animateQueue.push(element, 'animate', options); + } }; }]; }]; - function $$AsyncCallbackProvider(){ - this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) { - return $$rAF.supported - ? function(fn) { return $$rAF(fn); } - : function(fn) { - return $timeout(fn, 0, false); + var $$AnimateAsyncRunFactoryProvider = /** @this */ function() { + this.$get = ['$$rAF', function($$rAF) { + var waitQueue = []; + + function waitForTick(fn) { + waitQueue.push(fn); + if (waitQueue.length > 1) return; + $$rAF(function() { + for (var i = 0; i < waitQueue.length; i++) { + waitQueue[i](); + } + waitQueue = []; + }); + } + + return function() { + var passed = false; + waitForTick(function() { + passed = true; + }); + return function(callback) { + if (passed) { + callback(); + } else { + waitForTick(callback); + } + }; }; }]; - } + }; - /** - * ! This is a private undocumented service ! - * - * @name $browser - * @requires $log - * @description - * This object has two goals: - * - * - hide all the global state in the browser caused by the window object - * - abstract away all the browser specific features and inconsistencies - * - * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` - * service, which can be used for convenient testing of the application without the interaction with - * the real browser apis. - */ - /** - * @param {object} window The global window object. - * @param {object} document jQuery wrapped document. - * @param {function()} XHR XMLHttpRequest constructor. - * @param {object} $log console.log or an object with the same interface. - * @param {object} $sniffer $sniffer service + var $$AnimateRunnerFactoryProvider = /** @this */ function() { + this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout', + function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) { + + var INITIAL_STATE = 0; + var DONE_PENDING_STATE = 1; + var DONE_COMPLETE_STATE = 2; + + AnimateRunner.chain = function(chain, callback) { + var index = 0; + + next(); + function next() { + if (index === chain.length) { + callback(true); + return; + } + + chain[index](function(response) { + if (response === false) { + callback(false); + return; + } + index++; + next(); + }); + } + }; + + AnimateRunner.all = function(runners, callback) { + var count = 0; + var status = true; + forEach(runners, function(runner) { + runner.done(onProgress); + }); + + function onProgress(response) { + status = status && response; + if (++count === runners.length) { + callback(status); + } + } + }; + + function AnimateRunner(host) { + this.setHost(host); + + var rafTick = $$animateAsyncRun(); + var timeoutTick = function(fn) { + $timeout(fn, 0, false); + }; + + this._doneCallbacks = []; + this._tick = function(fn) { + if ($$isDocumentHidden()) { + timeoutTick(fn); + } else { + rafTick(fn); + } + }; + this._state = 0; + } + + AnimateRunner.prototype = { + setHost: function(host) { + this.host = host || {}; + }, + + done: function(fn) { + if (this._state === DONE_COMPLETE_STATE) { + fn(); + } else { + this._doneCallbacks.push(fn); + } + }, + + progress: noop, + + getPromise: function() { + if (!this.promise) { + var self = this; + this.promise = $q(function(resolve, reject) { + self.done(function(status) { + if (status === false) { + reject(); + } else { + resolve(); + } + }); + }); + } + return this.promise; + }, + + then: function(resolveHandler, rejectHandler) { + return this.getPromise().then(resolveHandler, rejectHandler); + }, + + 'catch': function(handler) { + return this.getPromise()['catch'](handler); + }, + + 'finally': function(handler) { + return this.getPromise()['finally'](handler); + }, + + pause: function() { + if (this.host.pause) { + this.host.pause(); + } + }, + + resume: function() { + if (this.host.resume) { + this.host.resume(); + } + }, + + end: function() { + if (this.host.end) { + this.host.end(); + } + this._resolve(true); + }, + + cancel: function() { + if (this.host.cancel) { + this.host.cancel(); + } + this._resolve(false); + }, + + complete: function(response) { + var self = this; + if (self._state === INITIAL_STATE) { + self._state = DONE_PENDING_STATE; + self._tick(function() { + self._resolve(response); + }); + } + }, + + _resolve: function(response) { + if (this._state !== DONE_COMPLETE_STATE) { + forEach(this._doneCallbacks, function(fn) { + fn(response); + }); + this._doneCallbacks.length = 0; + this._state = DONE_COMPLETE_STATE; + } + } + }; + + return AnimateRunner; + }]; + }; + + /* exported $CoreAnimateCssProvider */ + + /** + * @ngdoc service + * @name $animateCss + * @kind object + * @this + * + * @description + * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included, + * then the `$animateCss` service will actually perform animations. + * + * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}. + */ + var $CoreAnimateCssProvider = function() { + this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) { + + return function(element, initialOptions) { + // all of the animation functions should create + // a copy of the options data, however, if a + // parent service has already created a copy then + // we should stick to using that + var options = initialOptions || {}; + if (!options.$$prepared) { + options = copy(options); + } + + // there is no point in applying the styles since + // there is no animation that goes on at all in + // this version of $animateCss. + if (options.cleanupStyles) { + options.from = options.to = null; + } + + if (options.from) { + element.css(options.from); + options.from = null; + } + + var closed, runner = new $$AnimateRunner(); + return { + start: run, + end: run + }; + + function run() { + $$rAF(function() { + applyAnimationContents(); + if (!closed) { + runner.complete(); + } + closed = true; + }); + return runner; + } + + function applyAnimationContents() { + if (options.addClass) { + element.addClass(options.addClass); + options.addClass = null; + } + if (options.removeClass) { + element.removeClass(options.removeClass); + options.removeClass = null; + } + if (options.to) { + element.css(options.to); + options.to = null; + } + } + }; + }]; + }; + + /* global stripHash: true */ + + /** + * ! This is a private undocumented service ! + * + * @name $browser + * @requires $log + * @description + * This object has two goals: + * + * - hide all the global state in the browser caused by the window object + * - abstract away all the browser specific features and inconsistencies + * + * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` + * service, which can be used for convenient testing of the application without the interaction with + * the real browser apis. + */ + /** + * @param {object} window The global window object. + * @param {object} document jQuery wrapped document. + * @param {object} $log window.console or an object with the same interface. + * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, - rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, @@ -4301,7 +6429,7 @@ } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { - while(outstandingRequestCallbacks.length) { + while (outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { @@ -4312,18 +6440,17 @@ } } + function getHash(url) { + var index = url.indexOf('#'); + return index === -1 ? '' : url.substr(index); + } + /** * @private - * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { - // force browser to execute all pollFns - this is needed so that cookies and other pollers fire - // at some deterministic time in respect to the test runner's actions. Leaving things up to the - // regular poller would result in flaky tests. - forEach(pollFns, function(pollFn){ pollFn(); }); - if (outstandingRequestCount === 0) { callback(); } else { @@ -4331,51 +6458,23 @@ } }; - ////////////////////////////////////////////////////////////// - // Poll Watcher API - ////////////////////////////////////////////////////////////// - var pollFns = [], - pollTimeout; - - /** - * @name $browser#addPollFn - * - * @param {function()} fn Poll function to add - * - * @description - * Adds a function to the list of functions that poller periodically executes, - * and starts polling if not started yet. - * - * @returns {function()} the added function - */ - self.addPollFn = function(fn) { - if (isUndefined(pollTimeout)) startPoller(100, setTimeout); - pollFns.push(fn); - return fn; - }; - - /** - * @param {number} interval How often should browser call poll functions (ms) - * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. - * - * @description - * Configures the poller to run in the specified intervals, using the specified - * setTimeout fn and kicks it off. - */ - function startPoller(interval, setTimeout) { - (function check() { - forEach(pollFns, function(pollFn){ pollFn(); }); - pollTimeout = setTimeout(check, interval); - })(); - } - ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// - var lastBrowserUrl = location.href, + var cachedState, lastHistoryState, + lastBrowserUrl = location.href, baseElement = document.find('base'), - newLocation = null; + pendingLocation = null, + getCurrentState = !$sniffer.history ? noop : function getCurrentState() { + try { + return history.state; + } catch (e) { + // MSIE can reportedly throw when there is no state (UNCONFIRMED). + } + }; + + cacheState(); /** * @name $browser#url @@ -4394,52 +6493,120 @@ * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) - * @param {boolean=} replace Should new url replace current history record ? + * @param {boolean=} replace Should new url replace current history record? + * @param {object=} state object to use with pushState/replaceState */ - self.url = function(url, replace) { + self.url = function(url, replace, state) { + // In modern browsers `history.state` is `null` by default; treating it separately + // from `undefined` would cause `$browser.url('/foo')` to change `history.state` + // to undefined via `pushState`. Instead, let's change `undefined` to `null` here. + if (isUndefined(state)) { + state = null; + } + // Android Browser BFCache causes location, history reference to become stale. if (location !== window.location) location = window.location; if (history !== window.history) history = window.history; // setter if (url) { - if (lastBrowserUrl == url) return; + var sameState = lastHistoryState === state; + + // Don't change anything if previous and current URLs and states match. This also prevents + // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode. + // See https://github.com/angular/angular.js/commit/ffb2701 + if (lastBrowserUrl === url && (!$sniffer.history || sameState)) { + return self; + } + var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); lastBrowserUrl = url; - if ($sniffer.history) { - if (replace) history.replaceState(null, '', url); - else { - history.pushState(null, '', url); - // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 - baseElement.attr('href', baseElement.attr('href')); - } + lastHistoryState = state; + // Don't use history API if only the hash changed + // due to a bug in IE10/IE11 which leads + // to not firing a `hashchange` nor `popstate` event + // in some cases (see #9143). + if ($sniffer.history && (!sameBase || !sameState)) { + history[replace ? 'replaceState' : 'pushState'](state, '', url); + cacheState(); } else { - newLocation = url; + if (!sameBase) { + pendingLocation = url; + } if (replace) { location.replace(url); - } else { + } else if (!sameBase) { location.href = url; + } else { + location.hash = getHash(url); } + if (location.href !== url) { + pendingLocation = url; + } + } + if (pendingLocation) { + pendingLocation = url; } return self; // getter } else { - // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href - // methods not updating location.href synchronously. + // - pendingLocation is needed as browsers don't allow to read out + // the new location.href if a reload happened or if there is a bug like in iOS 9 (see + // https://openradar.appspot.com/22186109). // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 - return newLocation || location.href.replace(/%27/g,"'"); + return pendingLocation || location.href.replace(/%27/g,'\''); } }; + /** + * @name $browser#state + * + * @description + * This method is a getter. + * + * Return history.state or null if history.state is undefined. + * + * @returns {object} state + */ + self.state = function() { + return cachedState; + }; + var urlChangeListeners = [], urlChangeInit = false; - function fireUrlChange() { - newLocation = null; - if (lastBrowserUrl == self.url()) return; + function cacheStateAndFireUrlChange() { + pendingLocation = null; + fireStateOrUrlChange(); + } + + // This variable should be used *only* inside the cacheState function. + var lastCachedState = null; + function cacheState() { + // This should be the only place in $browser where `history.state` is read. + cachedState = getCurrentState(); + cachedState = isUndefined(cachedState) ? null : cachedState; + + // Prevent callbacks fo fire twice if both hashchange & popstate were fired. + if (equals(cachedState, lastCachedState)) { + cachedState = lastCachedState; + } + + lastCachedState = cachedState; + lastHistoryState = cachedState; + } + + function fireStateOrUrlChange() { + var prevLastHistoryState = lastHistoryState; + cacheState(); + + if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) { + return; + } lastBrowserUrl = self.url(); + lastHistoryState = cachedState; forEach(urlChangeListeners, function(listener) { - listener(self.url()); + listener(self.url(), cachedState); }); } @@ -4449,7 +6616,7 @@ * @description * Register callback function that will be called, when url changes. * - * It's only called when the url is changed from outside of angular: + * It's only called when the url is changed from outside of AngularJS: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link @@ -4459,7 +6626,7 @@ * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the - * {@link ng.$location $location service} to monitor url changes in angular apps. + * {@link ng.$location $location service} to monitor url changes in AngularJS apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. @@ -4467,16 +6634,14 @@ self.onUrlChange = function(callback) { // TODO(vojta): refactor to use node's syntax for events if (!urlChangeInit) { - // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) - // don't fire popstate when user change the address bar and don't fire hashchange when url + // We listen on both (hashchange/popstate) when available, as some browsers don't + // fire popstate when user changes the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event - if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange); + if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange); // hashchange event - if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange); - // polling - else self.addPollFn(fireUrlChange); + jqLite(window).on('hashchange', cacheStateAndFireUrlChange); urlChangeInit = true; } @@ -4485,6 +6650,23 @@ return callback; }; + /** + * @private + * Remove popstate and hashchange handler from window. + * + * NOTE: this api is intended for use only by $rootScope. + */ + self.$$applicationDestroyed = function() { + jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange); + }; + + /** + * Checks whether the url has changed outside of AngularJS. + * Needs to be exported to be able to check for changes that have been done in sync, + * as hashchange/popstate events fire in async. + */ + self.$$checkUrlChange = fireStateOrUrlChange; + ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// @@ -4500,85 +6682,9 @@ */ self.baseHref = function() { var href = baseElement.attr('href'); - return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; - }; - - ////////////////////////////////////////////////////////////// - // Cookies API - ////////////////////////////////////////////////////////////// - var lastCookies = {}; - var lastCookieString = ''; - var cookiePath = self.baseHref(); - - /** - * @name $browser#cookies - * - * @param {string=} name Cookie name - * @param {string=} value Cookie value - * - * @description - * The cookies method provides a 'private' low level access to browser cookies. - * It is not meant to be used directly, use the $cookie service instead. - * - * The return values vary depending on the arguments that the method was called with as follows: - * - * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify - * it - * - cookies(name, value) -> set name to value, if value is undefined delete the cookie - * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that - * way) - * - * @returns {Object} Hash of all cookies (if called without any parameter) - */ - self.cookies = function(name, value) { - /* global escape: false, unescape: false */ - var cookieLength, cookieArray, cookie, i, index; - - if (name) { - if (value === undefined) { - rawDocument.cookie = escape(name) + "=;path=" + cookiePath + - ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; - } else { - if (isString(value)) { - cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + - ';path=' + cookiePath).length + 1; - - // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: - // - 300 cookies - // - 20 cookies per unique domain - // - 4096 bytes per cookie - if (cookieLength > 4096) { - $log.warn("Cookie '"+ name + - "' possibly not set or overflowed because it was too large ("+ - cookieLength + " > 4096 bytes)!"); - } - } - } - } else { - if (rawDocument.cookie !== lastCookieString) { - lastCookieString = rawDocument.cookie; - cookieArray = lastCookieString.split("; "); - lastCookies = {}; - - for (i = 0; i < cookieArray.length; i++) { - cookie = cookieArray[i]; - index = cookie.indexOf('='); - if (index > 0) { //ignore nameless cookies - name = unescape(cookie.substring(0, index)); - // the first value that is seen for a cookie is the most - // specific one. values for the same cookie name that - // follow are for less specific paths. - if (lastCookies[name] === undefined) { - lastCookies[name] = unescape(cookie.substring(index + 1)); - } - } - } - } - return lastCookies; - } + return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : ''; }; - /** * @name $browser#defer * @param {function()} fn A function, who's execution should be deferred. @@ -4627,9 +6733,10 @@ } - function $BrowserProvider(){ + /** @this */ + function $BrowserProvider() { this.$get = ['$window', '$log', '$sniffer', '$document', - function( $window, $log, $sniffer, $document){ + function($window, $log, $sniffer, $document) { return new Browser($window, $document, $log, $sniffer); }]; } @@ -4637,6 +6744,7 @@ /** * @ngdoc service * @name $cacheFactory + * @this * * @description * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to @@ -4673,7 +6781,7 @@ * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. * * @example - +
    @@ -4701,8 +6809,10 @@ $scope.keys = []; $scope.cache = $cacheFactory('cacheId'); $scope.put = function(key, value) { - $scope.cache.put(key, value); - $scope.keys.push(key); + if (angular.isUndefined($scope.cache.get(key))) { + $scope.keys.push(key); + } + $scope.cache.put(key, angular.isUndefined(value) ? null : value); }; }]); @@ -4720,14 +6830,14 @@ function cacheFactory(cacheId, options) { if (cacheId in caches) { - throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); + throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId); } var size = 0, stats = extend({}, options, {id: cacheId}), - data = {}, + data = createMap(), capacity = (options && options.capacity) || Number.MAX_VALUE, - lruHash = {}, + lruHash = createMap(), freshEnd = null, staleEnd = null; @@ -4737,45 +6847,45 @@ * * @description * A cache object used to store and retrieve data, primarily used by - * {@link $http $http} and the {@link ng.directive:script script} directive to cache - * templates and other data. + * {@link $templateRequest $templateRequest} and the {@link ng.directive:script script} + * directive to cache templates and other data. * * ```js * angular.module('superCache') * .factory('superCache', ['$cacheFactory', function($cacheFactory) { - * return $cacheFactory('super-cache'); - * }]); + * return $cacheFactory('super-cache'); + * }]); * ``` * * Example test: * * ```js * it('should behave like a cache', inject(function(superCache) { - * superCache.put('key', 'value'); - * superCache.put('another key', 'another value'); - * - * expect(superCache.info()).toEqual({ - * id: 'super-cache', - * size: 2 - * }); - * - * superCache.remove('another key'); - * expect(superCache.get('another key')).toBeUndefined(); - * - * superCache.removeAll(); - * expect(superCache.info()).toEqual({ - * id: 'super-cache', - * size: 0 - * }); - * })); + * superCache.put('key', 'value'); + * superCache.put('another key', 'another value'); + * + * expect(superCache.info()).toEqual({ + * id: 'super-cache', + * size: 2 + * }); + * + * superCache.remove('another key'); + * expect(superCache.get('another key')).toBeUndefined(); + * + * superCache.removeAll(); + * expect(superCache.info()).toEqual({ + * id: 'super-cache', + * size: 0 + * }); + * })); * ``` */ - return caches[cacheId] = { + return (caches[cacheId] = { /** * @ngdoc method * @name $cacheFactory.Cache#put - * @function + * @kind function * * @description * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be @@ -4791,13 +6901,13 @@ * @returns {*} the value stored. */ put: function(key, value) { + if (isUndefined(value)) return; if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); } - if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; @@ -4811,7 +6921,7 @@ /** * @ngdoc method * @name $cacheFactory.Cache#get - * @function + * @kind function * * @description * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. @@ -4835,7 +6945,7 @@ /** * @ngdoc method * @name $cacheFactory.Cache#remove - * @function + * @kind function * * @description * Removes an entry from the {@link $cacheFactory.Cache Cache} object. @@ -4848,13 +6958,15 @@ if (!lruEntry) return; - if (lruEntry == freshEnd) freshEnd = lruEntry.p; - if (lruEntry == staleEnd) staleEnd = lruEntry.n; + if (lruEntry === freshEnd) freshEnd = lruEntry.p; + if (lruEntry === staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; } + if (!(key in data)) return; + delete data[key]; size--; }, @@ -4863,15 +6975,15 @@ /** * @ngdoc method * @name $cacheFactory.Cache#removeAll - * @function + * @kind function * * @description * Clears the cache object of any entries. */ removeAll: function() { - data = {}; + data = createMap(); size = 0; - lruHash = {}; + lruHash = createMap(); freshEnd = staleEnd = null; }, @@ -4879,7 +6991,7 @@ /** * @ngdoc method * @name $cacheFactory.Cache#destroy - * @function + * @kind function * * @description * Destroys the {@link $cacheFactory.Cache Cache} object entirely, @@ -4896,7 +7008,7 @@ /** * @ngdoc method * @name $cacheFactory.Cache#info - * @function + * @kind function * * @description * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. @@ -4912,17 +7024,17 @@ info: function() { return extend({}, stats, {size: size}); } - }; + }); /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { - if (entry != freshEnd) { + if (entry !== freshEnd) { if (!staleEnd) { staleEnd = entry; - } else if (staleEnd == entry) { + } else if (staleEnd === entry) { staleEnd = entry.n; } @@ -4938,7 +7050,7 @@ * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { - if (nextEntry != prevEntry) { + if (nextEntry !== prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } @@ -4951,7 +7063,7 @@ * @name $cacheFactory#info * * @description - * Get information about all the of the caches that have been created + * Get information about all the caches that have been created * * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` */ @@ -4986,11 +7098,15 @@ /** * @ngdoc service * @name $templateCache + * @this * * @description + * `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the + * {@link ng.$cacheFactory $cacheFactory}. + * * The first time a template is used, it is loaded in the template cache for quick retrieval. You - * can load templates directly into the cache in a `script` tag, or by consuming the - * `$templateCache` service directly. + * can load templates directly into the cache in a `script` tag, by using {@link $templateRequest}, + * or by consuming the `$templateCache` service directly. * * Adding via the `script` tag: * @@ -5001,29 +7117,30 @@ * ``` * * **Note:** the `script` tag containing the template does not need to be included in the `head` of - * the document, but it must be below the `ng-app` definition. + * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g. + * element with {@link ngApp} attribute), otherwise the template will be ignored. * - * Adding via the $templateCache service: + * Adding via the `$templateCache` service: * * ```js * var myApp = angular.module('myApp', []); * myApp.run(function($templateCache) { - * $templateCache.put('templateId.html', 'This is the content of the template'); - * }); + * $templateCache.put('templateId.html', 'This is the content of the template'); + * }); * ``` * - * To retrieve the template later, simply use it in your HTML: - * ```html - *
    + * To retrieve the template later, simply use it in your component: + * ```js + * myApp.component('myComponent', { + * templateUrl: 'templateId.html' + * }); * ``` * - * or get it via Javascript: + * or get it via the `$templateCache` service: * ```js * $templateCache.get('templateId.html') * ``` * - * See {@link ng.$cacheFactory $cacheFactory}. - * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { @@ -5031,28 +7148,39 @@ }]; } + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Any commits to this file should be reviewed with security in mind. * + * Changes to this file can potentially create security vulnerabilities. * + * An approval from 2 Core members with history of modifying * + * this file is required. * + * * + * Does the change somehow allow for arbitrary javascript to be executed? * + * Or allows for someone to change the prototype of built-in objects? * + * Or gives undesired access to variables like document or window? * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! - * - * DOM-related variables: - * - * - "node" - DOM Node - * - "element" - DOM Element or Node - * - "$node" or "$element" - jqLite-wrapped node or element - * - * - * Compiler related stuff: - * - * - "linkFn" - linking fn of a single directive - * - "nodeLinkFn" - function that aggregates all linking fns for a particular node - * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node - * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) - */ + * + * DOM-related variables: + * + * - "node" - DOM Node + * - "element" - DOM Element or Node + * - "$node" or "$element" - jqLite-wrapped node or element + * + * + * Compiler related stuff: + * + * - "linkFn" - linking fn of a single directive + * - "nodeLinkFn" - function that aggregates all linking fns for a particular node + * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node + * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) + */ /** * @ngdoc service * @name $compile - * @function + * @kind function * * @description * Compiles an HTML string or DOM into a template and produces a template function, which @@ -5072,8 +7200,9 @@ * There are many different options for a directive. * * The difference resides in the return value of the factory function. - * You can either return a "Directive Definition Object" (see below) that defines the directive properties, - * or just the `postLink` function (all other properties will have the default values). + * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)} + * that defines the directive properties, or just the `postLink` function (all other properties will have + * the default values). * *
    * **Best Practice:** It's recommended to use the "directive definition object" form. @@ -5085,36 +7214,38 @@ * var myModule = angular.module(...); * * myModule.directive('directiveName', function factory(injectables) { - * var directiveDefinitionObject = { - * priority: 0, - * template: '
    ', // or // function(tElement, tAttrs) { ... }, - * // or - * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, - * replace: false, - * transclude: false, - * restrict: 'A', - * scope: false, - * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, - * controllerAs: 'stringAlias', - * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], - * compile: function compile(tElement, tAttrs, transclude) { - * return { - * pre: function preLink(scope, iElement, iAttrs, controller) { ... }, - * post: function postLink(scope, iElement, iAttrs, controller) { ... } - * } - * // or - * // return function postLink( ... ) { ... } - * }, - * // or - * // link: { - * // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, - * // post: function postLink(scope, iElement, iAttrs, controller) { ... } - * // } - * // or - * // link: function postLink( ... ) { ... } - * }; - * return directiveDefinitionObject; - * }); + * var directiveDefinitionObject = { + * {@link $compile#-priority- priority}: 0, + * {@link $compile#-template- template}: '
    ', // or // function(tElement, tAttrs) { ... }, + * // or + * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... }, + * {@link $compile#-transclude- transclude}: false, + * {@link $compile#-restrict- restrict}: 'A', + * {@link $compile#-templatenamespace- templateNamespace}: 'html', + * {@link $compile#-scope- scope}: false, + * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, + * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier', + * {@link $compile#-bindtocontroller- bindToController}: false, + * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], + * {@link $compile#-multielement- multiElement}: false, + * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) { + * return { + * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... }, + * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... } + * } + * // or + * // return function postLink( ... ) { ... } + * }, + * // or + * // {@link $compile#-link- link}: { + * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... }, + * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... } + * // } + * // or + * // {@link $compile#-link- link}: function postLink( ... ) { ... } + * }; + * return directiveDefinitionObject; + * }); * ``` * *
    @@ -5127,21 +7258,148 @@ * var myModule = angular.module(...); * * myModule.directive('directiveName', function factory(injectables) { - * var directiveDefinitionObject = { - * link: function postLink(scope, iElement, iAttrs) { ... } - * }; - * return directiveDefinitionObject; - * // or - * // return function postLink(scope, iElement, iAttrs) { ... } - * }); + * var directiveDefinitionObject = { + * link: function postLink(scope, iElement, iAttrs) { ... } + * }; + * return directiveDefinitionObject; + * // or + * // return function postLink(scope, iElement, iAttrs) { ... } + * }); * ``` * + * ### Life-cycle hooks + * Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the + * directive: + * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and + * had their bindings initialized (and before the pre & post linking functions for the directives on + * this element). This is a good place to put initialization code for your controller. + * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The + * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an + * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a + * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will + * also be called when your bindings are initialized. + * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on + * changes. Any actions that you wish to take in response to the changes that you detect must be + * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook + * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not + * be detected by AngularJS's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; + * if detecting changes, you must store the previous value(s) for comparison to the current values. + * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing + * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in + * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent + * components will have their `$onDestroy()` hook called before child components. + * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link + * function this hook can be used to set up DOM event handlers and do direct DOM manipulation. + * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since + * they are waiting for their template to load asynchronously and their own compilation and linking has been + * suspended until that occurs. + * + * #### Comparison with life-cycle hooks in the new Angular + * The new Angular also uses life-cycle hooks for its components. While the AngularJS life-cycle hooks are similar there are + * some differences that you should be aware of, especially when it comes to moving your code from AngularJS to Angular: + * + * * AngularJS hooks are prefixed with `$`, such as `$onInit`. Angular hooks are prefixed with `ng`, such as `ngOnInit`. + * * AngularJS hooks can be defined on the controller prototype or added to the controller inside its constructor. + * In Angular you can only define hooks on the prototype of the Component class. + * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in AngularJS than you would to + * `ngDoCheck` in Angular. + * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be + * propagated throughout the application. + * Angular does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an + * error or do nothing depending upon the state of `enableProdMode()`. + * + * #### Life-cycle hook examples + * + * This example shows how you can check for mutations to a Date object even though the identity of the object + * has not changed. + * + * + * + * angular.module('do-check-module', []) + * .component('app', { + * template: + * 'Month: ' + + * 'Date: {{ $ctrl.date }}' + + * '', + * controller: function() { + * this.date = new Date(); + * this.month = this.date.getMonth(); + * this.updateDate = function() { + * this.date.setMonth(this.month); + * }; + * } + * }) + * .component('test', { + * bindings: { date: '<' }, + * template: + * '
    {{ $ctrl.log | json }}
    ', + * controller: function() { + * var previousValue; + * this.log = []; + * this.$doCheck = function() { + * var currentValue = this.date && this.date.valueOf(); + * if (previousValue !== currentValue) { + * this.log.push('doCheck: date mutated: ' + this.date); + * previousValue = currentValue; + * } + * }; + * } + * }); + *
    + * + * + * + *
    * + * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the + * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large + * arrays or objects can have a negative impact on your application performance) * - * ### Directive Definition Object - * - * The directive definition object provides instructions to the {@link ng.$compile - * compiler}. The attributes are: + * + * + *
    + * + * + *
    {{ items }}
    + * + *
    + *
    + * + * angular.module('do-check-module', []) + * .component('test', { + * bindings: { items: '<' }, + * template: + * '
    {{ $ctrl.log | json }}
    ', + * controller: function() { + * this.log = []; + * + * this.$doCheck = function() { + * if (this.items_ref !== this.items) { + * this.log.push('doCheck: items changed'); + * this.items_ref = this.items; + * } + * if (!angular.equals(this.items_clone, this.items)) { + * this.log.push('doCheck: items mutated'); + * this.items_clone = angular.copy(this.items); + * } + * }; + * } + * }); + *
    + *
    + * + * + * ### Directive Definition Object + * + * The directive definition object provides instructions to the {@link ng.$compile + * compiler}. The attributes are: + * + * #### `multiElement` + * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between + * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them + * together as the directive elements. It is recommended that this feature be used on directives + * which are not strictly behavioral (such as {@link ngClick}), and which + * do not manipulate or replace child nodes (such as {@link ngInclude}). * * #### `priority` * When there are multiple directives defined on a single DOM element, sometimes it @@ -5154,136 +7412,269 @@ * #### `terminal` * If set to true then the current `priority` will be the last set of directives * which will execute (any directives at the current priority will still execute - * as the order of execution on same `priority` is undefined). + * as the order of execution on same `priority` is undefined). Note that expressions + * and other directives used in the directive's template will also be excluded from execution. * * #### `scope` - * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the - * same element request a new scope, only one new scope is created. The new scope rule does not - * apply for the root of the template since the root of the template always gets a new scope. + * The scope property can be `false`, `true`, or an object: * - * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from - * normal scope in that it does not prototypically inherit from the parent scope. This is useful - * when creating reusable components, which should not accidentally read or modify data in the - * parent scope. + * * **`false` (default):** No scope will be created for the directive. The directive will use its + * parent's scope. * - * The 'isolate' scope takes an object hash which defines a set of local scope properties - * derived from the parent scope. These local properties are useful for aliasing values for - * templates. Locals definition is a hash of local scope property to its source: + * * **`true`:** A new child scope that prototypically inherits from its parent will be created for + * the directive's element. If multiple directives on the same element request a new scope, + * only one new scope is created. + * + * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template. + * The 'isolate' scope differs from normal scope in that it does not prototypically + * inherit from its parent scope. This is useful when creating reusable components, which should not + * accidentally read or modify data in the parent scope. Note that an isolate scope + * directive without a `template` or `templateUrl` will not apply the isolate scope + * to its children elements. + * + * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the + * directive's element. These local properties are useful for aliasing values for templates. The keys in + * the object hash map to the name of the property on the isolate scope; the values define how the property + * is bound to the parent scope, via matching attributes on the directive's element: * * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is - * always a string since DOM attributes are strings. If no `attr` name is specified then the - * attribute name is assumed to be the same as the local name. - * Given `` and widget definition - * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect - * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the - * `localName` property on the widget scope. The `name` is read from the parent scope (not - * component scope). - * - * * `=` or `=attr` - set up bi-directional binding between a local scope property and the - * parent scope property of name defined via the value of the `attr` attribute. If no `attr` - * name is specified then the attribute name is assumed to be the same as the local name. - * Given `` and widget definition of - * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the + * always a string since DOM attributes are strings. If no `attr` name is specified then the + * attribute name is assumed to be the same as the local name. Given `` and the isolate scope definition `scope: { localName:'@myAttr' }`, + * the directive's scope property `localName` will reflect the interpolated value of `hello + * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's + * scope. The `name` is read from the parent scope (not the directive's scope). + * + * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression + * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope. + * If no `attr` name is specified then the attribute name is assumed to be the same as the local + * name. Given `` and the isolate scope definition `scope: { + * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the + * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in + * `localModel` and vice versa. Optional attributes should be marked as such with a question mark: + * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't + * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`}) + * will be thrown upon discovering changes to the local value, since it will be impossible to sync + * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`} + * method is used for tracking changes, and the equality check is based on object identity. + * However, if an object literal or an array literal is passed as the binding expression, the + * equality check is done by value (using the {@link angular.equals} function). It's also possible + * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection + * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional). + * + * * `<` or `` and directive definition of + * `scope: { localModel:'` and the isolate scope definition `scope: { + * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for + * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope + * via an expression to the parent scope. This can be done by passing a map of local variable names + * and values into the expression wrapper fn. For example, if the expression is `increment(amount)` + * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`. + * + * In general it's possible to apply more than one directive to one element, but there might be limitations + * depending on the type of scope required by the directives. The following points will help explain these limitations. + * For simplicity only two directives are taken into account, but it is also applicable for several directives: + * + * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope + * * **child scope** + **no scope** => Both directives will share one single child scope + * * **child scope** + **child scope** => Both directives will share one single child scope + * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use + * its parent's scope + * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot + * be applied to the same element. + * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives + * cannot be applied to the same element. + * + * + * #### `bindToController` + * This property is used to bind scope properties directly to the controller. It can be either + * `true` or an object hash with the same format as the `scope` property. + * + * When an isolate scope is used for a directive (see above), `bindToController: true` will + * allow a component to have its properties bound to the controller, rather than to scope. + * + * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller + * properties. You can access these bindings once they have been initialized by providing a controller method called + * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings + * initialized. + * + *
    + * **Deprecation warning:** if `$compileProcvider.preAssignBindingsEnabled(true)` was called, bindings for non-ES6 class + * controllers are bound to `this` before the controller constructor is called but this use is now deprecated. Please + * place initialization code that relies upon bindings inside a `$onInit` method on the controller, instead. + *
    * - * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. - * If no `attr` name is specified then the attribute name is assumed to be the same as the - * local name. Given `` and widget definition of - * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to - * a function wrapper for the `count = count + value` expression. Often it's desirable to - * pass data from the isolated scope via an expression and to the parent scope, this can be - * done by passing a map of local variable names and values into the expression wrapper fn. - * For example, if the expression is `increment(amount)` then we can specify the amount value - * by calling the `localFn` as `localFn({amount: 22})`. + * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property. + * This will set up the scope bindings to the controller directly. Note that `scope` can still be used + * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate + * scope (useful for component directives). * + * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`. * * * #### `controller` * Controller constructor function. The controller is instantiated before the - * pre-linking phase and it is shared with other directives (see + * pre-linking phase and can be accessed by other directives (see * `require` attribute). This allows the directives to communicate with each other and augment * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: * * * `$scope` - Current scope associated with the element * * `$element` - Current element * * `$attrs` - Current attributes object for the element - * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope. - * The scope can be overridden by an optional first argument. - * `function([scope], cloneLinkingFn)`. - * + * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope: + * `function([scope], cloneLinkingFn, futureParentElement, slotName)`: + * * `scope`: (optional) override the scope. + * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content. + * * `futureParentElement` (optional): + * * defines the parent to which the `cloneLinkingFn` will add the cloned elements. + * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`. + * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements) + * and when the `cloneLinkingFn` is passed, + * as those elements need to created and cloned in a special way when they are defined outside their + * usual containers (e.g. like ``). + * * See also the `directive.templateNamespace` property. + * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`) + * then the default transclusion is provided. + * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns + * `true` if the specified slot contains content (i.e. one or more DOM nodes). * * #### `require` * Require another directive and inject its controller as the fourth argument to the linking function. The - * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the - * injected argument will be an array in corresponding order. If no such directive can be - * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: + * `require` property can be a string, an array or an object: + * * a **string** containing the name of the directive to pass to the linking function + * * an **array** containing the names of directives to pass to the linking function. The argument passed to the + * linking function will be an array of controllers in the same order as the names in the `require` property + * * an **object** whose property values are the names of the directives to pass to the linking function. The argument + * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding + * controllers. + * + * If the `require` property is an object and `bindToController` is truthy, then the required controllers are + * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers + * have been constructed but before `$onInit` is called. + * If the name of the required controller is the same as the local name (the key), the name can be + * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`. + * See the {@link $compileProvider#component} helper for an example of how this can be used. + * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is + * raised (unless no link function is specified and the required controllers are not being bound to the directive + * controller, in which case error checking is skipped). The name can be prefixed with: * * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. - * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found. - * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the - * `link` fn if not found. + * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found. + * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found. + * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass + * `null` to the `link` fn if not found. + * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass + * `null` to the `link` fn if not found. * * * #### `controllerAs` - * Controller alias at the directive scope. An alias for the controller so it - * can be referenced at the directive template. The directive needs to define a scope for this - * configuration to be used. Useful in the case when directive is used as component. + * Identifier name for a reference to the controller in the directive's scope. + * This allows the controller to be referenced from the directive template. This is especially + * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible + * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the + * `controllerAs` reference might overwrite a property that already exists on the parent scope. * * * #### `restrict` * String of subset of `EACM` which restricts the directive to a specific directive - * declaration style. If omitted, the default (attributes only) is used. + * declaration style. If omitted, the defaults (elements and attributes) are used. * - * * `E` - Element name: `` + * * `E` - Element name (default): `` * * `A` - Attribute (default): `
    ` * * `C` - Class: `
    ` * * `M` - Comment: `` * * + * #### `templateNamespace` + * String representing the document type used by the markup in the template. + * AngularJS needs this information as those elements need to be created and cloned + * in a special way when they are defined outside their usual containers like `` and ``. + * + * * `html` - All root nodes in the template are HTML. Root nodes may also be + * top-level elements such as `` or ``. + * * `svg` - The root nodes in the template are SVG elements (excluding ``). + * * `math` - The root nodes in the template are MathML elements (excluding ``). + * + * If no `templateNamespace` is specified, then the namespace is considered to be `html`. + * * #### `template` - * replace the current element with the contents of the HTML. The replacement process - * migrates all of the attributes / classes from the old element to the new one. See the - * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive - * Directives Guide} for an example. + * HTML markup that may: + * * Replace the contents of the directive's element (default). + * * Replace the directive's element itself (if `replace` is true - DEPRECATED). + * * Wrap the contents of the directive's element (if `transclude` is true). * - * You can specify `template` as a string representing the template or as a function which takes - * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and - * returns a string value representing the template. + * Value may be: + * + * * A string. For example `
    {{delete_str}}
    `. + * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile` + * function api below) and returns a string value. * * * #### `templateUrl` - * Same as `template` but the template is loaded from the specified URL. Because - * the template loading is asynchronous the compilation/linking is suspended until the template - * is loaded. + * This is similar to `template` but the template is loaded from the specified URL, asynchronously. + * + * Because template loading is asynchronous the compiler will suspend compilation of directives on that element + * for later when the template has been resolved. In the meantime it will continue to compile and link + * sibling and parent elements as though this element had not contained any directives. + * + * The compiler does not suspend the entire compilation to wait for templates to be loaded because this + * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the + * case when only one deeply nested directive has `templateUrl`. + * + * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache} * * You can specify `templateUrl` as a string representing the URL or as a function which takes two * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns * a string value representing the url. In either case, the template URL is passed through {@link - * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. + * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. * * - * #### `replace` - * specify where the template should be inserted. Defaults to `false`. + * #### `replace` (*DEPRECATED*) * - * * `true` - the template will replace the current element. - * * `false` - the template will replace the contents of the current element. + * `replace` will be removed in next major release - i.e. v2.0). * + * Specifies what the template should replace. Defaults to `false`. * - * #### `transclude` - * compile the content of the element and make it available to the directive. - * Typically used with {@link ng.directive:ngTransclude - * ngTransclude}. The advantage of transclusion is that the linking function receives a - * transclusion function which is pre-bound to the correct scope. In a typical setup the widget - * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate` - * scope. This makes it possible for the widget to have private state, and the transclusion to - * be bound to the parent (pre-`isolate`) scope. + * * `true` - the template will replace the directive's element. + * * `false` - the template will replace the contents of the directive's element. + * + * The replacement process migrates all of the attributes / classes from the old element to the new + * one. See the {@link guide/directive#template-expanding-directive + * Directives Guide} for an example. + * + * There are very few scenarios where element replacement is required for the application function, + * the main one being reusable custom components that are used within SVG contexts + * (because SVG doesn't work with custom elements in the DOM tree). * - * * `true` - transclude the content of the directive. - * * `'element'` - transclude the whole element including any directives defined at lower priority. + * #### `transclude` + * Extract the contents of the element where the directive appears and make it available to the directive. + * The contents are compiled and provided to the directive as a **transclusion function**. See the + * {@link $compile#transclusion Transclusion} section below. * * * #### `compile` @@ -5293,11 +7684,7 @@ * ``` * * The compile function deals with transforming the template DOM. Since most directives do not do - * template transformation, it is not used often. Examples that require compile functions are - * directives that transform template DOM, such as {@link - * api/ng.directive:ngRepeat ngRepeat}, or load the contents - * asynchronously, such as {@link ngRoute.directive:ngView ngView}. The - * compile function takes the following arguments. + * template transformation, it is not used often. The compile function takes the following arguments: * * * `tElement` - template element - The element where the directive has been declared. It is * safe to do template transformation on the element and child elements only. @@ -5316,7 +7703,7 @@ *
    * **Note:** The compile function cannot handle directives that recursively use themselves in their - * own templates or compile functions. Compiling these directives results in an infinite loop and a + * own templates or compile functions. Compiling these directives results in an infinite loop and * stack overflow errors. * * This can be avoided by manually using $compile in the postLink function to imperatively compile @@ -5324,7 +7711,7 @@ * `templateUrl` declaration or manual compilation inside the compile function. *
    * - *
    + *
    * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it * e.g. does not know about the right outer scope. Please use the transclude function that is passed * to the link function instead. @@ -5361,15 +7748,23 @@ * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared * between all directive linking functions. * - * * `controller` - a controller instance - A controller instance if at least one directive on the - * element defines a controller. The controller is shared among all the directives, which allows - * the directives to use the controllers as a communication channel. + * * `controller` - the directive's required controller instance(s) - Instances are shared + * among all directives, which allows the directives to use the controllers as a communication + * channel. The exact value depends on the directive's `require` property: + * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one + * * `string`: the controller instance + * * `array`: array of controller instances * - * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. - * The scope can be overridden by an optional first argument. This is the same as the `$transclude` - * parameter of directive controllers. - * `function([scope], cloneLinkingFn)`. + * If a required controller cannot be found, and it is optional, the instance is `null`, + * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown. * + * Note that you can also require the directive's own controller - it will be made available like + * any other controller. + * + * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. + * This is the same as the `$transclude` parameter of directive controllers, + * see {@link ng.$compile#-controller- the controller section for details}. + * `function([scope], cloneLinkingFn, futureParentElement)`. * * #### Pre-linking function * @@ -5378,18 +7773,166 @@ * * #### Post-linking function * - * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function. + * Executed after the child elements are linked. + * + * Note that child elements that contain `templateUrl` directives will not have been compiled + * and linked since they are waiting for their template to load asynchronously and their own + * compilation and linking has been suspended until that occurs. + * + * It is safe to do DOM transformation in the post-linking function on elements that are not waiting + * for their async templates to be resolved. + * + * + * ### Transclusion + * + * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and + * copying them to another part of the DOM, while maintaining their connection to the original AngularJS + * scope from where they were taken. + * + * Transclusion is used (often with {@link ngTransclude}) to insert the + * original contents of a directive's element into a specified place in the template of the directive. + * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded + * content has access to the properties on the scope from which it was taken, even if the directive + * has isolated scope. + * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}. + * + * This makes it possible for the widget to have private state for its template, while the transcluded + * content has access to its originating scope. + * + *
    + * **Note:** When testing an element transclude directive you must not place the directive at the root of the + * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives + * Testing Transclusion Directives}. + *
    + * + * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the + * directive's element, the entire element or multiple parts of the element contents: + * + * * `true` - transclude the content (i.e. the child nodes) of the directive's element. + * * `'element'` - transclude the whole of the directive's element including any directives on this + * element that defined at a lower priority than this directive. When used, the `template` + * property is ignored. + * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template. + * + * **Mult-slot transclusion** is declared by providing an object for the `transclude` property. + * + * This object is a map where the keys are the name of the slot to fill and the value is an element selector + * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`) + * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc). + * + * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives} + * + * If the element selector is prefixed with a `?` then that slot is optional. + * + * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `` elements to + * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive. + * + * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements + * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call + * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and + * injectable into the directive's controller. + * + * + * #### Transclusion Functions + * + * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion + * function** to the directive's `link` function and `controller`. This transclusion function is a special + * **linking function** that will return the compiled contents linked to a new transclusion scope. + * + *
    + * If you are just using {@link ngTransclude} then you don't need to worry about this function, since + * ngTransclude will deal with it for us. + *
    + * + * If you want to manually control the insertion and removal of the transcluded content in your directive + * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery + * object that contains the compiled DOM, which is linked to the correct transclusion scope. + * + * When you call a transclusion function you can pass in a **clone attach function**. This function accepts + * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded + * content and the `scope` is the newly created transclusion scope, which the clone will be linked to. + * + *
    + * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function + * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope. + *
    + * + * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone + * attach function**: + * + * ```js + * var transcludedContent, transclusionScope; + * + * $transclude(function(clone, scope) { + * element.append(clone); + * transcludedContent = clone; + * transclusionScope = scope; + * }); + * ``` + * + * Later, if you want to remove the transcluded content from your DOM then you should also destroy the + * associated transclusion scope: + * + * ```js + * transcludedContent.remove(); + * transclusionScope.$destroy(); + * ``` + * + *
    + * **Best Practice**: if you intend to add and remove transcluded content manually in your directive + * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it), + * then you are also responsible for calling `$destroy` on the transclusion scope. + *
    + * + * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat} + * automatically destroy their transcluded clones as necessary so you do not need to worry about this if + * you are simply using {@link ngTransclude} to inject the transclusion into your directive. + * + * + * #### Transclusion Scopes + * + * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion + * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed + * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it + * was taken. + * + * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look + * like this: + * + * ```html + *
    + *
    + *
    + *
    + *
    + *
    + * ``` + * + * The `$parent` scope hierarchy will look like this: + * + ``` + - $rootScope + - isolate + - transclusion + ``` + * + * but the scopes will inherit prototypically from different scopes to their `$parent`. + * + ``` + - $rootScope + - transclusion + - isolate + ``` + * * - * * ### Attributes * * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the * `link()` or `compile()` functions. It has a variety of uses. * - * accessing *Normalized attribute names:* - * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. - * the attributes object allows for normalized access to - * the attributes. + * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways: + * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access + * to the attributes. * * * *Directive inter-communication:* All directives share the same instance of the attributes * object which allows the directives to use the attributes object as inter directive @@ -5405,30 +7948,30 @@ * * ```js * function linkingFn(scope, elm, attrs, ctrl) { - * // get the attribute value - * console.log(attrs.ngModel); - * - * // change the attribute - * attrs.$set('ngModel', 'new value'); - * - * // observe changes to interpolated attribute - * attrs.$observe('ngModel', function(value) { - * console.log('ngModel has changed value to ' + value); - * }); - * } + * // get the attribute value + * console.log(attrs.ngModel); + * + * // change the attribute + * attrs.$set('ngModel', 'new value'); + * + * // observe changes to interpolated attribute + * attrs.$observe('ngModel', function(value) { + * console.log('ngModel has changed value to ' + value); + * }); + * } * ``` * - * Below is an example using `$compileProvider`. + * ## Example * *
    * **Note**: Typically directives are registered with `module.directive`. The example below is * to illustrate how `$compile` works. *
    * - + -
    -
    -
    +
    +
    +
    @@ -5470,11 +8012,11 @@ it('should auto compile', function() { var textarea = $('textarea'); var output = $('div[compile]'); - // The initial state reads 'Hello Angular'. - expect(output.getText()).toBe('Hello Angular'); + // The initial state reads 'Hello AngularJS'. + expect(output.getText()).toBe('Hello AngularJS'); textarea.clear(); textarea.sendKeys('{{name}}!'); - expect(output.getText()).toBe('Angular!'); + expect(output.getText()).toBe('AngularJS!'); }); @@ -5482,26 +8024,53 @@ * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. - * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives. + * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED. + * + *
    + * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it + * e.g. will not use the right outer scope. Please pass the transclude function as a + * `parentBoundTranscludeFn` to the link function instead. + *
    + * * @param {number} maxPriority only apply directives lower than given priority (Only effects the * root element(s), not their children) - * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template + * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is - * called as:
    `cloneAttachFn(clonedElement, scope)` where: + * called as:
    `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * + * * `options` - An optional object hash with linking options. If `options` is provided, then the following + * keys may be used to control linking behavior: + * + * * `parentBoundTranscludeFn` - the transclude function made available to + * directives; if given, it will be passed through to the link functions of + * directives found in `element` during compilation. + * * `transcludeControllers` - an object hash with keys that map controller names + * to a hash with the key `instance`, which maps to the controller instance; + * if given, it will make the controllers available to directives on the compileNode: + * ``` + * { + * parent: { + * instance: parentControllerInstance + * } + * } + * ``` + * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add + * the cloned elements; only needed for transcludes that are allowed to contain non html + * elements (e.g. SVG elements). See also the directive.controller property. + * * Calling the linking function returns the element of the template. It is either the original * element passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by - * Angular automatically. + * AngularJS automatically. * * If you need access to the bound view, there are two ways to do it: * @@ -5519,42 +8088,158 @@ * scope = ....; * * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { - * //attach the clone to DOM document at the right place - * }); + * //attach the clone to DOM document at the right place + * }); * * //now we have reference to the cloned DOM via `clonedElement` * ``` * * * For information on how the compiler works, see the - * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. + * {@link guide/compiler AngularJS HTML Compiler} section of the Developer Guide. + * + * @knownIssue + * + * ### Double Compilation + * + Double compilation occurs when an already compiled part of the DOM gets + compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues, + and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it + section on double compilation} for an in-depth explanation and ways to avoid it. + * */ var $compileMinErr = minErr('$compile'); + function UNINITIALIZED_VALUE() {} + var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE(); + /** * @ngdoc provider * @name $compileProvider - * @function * * @description */ $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; + /** @this */ function $CompileProvider($provide, $$sanitizeUriProvider) { var hasDirectives = {}, Suffix = 'Directive', - COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, - CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/; + COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/, + CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/, + ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'), + REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/; // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes // The assumption is that future DOM event attribute names will begin with // 'on' and be composed of only English letters. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; + var bindingCache = createMap(); + + function parseIsolateBindings(scope, directiveName, isController) { + var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/; + + var bindings = createMap(); + + forEach(scope, function(definition, scopeName) { + if (definition in bindingCache) { + bindings[scopeName] = bindingCache[definition]; + return; + } + var match = definition.match(LOCAL_REGEXP); + + if (!match) { + throw $compileMinErr('iscp', + 'Invalid {3} for directive \'{0}\'.' + + ' Definition: {... {1}: \'{2}\' ...}', + directiveName, scopeName, definition, + (isController ? 'controller bindings definition' : + 'isolate scope definition')); + } + + bindings[scopeName] = { + mode: match[1][0], + collection: match[2] === '*', + optional: match[3] === '?', + attrName: match[4] || scopeName + }; + if (match[4]) { + bindingCache[definition] = bindings[scopeName]; + } + }); + + return bindings; + } + + function parseDirectiveBindings(directive, directiveName) { + var bindings = { + isolateScope: null, + bindToController: null + }; + if (isObject(directive.scope)) { + if (directive.bindToController === true) { + bindings.bindToController = parseIsolateBindings(directive.scope, + directiveName, true); + bindings.isolateScope = {}; + } else { + bindings.isolateScope = parseIsolateBindings(directive.scope, + directiveName, false); + } + } + if (isObject(directive.bindToController)) { + bindings.bindToController = + parseIsolateBindings(directive.bindToController, directiveName, true); + } + if (bindings.bindToController && !directive.controller) { + // There is no controller + throw $compileMinErr('noctrl', + 'Cannot bind to controller without directive \'{0}\'s controller.', + directiveName); + } + return bindings; + } + + function assertValidDirectiveName(name) { + var letter = name.charAt(0); + if (!letter || letter !== lowercase(letter)) { + throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name); + } + if (name !== name.trim()) { + throw $compileMinErr('baddir', + 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces', + name); + } + } + + function getDirectiveRequire(directive) { + var require = directive.require || (directive.controller && directive.name); + + if (!isArray(require) && isObject(require)) { + forEach(require, function(value, key) { + var match = value.match(REQUIRE_PREFIX_REGEXP); + var name = value.substring(match[0].length); + if (!name) require[key] = match[0] + key; + }); + } + + return require; + } + + function getDirectiveRestrict(restrict, name) { + if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) { + throw $compileMinErr('badrestrict', + 'Restrict property \'{0}\' of directive \'{1}\' is invalid', + restrict, + name); + } + + return restrict || 'EA'; + } /** * @ngdoc method * @name $compileProvider#directive - * @function + * @kind function * * @description * Register a new directive with the compiler. @@ -5562,13 +8247,15 @@ * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which * will match as ng-bind), or an object map of directives where the keys are the * names and the values are the factories. - * @param {Function|Array} directiveFactory An injectable directive factory function. See - * {@link guide/directive} for more info. + * @param {Function|Array} directiveFactory An injectable directive factory function. See the + * {@link guide/directive directive guide} and the {@link $compile compile API} for more info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { + assertArg(name, 'name'); assertNotHasOwnProperty(name, 'directive'); if (isString(name)) { + assertValidDirectiveName(name); assertArg(directiveFactory, 'directiveFactory'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; @@ -5586,8 +8273,9 @@ directive.priority = directive.priority || 0; directive.index = index; directive.name = directive.name || name; - directive.require = directive.require || (directive.controller && directive.name); - directive.restrict = directive.restrict || 'A'; + directive.require = getDirectiveRequire(directive); + directive.restrict = getDirectiveRestrict(directive.restrict, name); + directive.$$moduleName = directiveFactory.$$moduleName; directives.push(directive); } catch (e) { $exceptionHandler(e); @@ -5603,17 +8291,164 @@ return this; }; + /** + * @ngdoc method + * @name $compileProvider#component + * @module ng + * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match ``), + * or an object map of components where the keys are the names and the values are the component definition objects. + * @param {Object} options Component definition object (a simplified + * {@link ng.$compile#directive-definition-object directive definition object}), + * with the following properties (all optional): + * + * - `controller` – `{(string|function()=}` – controller constructor function that should be + * associated with newly created scope or the name of a {@link ng.$compile#-controller- + * registered controller} if passed as a string. An empty `noop` function by default. + * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope. + * If present, the controller will be published to scope under the `controllerAs` name. + * If not present, this will default to be `$ctrl`. + * - `template` – `{string=|function()=}` – html template as a string or a function that + * returns an html template as a string which should be used as the contents of this component. + * Empty string by default. + * + * If `template` is a function, then it is {@link auto.$injector#invoke injected} with + * the following locals: + * + * - `$element` - Current element + * - `$attrs` - Current attributes object for the element + * + * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html + * template that should be used as the contents of this component. + * + * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with + * the following locals: + * + * - `$element` - Current element + * - `$attrs` - Current attributes object for the element + * + * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties. + * Component properties are always bound to the component controller and not to the scope. + * See {@link ng.$compile#-bindtocontroller- `bindToController`}. + * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled. + * Disabled by default. + * - `require` - `{Object=}` - requires the controllers of other directives and binds them to + * this component's controller. The object keys specify the property names under which the required + * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}. + * - `$...` – additional properties to attach to the directive factory function and the controller + * constructor function. (This is used by the component router to annotate) + * + * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls. + * @description + * Register a **component definition** with the compiler. This is a shorthand for registering a special + * type of directive, which represents a self-contained UI component in your application. Such components + * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`). + * + * Component definitions are very simple and do not require as much configuration as defining general + * directives. Component definitions usually consist only of a template and a controller backing it. + * + * In order to make the definition easier, components enforce best practices like use of `controllerAs`, + * `bindToController`. They always have **isolate scope** and are restricted to elements. + * + * Here are a few examples of how you would usually define components: + * + * ```js + * var myMod = angular.module(...); + * myMod.component('myComp', { + * template: '
    My name is {{$ctrl.name}}
    ', + * controller: function() { + * this.name = 'shahar'; + * } + * }); + * + * myMod.component('myComp', { + * template: '
    My name is {{$ctrl.name}}
    ', + * bindings: {name: '@'} + * }); + * + * myMod.component('myComp', { + * templateUrl: 'views/my-comp.html', + * controller: 'MyCtrl', + * controllerAs: 'ctrl', + * bindings: {name: '@'} + * }); + * + * ``` + * For more examples, and an in-depth guide, see the {@link guide/component component guide}. + * + *
    + * See also {@link ng.$compileProvider#directive $compileProvider.directive()}. + */ + this.component = function registerComponent(name, options) { + if (!isString(name)) { + forEach(name, reverseParams(bind(this, registerComponent))); + return this; + } + + var controller = options.controller || function() {}; + + function factory($injector) { + function makeInjectable(fn) { + if (isFunction(fn) || isArray(fn)) { + return /** @this */ function(tElement, tAttrs) { + return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs}); + }; + } else { + return fn; + } + } + + var template = (!options.template && !options.templateUrl ? '' : options.template); + var ddo = { + controller: controller, + controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl', + template: makeInjectable(template), + templateUrl: makeInjectable(options.templateUrl), + transclude: options.transclude, + scope: {}, + bindToController: options.bindings || {}, + restrict: 'E', + require: options.require + }; + + // Copy annotations (starting with $) over to the DDO + forEach(options, function(val, key) { + if (key.charAt(0) === '$') ddo[key] = val; + }); + + return ddo; + } + + // TODO(pete) remove the following `forEach` before we release 1.6.0 + // The component-router@0.2.0 looks for the annotations on the controller constructor + // Nothing in AngularJS looks for annotations on the factory function but we can't remove + // it from 1.5.x yet. + + // Copy any annotation properties (starting with $) over to the factory and controller constructor functions + // These could be used by libraries such as the new component router + forEach(options, function(val, key) { + if (key.charAt(0) === '$') { + factory[key] = val; + // Don't try to copy over annotations to named controller + if (isFunction(controller)) controller[key] = val; + } + }); + + factory.$inject = ['$injector']; + + return this.directive(name, factory); + }; + /** * @ngdoc method * @name $compileProvider#aHrefSanitizationWhitelist - * @function + * @kind function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * - * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * The sanitization is a security measure aimed at preventing XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` @@ -5637,7 +8472,7 @@ /** * @ngdoc method * @name $compileProvider#imgSrcSanitizationWhitelist - * @function + * @kind function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe @@ -5663,42 +8498,295 @@ } }; - this.$get = [ - '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', - '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', - function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, - $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { - - var Attributes = function(element, attr) { - this.$$element = element; - this.$attr = attr || {}; - }; + /** + * @ngdoc method + * @name $compileProvider#debugInfoEnabled + * + * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the + * current debugInfoEnabled state + * @returns {*} current value if used as getter or itself (chaining) if used as setter + * + * @kind function + * + * @description + * Call this method to enable/disable various debug runtime information in the compiler such as adding + * binding information and a reference to the current scope on to DOM elements. + * If enabled, the compiler will add the following to DOM elements that have been bound to the scope + * * `ng-binding` CSS class + * * `ng-scope` and `ng-isolated-scope` CSS classes + * * `$binding` data property containing an array of the binding expressions + * * Data properties used by the {@link angular.element#methods `scope()`/`isolateScope()` methods} to return + * the element's scope. + * * Placeholder comments will contain information about what directive and binding caused the placeholder. + * E.g. ``. + * + * You may want to disable this in production for a significant performance boost. See + * {@link guide/production#disabling-debug-data Disabling Debug Data} for more. + * + * The default value is true. + */ + var debugInfoEnabled = true; + this.debugInfoEnabled = function(enabled) { + if (isDefined(enabled)) { + debugInfoEnabled = enabled; + return this; + } + return debugInfoEnabled; + }; - Attributes.prototype = { - $normalize: directiveNormalize, + /** + * @ngdoc method + * @name $compileProvider#preAssignBindingsEnabled + * + * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the + * current preAssignBindingsEnabled state + * @returns {*} current value if used as getter or itself (chaining) if used as setter + * + * @kind function + * + * @description + * Call this method to enable/disable whether directive controllers are assigned bindings before + * calling the controller's constructor. + * If enabled (true), the compiler assigns the value of each of the bindings to the + * properties of the controller object before the constructor of this object is called. + * + * If disabled (false), the compiler calls the constructor first before assigning bindings. + * + * The default value is false. + * + * @deprecated + * sinceVersion="1.6.0" + * removeVersion="1.7.0" + * + * This method and the option to assign the bindings before calling the controller's constructor + * will be removed in v1.7.0. + */ + var preAssignBindingsEnabled = false; + this.preAssignBindingsEnabled = function(enabled) { + if (isDefined(enabled)) { + preAssignBindingsEnabled = enabled; + return this; + } + return preAssignBindingsEnabled; + }; + /** + * @ngdoc method + * @name $compileProvider#strictComponentBindingsEnabled + * + * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided, otherwise just return the + * current strictComponentBindingsEnabled state + * @returns {*} current value if used as getter or itself (chaining) if used as setter + * + * @kind function + * + * @description + * Call this method to enable/disable strict component bindings check. If enabled, the compiler will enforce that + * for all bindings of a component that are not set as optional with `?`, an attribute needs to be provided + * on the component's HTML tag. + * + * The default value is false. + */ + var strictComponentBindingsEnabled = false; + this.strictComponentBindingsEnabled = function(enabled) { + if (isDefined(enabled)) { + strictComponentBindingsEnabled = enabled; + return this; + } + return strictComponentBindingsEnabled; + }; - /** - * @ngdoc method - * @name $compile.directive.Attributes#$addClass - * @function - * - * @description - * Adds the CSS class value specified by the classVal parameter to the element. If animations - * are enabled then an animation will be triggered for the class addition. - * - * @param {string} classVal The className value that will be added to the element - */ - $addClass : function(classVal) { - if(classVal && classVal.length > 0) { - $animate.addClass(this.$$element, classVal); + var TTL = 10; + /** + * @ngdoc method + * @name $compileProvider#onChangesTtl + * @description + * + * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and + * assuming that the model is unstable. + * + * The current default is 10 iterations. + * + * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result + * in several iterations of calls to these hooks. However if an application needs more than the default 10 + * iterations to stabilize then you should investigate what is causing the model to continuously change during + * the `$onChanges` hook execution. + * + * Increasing the TTL could have performance implications, so you should not change it without proper justification. + * + * @param {number} limit The number of `$onChanges` hook iterations. + * @returns {number|object} the current limit (or `this` if called as a setter for chaining) + */ + this.onChangesTtl = function(value) { + if (arguments.length) { + TTL = value; + return this; + } + return TTL; + }; + + var commentDirectivesEnabledConfig = true; + /** + * @ngdoc method + * @name $compileProvider#commentDirectivesEnabled + * @description + * + * It indicates to the compiler + * whether or not directives on comments should be compiled. + * Defaults to `true`. + * + * Calling this function with false disables the compilation of directives + * on comments for the whole application. + * This results in a compilation performance gain, + * as the compiler doesn't have to check comments when looking for directives. + * This should however only be used if you are sure that no comment directives are used in + * the application (including any 3rd party directives). + * + * @param {boolean} enabled `false` if the compiler may ignore directives on comments + * @returns {boolean|object} the current value (or `this` if called as a setter for chaining) + */ + this.commentDirectivesEnabled = function(value) { + if (arguments.length) { + commentDirectivesEnabledConfig = value; + return this; + } + return commentDirectivesEnabledConfig; + }; + + + var cssClassDirectivesEnabledConfig = true; + /** + * @ngdoc method + * @name $compileProvider#cssClassDirectivesEnabled + * @description + * + * It indicates to the compiler + * whether or not directives on element classes should be compiled. + * Defaults to `true`. + * + * Calling this function with false disables the compilation of directives + * on element classes for the whole application. + * This results in a compilation performance gain, + * as the compiler doesn't have to check element classes when looking for directives. + * This should however only be used if you are sure that no class directives are used in + * the application (including any 3rd party directives). + * + * @param {boolean} enabled `false` if the compiler may ignore directives on element classes + * @returns {boolean|object} the current value (or `this` if called as a setter for chaining) + */ + this.cssClassDirectivesEnabled = function(value) { + if (arguments.length) { + cssClassDirectivesEnabledConfig = value; + return this; + } + return cssClassDirectivesEnabledConfig; + }; + + this.$get = [ + '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse', + '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri', + function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse, + $controller, $rootScope, $sce, $animate, $$sanitizeUri) { + + var SIMPLE_ATTR_NAME = /^\w/; + var specialAttrHolder = window.document.createElement('div'); + + + var commentDirectivesEnabled = commentDirectivesEnabledConfig; + var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig; + + + var onChangesTtl = TTL; + // The onChanges hooks should all be run together in a single digest + // When changes occur, the call to trigger their hooks will be added to this queue + var onChangesQueue; + + // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest + function flushOnChangesQueue() { + try { + if (!(--onChangesTtl)) { + // We have hit the TTL limit so reset everything + onChangesQueue = undefined; + throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL); + } + // We must run this hook in an apply since the $$postDigest runs outside apply + $rootScope.$apply(function() { + var errors = []; + for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) { + try { + onChangesQueue[i](); + } catch (e) { + errors.push(e); + } + } + // Reset the queue to trigger a new schedule next time there is a change + onChangesQueue = undefined; + if (errors.length) { + throw errors; + } + }); + } finally { + onChangesTtl++; + } + } + + + function Attributes(element, attributesToCopy) { + if (attributesToCopy) { + var keys = Object.keys(attributesToCopy); + var i, l, key; + + for (i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + this[key] = attributesToCopy[key]; + } + } else { + this.$attr = {}; + } + + this.$$element = element; + } + + Attributes.prototype = { + /** + * @ngdoc method + * @name $compile.directive.Attributes#$normalize + * @kind function + * + * @description + * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or + * `data-`) to its normalized, camelCase form. + * + * Also there is special case for Moz prefix starting with upper case letter. + * + * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives} + * + * @param {string} name Name to normalize + */ + $normalize: directiveNormalize, + + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$addClass + * @kind function + * + * @description + * Adds the CSS class value specified by the classVal parameter to the element. If animations + * are enabled then an animation will be triggered for the class addition. + * + * @param {string} classVal The className value that will be added to the element + */ + $addClass: function(classVal) { + if (classVal && classVal.length > 0) { + $animate.addClass(this.$$element, classVal); } }, /** * @ngdoc method * @name $compile.directive.Attributes#$removeClass - * @function + * @kind function * * @description * Removes the CSS class value specified by the classVal parameter from the element. If @@ -5706,8 +8794,8 @@ * * @param {string} classVal The className value that will be removed from the element */ - $removeClass : function(classVal) { - if(classVal && classVal.length > 0) { + $removeClass: function(classVal) { + if (classVal && classVal.length > 0) { $animate.removeClass(this.$$element, classVal); } }, @@ -5715,7 +8803,7 @@ /** * @ngdoc method * @name $compile.directive.Attributes#$updateClass - * @function + * @kind function * * @description * Adds and removes the appropriate CSS class values to the element based on the difference @@ -5724,16 +8812,15 @@ * @param {string} newClasses The current CSS className value * @param {string} oldClasses The former CSS className value */ - $updateClass : function(newClasses, oldClasses) { + $updateClass: function(newClasses, oldClasses) { var toAdd = tokenDifference(newClasses, oldClasses); - var toRemove = tokenDifference(oldClasses, newClasses); + if (toAdd && toAdd.length) { + $animate.addClass(this.$$element, toAdd); + } - if(toAdd.length === 0) { + var toRemove = tokenDifference(oldClasses, newClasses); + if (toRemove && toRemove.length) { $animate.removeClass(this.$$element, toRemove); - } else if(toRemove.length === 0) { - $animate.addClass(this.$$element, toAdd); - } else { - $animate.setClass(this.$$element, toAdd, toRemove); } }, @@ -5751,13 +8838,18 @@ //is set through this function since it may cause $updateClass to //become unstable. - var booleanKey = getBooleanAttrName(this.$$element[0], key), - normalizedVal, + var node = this.$$element[0], + booleanKey = getBooleanAttrName(node, key), + aliasedKey = getAliasedAttrName(key), + observer = key, nodeName; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; + } else if (aliasedKey) { + this[aliasedKey] = value; + observer = aliasedKey; } this[key] = value; @@ -5774,36 +8866,76 @@ nodeName = nodeName_(this.$$element); - // sanitize a[href] and img[src] values - if ((nodeName === 'A' && key === 'href') || - (nodeName === 'IMG' && key === 'src')) { + if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) || + (nodeName === 'img' && key === 'src')) { + // sanitize a[href] and img[src] values this[key] = value = $$sanitizeUri(value, key === 'src'); + } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) { + // sanitize img[srcset] values + var result = ''; + + // first check if there are spaces because it's not the same pattern + var trimmedSrcset = trim(value); + // ( 999x ,| 999w ,| ,|, ) + var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/; + var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/; + + // split srcset into tuple of uri and descriptor except for the last item + var rawUris = trimmedSrcset.split(pattern); + + // for each tuples + var nbrUrisWith2parts = Math.floor(rawUris.length / 2); + for (var i = 0; i < nbrUrisWith2parts; i++) { + var innerIdx = i * 2; + // sanitize the uri + result += $$sanitizeUri(trim(rawUris[innerIdx]), true); + // add the descriptor + result += (' ' + trim(rawUris[innerIdx + 1])); + } + + // split the last item into uri and descriptor + var lastTuple = trim(rawUris[i * 2]).split(/\s/); + + // sanitize the last uri + result += $$sanitizeUri(trim(lastTuple[0]), true); + + // and add the last descriptor if any + if (lastTuple.length === 2) { + result += (' ' + trim(lastTuple[1])); + } + this[key] = value = result; } if (writeAttr !== false) { - if (value === null || value === undefined) { + if (value === null || isUndefined(value)) { this.$$element.removeAttr(attrName); } else { - this.$$element.attr(attrName, value); + if (SIMPLE_ATTR_NAME.test(attrName)) { + this.$$element.attr(attrName, value); + } else { + setSpecialAttr(this.$$element[0], attrName, value); + } } } // fire observers var $$observers = this.$$observers; - $$observers && forEach($$observers[key], function(fn) { - try { - fn(value); - } catch (e) { - $exceptionHandler(e); - } - }); + if ($$observers) { + forEach($$observers[observer], function(fn) { + try { + fn(value); + } catch (e) { + $exceptionHandler(e); + } + }); + } }, /** * @ngdoc method * @name $compile.directive.Attributes#$observe - * @function + * @kind function * * @description * Observes an interpolated attribute. @@ -5815,34 +8947,95 @@ * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(interpolatedValue)} fn Function that will be called whenever the interpolated value of the attribute changes. - * See the {@link guide/directive#Attributes Directives} guide for more info. - * @returns {function()} the `fn` parameter. + * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation + * guide} for more info. + * @returns {function()} Returns a deregistration function for this observer. */ $observe: function(key, fn) { var attrs = this, - $$observers = (attrs.$$observers || (attrs.$$observers = {})), + $$observers = (attrs.$$observers || (attrs.$$observers = createMap())), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { - if (!listeners.$$inter) { + if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); - return fn; + + return function() { + arrayRemove(listeners, fn); + }; } }; + function setSpecialAttr(element, attrName, value) { + // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute` + // so we have to jump through some hoops to get such an attribute + // https://github.com/angular/angular.js/pull/13318 + specialAttrHolder.innerHTML = ''; + var attributes = specialAttrHolder.firstChild.attributes; + var attribute = attributes[0]; + // We have to remove the attribute from its container element before we can add it to the destination element + attributes.removeNamedItem(attribute.name); + attribute.value = value; + element.attributes.setNamedItem(attribute); + } + + function safeAddClass($element, className) { + try { + $element.addClass(className); + } catch (e) { + // ignore, since it means that we are trying to set class on + // SVG element, where class name is read-only. + } + } + + var startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), - denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') + denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}') ? identity : function denormalizeTemplate(template) { - return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); - }, + return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); + }, NG_ATTR_BINDING = /^ngAttr[A-Z]/; + var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/; + + compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) { + var bindings = $element.data('$binding') || []; + if (isArray(binding)) { + bindings = bindings.concat(binding); + } else { + bindings.push(binding); + } + + $element.data('$binding', bindings); + } : noop; + + compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) { + safeAddClass($element, 'ng-binding'); + } : noop; + + compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) { + var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope'; + $element.data(dataName, scope); + } : noop; + + compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) { + safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope'); + } : noop; + + compile.$$createComment = function(directiveName, comment) { + var content = ''; + if (debugInfoEnabled) { + content = ' ' + (directiveName || '') + ': '; + if (comment) content += comment + ' '; + } + return window.document.createComment(content); + }; return compile; @@ -5855,50 +9048,84 @@ // modify it. $compileNodes = jqLite($compileNodes); } - // We can not compile top level text elements since text nodes can be merged and we will - // not be able to attach scope data to them, so we will wrap them in - forEach($compileNodes, function(node, index){ - if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { - $compileNodes[index] = node = jqLite(node).wrap('').parent()[0]; - } - }); var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective, previousCompileContext); - safeAddClass($compileNodes, 'ng-scope'); - return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){ + compile.$$addScopeClass($compileNodes); + var namespace = null; + return function publicLinkFn(scope, cloneConnectFn, options) { + if (!$compileNodes) { + throw $compileMinErr('multilink', 'This element has already been linked.'); + } assertArg(scope, 'scope'); - // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart - // and sometimes changes the structure of the DOM. - var $linkNode = cloneConnectFn - ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! - : $compileNodes; - - forEach(transcludeControllers, function(instance, name) { - $linkNode.data('$' + name + 'Controller', instance); - }); - // Attach scope only to non-text nodes. - for(var i = 0, ii = $linkNode.length; i').append($compileNodes).html()) + ); + } else if (cloneConnectFn) { + // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart + // and sometimes changes the structure of the DOM. + $linkNode = JQLitePrototype.clone.call($compileNodes); + } else { + $linkNode = $compileNodes; + } + + if (transcludeControllers) { + for (var controllerName in transcludeControllers) { + $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance); } } + compile.$$addScopeInfo($linkNode, scope); + if (cloneConnectFn) cloneConnectFn($linkNode, scope); - if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode); + if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); + + if (!cloneConnectFn) { + $compileNodes = compositeLinkFn = null; + } return $linkNode; }; } - function safeAddClass($element, className) { - try { - $element.addClass(className); - } catch(e) { - // ignore, since it means that we are trying to set class on - // SVG element, where class name is read-only. + function detectNamespaceForChildElements(parentElement) { + // TODO: Make this detect MathML as well... + var node = parentElement && parentElement[0]; + if (!node) { + return 'html'; + } else { + return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html'; } } @@ -5920,33 +9147,50 @@ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, previousCompileContext) { var linkFns = [], - attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound; + // `nodeList` can be either an element's `.childNodes` (live NodeList) + // or a jqLite/jQuery collection or an array + notLiveList = isArray(nodeList) || (nodeList instanceof jqLite), + attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound; + for (var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); - // we must always refer to nodeList[i] since the nodes can be replaced underneath us. + // Support: IE 11 only + // Workaround for #11781 and #14924 + if (msie === 11) { + mergeConsecutiveTextNodes(nodeList, i, notLiveList); + } + + // We must always refer to `nodeList[i]` hereafter, + // since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, ignoreDirective); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement, - null, [], [], previousCompileContext) + null, [], [], previousCompileContext) : null; if (nodeLinkFn && nodeLinkFn.scope) { - safeAddClass(jqLite(nodeList[i]), 'ng-scope'); + compile.$$addScopeClass(attrs.$$element); } childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || - !(childNodes = nodeList[i].childNodes) || - !childNodes.length) + !(childNodes = nodeList[i].childNodes) || + !childNodes.length) ? null : compileNodes(childNodes, - nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); + nodeLinkFn ? ( + (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement) + && nodeLinkFn.transclude) : transcludeFn); + + if (nodeLinkFn || childLinkFn) { + linkFns.push(i, nodeLinkFn, childLinkFn); + linkFnFound = true; + nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn; + } - linkFns.push(nodeLinkFn, childLinkFn); - linkFnFound = linkFnFound || nodeLinkFn || childLinkFn; //use the previous context only for the first element in the virtual group previousCompileContext = null; } @@ -5954,60 +9198,115 @@ // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; - function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) { - var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n; + function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) { + var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn; + var stableNodeList; - // copy nodeList so that linking doesn't break due to live list updates. - var nodeListLength = nodeList.length, + + if (nodeLinkFnFound) { + // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our + // offsets don't get screwed up + var nodeListLength = nodeList.length; stableNodeList = new Array(nodeListLength); - for (i = 0; i < nodeListLength; i++) { - stableNodeList[i] = nodeList[i]; + + // create a sparse array by only copying the elements which have a linkFn + for (i = 0; i < linkFns.length; i += 3) { + idx = linkFns[i]; + stableNodeList[idx] = nodeList[idx]; + } + } else { + stableNodeList = nodeList; } - for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) { - node = stableNodeList[n]; + for (i = 0, ii = linkFns.length; i < ii;) { + node = stableNodeList[linkFns[i++]]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; - $node = jqLite(node); if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(); - $node.data('$scope', childScope); + compile.$$addScopeInfo(jqLite(node), childScope); } else { childScope = scope; } - childTranscludeFn = nodeLinkFn.transclude; - if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) { - nodeLinkFn(childLinkFn, childScope, node, $rootElement, - createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn) - ); + + if (nodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn( + scope, nodeLinkFn.transclude, parentBoundTranscludeFn); + + } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { + childBoundTranscludeFn = parentBoundTranscludeFn; + + } else if (!parentBoundTranscludeFn && transcludeFn) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn); + } else { - nodeLinkFn(childLinkFn, childScope, node, $rootElement, boundTranscludeFn); + childBoundTranscludeFn = null; } + + nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn); + } else if (childLinkFn) { - childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn); + childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn); } } } } - function createBoundTranscludeFn(scope, transcludeFn) { - return function boundTranscludeFn(transcludedScope, cloneFn, controllers) { - var scopeCreated = false; + function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) { + var node = nodeList[idx]; + var parent = node.parentNode; + var sibling; + + if (node.nodeType !== NODE_TYPE_TEXT) { + return; + } + + while (true) { + sibling = parent ? node.nextSibling : nodeList[idx + 1]; + if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) { + break; + } + + node.nodeValue = node.nodeValue + sibling.nodeValue; + + if (sibling.parentNode) { + sibling.parentNode.removeChild(sibling); + } + if (notLiveList && sibling === nodeList[idx + 1]) { + nodeList.splice(idx + 1, 1); + } + } + } + + function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) { + function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { if (!transcludedScope) { - transcludedScope = scope.$new(); + transcludedScope = scope.$new(false, containingScope); transcludedScope.$$transcluded = true; - scopeCreated = true; } - var clone = transcludeFn(transcludedScope, cloneFn, controllers); - if (scopeCreated) { - clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy)); + return transcludeFn(transcludedScope, cloneFn, { + parentBoundTranscludeFn: previousBoundTranscludeFn, + transcludeControllers: controllers, + futureParentElement: futureParentElement + }); + } + + // We need to attach the transclusion slots onto the `boundTranscludeFn` + // so that they are available inside the `controllersBoundTransclude` function + var boundSlots = boundTranscludeFn.$$slots = createMap(); + for (var slotName in transcludeFn.$$slots) { + if (transcludeFn.$$slots[slotName]) { + boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn); + } else { + boundSlots[slotName] = null; } - return clone; - }; + } + + return boundTranscludeFn; } /** @@ -6024,52 +9323,73 @@ var nodeType = node.nodeType, attrsMap = attrs.$attr, match, + nodeName, className; - switch(nodeType) { - case 1: /* Element */ + switch (nodeType) { + case NODE_TYPE_ELEMENT: /* Element */ + + nodeName = nodeName_(node); + // use the node name: addDirective(directives, - directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective); + directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective); // iterate over the attributes - for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, + for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { var attrStartName = false; var attrEndName = false; attr = nAttrs[j]; - if (!msie || msie >= 8 || attr.specified) { - name = attr.name; - // support ngAttr attribute binding - ngAttrName = directiveNormalize(name); - if (NG_ATTR_BINDING.test(ngAttrName)) { - name = snake_case(ngAttrName.substr(6), '-'); - } + name = attr.name; + value = attr.value; + + // support ngAttr attribute binding + ngAttrName = directiveNormalize(name); + isNgAttr = NG_ATTR_BINDING.test(ngAttrName); + if (isNgAttr) { + name = name.replace(PREFIX_REGEXP, '') + .substr(8).replace(/_(.)/g, function(match, letter) { + return letter.toUpperCase(); + }); + } - var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); - if (ngAttrName === directiveNName + 'Start') { - attrStartName = name; - attrEndName = name.substr(0, name.length - 5) + 'end'; - name = name.substr(0, name.length - 6); - } + var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE); + if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) { + attrStartName = name; + attrEndName = name.substr(0, name.length - 5) + 'end'; + name = name.substr(0, name.length - 6); + } - nName = directiveNormalize(name.toLowerCase()); - attrsMap[nName] = name; - attrs[nName] = value = trim(attr.value); + nName = directiveNormalize(name.toLowerCase()); + attrsMap[nName] = name; + if (isNgAttr || !attrs.hasOwnProperty(nName)) { + attrs[nName] = value; if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } - addAttrInterpolateDirective(node, directives, value, nName); - addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, - attrEndName); } + addAttrInterpolateDirective(node, directives, value, nName, isNgAttr); + addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, + attrEndName); + } + + if (nodeName === 'input' && node.getAttribute('type') === 'hidden') { + // Hidden input elements can have strange behaviour when navigating back to the page + // This tells the browser not to try to cache and reinstate previous values + node.setAttribute('autocomplete', 'off'); } // use class as directive + if (!cssClassDirectivesEnabled) break; className = node.className; + if (isObject(className)) { + // Maybe SVGAnimatedString + className = className.animVal; + } if (isString(className) && className !== '') { - while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { + while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[3]); @@ -6078,23 +9398,12 @@ } } break; - case 3: /* Text Node */ + case NODE_TYPE_TEXT: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; - case 8: /* Comment */ - try { - match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); - if (match) { - nName = directiveNormalize(match[1]); - if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { - attrs[nName] = trim(match[2]); - } - } - } catch (e) { - // turns out that under some circumstances IE9 throws errors when one attempts to read - // comment's node value. - // Just ignore it and continue. (Can't seem to reproduce in test case.) - } + case NODE_TYPE_COMMENT: /* Comment */ + if (!commentDirectivesEnabled) break; + collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective); break; } @@ -6102,8 +9411,26 @@ return directives; } + function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) { + // function created because of performance, try/catch disables + // the optimization of the whole function #14848 + try { + var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); + if (match) { + var nName = directiveNormalize(match[1]); + if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { + attrs[nName] = trim(match[2]); + } + } + } catch (e) { + // turns out that under some circumstances IE9 throws errors when one attempts to read + // comment's node value. + // Just ignore it and continue. (Can't seem to reproduce in test case.) + } + } + /** - * Given a node with an directive-start it collects all of the siblings until it finds + * Given a node with a directive-start it collects all of the siblings until it finds * directive-end. * @param node * @param attrStart @@ -6114,14 +9441,13 @@ var nodes = []; var depth = 0; if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { - var startNode = node; do { if (!node) { throw $compileMinErr('uterdir', - "Unterminated attribute, found '{0}' but no matching '{1}' found.", + 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.', attrStart, attrEnd); } - if (node.nodeType == 1 /** Element **/) { + if (node.nodeType === NODE_TYPE_ELEMENT) { if (node.hasAttribute(attrStart)) depth++; if (node.hasAttribute(attrEnd)) depth--; } @@ -6144,12 +9470,41 @@ * @returns {Function} */ function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { - return function(scope, element, attrs, controllers, transcludeFn) { + return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) { element = groupScan(element[0], attrStart, attrEnd); return linkFn(scope, element, attrs, controllers, transcludeFn); }; } + /** + * A function generator that is used to support both eager and lazy compilation + * linking function. + * @param eager + * @param $compileNodes + * @param transcludeFn + * @param maxPriority + * @param ignoreDirective + * @param previousCompileContext + * @returns {Function} + */ + function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) { + var compiled; + + if (eager) { + return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext); + } + return /** @this */ function lazyCompilation() { + if (!compiled) { + compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext); + + // Null out all of these references in order to make them eligible for garbage collection + // since this is a potentially long lived closure + $compileNodes = transcludeFn = previousCompileContext = null; + } + return compiled.apply(this, arguments); + }; + } + /** * Once the directives have been collected, their compile functions are executed. This method * is responsible for inlining directive templates as well as terminating the application @@ -6179,12 +9534,13 @@ previousCompileContext = previousCompileContext || {}; var terminalPriority = -Number.MAX_VALUE, - newScopeDirective, + newScopeDirective = previousCompileContext.newScopeDirective, controllerDirectives = previousCompileContext.controllerDirectives, newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, templateDirective = previousCompileContext.templateDirective, nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, hasTranscludeDirective = false, + hasTemplate = false, hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, @@ -6193,10 +9549,12 @@ replaceDirective = originalReplaceDirective, childTranscludeFn = transcludeFn, linkFn, + didScanForMultipleTransclusion = false, + mightHaveMultipleTransclusionError = false, directiveValue; // executes all directives on the current element - for(var i = 0, ii = directives.length; i < ii; i++) { + for (var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; var attrStart = directive.$$start; var attrEnd = directive.$$end; @@ -6211,31 +9569,63 @@ break; // prevent further processing of directives } - if (directiveValue = directive.scope) { - newScopeDirective = newScopeDirective || directive; + directiveValue = directive.scope; + + if (directiveValue) { // skip the check for directives with async templates, we'll check the derived sync // directive when the template arrives if (!directive.templateUrl) { - assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, - $compileNode); if (isObject(directiveValue)) { + // This directive is trying to add an isolated scope. + // Check that there is no scope of any kind already + assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective, + directive, $compileNode); newIsolateScopeDirective = directive; + } else { + // This directive is trying to add a child scope. + // Check that there is no isolated scope already + assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, + $compileNode); } } + + newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; + // If we encounter a condition that can result in transclusion on the directive, + // then scan ahead in the remaining directives for others that may cause a multiple + // transclusion error to be thrown during the compilation process. If a matching directive + // is found, then we know that when we encounter a transcluded directive, we need to eagerly + // compile the `transclude` function rather than doing it lazily in order to throw + // exceptions at the correct time + if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template)) + || (directive.transclude && !directive.$$tlb))) { + var candidateDirective; + + for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) { + if ((candidateDirective.transclude && !candidateDirective.$$tlb) + || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) { + mightHaveMultipleTransclusionError = true; + break; + } + } + + didScanForMultipleTransclusion = true; + } + if (!directive.templateUrl && directive.controller) { - directiveValue = directive.controller; - controllerDirectives = controllerDirectives || {}; - assertNoDuplicate("'" + directiveName + "' controller", + controllerDirectives = controllerDirectives || createMap(); + assertNoDuplicate('\'' + directiveName + '\' controller', controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } - if (directiveValue = directive.transclude) { + directiveValue = directive.transclude; + + if (directiveValue) { hasTranscludeDirective = true; // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. @@ -6246,17 +9636,27 @@ nonTlbTranscludeDirective = directive; } - if (directiveValue == 'element') { + if (directiveValue === 'element') { hasElementTranscludeDirective = true; terminalPriority = directive.priority; - $template = groupScan(compileNode, attrStart, attrEnd); + $template = $compileNode; $compileNode = templateAttrs.$$element = - jqLite(document.createComment(' ' + directiveName + ': ' + - templateAttrs[directiveName] + ' ')); + jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName])); compileNode = $compileNode[0]; - replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode); + replaceWith(jqCollection, sliceArgs($template), compileNode); - childTranscludeFn = compile($template, transcludeFn, terminalPriority, + // Support: Chrome < 50 + // https://github.com/angular/angular.js/issues/14041 + + // In the versions of V8 prior to Chrome 50, the document fragment that is created + // in the `replaceWith` function is improperly garbage collected despite still + // being referenced by the `parentNode` property of all of the child nodes. By adding + // a reference to the fragment via a different property, we can avoid that incorrect + // behavior. + // TODO: remove this line after Chrome 50 has been released + $template[0].$$parentNode = $template[0].parentNode; + + childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority, replaceDirective && replaceDirective.name, { // Don't pass in: // - controllerDirectives - otherwise we'll create duplicates controllers @@ -6268,19 +9668,80 @@ nonTlbTranscludeDirective: nonTlbTranscludeDirective }); } else { - $template = jqLite(jqLiteClone(compileNode)).contents(); - $compileNode.empty(); // clear contents - childTranscludeFn = compile($template, transcludeFn); - } - } - if (directive.template) { - assertNoDuplicate('template', templateDirective, directive, $compileNode); - templateDirective = directive; + var slots = createMap(); - directiveValue = (isFunction(directive.template)) - ? directive.template($compileNode, templateAttrs) - : directive.template; + if (!isObject(directiveValue)) { + $template = jqLite(jqLiteClone(compileNode)).contents(); + } else { + + // We have transclusion slots, + // collect them up, compile them and store their transclusion functions + $template = []; + + var slotMap = createMap(); + var filledSlots = createMap(); + + // Parse the element selectors + forEach(directiveValue, function(elementSelector, slotName) { + // If an element selector starts with a ? then it is optional + var optional = (elementSelector.charAt(0) === '?'); + elementSelector = optional ? elementSelector.substring(1) : elementSelector; + + slotMap[elementSelector] = slotName; + + // We explicitly assign `null` since this implies that a slot was defined but not filled. + // Later when calling boundTransclusion functions with a slot name we only error if the + // slot is `undefined` + slots[slotName] = null; + + // filledSlots contains `true` for all slots that are either optional or have been + // filled. This is used to check that we have not missed any required slots + filledSlots[slotName] = optional; + }); + + // Add the matching elements into their slot + forEach($compileNode.contents(), function(node) { + var slotName = slotMap[directiveNormalize(nodeName_(node))]; + if (slotName) { + filledSlots[slotName] = true; + slots[slotName] = slots[slotName] || []; + slots[slotName].push(node); + } else { + $template.push(node); + } + }); + + // Check for required slots that were not filled + forEach(filledSlots, function(filled, slotName) { + if (!filled) { + throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName); + } + }); + + for (var slotName in slots) { + if (slots[slotName]) { + // Only define a transclusion function if the slot was filled + slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn); + } + } + } + + $compileNode.empty(); // clear contents + childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined, + undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope}); + childTranscludeFn.$$slots = slots; + } + } + + if (directive.template) { + hasTemplate = true; + assertNoDuplicate('template', templateDirective, directive, $compileNode); + templateDirective = directive; + + directiveValue = (isFunction(directive.template)) + ? directive.template($compileNode, templateAttrs) + : directive.template; directiveValue = denormalizeTemplate(directiveValue); @@ -6289,13 +9750,13 @@ if (jqLiteIsTextNode(directiveValue)) { $template = []; } else { - $template = jqLite(directiveValue); + $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue))); } compileNode = $template[0]; - if ($template.length != 1 || compileNode.nodeType !== 1) { + if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { throw $compileMinErr('tplrt', - "Template for directive '{0}' must have exactly one root element. {1}", + 'Template for directive \'{0}\' must have exactly one root element. {1}', directiveName, ''); } @@ -6311,8 +9772,11 @@ var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); - if (newIsolateScopeDirective) { - markDirectivesAsIsolate(templateDirectives); + if (newIsolateScopeDirective || newScopeDirective) { + // The original directive caused the current element to be replaced but this element + // also needs to have a new scope, so we need to tell the template directives + // that they would need to get their scope from further up, if they require transclusion + markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective); } directives = directives.concat(templateDirectives).concat(unprocessedDirectives); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); @@ -6324,6 +9788,7 @@ } if (directive.templateUrl) { + hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; @@ -6331,9 +9796,11 @@ replaceDirective = directive; } + // eslint-disable-next-line no-func-assign nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, - templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, { + templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { controllerDirectives: controllerDirectives, + newScopeDirective: (newScopeDirective !== directive) && newScopeDirective, newIsolateScopeDirective: newIsolateScopeDirective, templateDirective: templateDirective, nonTlbTranscludeDirective: nonTlbTranscludeDirective @@ -6342,10 +9809,11 @@ } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); + var context = directive.$$originalDirective || directive; if (isFunction(linkFn)) { - addLinkFns(null, linkFn, attrStart, attrEnd); + addLinkFns(null, bind(context, linkFn), attrStart, attrEnd); } else if (linkFn) { - addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); + addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); @@ -6360,7 +9828,10 @@ } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; - nodeLinkFn.transclude = hasTranscludeDirective && childTranscludeFn; + nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; + nodeLinkFn.templateOnThisElement = hasTemplate; + nodeLinkFn.transclude = childTranscludeFn; + previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; // might be normal or delayed nodeLinkFn depending on if templateUrl is present @@ -6372,6 +9843,7 @@ if (pre) { if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); pre.require = directive.require; + pre.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { pre = cloneAndAnnotateFn(pre, {isolateScope: true}); } @@ -6380,6 +9852,7 @@ if (post) { if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); post.require = directive.require; + post.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { post = cloneAndAnnotateFn(post, {isolateScope: true}); } @@ -6387,180 +9860,135 @@ } } - - function getControllers(require, $element, elementControllers) { - var value, retrievalMethod = 'data', optional = false; - if (isString(require)) { - while((value = require.charAt(0)) == '^' || value == '?') { - require = require.substr(1); - if (value == '^') { - retrievalMethod = 'inheritedData'; - } - optional = optional || value == '?'; - } - value = null; - - if (elementControllers && retrievalMethod === 'data') { - value = elementControllers[require]; - } - value = value || $element[retrievalMethod]('$' + require + 'Controller'); - - if (!value && !optional) { - throw $compileMinErr('ctreq', - "Controller '{0}', required by directive '{1}', can't be found!", - require, directiveName); - } - return value; - } else if (isArray(require)) { - value = []; - forEach(require, function(require) { - value.push(getControllers(require, $element, elementControllers)); - }); - } - return value; - } - - function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { - var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn; + var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element, + attrs, scopeBindingInfo; if (compileNode === linkNode) { attrs = templateAttrs; + $element = templateAttrs.$$element; } else { - attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); + $element = jqLite(linkNode); + attrs = new Attributes($element, templateAttrs); } - $element = attrs.$$element; + controllerScope = scope; if (newIsolateScopeDirective) { - var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; - var $linkNode = jqLite(linkNode); - isolateScope = scope.$new(true); + } else if (newScopeDirective) { + controllerScope = scope.$parent; + } - if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) { - $linkNode.data('$isolateScope', isolateScope) ; - } else { - $linkNode.data('$isolateScopeNoTemplate', isolateScope); - } - - - - safeAddClass($linkNode, 'ng-isolate-scope'); + if (boundTranscludeFn) { + // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn` + // is later passed as `parentBoundTranscludeFn` to `publicLinkFn` + transcludeFn = controllersBoundTransclude; + transcludeFn.$$boundTransclude = boundTranscludeFn; + // expose the slots on the `$transclude` function + transcludeFn.isSlotFilled = function(slotName) { + return !!boundTranscludeFn.$$slots[slotName]; + }; + } - forEach(newIsolateScopeDirective.scope, function(definition, scopeName) { - var match = definition.match(LOCAL_REGEXP) || [], - attrName = match[3] || scopeName, - optional = (match[2] == '?'), - mode = match[1], // @, =, or & - lastValue, - parentGet, parentSet, compare; + if (controllerDirectives) { + elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective); + } - isolateScope.$$isolateBindings[scopeName] = mode + attrName; + if (newIsolateScopeDirective) { + // Initialize isolate scope bindings for new isolate scope directive. + compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective || + templateDirective === newIsolateScopeDirective.$$originalDirective))); + compile.$$addScopeClass($element, true); + isolateScope.$$isolateBindings = + newIsolateScopeDirective.$$isolateBindings; + scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope, + isolateScope.$$isolateBindings, + newIsolateScopeDirective); + if (scopeBindingInfo.removeWatches) { + isolateScope.$on('$destroy', scopeBindingInfo.removeWatches); + } + } - switch (mode) { + // Initialize bindToController bindings + for (var name in elementControllers) { + var controllerDirective = controllerDirectives[name]; + var controller = elementControllers[name]; + var bindings = controllerDirective.$$bindings.bindToController; - case '@': - attrs.$observe(attrName, function(value) { - isolateScope[scopeName] = value; - }); - attrs.$$observers[attrName].$$scope = scope; - if( attrs[attrName] ) { - // If the attribute has been provided then we trigger an interpolation to ensure - // the value is there for use in the link fn - isolateScope[scopeName] = $interpolate(attrs[attrName])(scope); - } - break; + if (preAssignBindingsEnabled) { + if (bindings) { + controller.bindingInfo = + initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective); + } else { + controller.bindingInfo = {}; + } - case '=': - if (optional && !attrs[attrName]) { - return; - } - parentGet = $parse(attrs[attrName]); - if (parentGet.literal) { - compare = equals; - } else { - compare = function(a,b) { return a === b; }; - } - parentSet = parentGet.assign || function() { - // reset the change, or we will throw this exception on every $digest - lastValue = isolateScope[scopeName] = parentGet(scope); - throw $compileMinErr('nonassign', - "Expression '{0}' used with directive '{1}' is non-assignable!", - attrs[attrName], newIsolateScopeDirective.name); - }; - lastValue = isolateScope[scopeName] = parentGet(scope); - isolateScope.$watch(function parentValueWatch() { - var parentValue = parentGet(scope); - if (!compare(parentValue, isolateScope[scopeName])) { - // we are out of sync and need to copy - if (!compare(parentValue, lastValue)) { - // parent changed and it has precedence - isolateScope[scopeName] = parentValue; - } else { - // if the parent can be assigned then do so - parentSet(scope, parentValue = isolateScope[scopeName]); - } - } - return lastValue = parentValue; - }, null, parentGet.literal); - break; - - case '&': - parentGet = $parse(attrs[attrName]); - isolateScope[scopeName] = function(locals) { - return parentGet(scope, locals); - }; - break; - - default: - throw $compileMinErr('iscp', - "Invalid isolate scope definition for directive '{0}'." + - " Definition: {... {1}: '{2}' ...}", - newIsolateScopeDirective.name, scopeName, definition); + var controllerResult = controller(); + if (controllerResult !== controller.instance) { + // If the controller constructor has a return value, overwrite the instance + // from setupControllers + controller.instance = controllerResult; + $element.data('$' + controllerDirective.name + 'Controller', controllerResult); + if (controller.bindingInfo.removeWatches) { + controller.bindingInfo.removeWatches(); + } + controller.bindingInfo = + initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective); } - }); + } else { + controller.instance = controller(); + $element.data('$' + controllerDirective.name + 'Controller', controller.instance); + controller.bindingInfo = + initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective); + } } - transcludeFn = boundTranscludeFn && controllersBoundTransclude; - if (controllerDirectives) { - forEach(controllerDirectives, function(directive) { - var locals = { - $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, - $element: $element, - $attrs: attrs, - $transclude: transcludeFn - }, controllerInstance; - - controller = directive.controller; - if (controller == '@') { - controller = attrs[directive.name]; - } - controllerInstance = $controller(controller, locals); - // For directives with element transclusion the element is a comment, - // but jQuery .data doesn't support attaching data to comment nodes as it's hard to - // clean up (http://bugs.jquery.com/ticket/8335). - // Instead, we save the controllers for the element in a local hash and attach to .data - // later, once we have the actual element. - elementControllers[directive.name] = controllerInstance; - if (!hasElementTranscludeDirective) { - $element.data('$' + directive.name + 'Controller', controllerInstance); - } + // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy + forEach(controllerDirectives, function(controllerDirective, name) { + var require = controllerDirective.require; + if (controllerDirective.bindToController && !isArray(require) && isObject(require)) { + extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers)); + } + }); - if (directive.controllerAs) { - locals.$scope[directive.controllerAs] = controllerInstance; + // Handle the init and destroy lifecycle hooks on all controllers that have them + forEach(elementControllers, function(controller) { + var controllerInstance = controller.instance; + if (isFunction(controllerInstance.$onChanges)) { + try { + controllerInstance.$onChanges(controller.bindingInfo.initialChanges); + } catch (e) { + $exceptionHandler(e); } - }); - } + } + if (isFunction(controllerInstance.$onInit)) { + try { + controllerInstance.$onInit(); + } catch (e) { + $exceptionHandler(e); + } + } + if (isFunction(controllerInstance.$doCheck)) { + controllerScope.$watch(function() { controllerInstance.$doCheck(); }); + controllerInstance.$doCheck(); + } + if (isFunction(controllerInstance.$onDestroy)) { + controllerScope.$on('$destroy', function callOnDestroyHook() { + controllerInstance.$onDestroy(); + }); + } + }); // PRELINKING - for(i = 0, ii = preLinkFns.length; i < ii; i++) { - try { - linkFn = preLinkFns[i]; - linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, - linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn); - } catch (e) { - $exceptionHandler(e, startingTag($element)); - } + for (i = 0, ii = preLinkFns.length; i < ii; i++) { + linkFn = preLinkFns[i]; + invokeLinkFn(linkFn, + linkFn.isolateScope ? isolateScope : scope, + $element, + attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), + transcludeFn + ); } // RECURSION @@ -6570,25 +9998,38 @@ if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { scopeToChild = isolateScope; } - childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); + if (childLinkFn) { + childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); + } // POSTLINKING - for(i = postLinkFns.length - 1; i >= 0; i--) { - try { - linkFn = postLinkFns[i]; - linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, - linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn); - } catch (e) { - $exceptionHandler(e, startingTag($element)); - } + for (i = postLinkFns.length - 1; i >= 0; i--) { + linkFn = postLinkFns[i]; + invokeLinkFn(linkFn, + linkFn.isolateScope ? isolateScope : scope, + $element, + attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), + transcludeFn + ); } + // Trigger $postLink lifecycle hooks + forEach(elementControllers, function(controller) { + var controllerInstance = controller.instance; + if (isFunction(controllerInstance.$postLink)) { + controllerInstance.$postLink(); + } + }); + // This is the function that is injected as `$transclude`. - function controllersBoundTransclude(scope, cloneAttachFn) { + // Note: all arguments are optional! + function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) { var transcludeControllers; - - // no scope passed - if (arguments.length < 2) { + // No scope passed in: + if (!isScope(scope)) { + slotName = futureParentElement; + futureParentElement = cloneAttachFn; cloneAttachFn = scope; scope = undefined; } @@ -6596,16 +10037,111 @@ if (hasElementTranscludeDirective) { transcludeControllers = elementControllers; } + if (!futureParentElement) { + futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element; + } + if (slotName) { + // slotTranscludeFn can be one of three things: + // * a transclude function - a filled slot + // * `null` - an optional slot that was not filled + // * `undefined` - a slot that was not declared (i.e. invalid) + var slotTranscludeFn = boundTranscludeFn.$$slots[slotName]; + if (slotTranscludeFn) { + return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); + } else if (isUndefined(slotTranscludeFn)) { + throw $compileMinErr('noslot', + 'No parent directive that requires a transclusion with slot name "{0}". ' + + 'Element: {1}', + slotName, startingTag($element)); + } + } else { + return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); + } + } + } + } + + function getControllers(directiveName, require, $element, elementControllers) { + var value; - return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers); + if (isString(require)) { + var match = require.match(REQUIRE_PREFIX_REGEXP); + var name = require.substring(match[0].length); + var inheritType = match[1] || match[3]; + var optional = match[2] === '?'; + + //If only parents then start at the parent element + if (inheritType === '^^') { + $element = $element.parent(); + //Otherwise attempt getting the controller from elementControllers in case + //the element is transcluded (and has no data) and to avoid .data if possible + } else { + value = elementControllers && elementControllers[name]; + value = value && value.instance; + } + + if (!value) { + var dataName = '$' + name + 'Controller'; + value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName); + } + + if (!value && !optional) { + throw $compileMinErr('ctreq', + 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!', + name, directiveName); + } + } else if (isArray(require)) { + value = []; + for (var i = 0, ii = require.length; i < ii; i++) { + value[i] = getControllers(directiveName, require[i], $element, elementControllers); + } + } else if (isObject(require)) { + value = {}; + forEach(require, function(controller, property) { + value[property] = getControllers(directiveName, controller, $element, elementControllers); + }); + } + + return value || null; + } + + function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) { + var elementControllers = createMap(); + for (var controllerKey in controllerDirectives) { + var directive = controllerDirectives[controllerKey]; + var locals = { + $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, + $element: $element, + $attrs: attrs, + $transclude: transcludeFn + }; + + var controller = directive.controller; + if (controller === '@') { + controller = attrs[directive.name]; } + + var controllerInstance = $controller(controller, locals, true, directive.controllerAs); + + // For directives with element transclusion the element is a comment. + // In this case .data will not attach any data. + // Instead, we save the controllers for the element in a local hash and attach to .data + // later, once we have the actual element. + elementControllers[directive.name] = controllerInstance; + $element.data('$' + directive.name + 'Controller', controllerInstance.instance); } + return elementControllers; } - function markDirectivesAsIsolate(directives) { - // mark all directives as needing isolate scope. + // Depending upon the context in which a directive finds itself it might need to have a new isolated + // or child scope created. For instance: + // * if the directive has been pulled into a template because another directive with a higher priority + // asked for element transclusion + // * if the directive itself asks for transclusion but it is at the root of a template and the original + // element was replaced. See https://github.com/angular/angular.js/issues/12936 + function markDirectiveScope(directives, isolateScope, newScope) { for (var j = 0, jj = directives.length; j < jj; j++) { - directives[j] = inherit(directives[j], {$$isolateScope: true}); + directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope}); } } @@ -6628,25 +10164,51 @@ if (name === ignoreDirective) return null; var match = null; if (hasDirectives.hasOwnProperty(name)) { - for(var directive, directives = $injector.get(name + Suffix), - i = 0, ii = directives.length; i directive.priority) && - directive.restrict.indexOf(location) != -1) { - if (startAttrName) { - directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); + for (var directive, directives = $injector.get(name + Suffix), + i = 0, ii = directives.length; i < ii; i++) { + directive = directives[i]; + if ((isUndefined(maxPriority) || maxPriority > directive.priority) && + directive.restrict.indexOf(location) !== -1) { + if (startAttrName) { + directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); + } + if (!directive.$$bindings) { + var bindings = directive.$$bindings = + parseDirectiveBindings(directive, directive.name); + if (isObject(bindings.isolateScope)) { + directive.$$isolateBindings = bindings.isolateScope; } - tDirectives.push(directive); - match = directive; } - } catch(e) { $exceptionHandler(e); } + tDirectives.push(directive); + match = directive; + } } } return match; } + /** + * looks up the directive and returns true if it is a multi-element directive, + * and therefore requires DOM nodes between -start and -end markers to be grouped + * together. + * + * @param {string} name name of the directive to look up. + * @returns true if directive was registered as multi-element. + */ + function directiveIsMultiElement(name) { + if (hasDirectives.hasOwnProperty(name)) { + for (var directive, directives = $injector.get(name + Suffix), + i = 0, ii = directives.length; i < ii; i++) { + directive = directives[i]; + if (directive.multiElement) { + return true; + } + } + } + return false; + } + /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. @@ -6657,14 +10219,17 @@ */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, - dstAttr = dst.$attr, - $element = dst.$$element; + dstAttr = dst.$attr; // reapply the old attributes to the new element forEach(dst, function(value, key) { - if (key.charAt(0) != '$') { - if (src[key]) { - value += (key === 'style' ? ';' : ' ') + src[key]; + if (key.charAt(0) !== '$') { + if (src[key] && src[key] !== value) { + if (value.length) { + value += (key === 'style' ? ';' : ' ') + src[key]; + } else { + value = src[key]; + } } dst.$set(key, value, true, srcAttr[key]); } @@ -6672,18 +10237,16 @@ // copy the new attributes on the old attrs object forEach(src, function(value, key) { - if (key == 'class') { - safeAddClass($element, value); - dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; - } else if (key == 'style') { - $element.attr('style', $element.attr('style') + ';' + value); - dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; - // `dst` will never contain hasOwnProperty as DOM parser won't let it. - // You will get an "InvalidCharacterError: DOM Exception 5" error if you - // have an attribute like "has-own-property" or "data-has-own-property", etc. - } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { + // Check if we already set this attribute in the loop above. + // `dst` will never contain hasOwnProperty as DOM parser won't let it. + // You will get an "InvalidCharacterError: DOM Exception 5" error if you + // have an attribute like "has-own-property" or "data-has-own-property", etc. + if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') { dst[key] = value; - dstAttr[key] = srcAttr[key]; + + if (key !== 'class' && key !== 'style') { + dstAttr[key] = srcAttr[key]; + } } }); } @@ -6696,18 +10259,18 @@ afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), - // The fact that we have to copy and patch the directive seems wrong! - derivedSyncDirective = extend({}, origAsyncDirective, { + derivedSyncDirective = inherit(origAsyncDirective, { templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective }), templateUrl = (isFunction(origAsyncDirective.templateUrl)) ? origAsyncDirective.templateUrl($compileNode, tAttrs) - : origAsyncDirective.templateUrl; + : origAsyncDirective.templateUrl, + templateNamespace = origAsyncDirective.templateNamespace; $compileNode.empty(); - $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}). - success(function(content) { + $templateRequest(templateUrl) + .then(function(content) { var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; content = denormalizeTemplate(content); @@ -6716,13 +10279,13 @@ if (jqLiteIsTextNode(content)) { $template = []; } else { - $template = jqLite(content); + $template = removeComments(wrapTemplate(templateNamespace, trim(content))); } compileNode = $template[0]; - if ($template.length != 1 || compileNode.nodeType !== 1) { + if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { throw $compileMinErr('tplrt', - "Template for directive '{0}' must have exactly one root element. {1}", + 'Template for directive \'{0}\' must have exactly one root element. {1}', origAsyncDirective.name, templateUrl); } @@ -6731,7 +10294,9 @@ var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); if (isObject(origAsyncDirective.scope)) { - markDirectivesAsIsolate(templateDirectives); + // the original directive that caused the template to be loaded async required + // an isolate scope + markDirectiveScope(templateDirectives, true); } directives = templateDirectives.concat(directives); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); @@ -6746,20 +10311,21 @@ childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, previousCompileContext); forEach($rootElement, function(node, i) { - if (node == compileNode) { + if (node === compileNode) { $rootElement[i] = $compileNode[0]; } }); afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); - - while(linkQueue.length) { + while (linkQueue.length) { var scope = linkQueue.shift(), beforeTemplateLinkNode = linkQueue.shift(), linkRootElement = linkQueue.shift(), boundTranscludeFn = linkQueue.shift(), linkNode = $compileNode[0]; + if (scope.$$destroyed) continue; + if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { var oldClasses = beforeTemplateLinkNode.className; @@ -6768,14 +10334,13 @@ // it was cloned therefore we have to clone as well. linkNode = jqLiteClone(compileNode); } - replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); // Copy in CSS classes from original node safeAddClass(jqLite(linkNode), oldClasses); } - if (afterTemplateNodeLinkFn.transclude) { - childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude); + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); } else { childBoundTranscludeFn = boundTranscludeFn; } @@ -6783,19 +10348,25 @@ childBoundTranscludeFn); } linkQueue = null; - }). - error(function(response, code, headers, config) { - throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url); - }); + }).catch(function(error) { + if (isError(error)) { + $exceptionHandler(error); + } + }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { + var childBoundTranscludeFn = boundTranscludeFn; + if (scope.$$destroyed) return; if (linkQueue) { - linkQueue.push(scope); - linkQueue.push(node); - linkQueue.push(rootElement); - linkQueue.push(boundTranscludeFn); + linkQueue.push(scope, + node, + rootElement, + childBoundTranscludeFn); } else { - afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, boundTranscludeFn); + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); + } + afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); } }; } @@ -6811,11 +10382,18 @@ return a.index - b.index; } - function assertNoDuplicate(what, previousDirective, directive, element) { + + function wrapModuleNameIfDefined(moduleName) { + return moduleName ? + (' (module: ' + moduleName + ')') : + ''; + } + if (previousDirective) { - throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', - previousDirective.name, directive.name, what, startingTag(element)); + throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}', + previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName), + directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element)); } } @@ -6825,87 +10403,127 @@ if (interpolateFn) { directives.push({ priority: 0, - compile: valueFn(function textInterpolateLinkFn(scope, node) { - var parent = node.parent(), - bindings = parent.data('$binding') || []; - bindings.push(interpolateFn); - safeAddClass(parent.data('$binding', bindings), 'ng-binding'); - scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { - node[0].nodeValue = value; - }); - }) + compile: function textInterpolateCompileFn(templateNode) { + var templateNodeParent = templateNode.parent(), + hasCompileParent = !!templateNodeParent.length; + + // When transcluding a template that has bindings in the root + // we don't have a parent and thus need to add the class during linking fn. + if (hasCompileParent) compile.$$addBindingClass(templateNodeParent); + + return function textInterpolateLinkFn(scope, node) { + var parent = node.parent(); + if (!hasCompileParent) compile.$$addBindingClass(parent); + compile.$$addBindingInfo(parent, interpolateFn.expressions); + scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { + node[0].nodeValue = value; + }); + }; + } }); } } + function wrapTemplate(type, template) { + type = lowercase(type || 'html'); + switch (type) { + case 'svg': + case 'math': + var wrapper = window.document.createElement('div'); + wrapper.innerHTML = '<' + type + '>' + template + ''; + return wrapper.childNodes[0].childNodes; + default: + return template; + } + } + + function getTrustedContext(node, attrNormalizedName) { - if (attrNormalizedName == "srcdoc") { + if (attrNormalizedName === 'srcdoc') { return $sce.HTML; } var tag = nodeName_(node); - // maction[xlink:href] can source SVG. It's not limited to . - if (attrNormalizedName == "xlinkHref" || - (tag == "FORM" && attrNormalizedName == "action") || - (tag != "IMG" && (attrNormalizedName == "src" || - attrNormalizedName == "ngSrc"))) { + // All tags with src attributes require a RESOURCE_URL value, except for + // img and various html5 media tags. + if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') { + if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) { + return $sce.RESOURCE_URL; + } + // maction[xlink:href] can source SVG. It's not limited to . + } else if (attrNormalizedName === 'xlinkHref' || + (tag === 'form' && attrNormalizedName === 'action') || + // links can be stylesheets or imports, which can run script in the current origin + (tag === 'link' && attrNormalizedName === 'href') + ) { return $sce.RESOURCE_URL; } } - function addAttrInterpolateDirective(node, directives, value, name) { - var interpolateFn = $interpolate(value, true); + function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) { + var trustedContext = getTrustedContext(node, name); + var mustHaveExpression = !isNgAttr; + var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr; + + var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing); // no interpolation found -> ignore if (!interpolateFn) return; - - if (name === "multiple" && nodeName_(node) === "SELECT") { - throw $compileMinErr("selmulti", - "Binding to the 'multiple' attribute is not supported. Element: {0}", + if (name === 'multiple' && nodeName_(node) === 'select') { + throw $compileMinErr('selmulti', + 'Binding to the \'multiple\' attribute is not supported. Element: {0}', startingTag(node)); } + if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { + throw $compileMinErr('nodomevents', + 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' + + 'ng- versions (such as ng-click instead of onclick) instead.'); + } + directives.push({ priority: 100, compile: function() { return { pre: function attrInterpolatePreLinkFn(scope, element, attr) { - var $$observers = (attr.$$observers || (attr.$$observers = {})); - - if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { - throw $compileMinErr('nodomevents', - "Interpolations for HTML DOM event attributes are disallowed. Please use the " + - "ng- versions (such as ng-click instead of onclick) instead."); + var $$observers = (attr.$$observers || (attr.$$observers = createMap())); + + // If the attribute has changed since last $interpolate()ed + var newValue = attr[name]; + if (newValue !== value) { + // we need to interpolate again since the attribute value has been updated + // (e.g. by another directive's compile function) + // ensure unset/empty values make interpolateFn falsy + interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing); + value = newValue; } - // we need to interpolate again, in case the attribute value has been updated - // (e.g. by another directive's compile function) - interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name)); - // if attribute was updated so that there is no interpolation going on we don't want to // register any observers if (!interpolateFn) return; - // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the - // actual attr value + // initialize attr object so that it's ready in case we need the value for isolate + // scope initialization, otherwise the value would not be available from isolate + // directive's linking fn during linking phase attr[name] = interpolateFn(scope); + ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). - $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { - //special case for class attribute addition + removal - //so that class changes can tap into the animation - //hooks provided by the $animate service. Be sure to - //skip animations when the first digest occurs (when - //both the new and the old values are the same) since - //the CSS classes are the non-interpolated values - if(name === 'class' && newValue != oldValue) { - attr.$updateClass(newValue, oldValue); - } else { - attr.$set(name, newValue); - } - }); + $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { + //special case for class attribute addition + removal + //so that class changes can tap into the animation + //hooks provided by the $animate service. Be sure to + //skip animations when the first digest occurs (when + //both the new and the old values are the same) since + //the CSS classes are the non-interpolated values + if (name === 'class' && newValue !== oldValue) { + attr.$updateClass(newValue, oldValue); + } else { + attr.$set(name, newValue); + } + }); } }; } @@ -6930,8 +10548,8 @@ i, ii; if ($rootElement) { - for(i = 0, ii = $rootElement.length; i < ii; i++) { - if ($rootElement[i] == firstElementToRemove) { + for (i = 0, ii = $rootElement.length; i < ii; i++) { + if ($rootElement[i] === firstElementToRemove) { $rootElement[i++] = newNode; for (var j = i, j2 = j + removeCount - 1, jj = $rootElement.length; @@ -6943,6 +10561,13 @@ } } $rootElement.length -= removeCount - 1; + + // If the replaced element is also the jQuery .context then replace it + // .context is a deprecated jQuery api, so we should set it only when jQuery set it + // http://api.jquery.com/context/ + if ($rootElement.context === firstElementToRemove) { + $rootElement.context = newNode; + } break; } } @@ -6951,16 +10576,34 @@ if (parent) { parent.replaceChild(newNode, firstElementToRemove); } - var fragment = document.createDocumentFragment(); - fragment.appendChild(firstElementToRemove); - newNode[jqLite.expando] = firstElementToRemove[jqLite.expando]; - for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { - var element = elementsToRemove[k]; - jqLite(element).remove(); // must do this way to clean up expando - fragment.appendChild(element); - delete elementsToRemove[k]; + + // Append all the `elementsToRemove` to a fragment. This will... + // - remove them from the DOM + // - allow them to still be traversed with .nextSibling + // - allow a single fragment.qSA to fetch all elements being removed + var fragment = window.document.createDocumentFragment(); + for (i = 0; i < removeCount; i++) { + fragment.appendChild(elementsToRemove[i]); + } + + if (jqLite.hasData(firstElementToRemove)) { + // Copy over user data (that includes AngularJS's $scope etc.). Don't copy private + // data here because there's no public interface in jQuery to do that and copying over + // event listeners (which is the main use of private data) wouldn't work anyway. + jqLite.data(newNode, jqLite.data(firstElementToRemove)); + + // Remove $destroy event listeners from `firstElementToRemove` + jqLite(firstElementToRemove).off('$destroy'); } + // Cleanup any data/listeners on the elements and children. + // This includes invoking the $destroy event on any elements with listeners. + jqLite.cleanData(fragment.querySelectorAll('*')); + + // Update the jqLite collection to only contain the `newNode` + for (i = 1; i < removeCount; i++) { + delete elementsToRemove[i]; + } elementsToRemove[0] = newNode; elementsToRemove.length = 1; } @@ -6969,102 +10612,332 @@ function cloneAndAnnotateFn(fn, annotation) { return extend(function() { return fn.apply(null, arguments); }, fn, annotation); } - }]; - } - - var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; - /** - * Converts all accepted directives format into proper directive name. - * All of these will become 'myDirective': - * my:Directive - * my-directive - * x-my-directive - * data-my:directive - * - * Also there is special case for Moz prefix starting with upper case letter. - * @param name Name to normalize - */ - function directiveNormalize(name) { - return camelCase(name.replace(PREFIX_REGEXP, '')); - } - /** - * @ngdoc type - * @name $compile.directive.Attributes - * - * @description - * A shared object between directive compile / linking functions which contains normalized DOM - * element attributes. The values reflect current binding state `{{ }}`. The normalization is - * needed since all of these are treated as equivalent in Angular: - * - * - */ - /** - * @ngdoc property - * @name $compile.directive.Attributes#$attr - * @returns {object} A map of DOM element attribute names to the normalized name. This is - * needed to do reverse lookup from normalized name back to actual name. - */ + function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) { + try { + linkFn(scope, $element, attrs, controllers, transcludeFn); + } catch (e) { + $exceptionHandler(e, startingTag($element)); + } + } + function strictBindingsCheck(attrName, directiveName) { + if (strictComponentBindingsEnabled) { + throw $compileMinErr('missingattr', + 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!', + attrName, directiveName); + } + } - /** - * @ngdoc method - * @name $compile.directive.Attributes#$set - * @function - * - * @description - * Set DOM element attribute value. - * - * - * @param {string} name Normalized element attribute name of the property to modify. The name is - * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} - * property to the original name. - * @param {string} value Value to set the attribute to. The value can be an interpolated string. - */ + // Set up $watches for isolate scope and controller bindings. + function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) { + var removeWatchCollection = []; + var initialChanges = {}; + var changes; + forEach(bindings, function initializeBinding(definition, scopeName) { + var attrName = definition.attrName, + optional = definition.optional, + mode = definition.mode, // @, =, <, or & + lastValue, + parentGet, parentSet, compare, removeWatch; + switch (mode) { - /** - * Closure compiler type information - */ + case '@': + if (!optional && !hasOwnProperty.call(attrs, attrName)) { + strictBindingsCheck(attrName, directive.name); + destination[scopeName] = attrs[attrName] = undefined; - function nodesetLinkingFn( - /* angular.Scope */ scope, - /* NodeList */ nodeList, - /* Element */ rootElement, - /* function(Function) */ boundTranscludeFn - ){} + } + removeWatch = attrs.$observe(attrName, function(value) { + if (isString(value) || isBoolean(value)) { + var oldValue = destination[scopeName]; + recordChanges(scopeName, value, oldValue); + destination[scopeName] = value; + } + }); + attrs.$$observers[attrName].$$scope = scope; + lastValue = attrs[attrName]; + if (isString(lastValue)) { + // If the attribute has been provided then we trigger an interpolation to ensure + // the value is there for use in the link fn + destination[scopeName] = $interpolate(lastValue)(scope); + } else if (isBoolean(lastValue)) { + // If the attributes is one of the BOOLEAN_ATTR then AngularJS will have converted + // the value to boolean rather than a string, so we special case this situation + destination[scopeName] = lastValue; + } + initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]); + removeWatchCollection.push(removeWatch); + break; - function directiveLinkingFn( - /* nodesetLinkingFn */ nodesetLinkingFn, - /* angular.Scope */ scope, - /* Node */ node, - /* Element */ rootElement, - /* function(Function) */ boundTranscludeFn - ){} + case '=': + if (!hasOwnProperty.call(attrs, attrName)) { + if (optional) break; + strictBindingsCheck(attrName, directive.name); + attrs[attrName] = undefined; + } + if (optional && !attrs[attrName]) break; - function tokenDifference(str1, str2) { - var values = '', - tokens1 = str1.split(/\s+/), - tokens2 = str2.split(/\s+/); + parentGet = $parse(attrs[attrName]); + if (parentGet.literal) { + compare = equals; + } else { + compare = simpleCompare; + } + parentSet = parentGet.assign || function() { + // reset the change, or we will throw this exception on every $digest + lastValue = destination[scopeName] = parentGet(scope); + throw $compileMinErr('nonassign', + 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!', + attrs[attrName], attrName, directive.name); + }; + lastValue = destination[scopeName] = parentGet(scope); + var parentValueWatch = function parentValueWatch(parentValue) { + if (!compare(parentValue, destination[scopeName])) { + // we are out of sync and need to copy + if (!compare(parentValue, lastValue)) { + // parent changed and it has precedence + destination[scopeName] = parentValue; + } else { + // if the parent can be assigned then do so + parentSet(scope, parentValue = destination[scopeName]); + } + } + lastValue = parentValue; + return lastValue; + }; + parentValueWatch.$stateful = true; + if (definition.collection) { + removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch); + } else { + removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal); + } + removeWatchCollection.push(removeWatch); + break; + + case '<': + if (!hasOwnProperty.call(attrs, attrName)) { + if (optional) break; + strictBindingsCheck(attrName, directive.name); + attrs[attrName] = undefined; + } + if (optional && !attrs[attrName]) break; + + parentGet = $parse(attrs[attrName]); + var deepWatch = parentGet.literal; + + var initialValue = destination[scopeName] = parentGet(scope); + initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]); + + removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) { + if (oldValue === newValue) { + if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) { + return; + } + oldValue = initialValue; + } + recordChanges(scopeName, newValue, oldValue); + destination[scopeName] = newValue; + }, deepWatch); + + removeWatchCollection.push(removeWatch); + break; + + case '&': + if (!optional && !hasOwnProperty.call(attrs, attrName)) { + strictBindingsCheck(attrName, directive.name); + } + // Don't assign Object.prototype method to scope + parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop; + + // Don't assign noop to destination if expression is not valid + if (parentGet === noop && optional) break; + + destination[scopeName] = function(locals) { + return parentGet(scope, locals); + }; + break; + } + }); + + function recordChanges(key, currentValue, previousValue) { + if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) { + // If we have not already scheduled the top level onChangesQueue handler then do so now + if (!onChangesQueue) { + scope.$$postDigest(flushOnChangesQueue); + onChangesQueue = []; + } + // If we have not already queued a trigger of onChanges for this controller then do so now + if (!changes) { + changes = {}; + onChangesQueue.push(triggerOnChangesHook); + } + // If the has been a change on this property already then we need to reuse the previous value + if (changes[key]) { + previousValue = changes[key].previousValue; + } + // Store this change + changes[key] = new SimpleChange(previousValue, currentValue); + } + } + + function triggerOnChangesHook() { + destination.$onChanges(changes); + // Now clear the changes so that we schedule onChanges when more changes arrive + changes = undefined; + } + + return { + initialChanges: initialChanges, + removeWatches: removeWatchCollection.length && function removeWatches() { + for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) { + removeWatchCollection[i](); + } + } + }; + } + }]; + } + + function SimpleChange(previous, current) { + this.previousValue = previous; + this.currentValue = current; + } + SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; }; + + + var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i; + var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g; + + /** + * Converts all accepted directives format into proper directive name. + * @param name Name to normalize + */ + function directiveNormalize(name) { + return name + .replace(PREFIX_REGEXP, '') + .replace(SPECIAL_CHARS_REGEXP, function(_, letter, offset) { + return offset ? letter.toUpperCase() : letter; + }); + } + + /** + * @ngdoc type + * @name $compile.directive.Attributes + * + * @description + * A shared object between directive compile / linking functions which contains normalized DOM + * element attributes. The values reflect current binding state `{{ }}`. The normalization is + * needed since all of these are treated as equivalent in AngularJS: + * + * ``` + * + * ``` + */ + + /** + * @ngdoc property + * @name $compile.directive.Attributes#$attr + * + * @description + * A map of DOM element attribute names to the normalized name. This is + * needed to do reverse lookup from normalized name back to actual name. + */ + + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$set + * @kind function + * + * @description + * Set DOM element attribute value. + * + * + * @param {string} name Normalized element attribute name of the property to modify. The name is + * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} + * property to the original name. + * @param {string} value Value to set the attribute to. The value can be an interpolated string. + */ + + + + /** + * Closure compiler type information + */ + + function nodesetLinkingFn( + /* angular.Scope */ scope, + /* NodeList */ nodeList, + /* Element */ rootElement, + /* function(Function) */ boundTranscludeFn + ) {} + + function directiveLinkingFn( + /* nodesetLinkingFn */ nodesetLinkingFn, + /* angular.Scope */ scope, + /* Node */ node, + /* Element */ rootElement, + /* function(Function) */ boundTranscludeFn + ) {} + + function tokenDifference(str1, str2) { + var values = '', + tokens1 = str1.split(/\s+/), + tokens2 = str2.split(/\s+/); outer: - for(var i = 0; i < tokens1.length; i++) { + for (var i = 0; i < tokens1.length; i++) { var token = tokens1[i]; - for(var j = 0; j < tokens2.length; j++) { - if(token == tokens2[j]) continue outer; + for (var j = 0; j < tokens2.length; j++) { + if (token === tokens2[j]) continue outer; } values += (values.length > 0 ? ' ' : '') + token; } return values; } + function removeComments(jqNodes) { + jqNodes = jqLite(jqNodes); + var i = jqNodes.length; + + if (i <= 1) { + return jqNodes; + } + + while (i--) { + var node = jqNodes[i]; + if (node.nodeType === NODE_TYPE_COMMENT || + (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) { + splice.call(jqNodes, i, 1); + } + } + return jqNodes; + } + + var $controllerMinErr = minErr('$controller'); + + + var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/; + function identifierForController(controller, ident) { + if (ident && isString(ident)) return ident; + if (isString(controller)) { + var match = CNTRL_REG.exec(controller); + if (match) return match[3]; + } + } + + /** * @ngdoc provider * @name $controllerProvider + * @this + * * @description - * The {@link ng.$controller $controller service} is used by Angular to create new + * The {@link ng.$controller $controller service} is used by AngularJS to create new * controllers. * * This provider allows controller registration via the @@ -7072,8 +10945,16 @@ */ function $ControllerProvider() { var controllers = {}, - CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; + globals = false; + /** + * @ngdoc method + * @name $controllerProvider#has + * @param {string} name Controller name to check. + */ + this.has = function(name) { + return controllers.hasOwnProperty(name); + }; /** * @ngdoc method @@ -7092,6 +10973,20 @@ } }; + /** + * @ngdoc method + * @name $controllerProvider#allowGlobals + * @description If called, allows `$controller` to find controller constructors on `window` + * + * @deprecated + * sinceVersion="v1.3.0" + * removeVersion="v1.7.0" + * This method of finding controllers has been deprecated. + */ + this.allowGlobals = function() { + globals = true; + }; + this.$get = ['$injector', '$window', function($injector, $window) { @@ -7106,7 +11001,12 @@ * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor - * * check `window[constructor]` on the global `window` object + * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global + * `window` object (deprecated, not recommended) + * + * The string can use the `controller as property` syntax, where the controller instance is published + * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this + * to work correctly. * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. @@ -7117,34 +11017,95 @@ * It's just a simple call to {@link auto.$injector $injector}, but extracted into * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). */ - return function(expression, locals) { + return function $controller(expression, locals, later, ident) { + // PRIVATE API: + // param `later` --- indicates that the controller's constructor is invoked at a later time. + // If true, $controller will allocate the object with the correct + // prototype chain, but will not invoke the controller until a returned + // callback is invoked. + // param `ident` --- An optional label which overrides the label parsed from the controller + // expression, if any. var instance, match, constructor, identifier; + later = later === true; + if (ident && isString(ident)) { + identifier = ident; + } - if(isString(expression)) { - match = expression.match(CNTRL_REG), - constructor = match[1], - identifier = match[3]; + if (isString(expression)) { + match = expression.match(CNTRL_REG); + if (!match) { + throw $controllerMinErr('ctrlfmt', + 'Badly formed controller string \'{0}\'. ' + + 'Must match `__name__ as __id__` or `__name__`.', expression); + } + constructor = match[1]; + identifier = identifier || match[3]; expression = controllers.hasOwnProperty(constructor) ? controllers[constructor] - : getter(locals.$scope, constructor, true) || getter($window, constructor, true); + : getter(locals.$scope, constructor, true) || + (globals ? getter($window, constructor, true) : undefined); + + if (!expression) { + throw $controllerMinErr('ctrlreg', + 'The controller with the name \'{0}\' is not registered.', constructor); + } assertArgFn(expression, constructor, true); } - instance = $injector.instantiate(expression, locals); - - if (identifier) { - if (!(locals && typeof locals.$scope == 'object')) { - throw minErr('$controller')('noscp', - "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", - constructor || expression.name, identifier); + if (later) { + // Instantiate controller later: + // This machinery is used to create an instance of the object before calling the + // controller's constructor itself. + // + // This allows properties to be added to the controller before the constructor is + // invoked. Primarily, this is used for isolate scope bindings in $compile. + // + // This feature is not intended for use by applications, and is thus not documented + // publicly. + // Object creation: http://jsperf.com/create-constructor/2 + var controllerPrototype = (isArray(expression) ? + expression[expression.length - 1] : expression).prototype; + instance = Object.create(controllerPrototype || null); + + if (identifier) { + addIdentifier(locals, identifier, instance, constructor || expression.name); } - locals.$scope[identifier] = instance; + return extend(function $controllerInit() { + var result = $injector.invoke(expression, instance, locals, constructor); + if (result !== instance && (isObject(result) || isFunction(result))) { + instance = result; + if (identifier) { + // If result changed, re-assign controllerAs value to scope. + addIdentifier(locals, identifier, instance, constructor || expression.name); + } + } + return instance; + }, { + instance: instance, + identifier: identifier + }); + } + + instance = $injector.instantiate(expression, locals, constructor); + + if (identifier) { + addIdentifier(locals, identifier, instance, constructor || expression.name); } return instance; }; + + function addIdentifier(locals, identifier, instance, name) { + if (!(locals && isObject(locals.$scope))) { + throw minErr('$controller')('noscp', + 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.', + name, identifier); + } + + locals.$scope[identifier] = instance; + } }]; } @@ -7152,39 +11113,69 @@ * @ngdoc service * @name $document * @requires $window + * @this * * @description * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. * * @example - + -
    +

    $document title:

    window.document title:

    - function MainCtrl($scope, $document) { - $scope.title = $document[0].title; - $scope.windowTitle = angular.element(window.document)[0].title; - } + angular.module('documentExample', []) + .controller('ExampleController', ['$scope', '$document', function($scope, $document) { + $scope.title = $document[0].title; + $scope.windowTitle = angular.element(window.document)[0].title; + }]); */ - function $DocumentProvider(){ - this.$get = ['$window', function(window){ + function $DocumentProvider() { + this.$get = ['$window', function(window) { return jqLite(window.document); }]; } + + /** + * @private + * @this + * Listens for document visibility change and makes the current status accessible. + */ + function $$IsDocumentHiddenProvider() { + this.$get = ['$document', '$rootScope', function($document, $rootScope) { + var doc = $document[0]; + var hidden = doc && doc.hidden; + + $document.on('visibilitychange', changeListener); + + $rootScope.$on('$destroy', function() { + $document.off('visibilitychange', changeListener); + }); + + function changeListener() { + hidden = doc.hidden; + } + + return function() { + return hidden; + }; + }]; + } + /** * @ngdoc service * @name $exceptionHandler * @requires ng.$log + * @this * * @description - * Any uncaught exception in angular expressions is delegated to this service. + * Any uncaught exception in AngularJS expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * @@ -7193,20 +11184,31 @@ * * ## Example: * + * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught + * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead + * of `$log.error()`. + * * ```js - * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () { - * return function (exception, cause) { - * exception.message += ' (caused by "' + cause + '")'; - * throw exception; - * }; - * }); + * angular. + * module('exceptionOverwrite', []). + * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) { + * return function myExceptionHandler(exception, cause) { + * logErrorsToBackend(exception, cause); + * $log.warn(exception, cause); + * }; + * }]); * ``` * - * This example will override the normal action of `$exceptionHandler`, to make angular - * exceptions fail hard when they happen, instead of just logging to the console. + *
    + * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind` + * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler} + * (unless executed during a digest). + * + * If you wish, you can manually delegate exceptions, e.g. + * `try { ... } catch(e) { $exceptionHandler(e); }` * * @param {Error} exception Exception associated with the error. - * @param {string=} cause optional information about the context in which + * @param {string=} cause Optional information about the context in which * the error was thrown. * */ @@ -7218,110 +11220,349 @@ }]; } - /** - * Parse headers into key value object - * - * @param {string} headers Raw headers as a string - * @returns {Object} Parsed headers as key value object - */ - function parseHeaders(headers) { - var parsed = {}, key, val, i; - - if (!headers) return parsed; - - forEach(headers.split('\n'), function(line) { - i = line.indexOf(':'); - key = lowercase(trim(line.substr(0, i))); - val = trim(line.substr(i + 1)); - - if (key) { - if (parsed[key]) { - parsed[key] += ', ' + val; + var $$ForceReflowProvider = /** @this */ function() { + this.$get = ['$document', function($document) { + return function(domNode) { + //the line below will force the browser to perform a repaint so + //that all the animated elements within the animation frame will + //be properly updated and drawn on screen. This is required to + //ensure that the preparation animation is properly flushed so that + //the active state picks up from there. DO NOT REMOVE THIS LINE. + //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH + //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND + //WILL TAKE YEARS AWAY FROM YOUR LIFE. + if (domNode) { + if (!domNode.nodeType && domNode instanceof jqLite) { + domNode = domNode[0]; + } } else { - parsed[key] = val; + domNode = $document[0].body; } - } - }); - - return parsed; - } - - - /** - * Returns a function that provides access to parsed headers. - * - * Headers are lazy parsed when first requested. - * @see parseHeaders - * - * @param {(string|Object)} headers Headers to provide access to. - * @returns {function(string=)} Returns a getter function which if called with: - * - * - if called with single an argument returns a single header value or null - * - if called with no arguments returns an object containing all headers. - */ - function headersGetter(headers) { - var headersObj = isObject(headers) ? headers : undefined; - - return function(name) { - if (!headersObj) headersObj = parseHeaders(headers); + return domNode.offsetWidth + 1; + }; + }]; + }; - if (name) { - return headersObj[lowercase(name)] || null; - } + var APPLICATION_JSON = 'application/json'; + var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; + var JSON_START = /^\[|^\{(?!\{)/; + var JSON_ENDS = { + '[': /]$/, + '{': /}$/ + }; + var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/; + var $httpMinErr = minErr('$http'); - return headersObj; - }; + function serializeValue(v) { + if (isObject(v)) { + return isDate(v) ? v.toISOString() : toJson(v); + } + return v; } - /** - * Chain all given functions - * - * This function is used for both request and response transforming - * - * @param {*} data Data to transform. - * @param {function(string=)} headers Http headers getter fn. - * @param {(Function|Array.)} fns Function or an array of functions. - * @returns {*} Transformed data. - */ - function transformData(data, headers, fns) { - if (isFunction(fns)) - return fns(data, headers); - - forEach(fns, function(fn) { - data = fn(data, headers); - }); - - return data; - } + /** @this */ + function $HttpParamSerializerProvider() { + /** + * @ngdoc service + * @name $httpParamSerializer + * @description + * + * Default {@link $http `$http`} params serializer that converts objects to strings + * according to the following rules: + * + * * `{'foo': 'bar'}` results in `foo=bar` + * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object) + * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element) + * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object) + * + * Note that serializer will sort the request parameters alphabetically. + * */ + this.$get = function() { + return function ngParamSerializer(params) { + if (!params) return ''; + var parts = []; + forEachSorted(params, function(value, key) { + if (value === null || isUndefined(value) || isFunction(value)) return; + if (isArray(value)) { + forEach(value, function(v) { + parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v))); + }); + } else { + parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value))); + } + }); - function isSuccess(status) { - return 200 <= status && status < 300; + return parts.join('&'); + }; + }; } + /** @this */ + function $HttpParamSerializerJQLikeProvider() { + /** + * @ngdoc service + * @name $httpParamSerializerJQLike + * + * @description + * + * Alternative {@link $http `$http`} params serializer that follows + * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic. + * The serializer will also sort the params alphabetically. + * + * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property: + * + * ```js + * $http({ + * url: myUrl, + * method: 'GET', + * params: myParams, + * paramSerializer: '$httpParamSerializerJQLike' + * }); + * ``` + * + * It is also possible to set it as the default `paramSerializer` in the + * {@link $httpProvider#defaults `$httpProvider`}. + * + * Additionally, you can inject the serializer and use it explicitly, for example to serialize + * form data for submission: + * + * ```js + * .controller(function($http, $httpParamSerializerJQLike) { + * //... + * + * $http({ + * url: myUrl, + * method: 'POST', + * data: $httpParamSerializerJQLike(myData), + * headers: { + * 'Content-Type': 'application/x-www-form-urlencoded' + * } + * }); + * + * }); + * ``` + * + * */ + this.$get = function() { + return function jQueryLikeParamSerializer(params) { + if (!params) return ''; + var parts = []; + serialize(params, '', true); + return parts.join('&'); + + function serialize(toSerialize, prefix, topLevel) { + if (toSerialize === null || isUndefined(toSerialize)) return; + if (isArray(toSerialize)) { + forEach(toSerialize, function(value, index) { + serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']'); + }); + } else if (isObject(toSerialize) && !isDate(toSerialize)) { + forEachSorted(toSerialize, function(value, key) { + serialize(value, prefix + + (topLevel ? '' : '[') + + key + + (topLevel ? '' : ']')); + }); + } else { + parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize))); + } + } + }; + }; + } + + function defaultHttpResponseTransform(data, headers) { + if (isString(data)) { + // Strip json vulnerability protection prefix and trim whitespace + var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim(); + + if (tempData) { + var contentType = headers('Content-Type'); + var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0); + + if (hasJsonContentType || isJsonLike(tempData)) { + try { + data = fromJson(tempData); + } catch (e) { + if (!hasJsonContentType) { + return data; + } + throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' + + 'Parse error: "{1}"', data, e); + } + } + } + } + + return data; + } + + function isJsonLike(str) { + var jsonStart = str.match(JSON_START); + return jsonStart && JSON_ENDS[jsonStart[0]].test(str); + } + + /** + * Parse headers into key value object + * + * @param {string} headers Raw headers as a string + * @returns {Object} Parsed headers as key value object + */ + function parseHeaders(headers) { + var parsed = createMap(), i; + + function fillInParsed(key, val) { + if (key) { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + + if (isString(headers)) { + forEach(headers.split('\n'), function(line) { + i = line.indexOf(':'); + fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1))); + }); + } else if (isObject(headers)) { + forEach(headers, function(headerVal, headerKey) { + fillInParsed(lowercase(headerKey), trim(headerVal)); + }); + } + + return parsed; + } + + + /** + * Returns a function that provides access to parsed headers. + * + * Headers are lazy parsed when first requested. + * @see parseHeaders + * + * @param {(string|Object)} headers Headers to provide access to. + * @returns {function(string=)} Returns a getter function which if called with: + * + * - if called with an argument returns a single header value or null + * - if called with no arguments returns an object containing all headers. + */ + function headersGetter(headers) { + var headersObj; + + return function(name) { + if (!headersObj) headersObj = parseHeaders(headers); + + if (name) { + var value = headersObj[lowercase(name)]; + if (value === undefined) { + value = null; + } + return value; + } + + return headersObj; + }; + } + + + /** + * Chain all given functions + * + * This function is used for both request and response transforming + * + * @param {*} data Data to transform. + * @param {function(string=)} headers HTTP headers getter fn. + * @param {number} status HTTP status code of the response. + * @param {(Function|Array.)} fns Function or an array of functions. + * @returns {*} Transformed data. + */ + function transformData(data, headers, status, fns) { + if (isFunction(fns)) { + return fns(data, headers, status); + } + + forEach(fns, function(fn) { + data = fn(data, headers, status); + }); + + return data; + } + + + function isSuccess(status) { + return 200 <= status && status < 300; + } - function $HttpProvider() { - var JSON_START = /^\s*(\[|\{[^\{])/, - JSON_END = /[\}\]]\s*$/, - PROTECTION_PREFIX = /^\)\]\}',?\n/, - CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; - + + /** + * @ngdoc provider + * @name $httpProvider + * @this + * + * @description + * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. + * */ + function $HttpProvider() { + /** + * @ngdoc property + * @name $httpProvider#defaults + * @description + * + * Object containing default values for all {@link ng.$http $http} requests. + * + * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with + * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses + * by default. See {@link $http#caching $http Caching} for more information. + * + * - **`defaults.headers`** - {Object} - Default headers for all $http requests. + * Refer to {@link ng.$http#setting-http-headers $http} for documentation on + * setting default headers. + * - **`defaults.headers.common`** + * - **`defaults.headers.post`** + * - **`defaults.headers.put`** + * - **`defaults.headers.patch`** + * + * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the + * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the + * {@link $jsonpCallbacks} service. Defaults to `'callback'`. + * + * - **`defaults.paramSerializer`** - `{string|function(Object):string}` - A function + * used to the prepare string representation of request parameters (specified as an object). + * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}. + * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}. + * + * - **`defaults.transformRequest`** - + * `{Array|function(data, headersGetter)}` - + * An array of functions (or a single function) which are applied to the request data. + * By default, this is an array with one request transformation function: + * + * - If the `data` property of the request configuration object contains an object, serialize it + * into JSON format. + * + * - **`defaults.transformResponse`** - + * `{Array|function(data, headersGetter, status)}` - + * An array of functions (or a single function) which are applied to the response data. By default, + * this is an array which applies one response transformation function that does two things: + * + * - If XSRF prefix is detected, strip it + * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}). + * - If the `Content-Type` is `application/json` or the response looks like JSON, + * deserialize it using a JSON parser. + * + * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. + * Defaults value is `'XSRF-TOKEN'`. + * + * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the + * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. + * + **/ var defaults = this.defaults = { // transform incoming response data - transformResponse: [function(data) { - if (isString(data)) { - // strip json vulnerability protection prefix - data = data.replace(PROTECTION_PREFIX, ''); - if (JSON_START.test(data) && JSON_END.test(data)) - data = fromJson(data); - } - return data; - }], + transformResponse: [defaultHttpResponseTransform], // transform outgoing request data transformRequest: [function(d) { - return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d; + return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d; }], // default headers @@ -7329,32 +11570,73 @@ common: { 'Accept': 'application/json, text/plain, */*' }, - post: copy(CONTENT_TYPE_APPLICATION_JSON), - put: copy(CONTENT_TYPE_APPLICATION_JSON), - patch: copy(CONTENT_TYPE_APPLICATION_JSON) + post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) }, xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN' + xsrfHeaderName: 'X-XSRF-TOKEN', + + paramSerializer: '$httpParamSerializer', + + jsonpCallbackParam: 'callback' }; + var useApplyAsync = false; /** - * Are ordered by request, i.e. they are applied in the same order as the - * array, on request, but reverse order, on response. - */ - var interceptorFactories = this.interceptors = []; + * @ngdoc method + * @name $httpProvider#useApplyAsync + * @description + * + * Configure $http service to combine processing of multiple http responses received at around + * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in + * significant performance improvement for bigger applications that make many HTTP requests + * concurrently (common during application bootstrap). + * + * Defaults to false. If no value is specified, returns the current configured value. + * + * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred + * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window + * to load and share the same digest cycle. + * + * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. + * otherwise, returns the current configured value. + **/ + this.useApplyAsync = function(value) { + if (isDefined(value)) { + useApplyAsync = !!value; + return this; + } + return useApplyAsync; + }; /** - * For historical reasons, response interceptors are ordered by the order in which - * they are applied to the response. (This is the opposite of interceptorFactories) - */ - var responseInterceptorFactories = this.responseInterceptors = []; + * @ngdoc property + * @name $httpProvider#interceptors + * @description + * + * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http} + * pre-processing of request or postprocessing of responses. + * + * These service factories are ordered by request, i.e. they are applied in the same order as the + * array, on request, but reverse order, on response. + * + * {@link ng.$http#interceptors Interceptors detailed info} + **/ + var interceptorFactories = this.interceptors = []; - this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', - function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { + this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce', + function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) { var defaultCache = $cacheFactory('$http'); + /** + * Make sure that default param serializer is exposed as a function + */ + defaults.paramSerializer = isString(defaults.paramSerializer) ? + $injector.get(defaults.paramSerializer) : defaults.paramSerializer; + /** * Interceptors stored in reverse order. Inner interceptors before outer interceptors. * The reversal is needed so that we can build up the interception chain around the @@ -7367,27 +11649,6 @@ ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); - forEach(responseInterceptorFactories, function(interceptorFactory, index) { - var responseFn = isString(interceptorFactory) - ? $injector.get(interceptorFactory) - : $injector.invoke(interceptorFactory); - - /** - * Response interceptors go before "around" interceptors (no real reason, just - * had to pick one.) But they are already reversed, so we can't use unshift, hence - * the splice. - */ - reversedInterceptors.splice(index, 0, { - response: function(response) { - return responseFn($q.when(response)); - }, - responseError: function(response) { - return responseFn($q.reject(response)); - } - }); - }); - - /** * @ngdoc service * @kind function @@ -7399,7 +11660,7 @@ * @requires $injector * * @description - * The `$http` service is a core Angular service that facilitates communication with the remote + * The `$http` service is a core AngularJS service that facilitates communication with the remote * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). * @@ -7414,52 +11675,52 @@ * it is important to familiarize yourself with these APIs and the guarantees they provide. * * - * # General usage - * The `$http` service is a function which takes a single argument — a configuration object — - * that is used to generate an HTTP request and returns a {@link ng.$q promise} - * with two $http specific methods: `success` and `error`. + * ## General usage + * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} — + * that is used to generate an HTTP request and returns a {@link ng.$q promise}. * * ```js - * $http({method: 'GET', url: '/someUrl'}). - * success(function(data, status, headers, config) { - * // this callback will be called asynchronously - * // when the response is available - * }). - * error(function(data, status, headers, config) { - * // called asynchronously if an error occurs - * // or server returns response with an error status. - * }); + * // Simple GET request example: + * $http({ + * method: 'GET', + * url: '/someUrl' + * }).then(function successCallback(response) { + * // this callback will be called asynchronously + * // when the response is available + * }, function errorCallback(response) { + * // called asynchronously if an error occurs + * // or server returns response with an error status. + * }); * ``` * - * Since the returned value of calling the $http function is a `promise`, you can also use - * the `then` method to register callbacks, and these callbacks will receive a single argument – - * an object representing the response. See the API signature and type info below for more - * details. + * The response object has these properties: * - * A response status code between 200 and 299 is considered a success status and - * will result in the success callback being called. Note that if the response is a redirect, - * XMLHttpRequest will transparently follow it, meaning that the error callback will not be - * called for such responses. + * - **data** – `{string|Object}` – The response body transformed with the transform + * functions. + * - **status** – `{number}` – HTTP status code of the response. + * - **headers** – `{function([headerName])}` – Header getter function. + * - **config** – `{Object}` – The configuration object that was used to generate the request. + * - **statusText** – `{string}` – HTTP status text of the response. + * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest (`complete`, `error`, `timeout` or `abort`). * - * # Writing Unit Tests that use $http - * When unit testing (using {@link ngMock ngMock}), it is necessary to call - * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending - * request using trained responses. + * A response status code between 200 and 299 is considered a success status and will result in + * the success callback being called. Any response status code outside of that range is + * considered an error status and will result in the error callback being called. + * Also, status codes less than -1 are normalized to zero. -1 usually means the request was + * aborted, e.g. using a `config.timeout`. + * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning + * that the outcome (success or error) will be determined by the final response status code. * - * ``` - * $httpBackend.expectGET(...); - * $http.get(...); - * $httpBackend.flush(); - * ``` * - * # Shortcut methods + * ## Shortcut methods * * Shortcut methods are also available. All shortcut methods require passing in the URL, and - * request data must be passed in for POST/PUT requests. + * request data must be passed in for POST/PUT requests. An optional config can be passed as the + * last argument. * * ```js - * $http.get('/someUrl').success(successCallback); - * $http.post('/someUrl', data).success(successCallback); + * $http.get('/someUrl', config).then(successCallback, errorCallback); + * $http.post('/someUrl', data, config).then(successCallback, errorCallback); * ``` * * Complete list of shortcut methods: @@ -7470,16 +11731,28 @@ * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} + * - {@link ng.$http#patch $http.patch} + * * + * ## Writing Unit Tests that use $http + * When unit testing (using {@link ngMock ngMock}), it is necessary to call + * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending + * request using trained responses. + * + * ``` + * $httpBackend.expectGET(...); + * $http.get(...); + * $httpBackend.flush(); + * ``` * - * # Setting HTTP Headers + * ## Setting HTTP Headers * * The $http service will automatically add certain HTTP headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): - * - `Accept: application/json, text/plain, * / *` + * - Accept: application/json, text/plain, \*/\* * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) @@ -7488,74 +11761,143 @@ * To add or overwrite these defaults, simply add or remove a property from these configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with the lowercased HTTP method name as the key, e.g. - * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. + * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`. * * The defaults can also be set at runtime via the `$http.defaults` object in the same * fashion. For example: * * ``` * module.run(function($http) { - * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' - * }); + * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'; + * }); * ``` * * In addition, you can supply a `headers` property in the config object passed when * calling `$http(config)`, which overrides the defaults without changing them globally. * + * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, + * Use the `headers` property, setting the desired header to `undefined`. For example: + * + * ```js + * var req = { + * method: 'POST', + * url: 'http://example.com', + * headers: { + * 'Content-Type': undefined + * }, + * data: { test: 'test' } + * } + * + * $http(req).then(function(){...}, function(){...}); + * ``` + * + * ## Transforming Requests and Responses + * + * Both requests and responses can be transformed using transformation functions: `transformRequest` + * and `transformResponse`. These properties can be a single function that returns + * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions, + * which allows you to `push` or `unshift` a new transformation function into the transformation chain. * - * # Transforming Requests and Responses + *
    + * **Note:** AngularJS does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline. + * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference). + * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest + * function will be reflected on the scope and in any templates where the object is data-bound. + * To prevent this, transform functions should have no side-effects. + * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return. + *
    + * + * ### Default Transformations + * + * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and + * `defaults.transformResponse` properties. If a request does not provide its own transformations + * then these will be applied. * - * Both requests and responses can be transformed using transform functions. By default, Angular - * applies these transformations: + * You can augment or replace the default transformations by modifying these properties by adding to or + * replacing the array. * - * Request transformations: + * AngularJS provides the following default transformations: + * + * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is + * an array with one function that does the following: * * - If the `data` property of the request configuration object contains an object, serialize it * into JSON format. * - * Response transformations: + * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is + * an array with one function that does the following: * * - If XSRF prefix is detected, strip it (see Security Considerations section below). - * - If JSON response is detected, deserialize it using a JSON parser. + * - If the `Content-Type` is `application/json` or the response looks like JSON, + * deserialize it using a JSON parser. + * * - * To globally augment or override the default transforms, modify the - * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse` - * properties. These properties are by default an array of transform functions, which allows you - * to `push` or `unshift` a new transformation function into the transformation chain. You can - * also decide to completely override any default transformations by assigning your - * transformation functions to these properties directly without the array wrapper. These defaults - * are again available on the $http factory at run-time, which may be useful if you have run-time - * services you wish to be involved in your transformations. + * ### Overriding the Default Transformations Per Request * - * Similarly, to locally override the request/response transforms, augment the - * `transformRequest` and/or `transformResponse` properties of the configuration object passed + * If you wish to override the request/response transformations only for a single request then provide + * `transformRequest` and/or `transformResponse` properties on the configuration object passed * into `$http`. * + * Note that if you provide these properties on the config object the default transformations will be + * overwritten. If you wish to augment the default transformations then you must include them in your + * local transformation array. + * + * The following code demonstrates adding a new response transformation to be run after the default response + * transformations have been run. + * + * ```js + * function appendTransform(defaults, transform) { + * + * // We can't guarantee that the default transformation is an array + * defaults = angular.isArray(defaults) ? defaults : [defaults]; + * + * // Append the new transformation to the defaults + * return defaults.concat(transform); + * } + * + * $http({ + * url: '...', + * method: 'GET', + * transformResponse: appendTransform($http.defaults.transformResponse, function(value) { + * return doTransform(value); + * }) + * }); + * ``` + * + * + * ## Caching + * + * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must + * set the config.cache value or the default cache value to TRUE or to a cache object (created + * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes + * precedence over the default cache value. * - * # Caching + * In order to: + * * cache all responses - set the default cache value to TRUE or to a cache object + * * cache a specific response - set config.cache value to TRUE or to a cache object * - * To enable caching, set the request configuration `cache` property to `true` (to use default - * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). - * When the cache is enabled, `$http` stores the response from the server in the specified - * cache. The next time the same request is made, the response is served from the cache without - * sending a request to the server. + * If caching is enabled, but neither the default cache nor config.cache are set to a cache object, + * then the default `$cacheFactory("$http")` object is used. * - * Note that even if the response is served from cache, delivery of the data is asynchronous in - * the same way that real requests are. + * The default cache value can be set by updating the + * {@link ng.$http#defaults `$http.defaults.cache`} property or the + * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property. * - * If there are multiple GET requests for the same URL that should be cached using the same - * cache, but the cache is not populated yet, only one request to the server will be made and - * the remaining requests will be fulfilled using the response from the first request. + * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using + * the relevant cache object. The next time the same request is made, the response is returned + * from the cache without sending a request to the server. * - * You can change the default cache to a new object (built with - * {@link ng.$cacheFactory `$cacheFactory`}) by updating the - * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set - * their `cache` property to `true` will now use this cache object. + * Take note that: * - * If you set the default cache to `false` then only requests that specify their own custom - * cache object will be cached. + * * Only GET and JSONP requests are cached. + * * The cache key is the request URL including search parameters; headers are not considered. + * * Cached responses are returned asynchronously, in the same way as responses from the server. + * * If multiple identical requests are made using the same cache, which is not yet populated, + * one request will be made to the server and remaining requests will return the same response. + * * A cache-control header on the response does not affect if or how responses are cached. * - * # Interceptors + * + * ## Interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. @@ -7573,14 +11915,14 @@ * * There are two kinds of interceptors (and two kinds of rejection interceptors): * - * * `request`: interceptors get called with http `config` object. The function is free to - * modify the `config` or create a new one. The function needs to return the `config` - * directly or as a promise. + * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to + * modify the `config` object or create a new one. The function needs to return the `config` + * object directly, or a promise containing the `config` or a new `config` object. * * `requestError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * `response`: interceptors get called with http `response` object. The function is free to - * modify the `response` or create a new one. The function needs to return the `response` - * directly or as a promise. + * modify the `response` object or create a new one. The function needs to return the `response` + * object directly, or as a promise containing the `response` or a new `response` object. * * `responseError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * @@ -7588,121 +11930,76 @@ * ```js * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { - * return { - * // optional method - * 'request': function(config) { - * // do something on success - * return config || $q.when(config); - * }, - * - * // optional method - * 'requestError': function(rejection) { - * // do something on error - * if (canRecover(rejection)) { - * return responseOrNewPromise - * } - * return $q.reject(rejection); - * }, - * - * - * - * // optional method - * 'response': function(response) { - * // do something on success - * return response || $q.when(response); - * }, - * - * // optional method - * 'responseError': function(rejection) { - * // do something on error - * if (canRecover(rejection)) { - * return responseOrNewPromise - * } - * return $q.reject(rejection); - * } - * }; - * }); + * return { + * // optional method + * 'request': function(config) { + * // do something on success + * return config; + * }, + * + * // optional method + * 'requestError': function(rejection) { + * // do something on error + * if (canRecover(rejection)) { + * return responseOrNewPromise + * } + * return $q.reject(rejection); + * }, + * + * + * + * // optional method + * 'response': function(response) { + * // do something on success + * return response; + * }, + * + * // optional method + * 'responseError': function(rejection) { + * // do something on error + * if (canRecover(rejection)) { + * return responseOrNewPromise + * } + * return $q.reject(rejection); + * } + * }; + * }); * * $httpProvider.interceptors.push('myHttpInterceptor'); * * * // alternatively, register the interceptor via an anonymous factory * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { - * return { - * 'request': function(config) { - * // same as above - * }, - * - * 'response': function(response) { - * // same as above - * } - * }; - * }); + * return { + * 'request': function(config) { + * // same as above + * }, + * + * 'response': function(response) { + * // same as above + * } + * }; + * }); * ``` * - * # Response interceptors (DEPRECATED) + * ## Security Considerations * - * Before you start creating interceptors, be sure to understand the - * {@link ng.$q $q and deferred/promise APIs}. + * When designing web applications, consider security threats from: * - * For purposes of global error handling, authentication or any kind of synchronous or - * asynchronous preprocessing of received responses, it is desirable to be able to intercept - * responses for http requests before they are handed over to the application code that - * initiated these requests. The response interceptors leverage the {@link ng.$q - * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. + * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) + * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) * - * The interceptors are service factories that are registered with the $httpProvider by - * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and - * injected with dependencies (if specified) and returns the interceptor — a function that - * takes a {@link ng.$q promise} and returns the original or a new promise. + * Both server and the client must cooperate in order to eliminate these threats. AngularJS comes + * pre-configured with strategies that address these issues, but for this to work backend server + * cooperation is required. * - * ```js - * // register the interceptor as a service - * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { - * return function(promise) { - * return promise.then(function(response) { - * // do something on success - * return response; - * }, function(response) { - * // do something on error - * if (canRecover(response)) { - * return responseOrNewPromise - * } - * return $q.reject(response); - * }); - * } - * }); - * - * $httpProvider.responseInterceptors.push('myHttpInterceptor'); - * - * - * // register the interceptor via an anonymous factory - * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { - * return function(promise) { - * // same as above - * } - * }); - * ``` - * - * - * # Security Considerations - * - * When designing web applications, consider security threats from: - * - * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) - * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) - * - * Both server and the client must cooperate in order to eliminate these threats. Angular comes - * pre-configured with strategies that address these issues, but for this to work backend server - * cooperation is required. - * - * ## JSON Vulnerability Protection + * ### JSON Vulnerability Protection * * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * allows third party website to turn your JSON resource URL into * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. - * Angular will automatically strip the prefix before processing it as JSON. + * AngularJS will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * ```js @@ -7715,18 +12012,18 @@ * ['one','two'] * ``` * - * Angular will strip the prefix, before processing the JSON. + * AngularJS will strip the prefix, before processing the JSON. * * - * ## Cross Site Request Forgery (XSRF) Protection + * ### Cross Site Request Forgery (XSRF) Protection * - * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which - * an unauthorized site can gain your user's private data. Angular provides a mechanism - * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie - * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only - * JavaScript that runs on your domain could read the cookie, your server can be assured that - * the XHR came from JavaScript running on your domain. The header will not be set for - * cross-domain requests. + * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by + * which the attacker can trick an authenticated user into unknowingly executing actions on your + * website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the + * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP + * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the + * cookie, your server can be assured that the XHR came from JavaScript running on your domain. + * The header will not be set for cross-domain requests. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the @@ -7734,85 +12031,92 @@ * that only JavaScript running on your domain could have sent the request. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript from * making up its own tokens). We recommend that the token is a digest of your site's - * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) + * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) * for added security. * * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, * or the per-request config object. * + * In order to prevent collisions in environments where multiple AngularJS apps share the + * same domain or subdomain, we recommend that each application uses unique cookie name. * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) - * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. - * - **params** – `{Object.}` – Map of strings or objects which will be turned - * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be - * JSONified. + * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * - **params** – `{Object.}` – Map of strings or objects which will be serialized + * with the `paramSerializer` and appended as GET parameters. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings or functions which return strings representing * HTTP headers to send to the server. If the return value of a function is null, the - * header will not be sent. + * header will not be sent. Functions accept a config object as an argument. + * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object. + * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`. + * The handler will be called in the context of a `$apply` block. + * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload + * object. To bind events to the XMLHttpRequest object, use `eventHandlers`. + * The handler will be called in the context of a `$apply` block. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – * `{function(data, headersGetter)|Array.}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. + * See {@link ng.$http#overriding-the-default-transformations-per-request + * Overriding the Default Transformations} * - **transformResponse** – - * `{function(data, headersGetter)|Array.}` – + * `{function(data, headersGetter, status)|Array.}` – * transform function or an array of such functions. The transform function takes the http - * response body and headers and returns its transformed (typically deserialized) version. - * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the - * GET request, otherwise if a cache instance built with - * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for - * caching. + * response body, headers and status and returns its transformed (typically deserialized) version. + * See {@link ng.$http#overriding-the-default-transformations-per-request + * Overriding the Default Transformations} + * - **paramSerializer** - `{string|function(Object):string}` - A function used to + * prepare the string representation of request parameters (specified as an object). + * If specified as string, it is interpreted as function registered with the + * {@link $injector $injector}, which means you can create your own serializer + * by registering it as a {@link auto.$provide#service service}. + * The default serializer is the {@link $httpParamSerializer $httpParamSerializer}; + * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike} + * - **cache** – `{boolean|Object}` – A boolean value or object created with + * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response. + * See {@link $http#caching $http Caching} for more information. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} * that should abort the request when resolved. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the - * XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 + * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) * for more information. * - **responseType** - `{string}` - see - * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). + * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype). * - * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the - * standard `then` method and two http specific methods: `success` and `error`. The `then` - * method takes two arguments a success and an error callback which will be called with a - * response object. The `success` and `error` methods take a single argument - a function that - * will be called when the request succeeds or fails respectively. The arguments passed into - * these functions are destructured representation of the response object passed into the - * `then` method. The response object has these properties: + * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object + * when the request succeeds or fails. * - * - **data** – `{string|Object}` – The response body transformed with the transform - * functions. - * - **status** – `{number}` – HTTP status code of the response. - * - **headers** – `{function([headerName])}` – Header getter function. - * - **config** – `{Object}` – The configuration object that was used to generate the request. - * - **statusText** – `{string}` – HTTP status text of the response. * * @property {Array.} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example - + -
    - - +
    http status code: {{status}}
    @@ -7820,30 +12124,38 @@
    - function FetchCtrl($scope, $http, $templateCache) { - $scope.method = 'GET'; - $scope.url = 'http-hello.html'; - - $scope.fetch = function() { - $scope.code = null; - $scope.response = null; - - $http({method: $scope.method, url: $scope.url, cache: $templateCache}). - success(function(data, status) { - $scope.status = status; - $scope.data = data; - }). - error(function(data, status) { - $scope.data = data || "Request failed"; - $scope.status = status; - }); - }; + angular.module('httpExample', []) + .config(['$sceDelegateProvider', function($sceDelegateProvider) { + // We must whitelist the JSONP endpoint that we are using to show that we trust it + $sceDelegateProvider.resourceUrlWhitelist([ + 'self', + 'https://angularjs.org/**' + ]); + }]) + .controller('FetchController', ['$scope', '$http', '$templateCache', + function($scope, $http, $templateCache) { + $scope.method = 'GET'; + $scope.url = 'http-hello.html'; + + $scope.fetch = function() { + $scope.code = null; + $scope.response = null; + + $http({method: $scope.method, url: $scope.url, cache: $templateCache}). + then(function(response) { + $scope.status = response.status; + $scope.data = response.data; + }, function(response) { + $scope.data = response.data || 'Request failed'; + $scope.status = response.status; + }); + }; - $scope.updateModel = function(method, url) { - $scope.method = method; - $scope.url = url; - }; - } + $scope.updateModel = function(method, url) { + $scope.method = method; + $scope.url = url; + }; + }]); Hello, $http! @@ -7853,7 +12165,6 @@ var data = element(by.binding('data')); var fetchBtn = element(by.id('fetchbtn')); var sampleGetBtn = element(by.id('samplegetbtn')); - var sampleJsonpBtn = element(by.id('samplejsonpbtn')); var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); it('should make an xhr GET request', function() { @@ -7863,12 +12174,14 @@ expect(data.getText()).toMatch(/Hello, \$http!/); }); - it('should make a JSONP request to angularjs.org', function() { - sampleJsonpBtn.click(); - fetchBtn.click(); - expect(status.getText()).toMatch('200'); - expect(data.getText()).toMatch(/Super Hero!/); - }); + // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 + // it('should make a JSONP request to angularjs.org', function() { +// var sampleJsonpBtn = element(by.id('samplejsonpbtn')); +// sampleJsonpBtn.click(); +// fetchBtn.click(); +// expect(status.getText()).toMatch('200'); +// expect(data.getText()).toMatch(/Super Hero!/); +// }); it('should make JSONP request to invalid URL and invoke the error handler', function() { @@ -7881,90 +12194,84 @@
    */ function $http(requestConfig) { - var config = { - method: 'get', - transformRequest: defaults.transformRequest, - transformResponse: defaults.transformResponse - }; - var headers = mergeHeaders(requestConfig); - - extend(config, requestConfig); - config.headers = headers; - config.method = uppercase(config.method); - var xsrfValue = urlIsSameOrigin(config.url) - ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] - : undefined; - if (xsrfValue) { - headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; + if (!isObject(requestConfig)) { + throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig); } + if (!isString($sce.valueOf(requestConfig.url))) { + throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url); + } - var serverRequest = function(config) { - headers = config.headers; - var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); - - // strip content-type if data is undefined - if (isUndefined(config.data)) { - forEach(headers, function(value, header) { - if (lowercase(header) === 'content-type') { - delete headers[header]; - } - }); - } + var config = extend({ + method: 'get', + transformRequest: defaults.transformRequest, + transformResponse: defaults.transformResponse, + paramSerializer: defaults.paramSerializer, + jsonpCallbackParam: defaults.jsonpCallbackParam + }, requestConfig); - if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { - config.withCredentials = defaults.withCredentials; - } + config.headers = mergeHeaders(requestConfig); + config.method = uppercase(config.method); + config.paramSerializer = isString(config.paramSerializer) ? + $injector.get(config.paramSerializer) : config.paramSerializer; - // send request - return sendReq(config, reqData, headers).then(transformResponse, transformResponse); - }; + $browser.$$incOutstandingRequestCount(); - var chain = [serverRequest, undefined]; - var promise = $q.when(config); + var requestInterceptors = []; + var responseInterceptors = []; + var promise = $q.resolve(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { - chain.unshift(interceptor.request, interceptor.requestError); + requestInterceptors.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { - chain.push(interceptor.response, interceptor.responseError); + responseInterceptors.push(interceptor.response, interceptor.responseError); } }); - while(chain.length) { - var thenFn = chain.shift(); - var rejectFn = chain.shift(); + promise = chainInterceptors(promise, requestInterceptors); + promise = promise.then(serverRequest); + promise = chainInterceptors(promise, responseInterceptors); + promise = promise.finally(completeOutstandingRequest); - promise = promise.then(thenFn, rejectFn); - } + return promise; - promise.success = function(fn) { - promise.then(function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; - promise.error = function(fn) { - promise.then(null, function(response) { - fn(response.data, response.status, response.headers, config); - }); + function chainInterceptors(promise, interceptors) { + for (var i = 0, ii = interceptors.length; i < ii;) { + var thenFn = interceptors[i++]; + var rejectFn = interceptors[i++]; + + promise = promise.then(thenFn, rejectFn); + } + + interceptors.length = 0; + return promise; - }; + } - return promise; + function completeOutstandingRequest() { + $browser.$$completeOutstandingRequest(noop); + } - function transformResponse(response) { - // make a copy since the response must be cacheable - var resp = extend({}, response, { - data: transformData(response.data, response.headers, config.transformResponse) + function executeHeaderFns(headers, config) { + var headerContent, processedHeaders = {}; + + forEach(headers, function(headerFn, header) { + if (isFunction(headerFn)) { + headerContent = headerFn(config); + if (headerContent != null) { + processedHeaders[header] = headerContent; + } + } else { + processedHeaders[header] = headerFn; + } }); - return (isSuccess(response.status)) - ? resp - : $q.reject(resp); + + return processedHeaders; } function mergeHeaders(config) { @@ -7974,11 +12281,7 @@ defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); - // execute if header value is function - execHeaders(defHeaders); - execHeaders(reqHeaders); - - // using for-in instead of forEach to avoid unecessary iteration after header has been found + // using for-in instead of forEach to avoid unnecessary iteration after header has been found defaultHeadersIteration: for (defHeaderName in defHeaders) { lowercaseDefHeaderName = lowercase(defHeaderName); @@ -7992,22 +12295,39 @@ reqHeaders[defHeaderName] = defHeaders[defHeaderName]; } - return reqHeaders; + // execute if header value is a function for merged headers + return executeHeaderFns(reqHeaders, shallowCopy(config)); + } - function execHeaders(headers) { - var headerContent; + function serverRequest(config) { + var headers = config.headers; + var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest); - forEach(headers, function(headerFn, header) { - if (isFunction(headerFn)) { - headerContent = headerFn(); - if (headerContent != null) { - headers[header] = headerContent; - } else { - delete headers[header]; - } + // strip content-type if data is undefined + if (isUndefined(reqData)) { + forEach(headers, function(value, header) { + if (lowercase(header) === 'content-type') { + delete headers[header]; } }); } + + if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { + config.withCredentials = defaults.withCredentials; + } + + // send request + return sendReq(config, reqData).then(transformResponse, transformResponse); + } + + function transformResponse(response) { + // make a copy since the response must be cacheable + var resp = extend({}, response); + resp.data = transformData(response.data, response.headers, response.status, + config.transformResponse); + return (isSuccess(response.status)) + ? resp + : $q.reject(resp); } } @@ -8020,8 +12340,9 @@ * @description * Shortcut method to perform `GET` request. * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object + * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage * @returns {HttpPromise} Future object */ @@ -8032,8 +12353,9 @@ * @description * Shortcut method to perform `DELETE` request. * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object + * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage * @returns {HttpPromise} Future object */ @@ -8044,8 +12366,9 @@ * @description * Shortcut method to perform `HEAD` request. * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object + * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage * @returns {HttpPromise} Future object */ @@ -8056,9 +12379,38 @@ * @description * Shortcut method to perform `JSONP` request. * - * @param {string} url Relative or absolute URL specifying the destination of the request. - * Should contain `JSON_CALLBACK` string. - * @param {Object=} config Optional configuration object + * Note that, since JSONP requests are sensitive because the response is given full access to the browser, + * the url must be declared, via {@link $sce} as a trusted resource URL. + * You can trust a URL by adding it to the whitelist via + * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or + * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}. + * + * You should avoid generating the URL for the JSONP request from user provided data. + * Provide additional query parameters via `params` property of the `config` parameter, rather than + * modifying the URL itself. + * + * JSONP requests must specify a callback to be used in the response from the server. This callback + * is passed as a query parameter in the request. You must specify the name of this parameter by + * setting the `jsonpCallbackParam` property on the request config object. + * + * ``` + * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'}) + * ``` + * + * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`. + * Initially this is set to `'callback'`. + * + *
    + * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback + * parameter value should go. + *
    + * + * If you would like to customise where and how the callbacks are stored then try overriding + * or decorating the {@link $jsonpCallbacks} service. + * + * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); @@ -8072,7 +12424,7 @@ * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content - * @param {Object=} config Optional configuration object + * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage * @returns {HttpPromise} Future object */ @@ -8085,10 +12437,23 @@ * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content - * @param {Object=} config Optional configuration object + * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#patch + * + * @description + * Shortcut method to perform `PATCH` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage * @returns {HttpPromise} Future object */ - createShortMethodsWithData('post', 'put'); + createShortMethodsWithData('post', 'put', 'patch'); /** * @ngdoc property @@ -8109,7 +12474,7 @@ function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { - return $http(extend(config || {}, { + return $http(extend({}, config || {}, { method: name, url: url })); @@ -8121,7 +12486,7 @@ function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { - return $http(extend(config || {}, { + return $http(extend({}, config || {}, { method: name, url: url, data: data @@ -8137,36 +12502,54 @@ * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ - function sendReq(config, reqData, reqHeaders) { + function sendReq(config, reqData) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, - url = buildUrl(config.url, config.params); + reqHeaders = config.headers, + isJsonp = lowercase(config.method) === 'jsonp', + url = config.url; + + if (isJsonp) { + // JSONP is a pretty sensitive operation where we're allowing a script to have full access to + // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL. + url = $sce.getTrustedResourceUrl(url); + } else if (!isString(url)) { + // If it is not a string then the URL must be a $sce trusted object + url = $sce.valueOf(url); + } + + url = buildUrl(url, config.paramSerializer(config.params)); + + if (isJsonp) { + // Check the url and add the JSONP callback placeholder + url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam); + } $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); - - if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') { + if ((config.cache || defaults.cache) && config.cache !== false && + (config.method === 'GET' || config.method === 'JSONP')) { cache = isObject(config.cache) ? config.cache - : isObject(defaults.cache) ? defaults.cache - : defaultCache; + : isObject(/** @type {?} */ (defaults).cache) + ? /** @type {?} */ (defaults).cache + : defaultCache; } if (cache) { cachedResp = cache.get(url); if (isDefined(cachedResp)) { - if (cachedResp.then) { + if (isPromiseLike(cachedResp)) { // cached request has already been sent, but there is no response yet - cachedResp.then(removePendingReq, removePendingReq); - return cachedResp; + cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult); } else { // serving from cache if (isArray(cachedResp)) { - resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]), cachedResp[3]); + resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]); } else { - resolvePromise(cachedResp, 200, {}, 'OK'); + resolvePromise(cachedResp, 200, {}, 'OK', 'complete'); } } } else { @@ -8175,14 +12558,47 @@ } } - // if we won't have the response in cache, send the request to the backend + + // if we won't have the response in cache, set the xsrf headers and + // send the request to the backend if (isUndefined(cachedResp)) { + var xsrfValue = urlIsSameOrigin(config.url) + ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName] + : undefined; + if (xsrfValue) { + reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; + } + $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, - config.withCredentials, config.responseType); + config.withCredentials, config.responseType, + createApplyHandlers(config.eventHandlers), + createApplyHandlers(config.uploadEventHandlers)); } return promise; + function createApplyHandlers(eventHandlers) { + if (eventHandlers) { + var applyHandlers = {}; + forEach(eventHandlers, function(eventHandler, key) { + applyHandlers[key] = function(event) { + if (useApplyAsync) { + $rootScope.$applyAsync(callEventHandler); + } else if ($rootScope.$$phase) { + callEventHandler(); + } else { + $rootScope.$apply(callEventHandler); + } + + function callEventHandler() { + eventHandler(event); + } + }; + }); + return applyHandlers; + } + } + /** * Callback registered to $httpBackend(): @@ -8190,89 +12606,127 @@ * - resolves the raw $http promise * - calls $apply */ - function done(status, response, headersString, statusText) { + function done(status, response, headersString, statusText, xhrStatus) { if (cache) { if (isSuccess(status)) { - cache.put(url, [status, response, parseHeaders(headersString), statusText]); + cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]); } else { // remove promise from the cache cache.remove(url); } } - resolvePromise(response, status, headersString, statusText); - if (!$rootScope.$$phase) $rootScope.$apply(); + function resolveHttpPromise() { + resolvePromise(response, status, headersString, statusText, xhrStatus); + } + + if (useApplyAsync) { + $rootScope.$applyAsync(resolveHttpPromise); + } else { + resolveHttpPromise(); + if (!$rootScope.$$phase) $rootScope.$apply(); + } } /** * Resolves the raw $http promise. */ - function resolvePromise(response, status, headers, statusText) { - // normalize internal statuses to 0 - status = Math.max(status, 0); + function resolvePromise(response, status, headers, statusText, xhrStatus) { + //status: HTTP response status code, 0, -1 (aborted by timeout / promise) + status = status >= -1 ? status : 0; (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config, - statusText : statusText + statusText: statusText, + xhrStatus: xhrStatus }); } + function resolvePromiseWithResult(result) { + resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus); + } function removePendingReq() { - var idx = indexOf($http.pendingRequests, config); + var idx = $http.pendingRequests.indexOf(config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } - function buildUrl(url, params) { - if (!params) return url; - var parts = []; - forEachSorted(params, function(value, key) { - if (value === null || isUndefined(value)) return; - if (!isArray(value)) value = [value]; - - forEach(value, function(v) { - if (isObject(v)) { - v = toJson(v); - } - parts.push(encodeUriQuery(key) + '=' + - encodeUriQuery(v)); - }); - }); - if(parts.length > 0) { - url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); + function buildUrl(url, serializedParams) { + if (serializedParams.length > 0) { + url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams; } return url; } + function sanitizeJsonpCallbackParam(url, cbKey) { + var parts = url.split('?'); + if (parts.length > 2) { + // Throw if the url contains more than one `?` query indicator + throw $httpMinErr('badjsonp', 'Illegal use more than one "?", in url, "{1}"', url); + } + var params = parseKeyValue(parts[1]); + forEach(params, function(value, key) { + if (value === 'JSON_CALLBACK') { + // Throw if the url already contains a reference to JSON_CALLBACK + throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url); + } + if (key === cbKey) { + // Throw if the callback param was already provided + throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', cbKey, url); + } + }); + + // Add in the JSON_CALLBACK callback param value + url += ((url.indexOf('?') === -1) ? '?' : '&') + cbKey + '=JSON_CALLBACK'; + return url; + } }]; } - function createXhr(method) { - //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest - //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest - //if it is available - if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) || - !window.XMLHttpRequest)) { - return new window.ActiveXObject("Microsoft.XMLHTTP"); - } else if (window.XMLHttpRequest) { - return new window.XMLHttpRequest(); - } - - throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest."); + /** + * @ngdoc service + * @name $xhrFactory + * @this + * + * @description + * Factory function used to create XMLHttpRequest objects. + * + * Replace or decorate this service to create your own custom XMLHttpRequest objects. + * + * ``` + * angular.module('myApp', []) + * .factory('$xhrFactory', function() { + * return function createXhr(method, url) { + * return new window.XMLHttpRequest({mozSystem: true}); + * }; + * }); + * ``` + * + * @param {string} method HTTP method of the request (GET, POST, PUT, ..) + * @param {string} url URL of the request. + */ + function $xhrFactoryProvider() { + this.$get = function() { + return function createXhr() { + return new window.XMLHttpRequest(); + }; + }; } /** * @ngdoc service * @name $httpBackend - * @requires $window + * @requires $jsonpCallbacks * @requires $document + * @requires $xhrFactory + * @this * * @description * HTTP backend used by the {@link ng.$http service} that delegates to @@ -8285,38 +12739,27 @@ * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { - this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { - return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); + this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) { + return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]); }]; } function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { - var ABORTED = -1; - // TODO(vojta): fix the signature - return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { - var status; - $browser.$$incOutstandingRequestCount(); + return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) { url = url || $browser.url(); - if (lowercase(method) == 'jsonp') { - var callbackId = '_' + (callbacks.counter++).toString(36); - callbacks[callbackId] = function(data) { - callbacks[callbackId].data = data; - }; - - var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), - function() { - if (callbacks[callbackId].data) { - completeRequest(callback, 200, callbacks[callbackId].data); - } else { - completeRequest(callback, status || -2); - } - callbacks[callbackId] = angular.noop; - }); + if (lowercase(method) === 'jsonp') { + var callbackPath = callbacks.createCallback(url); + var jsonpDone = jsonpReq(url, callbackPath, function(status, text) { + // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING) + var response = (status === 200) && callbacks.getResponse(callbackPath); + completeRequest(callback, status, response, '', text, 'complete'); + callbacks.removeCallback(callbackPath); + }); } else { - var xhr = createXhr(method); + var xhr = createXhr(method, url); xhr.open(method, url, true); forEach(headers, function(value, key) { @@ -8325,37 +12768,59 @@ } }); - // In IE6 and 7, this might be called synchronously when xhr.send below is called and the - // response is in the cache. the promise api will ensure that to the app code the api is - // always async - xhr.onreadystatechange = function() { - // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by - // xhrs that are resolved while the app is in the background (see #5426). - // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before - // continuing - // - // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and - // Safari respectively. - if (xhr && xhr.readyState == 4) { - var responseHeaders = null, - response = null; - - if(status !== ABORTED) { - responseHeaders = xhr.getAllResponseHeaders(); - - // responseText is the old-school way of retrieving response (supported by IE8 & 9) - // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) - response = ('response' in xhr) ? xhr.response : xhr.responseText; - } + xhr.onload = function requestLoaded() { + var statusText = xhr.statusText || ''; - completeRequest(callback, - status || xhr.status, - response, - responseHeaders, - xhr.statusText || ''); + // responseText is the old-school way of retrieving response (supported by IE9) + // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) + var response = ('response' in xhr) ? xhr.response : xhr.responseText; + + // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) + var status = xhr.status === 1223 ? 204 : xhr.status; + + // fix status code when it is 0 (0 status is undocumented). + // Occurs when accessing file resources or on Android 4.1 stock browser + // while retrieving files from application cache. + if (status === 0) { + status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0; } + + completeRequest(callback, + status, + response, + xhr.getAllResponseHeaders(), + statusText, + 'complete'); + }; + + var requestError = function() { + // The response is always empty + // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error + completeRequest(callback, -1, null, null, '', 'error'); + }; + + var requestAborted = function() { + completeRequest(callback, -1, null, null, '', 'abort'); + }; + + var requestTimeout = function() { + // The response is always empty + // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error + completeRequest(callback, -1, null, null, '', 'timeout'); }; + xhr.onerror = requestError; + xhr.onabort = requestAborted; + xhr.ontimeout = requestTimeout; + + forEach(eventHandlers, function(value, key) { + xhr.addEventListener(key, value); + }); + + forEach(uploadEventHandlers, function(value, key) { + xhr.upload.addEventListener(key, value); + }); + if (withCredentials) { xhr.withCredentials = true; } @@ -8377,87 +12842,105 @@ } } - xhr.send(post || null); + xhr.send(isUndefined(post) ? null : post); } if (timeout > 0) { var timeoutId = $browserDefer(timeoutRequest, timeout); - } else if (timeout && timeout.then) { + } else if (isPromiseLike(timeout)) { timeout.then(timeoutRequest); } function timeoutRequest() { - status = ABORTED; - jsonpDone && jsonpDone(); - xhr && xhr.abort(); + if (jsonpDone) { + jsonpDone(); + } + if (xhr) { + xhr.abort(); + } } - function completeRequest(callback, status, response, headersString, statusText) { + function completeRequest(callback, status, response, headersString, statusText, xhrStatus) { // cancel timeout and subsequent timeout promise resolution - timeoutId && $browserDefer.cancel(timeoutId); - jsonpDone = xhr = null; - - // fix status code when it is 0 (0 status is undocumented). - // Occurs when accessing file resources or on Android 4.1 stock browser - // while retrieving files from application cache. - if (status === 0) { - status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0; + if (isDefined(timeoutId)) { + $browserDefer.cancel(timeoutId); } + jsonpDone = xhr = null; - // normalize IE bug (http://bugs.jquery.com/ticket/1450) - status = status === 1223 ? 204 : status; - statusText = statusText || ''; - - callback(status, response, headersString, statusText); - $browser.$$completeOutstandingRequest(noop); + callback(status, response, headersString, statusText, xhrStatus); } }; - function jsonpReq(url, done) { - // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: + function jsonpReq(url, callbackPath, done) { + url = url.replace('JSON_CALLBACK', callbackPath); + // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document - var script = rawDocument.createElement('script'), - doneWrapper = function() { - script.onreadystatechange = script.onload = script.onerror = null; - rawDocument.body.removeChild(script); - if (done) done(); - }; - + var script = rawDocument.createElement('script'), callback = null; script.type = 'text/javascript'; script.src = url; - - if (msie && msie <= 8) { - script.onreadystatechange = function() { - if (/loaded|complete/.test(script.readyState)) { - doneWrapper(); + script.async = true; + + callback = function(event) { + script.removeEventListener('load', callback); + script.removeEventListener('error', callback); + rawDocument.body.removeChild(script); + script = null; + var status = -1; + var text = 'unknown'; + + if (event) { + if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) { + event = { type: 'error' }; } - }; - } else { - script.onload = script.onerror = function() { - doneWrapper(); - }; - } + text = event.type; + status = event.type === 'error' ? 404 : 200; + } + if (done) { + done(status, text); + } + }; + + script.addEventListener('load', callback); + script.addEventListener('error', callback); rawDocument.body.appendChild(script); - return doneWrapper; + return callback; } } - var $interpolateMinErr = minErr('$interpolate'); + var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate'); + $interpolateMinErr.throwNoconcat = function(text) { + throw $interpolateMinErr('noconcat', + 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' + + 'interpolations that concatenate multiple expressions when a trusted value is ' + + 'required. See http://docs.angularjs.org/api/ng.$sce', text); + }; + + $interpolateMinErr.interr = function(text, err) { + return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString()); + }; /** * @ngdoc provider * @name $interpolateProvider - * @function + * @this * * @description * * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. * + *
    + * This feature is sometimes used to mix different markup languages, e.g. to wrap an AngularJS + * template within a Python Jinja template (or any other template language). Mixing templating + * languages is **very dangerous**. The embedding template language will not safely escape AngularJS + * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS) + * security bugs! + *
    + * * @example - + -
    +
    //demo.label//
    @@ -8492,11 +12975,11 @@ * @name $interpolateProvider#startSymbol * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. - * - * @param {string=} value new value to set the starting symbol to. + * + * @param {string=} value new value to set the starting symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ - this.startSymbol = function(value){ + this.startSymbol = function(value) { if (value) { startSymbol = value; return this; @@ -8514,7 +12997,7 @@ * @param {string=} value new value to set the ending symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ - this.endSymbol = function(value){ + this.endSymbol = function(value) { if (value) { endSymbol = value; return this; @@ -8526,12 +13009,32 @@ this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { var startSymbolLength = startSymbol.length, - endSymbolLength = endSymbol.length; + endSymbolLength = endSymbol.length, + escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'), + escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g'); + + function escape(ch) { + return '\\\\\\' + ch; + } + + function unescapeText(text) { + return text.replace(escapedStartRegexp, startSymbol). + replace(escapedEndRegexp, endSymbol); + } + + // TODO: this is the same as the constantWatchDelegate in parse.js + function constantWatchDelegate(scope, listener, objectEquality, constantInterp) { + var unwatch = scope.$watch(function constantInterpolateWatch(scope) { + unwatch(); + return constantInterp(scope); + }, listener, objectEquality); + return unwatch; + } /** * @ngdoc service * @name $interpolate - * @function + * @kind function * * @requires $parse * @requires $sce @@ -8547,9 +13050,89 @@ * ```js * var $interpolate = ...; // injected * var exp = $interpolate('Hello {{name | uppercase}}!'); - * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); + * expect(exp({name:'AngularJS'})).toEqual('Hello ANGULAR!'); + * ``` + * + * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is + * `true`, the interpolation function will return `undefined` unless all embedded expressions + * evaluate to a value other than `undefined`. + * + * ```js + * var $interpolate = ...; // injected + * var context = {greeting: 'Hello', name: undefined }; + * + * // default "forgiving" mode + * var exp = $interpolate('{{greeting}} {{name}}!'); + * expect(exp(context)).toEqual('Hello !'); + * + * // "allOrNothing" mode + * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); + * expect(exp(context)).toBeUndefined(); + * context.name = 'AngularJS'; + * expect(exp(context)).toEqual('Hello AngularJS!'); + * ``` + * + * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. + * + * #### Escaped Interpolation + * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers + * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). + * It will be rendered as a regular start/end marker, and will not be interpreted as an expression + * or binding. + * + * This enables web-servers to prevent script injection attacks and defacing attacks, to some + * degree, while also enabling code examples to work without relying on the + * {@link ng.directive:ngNonBindable ngNonBindable} directive. + * + * **For security purposes, it is strongly encouraged that web servers escape user-supplied data, + * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all + * interpolation start/end markers with their escaped counterparts.** + * + * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered + * output when the $interpolate service processes the text. So, for HTML elements interpolated + * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter + * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such, + * this is typically useful only when user-data is used in rendering a template from the server, or + * when otherwise untrusted data is used by a directive. + * + * + * + *
    + *

    {{apptitle}}: \{\{ username = "defaced value"; \}\} + *

    + *

    {{username}} attempts to inject code which will deface the + * application, but fails to accomplish their task, because the server has correctly + * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash) + * characters.

    + *

    Instead, the result of the attempted script injection is visible, and can be removed + * from the database by an administrator.

    + *
    + *
    + *
    + * + * @knownIssue + * It is currently not possible for an interpolated expression to contain the interpolation end + * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e. + * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string. + * + * @knownIssue + * All directives and components must use the standard `{{` `}}` interpolation symbols + * in their templates. If you change the application interpolation symbols the {@link $compile} + * service will attempt to denormalize the standard symbols to the custom symbols. + * The denormalization process is not clever enough to know not to replace instances of the standard + * symbols where they would not normally be treated as interpolation symbols. For example in the following + * code snippet the closing braces of the literal object will get incorrectly denormalized: + * + * ``` + *
    * ``` * + * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information. * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have @@ -8559,43 +13142,57 @@ * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that * provides Strict Contextual Escaping for details. + * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined + * unless all embedded expressions evaluate to a value other than `undefined`. * @returns {function(context)} an interpolation function which is used to compute the * interpolated string. The function has these parameters: * - * * `context`: an object against which any expressions embedded in the strings are evaluated - * against. - * + * - `context`: evaluation context for all expressions embedded in the interpolated text */ - function $interpolate(text, mustHaveExpression, trustedContext) { + function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { + // Provide a quick exit and simplified result function for text with no interpolation + if (!text.length || text.indexOf(startSymbol) === -1) { + var constantInterp; + if (!mustHaveExpression) { + var unescapedText = unescapeText(text); + constantInterp = valueFn(unescapedText); + constantInterp.exp = text; + constantInterp.expressions = []; + constantInterp.$$watchDelegate = constantWatchDelegate; + } + return constantInterp; + } + + allOrNothing = !!allOrNothing; var startIndex, endIndex, index = 0, - parts = [], - length = text.length, - hasInterpolation = false, - fn, + expressions = [], + parseFns = [], + textLength = text.length, exp, - concat = []; - - while(index < length) { - if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && - ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { - (index != startIndex) && parts.push(text.substring(index, startIndex)); - parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); - fn.exp = exp; + concat = [], + expressionPositions = []; + + while (index < textLength) { + if (((startIndex = text.indexOf(startSymbol, index)) !== -1) && + ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) { + if (index !== startIndex) { + concat.push(unescapeText(text.substring(index, startIndex))); + } + exp = text.substring(startIndex + startSymbolLength, endIndex); + expressions.push(exp); + parseFns.push($parse(exp, parseStringifyInterceptor)); index = endIndex + endSymbolLength; - hasInterpolation = true; + expressionPositions.push(concat.length); + concat.push(''); } else { - // we did not find anything, so we have to add the remainder to the parts array - (index != length) && parts.push(text.substring(index)); - index = length; - } - } - - if (!(length = parts.length)) { - // we added, nothing, must have been an empty string. - parts.push(''); - length = 1; + // we did not find an interpolation, so we have to add the remainder to the separators array + if (index !== textLength) { + concat.push(unescapeText(text.substring(index))); + } + break; + } } // Concatenating expressions makes it hard to reason about whether some combination of @@ -8604,44 +13201,62 @@ // that's used is assigned or constructed by some JS code somewhere that is more testable or // make it obvious that you bound the value to some user controlled value. This helps reduce // the load when auditing for XSS issues. - if (trustedContext && parts.length > 1) { - throw $interpolateMinErr('noconcat', - "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + - "interpolations that concatenate multiple expressions when a trusted value is " + - "required. See http://docs.angularjs.org/api/ng.$sce", text); + if (trustedContext && concat.length > 1) { + $interpolateMinErr.throwNoconcat(text); } - if (!mustHaveExpression || hasInterpolation) { - concat.length = length; - fn = function(context) { + if (!mustHaveExpression || expressions.length) { + var compute = function(values) { + for (var i = 0, ii = expressions.length; i < ii; i++) { + if (allOrNothing && isUndefined(values[i])) return; + concat[expressionPositions[i]] = values[i]; + } + return concat.join(''); + }; + + var getValue = function(value) { + return trustedContext ? + $sce.getTrusted(trustedContext, value) : + $sce.valueOf(value); + }; + + return extend(function interpolationFn(context) { + var i = 0; + var ii = expressions.length; + var values = new Array(ii); + try { - for(var i = 0, ii = length, part; i * - * @param {function()} fn A function that should be called repeatedly. + * @param {function()} fn A function that should be called repeatedly. If no additional arguments + * are passed (see below), the function is called with the current iteration count. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. - * @returns {promise} A promise which will be notified on each iteration. + * @param {...*=} Pass additional parameters to the executed function. + * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete. * * @example - * - * - * + * // used to update the UI + * function updateTime() { + * element.text(dateFilter(new Date(), format)); + * } * - *
    - *
    - * Date format:
    - * Current time is: - *
    - * Blood 1 : {{blood_1}} - * Blood 2 : {{blood_2}} - * - * - * - *
    + * // watch the expression, and update the UI on change. + * scope.$watch(attrs.myCurrentTime, function(value) { + * format = value; + * updateTime(); + * }); + * + * stopTime = $interval(updateTime, 1000); + * + * // listen on DOM destroy (removal) event, and cancel the next UI update + * // to prevent updating time after the DOM element was removed. + * element.on('$destroy', function() { + * $interval.cancel(stopTime); + * }); + * } + * }]); + * + * + *
    + *
    + *
    + * Current time is: + *
    + * Blood 1 : {{blood_1}} + * Blood 2 : {{blood_2}} + * + * + * *
    + *
    * - * + * * */ function interval(fn, delay, count, invokeApply) { - var setInterval = $window.setInterval, + var hasParams = arguments.length > 4, + args = hasParams ? sliceArgs(arguments, 4) : [], + setInterval = $window.setInterval, clearInterval = $window.clearInterval, - deferred = $q.defer(), - promise = deferred.promise, iteration = 0, - skipApply = (isDefined(invokeApply) && !invokeApply); + skipApply = (isDefined(invokeApply) && !invokeApply), + deferred = (skipApply ? $$q : $q).defer(), + promise = deferred.promise; count = isDefined(count) ? count : 0; - promise.then(null, null, fn); - promise.$$intervalId = setInterval(function tick() { + if (skipApply) { + $browser.defer(callback); + } else { + $rootScope.$evalAsync(callback); + } deferred.notify(iteration++); if (count > 0 && iteration >= count) { @@ -8838,6 +13462,14 @@ intervals[promise.$$intervalId] = deferred; return promise; + + function callback() { + if (!hasParams) { + fn(iteration); + } else { + fn.apply(null, args); + } + } } @@ -8848,13 +13480,15 @@ * @description * Cancels a task associated with the `promise`. * - * @param {promise} promise returned by the `$interval` function. + * @param {Promise=} promise returned by the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully canceled. */ interval.cancel = function(promise) { if (promise && promise.$$intervalId in intervals) { + // Interval cancels should not report as unhandled promise. + markQExceptionHandled(intervals[promise.$$intervalId].promise); intervals[promise.$$intervalId].reject('canceled'); - clearInterval(promise.$$intervalId); + $window.clearInterval(promise.$$intervalId); delete intervals[promise.$$intervalId]; return true; } @@ -8867,77 +13501,97 @@ /** * @ngdoc service - * @name $locale - * + * @name $jsonpCallbacks + * @requires $window * @description - * $locale service provides localization rules for various Angular components. As of right now the - * only public api is: - * - * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) + * This service handles the lifecycle of callbacks to handle JSONP requests. + * Override this service if you wish to customise where the callbacks are stored and + * how they vary compared to the requested url. */ - function $LocaleProvider(){ + var $jsonpCallbacksProvider = /** @this */ function() { this.$get = function() { + var callbacks = angular.callbacks; + var callbackMap = {}; + + function createCallback(callbackId) { + var callback = function(data) { + callback.data = data; + callback.called = true; + }; + callback.id = callbackId; + return callback; + } + return { - id: 'en-us', - - NUMBER_FORMATS: { - DECIMAL_SEP: '.', - GROUP_SEP: ',', - PATTERNS: [ - { // Decimal Pattern - minInt: 1, - minFrac: 0, - maxFrac: 3, - posPre: '', - posSuf: '', - negPre: '-', - negSuf: '', - gSize: 3, - lgSize: 3 - },{ //Currency Pattern - minInt: 1, - minFrac: 2, - maxFrac: 2, - posPre: '\u00A4', - posSuf: '', - negPre: '(\u00A4', - negSuf: ')', - gSize: 3, - lgSize: 3 - } - ], - CURRENCY_SYM: '$' + /** + * @ngdoc method + * @name $jsonpCallbacks#createCallback + * @param {string} url the url of the JSONP request + * @returns {string} the callback path to send to the server as part of the JSONP request + * @description + * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback + * to pass to the server, which will be used to call the callback with its payload in the JSONP response. + */ + createCallback: function(url) { + var callbackId = '_' + (callbacks.$$counter++).toString(36); + var callbackPath = 'angular.callbacks.' + callbackId; + var callback = createCallback(callbackId); + callbackMap[callbackPath] = callbacks[callbackId] = callback; + return callbackPath; }, - - DATETIME_FORMATS: { - MONTH: - 'January,February,March,April,May,June,July,August,September,October,November,December' - .split(','), - SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), - DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), - SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), - AMPMS: ['AM','PM'], - medium: 'MMM d, y h:mm:ss a', - short: 'M/d/yy h:mm a', - fullDate: 'EEEE, MMMM d, y', - longDate: 'MMMM d, y', - mediumDate: 'MMM d, y', - shortDate: 'M/d/yy', - mediumTime: 'h:mm:ss a', - shortTime: 'h:mm a' + /** + * @ngdoc method + * @name $jsonpCallbacks#wasCalled + * @param {string} callbackPath the path to the callback that was sent in the JSONP request + * @returns {boolean} whether the callback has been called, as a result of the JSONP response + * @description + * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the + * callback that was passed in the request. + */ + wasCalled: function(callbackPath) { + return callbackMap[callbackPath].called; }, - - pluralCat: function(num) { - if (num === 1) { - return 'one'; - } - return 'other'; + /** + * @ngdoc method + * @name $jsonpCallbacks#getResponse + * @param {string} callbackPath the path to the callback that was sent in the JSONP request + * @returns {*} the data received from the response via the registered callback + * @description + * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback + * in the JSONP response. + */ + getResponse: function(callbackPath) { + return callbackMap[callbackPath].data; + }, + /** + * @ngdoc method + * @name $jsonpCallbacks#removeCallback + * @param {string} callbackPath the path to the callback that was sent in the JSONP request + * @description + * {@link $httpBackend} calls this method to remove the callback after the JSONP request has + * completed or timed-out. + */ + removeCallback: function(callbackPath) { + var callback = callbackMap[callbackPath]; + delete callbacks[callback.id]; + delete callbackMap[callbackPath]; } }; }; - } + }; + + /** + * @ngdoc service + * @name $locale + * + * @description + * $locale service provides localization rules for various AngularJS components. As of right now the + * only public api is: + * + * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) + */ - var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, + var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; var $locationMinErr = minErr('$location'); @@ -8953,56 +13607,84 @@ i = segments.length; while (i--) { - segments[i] = encodeUriSegment(segments[i]); + // decode forward slashes to prevent them from being double encoded + segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/')); + } + + return segments.join('/'); + } + + function decodePath(path, html5Mode) { + var segments = path.split('/'), + i = segments.length; + + while (i--) { + segments[i] = decodeURIComponent(segments[i]); + if (html5Mode) { + // encode forward slashes to prevent them from being mistaken for path separators + segments[i] = segments[i].replace(/\//g, '%2F'); + } } return segments.join('/'); } - function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) { - var parsedUrl = urlResolve(absoluteUrl, appBase); + function parseAbsoluteUrl(absoluteUrl, locationObj) { + var parsedUrl = urlResolve(absoluteUrl); locationObj.$$protocol = parsedUrl.protocol; locationObj.$$host = parsedUrl.hostname; - locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; + locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; } + var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/; + function parseAppUrl(url, locationObj, html5Mode) { + + if (DOUBLE_SLASH_REGEX.test(url)) { + throw $locationMinErr('badpath', 'Invalid url "{0}".', url); + } - function parseAppUrl(relativeUrl, locationObj, appBase) { - var prefixed = (relativeUrl.charAt(0) !== '/'); + var prefixed = (url.charAt(0) !== '/'); if (prefixed) { - relativeUrl = '/' + relativeUrl; + url = '/' + url; } - var match = urlResolve(relativeUrl, appBase); - locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? - match.pathname.substring(1) : match.pathname); + var match = urlResolve(url); + var path = prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname; + locationObj.$$path = decodePath(path, html5Mode); locationObj.$$search = parseKeyValue(match.search); locationObj.$$hash = decodeURIComponent(match.hash); // make sure path starts with '/'; - if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { + if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') { locationObj.$$path = '/' + locationObj.$$path; } } + function startsWith(str, search) { + return str.slice(0, search.length) === search; + } /** * - * @param {string} begin - * @param {string} whole - * @returns {string} returns text from whole after begin or undefined if it does not begin with - * expected string. + * @param {string} base + * @param {string} url + * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with + * the expected string. */ - function beginsWith(begin, whole) { - if (whole.indexOf(begin) === 0) { - return whole.substr(begin.length); + function stripBaseUrl(base, url) { + if (startsWith(url, base)) { + return url.substr(base.length); } } function stripHash(url) { var index = url.indexOf('#'); - return index == -1 ? url : url.substr(0, index); + return index === -1 ? url : url.substr(0, index); + } + + function trimEmptyHash(url) { + return url.replace(/(#.+)|#$/, '$1'); } @@ -9017,33 +13699,33 @@ /** - * LocationHtml5Url represents an url + * LocationHtml5Url represents a URL * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} appBase application base URL - * @param {string} basePrefix url path prefix + * @param {string} appBaseNoFile application base URL stripped of any filename + * @param {string} basePrefix URL path prefix */ - function LocationHtml5Url(appBase, basePrefix) { + function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) { this.$$html5 = true; basePrefix = basePrefix || ''; - var appBaseNoFile = stripFile(appBase); - parseAbsoluteUrl(appBase, this, appBase); + parseAbsoluteUrl(appBase, this); /** - * Parse given html5 (regular) url string into properties - * @param {string} newAbsoluteUrl HTML5 url + * Parse given HTML5 (regular) URL string into properties + * @param {string} url HTML5 URL * @private */ this.$$parse = function(url) { - var pathUrl = beginsWith(appBaseNoFile, url); + var pathUrl = stripBaseUrl(appBaseNoFile, url); if (!isString(pathUrl)) { throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, appBaseNoFile); } - parseAppUrl(pathUrl, this, appBase); + parseAppUrl(pathUrl, this, true); if (!this.$$path) { this.$$path = '/'; @@ -9062,94 +13744,122 @@ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' + + this.$$urlUpdatedByLocation = true; }; - this.$$rewrite = function(url) { + this.$$parseLinkUrl = function(url, relHref) { + if (relHref && relHref[0] === '#') { + // special case for links to hash fragments: + // keep the old url and only replace the hash fragment + this.hash(relHref.slice(1)); + return true; + } var appUrl, prevAppUrl; + var rewrittenUrl; + - if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { + if (isDefined(appUrl = stripBaseUrl(appBase, url))) { prevAppUrl = appUrl; - if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { - return appBaseNoFile + (beginsWith('/', appUrl) || appUrl); + if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) { + rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl); } else { - return appBase + prevAppUrl; + rewrittenUrl = appBase + prevAppUrl; } - } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { - return appBaseNoFile + appUrl; - } else if (appBaseNoFile == url + '/') { - return appBaseNoFile; + } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) { + rewrittenUrl = appBaseNoFile + appUrl; + } else if (appBaseNoFile === url + '/') { + rewrittenUrl = appBaseNoFile; } + if (rewrittenUrl) { + this.$$parse(rewrittenUrl); + } + return !!rewrittenUrl; }; } /** - * LocationHashbangUrl represents url + * LocationHashbangUrl represents URL * This object is exposed as $location service when developer doesn't opt into html5 mode. * It also serves as the base class for html5 mode fallback on legacy browsers. * * @constructor * @param {string} appBase application base URL + * @param {string} appBaseNoFile application base URL stripped of any filename * @param {string} hashPrefix hashbang prefix */ - function LocationHashbangUrl(appBase, hashPrefix) { - var appBaseNoFile = stripFile(appBase); + function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) { - parseAbsoluteUrl(appBase, this, appBase); + parseAbsoluteUrl(appBase, this); /** - * Parse given hashbang url into properties - * @param {string} url Hashbang url + * Parse given hashbang URL into properties + * @param {string} url Hashbang URL * @private */ this.$$parse = function(url) { - var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); - var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' - ? beginsWith(hashPrefix, withoutBaseUrl) - : (this.$$html5) - ? withoutBaseUrl - : ''; + var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url); + var withoutHashUrl; + + if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') { - if (!isString(withoutHashUrl)) { - throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, - hashPrefix); + // The rest of the URL starts with a hash so we have + // got either a hashbang path or a plain hash fragment + withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl); + if (isUndefined(withoutHashUrl)) { + // There was no hashbang prefix so we just have a hash fragment + withoutHashUrl = withoutBaseUrl; + } + + } else { + // There was no hashbang path nor hash fragment: + // If we are in HTML5 mode we use what is left as the path; + // Otherwise we ignore what is left + if (this.$$html5) { + withoutHashUrl = withoutBaseUrl; + } else { + withoutHashUrl = ''; + if (isUndefined(withoutBaseUrl)) { + appBase = url; + /** @type {?} */ (this).replace(); + } + } } - parseAppUrl(withoutHashUrl, this, appBase); + + parseAppUrl(withoutHashUrl, this, false); this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); this.$$compose(); /* - * In Windows, on an anchor node on documents loaded from - * the filesystem, the browser will return a pathname - * prefixed with the drive name ('/C:/path') when a - * pathname without a drive is set: - * * a.setAttribute('href', '/foo') - * * a.pathname === '/C:/foo' //true - * - * Inside of Angular, we're always using pathnames that - * do not include drive names for routing. - */ - function removeWindowsDriveName (path, url, base) { + * In Windows, on an anchor node on documents loaded from + * the filesystem, the browser will return a pathname + * prefixed with the drive name ('/C:/path') when a + * pathname without a drive is set: + * * a.setAttribute('href', '/foo') + * * a.pathname === '/C:/foo' //true + * + * Inside of AngularJS, we're always using pathnames that + * do not include drive names for routing. + */ + function removeWindowsDriveName(path, url, base) { /* - Matches paths for file protocol on windows, - such as /C:/foo/bar, and captures only /foo/bar. - */ - var windowsFilePathExp = /^\/?.*?:(\/.*)/; + Matches paths for file protocol on windows, + such as /C:/foo/bar, and captures only /foo/bar. + */ + var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; var firstPathSegmentMatch; //Get the relative path from the input URL. - if (url.indexOf(base) === 0) { + if (startsWith(url, base)) { url = url.replace(base, ''); } - /* - * The input URL intentionally contains a - * first path segment that ends with a colon. - */ + // The input URL intentionally contains a first path segment that ends with a colon. if (windowsFilePathExp.exec(url)) { return path; } @@ -9160,7 +13870,7 @@ }; /** - * Compose hashbang url and update `absUrl` property + * Compose hashbang URL and update `absUrl` property * @private */ this.$$compose = function() { @@ -9169,250 +13879,415 @@ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); + + this.$$urlUpdatedByLocation = true; }; - this.$$rewrite = function(url) { - if(stripHash(appBase) == stripHash(url)) { - return url; + this.$$parseLinkUrl = function(url, relHref) { + if (stripHash(appBase) === stripHash(url)) { + this.$$parse(url); + return true; } + return false; }; } /** - * LocationHashbangUrl represents url + * LocationHashbangUrl represents URL * This object is exposed as $location service when html5 history api is enabled but the browser * does not support it. * * @constructor * @param {string} appBase application base URL + * @param {string} appBaseNoFile application base URL stripped of any filename * @param {string} hashPrefix hashbang prefix */ - function LocationHashbangInHtml5Url(appBase, hashPrefix) { + function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) { this.$$html5 = true; LocationHashbangUrl.apply(this, arguments); - var appBaseNoFile = stripFile(appBase); + this.$$parseLinkUrl = function(url, relHref) { + if (relHref && relHref[0] === '#') { + // special case for links to hash fragments: + // keep the old url and only replace the hash fragment + this.hash(relHref.slice(1)); + return true; + } - this.$$rewrite = function(url) { + var rewrittenUrl; var appUrl; - if ( appBase == stripHash(url) ) { - return url; - } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { - return appBase + hashPrefix + appUrl; - } else if ( appBaseNoFile === url + '/') { - return appBaseNoFile; + if (appBase === stripHash(url)) { + rewrittenUrl = url; + } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) { + rewrittenUrl = appBase + hashPrefix + appUrl; + } else if (appBaseNoFile === url + '/') { + rewrittenUrl = appBaseNoFile; } + if (rewrittenUrl) { + this.$$parse(rewrittenUrl); + } + return !!rewrittenUrl; }; - } + this.$$compose = function() { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - LocationHashbangInHtml5Url.prototype = - LocationHashbangUrl.prototype = - LocationHtml5Url.prototype = { + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#' + this.$$absUrl = appBase + hashPrefix + this.$$url; - /** - * Are we in html5 mode? - * @private - */ - $$html5: false, + this.$$urlUpdatedByLocation = true; + }; - /** - * Has any change been replacing ? - * @private - */ - $$replace: false, + } - /** - * @ngdoc method - * @name $location#absUrl - * - * @description - * This method is getter only. - * - * Return full url representation with all segments encoded according to rules specified in - * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). - * - * @return {string} full url - */ - absUrl: locationGetter('$$absUrl'), - /** - * @ngdoc method - * @name $location#url - * - * @description - * This method is getter / setter. - * - * Return url (e.g. `/path?a=b#hash`) when called without any parameter. - * - * Change path, search and hash, when called with parameter and return `$location`. - * - * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) - * @param {string=} replace The path that will be changed - * @return {string} url - */ - url: function(url, replace) { - if (isUndefined(url)) - return this.$$url; + var locationPrototype = { - var match = PATH_MATCH.exec(url); - if (match[1]) this.path(decodeURIComponent(match[1])); - if (match[2] || match[1]) this.search(match[3] || ''); - this.hash(match[5] || '', replace); + /** + * Ensure absolute URL is initialized. + * @private + */ + $$absUrl:'', - return this; - }, + /** + * Are we in html5 mode? + * @private + */ + $$html5: false, - /** - * @ngdoc method - * @name $location#protocol - * - * @description - * This method is getter only. - * - * Return protocol of current url. - * - * @return {string} protocol of current url - */ - protocol: locationGetter('$$protocol'), + /** + * Has any change been replacing? + * @private + */ + $$replace: false, - /** - * @ngdoc method - * @name $location#host - * - * @description - * This method is getter only. - * - * Return host of current url. - * - * @return {string} host of current url. - */ - host: locationGetter('$$host'), + /** + * @ngdoc method + * @name $location#absUrl + * + * @description + * This method is getter only. + * + * Return full URL representation with all segments encoded according to rules specified in + * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var absUrl = $location.absUrl(); + * // => "http://example.com/#/some/path?foo=bar&baz=xoxo" + * ``` + * + * @return {string} full URL + */ + absUrl: locationGetter('$$absUrl'), - /** - * @ngdoc method - * @name $location#port - * - * @description - * This method is getter only. - * - * Return port of current url. - * - * @return {Number} port - */ - port: locationGetter('$$port'), + /** + * @ngdoc method + * @name $location#url + * + * @description + * This method is getter / setter. + * + * Return URL (e.g. `/path?a=b#hash`) when called without any parameter. + * + * Change path, search and hash, when called with parameter and return `$location`. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var url = $location.url(); + * // => "/some/path?foo=bar&baz=xoxo" + * ``` + * + * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`) + * @return {string} url + */ + url: function(url) { + if (isUndefined(url)) { + return this.$$url; + } - /** - * @ngdoc method - * @name $location#path - * - * @description - * This method is getter / setter. - * - * Return path of current url when called without any parameter. - * - * Change path when called with parameter and return `$location`. - * - * Note: Path should always begin with forward slash (/), this method will add the forward slash - * if it is missing. - * - * @param {string=} path New path - * @return {string} path - */ - path: locationGetterSetter('$$path', function(path) { - return path.charAt(0) == '/' ? path : '/' + path; - }), + var match = PATH_MATCH.exec(url); + if (match[1] || url === '') this.path(decodeURIComponent(match[1])); + if (match[2] || match[1] || url === '') this.search(match[3] || ''); + this.hash(match[5] || ''); - /** - * @ngdoc method - * @name $location#search - * - * @description - * This method is getter / setter. - * - * Return search part (as object) of current url when called without any parameter. - * - * Change search part when called with parameter and return `$location`. - * - * @param {string|Object.|Object.>} search New search params - string or - * hash object. Hash object may contain an array of values, which will be decoded as duplicates in - * the url. - * - * @param {(string|Array)=} paramValue If `search` is a string, then `paramValue` will override only a - * single search parameter. If `paramValue` is an array, it will set the parameter as a - * comma-separated value. If `paramValue` is `null`, the parameter will be deleted. - * - * @return {string} search - */ - search: function(search, paramValue) { - switch (arguments.length) { - case 0: - return this.$$search; - case 1: - if (isString(search)) { - this.$$search = parseKeyValue(search); - } else if (isObject(search)) { - this.$$search = search; - } else { - throw $locationMinErr('isrcharg', - 'The first argument of the `$location#search()` call must be a string or an object.'); - } - break; - default: - if (isUndefined(paramValue) || paramValue === null) { - delete this.$$search[search]; - } else { - this.$$search[search] = paramValue; - } - } + return this; + }, - this.$$compose(); - return this; - }, + /** + * @ngdoc method + * @name $location#protocol + * + * @description + * This method is getter only. + * + * Return protocol of current URL. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var protocol = $location.protocol(); + * // => "http" + * ``` + * + * @return {string} protocol of current URL + */ + protocol: locationGetter('$$protocol'), - /** - * @ngdoc method - * @name $location#hash - * - * @description - * This method is getter / setter. - * - * Return hash fragment when called without any parameter. - * - * Change hash fragment when called with parameter and return `$location`. - * - * @param {string=} hash New hash fragment - * @return {string} hash - */ - hash: locationGetterSetter('$$hash', identity), + /** + * @ngdoc method + * @name $location#host + * + * @description + * This method is getter only. + * + * Return host of current URL. + * + * Note: compared to the non-AngularJS version `location.host` which returns `hostname:port`, this returns the `hostname` portion only. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var host = $location.host(); + * // => "example.com" + * + * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo + * host = $location.host(); + * // => "example.com" + * host = location.host; + * // => "example.com:8080" + * ``` + * + * @return {string} host of current URL. + */ + host: locationGetter('$$host'), + + /** + * @ngdoc method + * @name $location#port + * + * @description + * This method is getter only. + * + * Return port of current URL. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var port = $location.port(); + * // => 80 + * ``` + * + * @return {Number} port + */ + port: locationGetter('$$port'), + + /** + * @ngdoc method + * @name $location#path + * + * @description + * This method is getter / setter. + * + * Return path of current URL when called without any parameter. + * + * Change path when called with parameter and return `$location`. + * + * Note: Path should always begin with forward slash (/), this method will add the forward slash + * if it is missing. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var path = $location.path(); + * // => "/some/path" + * ``` + * + * @param {(string|number)=} path New path + * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter + */ + path: locationGetterSetter('$$path', function(path) { + path = path !== null ? path.toString() : ''; + return path.charAt(0) === '/' ? path : '/' + path; + }), + + /** + * @ngdoc method + * @name $location#search + * + * @description + * This method is getter / setter. + * + * Return search part (as object) of current URL when called without any parameter. + * + * Change search part when called with parameter and return `$location`. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var searchObject = $location.search(); + * // => {foo: 'bar', baz: 'xoxo'} + * + * // set foo to 'yipee' + * $location.search('foo', 'yipee'); + * // $location.search() => {foo: 'yipee', baz: 'xoxo'} + * ``` + * + * @param {string|Object.|Object.>} search New search params - string or + * hash object. + * + * When called with a single argument the method acts as a setter, setting the `search` component + * of `$location` to the specified value. + * + * If the argument is a hash object containing an array of values, these values will be encoded + * as duplicate search parameters in the URL. + * + * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, then `paramValue` + * will override only a single search property. + * + * If `paramValue` is an array, it will override the property of the `search` component of + * `$location` specified via the first argument. + * + * If `paramValue` is `null`, the property specified via the first argument will be deleted. + * + * If `paramValue` is `true`, the property specified via the first argument will be added with no + * value nor trailing equal sign. + * + * @return {Object} If called with no arguments returns the parsed `search` object. If called with + * one or more arguments returns `$location` object itself. + */ + search: function(search, paramValue) { + switch (arguments.length) { + case 0: + return this.$$search; + case 1: + if (isString(search) || isNumber(search)) { + search = search.toString(); + this.$$search = parseKeyValue(search); + } else if (isObject(search)) { + search = copy(search, {}); + // remove object undefined or null properties + forEach(search, function(value, key) { + if (value == null) delete search[key]; + }); + + this.$$search = search; + } else { + throw $locationMinErr('isrcharg', + 'The first argument of the `$location#search()` call must be a string or an object.'); + } + break; + default: + if (isUndefined(paramValue) || paramValue === null) { + delete this.$$search[search]; + } else { + this.$$search[search] = paramValue; + } + } + + this.$$compose(); + return this; + }, + + /** + * @ngdoc method + * @name $location#hash + * + * @description + * This method is getter / setter. + * + * Returns the hash fragment when called without any parameters. + * + * Changes the hash fragment when called with a parameter and returns `$location`. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue + * var hash = $location.hash(); + * // => "hashValue" + * ``` + * + * @param {(string|number)=} hash New hash fragment + * @return {string} hash + */ + hash: locationGetterSetter('$$hash', function(hash) { + return hash !== null ? hash.toString() : ''; + }), + + /** + * @ngdoc method + * @name $location#replace + * + * @description + * If called, all changes to $location during the current `$digest` will replace the current history + * record, instead of adding a new one. + */ + replace: function() { + this.$$replace = true; + return this; + } + }; + + forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) { + Location.prototype = Object.create(locationPrototype); + + /** + * @ngdoc method + * @name $location#state + * + * @description + * This method is getter / setter. + * + * Return the history state object when called without any parameter. + * + * Change the history state object when called with one parameter and return `$location`. + * The state object is later passed to `pushState` or `replaceState`. + * + * NOTE: This method is supported only in HTML5 mode and only in browsers supporting + * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support + * older browsers (like IE9 or Android < 4.0), don't use this method. + * + * @param {object=} state State object for pushState or replaceState + * @return {object} state + */ + Location.prototype.state = function(state) { + if (!arguments.length) { + return this.$$state; + } + + if (Location !== LocationHtml5Url || !this.$$html5) { + throw $locationMinErr('nostate', 'History API state support is available only ' + + 'in HTML5 mode and only in browsers supporting HTML5 History API'); + } + // The user might modify `stateObject` after invoking `$location.state(stateObject)` + // but we're changing the $$state reference to $browser.state() during the $digest + // so the modification window is narrow. + this.$$state = isUndefined(state) ? null : state; + this.$$urlUpdatedByLocation = true; + + return this; + }; + }); - /** - * @ngdoc method - * @name $location#replace - * - * @description - * If called, all changes to $location during current `$digest` will be replacing current history - * record, instead of adding new one. - */ - replace: function() { - this.$$replace = true; - return this; - } - }; function locationGetter(property) { - return function() { + return /** @this */ function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { - return function(value) { - if (isUndefined(value)) + return /** @this */ function(value) { + if (isUndefined(value)) { return this[property]; + } this[property] = preprocess(value); this.$$compose(); @@ -9451,17 +14326,24 @@ /** * @ngdoc provider * @name $locationProvider + * @this + * * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ - function $LocationProvider(){ - var hashPrefix = '', - html5Mode = false; + function $LocationProvider() { + var hashPrefix = '!', + html5Mode = { + enabled: false, + requireBase: true, + rewriteLinks: true + }; /** - * @ngdoc property + * @ngdoc method * @name $locationProvider#hashPrefix * @description + * The default value for the prefix is `'!'`. * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ @@ -9475,15 +14357,46 @@ }; /** - * @ngdoc property + * @ngdoc method * @name $locationProvider#html5Mode * @description - * @param {boolean=} mode Use HTML5 strategy if available. - * @returns {*} current value if used as getter or itself (chaining) if used as setter + * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value. + * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported + * properties: + * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to + * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not + * support `pushState`. + * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies + * whether or not a tag is required to be present. If `enabled` and `requireBase` are + * true, and a base tag is not present, an error will be thrown when `$location` is injected. + * See the {@link guide/$location $location guide for more information} + * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled, + * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will + * only happen on links with an attribute that matches the given string. For example, if set + * to `'internal-link'`, then the URL will only be rewritten for `` links. + * Note that [attribute name normalization](guide/directive#normalization) does not apply + * here, so `'internalLink'` will **not** match `'internal-link'`. + * + * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { - if (isDefined(mode)) { - html5Mode = mode; + if (isBoolean(mode)) { + html5Mode.enabled = mode; + return this; + } else if (isObject(mode)) { + + if (isBoolean(mode.enabled)) { + html5Mode.enabled = mode.enabled; + } + + if (isBoolean(mode.requireBase)) { + html5Mode.requireBase = mode.requireBase; + } + + if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) { + html5Mode.rewriteLinks = mode.rewriteLinks; + } + return this; } else { return html5Mode; @@ -9495,14 +14408,21 @@ * @name $location#$locationChangeStart * @eventType broadcast on root scope * @description - * Broadcasted before a URL will change. This change can be prevented by calling + * Broadcasted before a URL will change. + * + * This change can be prevented by calling * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more * details about event object. Upon successful change - * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired. + * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired. + * + * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when + * the browser supports the HTML5 History API. * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. + * @param {string=} newState New history state object + * @param {string=} oldState History state object that was before it was changed. */ /** @@ -9512,44 +14432,84 @@ * @description * Broadcasted after a URL was changed. * + * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when + * the browser supports the HTML5 History API. + * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. + * @param {string=} newState New history state object + * @param {string=} oldState History state object that was before it was changed. */ - this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', - function( $rootScope, $browser, $sniffer, $rootElement) { + this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window', + function($rootScope, $browser, $sniffer, $rootElement, $window) { var $location, LocationMode, baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' initialUrl = $browser.url(), appBase; - if (html5Mode) { + if (html5Mode.enabled) { + if (!baseHref && html5Mode.requireBase) { + throw $locationMinErr('nobase', + '$location in HTML5 mode requires a tag to be present!'); + } appBase = serverBase(initialUrl) + (baseHref || '/'); LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; } else { appBase = stripHash(initialUrl); LocationMode = LocationHashbangUrl; } - $location = new LocationMode(appBase, '#' + hashPrefix); - $location.$$parse($location.$$rewrite(initialUrl)); + var appBaseNoFile = stripFile(appBase); + + $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix); + $location.$$parseLinkUrl(initialUrl, initialUrl); + + $location.$$state = $browser.state(); + + var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; + + function setBrowserUrlWithFallback(url, replace, state) { + var oldUrl = $location.url(); + var oldState = $location.$$state; + try { + $browser.url(url, replace, state); + + // Make sure $location.state() returns referentially identical (not just deeply equal) + // state object; this makes possible quick checking if the state changed in the digest + // loop. Checking deep equality would be too expensive. + $location.$$state = $browser.state(); + } catch (e) { + // Restore old values if pushState fails + $location.url(oldUrl); + $location.$$state = oldState; + + throw e; + } + } $rootElement.on('click', function(event) { + var rewriteLinks = html5Mode.rewriteLinks; // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then - if (event.ctrlKey || event.metaKey || event.which == 2) return; + if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag - while (lowercase(elm[0].nodeName) !== 'a') { + while (nodeName_(elm[0]) !== 'a') { // ignore rewriting if no A tag (reached root element, or no parent - removed from document) if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } + if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return; + var absHref = elm.prop('href'); + // get the actual href attribute - see + // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx + var relHref = elm.attr('href') || elm.attr('xlink:href'); if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during @@ -9557,72 +14517,118 @@ absHref = urlResolve(absHref.animVal).href; } - var rewrittenUrl = $location.$$rewrite(absHref); + // Ignore when url is started with javascript: or mailto: + if (IGNORE_URI_REGEXP.test(absHref)) return; - if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) { - event.preventDefault(); - if (rewrittenUrl != $browser.url()) { + if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { + if ($location.$$parseLinkUrl(absHref, relHref)) { + // We do a preventDefault for all urls that are part of the AngularJS application, + // in html5mode and also without, so that we are able to abort navigation without + // getting double entries in the location history. + event.preventDefault(); // update location manually - $location.$$parse(rewrittenUrl); - $rootScope.$apply(); - // hack to work around FF6 bug 684208 when scenario runner clicks on links - window.angular['ff-684208-preventDefault'] = true; + if ($location.absUrl() !== $browser.url()) { + $rootScope.$apply(); + // hack to work around FF6 bug 684208 when scenario runner clicks on links + $window.angular['ff-684208-preventDefault'] = true; + } } } }); // rewrite hashbang url <> html5 url - if ($location.absUrl() != initialUrl) { + if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) { $browser.url($location.absUrl(), true); } + var initializing = true; + // update $location when $browser url changes - $browser.onUrlChange(function(newUrl) { - if ($location.absUrl() != newUrl) { - $rootScope.$evalAsync(function() { - var oldUrl = $location.absUrl(); + $browser.onUrlChange(function(newUrl, newState) { - $location.$$parse(newUrl); - if ($rootScope.$broadcast('$locationChangeStart', newUrl, - oldUrl).defaultPrevented) { - $location.$$parse(oldUrl); - $browser.url(oldUrl); - } else { - afterLocationChange(oldUrl); - } - }); - if (!$rootScope.$$phase) $rootScope.$digest(); + if (!startsWith(newUrl, appBaseNoFile)) { + // If we are navigating outside of the app then force a reload + $window.location.href = newUrl; + return; } + + $rootScope.$evalAsync(function() { + var oldUrl = $location.absUrl(); + var oldState = $location.$$state; + var defaultPrevented; + newUrl = trimEmptyHash(newUrl); + $location.$$parse(newUrl); + $location.$$state = newState; + + defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, + newState, oldState).defaultPrevented; + + // if the location was changed by a `$locationChangeStart` handler then stop + // processing this location change + if ($location.absUrl() !== newUrl) return; + + if (defaultPrevented) { + $location.$$parse(oldUrl); + $location.$$state = oldState; + setBrowserUrlWithFallback(oldUrl, false, oldState); + } else { + initializing = false; + afterLocationChange(oldUrl, oldState); + } + }); + if (!$rootScope.$$phase) $rootScope.$digest(); }); // update browser - var changeCounter = 0; $rootScope.$watch(function $locationWatch() { - var oldUrl = $browser.url(); - var currentReplace = $location.$$replace; - - if (!changeCounter || oldUrl != $location.absUrl()) { - changeCounter++; - $rootScope.$evalAsync(function() { - if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). - defaultPrevented) { - $location.$$parse(oldUrl); - } else { - $browser.url($location.absUrl(), currentReplace); - afterLocationChange(oldUrl); - } - }); + if (initializing || $location.$$urlUpdatedByLocation) { + $location.$$urlUpdatedByLocation = false; + + var oldUrl = trimEmptyHash($browser.url()); + var newUrl = trimEmptyHash($location.absUrl()); + var oldState = $browser.state(); + var currentReplace = $location.$$replace; + var urlOrStateChanged = oldUrl !== newUrl || + ($location.$$html5 && $sniffer.history && oldState !== $location.$$state); + + if (initializing || urlOrStateChanged) { + initializing = false; + + $rootScope.$evalAsync(function() { + var newUrl = $location.absUrl(); + var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, + $location.$$state, oldState).defaultPrevented; + + // if the location was changed by a `$locationChangeStart` handler then stop + // processing this location change + if ($location.absUrl() !== newUrl) return; + + if (defaultPrevented) { + $location.$$parse(oldUrl); + $location.$$state = oldState; + } else { + if (urlOrStateChanged) { + setBrowserUrlWithFallback(newUrl, currentReplace, + oldState === $location.$$state ? null : $location.$$state); + } + afterLocationChange(oldUrl, oldState); + } + }); + } } + $location.$$replace = false; - return changeCounter; + // we don't need to return anything because $evalAsync will make the digest loop dirty when + // there is a change }); return $location; - function afterLocationChange(oldUrl) { - $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); + function afterLocationChange(oldUrl, oldState) { + $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl, + $location.$$state, oldState); } }]; } @@ -9638,26 +14644,36 @@ * * The main purpose of this service is to simplify debugging and troubleshooting. * + * To reveal the location of the calls to `$log` in the JavaScript console, + * you can "blackbox" the AngularJS source in your browser: + * + * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source). + * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing). + * + * Note: Not all browsers support blackboxing. + * * The default is to log `debug` messages. You can use * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. * * @example - + - function LogCtrl($scope, $log) { - $scope.$log = $log; - $scope.message = 'Hello World!'; - } + angular.module('logExample', []) + .controller('LogController', ['$scope', '$log', function($scope, $log) { + $scope.$log = $log; + $scope.message = 'Hello World!'; + }]); -
    +

    Reload this page with open console, enter text and hit the log button...

    - Message: - + +
    @@ -9666,15 +14682,17 @@ /** * @ngdoc provider * @name $logProvider + * @this + * * @description * Use the `$logProvider` to configure how the application logs messages */ - function $LogProvider(){ + function $LogProvider() { var debug = true, self = this; /** - * @ngdoc property + * @ngdoc method * @name $logProvider#debugEnabled * @description * @param {boolean=} flag enable or disable debug level messages @@ -9689,7 +14707,16 @@ } }; - this.$get = ['$window', function($window){ + this.$get = ['$window', function($window) { + // Support: IE 9-11, Edge 12-14+ + // IE/Edge display errors in such a way that it requires the user to click in 4 places + // to see the stack trace. There is no way to feature-detect it so there's a chance + // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't + // break apps. Other browsers display errors in a sensible way and some of them map stack + // traces along source maps if available so it makes sense to let browsers display it + // as they want. + var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent); + return { /** * @ngdoc method @@ -9734,7 +14761,7 @@ * @description * Write a debug message */ - debug: (function () { + debug: (function() { var fn = consoleLog('debug'); return function() { @@ -9742,12 +14769,12 @@ fn.apply(self, arguments); } }; - }()) + })() }; function formatError(arg) { - if (arg instanceof Error) { - if (arg.stack) { + if (isError(arg)) { + if (arg.stack && formatStackTrace) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; @@ -9760,139 +14787,74 @@ function consoleLog(type) { var console = $window.console || {}, - logFn = console[type] || console.log || noop, - hasApply = false; - - // Note: reading logFn.apply throws an error in IE11 in IE8 document mode. - // The reason behind this is that console.log has type "object" in IE8... - try { - hasApply = !!logFn.apply; - } catch (e) {} + logFn = console[type] || console.log || noop; - if (hasApply) { - return function() { - var args = []; - forEach(arguments, function(arg) { - args.push(formatError(arg)); - }); - return logFn.apply(console, args); - }; - } - - // we are IE which either doesn't have window.console => this is noop and we do nothing, - // or we are IE where console.log doesn't have apply so we log at least first 2 args - return function(arg1, arg2) { - logFn(arg1, arg2 == null ? '' : arg2); + return function() { + var args = []; + forEach(arguments, function(arg) { + args.push(formatError(arg)); + }); + // Support: IE 9 only + // console methods don't inherit from Function.prototype in IE 9 so we can't + // call `logFn.apply(console, args)` directly. + return Function.prototype.apply.call(logFn, console, args); }; } }]; } + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Any commits to this file should be reviewed with security in mind. * + * Changes to this file can potentially create security vulnerabilities. * + * An approval from 2 Core members with history of modifying * + * this file is required. * + * * + * Does the change somehow allow for arbitrary javascript to be executed? * + * Or allows for someone to change the prototype of built-in objects? * + * Or gives undesired access to variables likes document or window? * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + var $parseMinErr = minErr('$parse'); - var promiseWarningCache = {}; - var promiseWarning; -// Sandboxing Angular Expressions + var objectValueOf = {}.constructor.prototype.valueOf; + +// Sandboxing AngularJS Expressions // ------------------------------ -// Angular expressions are generally considered safe because these expressions only have direct -// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by -// obtaining a reference to native JS functions such as the Function constructor. -// -// As an example, consider the following Angular expression: -// -// {}.toString.constructor(alert("evil JS code")) -// -// We want to prevent this type of access. For the sake of performance, during the lexing phase we -// disallow any "dotted" access to any member named "constructor". +// AngularJS expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by +// various means such as obtaining a reference to native JS functions like the Function constructor. // -// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor -// while evaluating the expression, which is a stronger but more expensive test. Since reflective -// calls are expensive anyway, this is not such a big deal compared to static dereferencing. +// As an example, consider the following AngularJS expression: // -// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits -// against the expression language, but not to prevent exploits that were enabled by exposing -// sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good -// practice and therefore we are not even trying to protect against interaction with an object -// explicitly exposed in this way. +// {}.toString.constructor('alert("evil JS code")') // -// A developer could foil the name check by aliasing the Function constructor under a different -// name on the scope. +// It is important to realize that if you create an expression from a string that contains user provided +// content then it is possible that your application contains a security vulnerability to an XSS style attack. // -// In general, it is not possible to access a Window object from an angular expression unless a -// window or some DOM object that has a reference to window is published onto a Scope. - - function ensureSafeMemberName(name, fullExpression) { - if (name === "constructor") { - throw $parseMinErr('isecfld', - 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } - return name; +// See https://docs.angularjs.org/guide/security + + + function getStringValue(name) { + // Property names must be strings. This means that non-string objects cannot be used + // as keys in an object. Any non-string object, including a number, is typecasted + // into a string via the toString method. + // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names + // + // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it + // to a string. It's not always possible. If `name` is an object and its `toString` method is + // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown: + // + // TypeError: Cannot convert object to primitive value + // + // For performance reasons, we don't catch this error here and allow it to propagate up the call + // stack. Note that you'll get the same error in JavaScript if you try to access a property using + // such a 'broken' object as a key. + return name + ''; } - function ensureSafeObject(obj, fullExpression) { - // nifty check if obj is Function that is fast and works across iframes and other contexts - if (obj) { - if (obj.constructor === obj) { - throw $parseMinErr('isecfn', - 'Referencing Function in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } else if (// isWindow(obj) - obj.document && obj.location && obj.alert && obj.setInterval) { - throw $parseMinErr('isecwindow', - 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } else if (// isElement(obj) - obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { - throw $parseMinErr('isecdom', - 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } - } - return obj; - } - var OPERATORS = { - /* jshint bitwise : false */ - 'null':function(){return null;}, - 'true':function(){return true;}, - 'false':function(){return false;}, - undefined:noop, - '+':function(self, locals, a,b){ - a=a(self, locals); b=b(self, locals); - if (isDefined(a)) { - if (isDefined(b)) { - return a + b; - } - return a; - } - return isDefined(b)?b:undefined;}, - '-':function(self, locals, a,b){ - a=a(self, locals); b=b(self, locals); - return (isDefined(a)?a:0)-(isDefined(b)?b:0); - }, - '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, - '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, - '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, - '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, - '=':noop, - '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, - '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, - '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, - '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, - '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, - '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, - '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, - '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, - '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, - '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, -// '|':function(self, locals, a,b){return a|b;}, - '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, - '!':function(self, locals, a){return !a(self, locals);} - }; - /* jshint bitwise: true */ - var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; + var OPERATORS = createMap(); + forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; }); + var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'}; ///////////////////////////////////////// @@ -9901,85 +14863,51 @@ /** * @constructor */ - var Lexer = function (options) { + var Lexer = function Lexer(options) { this.options = options; }; Lexer.prototype = { constructor: Lexer, - lex: function (text) { + lex: function(text) { this.text = text; - this.index = 0; - this.ch = undefined; - this.lastCh = ':'; // can start regexp - this.tokens = []; - var token; - var json = []; - while (this.index < this.text.length) { - this.ch = this.text.charAt(this.index); - if (this.is('"\'')) { - this.readString(this.ch); - } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) { + var ch = this.text.charAt(this.index); + if (ch === '"' || ch === '\'') { + this.readString(ch); + } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) { this.readNumber(); - } else if (this.isIdent(this.ch)) { + } else if (this.isIdentifierStart(this.peekMultichar())) { this.readIdent(); - // identifiers can only be if the preceding char was a { or , - if (this.was('{,') && json[0] === '{' && - (token = this.tokens[this.tokens.length - 1])) { - token.json = token.text.indexOf('.') === -1; - } - } else if (this.is('(){}[].,;:?')) { - this.tokens.push({ - index: this.index, - text: this.ch, - json: (this.was(':[,') && this.is('{[')) || this.is('}]:,') - }); - if (this.is('{[')) json.unshift(this.ch); - if (this.is('}]')) json.shift(); + } else if (this.is(ch, '(){}[].,;:?')) { + this.tokens.push({index: this.index, text: ch}); this.index++; - } else if (this.isWhitespace(this.ch)) { + } else if (this.isWhitespace(ch)) { this.index++; - continue; } else { - var ch2 = this.ch + this.peek(); + var ch2 = ch + this.peek(); var ch3 = ch2 + this.peek(2); - var fn = OPERATORS[this.ch]; - var fn2 = OPERATORS[ch2]; - var fn3 = OPERATORS[ch3]; - if (fn3) { - this.tokens.push({index: this.index, text: ch3, fn: fn3}); - this.index += 3; - } else if (fn2) { - this.tokens.push({index: this.index, text: ch2, fn: fn2}); - this.index += 2; - } else if (fn) { - this.tokens.push({ - index: this.index, - text: this.ch, - fn: fn, - json: (this.was('[,:') && this.is('+-')) - }); - this.index += 1; + var op1 = OPERATORS[ch]; + var op2 = OPERATORS[ch2]; + var op3 = OPERATORS[ch3]; + if (op1 || op2 || op3) { + var token = op3 ? ch3 : (op2 ? ch2 : ch); + this.tokens.push({index: this.index, text: token, operator: true}); + this.index += token.length; } else { this.throwError('Unexpected next character ', this.index, this.index + 1); } } - this.lastCh = this.ch; } return this.tokens; }, - is: function(chars) { - return chars.indexOf(this.ch) !== -1; - }, - - was: function(chars) { - return chars.indexOf(this.lastCh) !== -1; + is: function(ch, chars) { + return chars.indexOf(ch) !== -1; }, peek: function(i) { @@ -9988,19 +14916,55 @@ }, isNumber: function(ch) { - return ('0' <= ch && ch <= '9'); + return ('0' <= ch && ch <= '9') && typeof ch === 'string'; }, isWhitespace: function(ch) { // IE treats non-breaking space as \u00A0 return (ch === ' ' || ch === '\r' || ch === '\t' || - ch === '\n' || ch === '\v' || ch === '\u00A0'); + ch === '\n' || ch === '\v' || ch === '\u00A0'); + }, + + isIdentifierStart: function(ch) { + return this.options.isIdentifierStart ? + this.options.isIdentifierStart(ch, this.codePointAt(ch)) : + this.isValidIdentifierStart(ch); }, - isIdent: function(ch) { + isValidIdentifierStart: function(ch) { return ('a' <= ch && ch <= 'z' || - 'A' <= ch && ch <= 'Z' || - '_' === ch || ch === '$'); + 'A' <= ch && ch <= 'Z' || + '_' === ch || ch === '$'); + }, + + isIdentifierContinue: function(ch) { + return this.options.isIdentifierContinue ? + this.options.isIdentifierContinue(ch, this.codePointAt(ch)) : + this.isValidIdentifierContinue(ch); + }, + + isValidIdentifierContinue: function(ch, cp) { + return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch); + }, + + codePointAt: function(ch) { + if (ch.length === 1) return ch.charCodeAt(0); + // eslint-disable-next-line no-bitwise + return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00; + }, + + peekMultichar: function() { + var ch = this.text.charAt(this.index); + var peek = this.peek(); + if (!peek) { + return ch; + } + var cp1 = ch.charCodeAt(0); + var cp2 = peek.charCodeAt(0); + if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) { + return ch + peek; + } + return ch; }, isExpOperator: function(ch) { @@ -10021,19 +14985,19 @@ var start = this.index; while (this.index < this.text.length) { var ch = lowercase(this.text.charAt(this.index)); - if (ch == '.' || this.isNumber(ch)) { + if (ch === '.' || this.isNumber(ch)) { number += ch; } else { var peekCh = this.peek(); - if (ch == 'e' && this.isExpOperator(peekCh)) { + if (ch === 'e' && this.isExpOperator(peekCh)) { number += ch; } else if (this.isExpOperator(ch) && peekCh && this.isNumber(peekCh) && - number.charAt(number.length - 1) == 'e') { + number.charAt(number.length - 1) === 'e') { number += ch; } else if (this.isExpOperator(ch) && (!peekCh || !this.isNumber(peekCh)) && - number.charAt(number.length - 1) == 'e') { + number.charAt(number.length - 1) === 'e') { this.throwError('Invalid exponent'); } else { break; @@ -10041,89 +15005,30 @@ } this.index++; } - number = 1 * number; this.tokens.push({ index: start, text: number, - json: true, - fn: function() { return number; } + constant: true, + value: Number(number) }); }, readIdent: function() { - var parser = this; - - var ident = ''; var start = this.index; - - var lastDot, peekIndex, methodName, ch; - + this.index += this.peekMultichar().length; while (this.index < this.text.length) { - ch = this.text.charAt(this.index); - if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) { - if (ch === '.') lastDot = this.index; - ident += ch; - } else { + var ch = this.peekMultichar(); + if (!this.isIdentifierContinue(ch)) { break; } - this.index++; - } - - //check if this is not a method invocation and if it is back out to last dot - if (lastDot) { - peekIndex = this.index; - while (peekIndex < this.text.length) { - ch = this.text.charAt(peekIndex); - if (ch === '(') { - methodName = ident.substr(lastDot - start + 1); - ident = ident.substr(0, lastDot - start); - this.index = peekIndex; - break; - } - if (this.isWhitespace(ch)) { - peekIndex++; - } else { - break; - } - } + this.index += ch.length; } - - - var token = { + this.tokens.push({ index: start, - text: ident - }; - - // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn - if (OPERATORS.hasOwnProperty(ident)) { - token.fn = OPERATORS[ident]; - token.json = OPERATORS[ident]; - } else { - var getter = getterFn(ident, this.options, this.text); - token.fn = extend(function(self, locals) { - return (getter(self, locals)); - }, { - assign: function(self, value) { - return setter(self, ident, value, parser.text, parser.options); - } - }); - } - - this.tokens.push(token); - - if (methodName) { - this.tokens.push({ - index:lastDot, - text: '.', - json: false - }); - this.tokens.push({ - index: lastDot + 1, - text: methodName, - json: false - }); - } - }, + text: this.text.slice(start, this.index), + identifier: true + }); + }, readString: function(quote) { var start = this.index; @@ -10137,17 +15042,14 @@ if (escape) { if (ch === 'u') { var hex = this.text.substring(this.index + 1, this.index + 5); - if (!hex.match(/[\da-f]{4}/i)) + if (!hex.match(/[\da-f]{4}/i)) { this.throwError('Invalid unicode escape [\\u' + hex + ']'); + } this.index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; - if (rep) { - string += rep; - } else { - string += ch; - } + string = string + (rep || ch); } escape = false; } else if (ch === '\\') { @@ -10157,9 +15059,8 @@ this.tokens.push({ index: start, text: rawString, - string: string, - json: true, - fn: function() { return string; } + constant: true, + value: string }); return; } else { @@ -10171,219 +15072,66 @@ } }; - - /** - * @constructor - */ - var Parser = function (lexer, $filter, options) { + var AST = function AST(lexer, options) { this.lexer = lexer; - this.$filter = $filter; this.options = options; }; - Parser.ZERO = extend(function () { - return 0; - }, { - constant: true - }); - - Parser.prototype = { - constructor: Parser, - - parse: function (text, json) { + AST.Program = 'Program'; + AST.ExpressionStatement = 'ExpressionStatement'; + AST.AssignmentExpression = 'AssignmentExpression'; + AST.ConditionalExpression = 'ConditionalExpression'; + AST.LogicalExpression = 'LogicalExpression'; + AST.BinaryExpression = 'BinaryExpression'; + AST.UnaryExpression = 'UnaryExpression'; + AST.CallExpression = 'CallExpression'; + AST.MemberExpression = 'MemberExpression'; + AST.Identifier = 'Identifier'; + AST.Literal = 'Literal'; + AST.ArrayExpression = 'ArrayExpression'; + AST.Property = 'Property'; + AST.ObjectExpression = 'ObjectExpression'; + AST.ThisExpression = 'ThisExpression'; + AST.LocalsExpression = 'LocalsExpression'; + +// Internal use only + AST.NGValueParameter = 'NGValueParameter'; + + AST.prototype = { + ast: function(text) { this.text = text; - - //TODO(i): strip all the obsolte json stuff from this file - this.json = json; - this.tokens = this.lexer.lex(text); - if (json) { - // The extra level of aliasing is here, just in case the lexer misses something, so that - // we prevent any accidental execution in JSON. - this.assignment = this.logicalOR; - - this.functionCall = - this.fieldAccess = - this.objectIndex = - this.filterChain = function() { - this.throwError('is not valid json', {text: text, index: 0}); - }; - } - - var value = json ? this.primary() : this.statements(); + var value = this.program(); if (this.tokens.length !== 0) { this.throwError('is an unexpected token', this.tokens[0]); } - value.literal = !!value.literal; - value.constant = !!value.constant; - return value; }, - primary: function () { - var primary; - if (this.expect('(')) { - primary = this.filterChain(); - this.consume(')'); - } else if (this.expect('[')) { - primary = this.arrayDeclaration(); - } else if (this.expect('{')) { - primary = this.object(); - } else { - var token = this.expect(); - primary = token.fn; - if (!primary) { - this.throwError('not a primary expression', token); - } - if (token.json) { - primary.constant = true; - primary.literal = true; - } - } - - var next, context; - while ((next = this.expect('(', '[', '.'))) { - if (next.text === '(') { - primary = this.functionCall(primary, context); - context = null; - } else if (next.text === '[') { - context = primary; - primary = this.objectIndex(primary); - } else if (next.text === '.') { - context = primary; - primary = this.fieldAccess(primary); - } else { - this.throwError('IMPOSSIBLE'); - } - } - return primary; - }, - - throwError: function(msg, token) { - throw $parseMinErr('syntax', - 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', - token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); - }, - - peekToken: function() { - if (this.tokens.length === 0) - throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); - return this.tokens[0]; - }, - - peek: function(e1, e2, e3, e4) { - if (this.tokens.length > 0) { - var token = this.tokens[0]; - var t = token.text; - if (t === e1 || t === e2 || t === e3 || t === e4 || - (!e1 && !e2 && !e3 && !e4)) { - return token; - } - } - return false; - }, - - expect: function(e1, e2, e3, e4){ - var token = this.peek(e1, e2, e3, e4); - if (token) { - if (this.json && !token.json) { - this.throwError('is not valid json', token); - } - this.tokens.shift(); - return token; - } - return false; - }, - - consume: function(e1){ - if (!this.expect(e1)) { - this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); - } - }, - - unaryFn: function(fn, right) { - return extend(function(self, locals) { - return fn(self, locals, right); - }, { - constant:right.constant - }); - }, - - ternaryFn: function(left, middle, right){ - return extend(function(self, locals){ - return left(self, locals) ? middle(self, locals) : right(self, locals); - }, { - constant: left.constant && middle.constant && right.constant - }); - }, - - binaryFn: function(left, fn, right) { - return extend(function(self, locals) { - return fn(self, locals, left, right); - }, { - constant:left.constant && right.constant - }); - }, - - statements: function() { - var statements = []; + program: function() { + var body = []; while (true) { if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) - statements.push(this.filterChain()); + body.push(this.expressionStatement()); if (!this.expect(';')) { - // optimize for the common case where there is only one statement. - // TODO(size): maybe we should not support multiple statements? - return (statements.length === 1) - ? statements[0] - : function(self, locals) { - var value; - for (var i = 0; i < statements.length; i++) { - var statement = statements[i]; - if (statement) { - value = statement(self, locals); - } - } - return value; - }; + return { type: AST.Program, body: body}; } } }, - filterChain: function() { - var left = this.expression(); - var token; - while (true) { - if ((token = this.expect('|'))) { - left = this.binaryFn(left, token.fn, this.filter()); - } else { - return left; - } - } + expressionStatement: function() { + return { type: AST.ExpressionStatement, expression: this.filterChain() }; }, - filter: function() { - var token = this.expect(); - var fn = this.$filter(token.text); - var argsFn = []; - while (true) { - if ((token = this.expect(':'))) { - argsFn.push(this.expression()); - } else { - var fnInvoke = function(self, locals, input) { - var args = [input]; - for (var i = 0; i < argsFn.length; i++) { - args.push(argsFn[i](self, locals)); - } - return fn.apply(self, args); - }; - return function() { - return fnInvoke; - }; - } + filterChain: function() { + var left = this.expression(); + while (this.expect('|')) { + left = this.filter(left); } + return left; }, expression: function() { @@ -10391,55 +15139,43 @@ }, assignment: function() { - var left = this.ternary(); - var right; - var token; - if ((token = this.expect('='))) { - if (!left.assign) { - this.throwError('implies assignment but [' + - this.text.substring(0, token.index) + '] can not be assigned to', token); - } - right = this.ternary(); - return function(scope, locals) { - return left.assign(scope, right(scope, locals), locals); - }; + var result = this.ternary(); + if (this.expect('=')) { + if (!isAssignable(result)) { + throw $parseMinErr('lval', 'Trying to assign a value to a non l-value'); + } + + result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='}; } - return left; + return result; }, ternary: function() { - var left = this.logicalOR(); - var middle; - var token; - if ((token = this.expect('?'))) { - middle = this.ternary(); - if ((token = this.expect(':'))) { - return this.ternaryFn(left, middle, this.ternary()); - } else { - this.throwError('expected :', token); + var test = this.logicalOR(); + var alternate; + var consequent; + if (this.expect('?')) { + alternate = this.expression(); + if (this.consume(':')) { + consequent = this.expression(); + return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent}; } - } else { - return left; } + return test; }, logicalOR: function() { var left = this.logicalAND(); - var token; - while (true) { - if ((token = this.expect('||'))) { - left = this.binaryFn(left, token.fn, this.logicalAND()); - } else { - return left; - } + while (this.expect('||')) { + left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() }; } + return left; }, logicalAND: function() { var left = this.equality(); - var token; - if ((token = this.expect('&&'))) { - left = this.binaryFn(left, token.fn, this.logicalAND()); + while (this.expect('&&')) { + left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()}; } return left; }, @@ -10447,8 +15183,8 @@ equality: function() { var left = this.relational(); var token; - if ((token = this.expect('==','!=','===','!=='))) { - left = this.binaryFn(left, token.fn, this.equality()); + while ((token = this.expect('==','!=','===','!=='))) { + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() }; } return left; }, @@ -10456,8 +15192,8 @@ relational: function() { var left = this.additive(); var token; - if ((token = this.expect('<', '>', '<=', '>='))) { - left = this.binaryFn(left, token.fn, this.relational()); + while ((token = this.expect('<', '>', '<=', '>='))) { + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() }; } return left; }, @@ -10466,7 +15202,7 @@ var left = this.multiplicative(); var token; while ((token = this.expect('+','-'))) { - left = this.binaryFn(left, token.fn, this.multiplicative()); + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() }; } return left; }, @@ -10475,9029 +15211,15853 @@ var left = this.unary(); var token; while ((token = this.expect('*','/','%'))) { - left = this.binaryFn(left, token.fn, this.unary()); + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() }; } return left; }, unary: function() { var token; - if (this.expect('+')) { - return this.primary(); - } else if ((token = this.expect('-'))) { - return this.binaryFn(Parser.ZERO, token.fn, this.unary()); - } else if ((token = this.expect('!'))) { - return this.unaryFn(token.fn, this.unary()); + if ((token = this.expect('+', '-', '!'))) { + return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() }; } else { return this.primary(); } }, - fieldAccess: function(object) { - var parser = this; - var field = this.expect().text; - var getter = getterFn(field, this.options, this.text); + primary: function() { + var primary; + if (this.expect('(')) { + primary = this.filterChain(); + this.consume(')'); + } else if (this.expect('[')) { + primary = this.arrayDeclaration(); + } else if (this.expect('{')) { + primary = this.object(); + } else if (this.selfReferential.hasOwnProperty(this.peek().text)) { + primary = copy(this.selfReferential[this.consume().text]); + } else if (this.options.literals.hasOwnProperty(this.peek().text)) { + primary = { type: AST.Literal, value: this.options.literals[this.consume().text]}; + } else if (this.peek().identifier) { + primary = this.identifier(); + } else if (this.peek().constant) { + primary = this.constant(); + } else { + this.throwError('not a primary expression', this.peek()); + } - return extend(function(scope, locals, self) { - return getter(self || object(scope, locals)); - }, { - assign: function(scope, value, locals) { - return setter(object(scope, locals), field, value, parser.text, parser.options); + var next; + while ((next = this.expect('(', '[', '.'))) { + if (next.text === '(') { + primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() }; + this.consume(')'); + } else if (next.text === '[') { + primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true }; + this.consume(']'); + } else if (next.text === '.') { + primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false }; + } else { + this.throwError('IMPOSSIBLE'); } - }); + } + return primary; }, - objectIndex: function(obj) { - var parser = this; + filter: function(baseExpression) { + var args = [baseExpression]; + var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true}; - var indexFn = this.expression(); - this.consume(']'); + while (this.expect(':')) { + args.push(this.expression()); + } - return extend(function(self, locals) { - var o = obj(self, locals), - i = indexFn(self, locals), - v, p; - - if (!o) return undefined; - v = ensureSafeObject(o[i], parser.text); - if (v && v.then && parser.options.unwrapPromises) { - p = v; - if (!('$$v' in v)) { - p.$$v = undefined; - p.then(function(val) { p.$$v = val; }); - } - v = v.$$v; - } - return v; - }, { - assign: function(self, value, locals) { - var key = indexFn(self, locals); - // prevent overwriting of Function.constructor which would break ensureSafeObject check - var safe = ensureSafeObject(obj(self, locals), parser.text); - return safe[key] = value; - } - }); + return result; }, - functionCall: function(fn, contextGetter) { - var argsFn = []; + parseArguments: function() { + var args = []; if (this.peekToken().text !== ')') { do { - argsFn.push(this.expression()); + args.push(this.filterChain()); } while (this.expect(',')); } - this.consume(')'); - - var parser = this; - - return function(scope, locals) { - var args = []; - var context = contextGetter ? contextGetter(scope, locals) : scope; - - for (var i = 0; i < argsFn.length; i++) { - args.push(argsFn[i](scope, locals)); - } - var fnPtr = fn(scope, locals, context) || noop; - - ensureSafeObject(context, parser.text); - ensureSafeObject(fnPtr, parser.text); + return args; + }, - // IE stupidity! (IE doesn't have apply for some native functions) - var v = fnPtr.apply - ? fnPtr.apply(context, args) - : fnPtr(args[0], args[1], args[2], args[3], args[4]); + identifier: function() { + var token = this.consume(); + if (!token.identifier) { + this.throwError('is not a valid identifier', token); + } + return { type: AST.Identifier, name: token.text }; + }, - return ensureSafeObject(v, parser.text); - }; + constant: function() { + // TODO check that it is a constant + return { type: AST.Literal, value: this.consume().value }; }, - // This is used with json array declaration - arrayDeclaration: function () { - var elementFns = []; - var allConstant = true; + arrayDeclaration: function() { + var elements = []; if (this.peekToken().text !== ']') { do { if (this.peek(']')) { // Support trailing commas per ES5.1. break; } - var elementFn = this.expression(); - elementFns.push(elementFn); - if (!elementFn.constant) { - allConstant = false; - } + elements.push(this.expression()); } while (this.expect(',')); } this.consume(']'); - return extend(function(self, locals) { - var array = []; - for (var i = 0; i < elementFns.length; i++) { - array.push(elementFns[i](self, locals)); - } - return array; - }, { - literal: true, - constant: allConstant - }); + return { type: AST.ArrayExpression, elements: elements }; }, - object: function () { - var keyValues = []; - var allConstant = true; + object: function() { + var properties = [], property; if (this.peekToken().text !== '}') { do { if (this.peek('}')) { // Support trailing commas per ES5.1. break; } - var token = this.expect(), - key = token.string || token.text; - this.consume(':'); - var value = this.expression(); - keyValues.push({key: key, value: value}); - if (!value.constant) { - allConstant = false; + property = {type: AST.Property, kind: 'init'}; + if (this.peek().constant) { + property.key = this.constant(); + property.computed = false; + this.consume(':'); + property.value = this.expression(); + } else if (this.peek().identifier) { + property.key = this.identifier(); + property.computed = false; + if (this.peek(':')) { + this.consume(':'); + property.value = this.expression(); + } else { + property.value = property.key; + } + } else if (this.peek('[')) { + this.consume('['); + property.key = this.expression(); + this.consume(']'); + property.computed = true; + this.consume(':'); + property.value = this.expression(); + } else { + this.throwError('invalid key', this.peek()); } + properties.push(property); } while (this.expect(',')); } this.consume('}'); - return extend(function(self, locals) { - var object = {}; - for (var i = 0; i < keyValues.length; i++) { - var keyValue = keyValues[i]; - object[keyValue.key] = keyValue.value(self, locals); - } - return object; - }, { - literal: true, - constant: allConstant - }); - } - }; + return {type: AST.ObjectExpression, properties: properties }; + }, + throwError: function(msg, token) { + throw $parseMinErr('syntax', + 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', + token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); + }, -////////////////////////////////////////////////// -// Parser helper functions -////////////////////////////////////////////////// + consume: function(e1) { + if (this.tokens.length === 0) { + throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); + } - function setter(obj, path, setValue, fullExp, options) { - //needed? - options = options || {}; + var token = this.expect(e1); + if (!token) { + this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); + } + return token; + }, - var element = path.split('.'), key; - for (var i = 0; element.length > 1; i++) { - key = ensureSafeMemberName(element.shift(), fullExp); - var propertyObj = obj[key]; - if (!propertyObj) { - propertyObj = {}; - obj[key] = propertyObj; + peekToken: function() { + if (this.tokens.length === 0) { + throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); } - obj = propertyObj; - if (obj.then && options.unwrapPromises) { - promiseWarning(fullExp); - if (!("$$v" in obj)) { - (function(promise) { - promise.then(function(val) { promise.$$v = val; }); } - )(obj); - } - if (obj.$$v === undefined) { - obj.$$v = {}; + return this.tokens[0]; + }, + + peek: function(e1, e2, e3, e4) { + return this.peekAhead(0, e1, e2, e3, e4); + }, + + peekAhead: function(i, e1, e2, e3, e4) { + if (this.tokens.length > i) { + var token = this.tokens[i]; + var t = token.text; + if (t === e1 || t === e2 || t === e3 || t === e4 || + (!e1 && !e2 && !e3 && !e4)) { + return token; } - obj = obj.$$v; } + return false; + }, + + expect: function(e1, e2, e3, e4) { + var token = this.peek(e1, e2, e3, e4); + if (token) { + this.tokens.shift(); + return token; + } + return false; + }, + + selfReferential: { + 'this': {type: AST.ThisExpression }, + '$locals': {type: AST.LocalsExpression } } - key = ensureSafeMemberName(element.shift(), fullExp); - obj[key] = setValue; - return setValue; + }; + + function ifDefined(v, d) { + return typeof v !== 'undefined' ? v : d; + } + + function plusFn(l, r) { + if (typeof l === 'undefined') return r; + if (typeof r === 'undefined') return l; + return l + r; } - var getterFnCache = {}; + function isStateless($filter, filterName) { + var fn = $filter(filterName); + return !fn.$stateful; + } - /** - * Implementation of the "Black Hole" variant from: - * - http://jsperf.com/angularjs-parse-getter/4 - * - http://jsperf.com/path-evaluation-simplified/7 - */ - function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) { - ensureSafeMemberName(key0, fullExp); - ensureSafeMemberName(key1, fullExp); - ensureSafeMemberName(key2, fullExp); - ensureSafeMemberName(key3, fullExp); - ensureSafeMemberName(key4, fullExp); + var PURITY_ABSOLUTE = 1; + var PURITY_RELATIVE = 2; - return !options.unwrapPromises - ? function cspSafeGetter(scope, locals) { - var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; +// Detect nodes which could depend on non-shallow state of objects + function isPure(node, parentIsPure) { + switch (node.type) { + // Computed members might invoke a stateful toString() + case AST.MemberExpression: + if (node.computed) { + return false; + } + break; - if (pathVal == null) return pathVal; - pathVal = pathVal[key0]; + // Unary always convert to primative + case AST.UnaryExpression: + return PURITY_ABSOLUTE; - if (!key1) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key1]; + // The binary + operator can invoke a stateful toString(). + case AST.BinaryExpression: + return node.operator !== '+' ? PURITY_ABSOLUTE : false; + + // Functions / filters probably read state from within objects + case AST.CallExpression: + return false; + } - if (!key2) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key2]; + return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure; + } - if (!key3) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key3]; + function findConstantAndWatchExpressions(ast, $filter, parentIsPure) { + var allConstants; + var argsToWatch; + var isStatelessFilter; - if (!key4) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key4]; + var astIsPure = ast.isPure = isPure(ast, parentIsPure); - return pathVal; + switch (ast.type) { + case AST.Program: + allConstants = true; + forEach(ast.body, function(expr) { + findConstantAndWatchExpressions(expr.expression, $filter, astIsPure); + allConstants = allConstants && expr.expression.constant; + }); + ast.constant = allConstants; + break; + case AST.Literal: + ast.constant = true; + ast.toWatch = []; + break; + case AST.UnaryExpression: + findConstantAndWatchExpressions(ast.argument, $filter, astIsPure); + ast.constant = ast.argument.constant; + ast.toWatch = ast.argument.toWatch; + break; + case AST.BinaryExpression: + findConstantAndWatchExpressions(ast.left, $filter, astIsPure); + findConstantAndWatchExpressions(ast.right, $filter, astIsPure); + ast.constant = ast.left.constant && ast.right.constant; + ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch); + break; + case AST.LogicalExpression: + findConstantAndWatchExpressions(ast.left, $filter, astIsPure); + findConstantAndWatchExpressions(ast.right, $filter, astIsPure); + ast.constant = ast.left.constant && ast.right.constant; + ast.toWatch = ast.constant ? [] : [ast]; + break; + case AST.ConditionalExpression: + findConstantAndWatchExpressions(ast.test, $filter, astIsPure); + findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure); + findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure); + ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant; + ast.toWatch = ast.constant ? [] : [ast]; + break; + case AST.Identifier: + ast.constant = false; + ast.toWatch = [ast]; + break; + case AST.MemberExpression: + findConstantAndWatchExpressions(ast.object, $filter, astIsPure); + if (ast.computed) { + findConstantAndWatchExpressions(ast.property, $filter, astIsPure); + } + ast.constant = ast.object.constant && (!ast.computed || ast.property.constant); + ast.toWatch = ast.constant ? [] : [ast]; + break; + case AST.CallExpression: + isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false; + allConstants = isStatelessFilter; + argsToWatch = []; + forEach(ast.arguments, function(expr) { + findConstantAndWatchExpressions(expr, $filter, astIsPure); + allConstants = allConstants && expr.constant; + argsToWatch.push.apply(argsToWatch, expr.toWatch); + }); + ast.constant = allConstants; + ast.toWatch = isStatelessFilter ? argsToWatch : [ast]; + break; + case AST.AssignmentExpression: + findConstantAndWatchExpressions(ast.left, $filter, astIsPure); + findConstantAndWatchExpressions(ast.right, $filter, astIsPure); + ast.constant = ast.left.constant && ast.right.constant; + ast.toWatch = [ast]; + break; + case AST.ArrayExpression: + allConstants = true; + argsToWatch = []; + forEach(ast.elements, function(expr) { + findConstantAndWatchExpressions(expr, $filter, astIsPure); + allConstants = allConstants && expr.constant; + argsToWatch.push.apply(argsToWatch, expr.toWatch); + }); + ast.constant = allConstants; + ast.toWatch = argsToWatch; + break; + case AST.ObjectExpression: + allConstants = true; + argsToWatch = []; + forEach(ast.properties, function(property) { + findConstantAndWatchExpressions(property.value, $filter, astIsPure); + allConstants = allConstants && property.value.constant; + argsToWatch.push.apply(argsToWatch, property.value.toWatch); + if (property.computed) { + //`{[key]: value}` implicitly does `key.toString()` which may be non-pure + findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false); + allConstants = allConstants && property.key.constant; + argsToWatch.push.apply(argsToWatch, property.key.toWatch); + } + }); + ast.constant = allConstants; + ast.toWatch = argsToWatch; + break; + case AST.ThisExpression: + ast.constant = false; + ast.toWatch = []; + break; + case AST.LocalsExpression: + ast.constant = false; + ast.toWatch = []; + break; } - : function cspSafePromiseEnabledGetter(scope, locals) { - var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, - promise; - - if (pathVal == null) return pathVal; - - pathVal = pathVal[key0]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - - if (!key1) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key1]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - - if (!key2) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key2]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - - if (!key3) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key3]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - - if (!key4) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key4]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - return pathVal; - }; } - function simpleGetterFn1(key0, fullExp) { - ensureSafeMemberName(key0, fullExp); + function getInputs(body) { + if (body.length !== 1) return; + var lastExpression = body[0].expression; + var candidate = lastExpression.toWatch; + if (candidate.length !== 1) return candidate; + return candidate[0] !== lastExpression ? candidate : undefined; + } - return function simpleGetterFn1(scope, locals) { - if (scope == null) return undefined; - return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0]; - }; + function isAssignable(ast) { + return ast.type === AST.Identifier || ast.type === AST.MemberExpression; } - function simpleGetterFn2(key0, key1, fullExp) { - ensureSafeMemberName(key0, fullExp); - ensureSafeMemberName(key1, fullExp); + function assignableAST(ast) { + if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) { + return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='}; + } + } - return function simpleGetterFn2(scope, locals) { - if (scope == null) return undefined; - scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0]; - return scope == null ? undefined : scope[key1]; - }; + function isLiteral(ast) { + return ast.body.length === 0 || + ast.body.length === 1 && ( + ast.body[0].expression.type === AST.Literal || + ast.body[0].expression.type === AST.ArrayExpression || + ast.body[0].expression.type === AST.ObjectExpression); } - function getterFn(path, options, fullExp) { - // Check whether the cache has this getter already. - // We can use hasOwnProperty directly on the cache because we ensure, - // see below, that the cache never stores a path called 'hasOwnProperty' - if (getterFnCache.hasOwnProperty(path)) { - return getterFnCache[path]; - } + function isConstant(ast) { + return ast.constant; + } - var pathKeys = path.split('.'), - pathKeysLength = pathKeys.length, - fn; - - // When we have only 1 or 2 tokens, use optimized special case closures. - // http://jsperf.com/angularjs-parse-getter/6 - if (!options.unwrapPromises && pathKeysLength === 1) { - fn = simpleGetterFn1(pathKeys[0], fullExp); - } else if (!options.unwrapPromises && pathKeysLength === 2) { - fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp); - } else if (options.csp) { - if (pathKeysLength < 6) { - fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, - options); - } else { - fn = function(scope, locals) { - var i = 0, val; - do { - val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], - pathKeys[i++], fullExp, options)(scope, locals); + function ASTCompiler($filter) { + this.$filter = $filter; + } - locals = undefined; // clear after first iteration - scope = val; - } while (i < pathKeysLength); - return val; - }; + ASTCompiler.prototype = { + compile: function(ast) { + var self = this; + this.state = { + nextId: 0, + filters: {}, + fn: {vars: [], body: [], own: {}}, + assign: {vars: [], body: [], own: {}}, + inputs: [] + }; + findConstantAndWatchExpressions(ast, self.$filter); + var extra = ''; + var assignable; + this.stage = 'assign'; + if ((assignable = assignableAST(ast))) { + this.state.computing = 'assign'; + var result = this.nextId(); + this.recurse(assignable, result); + this.return_(result); + extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l'); } - } else { - var code = 'var p;\n'; - forEach(pathKeys, function(key, index) { - ensureSafeMemberName(key, fullExp); - code += 'if(s == null) return undefined;\n' + - 's='+ (index - // we simply dereference 's' on any .dot notation - ? 's' - // but if we are first then we check locals first, and if so read it first - : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + - (options.unwrapPromises - ? 'if (s && s.then) {\n' + - ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' + - ' if (!("$$v" in s)) {\n' + - ' p=s;\n' + - ' p.$$v = undefined;\n' + - ' p.then(function(v) {p.$$v=v;});\n' + - '}\n' + - ' s=s.$$v\n' + - '}\n' - : ''); + var toWatch = getInputs(ast.body); + self.stage = 'inputs'; + forEach(toWatch, function(watch, key) { + var fnKey = 'fn' + key; + self.state[fnKey] = {vars: [], body: [], own: {}}; + self.state.computing = fnKey; + var intoId = self.nextId(); + self.recurse(watch, intoId); + self.return_(intoId); + self.state.inputs.push({name: fnKey, isPure: watch.isPure}); + watch.watchId = key; }); - code += 'return s;'; - - /* jshint -W054 */ - var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning - /* jshint +W054 */ - evaledFnGetter.toString = valueFn(code); - fn = options.unwrapPromises ? function(scope, locals) { - return evaledFnGetter(scope, locals, promiseWarning); - } : evaledFnGetter; - } + this.state.computing = 'fn'; + this.stage = 'main'; + this.recurse(ast); + var fnString = + // The build and minification steps remove the string "use strict" from the code, but this is done using a regex. + // This is a workaround for this until we do a better job at only removing the prefix only when we should. + '"' + this.USE + ' ' + this.STRICT + '";\n' + + this.filterPrefix() + + 'var fn=' + this.generateFunction('fn', 's,l,a,i') + + extra + + this.watchFns() + + 'return fn;'; + + // eslint-disable-next-line no-new-func + var fn = (new Function('$filter', + 'getStringValue', + 'ifDefined', + 'plus', + fnString))( + this.$filter, + getStringValue, + ifDefined, + plusFn); + this.state = this.stage = undefined; + return fn; + }, - // Only cache the value if it's not going to mess up the cache object - // This is more performant that using Object.prototype.hasOwnProperty.call - if (path !== 'hasOwnProperty') { - getterFnCache[path] = fn; - } - return fn; - } + USE: 'use', -/////////////////////////////////// + STRICT: 'strict', - /** - * @ngdoc service - * @name $parse - * @kind function - * - * @description - * - * Converts Angular {@link guide/expression expression} into a function. - * - * ```js - * var getter = $parse('user.name'); - * var setter = getter.assign; - * var context = {user:{name:'angular'}}; - * var locals = {user:{name:'local'}}; - * - * expect(getter(context)).toEqual('angular'); - * setter(context, 'newValue'); - * expect(context.user.name).toEqual('newValue'); - * expect(getter(context, locals)).toEqual('local'); - * ``` - * - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - * - * The returned function also has the following properties: - * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript - * literal. - * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript - * constant literals. - * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be - * set to a function to change its value on the given context. - * - */ + watchFns: function() { + var result = []; + var inputs = this.state.inputs; + var self = this; + forEach(inputs, function(input) { + result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's')); + if (input.isPure) { + result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';'); + } + }); + if (inputs.length) { + result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];'); + } + return result.join(''); + }, + generateFunction: function(name, params) { + return 'function(' + params + '){' + + this.varsPrefix(name) + + this.body(name) + + '};'; + }, - /** - * @ngdoc provider - * @name $parseProvider - * @function - * - * @description - * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} - * service. - */ - function $ParseProvider() { - var cache = {}; + filterPrefix: function() { + var parts = []; + var self = this; + forEach(this.state.filters, function(id, filter) { + parts.push(id + '=$filter(' + self.escape(filter) + ')'); + }); + if (parts.length) return 'var ' + parts.join(',') + ';'; + return ''; + }, - var $parseOptions = { - csp: false, - unwrapPromises: false, - logPromiseWarnings: true - }; + varsPrefix: function(section) { + return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : ''; + }, + body: function(section) { + return this.state[section].body.join(''); + }, - /** - * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. - * - * @ngdoc method - * @name $parseProvider#unwrapPromises - * @description - * - * **This feature is deprecated, see deprecation notes below for more info** - * - * If set to true (default is false), $parse will unwrap promises automatically when a promise is - * found at any part of the expression. In other words, if set to true, the expression will always - * result in a non-promise value. - * - * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled, - * the fulfillment value is used in place of the promise while evaluating the expression. - * - * **Deprecation notice** - * - * This is a feature that didn't prove to be wildly useful or popular, primarily because of the - * dichotomy between data access in templates (accessed as raw values) and controller code - * (accessed as promises). - * - * In most code we ended up resolving promises manually in controllers anyway and thus unifying - * the model access there. - * - * Other downsides of automatic promise unwrapping: - * - * - when building components it's often desirable to receive the raw promises - * - adds complexity and slows down expression evaluation - * - makes expression code pre-generation unattractive due to the amount of code that needs to be - * generated - * - makes IDE auto-completion and tool support hard - * - * **Warning Logs** - * - * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a - * promise (to reduce the noise, each expression is logged only once). To disable this logging use - * `$parseProvider.logPromiseWarnings(false)` api. - * - * - * @param {boolean=} value New value. - * @returns {boolean|self} Returns the current setting when used as getter and self if used as - * setter. - */ - this.unwrapPromises = function(value) { - if (isDefined(value)) { - $parseOptions.unwrapPromises = !!value; - return this; + recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { + var left, right, self = this, args, expression, computed; + recursionFn = recursionFn || noop; + if (!skipWatchIdCheck && isDefined(ast.watchId)) { + intoId = intoId || this.nextId(); + this.if_('i', + this.lazyAssign(intoId, this.computedMember('i', ast.watchId)), + this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true) + ); + return; + } + switch (ast.type) { + case AST.Program: + forEach(ast.body, function(expression, pos) { + self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; }); + if (pos !== ast.body.length - 1) { + self.current().body.push(right, ';'); + } else { + self.return_(right); + } + }); + break; + case AST.Literal: + expression = this.escape(ast.value); + this.assign(intoId, expression); + recursionFn(intoId || expression); + break; + case AST.UnaryExpression: + this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; }); + expression = ast.operator + '(' + this.ifDefined(right, 0) + ')'; + this.assign(intoId, expression); + recursionFn(expression); + break; + case AST.BinaryExpression: + this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; }); + this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; }); + if (ast.operator === '+') { + expression = this.plus(left, right); + } else if (ast.operator === '-') { + expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0); + } else { + expression = '(' + left + ')' + ast.operator + '(' + right + ')'; + } + this.assign(intoId, expression); + recursionFn(expression); + break; + case AST.LogicalExpression: + intoId = intoId || this.nextId(); + self.recurse(ast.left, intoId); + self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId)); + recursionFn(intoId); + break; + case AST.ConditionalExpression: + intoId = intoId || this.nextId(); + self.recurse(ast.test, intoId); + self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId)); + recursionFn(intoId); + break; + case AST.Identifier: + intoId = intoId || this.nextId(); + if (nameId) { + nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s'); + nameId.computed = false; + nameId.name = ast.name; + } + self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)), + function() { + self.if_(self.stage === 'inputs' || 's', function() { + if (create && create !== 1) { + self.if_( + self.isNull(self.nonComputedMember('s', ast.name)), + self.lazyAssign(self.nonComputedMember('s', ast.name), '{}')); + } + self.assign(intoId, self.nonComputedMember('s', ast.name)); + }); + }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name)) + ); + recursionFn(intoId); + break; + case AST.MemberExpression: + left = nameId && (nameId.context = this.nextId()) || this.nextId(); + intoId = intoId || this.nextId(); + self.recurse(ast.object, left, undefined, function() { + self.if_(self.notNull(left), function() { + if (ast.computed) { + right = self.nextId(); + self.recurse(ast.property, right); + self.getStringValue(right); + if (create && create !== 1) { + self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}')); + } + expression = self.computedMember(left, right); + self.assign(intoId, expression); + if (nameId) { + nameId.computed = true; + nameId.name = right; + } + } else { + if (create && create !== 1) { + self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}')); + } + expression = self.nonComputedMember(left, ast.property.name); + self.assign(intoId, expression); + if (nameId) { + nameId.computed = false; + nameId.name = ast.property.name; + } + } + }, function() { + self.assign(intoId, 'undefined'); + }); + recursionFn(intoId); + }, !!create); + break; + case AST.CallExpression: + intoId = intoId || this.nextId(); + if (ast.filter) { + right = self.filter(ast.callee.name); + args = []; + forEach(ast.arguments, function(expr) { + var argument = self.nextId(); + self.recurse(expr, argument); + args.push(argument); + }); + expression = right + '(' + args.join(',') + ')'; + self.assign(intoId, expression); + recursionFn(intoId); + } else { + right = self.nextId(); + left = {}; + args = []; + self.recurse(ast.callee, right, left, function() { + self.if_(self.notNull(right), function() { + forEach(ast.arguments, function(expr) { + self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) { + args.push(argument); + }); + }); + if (left.name) { + expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')'; + } else { + expression = right + '(' + args.join(',') + ')'; + } + self.assign(intoId, expression); + }, function() { + self.assign(intoId, 'undefined'); + }); + recursionFn(intoId); + }); + } + break; + case AST.AssignmentExpression: + right = this.nextId(); + left = {}; + this.recurse(ast.left, undefined, left, function() { + self.if_(self.notNull(left.context), function() { + self.recurse(ast.right, right); + expression = self.member(left.context, left.name, left.computed) + ast.operator + right; + self.assign(intoId, expression); + recursionFn(intoId || expression); + }); + }, 1); + break; + case AST.ArrayExpression: + args = []; + forEach(ast.elements, function(expr) { + self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) { + args.push(argument); + }); + }); + expression = '[' + args.join(',') + ']'; + this.assign(intoId, expression); + recursionFn(intoId || expression); + break; + case AST.ObjectExpression: + args = []; + computed = false; + forEach(ast.properties, function(property) { + if (property.computed) { + computed = true; + } + }); + if (computed) { + intoId = intoId || this.nextId(); + this.assign(intoId, '{}'); + forEach(ast.properties, function(property) { + if (property.computed) { + left = self.nextId(); + self.recurse(property.key, left); + } else { + left = property.key.type === AST.Identifier ? + property.key.name : + ('' + property.key.value); + } + right = self.nextId(); + self.recurse(property.value, right); + self.assign(self.member(intoId, left, property.computed), right); + }); + } else { + forEach(ast.properties, function(property) { + self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) { + args.push(self.escape( + property.key.type === AST.Identifier ? property.key.name : + ('' + property.key.value)) + + ':' + expr); + }); + }); + expression = '{' + args.join(',') + '}'; + this.assign(intoId, expression); + } + recursionFn(intoId || expression); + break; + case AST.ThisExpression: + this.assign(intoId, 's'); + recursionFn(intoId || 's'); + break; + case AST.LocalsExpression: + this.assign(intoId, 'l'); + recursionFn(intoId || 'l'); + break; + case AST.NGValueParameter: + this.assign(intoId, 'v'); + recursionFn(intoId || 'v'); + break; + } + }, + + getHasOwnProperty: function(element, property) { + var key = element + '.' + property; + var own = this.current().own; + if (!own.hasOwnProperty(key)) { + own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')'); + } + return own[key]; + }, + + assign: function(id, value) { + if (!id) return; + this.current().body.push(id, '=', value, ';'); + return id; + }, + + filter: function(filterName) { + if (!this.state.filters.hasOwnProperty(filterName)) { + this.state.filters[filterName] = this.nextId(true); + } + return this.state.filters[filterName]; + }, + + ifDefined: function(id, defaultValue) { + return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')'; + }, + + plus: function(left, right) { + return 'plus(' + left + ',' + right + ')'; + }, + + return_: function(id) { + this.current().body.push('return ', id, ';'); + }, + + if_: function(test, alternate, consequent) { + if (test === true) { + alternate(); } else { - return $parseOptions.unwrapPromises; + var body = this.current().body; + body.push('if(', test, '){'); + alternate(); + body.push('}'); + if (consequent) { + body.push('else{'); + consequent(); + body.push('}'); + } } - }; + }, + not: function(expression) { + return '!(' + expression + ')'; + }, - /** - * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. - * - * @ngdoc method - * @name $parseProvider#logPromiseWarnings - * @description - * - * Controls whether Angular should log a warning on any encounter of a promise in an expression. - * - * The default is set to `true`. - * - * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well. - * - * @param {boolean=} value New value. - * @returns {boolean|self} Returns the current setting when used as getter and self if used as - * setter. - */ - this.logPromiseWarnings = function(value) { - if (isDefined(value)) { - $parseOptions.logPromiseWarnings = value; - return this; + isNull: function(expression) { + return expression + '==null'; + }, + + notNull: function(expression) { + return expression + '!=null'; + }, + + nonComputedMember: function(left, right) { + var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/; + var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g; + if (SAFE_IDENTIFIER.test(right)) { + return left + '.' + right; } else { - return $parseOptions.logPromiseWarnings; + return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]'; } - }; + }, + + computedMember: function(left, right) { + return left + '[' + right + ']'; + }, + member: function(left, right, computed) { + if (computed) return this.computedMember(left, right); + return this.nonComputedMember(left, right); + }, - this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) { - $parseOptions.csp = $sniffer.csp; + getStringValue: function(item) { + this.assign(item, 'getStringValue(' + item + ')'); + }, - promiseWarning = function promiseWarningFn(fullExp) { - if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return; - promiseWarningCache[fullExp] = true; - $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' + - 'Automatic unwrapping of promises in Angular expressions is deprecated.'); + lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { + var self = this; + return function() { + self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck); }; + }, - return function(exp) { - var parsedExpression; + lazyAssign: function(id, value) { + var self = this; + return function() { + self.assign(id, value); + }; + }, - switch (typeof exp) { - case 'string': + stringEscapeRegex: /[^ a-zA-Z0-9]/g, - if (cache.hasOwnProperty(exp)) { - return cache[exp]; - } + stringEscapeFn: function(c) { + return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); + }, - var lexer = new Lexer($parseOptions); - var parser = new Parser(lexer, $filter, $parseOptions); - parsedExpression = parser.parse(exp, false); + escape: function(value) { + if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\''; + if (isNumber(value)) return value.toString(); + if (value === true) return 'true'; + if (value === false) return 'false'; + if (value === null) return 'null'; + if (typeof value === 'undefined') return 'undefined'; - if (exp !== 'hasOwnProperty') { - // Only cache the value if it's not going to mess up the cache object - // This is more performant that using Object.prototype.hasOwnProperty.call - cache[exp] = parsedExpression; - } + throw $parseMinErr('esc', 'IMPOSSIBLE'); + }, - return parsedExpression; + nextId: function(skip, init) { + var id = 'v' + (this.state.nextId++); + if (!skip) { + this.current().vars.push(id + (init ? '=' + init : '')); + } + return id; + }, - case 'function': - return exp; + current: function() { + return this.state[this.state.computing]; + } + }; - default: - return noop; - } - }; - }]; + + function ASTInterpreter($filter) { + this.$filter = $filter; } - /** - * @ngdoc service - * @name $q - * @requires $rootScope - * - * @description - * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). - * - * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an - * interface for interacting with an object that represents the result of an action that is - * performed asynchronously, and may or may not be finished at any given point in time. - * - * From the perspective of dealing with error handling, deferred and promise APIs are to - * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. - * - * ```js - * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet` - * // are available in the current lexical scope (they could have been injected or passed in). - * - * function asyncGreet(name) { - * var deferred = $q.defer(); - * - * setTimeout(function() { - * // since this fn executes async in a future turn of the event loop, we need to wrap - * // our code into an $apply call so that the model changes are properly observed. - * scope.$apply(function() { - * deferred.notify('About to greet ' + name + '.'); - * - * if (okToGreet(name)) { - * deferred.resolve('Hello, ' + name + '!'); - * } else { - * deferred.reject('Greeting ' + name + ' is not allowed.'); - * } - * }); - * }, 1000); - * - * return deferred.promise; - * } - * - * var promise = asyncGreet('Robin Hood'); - * promise.then(function(greeting) { - * alert('Success: ' + greeting); - * }, function(reason) { - * alert('Failed: ' + reason); - * }, function(update) { - * alert('Got notification: ' + update); - * }); - * ``` - * - * At first it might not be obvious why this extra complexity is worth the trouble. The payoff - * comes in the way of guarantees that promise and deferred APIs make, see - * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. - * - * Additionally the promise api allows for composition that is very hard to do with the - * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. - * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the - * section on serial or parallel joining of promises. - * - * - * # The Deferred API - * - * A new instance of deferred is constructed by calling `$q.defer()`. - * - * The purpose of the deferred object is to expose the associated Promise instance as well as APIs - * that can be used for signaling the successful or unsuccessful completion, as well as the status - * of the task. - * - * **Methods** - * - * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection - * constructed via `$q.reject`, the promise will be rejected instead. - * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to - * resolving it with a rejection constructed via `$q.reject`. - * - `notify(value)` - provides updates on the status of the promise's execution. This may be called - * multiple times before the promise is either resolved or rejected. - * - * **Properties** - * - * - promise – `{Promise}` – promise object associated with this deferred. - * - * - * # The Promise API - * - * A new promise instance is created when a deferred instance is created and can be retrieved by - * calling `deferred.promise`. - * - * The purpose of the promise object is to allow for interested parties to get access to the result - * of the deferred task when it completes. - * - * **Methods** - * - * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or - * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously - * as soon as the result is available. The callbacks are called with a single argument: the result - * or rejection reason. Additionally, the notify callback may be called zero or more times to - * provide a progress indication, before the promise is resolved or rejected. - * - * This method *returns a new promise* which is resolved or rejected via the return value of the - * `successCallback`, `errorCallback`. It also notifies via the return value of the - * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback - * method. - * - * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` - * - * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, - * but to do so without modifying the final value. This is useful to release resources or do some - * clean-up that needs to be done whether the promise was rejected or resolved. See the [full - * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for - * more information. - * - * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as - * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to - * make your code IE8 and Android 2.x compatible. + ASTInterpreter.prototype = { + compile: function(ast) { + var self = this; + findConstantAndWatchExpressions(ast, self.$filter); + var assignable; + var assign; + if ((assignable = assignableAST(ast))) { + assign = this.recurse(assignable); + } + var toWatch = getInputs(ast.body); + var inputs; + if (toWatch) { + inputs = []; + forEach(toWatch, function(watch, key) { + var input = self.recurse(watch); + input.isPure = watch.isPure; + watch.input = input; + inputs.push(input); + watch.watchId = key; + }); + } + var expressions = []; + forEach(ast.body, function(expression) { + expressions.push(self.recurse(expression.expression)); + }); + var fn = ast.body.length === 0 ? noop : + ast.body.length === 1 ? expressions[0] : + function(scope, locals) { + var lastValue; + forEach(expressions, function(exp) { + lastValue = exp(scope, locals); + }); + return lastValue; + }; + if (assign) { + fn.assign = function(scope, value, locals) { + return assign(scope, locals, value); + }; + } + if (inputs) { + fn.inputs = inputs; + } + return fn; + }, + + recurse: function(ast, context, create) { + var left, right, self = this, args; + if (ast.input) { + return this.inputs(ast.input, ast.watchId); + } + switch (ast.type) { + case AST.Literal: + return this.value(ast.value, context); + case AST.UnaryExpression: + right = this.recurse(ast.argument); + return this['unary' + ast.operator](right, context); + case AST.BinaryExpression: + left = this.recurse(ast.left); + right = this.recurse(ast.right); + return this['binary' + ast.operator](left, right, context); + case AST.LogicalExpression: + left = this.recurse(ast.left); + right = this.recurse(ast.right); + return this['binary' + ast.operator](left, right, context); + case AST.ConditionalExpression: + return this['ternary?:']( + this.recurse(ast.test), + this.recurse(ast.alternate), + this.recurse(ast.consequent), + context + ); + case AST.Identifier: + return self.identifier(ast.name, context, create); + case AST.MemberExpression: + left = this.recurse(ast.object, false, !!create); + if (!ast.computed) { + right = ast.property.name; + } + if (ast.computed) right = this.recurse(ast.property); + return ast.computed ? + this.computedMember(left, right, context, create) : + this.nonComputedMember(left, right, context, create); + case AST.CallExpression: + args = []; + forEach(ast.arguments, function(expr) { + args.push(self.recurse(expr)); + }); + if (ast.filter) right = this.$filter(ast.callee.name); + if (!ast.filter) right = this.recurse(ast.callee, true); + return ast.filter ? + function(scope, locals, assign, inputs) { + var values = []; + for (var i = 0; i < args.length; ++i) { + values.push(args[i](scope, locals, assign, inputs)); + } + var value = right.apply(undefined, values, inputs); + return context ? {context: undefined, name: undefined, value: value} : value; + } : + function(scope, locals, assign, inputs) { + var rhs = right(scope, locals, assign, inputs); + var value; + if (rhs.value != null) { + var values = []; + for (var i = 0; i < args.length; ++i) { + values.push(args[i](scope, locals, assign, inputs)); + } + value = rhs.value.apply(rhs.context, values); + } + return context ? {value: value} : value; + }; + case AST.AssignmentExpression: + left = this.recurse(ast.left, true, 1); + right = this.recurse(ast.right); + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + var rhs = right(scope, locals, assign, inputs); + lhs.context[lhs.name] = rhs; + return context ? {value: rhs} : rhs; + }; + case AST.ArrayExpression: + args = []; + forEach(ast.elements, function(expr) { + args.push(self.recurse(expr)); + }); + return function(scope, locals, assign, inputs) { + var value = []; + for (var i = 0; i < args.length; ++i) { + value.push(args[i](scope, locals, assign, inputs)); + } + return context ? {value: value} : value; + }; + case AST.ObjectExpression: + args = []; + forEach(ast.properties, function(property) { + if (property.computed) { + args.push({key: self.recurse(property.key), + computed: true, + value: self.recurse(property.value) + }); + } else { + args.push({key: property.key.type === AST.Identifier ? + property.key.name : + ('' + property.key.value), + computed: false, + value: self.recurse(property.value) + }); + } + }); + return function(scope, locals, assign, inputs) { + var value = {}; + for (var i = 0; i < args.length; ++i) { + if (args[i].computed) { + value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs); + } else { + value[args[i].key] = args[i].value(scope, locals, assign, inputs); + } + } + return context ? {value: value} : value; + }; + case AST.ThisExpression: + return function(scope) { + return context ? {value: scope} : scope; + }; + case AST.LocalsExpression: + return function(scope, locals) { + return context ? {value: locals} : locals; + }; + case AST.NGValueParameter: + return function(scope, locals, assign) { + return context ? {value: assign} : assign; + }; + } + }, + + 'unary+': function(argument, context) { + return function(scope, locals, assign, inputs) { + var arg = argument(scope, locals, assign, inputs); + if (isDefined(arg)) { + arg = +arg; + } else { + arg = 0; + } + return context ? {value: arg} : arg; + }; + }, + 'unary-': function(argument, context) { + return function(scope, locals, assign, inputs) { + var arg = argument(scope, locals, assign, inputs); + if (isDefined(arg)) { + arg = -arg; + } else { + arg = -0; + } + return context ? {value: arg} : arg; + }; + }, + 'unary!': function(argument, context) { + return function(scope, locals, assign, inputs) { + var arg = !argument(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary+': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + var rhs = right(scope, locals, assign, inputs); + var arg = plusFn(lhs, rhs); + return context ? {value: arg} : arg; + }; + }, + 'binary-': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + var rhs = right(scope, locals, assign, inputs); + var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0); + return context ? {value: arg} : arg; + }; + }, + 'binary*': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary/': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary%': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary===': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary!==': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary==': function(left, right, context) { + return function(scope, locals, assign, inputs) { + // eslint-disable-next-line eqeqeq + var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary!=': function(left, right, context) { + return function(scope, locals, assign, inputs) { + // eslint-disable-next-line eqeqeq + var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary<': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary>': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary<=': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary>=': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary&&': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary||': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'ternary?:': function(test, alternate, consequent, context) { + return function(scope, locals, assign, inputs) { + var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + value: function(value, context) { + return function() { return context ? {context: undefined, name: undefined, value: value} : value; }; + }, + identifier: function(name, context, create) { + return function(scope, locals, assign, inputs) { + var base = locals && (name in locals) ? locals : scope; + if (create && create !== 1 && base && base[name] == null) { + base[name] = {}; + } + var value = base ? base[name] : undefined; + if (context) { + return {context: base, name: name, value: value}; + } else { + return value; + } + }; + }, + computedMember: function(left, right, context, create) { + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + var rhs; + var value; + if (lhs != null) { + rhs = right(scope, locals, assign, inputs); + rhs = getStringValue(rhs); + if (create && create !== 1) { + if (lhs && !(lhs[rhs])) { + lhs[rhs] = {}; + } + } + value = lhs[rhs]; + } + if (context) { + return {context: lhs, name: rhs, value: value}; + } else { + return value; + } + }; + }, + nonComputedMember: function(left, right, context, create) { + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + if (create && create !== 1) { + if (lhs && lhs[right] == null) { + lhs[right] = {}; + } + } + var value = lhs != null ? lhs[right] : undefined; + if (context) { + return {context: lhs, name: right, value: value}; + } else { + return value; + } + }; + }, + inputs: function(input, watchId) { + return function(scope, value, locals, inputs) { + if (inputs) return inputs[watchId]; + return input(scope, value, locals); + }; + } + }; + + /** + * @constructor + */ + function Parser(lexer, $filter, options) { + this.ast = new AST(lexer, options); + this.astCompiler = options.csp ? new ASTInterpreter($filter) : + new ASTCompiler($filter); + } + + Parser.prototype = { + constructor: Parser, + + parse: function(text) { + var ast = this.getAst(text); + var fn = this.astCompiler.compile(ast.ast); + fn.literal = isLiteral(ast.ast); + fn.constant = isConstant(ast.ast); + fn.oneTime = ast.oneTime; + return fn; + }, + + getAst: function(exp) { + var oneTime = false; + exp = exp.trim(); + + if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { + oneTime = true; + exp = exp.substring(2); + } + return { + ast: this.ast.ast(exp), + oneTime: oneTime + }; + } + }; + + function getValueOf(value) { + return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value); + } + +/////////////////////////////////// + + /** + * @ngdoc service + * @name $parse + * @kind function * - * # Chaining promises + * @description * - * Because calling the `then` method of a promise returns a new derived promise, it is easily - * possible to create a chain of promises: + * Converts AngularJS {@link guide/expression expression} into a function. * * ```js - * promiseB = promiseA.then(function(result) { - * return result + 1; - * }); + * var getter = $parse('user.name'); + * var setter = getter.assign; + * var context = {user:{name:'AngularJS'}}; + * var locals = {user:{name:'local'}}; * - * // promiseB will be resolved immediately after promiseA is resolved and its value - * // will be the result of promiseA incremented by 1 + * expect(getter(context)).toEqual('AngularJS'); + * setter(context, 'newValue'); + * expect(context.user.name).toEqual('newValue'); + * expect(getter(context, locals)).toEqual('local'); * ``` * - * It is possible to create chains of any length and since a promise can be resolved with another - * promise (which will defer its resolution further), it is possible to pause/defer resolution of - * the promises at any point in the chain. This makes it possible to implement powerful APIs like - * $http's response interceptors. * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: * - * # Differences between Kris Kowal's Q and $q - * - * There are two main differences: - * - * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation - * mechanism in angular, which means faster propagation of resolution or rejection into your - * models and avoiding unnecessary browser repaints, which would result in flickering UI. - * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains - * all the important functionality needed for common async tasks. + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. * - * # Testing + * The returned function also has the following properties: + * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript + * literal. + * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript + * constant literals. + * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be + * set to a function to change its value on the given context. * - * ```js - * it('should simulate promise', inject(function($q, $rootScope) { - * var deferred = $q.defer(); - * var promise = deferred.promise; - * var resolvedValue; - * - * promise.then(function(value) { resolvedValue = value; }); - * expect(resolvedValue).toBeUndefined(); - * - * // Simulate resolving of promise - * deferred.resolve(123); - * // Note that the 'then' function does not get called synchronously. - * // This is because we want the promise API to always be async, whether or not - * // it got called synchronously or asynchronously. - * expect(resolvedValue).toBeUndefined(); - * - * // Propagate promise resolution to 'then' functions using $apply(). - * $rootScope.$apply(); - * expect(resolvedValue).toEqual(123); - * })); - * ``` */ - function $QProvider() { - - this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { - return qFactory(function(callback) { - $rootScope.$evalAsync(callback); - }, $exceptionHandler); - }]; - } /** - * Constructs a promise manager. + * @ngdoc provider + * @name $parseProvider + * @this * - * @param {function(Function)} nextTick Function for executing functions in the next turn. - * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for - * debugging purposes. - * @returns {object} Promise manager. + * @description + * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} + * service. */ - function qFactory(nextTick, exceptionHandler) { + function $ParseProvider() { + var cache = createMap(); + var literals = { + 'true': true, + 'false': false, + 'null': null, + 'undefined': undefined + }; + var identStart, identContinue; + + /** + * @ngdoc method + * @name $parseProvider#addLiteral + * @description + * + * Configure $parse service to add literal values that will be present as literal at expressions. + * + * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name. + * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`. + * + **/ + this.addLiteral = function(literalName, literalValue) { + literals[literalName] = literalValue; + }; /** * @ngdoc method - * @name $q#defer - * @function + * @name $parseProvider#setIdentifierFns * * @description - * Creates a `Deferred` object which represents a task which will finish in the future. * - * @returns {Deferred} Returns a new instance of deferred. + * Allows defining the set of characters that are allowed in AngularJS expressions. The function + * `identifierStart` will get called to know if a given character is a valid character to be the + * first character for an identifier. The function `identifierContinue` will get called to know if + * a given character is a valid character to be a follow-up identifier character. The functions + * `identifierStart` and `identifierContinue` will receive as arguments the single character to be + * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in + * mind that the `string` parameter can be two characters long depending on the character + * representation. It is expected for the function to return `true` or `false`, whether that + * character is allowed or not. + * + * Since this function will be called extensively, keep the implementation of these functions fast, + * as the performance of these functions have a direct impact on the expressions parsing speed. + * + * @param {function=} identifierStart The function that will decide whether the given character is + * a valid identifier start character. + * @param {function=} identifierContinue The function that will decide whether the given character is + * a valid identifier continue character. */ - var defer = function() { - var pending = [], - value, deferred; - - deferred = { - - resolve: function(val) { - if (pending) { - var callbacks = pending; - pending = undefined; - value = ref(val); - - if (callbacks.length) { - nextTick(function() { - var callback; - for (var i = 0, ii = callbacks.length; i < ii; i++) { - callback = callbacks[i]; - value.then(callback[0], callback[1], callback[2]); - } - }); + this.setIdentifierFns = function(identifierStart, identifierContinue) { + identStart = identifierStart; + identContinue = identifierContinue; + return this; + }; + + this.$get = ['$filter', function($filter) { + var noUnsafeEval = csp().noUnsafeEval; + var $parseOptions = { + csp: noUnsafeEval, + literals: copy(literals), + isIdentifierStart: isFunction(identStart) && identStart, + isIdentifierContinue: isFunction(identContinue) && identContinue + }; + $parse.$$getAst = $$getAst; + return $parse; + + function $parse(exp, interceptorFn) { + var parsedExpression, cacheKey; + + switch (typeof exp) { + case 'string': + exp = exp.trim(); + cacheKey = exp; + + parsedExpression = cache[cacheKey]; + + if (!parsedExpression) { + var lexer = new Lexer($parseOptions); + var parser = new Parser(lexer, $filter, $parseOptions); + parsedExpression = parser.parse(exp); + if (parsedExpression.constant) { + parsedExpression.$$watchDelegate = constantWatchDelegate; + } else if (parsedExpression.oneTime) { + parsedExpression.$$watchDelegate = parsedExpression.literal ? + oneTimeLiteralWatchDelegate : oneTimeWatchDelegate; + } else if (parsedExpression.inputs) { + parsedExpression.$$watchDelegate = inputsWatchDelegate; + } + cache[cacheKey] = parsedExpression; } - } - }, + return addInterceptor(parsedExpression, interceptorFn); + case 'function': + return addInterceptor(exp, interceptorFn); - reject: function(reason) { - deferred.resolve(createInternalRejectedPromise(reason)); - }, + default: + return addInterceptor(noop, interceptorFn); + } + } + function $$getAst(exp) { + var lexer = new Lexer($parseOptions); + var parser = new Parser(lexer, $filter, $parseOptions); + return parser.getAst(exp).ast; + } - notify: function(progress) { - if (pending) { - var callbacks = pending; + function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) { - if (pending.length) { - nextTick(function() { - var callback; - for (var i = 0, ii = callbacks.length; i < ii; i++) { - callback = callbacks[i]; - callback[2](progress); - } - }); - } - } - }, + if (newValue == null || oldValueOfValue == null) { // null/undefined + return newValue === oldValueOfValue; + } + if (typeof newValue === 'object') { - promise: { - then: function(callback, errback, progressback) { - var result = defer(); + // attempt to convert the value to a primitive type + // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can + // be cheaply dirty-checked + newValue = getValueOf(newValue); - var wrappedCallback = function(value) { - try { - result.resolve((isFunction(callback) ? callback : defaultCallback)(value)); - } catch(e) { - result.reject(e); - exceptionHandler(e); - } - }; + if (typeof newValue === 'object' && !compareObjectIdentity) { + // objects/arrays are not supported - deep-watching them would be too expensive + return false; + } - var wrappedErrback = function(reason) { - try { - result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); - } catch(e) { - result.reject(e); - exceptionHandler(e); - } - }; + // fall-through to the primitive equality check + } - var wrappedProgressback = function(progress) { - try { - result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress)); - } catch(e) { - exceptionHandler(e); - } - }; + //Primitive or NaN + // eslint-disable-next-line no-self-compare + return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue); + } - if (pending) { - pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]); - } else { - value.then(wrappedCallback, wrappedErrback, wrappedProgressback); + function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) { + var inputExpressions = parsedExpression.inputs; + var lastResult; + + if (inputExpressions.length === 1) { + var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails + inputExpressions = inputExpressions[0]; + return scope.$watch(function expressionInputWatch(scope) { + var newInputValue = inputExpressions(scope); + if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) { + lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]); + oldInputValueOf = newInputValue && getValueOf(newInputValue); } + return lastResult; + }, listener, objectEquality, prettyPrintExpression); + } - return result.promise; - }, - - "catch": function(callback) { - return this.then(null, callback); - }, + var oldInputValueOfValues = []; + var oldInputValues = []; + for (var i = 0, ii = inputExpressions.length; i < ii; i++) { + oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails + oldInputValues[i] = null; + } - "finally": function(callback) { + return scope.$watch(function expressionInputsWatch(scope) { + var changed = false; - function makePromise(value, resolved) { - var result = defer(); - if (resolved) { - result.resolve(value); - } else { - result.reject(value); - } - return result.promise; - } - - function handleCallback(value, isResolved) { - var callbackOutput = null; - try { - callbackOutput = (callback ||defaultCallback)(); - } catch(e) { - return makePromise(e, false); - } - if (callbackOutput && isFunction(callbackOutput.then)) { - return callbackOutput.then(function() { - return makePromise(value, isResolved); - }, function(error) { - return makePromise(error, false); - }); - } else { - return makePromise(value, isResolved); - } + for (var i = 0, ii = inputExpressions.length; i < ii; i++) { + var newInputValue = inputExpressions[i](scope); + if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) { + oldInputValues[i] = newInputValue; + oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue); } + } - return this.then(function(value) { - return handleCallback(value, true); - }, function(error) { - return handleCallback(error, false); - }); + if (changed) { + lastResult = parsedExpression(scope, undefined, undefined, oldInputValues); } - } - }; - return deferred; - }; + return lastResult; + }, listener, objectEquality, prettyPrintExpression); + } + function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) { + var unwatch, lastValue; + if (parsedExpression.inputs) { + unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression); + } else { + unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality); + } + return unwatch; - var ref = function(value) { - if (value && isFunction(value.then)) return value; - return { - then: function(callback) { - var result = defer(); - nextTick(function() { - result.resolve(callback(value)); - }); - return result.promise; + function oneTimeWatch(scope) { + return parsedExpression(scope); } - }; - }; + function oneTimeListener(value, old, scope) { + lastValue = value; + if (isFunction(listener)) { + listener(value, old, scope); + } + if (isDefined(value)) { + scope.$$postDigest(function() { + if (isDefined(lastValue)) { + unwatch(); + } + }); + } + } + } + function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) { + var unwatch, lastValue; + unwatch = scope.$watch(function oneTimeWatch(scope) { + return parsedExpression(scope); + }, function oneTimeListener(value, old, scope) { + lastValue = value; + if (isFunction(listener)) { + listener(value, old, scope); + } + if (isAllDefined(value)) { + scope.$$postDigest(function() { + if (isAllDefined(lastValue)) unwatch(); + }); + } + }, objectEquality); - /** - * @ngdoc method - * @name $q#reject - * @function - * - * @description - * Creates a promise that is resolved as rejected with the specified `reason`. This api should be - * used to forward rejection in a chain of promises. If you are dealing with the last promise in - * a promise chain, you don't need to worry about it. - * - * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of - * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via - * a promise error callback and you want to forward the error to the promise derived from the - * current promise, you have to "rethrow" the error by returning a rejection constructed via - * `reject`. - * - * ```js - * promiseB = promiseA.then(function(result) { - * // success: do something and resolve promiseB - * // with the old or a new result - * return result; - * }, function(reason) { - * // error: handle the error if possible and - * // resolve promiseB with newPromiseOrValue, - * // otherwise forward the rejection to promiseB - * if (canHandle(reason)) { - * // handle the error and recover - * return newPromiseOrValue; - * } - * return $q.reject(reason); - * }); - * ``` - * - * @param {*} reason Constant, message, exception or an object representing the rejection reason. - * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. - */ - var reject = function(reason) { - var result = defer(); - result.reject(reason); - return result.promise; - }; + return unwatch; - var createInternalRejectedPromise = function(reason) { - return { - then: function(callback, errback) { - var result = defer(); - nextTick(function() { - try { - result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); - } catch(e) { - result.reject(e); - exceptionHandler(e); - } + function isAllDefined(value) { + var allDefined = true; + forEach(value, function(val) { + if (!isDefined(val)) allDefined = false; }); - return result.promise; + return allDefined; } - }; - }; - + } - /** - * @ngdoc method - * @name $q#when - * @function - * - * @description - * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. - * This is useful when you are dealing with an object that might or might not be a promise, or if - * the promise comes from a source that can't be trusted. - * - * @param {*} value Value or a promise - * @returns {Promise} Returns a promise of the passed value or promise - */ - var when = function(value, callback, errback, progressback) { - var result = defer(), - done; + function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { + var unwatch = scope.$watch(function constantWatch(scope) { + unwatch(); + return parsedExpression(scope); + }, listener, objectEquality); + return unwatch; + } - var wrappedCallback = function(value) { - try { - return (isFunction(callback) ? callback : defaultCallback)(value); - } catch (e) { - exceptionHandler(e); - return reject(e); - } - }; + function addInterceptor(parsedExpression, interceptorFn) { + if (!interceptorFn) return parsedExpression; + var watchDelegate = parsedExpression.$$watchDelegate; + var useInputs = false; + + var regularWatch = + watchDelegate !== oneTimeLiteralWatchDelegate && + watchDelegate !== oneTimeWatchDelegate; + + var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) { + var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs); + return interceptorFn(value, scope, locals); + } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) { + var value = parsedExpression(scope, locals, assign, inputs); + var result = interceptorFn(value, scope, locals); + // we only return the interceptor's result if the + // initial value is defined (for bind-once) + return isDefined(value) ? result : value; + }; - var wrappedErrback = function(reason) { - try { - return (isFunction(errback) ? errback : defaultErrback)(reason); - } catch (e) { - exceptionHandler(e); - return reject(e); + // Propagate $$watchDelegates other then inputsWatchDelegate + useInputs = !parsedExpression.inputs; + if (watchDelegate && watchDelegate !== inputsWatchDelegate) { + fn.$$watchDelegate = watchDelegate; + fn.inputs = parsedExpression.inputs; + } else if (!interceptorFn.$stateful) { + // Treat interceptor like filters - assume non-stateful by default and use the inputsWatchDelegate + fn.$$watchDelegate = inputsWatchDelegate; + fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression]; } - }; - var wrappedProgressback = function(progress) { - try { - return (isFunction(progressback) ? progressback : defaultCallback)(progress); - } catch (e) { - exceptionHandler(e); + if (fn.inputs) { + fn.inputs = fn.inputs.map(function(e) { + // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a + // potentially non-pure interceptor function. + if (e.isPure === PURITY_RELATIVE) { + return function depurifier(s) { return e(s); }; + } + return e; + }); } - }; - - nextTick(function() { - ref(value).then(function(value) { - if (done) return; - done = true; - result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback)); - }, function(reason) { - if (done) return; - done = true; - result.resolve(wrappedErrback(reason)); - }, function(progress) { - if (done) return; - result.notify(wrappedProgressback(progress)); - }); - }); - - return result.promise; - }; - - - function defaultCallback(value) { - return value; - } - - - function defaultErrback(reason) { - return reject(reason); - } - - - /** - * @ngdoc method - * @name $q#all - * @function - * - * @description - * Combines multiple promises into a single promise that is resolved when all of the input - * promises are resolved. - * - * @param {Array.|Object.} promises An array or hash of promises. - * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, - * each value corresponding to the promise at the same index/key in the `promises` array/hash. - * If any of the promises is resolved with a rejection, this resulting promise will be rejected - * with the same rejection value. - */ - function all(promises) { - var deferred = defer(), - counter = 0, - results = isArray(promises) ? [] : {}; - - forEach(promises, function(promise, key) { - counter++; - ref(promise).then(function(value) { - if (results.hasOwnProperty(key)) return; - results[key] = value; - if (!(--counter)) deferred.resolve(results); - }, function(reason) { - if (results.hasOwnProperty(key)) return; - deferred.reject(reason); - }); - }); - - if (counter === 0) { - deferred.resolve(results); - } - - return deferred.promise; - } - - return { - defer: defer, - reject: reject, - when: when, - all: all - }; - } - - function $$RAFProvider(){ //rAF - this.$get = ['$window', '$timeout', function($window, $timeout) { - var requestAnimationFrame = $window.requestAnimationFrame || - $window.webkitRequestAnimationFrame || - $window.mozRequestAnimationFrame; - - var cancelAnimationFrame = $window.cancelAnimationFrame || - $window.webkitCancelAnimationFrame || - $window.mozCancelAnimationFrame || - $window.webkitCancelRequestAnimationFrame; - var rafSupported = !!requestAnimationFrame; - var raf = rafSupported - ? function(fn) { - var id = requestAnimationFrame(fn); - return function() { - cancelAnimationFrame(id); - }; + return fn; } - : function(fn) { - var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 - return function() { - $timeout.cancel(timer); - }; - }; - - raf.supported = rafSupported; - - return raf; }]; } /** - * DESIGN NOTES + * @ngdoc service + * @name $q + * @requires $rootScope * - * The design decisions behind the scope are heavily favored for speed and memory consumption. + * @description + * A service that helps you run functions asynchronously, and use their return values (or exceptions) + * when they are done processing. * - * The typical use of scope is to watch the expressions, which most of the time return the same - * value as last time so we optimize the operation. + * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred + * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). * - * Closures construction is expensive in terms of speed as well as memory: - * - No closures, instead use prototypical inheritance for API - * - Internal state needs to be stored on scope directly, which means that private state is - * exposed as $$____ properties + * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred + * implementations, and the other which resembles ES6 (ES2015) promises to some degree. * - * Loop operations are optimized by using while(count--) { ... } - * - this means that in order to keep the same order of execution as addition we have to add - * items to the array at the beginning (shift) instead of at the end (push) + * ## $q constructor * - * Child scopes are created and removed often - * - Using an array would be slow since inserts in middle are expensive so we use linked list + * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver` + * function as the first argument. This is similar to the native Promise implementation from ES6, + * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). * - * There are few watches then a lot of observers. This is why you don't want the observer to be - * implemented in the same way as watch. Watch requires return of initialization function which - * are expensive to construct. - */ - - - /** - * @ngdoc provider - * @name $rootScopeProvider - * @description + * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are + * available yet. * - * Provider for the $rootScope service. - */ - - /** - * @ngdoc method - * @name $rootScopeProvider#digestTtl - * @description + * It can be used like so: * - * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and - * assuming that the model is unstable. + * ```js + * // for the purpose of this example let's assume that variables `$q` and `okToGreet` + * // are available in the current lexical scope (they could have been injected or passed in). * - * The current default is 10 iterations. + * function asyncGreet(name) { + * // perform some asynchronous operation, resolve or reject the promise when appropriate. + * return $q(function(resolve, reject) { + * setTimeout(function() { + * if (okToGreet(name)) { + * resolve('Hello, ' + name + '!'); + * } else { + * reject('Greeting ' + name + ' is not allowed.'); + * } + * }, 1000); + * }); + * } * - * In complex applications it's possible that the dependencies between `$watch`s will result in - * several digest iterations. However if an application needs more than the default 10 digest - * iterations for its model to stabilize then you should investigate what is causing the model to - * continuously change during the digest. + * var promise = asyncGreet('Robin Hood'); + * promise.then(function(greeting) { + * alert('Success: ' + greeting); + * }, function(reason) { + * alert('Failed: ' + reason); + * }); + * ``` * - * Increasing the TTL could have performance implications, so you should not change it without - * proper justification. + * Note: progress/notify callbacks are not currently supported via the ES6-style interface. * - * @param {number} limit The number of digest iterations. - */ - - - /** - * @ngdoc service - * @name $rootScope - * @description + * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise. * - * Every application has a single root {@link ng.$rootScope.Scope scope}. - * All other scopes are descendant scopes of the root scope. Scopes provide separation - * between the model and the view, via a mechanism for watching the model for changes. - * They also provide an event emission/broadcast and subscription facility. See the - * {@link guide/scope developer guide on scopes}. - */ - function $RootScopeProvider(){ - var TTL = 10; - var $rootScopeMinErr = minErr('$rootScope'); - var lastDirtyWatch = null; - - this.digestTtl = function(value) { - if (arguments.length) { - TTL = value; - } - return TTL; - }; - - this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', - function( $injector, $exceptionHandler, $parse, $browser) { - - /** - * @ngdoc type - * @name $rootScope.Scope - * - * @description - * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the - * {@link auto.$injector $injector}. Child scopes are created using the - * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when - * compiled HTML template is executed.) - * - * Here is a simple scope snippet to show how you can interact with the scope. - * ```html - * - * ``` - * - * # Inheritance - * A scope can inherit from a parent scope, as in this example: - * ```js - var parent = $rootScope; - var child = parent.$new(); - - parent.salutation = "Hello"; - child.name = "World"; - expect(child.salutation).toEqual('Hello'); - - child.salutation = "Welcome"; - expect(child.salutation).toEqual('Welcome'); - expect(parent.salutation).toEqual('Hello'); - * ``` - * - * - * @param {Object.=} providers Map of service factory which need to be - * provided for the current scope. Defaults to {@link ng}. - * @param {Object.=} instanceCache Provides pre-instantiated services which should - * append/override services provided by `providers`. This is handy - * when unit-testing and having the need to override a default - * service. - * @returns {Object} Newly created scope. - * - */ - function Scope() { - this.$id = nextUid(); - this.$$phase = this.$parent = this.$$watchers = - this.$$nextSibling = this.$$prevSibling = - this.$$childHead = this.$$childTail = null; - this['this'] = this.$root = this; - this.$$destroyed = false; - this.$$asyncQueue = []; - this.$$postDigestQueue = []; - this.$$listeners = {}; - this.$$listenerCount = {}; - this.$$isolateBindings = {}; - } + * However, the more traditional CommonJS-style usage is still available, and documented below. + * + * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an + * interface for interacting with an object that represents the result of an action that is + * performed asynchronously, and may or may not be finished at any given point in time. + * + * From the perspective of dealing with error handling, deferred and promise APIs are to + * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. + * + * ```js + * // for the purpose of this example let's assume that variables `$q` and `okToGreet` + * // are available in the current lexical scope (they could have been injected or passed in). + * + * function asyncGreet(name) { + * var deferred = $q.defer(); + * + * setTimeout(function() { + * deferred.notify('About to greet ' + name + '.'); + * + * if (okToGreet(name)) { + * deferred.resolve('Hello, ' + name + '!'); + * } else { + * deferred.reject('Greeting ' + name + ' is not allowed.'); + * } + * }, 1000); + * + * return deferred.promise; + * } + * + * var promise = asyncGreet('Robin Hood'); + * promise.then(function(greeting) { + * alert('Success: ' + greeting); + * }, function(reason) { + * alert('Failed: ' + reason); + * }, function(update) { + * alert('Got notification: ' + update); + * }); + * ``` + * + * At first it might not be obvious why this extra complexity is worth the trouble. The payoff + * comes in the way of guarantees that promise and deferred APIs make, see + * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. + * + * Additionally the promise api allows for composition that is very hard to do with the + * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. + * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the + * section on serial or parallel joining of promises. + * + * ## The Deferred API + * + * A new instance of deferred is constructed by calling `$q.defer()`. + * + * The purpose of the deferred object is to expose the associated Promise instance as well as APIs + * that can be used for signaling the successful or unsuccessful completion, as well as the status + * of the task. + * + * **Methods** + * + * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection + * constructed via `$q.reject`, the promise will be rejected instead. + * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to + * resolving it with a rejection constructed via `$q.reject`. + * - `notify(value)` - provides updates on the status of the promise's execution. This may be called + * multiple times before the promise is either resolved or rejected. + * + * **Properties** + * + * - promise – `{Promise}` – promise object associated with this deferred. + * + * + * ## The Promise API + * + * A new promise instance is created when a deferred instance is created and can be retrieved by + * calling `deferred.promise`. + * + * The purpose of the promise object is to allow for interested parties to get access to the result + * of the deferred task when it completes. + * + * **Methods** + * + * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or + * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously + * as soon as the result is available. The callbacks are called with a single argument: the result + * or rejection reason. Additionally, the notify callback may be called zero or more times to + * provide a progress indication, before the promise is resolved or rejected. + * + * This method *returns a new promise* which is resolved or rejected via the return value of the + * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved + * with the value which is resolved in that promise using + * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)). + * It also notifies via the return value of the `notifyCallback` method. The promise cannot be + * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback + * arguments are optional. + * + * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` + * + * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise, + * but to do so without modifying the final value. This is useful to release resources or do some + * clean-up that needs to be done whether the promise was rejected or resolved. See the [full + * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for + * more information. + * + * ## Chaining promises + * + * Because calling the `then` method of a promise returns a new derived promise, it is easily + * possible to create a chain of promises: + * + * ```js + * promiseB = promiseA.then(function(result) { + * return result + 1; + * }); + * + * // promiseB will be resolved immediately after promiseA is resolved and its value + * // will be the result of promiseA incremented by 1 + * ``` + * + * It is possible to create chains of any length and since a promise can be resolved with another + * promise (which will defer its resolution further), it is possible to pause/defer resolution of + * the promises at any point in the chain. This makes it possible to implement powerful APIs like + * $http's response interceptors. + * + * + * ## Differences between Kris Kowal's Q and $q + * + * There are two main differences: + * + * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation + * mechanism in AngularJS, which means faster propagation of resolution or rejection into your + * models and avoiding unnecessary browser repaints, which would result in flickering UI. + * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains + * all the important functionality needed for common async tasks. + * + * ## Testing + * + * ```js + * it('should simulate promise', inject(function($q, $rootScope) { + * var deferred = $q.defer(); + * var promise = deferred.promise; + * var resolvedValue; + * + * promise.then(function(value) { resolvedValue = value; }); + * expect(resolvedValue).toBeUndefined(); + * + * // Simulate resolving of promise + * deferred.resolve(123); + * // Note that the 'then' function does not get called synchronously. + * // This is because we want the promise API to always be async, whether or not + * // it got called synchronously or asynchronously. + * expect(resolvedValue).toBeUndefined(); + * + * // Propagate promise resolution to 'then' functions using $apply(). + * $rootScope.$apply(); + * expect(resolvedValue).toEqual(123); + * })); + * ``` + * + * @param {function(function, function)} resolver Function which is responsible for resolving or + * rejecting the newly created promise. The first parameter is a function which resolves the + * promise, the second parameter is a function which rejects the promise. + * + * @returns {Promise} The newly created promise. + */ + /** + * @ngdoc provider + * @name $qProvider + * @this + * + * @description + */ + function $QProvider() { + var errorOnUnhandledRejections = true; + this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { + return qFactory(function(callback) { + $rootScope.$evalAsync(callback); + }, $exceptionHandler, errorOnUnhandledRejections); + }]; - /** - * @ngdoc property - * @name $rootScope.Scope#$id - * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for - * debugging. - */ + /** + * @ngdoc method + * @name $qProvider#errorOnUnhandledRejections + * @kind function + * + * @description + * Retrieves or overrides whether to generate an error when a rejected promise is not handled. + * This feature is enabled by default. + * + * @param {boolean=} value Whether to generate an error when a rejected promise is not handled. + * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for + * chaining otherwise. + */ + this.errorOnUnhandledRejections = function(value) { + if (isDefined(value)) { + errorOnUnhandledRejections = value; + return this; + } else { + return errorOnUnhandledRejections; + } + }; + } + /** @this */ + function $$QProvider() { + var errorOnUnhandledRejections = true; + this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) { + return qFactory(function(callback) { + $browser.defer(callback); + }, $exceptionHandler, errorOnUnhandledRejections); + }]; - Scope.prototype = { - constructor: Scope, - /** - * @ngdoc method - * @name $rootScope.Scope#$new - * @function - * - * @description - * Creates a new child {@link ng.$rootScope.Scope scope}. - * - * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and - * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the - * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. - * - * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is - * desired for the scope and its child scopes to be permanently detached from the parent and - * thus stop participating in model change detection and listener notification by invoking. - * - * @param {boolean} isolate If true, then the scope does not prototypically inherit from the - * parent scope. The scope is isolated, as it can not see parent scope properties. - * When creating widgets, it is useful for the widget to not accidentally read parent - * state. - * - * @returns {Object} The newly created child scope. - * - */ - $new: function(isolate) { - var ChildScope, - child; + this.errorOnUnhandledRejections = function(value) { + if (isDefined(value)) { + errorOnUnhandledRejections = value; + return this; + } else { + return errorOnUnhandledRejections; + } + }; + } - if (isolate) { - child = new Scope(); - child.$root = this.$root; - // ensure that there is just one async queue per $rootScope and its children - child.$$asyncQueue = this.$$asyncQueue; - child.$$postDigestQueue = this.$$postDigestQueue; - } else { - ChildScope = function() {}; // should be anonymous; This is so that when the minifier munges - // the name it does not become random set of chars. This will then show up as class - // name in the web inspector. - ChildScope.prototype = this; - child = new ChildScope(); - child.$id = nextUid(); - } - child['this'] = child; - child.$$listeners = {}; - child.$$listenerCount = {}; - child.$parent = this; - child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; - child.$$prevSibling = this.$$childTail; - if (this.$$childHead) { - this.$$childTail.$$nextSibling = child; - this.$$childTail = child; - } else { - this.$$childHead = this.$$childTail = child; - } - return child; - }, + /** + * Constructs a promise manager. + * + * @param {function(function)} nextTick Function for executing functions in the next turn. + * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for + * debugging purposes. + * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled + * promises rejections. + * @returns {object} Promise manager. + */ + function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) { + var $qMinErr = minErr('$q', TypeError); + var queueSize = 0; + var checkQueue = []; - /** - * @ngdoc method - * @name $rootScope.Scope#$watch - * @function - * - * @description - * Registers a `listener` callback to be executed whenever the `watchExpression` changes. - * - * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest - * $digest()} and should return the value that will be watched. (Since - * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the - * `watchExpression` can execute multiple times per - * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) - * - The `listener` is called only when the value from the current `watchExpression` and the - * previous call to `watchExpression` are not equal (with the exception of the initial run, - * see below). The inequality is determined according to - * {@link angular.equals} function. To save the value of the object for later comparison, - * the {@link angular.copy} function is used. It also means that watching complex options - * will have adverse memory and performance implications. - * - The watch `listener` may change the model, which may trigger other `listener`s to fire. - * This is achieved by rerunning the watchers until no changes are detected. The rerun - * iteration limit is 10 to prevent an infinite loop deadlock. - * - * - * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, - * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` - * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a - * change is detected, be prepared for multiple calls to your listener.) - * - * After a watcher is registered with the scope, the `listener` fn is called asynchronously - * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the - * watcher. In rare cases, this is undesirable because the listener is called when the result - * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you - * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the - * listener was called due to initialization. - * - * The example below contains an illustration of using a function as your $watch listener - * - * - * # Example - * ```js - // let's assume that scope was dependency injected as the $rootScope - var scope = $rootScope; - scope.name = 'misko'; - scope.counter = 0; + /** + * @ngdoc method + * @name ng.$q#defer + * @kind function + * + * @description + * Creates a `Deferred` object which represents a task which will finish in the future. + * + * @returns {Deferred} Returns a new instance of deferred. + */ + function defer() { + return new Deferred(); + } - expect(scope.counter).toEqual(0); - scope.$watch('name', function(newValue, oldValue) { - scope.counter = scope.counter + 1; - }); - expect(scope.counter).toEqual(0); + function Deferred() { + var promise = this.promise = new Promise(); + //Non prototype methods necessary to support unbound execution :/ + this.resolve = function(val) { resolvePromise(promise, val); }; + this.reject = function(reason) { rejectPromise(promise, reason); }; + this.notify = function(progress) { notifyPromise(promise, progress); }; + } - scope.$digest(); - // no variable change - expect(scope.counter).toEqual(0); - scope.name = 'adam'; - scope.$digest(); - expect(scope.counter).toEqual(1); + function Promise() { + this.$$state = { status: 0 }; + } + extend(Promise.prototype, { + then: function(onFulfilled, onRejected, progressBack) { + if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) { + return this; + } + var result = new Promise(); + this.$$state.pending = this.$$state.pending || []; + this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]); + if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); - // Using a listener function - var food; - scope.foodCounter = 0; - expect(scope.foodCounter).toEqual(0); - scope.$watch( - // This is the listener function - function() { return food; }, - // This is the change handler - function(newValue, oldValue) { - if ( newValue !== oldValue ) { - // Only increment the counter if the value changed - scope.foodCounter = scope.foodCounter + 1; - } - } - ); - // No digest has been run so the counter will be zero - expect(scope.foodCounter).toEqual(0); - - // Run the digest but since food has not changed count will still be zero - scope.$digest(); - expect(scope.foodCounter).toEqual(0); + return result; + }, - // Update food and run digest. Now the counter will increment - food = 'cheeseburger'; - scope.$digest(); - expect(scope.foodCounter).toEqual(1); + 'catch': function(callback) { + return this.then(null, callback); + }, - * ``` - * - * - * - * @param {(function()|string)} watchExpression Expression that is evaluated on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers - * a call to the `listener`. - * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(scope)`: called with current `scope` as a parameter. - * @param {(function()|string)=} listener Callback called whenever the return value of - * the `watchExpression` changes. - * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(newValue, oldValue, scope)`: called with current and previous values as - * parameters. - * - * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of - * comparing for reference equality. - * @returns {function()} Returns a deregistration function for this listener. - */ - $watch: function(watchExp, listener, objectEquality) { - var scope = this, - get = compileToFn(watchExp, 'watch'), - array = scope.$$watchers, - watcher = { - fn: listener, - last: initWatchVal, - get: get, - exp: watchExp, - eq: !!objectEquality - }; + 'finally': function(callback, progressBack) { + return this.then(function(value) { + return handleCallback(value, resolve, callback); + }, function(error) { + return handleCallback(error, reject, callback); + }, progressBack); + } + }); - lastDirtyWatch = null; + function processQueue(state) { + var fn, promise, pending; - // in the case user pass string, we need to compile it, do we really need this ? - if (!isFunction(listener)) { - var listenFn = compileToFn(listener || noop, 'listener'); - watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; + pending = state.pending; + state.processScheduled = false; + state.pending = undefined; + try { + for (var i = 0, ii = pending.length; i < ii; ++i) { + markQStateExceptionHandled(state); + promise = pending[i][0]; + fn = pending[i][state.status]; + try { + if (isFunction(fn)) { + resolvePromise(promise, fn(state.value)); + } else if (state.status === 1) { + resolvePromise(promise, state.value); + } else { + rejectPromise(promise, state.value); } - - if (typeof watchExp == 'string' && get.constant) { - var originalFn = watcher.fn; - watcher.fn = function(newVal, oldVal, scope) { - originalFn.call(this, newVal, oldVal, scope); - arrayRemove(array, watcher); - }; + } catch (e) { + rejectPromise(promise, e); + // This error is explicitly marked for being passed to the $exceptionHandler + if (e && e.$$passToExceptionHandler === true) { + exceptionHandler(e); } + } + } + } finally { + --queueSize; + if (errorOnUnhandledRejections && queueSize === 0) { + nextTick(processChecks); + } + } + } - if (!array) { - array = scope.$$watchers = []; - } - // we use unshift since we use a while loop in $digest for speed. - // the while loop reads in reverse order. - array.unshift(watcher); + function processChecks() { + // eslint-disable-next-line no-unmodified-loop-condition + while (!queueSize && checkQueue.length) { + var toCheck = checkQueue.shift(); + if (!isStateExceptionHandled(toCheck)) { + markQStateExceptionHandled(toCheck); + var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value); + if (isError(toCheck.value)) { + exceptionHandler(toCheck.value, errorMessage); + } else { + exceptionHandler(errorMessage); + } + } + } + } - return function() { - arrayRemove(array, watcher); - lastDirtyWatch = null; - }; - }, + function scheduleProcessQueue(state) { + if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) { + if (queueSize === 0 && checkQueue.length === 0) { + nextTick(processChecks); + } + checkQueue.push(state); + } + if (state.processScheduled || !state.pending) return; + state.processScheduled = true; + ++queueSize; + nextTick(function() { processQueue(state); }); + } + function resolvePromise(promise, val) { + if (promise.$$state.status) return; + if (val === promise) { + $$reject(promise, $qMinErr( + 'qcycle', + 'Expected promise to be resolved with value other than itself \'{0}\'', + val)); + } else { + $$resolve(promise, val); + } - /** - * @ngdoc method - * @name $rootScope.Scope#$watchCollection - * @function - * - * @description - * Shallow watches the properties of an object and fires whenever any of the properties change - * (for arrays, this implies watching the array items; for object maps, this implies watching - * the properties). If a change is detected, the `listener` callback is fired. - * - * - The `obj` collection is observed via standard $watch operation and is examined on every - * call to $digest() to see if any items have been added, removed, or moved. - * - The `listener` is called whenever anything within the `obj` has changed. Examples include - * adding, removing, and moving items belonging to an object or array. - * - * - * # Example - * ```js - $scope.names = ['igor', 'matias', 'misko', 'james']; - $scope.dataCount = 4; + } - $scope.$watchCollection('names', function(newNames, oldNames) { - $scope.dataCount = newNames.length; - }); + function $$resolve(promise, val) { + var then; + var done = false; + try { + if (isObject(val) || isFunction(val)) then = val.then; + if (isFunction(then)) { + promise.$$state.status = -1; + then.call(val, doResolve, doReject, doNotify); + } else { + promise.$$state.value = val; + promise.$$state.status = 1; + scheduleProcessQueue(promise.$$state); + } + } catch (e) { + doReject(e); + } - expect($scope.dataCount).toEqual(4); - $scope.$digest(); + function doResolve(val) { + if (done) return; + done = true; + $$resolve(promise, val); + } + function doReject(val) { + if (done) return; + done = true; + $$reject(promise, val); + } + function doNotify(progress) { + notifyPromise(promise, progress); + } + } - //still at 4 ... no changes - expect($scope.dataCount).toEqual(4); + function rejectPromise(promise, reason) { + if (promise.$$state.status) return; + $$reject(promise, reason); + } - $scope.names.pop(); - $scope.$digest(); + function $$reject(promise, reason) { + promise.$$state.value = reason; + promise.$$state.status = 2; + scheduleProcessQueue(promise.$$state); + } - //now there's been a change - expect($scope.dataCount).toEqual(3); - * ``` - * - * - * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The - * expression value should evaluate to an object or an array which is observed on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the - * collection will trigger a call to the `listener`. - * - * @param {function(newCollection, oldCollection, scope)} listener a callback function called - * when a change is detected. - * - The `newCollection` object is the newly modified data obtained from the `obj` expression - * - The `oldCollection` object is a copy of the former collection data. - * Due to performance considerations, the`oldCollection` value is computed only if the - * `listener` function declares two or more arguments. - * - The `scope` argument refers to the current scope. - * - * @returns {function()} Returns a de-registration function for this listener. When the - * de-registration function is executed, the internal watch operation is terminated. - */ - $watchCollection: function(obj, listener) { - var self = this; - // the current value, updated on each dirty-check run - var newValue; - // a shallow copy of the newValue from the last dirty-check run, - // updated to match newValue during dirty-check run - var oldValue; - // a shallow copy of the newValue from when the last change happened - var veryOldValue; - // only track veryOldValue if the listener is asking for it - var trackVeryOldValue = (listener.length > 1); - var changeDetected = 0; - var objGetter = $parse(obj); - var internalArray = []; - var internalObject = {}; - var initRun = true; - var oldLength = 0; + function notifyPromise(promise, progress) { + var callbacks = promise.$$state.pending; - function $watchCollectionWatch() { - newValue = objGetter(self); - var newLength, key; + if ((promise.$$state.status <= 0) && callbacks && callbacks.length) { + nextTick(function() { + var callback, result; + for (var i = 0, ii = callbacks.length; i < ii; i++) { + result = callbacks[i][0]; + callback = callbacks[i][3]; + try { + notifyPromise(result, isFunction(callback) ? callback(progress) : progress); + } catch (e) { + exceptionHandler(e); + } + } + }); + } + } - if (!isObject(newValue)) { // if primitive - if (oldValue !== newValue) { - oldValue = newValue; - changeDetected++; - } - } else if (isArrayLike(newValue)) { - if (oldValue !== internalArray) { - // we are transitioning from something which was not an array into array. - oldValue = internalArray; - oldLength = oldValue.length = 0; - changeDetected++; - } + /** + * @ngdoc method + * @name $q#reject + * @kind function + * + * @description + * Creates a promise that is resolved as rejected with the specified `reason`. This api should be + * used to forward rejection in a chain of promises. If you are dealing with the last promise in + * a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of + * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via + * a promise error callback and you want to forward the error to the promise derived from the + * current promise, you have to "rethrow" the error by returning a rejection constructed via + * `reject`. + * + * ```js + * promiseB = promiseA.then(function(result) { + * // success: do something and resolve promiseB + * // with the old or a new result + * return result; + * }, function(reason) { + * // error: handle the error if possible and + * // resolve promiseB with newPromiseOrValue, + * // otherwise forward the rejection to promiseB + * if (canHandle(reason)) { + * // handle the error and recover + * return newPromiseOrValue; + * } + * return $q.reject(reason); + * }); + * ``` + * + * @param {*} reason Constant, message, exception or an object representing the rejection reason. + * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. + */ + function reject(reason) { + var result = new Promise(); + rejectPromise(result, reason); + return result; + } - newLength = newValue.length; + function handleCallback(value, resolver, callback) { + var callbackOutput = null; + try { + if (isFunction(callback)) callbackOutput = callback(); + } catch (e) { + return reject(e); + } + if (isPromiseLike(callbackOutput)) { + return callbackOutput.then(function() { + return resolver(value); + }, reject); + } else { + return resolver(value); + } + } - if (oldLength !== newLength) { - // if lengths do not match we need to trigger change notification - changeDetected++; - oldValue.length = oldLength = newLength; - } - // copy the items to oldValue and look for changes. - for (var i = 0; i < newLength; i++) { - var bothNaN = (oldValue[i] !== oldValue[i]) && - (newValue[i] !== newValue[i]); - if (!bothNaN && (oldValue[i] !== newValue[i])) { - changeDetected++; - oldValue[i] = newValue[i]; - } - } - } else { - if (oldValue !== internalObject) { - // we are transitioning from something which was not an object into object. - oldValue = internalObject = {}; - oldLength = 0; - changeDetected++; - } - // copy the items to oldValue and look for changes. - newLength = 0; - for (key in newValue) { - if (newValue.hasOwnProperty(key)) { - newLength++; - if (oldValue.hasOwnProperty(key)) { - if (oldValue[key] !== newValue[key]) { - changeDetected++; - oldValue[key] = newValue[key]; - } - } else { - oldLength++; - oldValue[key] = newValue[key]; - changeDetected++; - } - } - } - if (oldLength > newLength) { - // we used to have more keys, need to find them and destroy them. - changeDetected++; - for(key in oldValue) { - if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { - oldLength--; - delete oldValue[key]; - } - } - } - } - return changeDetected; - } + /** + * @ngdoc method + * @name $q#when + * @kind function + * + * @description + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. + * This is useful when you are dealing with an object that might or might not be a promise, or if + * the promise comes from a source that can't be trusted. + * + * @param {*} value Value or a promise + * @param {Function=} successCallback + * @param {Function=} errorCallback + * @param {Function=} progressCallback + * @returns {Promise} Returns a promise of the passed value or promise + */ - function $watchCollectionAction() { - if (initRun) { - initRun = false; - listener(newValue, newValue, self); - } else { - listener(newValue, veryOldValue, self); - } - - // make a copy for the next time a collection is changed - if (trackVeryOldValue) { - if (!isObject(newValue)) { - //primitive - veryOldValue = newValue; - } else if (isArrayLike(newValue)) { - veryOldValue = new Array(newValue.length); - for (var i = 0; i < newValue.length; i++) { - veryOldValue[i] = newValue[i]; - } - } else { // if object - veryOldValue = {}; - for (var key in newValue) { - if (hasOwnProperty.call(newValue, key)) { - veryOldValue[key] = newValue[key]; - } - } - } - } - } - return this.$watch($watchCollectionWatch, $watchCollectionAction); - }, - - /** - * @ngdoc method - * @name $rootScope.Scope#$digest - * @function - * - * @description - * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and - * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change - * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} - * until no more listeners are firing. This means that it is possible to get into an infinite - * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of - * iterations exceeds 10. - * - * Usually, you don't call `$digest()` directly in - * {@link ng.directive:ngController controllers} or in - * {@link ng.$compileProvider#directive directives}. - * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within - * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`. - * - * If you want to be notified whenever `$digest()` is called, - * you can register a `watchExpression` function with - * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. - * - * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. - * - * # Example - * ```js - var scope = ...; - scope.name = 'misko'; - scope.counter = 0; + function when(value, callback, errback, progressBack) { + var result = new Promise(); + resolvePromise(result, value); + return result.then(callback, errback, progressBack); + } - expect(scope.counter).toEqual(0); - scope.$watch('name', function(newValue, oldValue) { - scope.counter = scope.counter + 1; - }); - expect(scope.counter).toEqual(0); + /** + * @ngdoc method + * @name $q#resolve + * @kind function + * + * @description + * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6. + * + * @param {*} value Value or a promise + * @param {Function=} successCallback + * @param {Function=} errorCallback + * @param {Function=} progressCallback + * @returns {Promise} Returns a promise of the passed value or promise + */ + var resolve = when; - scope.$digest(); - // no variable change - expect(scope.counter).toEqual(0); + /** + * @ngdoc method + * @name $q#all + * @kind function + * + * @description + * Combines multiple promises into a single promise that is resolved when all of the input + * promises are resolved. + * + * @param {Array.|Object.} promises An array or hash of promises. + * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, + * each value corresponding to the promise at the same index/key in the `promises` array/hash. + * If any of the promises is resolved with a rejection, this resulting promise will be rejected + * with the same rejection value. + */ - scope.name = 'adam'; - scope.$digest(); - expect(scope.counter).toEqual(1); - * ``` - * - */ - $digest: function() { - var watch, value, last, - watchers, - asyncQueue = this.$$asyncQueue, - postDigestQueue = this.$$postDigestQueue, - length, - dirty, ttl = TTL, - next, current, target = this, - watchLog = [], - logIdx, logMsg, asyncTask; + function all(promises) { + var result = new Promise(), + counter = 0, + results = isArray(promises) ? [] : {}; - beginPhase('$digest'); + forEach(promises, function(promise, key) { + counter++; + when(promise).then(function(value) { + results[key] = value; + if (!(--counter)) resolvePromise(result, results); + }, function(reason) { + rejectPromise(result, reason); + }); + }); - lastDirtyWatch = null; + if (counter === 0) { + resolvePromise(result, results); + } - do { // "while dirty" loop - dirty = false; - current = target; + return result; + } - while(asyncQueue.length) { - try { - asyncTask = asyncQueue.shift(); - asyncTask.scope.$eval(asyncTask.expression); - } catch (e) { - clearPhase(); - $exceptionHandler(e); - } - lastDirtyWatch = null; - } + /** + * @ngdoc method + * @name $q#race + * @kind function + * + * @description + * Returns a promise that resolves or rejects as soon as one of those promises + * resolves or rejects, with the value or reason from that promise. + * + * @param {Array.|Object.} promises An array or hash of promises. + * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises` + * resolves or rejects, with the value or reason from that promise. + */ - traverseScopesLoop: - do { // "traverse the scopes" loop - if ((watchers = current.$$watchers)) { - // process our watches - length = watchers.length; - while (length--) { - try { - watch = watchers[length]; - // Most common watches are on primitives, in which case we can short - // circuit it with === operator, only when === fails do we use .equals - if (watch) { - if ((value = watch.get(current)) !== (last = watch.last) && - !(watch.eq - ? equals(value, last) - : (typeof value == 'number' && typeof last == 'number' - && isNaN(value) && isNaN(last)))) { - dirty = true; - lastDirtyWatch = watch; - watch.last = watch.eq ? copy(value) : value; - watch.fn(value, ((last === initWatchVal) ? value : last), current); - if (ttl < 5) { - logIdx = 4 - ttl; - if (!watchLog[logIdx]) watchLog[logIdx] = []; - logMsg = (isFunction(watch.exp)) - ? 'fn: ' + (watch.exp.name || watch.exp.toString()) - : watch.exp; - logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); - watchLog[logIdx].push(logMsg); - } - } else if (watch === lastDirtyWatch) { - // If the most recently dirty watcher is now clean, short circuit since the remaining watchers - // have already been tested. - dirty = false; - break traverseScopesLoop; - } - } - } catch (e) { - clearPhase(); - $exceptionHandler(e); - } - } - } + function race(promises) { + var deferred = defer(); - // Insanity Warning: scope depth-first traversal - // yes, this code is a bit crazy, but it works and we have tests to prove it! - // this piece should be kept in sync with the traversal in $broadcast - if (!(next = (current.$$childHead || - (current !== target && current.$$nextSibling)))) { - while(current !== target && !(next = current.$$nextSibling)) { - current = current.$parent; - } - } - } while ((current = next)); + forEach(promises, function(promise) { + when(promise).then(deferred.resolve, deferred.reject); + }); - // `break traverseScopesLoop;` takes us to here + return deferred.promise; + } - if((dirty || asyncQueue.length) && !(ttl--)) { - clearPhase(); - throw $rootScopeMinErr('infdig', - '{0} $digest() iterations reached. Aborting!\n' + - 'Watchers fired in the last 5 iterations: {1}', - TTL, toJson(watchLog)); - } + function $Q(resolver) { + if (!isFunction(resolver)) { + throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver); + } - } while (dirty || asyncQueue.length); + var promise = new Promise(); - clearPhase(); + function resolveFn(value) { + resolvePromise(promise, value); + } - while(postDigestQueue.length) { - try { - postDigestQueue.shift()(); - } catch (e) { - $exceptionHandler(e); - } - } - }, + function rejectFn(reason) { + rejectPromise(promise, reason); + } + resolver(resolveFn, rejectFn); - /** - * @ngdoc event - * @name $rootScope.Scope#$destroy - * @eventType broadcast on scope being destroyed - * - * @description - * Broadcasted when a scope and its children are being destroyed. - * - * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to - * clean up DOM bindings before an element is removed from the DOM. - */ + return promise; + } - /** - * @ngdoc method - * @name $rootScope.Scope#$destroy - * @function - * - * @description - * Removes the current scope (and all of its children) from the parent scope. Removal implies - * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer - * propagate to the current scope and its children. Removal also implies that the current - * scope is eligible for garbage collection. - * - * The `$destroy()` is usually used by directives such as - * {@link ng.directive:ngRepeat ngRepeat} for managing the - * unrolling of the loop. - * - * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. - * Application code can register a `$destroy` event handler that will give it a chance to - * perform any necessary cleanup. - * - * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to - * clean up DOM bindings before an element is removed from the DOM. - */ - $destroy: function() { - // we can't destroy the root scope or a scope that has been already destroyed - if (this.$$destroyed) return; - var parent = this.$parent; + // Let's make the instanceof operator work for promises, so that + // `new $q(fn) instanceof $q` would evaluate to true. + $Q.prototype = Promise.prototype; - this.$broadcast('$destroy'); - this.$$destroyed = true; - if (this === $rootScope) return; + $Q.defer = defer; + $Q.reject = reject; + $Q.when = when; + $Q.resolve = resolve; + $Q.all = all; + $Q.race = race; - forEach(this.$$listenerCount, bind(null, decrementListenerCount, this)); + return $Q; + } - // sever all the references to parent scopes (after this cleanup, the current scope should - // not be retained by any of our references and should be eligible for garbage collection) - if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; - if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; - if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; - if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; + function isStateExceptionHandled(state) { + return !!state.pur; + } + function markQStateExceptionHandled(state) { + state.pur = true; + } + function markQExceptionHandled(q) { + markQStateExceptionHandled(q.$$state); + } + /** @this */ + function $$RAFProvider() { //rAF + this.$get = ['$window', '$timeout', function($window, $timeout) { + var requestAnimationFrame = $window.requestAnimationFrame || + $window.webkitRequestAnimationFrame; - // All of the code below is bogus code that works around V8's memory leak via optimized code - // and inline caches. - // - // see: - // - https://code.google.com/p/v8/issues/detail?id=2073#c26 - // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 - // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 + var cancelAnimationFrame = $window.cancelAnimationFrame || + $window.webkitCancelAnimationFrame || + $window.webkitCancelRequestAnimationFrame; - this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = - this.$$childTail = this.$root = null; + var rafSupported = !!requestAnimationFrame; + var raf = rafSupported + ? function(fn) { + var id = requestAnimationFrame(fn); + return function() { + cancelAnimationFrame(id); + }; + } + : function(fn) { + var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 + return function() { + $timeout.cancel(timer); + }; + }; - // don't reset these to null in case some async task tries to register a listener/watch/task - this.$$listeners = {}; - this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = []; + raf.supported = rafSupported; - // prevent NPEs since these methods have references to properties we nulled out - this.$destroy = this.$digest = this.$apply = noop; - this.$on = this.$watch = function() { return noop; }; - }, + return raf; + }]; + } - /** - * @ngdoc method - * @name $rootScope.Scope#$eval - * @function - * - * @description - * Executes the `expression` on the current scope and returns the result. Any exceptions in - * the expression are propagated (uncaught). This is useful when evaluating Angular - * expressions. - * - * # Example - * ```js - var scope = ng.$rootScope.Scope(); - scope.a = 1; - scope.b = 2; + /** + * DESIGN NOTES + * + * The design decisions behind the scope are heavily favored for speed and memory consumption. + * + * The typical use of scope is to watch the expressions, which most of the time return the same + * value as last time so we optimize the operation. + * + * Closures construction is expensive in terms of speed as well as memory: + * - No closures, instead use prototypical inheritance for API + * - Internal state needs to be stored on scope directly, which means that private state is + * exposed as $$____ properties + * + * Loop operations are optimized by using while(count--) { ... } + * - This means that in order to keep the same order of execution as addition we have to add + * items to the array at the beginning (unshift) instead of at the end (push) + * + * Child scopes are created and removed often + * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists + * + * There are fewer watches than observers. This is why you don't want the observer to be implemented + * in the same way as watch. Watch requires return of the initialization function which is expensive + * to construct. + */ - expect(scope.$eval('a+b')).toEqual(3); - expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); - * ``` - * - * @param {(string|function())=} expression An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with the current `scope` parameter. - * - * @param {(object)=} locals Local variables object, useful for overriding values in scope. - * @returns {*} The result of evaluating the expression. - */ - $eval: function(expr, locals) { - return $parse(expr)(this, locals); - }, + /** + * @ngdoc provider + * @name $rootScopeProvider + * @description + * + * Provider for the $rootScope service. + */ + + /** + * @ngdoc method + * @name $rootScopeProvider#digestTtl + * @description + * + * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and + * assuming that the model is unstable. + * + * The current default is 10 iterations. + * + * In complex applications it's possible that the dependencies between `$watch`s will result in + * several digest iterations. However if an application needs more than the default 10 digest + * iterations for its model to stabilize then you should investigate what is causing the model to + * continuously change during the digest. + * + * Increasing the TTL could have performance implications, so you should not change it without + * proper justification. + * + * @param {number} limit The number of digest iterations. + */ + + + /** + * @ngdoc service + * @name $rootScope + * @this + * + * @description + * + * Every application has a single root {@link ng.$rootScope.Scope scope}. + * All other scopes are descendant scopes of the root scope. Scopes provide separation + * between the model and the view, via a mechanism for watching the model for changes. + * They also provide event emission/broadcast and subscription facility. See the + * {@link guide/scope developer guide on scopes}. + */ + function $RootScopeProvider() { + var TTL = 10; + var $rootScopeMinErr = minErr('$rootScope'); + var lastDirtyWatch = null; + var applyAsyncId = null; + + this.digestTtl = function(value) { + if (arguments.length) { + TTL = value; + } + return TTL; + }; + + function createChildScopeClass(parent) { + function ChildScope() { + this.$$watchers = this.$$nextSibling = + this.$$childHead = this.$$childTail = null; + this.$$listeners = {}; + this.$$listenerCount = {}; + this.$$watchersCount = 0; + this.$id = nextUid(); + this.$$ChildScope = null; + } + ChildScope.prototype = parent; + return ChildScope; + } + + this.$get = ['$exceptionHandler', '$parse', '$browser', + function($exceptionHandler, $parse, $browser) { + + function destroyChildScope($event) { + $event.currentScope.$$destroyed = true; + } + + function cleanUpScope($scope) { + + // Support: IE 9 only + if (msie === 9) { + // There is a memory leak in IE9 if all child scopes are not disconnected + // completely when a scope is destroyed. So this code will recurse up through + // all this scopes children + // + // See issue https://github.com/angular/angular.js/issues/10706 + if ($scope.$$childHead) { + cleanUpScope($scope.$$childHead); + } + if ($scope.$$nextSibling) { + cleanUpScope($scope.$$nextSibling); + } + } + + // The code below works around IE9 and V8's memory leaks + // + // See: + // - https://code.google.com/p/v8/issues/detail?id=2073#c26 + // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 + // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 + + $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead = + $scope.$$childTail = $scope.$root = $scope.$$watchers = null; + } + + /** + * @ngdoc type + * @name $rootScope.Scope + * + * @description + * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the + * {@link auto.$injector $injector}. Child scopes are created using the + * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when + * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for + * an in-depth introduction and usage examples. + * + * + * ## Inheritance + * A scope can inherit from a parent scope, as in this example: + * ```js + var parent = $rootScope; + var child = parent.$new(); + + parent.salutation = "Hello"; + expect(child.salutation).toEqual('Hello'); + + child.salutation = "Welcome"; + expect(child.salutation).toEqual('Welcome'); + expect(parent.salutation).toEqual('Hello'); + * ``` + * + * When interacting with `Scope` in tests, additional helper methods are available on the + * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional + * details. + * + * + * @param {Object.=} providers Map of service factory which need to be + * provided for the current scope. Defaults to {@link ng}. + * @param {Object.=} instanceCache Provides pre-instantiated services which should + * append/override services provided by `providers`. This is handy + * when unit-testing and having the need to override a default + * service. + * @returns {Object} Newly created scope. + * + */ + function Scope() { + this.$id = nextUid(); + this.$$phase = this.$parent = this.$$watchers = + this.$$nextSibling = this.$$prevSibling = + this.$$childHead = this.$$childTail = null; + this.$root = this; + this.$$destroyed = false; + this.$$listeners = {}; + this.$$listenerCount = {}; + this.$$watchersCount = 0; + this.$$isolateBindings = null; + } + + /** + * @ngdoc property + * @name $rootScope.Scope#$id + * + * @description + * Unique scope ID (monotonically increasing) useful for debugging. + */ + + /** + * @ngdoc property + * @name $rootScope.Scope#$parent + * + * @description + * Reference to the parent scope. + */ + + /** + * @ngdoc property + * @name $rootScope.Scope#$root + * + * @description + * Reference to the root scope. + */ + + Scope.prototype = { + constructor: Scope, /** * @ngdoc method - * @name $rootScope.Scope#$evalAsync - * @function + * @name $rootScope.Scope#$new + * @kind function * * @description - * Executes the expression on the current scope at a later point in time. - * - * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only - * that: + * Creates a new child {@link ng.$rootScope.Scope scope}. * - * - it will execute after the function that scheduled the evaluation (preferably before DOM - * rendering). - * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after - * `expression` execution. + * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. + * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * - * Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. + * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is + * desired for the scope and its child scopes to be permanently detached from the parent and + * thus stop participating in model change detection and listener notification by invoking. * - * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle - * will be scheduled. However, it is encouraged to always call code that changes the model - * from within an `$apply` call. That includes code evaluated via `$evalAsync`. + * @param {boolean} isolate If true, then the scope does not prototypically inherit from the + * parent scope. The scope is isolated, as it can not see parent scope properties. + * When creating widgets, it is useful for the widget to not accidentally read parent + * state. * - * @param {(string|function())=} expression An angular expression to be executed. + * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent` + * of the newly created scope. Defaults to `this` scope if not provided. + * This is used when creating a transclude scope to correctly place it + * in the scope hierarchy while maintaining the correct prototypical + * inheritance. * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with the current `scope` parameter. + * @returns {Object} The newly created child scope. * */ - $evalAsync: function(expr) { - // if we are outside of an $digest loop and this is the first time we are scheduling async - // task also schedule async auto-flush - if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) { - $browser.defer(function() { - if ($rootScope.$$asyncQueue.length) { - $rootScope.$digest(); - } - }); + $new: function(isolate, parent) { + var child; + + parent = parent || this; + + if (isolate) { + child = new Scope(); + child.$root = this.$root; + } else { + // Only create a child scope class if somebody asks for one, + // but cache it to allow the VM to optimize lookups. + if (!this.$$ChildScope) { + this.$$ChildScope = createChildScopeClass(this); + } + child = new this.$$ChildScope(); + } + child.$parent = parent; + child.$$prevSibling = parent.$$childTail; + if (parent.$$childHead) { + parent.$$childTail.$$nextSibling = child; + parent.$$childTail = child; + } else { + parent.$$childHead = parent.$$childTail = child; } - this.$$asyncQueue.push({scope: this, expression: expr}); - }, + // When the new scope is not isolated or we inherit from `this`, and + // the parent scope is destroyed, the property `$$destroyed` is inherited + // prototypically. In all other cases, this property needs to be set + // when the parent scope is destroyed. + // The listener needs to be added after the parent is set + if (isolate || parent !== this) child.$on('$destroy', destroyChildScope); - $$postDigest : function(fn) { - this.$$postDigestQueue.push(fn); + return child; }, /** * @ngdoc method - * @name $rootScope.Scope#$apply - * @function + * @name $rootScope.Scope#$watch + * @kind function * * @description - * `$apply()` is used to execute an expression in angular from outside of the angular - * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). - * Because we are calling into the angular framework we need to perform proper scope life - * cycle of {@link ng.$exceptionHandler exception handling}, - * {@link ng.$rootScope.Scope#$digest executing watches}. - * - * ## Life cycle + * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * - * # Pseudo-Code of `$apply()` - * ```js - function $apply(expr) { - try { - return $eval(expr); - } catch (e) { - $exceptionHandler(e); - } finally { - $root.$digest(); - } - } - * ``` + * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest + * $digest()} and should return the value that will be watched. (`watchExpression` should not change + * its value when executed multiple times with the same input because it may be executed multiple + * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be + * [idempotent](http://en.wikipedia.org/wiki/Idempotence).) + * - The `listener` is called only when the value from the current `watchExpression` and the + * previous call to `watchExpression` are not equal (with the exception of the initial run, + * see below). Inequality is determined according to reference inequality, + * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) + * via the `!==` Javascript operator, unless `objectEquality == true` + * (see next point) + * - When `objectEquality == true`, inequality of the `watchExpression` is determined + * according to the {@link angular.equals} function. To save the value of the object for + * later comparison, the {@link angular.copy} function is used. This therefore means that + * watching complex objects will have adverse memory and performance implications. + * - This should not be used to watch for changes in objects that are + * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}. + * - The watch `listener` may change the model, which may trigger other `listener`s to fire. + * This is achieved by rerunning the watchers until no changes are detected. The rerun + * iteration limit is 10 to prevent an infinite loop deadlock. * * - * Scope's `$apply()` method transitions through the following stages: + * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, + * you can register a `watchExpression` function with no `listener`. (Be prepared for + * multiple calls to your `watchExpression` because it will execute multiple times in a + * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.) * - * 1. The {@link guide/expression expression} is executed using the - * {@link ng.$rootScope.Scope#$eval $eval()} method. - * 2. Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. - * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the - * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. + * After a watcher is registered with the scope, the `listener` fn is called asynchronously + * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the + * watcher. In rare cases, this is undesirable because the listener is called when the result + * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you + * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the + * listener was called due to initialization. * * - * @param {(string|function())=} exp An angular expression to be executed. * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with current `scope` parameter. - * - * @returns {*} The result of evaluating the expression. - */ - $apply: function(expr) { - try { - beginPhase('$apply'); - return this.$eval(expr); - } catch (e) { - $exceptionHandler(e); - } finally { - clearPhase(); - try { - $rootScope.$digest(); - } catch (e) { - $exceptionHandler(e); - throw e; - } - } - }, + * @example + * ```js + // let's assume that scope was dependency injected as the $rootScope + var scope = $rootScope; + scope.name = 'misko'; + scope.counter = 0; - /** - * @ngdoc method - * @name $rootScope.Scope#$on - * @function + expect(scope.counter).toEqual(0); + scope.$watch('name', function(newValue, oldValue) { + scope.counter = scope.counter + 1; + }); + expect(scope.counter).toEqual(0); + + scope.$digest(); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); + + scope.$digest(); + // but now it will not be called unless the value changes + expect(scope.counter).toEqual(1); + + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); + + + + // Using a function as a watchExpression + var food; + scope.foodCounter = 0; + expect(scope.foodCounter).toEqual(0); + scope.$watch( + // This function returns the value being watched. It is called for each turn of the $digest loop + function() { return food; }, + // This is the change listener, called when the value returned from the above function changes + function(newValue, oldValue) { + if ( newValue !== oldValue ) { + // Only increment the counter if the value changed + scope.foodCounter = scope.foodCounter + 1; + } + } + ); + // No digest has been run so the counter will be zero + expect(scope.foodCounter).toEqual(0); + + // Run the digest but since food has not changed count will still be zero + scope.$digest(); + expect(scope.foodCounter).toEqual(0); + + // Update food and run digest. Now the counter will increment + food = 'cheeseburger'; + scope.$digest(); + expect(scope.foodCounter).toEqual(1); + + * ``` * - * @description - * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for - * discussion of event life cycle. * - * The event listener function format is: `function(event, args...)`. The `event` object - * passed into the listener has the following attributes: * - * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or - * `$broadcast`-ed. - * - `currentScope` - `{Scope}`: the current scope which is handling the event. - * - `name` - `{string}`: name of the event. - * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel - * further event propagation (available only for events that were `$emit`-ed). - * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag - * to true. - * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. + * @param {(function()|string)} watchExpression Expression that is evaluated on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers + * a call to the `listener`. * - * @param {string} name Event name to listen on. - * @param {function(event, ...args)} listener Function to call when the event is emitted. + * - `string`: Evaluated as {@link guide/expression expression} + * - `function(scope)`: called with current `scope` as a parameter. + * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value + * of `watchExpression` changes. + * + * - `newVal` contains the current value of the `watchExpression` + * - `oldVal` contains the previous value of the `watchExpression` + * - `scope` refers to the current scope + * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of + * comparing for reference equality. * @returns {function()} Returns a deregistration function for this listener. */ - $on: function(name, listener) { - var namedListeners = this.$$listeners[name]; - if (!namedListeners) { - this.$$listeners[name] = namedListeners = []; + $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) { + var get = $parse(watchExp); + var fn = isFunction(listener) ? listener : noop; + + if (get.$$watchDelegate) { + return get.$$watchDelegate(this, fn, objectEquality, get, watchExp); } - namedListeners.push(listener); + var scope = this, + array = scope.$$watchers, + watcher = { + fn: fn, + last: initWatchVal, + get: get, + exp: prettyPrintExpression || watchExp, + eq: !!objectEquality + }; - var current = this; - do { - if (!current.$$listenerCount[name]) { - current.$$listenerCount[name] = 0; - } - current.$$listenerCount[name]++; - } while ((current = current.$parent)); + lastDirtyWatch = null; - var self = this; - return function() { - namedListeners[indexOf(namedListeners, listener)] = null; - decrementListenerCount(self, 1, name); + if (!array) { + array = scope.$$watchers = []; + array.$$digestWatchIndex = -1; + } + // we use unshift since we use a while loop in $digest for speed. + // the while loop reads in reverse order. + array.unshift(watcher); + array.$$digestWatchIndex++; + incrementWatchersCount(this, 1); + + return function deregisterWatch() { + var index = arrayRemove(array, watcher); + if (index >= 0) { + incrementWatchersCount(scope, -1); + if (index < array.$$digestWatchIndex) { + array.$$digestWatchIndex--; + } + } + lastDirtyWatch = null; }; }, - /** * @ngdoc method - * @name $rootScope.Scope#$emit - * @function + * @name $rootScope.Scope#$watchGroup + * @kind function * * @description - * Dispatches an event `name` upwards through the scope hierarchy notifying the - * registered {@link ng.$rootScope.Scope#$on} listeners. + * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. + * If any one expression in the collection changes the `listener` is executed. * - * The event life cycle starts at the scope on which `$emit` was called. All - * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get - * notified. Afterwards, the event traverses upwards toward the root scope and calls all - * registered listeners along the way. The event will stop propagating if one of the listeners - * cancels it. + * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return + * values are examined for changes on every call to `$digest`. + * - The `listener` is called whenever any expression in the `watchExpressions` array changes. * - * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed - * onto the {@link ng.$exceptionHandler $exceptionHandler} service. + * `$watchGroup` is more performant than watching each expression individually, and should be + * used when the listener does not need to know which expression has changed. + * If the listener needs to know which expression has changed, + * {@link ng.$rootScope.Scope#$watch $watch()} or + * {@link ng.$rootScope.Scope#$watchCollection $watchCollection()} should be used. * - * @param {string} name Event name to emit. - * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. - * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). + * @param {Array.} watchExpressions Array of expressions that will be individually + * watched using {@link ng.$rootScope.Scope#$watch $watch()} + * + * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any + * expression in `watchExpressions` changes + * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching + * those of `watchExpression` + * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching + * those of `watchExpression`. + * + * Note that `newValues` and `oldValues` reflect the differences in each **individual** + * expression, and not the difference of the values between each call of the listener. + * That means the difference between `newValues` and `oldValues` cannot be used to determine + * which expression has changed / remained stable: + * + * ```js + * + * $scope.$watchGroup(['v1', 'v2'], function(newValues, oldValues) { + * console.log(newValues, oldValues); + * }); + * + * // newValues, oldValues initially + * // [undefined, undefined], [undefined, undefined] + * + * $scope.v1 = 'a'; + * $scope.v2 = 'a'; + * + * // ['a', 'a'], [undefined, undefined] + * + * $scope.v2 = 'b' + * + * // v1 hasn't changed since it became `'a'`, therefore its oldValue is still `undefined` + * // ['a', 'b'], [undefined, 'a'] + * + * ``` + * + * The `scope` refers to the current scope. + * @returns {function()} Returns a de-registration function for all listeners. */ - $emit: function(name, args) { - var empty = [], - namedListeners, - scope = this, - stopPropagation = false, - event = { - name: name, - targetScope: scope, - stopPropagation: function() {stopPropagation = true;}, - preventDefault: function() { - event.defaultPrevented = true; - }, - defaultPrevented: false - }, - listenerArgs = concat([event], arguments, 1), - i, length; + $watchGroup: function(watchExpressions, listener) { + var oldValues = new Array(watchExpressions.length); + var newValues = new Array(watchExpressions.length); + var deregisterFns = []; + var self = this; + var changeReactionScheduled = false; + var firstRun = true; + + if (!watchExpressions.length) { + // No expressions means we call the listener ASAP + var shouldCall = true; + self.$evalAsync(function() { + if (shouldCall) listener(newValues, newValues, self); + }); + return function deregisterWatchGroup() { + shouldCall = false; + }; + } - do { - namedListeners = scope.$$listeners[name] || empty; - event.currentScope = scope; - for (i=0, length=namedListeners.length; i 1); + var changeDetected = 0; + var changeDetector = $parse(obj, $watchCollectionInterceptor); + var internalArray = []; + var internalObject = {}; + var initRun = true; + var oldLength = 0; + function $watchCollectionInterceptor(_value) { + newValue = _value; + var newLength, key, bothNaN, newItem, oldItem; - function beginPhase(phase) { - if ($rootScope.$$phase) { - throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); - } + // If the new value is undefined, then return undefined as the watch may be a one-time watch + if (isUndefined(newValue)) return; - $rootScope.$$phase = phase; - } + if (!isObject(newValue)) { // if primitive + if (oldValue !== newValue) { + oldValue = newValue; + changeDetected++; + } + } else if (isArrayLike(newValue)) { + if (oldValue !== internalArray) { + // we are transitioning from something which was not an array into array. + oldValue = internalArray; + oldLength = oldValue.length = 0; + changeDetected++; + } - function clearPhase() { - $rootScope.$$phase = null; - } + newLength = newValue.length; - function compileToFn(exp, name) { - var fn = $parse(exp); - assertArgFn(fn, name); - return fn; - } + if (oldLength !== newLength) { + // if lengths do not match we need to trigger change notification + changeDetected++; + oldValue.length = oldLength = newLength; + } + // copy the items to oldValue and look for changes. + for (var i = 0; i < newLength; i++) { + oldItem = oldValue[i]; + newItem = newValue[i]; - function decrementListenerCount(current, count, name) { - do { - current.$$listenerCount[name] -= count; + // eslint-disable-next-line no-self-compare + bothNaN = (oldItem !== oldItem) && (newItem !== newItem); + if (!bothNaN && (oldItem !== newItem)) { + changeDetected++; + oldValue[i] = newItem; + } + } + } else { + if (oldValue !== internalObject) { + // we are transitioning from something which was not an object into object. + oldValue = internalObject = {}; + oldLength = 0; + changeDetected++; + } + // copy the items to oldValue and look for changes. + newLength = 0; + for (key in newValue) { + if (hasOwnProperty.call(newValue, key)) { + newLength++; + newItem = newValue[key]; + oldItem = oldValue[key]; - if (current.$$listenerCount[name] === 0) { - delete current.$$listenerCount[name]; + if (key in oldValue) { + // eslint-disable-next-line no-self-compare + bothNaN = (oldItem !== oldItem) && (newItem !== newItem); + if (!bothNaN && (oldItem !== newItem)) { + changeDetected++; + oldValue[key] = newItem; + } + } else { + oldLength++; + oldValue[key] = newItem; + changeDetected++; + } + } + } + if (oldLength > newLength) { + // we used to have more keys, need to find them and destroy them. + changeDetected++; + for (key in oldValue) { + if (!hasOwnProperty.call(newValue, key)) { + oldLength--; + delete oldValue[key]; + } + } + } + } + return changeDetected; } - } while ((current = current.$parent)); - } - /** - * function used as an initial value for watchers. - * because it's unique we can easily tell it apart from other values - */ - function initWatchVal() {} - }]; - } + function $watchCollectionAction() { + if (initRun) { + initRun = false; + listener(newValue, newValue, self); + } else { + listener(newValue, veryOldValue, self); + } - /** - * @description - * Private service to sanitize uris for links and images. Used by $compile and $sanitize. - */ - function $$SanitizeUriProvider() { - var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, - imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//; + // make a copy for the next time a collection is changed + if (trackVeryOldValue) { + if (!isObject(newValue)) { + //primitive + veryOldValue = newValue; + } else if (isArrayLike(newValue)) { + veryOldValue = new Array(newValue.length); + for (var i = 0; i < newValue.length; i++) { + veryOldValue[i] = newValue[i]; + } + } else { // if object + veryOldValue = {}; + for (var key in newValue) { + if (hasOwnProperty.call(newValue, key)) { + veryOldValue[key] = newValue[key]; + } + } + } + } + } - /** - * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of safe - * urls during a[href] sanitization. - * - * The sanitization is a security measure aimed at prevent XSS attacks via html links. - * - * Any url about to be assigned to a[href] via data-binding is first normalized and turned into - * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` - * regular expression. If a match is found, the original url is written into the dom. Otherwise, - * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. - * - * @param {RegExp=} regexp New regexp to whitelist urls with. - * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for - * chaining otherwise. - */ - this.aHrefSanitizationWhitelist = function(regexp) { - if (isDefined(regexp)) { - aHrefSanitizationWhitelist = regexp; - return this; - } - return aHrefSanitizationWhitelist; - }; + return this.$watch(changeDetector, $watchCollectionAction); + }, + /** + * @ngdoc method + * @name $rootScope.Scope#$digest + * @kind function + * + * @description + * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and + * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change + * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} + * until no more listeners are firing. This means that it is possible to get into an infinite + * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of + * iterations exceeds 10. + * + * Usually, you don't call `$digest()` directly in + * {@link ng.directive:ngController controllers} or in + * {@link ng.$compileProvider#directive directives}. + * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within + * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. + * + * If you want to be notified whenever `$digest()` is called, + * you can register a `watchExpression` function with + * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. + * + * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. + * + * @example + * ```js + var scope = ...; + scope.name = 'misko'; + scope.counter = 0; - /** - * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of safe - * urls during img[src] sanitization. - * - * The sanitization is a security measure aimed at prevent XSS attacks via html links. - * - * Any url about to be assigned to img[src] via data-binding is first normalized and turned into - * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` - * regular expression. If a match is found, the original url is written into the dom. Otherwise, - * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. - * - * @param {RegExp=} regexp New regexp to whitelist urls with. - * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for - * chaining otherwise. - */ - this.imgSrcSanitizationWhitelist = function(regexp) { - if (isDefined(regexp)) { - imgSrcSanitizationWhitelist = regexp; - return this; - } - return imgSrcSanitizationWhitelist; - }; + expect(scope.counter).toEqual(0); + scope.$watch('name', function(newValue, oldValue) { + scope.counter = scope.counter + 1; + }); + expect(scope.counter).toEqual(0); - this.$get = function() { - return function sanitizeUri(uri, isImage) { - var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; - var normalizedVal; - // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case. - if (!msie || msie >= 8 ) { - normalizedVal = urlResolve(uri).href; - if (normalizedVal !== '' && !normalizedVal.match(regex)) { - return 'unsafe:'+normalizedVal; - } - } - return uri; - }; - }; - } + scope.$digest(); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); - var $sceMinErr = minErr('$sce'); - - var SCE_CONTEXTS = { - HTML: 'html', - CSS: 'css', - URL: 'url', - // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a - // url. (e.g. ng-include, script src, templateUrl) - RESOURCE_URL: 'resourceUrl', - JS: 'js' - }; - -// Helper functions follow. - -// Copied from: -// http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962 -// Prereq: s is a string. - function escapeForRegexp(s) { - return s.replace(/([-()\[\]{}+?*.$\^|,:# -1) { - throw $sceMinErr('iwcard', - 'Illegal sequence *** in string matcher. String: {0}', matcher); - } - matcher = escapeForRegexp(matcher). - replace('\\*\\*', '.*'). - replace('\\*', '[^:/.?&;]*'); - return new RegExp('^' + matcher + '$'); - } else if (isRegExp(matcher)) { - // The only other type of matcher allowed is a Regexp. - // Match entire URL / disallow partial matches. - // Flags are reset (i.e. no global, ignoreCase or multiline) - return new RegExp('^' + matcher.source + '$'); - } else { - throw $sceMinErr('imatcher', - 'Matchers may only be "self", string patterns or RegExp objects'); - } - } + scope.$digest(); + // but now it will not be called unless the value changes + expect(scope.counter).toEqual(1); + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); + * ``` + * + */ + $digest: function() { + var watch, value, last, fn, get, + watchers, + dirty, ttl = TTL, + next, current, target = this, + watchLog = [], + logIdx, asyncTask; - function adjustMatchers(matchers) { - var adjustedMatchers = []; - if (isDefined(matchers)) { - forEach(matchers, function(matcher) { - adjustedMatchers.push(adjustMatcher(matcher)); - }); - } - return adjustedMatchers; - } + beginPhase('$digest'); + // Check for changes to browser url that happened in sync before the call to $digest + $browser.$$checkUrlChange(); + + if (this === $rootScope && applyAsyncId !== null) { + // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then + // cancel the scheduled $apply and flush the queue of expressions to be evaluated. + $browser.defer.cancel(applyAsyncId); + flushApplyAsync(); + } + lastDirtyWatch = null; - /** - * @ngdoc service - * @name $sceDelegate - * @function - * - * @description - * - * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict - * Contextual Escaping (SCE)} services to AngularJS. - * - * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of - * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is - * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to - * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things - * work because `$sce` delegates to `$sceDelegate` for these operations. - * - * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. - * - * The default instance of `$sceDelegate` should work out of the box with little pain. While you - * can override it completely to change the behavior of `$sce`, the common case would - * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting - * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as - * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist - * $sceDelegateProvider.resourceUrlWhitelist} and {@link - * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} - */ + do { // "while dirty" loop + dirty = false; + current = target; - /** - * @ngdoc provider - * @name $sceDelegateProvider - * @description - * - * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate - * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure - * that the URLs used for sourcing Angular templates are safe. Refer {@link - * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and - * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} - * - * For the general details about this service in Angular, read the main page for {@link ng.$sce - * Strict Contextual Escaping (SCE)}. - * - * **Example**: Consider the following case.
    - * - * - your app is hosted at url `http://myapp.example.com/` - * - but some of your templates are hosted on other domains you control such as - * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. - * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. - * - * Here is what a secure configuration for this scenario might look like: - * - *
    -     *    angular.module('myApp', []).config(function($sceDelegateProvider) {
    - *      $sceDelegateProvider.resourceUrlWhitelist([
    - *        // Allow same origin resource loads.
    - *        'self',
    - *        // Allow loading from our assets domain.  Notice the difference between * and **.
    - *        'http://srv*.assets.example.com/**']);
    - *
    - *      // The blacklist overrides the whitelist so the open redirect here is blocked.
    - *      $sceDelegateProvider.resourceUrlBlacklist([
    - *        'http://myapp.example.com/clickThru**']);
    - *      });
    -     * 
    - */ + // It's safe for asyncQueuePosition to be a local variable here because this loop can't + // be reentered recursively. Calling $digest from a function passed to $evalAsync would + // lead to a '$digest already in progress' error. + for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) { + try { + asyncTask = asyncQueue[asyncQueuePosition]; + fn = asyncTask.fn; + fn(asyncTask.scope, asyncTask.locals); + } catch (e) { + $exceptionHandler(e); + } + lastDirtyWatch = null; + } + asyncQueue.length = 0; - function $SceDelegateProvider() { - this.SCE_CONTEXTS = SCE_CONTEXTS; + traverseScopesLoop: + do { // "traverse the scopes" loop + if ((watchers = current.$$watchers)) { + // process our watches + watchers.$$digestWatchIndex = watchers.length; + while (watchers.$$digestWatchIndex--) { + try { + watch = watchers[watchers.$$digestWatchIndex]; + // Most common watches are on primitives, in which case we can short + // circuit it with === operator, only when === fails do we use .equals + if (watch) { + get = watch.get; + if ((value = get(current)) !== (last = watch.last) && + !(watch.eq + ? equals(value, last) + : (isNumberNaN(value) && isNumberNaN(last)))) { + dirty = true; + lastDirtyWatch = watch; + watch.last = watch.eq ? copy(value, null) : value; + fn = watch.fn; + fn(value, ((last === initWatchVal) ? value : last), current); + if (ttl < 5) { + logIdx = 4 - ttl; + if (!watchLog[logIdx]) watchLog[logIdx] = []; + watchLog[logIdx].push({ + msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp, + newVal: value, + oldVal: last + }); + } + } else if (watch === lastDirtyWatch) { + // If the most recently dirty watcher is now clean, short circuit since the remaining watchers + // have already been tested. + dirty = false; + break traverseScopesLoop; + } + } + } catch (e) { + $exceptionHandler(e); + } + } + } - // Resource URLs can also be trusted by policy. - var resourceUrlWhitelist = ['self'], - resourceUrlBlacklist = []; + // Insanity Warning: scope depth-first traversal + // yes, this code is a bit crazy, but it works and we have tests to prove it! + // this piece should be kept in sync with the traversal in $broadcast + if (!(next = ((current.$$watchersCount && current.$$childHead) || + (current !== target && current.$$nextSibling)))) { + while (current !== target && !(next = current.$$nextSibling)) { + current = current.$parent; + } + } + } while ((current = next)); - /** - * @ngdoc method - * @name $sceDelegateProvider#resourceUrlWhitelist - * @function - * - * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value - * provided. This must be an array or null. A snapshot of this array is used so further - * changes to the array are ignored. - * - * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items - * allowed in this array. - * - * Note: **an empty whitelist array will block all URLs**! - * - * @return {Array} the currently set whitelist array. - * - * The **default value** when no whitelist has been explicitly set is `['self']` allowing only - * same origin resource requests. - * - * @description - * Sets/Gets the whitelist of trusted resource URLs. - */ - this.resourceUrlWhitelist = function (value) { - if (arguments.length) { - resourceUrlWhitelist = adjustMatchers(value); - } - return resourceUrlWhitelist; - }; + // `break traverseScopesLoop;` takes us to here - /** - * @ngdoc method - * @name $sceDelegateProvider#resourceUrlBlacklist - * @function - * - * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value - * provided. This must be an array or null. A snapshot of this array is used so further - * changes to the array are ignored. - * - * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items - * allowed in this array. - * - * The typical usage for the blacklist is to **block - * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as - * these would otherwise be trusted but actually return content from the redirected domain. - * - * Finally, **the blacklist overrides the whitelist** and has the final say. - * - * @return {Array} the currently set blacklist array. - * - * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there - * is no blacklist.) - * - * @description - * Sets/Gets the blacklist of trusted resource URLs. - */ + if ((dirty || asyncQueue.length) && !(ttl--)) { + clearPhase(); + throw $rootScopeMinErr('infdig', + '{0} $digest() iterations reached. Aborting!\n' + + 'Watchers fired in the last 5 iterations: {1}', + TTL, watchLog); + } - this.resourceUrlBlacklist = function (value) { - if (arguments.length) { - resourceUrlBlacklist = adjustMatchers(value); - } - return resourceUrlBlacklist; - }; + } while (dirty || asyncQueue.length); - this.$get = ['$injector', function($injector) { + clearPhase(); - var htmlSanitizer = function htmlSanitizer(html) { - throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); - }; + // postDigestQueuePosition isn't local here because this loop can be reentered recursively. + while (postDigestQueuePosition < postDigestQueue.length) { + try { + postDigestQueue[postDigestQueuePosition++](); + } catch (e) { + $exceptionHandler(e); + } + } + postDigestQueue.length = postDigestQueuePosition = 0; - if ($injector.has('$sanitize')) { - htmlSanitizer = $injector.get('$sanitize'); - } + // Check for changes to browser url that happened during the $digest + // (for which no event is fired; e.g. via `history.pushState()`) + $browser.$$checkUrlChange(); + }, - function matchUrl(matcher, parsedUrl) { - if (matcher === 'self') { - return urlIsSameOrigin(parsedUrl); - } else { - // definitely a regex. See adjustMatchers() - return !!matcher.exec(parsedUrl.href); - } - } + /** + * @ngdoc event + * @name $rootScope.Scope#$destroy + * @eventType broadcast on scope being destroyed + * + * @description + * Broadcasted when a scope and its children are being destroyed. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. + */ - function isResourceUrlAllowedByPolicy(url) { - var parsedUrl = urlResolve(url.toString()); - var i, n, allowed = false; - // Ensure that at least one item from the whitelist allows this url. - for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { - if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { - allowed = true; - break; - } - } - if (allowed) { - // Ensure that no item from the blacklist blocked this url. - for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { - if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { - allowed = false; - break; - } - } - } - return allowed; - } + /** + * @ngdoc method + * @name $rootScope.Scope#$destroy + * @kind function + * + * @description + * Removes the current scope (and all of its children) from the parent scope. Removal implies + * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer + * propagate to the current scope and its children. Removal also implies that the current + * scope is eligible for garbage collection. + * + * The `$destroy()` is usually used by directives such as + * {@link ng.directive:ngRepeat ngRepeat} for managing the + * unrolling of the loop. + * + * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. + * Application code can register a `$destroy` event handler that will give it a chance to + * perform any necessary cleanup. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. + */ + $destroy: function() { + // We can't destroy a scope that has been already destroyed. + if (this.$$destroyed) return; + var parent = this.$parent; - function generateHolderType(Base) { - var holderType = function TrustedValueHolderType(trustedValue) { - this.$$unwrapTrustedValue = function() { - return trustedValue; - }; - }; - if (Base) { - holderType.prototype = new Base(); - } - holderType.prototype.valueOf = function sceValueOf() { - return this.$$unwrapTrustedValue(); - }; - holderType.prototype.toString = function sceToString() { - return this.$$unwrapTrustedValue().toString(); - }; - return holderType; - } + this.$broadcast('$destroy'); + this.$$destroyed = true; - var trustedValueHolderBase = generateHolderType(), - byType = {}; + if (this === $rootScope) { + //Remove handlers attached to window when $rootScope is removed + $browser.$$applicationDestroyed(); + } - byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); + incrementWatchersCount(this, -this.$$watchersCount); + for (var eventName in this.$$listenerCount) { + decrementListenerCount(this, this.$$listenerCount[eventName], eventName); + } - /** - * @ngdoc method - * @name $sceDelegate#trustAs - * - * @description - * Returns an object that is trusted by angular for use in specified strict - * contextual escaping contexts (such as ng-bind-html, ng-include, any src - * attribute interpolation, any dom event binding attribute interpolation - * such as for onclick, etc.) that uses the provided value. - * See {@link ng.$sce $sce} for enabling strict contextual escaping. - * - * @param {string} type The kind of context in which this value is safe for use. e.g. url, - * resourceUrl, html, js and css. - * @param {*} value The value that that should be considered trusted/safe. - * @returns {*} A value that can be used to stand in for the provided `value` in places - * where Angular expects a $sce.trustAs() return value. - */ - function trustAs(type, trustedValue) { - var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); - if (!Constructor) { - throw $sceMinErr('icontext', - 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', - type, trustedValue); - } - if (trustedValue === null || trustedValue === undefined || trustedValue === '') { - return trustedValue; - } - // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting - // mutable objects, we ensure here that the value passed in is actually a string. - if (typeof trustedValue !== 'string') { - throw $sceMinErr('itype', - 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', - type); - } - return new Constructor(trustedValue); - } + // sever all the references to parent scopes (after this cleanup, the current scope should + // not be retained by any of our references and should be eligible for garbage collection) + if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling; + if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling; + if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; + if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; - /** - * @ngdoc method - * @name $sceDelegate#valueOf - * - * @description - * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link - * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. - * - * If the passed parameter is not a value that had been returned by {@link - * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is. - * - * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} - * call or anything else. - * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns - * `value` unchanged. - */ - function valueOf(maybeTrusted) { - if (maybeTrusted instanceof trustedValueHolderBase) { - return maybeTrusted.$$unwrapTrustedValue(); - } else { - return maybeTrusted; - } - } + // Disable listeners, watchers and apply/digest methods + this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop; + this.$on = this.$watch = this.$watchGroup = function() { return noop; }; + this.$$listeners = {}; - /** - * @ngdoc method - * @name $sceDelegate#getTrusted - * - * @description - * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and - * returns the originally supplied value if the queried context type is a supertype of the - * created type. If this condition isn't satisfied, throws an exception. - * - * @param {string} type The kind of context in which this value is to be used. - * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`} call. - * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. - */ - function getTrusted(type, maybeTrusted) { - if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { - return maybeTrusted; - } - var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); - if (constructor && maybeTrusted instanceof constructor) { - return maybeTrusted.$$unwrapTrustedValue(); - } - // If we get here, then we may only take one of two actions. - // 1. sanitize the value for the requested type, or - // 2. throw an exception. - if (type === SCE_CONTEXTS.RESOURCE_URL) { - if (isResourceUrlAllowedByPolicy(maybeTrusted)) { - return maybeTrusted; - } else { - throw $sceMinErr('insecurl', - 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', - maybeTrusted.toString()); - } - } else if (type === SCE_CONTEXTS.HTML) { - return htmlSanitizer(maybeTrusted); - } - throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); - } + // Disconnect the next sibling to prevent `cleanUpScope` destroying those too + this.$$nextSibling = null; + cleanUpScope(this); + }, - return { trustAs: trustAs, - getTrusted: getTrusted, - valueOf: valueOf }; - }]; - } + /** + * @ngdoc method + * @name $rootScope.Scope#$eval + * @kind function + * + * @description + * Executes the `expression` on the current scope and returns the result. Any exceptions in + * the expression are propagated (uncaught). This is useful when evaluating AngularJS + * expressions. + * + * @example + * ```js + var scope = ng.$rootScope.Scope(); + scope.a = 1; + scope.b = 2; + expect(scope.$eval('a+b')).toEqual(3); + expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); + * ``` + * + * @param {(string|function())=} expression An AngularJS expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with the current `scope` parameter. + * + * @param {(object)=} locals Local variables object, useful for overriding values in scope. + * @returns {*} The result of evaluating the expression. + */ + $eval: function(expr, locals) { + return $parse(expr)(this, locals); + }, - /** - * @ngdoc provider - * @name $sceProvider - * @description - * - * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. - * - enable/disable Strict Contextual Escaping (SCE) in a module - * - override the default implementation with a custom delegate - * - * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. - */ + /** + * @ngdoc method + * @name $rootScope.Scope#$evalAsync + * @kind function + * + * @description + * Executes the expression on the current scope at a later point in time. + * + * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only + * that: + * + * - it will execute after the function that scheduled the evaluation (preferably before DOM + * rendering). + * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after + * `expression` execution. + * + * Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * + * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle + * will be scheduled. However, it is encouraged to always call code that changes the model + * from within an `$apply` call. That includes code evaluated via `$evalAsync`. + * + * @param {(string|function())=} expression An AngularJS expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with the current `scope` parameter. + * + * @param {(object)=} locals Local variables object, useful for overriding values in scope. + */ + $evalAsync: function(expr, locals) { + // if we are outside of an $digest loop and this is the first time we are scheduling async + // task also schedule async auto-flush + if (!$rootScope.$$phase && !asyncQueue.length) { + $browser.defer(function() { + if (asyncQueue.length) { + $rootScope.$digest(); + } + }); + } - /* jshint maxlen: false*/ + asyncQueue.push({scope: this, fn: $parse(expr), locals: locals}); + }, - /** - * @ngdoc service - * @name $sce - * @function - * - * @description - * - * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. - * - * # Strict Contextual Escaping - * - * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain - * contexts to result in a value that is marked as safe to use for that context. One example of - * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer - * to these contexts as privileged or SCE contexts. - * - * As of version 1.2, Angular ships with SCE enabled by default. - * - * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows - * one to execute arbitrary javascript by the use of the expression() syntax. Refer - * to learn more about them. - * You can ensure your document is in standards mode and not quirks mode by adding `` - * to the top of your HTML document. - * - * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for - * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. - * - * Here's an example of a binding in a privileged context: - * - *
    -     *     
    -     *     
    - *
    - * - * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE - * disabled, this application allows the user to render arbitrary HTML into the DIV. - * In a more realistic example, one may be rendering user comments, blog articles, etc. via - * bindings. (HTML is just one example of a context where rendering user controlled input creates - * security vulnerabilities.) - * - * For the case of HTML, you might use a library, either on the client side, or on the server side, - * to sanitize unsafe HTML before binding to the value and rendering it in the document. - * - * How would you ensure that every place that used these types of bindings was bound to a value that - * was sanitized by your library (or returned as safe for rendering by your server?) How can you - * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some - * properties/fields and forgot to update the binding to the sanitized value? + $$postDigest: function(fn) { + postDigestQueue.push(fn); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$apply + * @kind function + * + * @description + * `$apply()` is used to execute an expression in AngularJS from outside of the AngularJS + * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). + * Because we are calling into the AngularJS framework we need to perform proper scope life + * cycle of {@link ng.$exceptionHandler exception handling}, + * {@link ng.$rootScope.Scope#$digest executing watches}. + * + * **Life cycle: Pseudo-Code of `$apply()`** + * + * ```js + function $apply(expr) { + try { + return $eval(expr); + } catch (e) { + $exceptionHandler(e); + } finally { + $root.$digest(); + } + } + * ``` + * + * + * Scope's `$apply()` method transitions through the following stages: + * + * 1. The {@link guide/expression expression} is executed using the + * {@link ng.$rootScope.Scope#$eval $eval()} method. + * 2. Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the + * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. + * + * + * @param {(string|function())=} exp An AngularJS expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with current `scope` parameter. + * + * @returns {*} The result of evaluating the expression. + */ + $apply: function(expr) { + try { + beginPhase('$apply'); + try { + return this.$eval(expr); + } finally { + clearPhase(); + } + } catch (e) { + $exceptionHandler(e); + } finally { + try { + $rootScope.$digest(); + } catch (e) { + $exceptionHandler(e); + // eslint-disable-next-line no-unsafe-finally + throw e; + } + } + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$applyAsync + * @kind function + * + * @description + * Schedule the invocation of $apply to occur at a later time. The actual time difference + * varies across browsers, but is typically around ~10 milliseconds. + * + * This can be used to queue up multiple expressions which need to be evaluated in the same + * digest. + * + * @param {(string|function())=} exp An AngularJS expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with current `scope` parameter. + */ + $applyAsync: function(expr) { + var scope = this; + if (expr) { + applyAsyncQueue.push($applyAsyncExpression); + } + expr = $parse(expr); + scheduleApplyAsync(); + + function $applyAsyncExpression() { + scope.$eval(expr); + } + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$on + * @kind function + * + * @description + * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for + * discussion of event life cycle. + * + * The event listener function format is: `function(event, args...)`. The `event` object + * passed into the listener has the following attributes: + * + * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or + * `$broadcast`-ed. + * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the + * event propagates through the scope hierarchy, this property is set to null. + * - `name` - `{string}`: name of the event. + * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel + * further event propagation (available only for events that were `$emit`-ed). + * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag + * to true. + * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. + * + * @param {string} name Event name to listen on. + * @param {function(event, ...args)} listener Function to call when the event is emitted. + * @returns {function()} Returns a deregistration function for this listener. + */ + $on: function(name, listener) { + var namedListeners = this.$$listeners[name]; + if (!namedListeners) { + this.$$listeners[name] = namedListeners = []; + } + namedListeners.push(listener); + + var current = this; + do { + if (!current.$$listenerCount[name]) { + current.$$listenerCount[name] = 0; + } + current.$$listenerCount[name]++; + } while ((current = current.$parent)); + + var self = this; + return function() { + var indexOfListener = namedListeners.indexOf(listener); + if (indexOfListener !== -1) { + // Use delete in the hope of the browser deallocating the memory for the array entry, + // while not shifting the array indexes of other listeners. + // See issue https://github.com/angular/angular.js/issues/16135 + delete namedListeners[indexOfListener]; + decrementListenerCount(self, 1, name); + } + }; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$emit + * @kind function + * + * @description + * Dispatches an event `name` upwards through the scope hierarchy notifying the + * registered {@link ng.$rootScope.Scope#$on} listeners. + * + * The event life cycle starts at the scope on which `$emit` was called. All + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get + * notified. Afterwards, the event traverses upwards toward the root scope and calls all + * registered listeners along the way. The event will stop propagating if one of the listeners + * cancels it. + * + * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed + * onto the {@link ng.$exceptionHandler $exceptionHandler} service. + * + * @param {string} name Event name to emit. + * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. + * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). + */ + $emit: function(name, args) { + var empty = [], + namedListeners, + scope = this, + stopPropagation = false, + event = { + name: name, + targetScope: scope, + stopPropagation: function() {stopPropagation = true;}, + preventDefault: function() { + event.defaultPrevented = true; + }, + defaultPrevented: false + }, + listenerArgs = concat([event], arguments, 1), + i, length; + + do { + namedListeners = scope.$$listeners[name] || empty; + event.currentScope = scope; + for (i = 0, length = namedListeners.length; i < length; i++) { + + // if listeners were deregistered, defragment the array + if (!namedListeners[i]) { + namedListeners.splice(i, 1); + i--; + length--; + continue; + } + try { + //allow all listeners attached to the current scope to run + namedListeners[i].apply(null, listenerArgs); + } catch (e) { + $exceptionHandler(e); + } + } + //if any listener on the current scope stops propagation, prevent bubbling + if (stopPropagation) { + break; + } + //traverse upwards + scope = scope.$parent; + } while (scope); + + event.currentScope = null; + + return event; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$broadcast + * @kind function + * + * @description + * Dispatches an event `name` downwards to all child scopes (and their children) notifying the + * registered {@link ng.$rootScope.Scope#$on} listeners. + * + * The event life cycle starts at the scope on which `$broadcast` was called. All + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get + * notified. Afterwards, the event propagates to all direct and indirect scopes of the current + * scope and calls all registered listeners along the way. The event cannot be canceled. + * + * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed + * onto the {@link ng.$exceptionHandler $exceptionHandler} service. + * + * @param {string} name Event name to broadcast. + * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. + * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} + */ + $broadcast: function(name, args) { + var target = this, + current = target, + next = target, + event = { + name: name, + targetScope: target, + preventDefault: function() { + event.defaultPrevented = true; + }, + defaultPrevented: false + }; + + if (!target.$$listenerCount[name]) return event; + + var listenerArgs = concat([event], arguments, 1), + listeners, i, length; + + //down while you can, then up and next sibling or up and next sibling until back at root + while ((current = next)) { + event.currentScope = current; + listeners = current.$$listeners[name] || []; + for (i = 0, length = listeners.length; i < length; i++) { + // if listeners were deregistered, defragment the array + if (!listeners[i]) { + listeners.splice(i, 1); + i--; + length--; + continue; + } + + try { + listeners[i].apply(null, listenerArgs); + } catch (e) { + $exceptionHandler(e); + } + } + + // Insanity Warning: scope depth-first traversal + // yes, this code is a bit crazy, but it works and we have tests to prove it! + // this piece should be kept in sync with the traversal in $digest + // (though it differs due to having the extra check for $$listenerCount) + if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || + (current !== target && current.$$nextSibling)))) { + while (current !== target && !(next = current.$$nextSibling)) { + current = current.$parent; + } + } + } + + event.currentScope = null; + return event; + } + }; + + var $rootScope = new Scope(); + + //The internal queues. Expose them on the $rootScope for debugging/testing purposes. + var asyncQueue = $rootScope.$$asyncQueue = []; + var postDigestQueue = $rootScope.$$postDigestQueue = []; + var applyAsyncQueue = $rootScope.$$applyAsyncQueue = []; + + var postDigestQueuePosition = 0; + + return $rootScope; + + + function beginPhase(phase) { + if ($rootScope.$$phase) { + throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); + } + + $rootScope.$$phase = phase; + } + + function clearPhase() { + $rootScope.$$phase = null; + } + + function incrementWatchersCount(current, count) { + do { + current.$$watchersCount += count; + } while ((current = current.$parent)); + } + + function decrementListenerCount(current, count, name) { + do { + current.$$listenerCount[name] -= count; + + if (current.$$listenerCount[name] === 0) { + delete current.$$listenerCount[name]; + } + } while ((current = current.$parent)); + } + + /** + * function used as an initial value for watchers. + * because it's unique we can easily tell it apart from other values + */ + function initWatchVal() {} + + function flushApplyAsync() { + while (applyAsyncQueue.length) { + try { + applyAsyncQueue.shift()(); + } catch (e) { + $exceptionHandler(e); + } + } + applyAsyncId = null; + } + + function scheduleApplyAsync() { + if (applyAsyncId === null) { + applyAsyncId = $browser.defer(function() { + $rootScope.$apply(flushApplyAsync); + }); + } + } + }]; + } + + /** + * @ngdoc service + * @name $rootElement + * + * @description + * The root element of AngularJS application. This is either the element where {@link + * ng.directive:ngApp ngApp} was declared or the element passed into + * {@link angular.bootstrap}. The element represents the root element of application. It is also the + * location where the application's {@link auto.$injector $injector} service gets + * published, and can be retrieved using `$rootElement.injector()`. + */ + + +// the implementation is in angular.bootstrap + + /** + * @this + * @description + * Private service to sanitize uris for links and images. Used by $compile and $sanitize. + */ + function $$SanitizeUriProvider() { + var aHrefSanitizationWhitelist = /^\s*(https?|s?ftp|mailto|tel|file):/, + imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/; + + /** + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during a[href] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to a[href] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.aHrefSanitizationWhitelist = function(regexp) { + if (isDefined(regexp)) { + aHrefSanitizationWhitelist = regexp; + return this; + } + return aHrefSanitizationWhitelist; + }; + + + /** + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during img[src] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to img[src] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.imgSrcSanitizationWhitelist = function(regexp) { + if (isDefined(regexp)) { + imgSrcSanitizationWhitelist = regexp; + return this; + } + return imgSrcSanitizationWhitelist; + }; + + this.$get = function() { + return function sanitizeUri(uri, isImage) { + var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; + var normalizedVal; + normalizedVal = urlResolve(uri && uri.trim()).href; + if (normalizedVal !== '' && !normalizedVal.match(regex)) { + return 'unsafe:' + normalizedVal; + } + return uri; + }; + }; + } + + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Any commits to this file should be reviewed with security in mind. * + * Changes to this file can potentially create security vulnerabilities. * + * An approval from 2 Core members with history of modifying * + * this file is required. * + * * + * Does the change somehow allow for arbitrary javascript to be executed? * + * Or allows for someone to change the prototype of built-in objects? * + * Or gives undesired access to variables likes document or window? * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + + /* exported $SceProvider, $SceDelegateProvider */ + + var $sceMinErr = minErr('$sce'); + + var SCE_CONTEXTS = { + // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding). + HTML: 'html', + + // Style statements or stylesheets. Currently unused in AngularJS. + CSS: 'css', + + // An URL used in a context where it does not refer to a resource that loads code. Currently + // unused in AngularJS. + URL: 'url', + + // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as + // code. (e.g. ng-include, script src binding, templateUrl) + RESOURCE_URL: 'resourceUrl', + + // Script. Currently unused in AngularJS. + JS: 'js' + }; + +// Helper functions follow. + + var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g; + + function snakeToCamel(name) { + return name + .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace); + } + + function adjustMatcher(matcher) { + if (matcher === 'self') { + return matcher; + } else if (isString(matcher)) { + // Strings match exactly except for 2 wildcards - '*' and '**'. + // '*' matches any character except those from the set ':/.?&'. + // '**' matches any character (like .* in a RegExp). + // More than 2 *'s raises an error as it's ill defined. + if (matcher.indexOf('***') > -1) { + throw $sceMinErr('iwcard', + 'Illegal sequence *** in string matcher. String: {0}', matcher); + } + matcher = escapeForRegexp(matcher). + replace(/\\\*\\\*/g, '.*'). + replace(/\\\*/g, '[^:/.?&;]*'); + return new RegExp('^' + matcher + '$'); + } else if (isRegExp(matcher)) { + // The only other type of matcher allowed is a Regexp. + // Match entire URL / disallow partial matches. + // Flags are reset (i.e. no global, ignoreCase or multiline) + return new RegExp('^' + matcher.source + '$'); + } else { + throw $sceMinErr('imatcher', + 'Matchers may only be "self", string patterns or RegExp objects'); + } + } + + + function adjustMatchers(matchers) { + var adjustedMatchers = []; + if (isDefined(matchers)) { + forEach(matchers, function(matcher) { + adjustedMatchers.push(adjustMatcher(matcher)); + }); + } + return adjustedMatchers; + } + + + /** + * @ngdoc service + * @name $sceDelegate + * @kind function + * + * @description + * + * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict + * Contextual Escaping (SCE)} services to AngularJS. + * + * For an overview of this service and the functionnality it provides in AngularJS, see the main + * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how + * SCE works in their application, which shouldn't be needed in most cases. + * + *
    + * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or + * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners, + * changes to this service will also influence users, so be extra careful and document your changes. + *
    + * + * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of + * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is + * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to + * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things + * work because `$sce` delegates to `$sceDelegate` for these operations. + * + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. + * + * The default instance of `$sceDelegate` should work out of the box with little pain. While you + * can override it completely to change the behavior of `$sce`, the common case would + * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting + * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as + * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist + * $sceDelegateProvider.resourceUrlWhitelist} and {@link + * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} + */ + + /** + * @ngdoc provider + * @name $sceDelegateProvider + * @this + * + * @description + * + * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate + * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}. + * + * The `$sceDelegateProvider` allows one to get/set the whitelists and blacklists used to ensure + * that the URLs used for sourcing AngularJS templates and other script-running URLs are safe (all + * places that use the `$sce.RESOURCE_URL` context). See + * {@link ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} + * and + * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}, + * + * For the general details about this service in AngularJS, read the main page for {@link ng.$sce + * Strict Contextual Escaping (SCE)}. + * + * **Example**: Consider the following case. + * + * - your app is hosted at url `http://myapp.example.com/` + * - but some of your templates are hosted on other domains you control such as + * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. + * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. + * + * Here is what a secure configuration for this scenario might look like: + * + * ``` + * angular.module('myApp', []).config(function($sceDelegateProvider) { + * $sceDelegateProvider.resourceUrlWhitelist([ + * // Allow same origin resource loads. + * 'self', + * // Allow loading from our assets domain. Notice the difference between * and **. + * 'http://srv*.assets.example.com/**' + * ]); + * + * // The blacklist overrides the whitelist so the open redirect here is blocked. + * $sceDelegateProvider.resourceUrlBlacklist([ + * 'http://myapp.example.com/clickThru**' + * ]); + * }); + * ``` + * Note that an empty whitelist will block every resource URL from being loaded, and will require + * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates + * requested by {@link ng.$templateRequest $templateRequest} that are present in + * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism + * to populate your templates in that cache at config time, then it is a good idea to remove 'self' + * from that whitelist. This helps to mitigate the security impact of certain types of issues, like + * for instance attacker-controlled `ng-includes`. + */ + + function $SceDelegateProvider() { + this.SCE_CONTEXTS = SCE_CONTEXTS; + + // Resource URLs can also be trusted by policy. + var resourceUrlWhitelist = ['self'], + resourceUrlBlacklist = []; + + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlWhitelist + * @kind function + * + * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value + * provided. This must be an array or null. A snapshot of this array is used so further + * changes to the array are ignored. + * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items + * allowed in this array. + * + * @return {Array} The currently set whitelist array. + * + * @description + * Sets/Gets the whitelist of trusted resource URLs. + * + * The **default value** when no whitelist has been explicitly set is `['self']` allowing only + * same origin resource requests. + * + *
    + * **Note:** the default whitelist of 'self' is not recommended if your app shares its origin + * with other apps! It is a good idea to limit it to only your application's directory. + *
    + */ + this.resourceUrlWhitelist = function(value) { + if (arguments.length) { + resourceUrlWhitelist = adjustMatchers(value); + } + return resourceUrlWhitelist; + }; + + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlBlacklist + * @kind function + * + * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value + * provided. This must be an array or null. A snapshot of this array is used so further + * changes to the array are ignored.

    + * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items + * allowed in this array.

    + * The typical usage for the blacklist is to **block + * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as + * these would otherwise be trusted but actually return content from the redirected domain. + *

    + * Finally, **the blacklist overrides the whitelist** and has the final say. + * + * @return {Array} The currently set blacklist array. + * + * @description + * Sets/Gets the blacklist of trusted resource URLs. + * + * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there + * is no blacklist.) + */ + + this.resourceUrlBlacklist = function(value) { + if (arguments.length) { + resourceUrlBlacklist = adjustMatchers(value); + } + return resourceUrlBlacklist; + }; + + this.$get = ['$injector', function($injector) { + + var htmlSanitizer = function htmlSanitizer(html) { + throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); + }; + + if ($injector.has('$sanitize')) { + htmlSanitizer = $injector.get('$sanitize'); + } + + + function matchUrl(matcher, parsedUrl) { + if (matcher === 'self') { + return urlIsSameOrigin(parsedUrl); + } else { + // definitely a regex. See adjustMatchers() + return !!matcher.exec(parsedUrl.href); + } + } + + function isResourceUrlAllowedByPolicy(url) { + var parsedUrl = urlResolve(url.toString()); + var i, n, allowed = false; + // Ensure that at least one item from the whitelist allows this url. + for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { + if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { + allowed = true; + break; + } + } + if (allowed) { + // Ensure that no item from the blacklist blocked this url. + for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { + if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { + allowed = false; + break; + } + } + } + return allowed; + } + + function generateHolderType(Base) { + var holderType = function TrustedValueHolderType(trustedValue) { + this.$$unwrapTrustedValue = function() { + return trustedValue; + }; + }; + if (Base) { + holderType.prototype = new Base(); + } + holderType.prototype.valueOf = function sceValueOf() { + return this.$$unwrapTrustedValue(); + }; + holderType.prototype.toString = function sceToString() { + return this.$$unwrapTrustedValue().toString(); + }; + return holderType; + } + + var trustedValueHolderBase = generateHolderType(), + byType = {}; + + byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); + + /** + * @ngdoc method + * @name $sceDelegate#trustAs + * + * @description + * Returns a trusted representation of the parameter for the specified context. This trusted + * object will later on be used as-is, without any security check, by bindings or directives + * that require this security context. + * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass + * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as + * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the + * sanitizer loaded, passing the value itself will render all the HTML that does not pose a + * security risk. + * + * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those + * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual + * escaping. + * + * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`, + * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`. + * + * @param {*} value The value that should be considered trusted. + * @return {*} A trusted representation of value, that can be used in the given context. + */ + function trustAs(type, trustedValue) { + var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); + if (!Constructor) { + throw $sceMinErr('icontext', + 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', + type, trustedValue); + } + if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') { + return trustedValue; + } + // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting + // mutable objects, we ensure here that the value passed in is actually a string. + if (typeof trustedValue !== 'string') { + throw $sceMinErr('itype', + 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', + type); + } + return new Constructor(trustedValue); + } + + /** + * @ngdoc method + * @name $sceDelegate#valueOf + * + * @description + * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. + * + * If the passed parameter is not a value that had been returned by {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is. + * + * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} + * call or anything else. + * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns + * `value` unchanged. + */ + function valueOf(maybeTrusted) { + if (maybeTrusted instanceof trustedValueHolderBase) { + return maybeTrusted.$$unwrapTrustedValue(); + } else { + return maybeTrusted; + } + } + + /** + * @ngdoc method + * @name $sceDelegate#getTrusted + * + * @description + * Takes any input, and either returns a value that's safe to use in the specified context, or + * throws an exception. + * + * In practice, there are several cases. When given a string, this function runs checks + * and sanitization to make it safe without prior assumptions. When given the result of a {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call, it returns the originally supplied + * value if that value's context is valid for this call's context. Finally, this function can + * also throw when there is no way to turn `maybeTrusted` in a safe value (e.g., no sanitization + * is available or possible.) + * + * @param {string} type The context in which this value is to be used (such as `$sce.HTML`). + * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.) + * @return {*} A version of the value that's safe to use in the given context, or throws an + * exception if this is impossible. + */ + function getTrusted(type, maybeTrusted) { + if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') { + return maybeTrusted; + } + var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); + // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return + // as-is. + if (constructor && maybeTrusted instanceof constructor) { + return maybeTrusted.$$unwrapTrustedValue(); + } + // Otherwise, if we get here, then we may either make it safe, or throw an exception. This + // depends on the context: some are sanitizatible (HTML), some use whitelists (RESOURCE_URL), + // some are impossible to do (JS). This step isn't implemented for CSS and URL, as AngularJS + // has no corresponding sinks. + if (type === SCE_CONTEXTS.RESOURCE_URL) { + // RESOURCE_URL uses a whitelist. + if (isResourceUrlAllowedByPolicy(maybeTrusted)) { + return maybeTrusted; + } else { + throw $sceMinErr('insecurl', + 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', + maybeTrusted.toString()); + } + } else if (type === SCE_CONTEXTS.HTML) { + // htmlSanitizer throws its own error when no sanitizer is available. + return htmlSanitizer(maybeTrusted); + } + // Default error when the $sce service has no way to make the input safe. + throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); + } + + return { trustAs: trustAs, + getTrusted: getTrusted, + valueOf: valueOf }; + }]; + } + + + /** + * @ngdoc provider + * @name $sceProvider + * @this + * + * @description + * + * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. + * - enable/disable Strict Contextual Escaping (SCE) in a module + * - override the default implementation with a custom delegate + * + * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. + */ + + /** + * @ngdoc service + * @name $sce + * @kind function + * + * @description + * + * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. + * + * ## Strict Contextual Escaping + * + * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render + * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and + * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier. + * + * ### Overview + * + * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in + * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically + * run security checks on them (sanitizations, whitelists, depending on context), or throw when it + * cannot guarantee the security of the result. That behavior depends strongly on contexts: HTML + * can be sanitized, but template URLs cannot, for instance. + * + * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML: + * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it + * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and + * render the input as-is, you will need to mark it as trusted for that context before attempting + * to bind it. + * + * As of version 1.2, AngularJS ships with SCE enabled by default. + * + * ### In practice + * + * Here's an example of a binding in a privileged context: + * + * ``` + * + *

    + * ``` + * + * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE + * disabled, this application allows the user to render arbitrary HTML into the DIV, which would + * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog + * articles, etc. via bindings. (HTML is just one example of a context where rendering user + * controlled input creates security vulnerabilities.) + * + * For the case of HTML, you might use a library, either on the client side, or on the server side, + * to sanitize unsafe HTML before binding to the value and rendering it in the document. + * + * How would you ensure that every place that used these types of bindings was bound to a value that + * was sanitized by your library (or returned as safe for rendering by your server?) How can you + * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some + * properties/fields and forgot to update the binding to the sanitized value? + * + * To be secure by default, AngularJS makes sure bindings go through that sanitization, or + * any similar validation process, unless there's a good reason to trust the given value in this + * context. That trust is formalized with a function call. This means that as a developer, you + * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues, + * you just need to ensure the values you mark as trusted indeed are safe - because they were + * received from your server, sanitized by your library, etc. You can organize your codebase to + * help with this - perhaps allowing only the files in a specific directory to do this. + * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then + * becomes a more manageable task. + * + * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} + * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to + * build the trusted versions of your values. + * + * ### How does it work? + * + * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted + * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as + * a way to enforce the required security context in your data sink. Directives use {@link + * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs + * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also, + * when binding without directives, AngularJS will understand the context of your bindings + * automatically. + * + * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link + * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly + * simplified): + * + * ``` + * var ngBindHtmlDirective = ['$sce', function($sce) { + * return function(scope, element, attr) { + * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { + * element.html(value || ''); + * }); + * }; + * }]; + * ``` + * + * ### Impact on loading templates + * + * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as + * `templateUrl`'s specified by {@link guide/directive directives}. + * + * By default, AngularJS only loads templates from the same domain and protocol as the application + * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or + * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist + * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. + * + * *Please note*: + * The browser's + * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) + * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) + * policy apply in addition to this and may further restrict whether the template is successfully + * loaded. This means that without the right CORS policy, loading templates from a different domain + * won't work on all browsers. Also, loading templates from `file://` URL does not work on some + * browsers. + * + * ### This feels like too much overhead + * + * It's important to remember that SCE only applies to interpolation expressions. + * + * If your expressions are constant literals, they're automatically trusted and you don't need to + * call `$sce.trustAs` on them (e.g. + * `
    `) just works. The `$sceDelegate` will + * also use the `$sanitize` service if it is available when binding untrusted values to + * `$sce.HTML` context. AngularJS provides an implementation in `angular-sanitize.js`, and if you + * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in + * your application. + * + * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load + * templates in `ng-include` from your application's domain without having to even know about SCE. + * It blocks loading templates from other domains or loading templates over http from an https + * served document. You can change these by setting your own custom {@link + * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link + * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. + * + * This significantly reduces the overhead. It is far easier to pay the small overhead and have an + * application that's secure and can be audited to verify that with much more ease than bolting + * security onto an application later. + * + * + * ### What trusted context types are supported? + * + * | Context | Notes | + * |---------------------|----------------| + * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered, and the {@link ngSanitize.$sanitize $sanitize} service is available (implemented by the {@link ngSanitize ngSanitize} module) this will sanitize the value instead of throwing an error. | + * | `$sce.CSS` | For CSS that's safe to source into the application. Currently, no bindings require this context. Feel free to use it in your own directives. | + * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
    Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does (it's not just the URL that matters, but also what is at the end of it), and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | + * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently, no bindings require this context. Feel free to use it in your own directives. | + * + * + * Be aware that `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them + * through {@link ng.$sce#getTrusted $sce.getTrusted}. There's no CSS-, URL-, or JS-context bindings + * in AngularJS currently, so their corresponding `$sce.trustAs` functions aren't useful yet. This + * might evolve. + * + * ### Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
    + * + * Each element in these arrays must be one of the following: + * + * - **'self'** + * - The special **string**, `'self'`, can be used to match against all URLs of the **same + * domain** as the application document using the **same protocol**. + * - **String** (except the special value `'self'`) + * - The string is matched against the full *normalized / absolute URL* of the resource + * being tested (substring matches are not good enough.) + * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters + * match themselves. + * - `*`: matches zero or more occurrences of any character other than one of the following 6 + * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use + * in a whitelist. + * - `**`: matches zero or more occurrences of *any* character. As such, it's not + * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g. + * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might + * not have been the intention.) Its usage at the very end of the path is ok. (e.g. + * http://foo.example.com/templates/**). + * - **RegExp** (*see caveat below*) + * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax + * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to + * accidentally introduce a bug when one updates a complex expression (imho, all regexes should + * have good test coverage). For instance, the use of `.` in the regex is correct only in a + * small number of cases. A `.` character in the regex used when matching the scheme or a + * subdomain could be matched against a `:` or literal `.` that was likely not intended. It + * is highly recommended to use the string patterns and only fall back to regular expressions + * as a last resort. + * - The regular expression must be an instance of RegExp (i.e. not a string.) It is + * matched against the **entire** *normalized / absolute URL* of the resource being tested + * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags + * present on the RegExp (such as multiline, global, ignoreCase) are ignored. + * - If you are generating your JavaScript from some other templating engine (not + * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), + * remember to escape your regular expression (and be aware that you might need more than + * one level of escaping depending on your templating engine and the way you interpolated + * the value.) Do make use of your platform's escaping mechanism as it might be good + * enough before coding your own. E.g. Ruby has + * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) + * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). + * Javascript lacks a similar built in function for escaping. Take a look at Google + * Closure library's [goog.string.regExpEscape(s)]( + * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). + * + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. + * + * ### Show me an example using SCE. + * + * + * + *
    + *

    + * User comments
    + * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when + * $sanitize is available. If $sanitize isn't available, this results in an error instead of an + * exploit. + *
    + *
    + * {{userComment.name}}: + * + *
    + *
    + *
    + *
    + *
    + * + * + * angular.module('mySceApp', ['ngSanitize']) + * .controller('AppController', ['$http', '$templateCache', '$sce', + * function AppController($http, $templateCache, $sce) { + * var self = this; + * $http.get('test_data.json', {cache: $templateCache}).then(function(response) { + * self.userComments = response.data; + * }); + * self.explicitlyTrustedHtml = $sce.trustAsHtml( + * 'Hover over this text.'); + * }]); + * + * + * + * [ + * { "name": "Alice", + * "htmlComment": + * "Is anyone reading this?" + * }, + * { "name": "Bob", + * "htmlComment": "Yes! Am I the only other one?" + * } + * ] + * + * + * + * describe('SCE doc demo', function() { + * it('should sanitize untrusted values', function() { + * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML')) + * .toBe('Is anyone reading this?'); + * }); + * + * it('should NOT sanitize explicitly trusted values', function() { + * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe( + * 'Hover over this text.'); + * }); + * }); + * + *
    + * + * + * + * ## Can I disable SCE completely? + * + * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits + * for little coding overhead. It will be much harder to take an SCE disabled application and + * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE + * for cases where you have a lot of existing code that was written before SCE was introduced and + * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if + * you are writing a library, you will cause security bugs applications using it. + * + * That said, here's how you can completely disable SCE: + * + * ``` + * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { + * // Completely disable SCE. For demonstration purposes only! + * // Do not use in new projects or libraries. + * $sceProvider.enabled(false); + * }); + * ``` + * + */ + + function $SceProvider() { + var enabled = true; + + /** + * @ngdoc method + * @name $sceProvider#enabled + * @kind function + * + * @param {boolean=} value If provided, then enables/disables SCE application-wide. + * @return {boolean} True if SCE is enabled, false otherwise. + * + * @description + * Enables/disables SCE and returns the current value. + */ + this.enabled = function(value) { + if (arguments.length) { + enabled = !!value; + } + return enabled; + }; + + + /* Design notes on the default implementation for SCE. + * + * The API contract for the SCE delegate + * ------------------------------------- + * The SCE delegate object must provide the following 3 methods: + * + * - trustAs(contextEnum, value) + * This method is used to tell the SCE service that the provided value is OK to use in the + * contexts specified by contextEnum. It must return an object that will be accepted by + * getTrusted() for a compatible contextEnum and return this value. + * + * - valueOf(value) + * For values that were not produced by trustAs(), return them as is. For values that were + * produced by trustAs(), return the corresponding input value to trustAs. Basically, if + * trustAs is wrapping the given values into some type, this operation unwraps it when given + * such a value. + * + * - getTrusted(contextEnum, value) + * This function should return the a value that is safe to use in the context specified by + * contextEnum or throw and exception otherwise. + * + * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be + * opaque or wrapped in some holder object. That happens to be an implementation detail. For + * instance, an implementation could maintain a registry of all trusted objects by context. In + * such a case, trustAs() would return the same object that was passed in. getTrusted() would + * return the same object passed in if it was found in the registry under a compatible context or + * throw an exception otherwise. An implementation might only wrap values some of the time based + * on some criteria. getTrusted() might return a value and not throw an exception for special + * constants or objects even if not wrapped. All such implementations fulfill this contract. + * + * + * A note on the inheritance model for SCE contexts + * ------------------------------------------------ + * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This + * is purely an implementation details. + * + * The contract is simply this: + * + * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) + * will also succeed. + * + * Inheritance happens to capture this in a natural way. In some future, we may not use + * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to + * be aware of this detail. + */ + + this.$get = ['$parse', '$sceDelegate', function( + $parse, $sceDelegate) { + // Support: IE 9-11 only + // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow + // the "expression(javascript expression)" syntax which is insecure. + if (enabled && msie < 8) { + throw $sceMinErr('iequirks', + 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' + + 'mode. You can fix this by adding the text to the top of your HTML ' + + 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); + } + + var sce = shallowCopy(SCE_CONTEXTS); + + /** + * @ngdoc method + * @name $sce#isEnabled + * @kind function + * + * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you + * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. + * + * @description + * Returns a boolean indicating if SCE is enabled. + */ + sce.isEnabled = function() { + return enabled; + }; + sce.trustAs = $sceDelegate.trustAs; + sce.getTrusted = $sceDelegate.getTrusted; + sce.valueOf = $sceDelegate.valueOf; + + if (!enabled) { + sce.trustAs = sce.getTrusted = function(type, value) { return value; }; + sce.valueOf = identity; + } + + /** + * @ngdoc method + * @name $sce#parseAs + * + * @description + * Converts AngularJS {@link guide/expression expression} into a function. This is like {@link + * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it + * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, + * *result*)} + * + * @param {string} type The SCE context in which this result will be used. + * @param {string} expression String expression to compile. + * @return {function(context, locals)} A function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. + */ + sce.parseAs = function sceParseAs(type, expr) { + var parsed = $parse(expr); + if (parsed.literal && parsed.constant) { + return parsed; + } else { + return $parse(expr, function(value) { + return sce.getTrusted(type, value); + }); + } + }; + + /** + * @ngdoc method + * @name $sce#trustAs + * + * @description + * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a + * wrapped object that represents your value, and the trust you have in its safety for the given + * context. AngularJS can then use that value as-is in bindings of the specified secure context. + * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute + * interpolations. See {@link ng.$sce $sce} for strict contextual escaping. + * + * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`, + * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`. + * + * @param {*} value The value that that should be considered trusted. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in the context you specified. + */ + + /** + * @ngdoc method + * @name $sce#trustAsHtml + * + * @description + * Shorthand method. `$sce.trustAsHtml(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} + * + * @param {*} value The value to mark as trusted for `$sce.HTML` context. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in `$sce.HTML` context (like `ng-bind-html`). + */ + + /** + * @ngdoc method + * @name $sce#trustAsCss + * + * @description + * Shorthand method. `$sce.trustAsCss(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`} + * + * @param {*} value The value to mark as trusted for `$sce.CSS` context. + * @return {*} A wrapped version of value that can be used as a trusted variant + * of your `value` in `$sce.CSS` context. This context is currently unused, so there are + * almost no reasons to use this function so far. + */ + + /** + * @ngdoc method + * @name $sce#trustAsUrl + * + * @description + * Shorthand method. `$sce.trustAsUrl(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} + * + * @param {*} value The value to mark as trusted for `$sce.URL` context. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in `$sce.URL` context. That context is currently unused, so there are almost no reasons + * to use this function so far. + */ + + /** + * @ngdoc method + * @name $sce#trustAsResourceUrl + * + * @description + * Shorthand method. `$sce.trustAsResourceUrl(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute + * bindings, ...) + */ + + /** + * @ngdoc method + * @name $sce#trustAsJs + * + * @description + * Shorthand method. `$sce.trustAsJs(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} + * + * @param {*} value The value to mark as trusted for `$sce.JS` context. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to + * use this function so far. + */ + + /** + * @ngdoc method + * @name $sce#getTrusted + * + * @description + * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, + * takes any input, and either returns a value that's safe to use in the specified context, + * or throws an exception. This function is aware of trusted values created by the `trustAs` + * function and its shorthands, and when contexts are appropriate, returns the unwrapped value + * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a + * safe value (e.g., no sanitization is available or possible.) + * + * @param {string} type The context in which this value is to be used. + * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs + * `$sce.trustAs`} call, or anything else (which will not be considered trusted.) + * @return {*} A version of the value that's safe to use in the given context, or throws an + * exception if this is impossible. + */ + + /** + * @ngdoc method + * @name $sce#getTrustedHtml + * + * @description + * Shorthand method. `$sce.getTrustedHtml(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedCss + * + * @description + * Shorthand method. `$sce.getTrustedCss(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedUrl + * + * @description + * Shorthand method. `$sce.getTrustedUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.URL, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedResourceUrl + * + * @description + * Shorthand method. `$sce.getTrustedResourceUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to pass to `$sceDelegate.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedJs + * + * @description + * Shorthand method. `$sce.getTrustedJs(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.JS, value)` + */ + + /** + * @ngdoc method + * @name $sce#parseAsHtml + * + * @description + * Shorthand method. `$sce.parseAsHtml(expression string)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`} + * + * @param {string} expression String expression to compile. + * @return {function(context, locals)} A function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsCss + * + * @description + * Shorthand method. `$sce.parseAsCss(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`} + * + * @param {string} expression String expression to compile. + * @return {function(context, locals)} A function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsUrl + * + * @description + * Shorthand method. `$sce.parseAsUrl(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`} + * + * @param {string} expression String expression to compile. + * @return {function(context, locals)} A function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsResourceUrl + * + * @description + * Shorthand method. `$sce.parseAsResourceUrl(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`} + * + * @param {string} expression String expression to compile. + * @return {function(context, locals)} A function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsJs + * + * @description + * Shorthand method. `$sce.parseAsJs(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`} + * + * @param {string} expression String expression to compile. + * @return {function(context, locals)} A function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. + */ + + // Shorthand delegations. + var parse = sce.parseAs, + getTrusted = sce.getTrusted, + trustAs = sce.trustAs; + + forEach(SCE_CONTEXTS, function(enumValue, name) { + var lName = lowercase(name); + sce[snakeToCamel('parse_as_' + lName)] = function(expr) { + return parse(enumValue, expr); + }; + sce[snakeToCamel('get_trusted_' + lName)] = function(value) { + return getTrusted(enumValue, value); + }; + sce[snakeToCamel('trust_as_' + lName)] = function(value) { + return trustAs(enumValue, value); + }; + }); + + return sce; + }]; + } + + /* exported $SnifferProvider */ + + /** + * !!! This is an undocumented "private" service !!! + * + * @name $sniffer + * @requires $window + * @requires $document + * @this + * + * @property {boolean} history Does the browser support html5 history api ? + * @property {boolean} transitions Does the browser support CSS transition events ? + * @property {boolean} animations Does the browser support CSS animation events ? + * + * @description + * This is very simple implementation of testing browser's features. + */ + function $SnifferProvider() { + this.$get = ['$window', '$document', function($window, $document) { + var eventSupport = {}, + // Chrome Packaged Apps are not allowed to access `history.pushState`. + // If not sandboxed, they can be detected by the presence of `chrome.app.runtime` + // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by + // the presence of an extension runtime ID and the absence of other Chrome runtime APIs + // (see https://developer.chrome.com/apps/manifest/sandbox). + // (NW.js apps have access to Chrome APIs, but do support `history`.) + isNw = $window.nw && $window.nw.process, + isChromePackagedApp = + !isNw && + $window.chrome && + ($window.chrome.app && $window.chrome.app.runtime || + !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id), + hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState, + android = + toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), + boxee = /Boxee/i.test(($window.navigator || {}).userAgent), + document = $document[0] || {}, + bodyStyle = document.body && document.body.style, + transitions = false, + animations = false; + + if (bodyStyle) { + // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x + // Mentioned browsers need a -webkit- prefix for transitions & animations. + transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle); + animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle); + } + + + return { + // Android has history.pushState, but it does not update location correctly + // so let's not use the history API at all. + // http://code.google.com/p/android/issues/detail?id=17471 + // https://github.com/angular/angular.js/issues/904 + + // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has + // so let's not use the history API also + // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined + history: !!(hasHistoryPushState && !(android < 4) && !boxee), + hasEvent: function(event) { + // Support: IE 9-11 only + // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have + // it. In particular the event is not fired when backspace or delete key are pressed or + // when cut operation is performed. + // IE10+ implements 'input' event but it erroneously fires under various situations, + // e.g. when placeholder changes, or a form is focused. + if (event === 'input' && msie) return false; + + if (isUndefined(eventSupport[event])) { + var divElm = document.createElement('div'); + eventSupport[event] = 'on' + event in divElm; + } + + return eventSupport[event]; + }, + csp: csp(), + transitions: transitions, + animations: animations, + android: android + }; + }]; + } + + var $templateRequestMinErr = minErr('$compile'); + + /** + * @ngdoc provider + * @name $templateRequestProvider + * @this + * + * @description + * Used to configure the options passed to the {@link $http} service when making a template request. + * + * For example, it can be used for specifying the "Accept" header that is sent to the server, when + * requesting a template. + */ + function $TemplateRequestProvider() { + + var httpOptions; + + /** + * @ngdoc method + * @name $templateRequestProvider#httpOptions + * @description + * The options to be passed to the {@link $http} service when making the request. + * You can use this to override options such as the "Accept" header for template requests. + * + * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the + * options if not overridden here. + * + * @param {string=} value new value for the {@link $http} options. + * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter. + */ + this.httpOptions = function(val) { + if (val) { + httpOptions = val; + return this; + } + return httpOptions; + }; + + /** + * @ngdoc service + * @name $templateRequest + * + * @description + * The `$templateRequest` service runs security checks then downloads the provided template using + * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request + * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the + * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the + * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted + * when `tpl` is of type string and `$templateCache` has the matching entry. + * + * If you want to pass custom options to the `$http` service, such as setting the Accept header you + * can configure this via {@link $templateRequestProvider#httpOptions}. + * + * `$templateRequest` is used internally by {@link $compile}, {@link ngRoute.$route}, and directives such + * as {@link ngInclude} to download and cache templates. + * + * 3rd party modules should use `$templateRequest` if their services or directives are loading + * templates. + * + * @param {string|TrustedResourceUrl} tpl The HTTP request template URL + * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty + * + * @return {Promise} a promise for the HTTP response data of the given URL. + * + * @property {number} totalPendingRequests total amount of pending template requests being downloaded. + */ + this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce', + function($exceptionHandler, $templateCache, $http, $q, $sce) { + + function handleRequestFn(tpl, ignoreRequestError) { + handleRequestFn.totalPendingRequests++; + + // We consider the template cache holds only trusted templates, so + // there's no need to go through whitelisting again for keys that already + // are included in there. This also makes AngularJS accept any script + // directive, no matter its name. However, we still need to unwrap trusted + // types. + if (!isString(tpl) || isUndefined($templateCache.get(tpl))) { + tpl = $sce.getTrustedResourceUrl(tpl); + } + + var transformResponse = $http.defaults && $http.defaults.transformResponse; + + if (isArray(transformResponse)) { + transformResponse = transformResponse.filter(function(transformer) { + return transformer !== defaultHttpResponseTransform; + }); + } else if (transformResponse === defaultHttpResponseTransform) { + transformResponse = null; + } + + return $http.get(tpl, extend({ + cache: $templateCache, + transformResponse: transformResponse + }, httpOptions)) + .finally(function() { + handleRequestFn.totalPendingRequests--; + }) + .then(function(response) { + $templateCache.put(tpl, response.data); + return response.data; + }, handleError); + + function handleError(resp) { + if (!ignoreRequestError) { + resp = $templateRequestMinErr('tpload', + 'Failed to load template: {0} (HTTP status: {1} {2})', + tpl, resp.status, resp.statusText); + + $exceptionHandler(resp); + } + + return $q.reject(resp); + } + } + + handleRequestFn.totalPendingRequests = 0; + + return handleRequestFn; + } + ]; + } + + /** @this */ + function $$TestabilityProvider() { + this.$get = ['$rootScope', '$browser', '$location', + function($rootScope, $browser, $location) { + + /** + * @name $testability + * + * @description + * The private $$testability service provides a collection of methods for use when debugging + * or by automated test and debugging tools. + */ + var testability = {}; + + /** + * @name $$testability#findBindings + * + * @description + * Returns an array of elements that are bound (via ng-bind or {{}}) + * to expressions matching the input. + * + * @param {Element} element The element root to search from. + * @param {string} expression The binding expression to match. + * @param {boolean} opt_exactMatch If true, only returns exact matches + * for the expression. Filters and whitespace are ignored. + */ + testability.findBindings = function(element, expression, opt_exactMatch) { + var bindings = element.getElementsByClassName('ng-binding'); + var matches = []; + forEach(bindings, function(binding) { + var dataBinding = angular.element(binding).data('$binding'); + if (dataBinding) { + forEach(dataBinding, function(bindingName) { + if (opt_exactMatch) { + var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)'); + if (matcher.test(bindingName)) { + matches.push(binding); + } + } else { + if (bindingName.indexOf(expression) !== -1) { + matches.push(binding); + } + } + }); + } + }); + return matches; + }; + + /** + * @name $$testability#findModels + * + * @description + * Returns an array of elements that are two-way found via ng-model to + * expressions matching the input. + * + * @param {Element} element The element root to search from. + * @param {string} expression The model expression to match. + * @param {boolean} opt_exactMatch If true, only returns exact matches + * for the expression. + */ + testability.findModels = function(element, expression, opt_exactMatch) { + var prefixes = ['ng-', 'data-ng-', 'ng\\:']; + for (var p = 0; p < prefixes.length; ++p) { + var attributeEquals = opt_exactMatch ? '=' : '*='; + var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]'; + var elements = element.querySelectorAll(selector); + if (elements.length) { + return elements; + } + } + }; + + /** + * @name $$testability#getLocation + * + * @description + * Shortcut for getting the location in a browser agnostic way. Returns + * the path, search, and hash. (e.g. /path?a=b#hash) + */ + testability.getLocation = function() { + return $location.url(); + }; + + /** + * @name $$testability#setLocation + * + * @description + * Shortcut for navigating to a location without doing a full page reload. + * + * @param {string} url The location url (path, search and hash, + * e.g. /path?a=b#hash) to go to. + */ + testability.setLocation = function(url) { + if (url !== $location.url()) { + $location.url(url); + $rootScope.$digest(); + } + }; + + /** + * @name $$testability#whenStable + * + * @description + * Calls the callback when $timeout and $http requests are completed. + * + * @param {function} callback + */ + testability.whenStable = function(callback) { + $browser.notifyWhenNoOutstandingRequests(callback); + }; + + return testability; + }]; + } + + /** @this */ + function $TimeoutProvider() { + this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', + function($rootScope, $browser, $q, $$q, $exceptionHandler) { + + var deferreds = {}; + + + /** + * @ngdoc service + * @name $timeout + * + * @description + * AngularJS's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch + * block and delegates any exceptions to + * {@link ng.$exceptionHandler $exceptionHandler} service. + * + * The return value of calling `$timeout` is a promise, which will be resolved when + * the delay has passed and the timeout function, if provided, is executed. + * + * To cancel a timeout request, call `$timeout.cancel(promise)`. + * + * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to + * synchronously flush the queue of deferred functions. + * + * If you only want a promise that will be resolved after some specified delay + * then you can call `$timeout` without the `fn` function. + * + * @param {function()=} fn A function, whose execution should be delayed. + * @param {number=} [delay=0] Delay in milliseconds. + * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise + * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. + * @param {...*=} Pass additional parameters to the executed function. + * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise + * will be resolved with the return value of the `fn` function. + * + */ + function timeout(fn, delay, invokeApply) { + if (!isFunction(fn)) { + invokeApply = delay; + delay = fn; + fn = noop; + } + + var args = sliceArgs(arguments, 3), + skipApply = (isDefined(invokeApply) && !invokeApply), + deferred = (skipApply ? $$q : $q).defer(), + promise = deferred.promise, + timeoutId; + + timeoutId = $browser.defer(function() { + try { + deferred.resolve(fn.apply(null, args)); + } catch (e) { + deferred.reject(e); + $exceptionHandler(e); + } finally { + delete deferreds[promise.$$timeoutId]; + } + + if (!skipApply) $rootScope.$apply(); + }, delay); + + promise.$$timeoutId = timeoutId; + deferreds[timeoutId] = deferred; + + return promise; + } + + + /** + * @ngdoc method + * @name $timeout#cancel + * + * @description + * Cancels a task associated with the `promise`. As a result of this, the promise will be + * resolved with a rejection. + * + * @param {Promise=} promise Promise returned by the `$timeout` function. + * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully + * canceled. + */ + timeout.cancel = function(promise) { + if (promise && promise.$$timeoutId in deferreds) { + // Timeout cancels should not report an unhandled promise. + markQExceptionHandled(deferreds[promise.$$timeoutId].promise); + deferreds[promise.$$timeoutId].reject('canceled'); + delete deferreds[promise.$$timeoutId]; + return $browser.defer.cancel(promise.$$timeoutId); + } + return false; + }; + + return timeout; + }]; + } + +// NOTE: The usage of window and document instead of $window and $document here is +// deliberate. This service depends on the specific behavior of anchor nodes created by the +// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and +// cause us to break tests. In addition, when the browser resolves a URL for XHR, it +// doesn't know about mocked locations and resolves URLs to the real document - which is +// exactly the behavior needed here. There is little value is mocking these out for this +// service. + var urlParsingNode = window.document.createElement('a'); + var originUrl = urlResolve(window.location.href); + + + /** + * + * Implementation Notes for non-IE browsers + * ---------------------------------------- + * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, + * results both in the normalizing and parsing of the URL. Normalizing means that a relative + * URL will be resolved into an absolute URL in the context of the application document. + * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related + * properties are all populated to reflect the normalized URL. This approach has wide + * compatibility - Safari 1+, Mozilla 1+ etc. See + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * + * Implementation Notes for IE + * --------------------------- + * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other + * browsers. However, the parsed components will not be set if the URL assigned did not specify + * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We + * work around that by performing the parsing in a 2nd step by taking a previously normalized + * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the + * properties such as protocol, hostname, port, etc. + * + * References: + * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * http://url.spec.whatwg.org/#urlutils + * https://github.com/angular/angular.js/pull/2902 + * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ + * + * @kind function + * @param {string} url The URL to be parsed. + * @description Normalizes and parses a URL. + * @returns {object} Returns the normalized URL as a dictionary. + * + * | member name | Description | + * |---------------|----------------| + * | href | A normalized version of the provided URL if it was not an absolute URL | + * | protocol | The protocol including the trailing colon | + * | host | The host and port (if the port is non-default) of the normalizedUrl | + * | search | The search params, minus the question mark | + * | hash | The hash string, minus the hash symbol + * | hostname | The hostname + * | port | The port, without ":" + * | pathname | The pathname, beginning with "/" + * + */ + function urlResolve(url) { + var href = url; + + // Support: IE 9-11 only + if (msie) { + // Normalize before parse. Refer Implementation Notes on why this is + // done in two steps on IE. + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') + ? urlParsingNode.pathname + : '/' + urlParsingNode.pathname + }; + } + + /** + * Parse a request URL and determine whether this is a same-origin request as the application document. + * + * @param {string|object} requestUrl The url of the request as a string that will be resolved + * or a parsed URL object. + * @returns {boolean} Whether the request is for the same origin as the application document. + */ + function urlIsSameOrigin(requestUrl) { + var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; + return (parsed.protocol === originUrl.protocol && + parsed.host === originUrl.host); + } + + /** + * @ngdoc service + * @name $window + * @this + * + * @description + * A reference to the browser's `window` object. While `window` + * is globally available in JavaScript, it causes testability problems, because + * it is a global variable. In AngularJS we always refer to it through the + * `$window` service, so it may be overridden, removed or mocked for testing. + * + * Expressions, like the one defined for the `ngClick` directive in the example + * below, are evaluated with respect to the current scope. Therefore, there is + * no risk of inadvertently coding in a dependency on a global value in such an + * expression. + * + * @example + + + +
    + + +
    +
    + + it('should display the greeting in the input box', function() { + element(by.model('greeting')).sendKeys('Hello, E2E Tests'); + // If we click the button it will block the test runner + // element(':button').click(); + }); + +
    + */ + function $WindowProvider() { + this.$get = valueFn(window); + } + + /** + * @name $$cookieReader + * @requires $document + * + * @description + * This is a private service for reading cookies used by $http and ngCookies + * + * @return {Object} a key/value map of the current cookies + */ + function $$CookieReader($document) { + var rawDocument = $document[0] || {}; + var lastCookies = {}; + var lastCookieString = ''; + + function safeGetCookie(rawDocument) { + try { + return rawDocument.cookie || ''; + } catch (e) { + return ''; + } + } + + function safeDecodeURIComponent(str) { + try { + return decodeURIComponent(str); + } catch (e) { + return str; + } + } + + return function() { + var cookieArray, cookie, i, index, name; + var currentCookieString = safeGetCookie(rawDocument); + + if (currentCookieString !== lastCookieString) { + lastCookieString = currentCookieString; + cookieArray = lastCookieString.split('; '); + lastCookies = {}; + + for (i = 0; i < cookieArray.length; i++) { + cookie = cookieArray[i]; + index = cookie.indexOf('='); + if (index > 0) { //ignore nameless cookies + name = safeDecodeURIComponent(cookie.substring(0, index)); + // the first value that is seen for a cookie is the most + // specific one. values for the same cookie name that + // follow are for less specific paths. + if (isUndefined(lastCookies[name])) { + lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1)); + } + } + } + } + return lastCookies; + }; + } + + $$CookieReader.$inject = ['$document']; + + /** @this */ + function $$CookieReaderProvider() { + this.$get = $$CookieReader; + } + + /* global currencyFilter: true, + dateFilter: true, + filterFilter: true, + jsonFilter: true, + limitToFilter: true, + lowercaseFilter: true, + numberFilter: true, + orderByFilter: true, + uppercaseFilter: true, + */ + + /** + * @ngdoc provider + * @name $filterProvider + * @description + * + * Filters are just functions which transform input to an output. However filters need to be + * Dependency Injected. To achieve this a filter definition consists of a factory function which is + * annotated with dependencies and is responsible for creating a filter function. + * + *
    + * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`. + * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace + * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores + * (`myapp_subsection_filterx`). + *
    + * + * ```js + * // Filter registration + * function MyModule($provide, $filterProvider) { + * // create a service to demonstrate injection (not always needed) + * $provide.value('greet', function(name){ + * return 'Hello ' + name + '!'; + * }); + * + * // register a filter factory which uses the + * // greet service to demonstrate DI. + * $filterProvider.register('greet', function(greet){ + * // return the filter function which uses the greet service + * // to generate salutation + * return function(text) { + * // filters need to be forgiving so check input validity + * return text && greet(text) || text; + * }; + * }); + * } + * ``` + * + * The filter function is registered with the `$injector` under the filter name suffix with + * `Filter`. + * + * ```js + * it('should be the same instance', inject( + * function($filterProvider) { + * $filterProvider.register('reverse', function(){ + * return ...; + * }); + * }, + * function($filter, reverseFilter) { + * expect($filter('reverse')).toBe(reverseFilter); + * }); + * ``` + * + * + * For more information about how AngularJS filters work, and how to create your own filters, see + * {@link guide/filter Filters} in the AngularJS Developer Guide. + */ + + /** + * @ngdoc service + * @name $filter + * @kind function + * @description + * Filters are used for formatting data displayed to the user. + * + * They can be used in view templates, controllers or services. AngularJS comes + * with a collection of [built-in filters](api/ng/filter), but it is easy to + * define your own as well. + * + * The general syntax in templates is as follows: + * + * ```html + * {{ expression [| filter_name[:parameter_value] ... ] }} + * ``` + * + * @param {String} name Name of the filter function to retrieve + * @return {Function} the filter function + * @example + + +
    +

    {{ originalText }}

    +

    {{ filteredText }}

    +
    +
    + + + angular.module('filterExample', []) + .controller('MainCtrl', function($scope, $filter) { + $scope.originalText = 'hello'; + $scope.filteredText = $filter('uppercase')($scope.originalText); + }); + +
    + */ + $FilterProvider.$inject = ['$provide']; + /** @this */ + function $FilterProvider($provide) { + var suffix = 'Filter'; + + /** + * @ngdoc method + * @name $filterProvider#register + * @param {string|Object} name Name of the filter function, or an object map of filters where + * the keys are the filter names and the values are the filter factories. + * + *
    + * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`. + * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace + * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores + * (`myapp_subsection_filterx`). + *
    + * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered. + * @returns {Object} Registered filter instance, or if a map of filters was provided then a map + * of the registered filter instances. + */ + function register(name, factory) { + if (isObject(name)) { + var filters = {}; + forEach(name, function(filter, key) { + filters[key] = register(key, filter); + }); + return filters; + } else { + return $provide.factory(name + suffix, factory); + } + } + this.register = register; + + this.$get = ['$injector', function($injector) { + return function(name) { + return $injector.get(name + suffix); + }; + }]; + + //////////////////////////////////////// + + /* global + currencyFilter: false, + dateFilter: false, + filterFilter: false, + jsonFilter: false, + limitToFilter: false, + lowercaseFilter: false, + numberFilter: false, + orderByFilter: false, + uppercaseFilter: false + */ + + register('currency', currencyFilter); + register('date', dateFilter); + register('filter', filterFilter); + register('json', jsonFilter); + register('limitTo', limitToFilter); + register('lowercase', lowercaseFilter); + register('number', numberFilter); + register('orderBy', orderByFilter); + register('uppercase', uppercaseFilter); + } + + /** + * @ngdoc filter + * @name filter + * @kind function + * + * @description + * Selects a subset of items from `array` and returns it as a new array. + * + * @param {Array} array The source array. + *
    + * **Note**: If the array contains objects that reference themselves, filtering is not possible. + *
    + * @param {string|Object|function()} expression The predicate to be used for selecting items from + * `array`. + * + * Can be one of: + * + * - `string`: The string is used for matching against the contents of the `array`. All strings or + * objects with string properties in `array` that match this string will be returned. This also + * applies to nested object properties. + * The predicate can be negated by prefixing the string with `!`. + * + * - `Object`: A pattern object can be used to filter specific properties on objects contained + * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items + * which have property `name` containing "M" and property `phone` containing "1". A special + * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match + * against any property of the object or its nested object properties. That's equivalent to the + * simple substring match with a `string` as described above. The special property name can be + * overwritten, using the `anyPropertyKey` parameter. + * The predicate can be negated by prefixing the string with `!`. + * For example `{name: "!M"}` predicate will return an array of items which have property `name` + * not containing "M". + * + * Note that a named property will match properties on the same level only, while the special + * `$` property will match properties on the same level or deeper. E.g. an array item like + * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but + * **will** be matched by `{$: 'John'}`. + * + * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters. + * The function is called for each element of the array, with the element, its index, and + * the entire array itself as arguments. + * + * The final result is an array of those elements that the predicate returned true for. + * + * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in + * determining if values retrieved using `expression` (when it is not a function) should be + * considered a match based on the expected value (from the filter expression) and actual + * value (from the object in the array). + * + * Can be one of: + * + * - `function(actual, expected)`: + * The function will be given the object value and the predicate value to compare and + * should return true if both values should be considered equal. + * + * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`. + * This is essentially strict comparison of expected and actual. + * + * - `false`: A short hand for a function which will look for a substring match in a case + * insensitive way. Primitive values are converted to strings. Objects are not compared against + * primitives, unless they have a custom `toString` method (e.g. `Date` objects). + * + * + * Defaults to `false`. + * + * @param {string} [anyPropertyKey] The special property name that matches against any property. + * By default `$`. + * + * @example + + +
    + + + + + + + + +
    NamePhone
    {{friend.name}}{{friend.phone}}
    +
    +
    +
    +
    +
    + + + + + + +
    NamePhone
    {{friendObj.name}}{{friendObj.phone}}
    +
    + + var expectFriendNames = function(expectedNames, key) { + element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { + arr.forEach(function(wd, i) { + expect(wd.getText()).toMatch(expectedNames[i]); + }); + }); + }; + + it('should search across all fields when filtering with a string', function() { + var searchText = element(by.model('searchText')); + searchText.clear(); + searchText.sendKeys('m'); + expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); + + searchText.clear(); + searchText.sendKeys('76'); + expectFriendNames(['John', 'Julie'], 'friend'); + }); + + it('should search in specific fields when filtering with a predicate object', function() { + var searchAny = element(by.model('search.$')); + searchAny.clear(); + searchAny.sendKeys('i'); + expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); + }); + it('should use a equal comparison when comparator is true', function() { + var searchName = element(by.model('search.name')); + var strict = element(by.model('strict')); + searchName.clear(); + searchName.sendKeys('Julie'); + strict.click(); + expectFriendNames(['Julie'], 'friendObj'); + }); + +
    + */ + + function filterFilter() { + return function(array, expression, comparator, anyPropertyKey) { + if (!isArrayLike(array)) { + if (array == null) { + return array; + } else { + throw minErr('filter')('notarray', 'Expected array but received: {0}', array); + } + } + + anyPropertyKey = anyPropertyKey || '$'; + var expressionType = getTypeForFilter(expression); + var predicateFn; + var matchAgainstAnyProp; + + switch (expressionType) { + case 'function': + predicateFn = expression; + break; + case 'boolean': + case 'null': + case 'number': + case 'string': + matchAgainstAnyProp = true; + // falls through + case 'object': + predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp); + break; + default: + return array; + } + + return Array.prototype.filter.call(array, predicateFn); + }; + } + +// Helper functions for `filterFilter` + function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) { + var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression); + var predicateFn; + + if (comparator === true) { + comparator = equals; + } else if (!isFunction(comparator)) { + comparator = function(actual, expected) { + if (isUndefined(actual)) { + // No substring matching against `undefined` + return false; + } + if ((actual === null) || (expected === null)) { + // No substring matching against `null`; only match against `null` + return actual === expected; + } + if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) { + // Should not compare primitives against objects, unless they have custom `toString` method + return false; + } + + actual = lowercase('' + actual); + expected = lowercase('' + expected); + return actual.indexOf(expected) !== -1; + }; + } + + predicateFn = function(item) { + if (shouldMatchPrimitives && !isObject(item)) { + return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false); + } + return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp); + }; + + return predicateFn; + } + + function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) { + var actualType = getTypeForFilter(actual); + var expectedType = getTypeForFilter(expected); + + if ((expectedType === 'string') && (expected.charAt(0) === '!')) { + return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp); + } else if (isArray(actual)) { + // In case `actual` is an array, consider it a match + // if ANY of it's items matches `expected` + return actual.some(function(item) { + return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp); + }); + } + + switch (actualType) { + case 'object': + var key; + if (matchAgainstAnyProp) { + for (key in actual) { + // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined + // See: https://github.com/angular/angular.js/issues/15644 + if (key.charAt && (key.charAt(0) !== '$') && + deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) { + return true; + } + } + return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false); + } else if (expectedType === 'object') { + for (key in expected) { + var expectedVal = expected[key]; + if (isFunction(expectedVal) || isUndefined(expectedVal)) { + continue; + } + + var matchAnyProperty = key === anyPropertyKey; + var actualVal = matchAnyProperty ? actual : actual[key]; + if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) { + return false; + } + } + return true; + } else { + return comparator(actual, expected); + } + case 'function': + return false; + default: + return comparator(actual, expected); + } + } + +// Used for easily differentiating between `null` and actual `object` + function getTypeForFilter(val) { + return (val === null) ? 'null' : typeof val; + } + + var MAX_DIGITS = 22; + var DECIMAL_SEP = '.'; + var ZERO_CHAR = '0'; + + /** + * @ngdoc filter + * @name currency + * @kind function + * + * @description + * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default + * symbol for current locale is used. + * + * @param {number} amount Input to filter. + * @param {string=} symbol Currency symbol or identifier to be displayed. + * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale + * @returns {string} Formatted number. + * + * + * @example + + + +
    +
    + default currency symbol ($): {{amount | currency}}
    + custom currency identifier (USD$): {{amount | currency:"USD$"}}
    + no fractions (0): {{amount | currency:"USD$":0}} +
    +
    + + it('should init with 1234.56', function() { + expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); + expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56'); + expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235'); + }); + it('should update', function() { + if (browser.params.browser === 'safari') { + // Safari does not understand the minus key. See + // https://github.com/angular/protractor/issues/481 + return; + } + element(by.model('amount')).clear(); + element(by.model('amount')).sendKeys('-1234'); + expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00'); + expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00'); + expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234'); + }); + +
    + */ + currencyFilter.$inject = ['$locale']; + function currencyFilter($locale) { + var formats = $locale.NUMBER_FORMATS; + return function(amount, currencySymbol, fractionSize) { + if (isUndefined(currencySymbol)) { + currencySymbol = formats.CURRENCY_SYM; + } + + if (isUndefined(fractionSize)) { + fractionSize = formats.PATTERNS[1].maxFrac; + } + + // If the currency symbol is empty, trim whitespace around the symbol + var currencySymbolRe = !currencySymbol ? /\s*\u00A4\s*/g : /\u00A4/g; + + // if null or undefined pass it through + return (amount == null) + ? amount + : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). + replace(currencySymbolRe, currencySymbol); + }; + } + + /** + * @ngdoc filter + * @name number + * @kind function + * + * @description + * Formats a number as text. + * + * If the input is null or undefined, it will just be returned. + * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively. + * If the input is not a number an empty string is returned. + * + * + * @param {number|string} number Number to format. + * @param {(number|string)=} fractionSize Number of decimal places to round the number to. + * If this is not provided then the fraction size is computed from the current locale's number + * formatting pattern. In the case of the default locale, it will be 3. + * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current + * locale (e.g., in the en_US locale it will have "." as the decimal separator and + * include "," group separators after each third digit). + * + * @example + + + +
    +
    + Default formatting: {{val | number}}
    + No fractions: {{val | number:0}}
    + Negative number: {{-val | number:4}} +
    +
    + + it('should format numbers', function() { + expect(element(by.id('number-default')).getText()).toBe('1,234.568'); + expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); + expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); + }); + + it('should update', function() { + element(by.model('val')).clear(); + element(by.model('val')).sendKeys('3374.333'); + expect(element(by.id('number-default')).getText()).toBe('3,374.333'); + expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); + expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); + }); + +
    + */ + numberFilter.$inject = ['$locale']; + function numberFilter($locale) { + var formats = $locale.NUMBER_FORMATS; + return function(number, fractionSize) { + + // if null or undefined pass it through + return (number == null) + ? number + : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, + fractionSize); + }; + } + + /** + * Parse a number (as a string) into three components that can be used + * for formatting the number. + * + * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/) + * + * @param {string} numStr The number to parse + * @return {object} An object describing this number, containing the following keys: + * - d : an array of digits containing leading zeros as necessary + * - i : the number of the digits in `d` that are to the left of the decimal point + * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d` + * + */ + function parse(numStr) { + var exponent = 0, digits, numberOfIntegerDigits; + var i, j, zeros; + + // Decimal point? + if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) { + numStr = numStr.replace(DECIMAL_SEP, ''); + } + + // Exponential form? + if ((i = numStr.search(/e/i)) > 0) { + // Work out the exponent. + if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i; + numberOfIntegerDigits += +numStr.slice(i + 1); + numStr = numStr.substring(0, i); + } else if (numberOfIntegerDigits < 0) { + // There was no decimal point or exponent so it is an integer. + numberOfIntegerDigits = numStr.length; + } + + // Count the number of leading zeros. + for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ } + + if (i === (zeros = numStr.length)) { + // The digits are all zero. + digits = [0]; + numberOfIntegerDigits = 1; + } else { + // Count the number of trailing zeros + zeros--; + while (numStr.charAt(zeros) === ZERO_CHAR) zeros--; + + // Trailing zeros are insignificant so ignore them + numberOfIntegerDigits -= i; + digits = []; + // Convert string to array of digits without leading/trailing zeros. + for (j = 0; i <= zeros; i++, j++) { + digits[j] = +numStr.charAt(i); + } + } + + // If the number overflows the maximum allowed digits then use an exponent. + if (numberOfIntegerDigits > MAX_DIGITS) { + digits = digits.splice(0, MAX_DIGITS - 1); + exponent = numberOfIntegerDigits - 1; + numberOfIntegerDigits = 1; + } + + return { d: digits, e: exponent, i: numberOfIntegerDigits }; + } + + /** + * Round the parsed number to the specified number of decimal places + * This function changed the parsedNumber in-place + */ + function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { + var digits = parsedNumber.d; + var fractionLen = digits.length - parsedNumber.i; + + // determine fractionSize if it is not specified; `+fractionSize` converts it to a number + fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; + + // The index of the digit to where rounding is to occur + var roundAt = fractionSize + parsedNumber.i; + var digit = digits[roundAt]; + + if (roundAt > 0) { + // Drop fractional digits beyond `roundAt` + digits.splice(Math.max(parsedNumber.i, roundAt)); + + // Set non-fractional digits beyond `roundAt` to 0 + for (var j = roundAt; j < digits.length; j++) { + digits[j] = 0; + } + } else { + // We rounded to zero so reset the parsedNumber + fractionLen = Math.max(0, fractionLen); + parsedNumber.i = 1; + digits.length = Math.max(1, roundAt = fractionSize + 1); + digits[0] = 0; + for (var i = 1; i < roundAt; i++) digits[i] = 0; + } + + if (digit >= 5) { + if (roundAt - 1 < 0) { + for (var k = 0; k > roundAt; k--) { + digits.unshift(0); + parsedNumber.i++; + } + digits.unshift(1); + parsedNumber.i++; + } else { + digits[roundAt - 1]++; + } + } + + // Pad out with zeros to get the required fraction length + for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); + + + // Do any carrying, e.g. a digit was rounded up to 10 + var carry = digits.reduceRight(function(carry, d, i, digits) { + d = d + carry; + digits[i] = d % 10; + return Math.floor(d / 10); + }, 0); + if (carry) { + digits.unshift(carry); + parsedNumber.i++; + } + } + + /** + * Format a number into a string + * @param {number} number The number to format + * @param {{ + * minFrac, // the minimum number of digits required in the fraction part of the number + * maxFrac, // the maximum number of digits required in the fraction part of the number + * gSize, // number of digits in each group of separated digits + * lgSize, // number of digits in the last group of digits before the decimal separator + * negPre, // the string to go in front of a negative number (e.g. `-` or `(`)) + * posPre, // the string to go in front of a positive number + * negSuf, // the string to go after a negative number (e.g. `)`) + * posSuf // the string to go after a positive number + * }} pattern + * @param {string} groupSep The string to separate groups of number (e.g. `,`) + * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`) + * @param {[type]} fractionSize The size of the fractional part of the number + * @return {string} The number formatted as a string + */ + function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { + + if (!(isString(number) || isNumber(number)) || isNaN(number)) return ''; + + var isInfinity = !isFinite(number); + var isZero = false; + var numStr = Math.abs(number) + '', + formattedText = '', + parsedNumber; + + if (isInfinity) { + formattedText = '\u221e'; + } else { + parsedNumber = parse(numStr); + + roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac); + + var digits = parsedNumber.d; + var integerLen = parsedNumber.i; + var exponent = parsedNumber.e; + var decimals = []; + isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true); + + // pad zeros for small numbers + while (integerLen < 0) { + digits.unshift(0); + integerLen++; + } + + // extract decimals digits + if (integerLen > 0) { + decimals = digits.splice(integerLen, digits.length); + } else { + decimals = digits; + digits = [0]; + } + + // format the integer digits with grouping separators + var groups = []; + if (digits.length >= pattern.lgSize) { + groups.unshift(digits.splice(-pattern.lgSize, digits.length).join('')); + } + while (digits.length > pattern.gSize) { + groups.unshift(digits.splice(-pattern.gSize, digits.length).join('')); + } + if (digits.length) { + groups.unshift(digits.join('')); + } + formattedText = groups.join(groupSep); + + // append the decimal digits + if (decimals.length) { + formattedText += decimalSep + decimals.join(''); + } + + if (exponent) { + formattedText += 'e+' + exponent; + } + } + if (number < 0 && !isZero) { + return pattern.negPre + formattedText + pattern.negSuf; + } else { + return pattern.posPre + formattedText + pattern.posSuf; + } + } + + function padNumber(num, digits, trim, negWrap) { + var neg = ''; + if (num < 0 || (negWrap && num <= 0)) { + if (negWrap) { + num = -num + 1; + } else { + num = -num; + neg = '-'; + } + } + num = '' + num; + while (num.length < digits) num = ZERO_CHAR + num; + if (trim) { + num = num.substr(num.length - digits); + } + return neg + num; + } + + + function dateGetter(name, size, offset, trim, negWrap) { + offset = offset || 0; + return function(date) { + var value = date['get' + name](); + if (offset > 0 || value > -offset) { + value += offset; + } + if (value === 0 && offset === -12) value = 12; + return padNumber(value, size, trim, negWrap); + }; + } + + function dateStrGetter(name, shortForm, standAlone) { + return function(date, formats) { + var value = date['get' + name](); + var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : ''); + var get = uppercase(propPrefix + name); + + return formats[get][value]; + }; + } + + function timeZoneGetter(date, formats, offset) { + var zone = -1 * offset; + var paddedZone = (zone >= 0) ? '+' : ''; + + paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + + padNumber(Math.abs(zone % 60), 2); + + return paddedZone; + } + + function getFirstThursdayOfYear(year) { + // 0 = index of January + var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay(); + // 4 = index of Thursday (+1 to account for 1st = 5) + // 11 = index of *next* Thursday (+1 account for 1st = 12) + return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst); + } + + function getThursdayThisWeek(datetime) { + return new Date(datetime.getFullYear(), datetime.getMonth(), + // 4 = index of Thursday + datetime.getDate() + (4 - datetime.getDay())); + } + + function weekGetter(size) { + return function(date) { + var firstThurs = getFirstThursdayOfYear(date.getFullYear()), + thisThurs = getThursdayThisWeek(date); + + var diff = +thisThurs - +firstThurs, + result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week + + return padNumber(result, size); + }; + } + + function ampmGetter(date, formats) { + return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; + } + + function eraGetter(date, formats) { + return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1]; + } + + function longEraGetter(date, formats) { + return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1]; + } + + var DATE_FORMATS = { + yyyy: dateGetter('FullYear', 4, 0, false, true), + yy: dateGetter('FullYear', 2, 0, true, true), + y: dateGetter('FullYear', 1, 0, false, true), + MMMM: dateStrGetter('Month'), + MMM: dateStrGetter('Month', true), + MM: dateGetter('Month', 2, 1), + M: dateGetter('Month', 1, 1), + LLLL: dateStrGetter('Month', false, true), + dd: dateGetter('Date', 2), + d: dateGetter('Date', 1), + HH: dateGetter('Hours', 2), + H: dateGetter('Hours', 1), + hh: dateGetter('Hours', 2, -12), + h: dateGetter('Hours', 1, -12), + mm: dateGetter('Minutes', 2), + m: dateGetter('Minutes', 1), + ss: dateGetter('Seconds', 2), + s: dateGetter('Seconds', 1), + // while ISO 8601 requires fractions to be prefixed with `.` or `,` + // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions + sss: dateGetter('Milliseconds', 3), + EEEE: dateStrGetter('Day'), + EEE: dateStrGetter('Day', true), + a: ampmGetter, + Z: timeZoneGetter, + ww: weekGetter(2), + w: weekGetter(1), + G: eraGetter, + GG: eraGetter, + GGG: eraGetter, + GGGG: longEraGetter + }; + + var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/, + NUMBER_STRING = /^-?\d+$/; + + /** + * @ngdoc filter + * @name date + * @kind function + * + * @description + * Formats `date` to a string based on the requested `format`. + * + * `format` string can be composed of the following elements: + * + * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) + * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) + * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) + * * `'MMMM'`: Month in year (January-December) + * * `'MMM'`: Month in year (Jan-Dec) + * * `'MM'`: Month in year, padded (01-12) + * * `'M'`: Month in year (1-12) + * * `'LLLL'`: Stand-alone month in year (January-December) + * * `'dd'`: Day in month, padded (01-31) + * * `'d'`: Day in month (1-31) + * * `'EEEE'`: Day in Week,(Sunday-Saturday) + * * `'EEE'`: Day in Week, (Sun-Sat) + * * `'HH'`: Hour in day, padded (00-23) + * * `'H'`: Hour in day (0-23) + * * `'hh'`: Hour in AM/PM, padded (01-12) + * * `'h'`: Hour in AM/PM, (1-12) + * * `'mm'`: Minute in hour, padded (00-59) + * * `'m'`: Minute in hour (0-59) + * * `'ss'`: Second in minute, padded (00-59) + * * `'s'`: Second in minute (0-59) + * * `'sss'`: Millisecond in second, padded (000-999) + * * `'a'`: AM/PM marker + * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) + * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year + * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year + * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD') + * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini') + * + * `format` string can also be one of the following predefined + * {@link guide/i18n localizable formats}: + * + * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale + * (e.g. Sep 3, 2010 12:05:08 PM) + * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM) + * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale + * (e.g. Friday, September 3, 2010) + * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) + * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) + * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) + * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM) + * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM) + * + * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g. + * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence + * (e.g. `"h 'o''clock'"`). + * + * Any other characters in the `format` string will be output as-is. + * + * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or + * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its + * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is + * specified in the string input, the time is considered to be in the local timezone. + * @param {string=} format Formatting rules (see Description). If not specified, + * `mediumDate` is used. + * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the + * continental US time zone abbreviations, but for general use, use a time zone offset, for + * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian) + * If not specified, the timezone of the browser will be used. + * @returns {string} Formatted string or the input if input is not recognized as date/millis. + * + * @example + + + {{1288323623006 | date:'medium'}}: + {{1288323623006 | date:'medium'}}
    + {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: + {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
    + {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: + {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
    + {{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: + {{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}
    +
    + + it('should format date', function() { + expect(element(by.binding("1288323623006 | date:'medium'")).getText()). + toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); + expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). + toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/); + expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). + toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); + expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()). + toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/); + }); + +
    + */ + dateFilter.$inject = ['$locale']; + function dateFilter($locale) { + + + var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; + // 1 2 3 4 5 6 7 8 9 10 11 + function jsonStringToDate(string) { + var match; + if ((match = string.match(R_ISO8601_STR))) { + var date = new Date(0), + tzHour = 0, + tzMin = 0, + dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, + timeSetter = match[8] ? date.setUTCHours : date.setHours; + + if (match[9]) { + tzHour = toInt(match[9] + match[10]); + tzMin = toInt(match[9] + match[11]); + } + dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3])); + var h = toInt(match[4] || 0) - tzHour; + var m = toInt(match[5] || 0) - tzMin; + var s = toInt(match[6] || 0); + var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000); + timeSetter.call(date, h, m, s, ms); + return date; + } + return string; + } + + + return function(date, format, timezone) { + var text = '', + parts = [], + fn, match; + + format = format || 'mediumDate'; + format = $locale.DATETIME_FORMATS[format] || format; + if (isString(date)) { + date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date); + } + + if (isNumber(date)) { + date = new Date(date); + } + + if (!isDate(date) || !isFinite(date.getTime())) { + return date; + } + + while (format) { + match = DATE_FORMATS_SPLIT.exec(format); + if (match) { + parts = concat(parts, match, 1); + format = parts.pop(); + } else { + parts.push(format); + format = null; + } + } + + var dateTimezoneOffset = date.getTimezoneOffset(); + if (timezone) { + dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); + date = convertTimezoneToLocal(date, timezone, true); + } + forEach(parts, function(value) { + fn = DATE_FORMATS[value]; + text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset) + : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\''); + }); + + return text; + }; + } + + + /** + * @ngdoc filter + * @name json + * @kind function + * + * @description + * Allows you to convert a JavaScript object into JSON string. + * + * This filter is mostly useful for debugging. When using the double curly {{value}} notation + * the binding is automatically converted to JSON. + * + * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. + * @param {number=} spacing The number of spaces to use per indentation, defaults to 2. + * @returns {string} JSON string. + * + * + * @example + + +
    {{ {'name':'value'} | json }}
    +
    {{ {'name':'value'} | json:4 }}
    +
    + + it('should jsonify filtered objects', function() { + expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/); + expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/); + }); + +
    + * + */ + function jsonFilter() { + return function(object, spacing) { + if (isUndefined(spacing)) { + spacing = 2; + } + return toJson(object, spacing); + }; + } + + + /** + * @ngdoc filter + * @name lowercase + * @kind function + * @description + * Converts string to lowercase. + * + * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example. + * + * @see angular.lowercase + */ + var lowercaseFilter = valueFn(lowercase); + + + /** + * @ngdoc filter + * @name uppercase + * @kind function + * @description + * Converts string to uppercase. + * @example + + + +
    + +

    {{title}}

    + +

    {{title | uppercase}}

    +
    +
    +
    + */ + var uppercaseFilter = valueFn(uppercase); + + /** + * @ngdoc filter + * @name limitTo + * @kind function + * + * @description + * Creates a new array or string containing only a specified number of elements. The elements are + * taken from either the beginning or the end of the source array, string or number, as specified by + * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported + * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input, + * it is converted to a string. + * + * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited. + * @param {string|number} limit - The length of the returned array or string. If the `limit` number + * is positive, `limit` number of items from the beginning of the source array/string are copied. + * If the number is negative, `limit` number of items from the end of the source array/string + * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined, + * the input will be returned unchanged. + * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index, + * `begin` indicates an offset from the end of `input`. Defaults to `0`. + * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had + * less than `limit` elements. + * + * @example + + + +
    + +

    Output numbers: {{ numbers | limitTo:numLimit }}

    + +

    Output letters: {{ letters | limitTo:letterLimit }}

    + +

    Output long number: {{ longNumber | limitTo:longNumberLimit }}

    +
    +
    + + var numLimitInput = element(by.model('numLimit')); + var letterLimitInput = element(by.model('letterLimit')); + var longNumberLimitInput = element(by.model('longNumberLimit')); + var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); + var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); + var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit')); + + it('should limit the number array to first three items', function() { + expect(numLimitInput.getAttribute('value')).toBe('3'); + expect(letterLimitInput.getAttribute('value')).toBe('3'); + expect(longNumberLimitInput.getAttribute('value')).toBe('3'); + expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); + expect(limitedLetters.getText()).toEqual('Output letters: abc'); + expect(limitedLongNumber.getText()).toEqual('Output long number: 234'); + }); + + // There is a bug in safari and protractor that doesn't like the minus key + // it('should update the output when -3 is entered', function() { + // numLimitInput.clear(); + // numLimitInput.sendKeys('-3'); + // letterLimitInput.clear(); + // letterLimitInput.sendKeys('-3'); + // longNumberLimitInput.clear(); + // longNumberLimitInput.sendKeys('-3'); + // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); + // expect(limitedLetters.getText()).toEqual('Output letters: ghi'); + // expect(limitedLongNumber.getText()).toEqual('Output long number: 342'); + // }); + + it('should not exceed the maximum size of input array', function() { + numLimitInput.clear(); + numLimitInput.sendKeys('100'); + letterLimitInput.clear(); + letterLimitInput.sendKeys('100'); + longNumberLimitInput.clear(); + longNumberLimitInput.sendKeys('100'); + expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); + expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); + expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342'); + }); + +
    + */ + function limitToFilter() { + return function(input, limit, begin) { + if (Math.abs(Number(limit)) === Infinity) { + limit = Number(limit); + } else { + limit = toInt(limit); + } + if (isNumberNaN(limit)) return input; + + if (isNumber(input)) input = input.toString(); + if (!isArrayLike(input)) return input; + + begin = (!begin || isNaN(begin)) ? 0 : toInt(begin); + begin = (begin < 0) ? Math.max(0, input.length + begin) : begin; + + if (limit >= 0) { + return sliceFn(input, begin, begin + limit); + } else { + if (begin === 0) { + return sliceFn(input, limit, input.length); + } else { + return sliceFn(input, Math.max(0, begin + limit), begin); + } + } + }; + } + + function sliceFn(input, begin, end) { + if (isString(input)) return input.slice(begin, end); + + return slice.call(input, begin, end); + } + + /** + * @ngdoc filter + * @name orderBy + * @kind function + * + * @description + * Returns an array containing the items from the specified `collection`, ordered by a `comparator` + * function based on the values computed using the `expression` predicate. + * + * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in + * `[{id: 'bar'}, {id: 'foo'}]`. + * + * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray, + * String, etc). + * + * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker + * for the preceding one. The `expression` is evaluated against each item and the output is used + * for comparing with other items. + * + * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in + * ascending order. + * + * The comparison is done using the `comparator` function. If none is specified, a default, built-in + * comparator is used (see below for details - in a nutshell, it compares numbers numerically and + * strings alphabetically). + * + * ### Under the hood + * + * Ordering the specified `collection` happens in two phases: + * + * 1. All items are passed through the predicate (or predicates), and the returned values are saved + * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed + * through a predicate that extracts the value of the `label` property, would be transformed to: + * ``` + * { + * value: 'foo', + * type: 'string', + * index: ... + * } + * ``` + * 2. The comparator function is used to sort the items, based on the derived values, types and + * indices. + * + * If you use a custom comparator, it will be called with pairs of objects of the form + * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal + * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the + * second, or `1` otherwise. + * + * In order to ensure that the sorting will be deterministic across platforms, if none of the + * specified predicates can distinguish between two items, `orderBy` will automatically introduce a + * dummy predicate that returns the item's index as `value`. + * (If you are using a custom comparator, make sure it can handle this predicate as well.) + * + * If a custom comparator still can't distinguish between two items, then they will be sorted based + * on their index using the built-in comparator. + * + * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted + * value for an item, `orderBy` will try to convert that object to a primitive value, before passing + * it to the comparator. The following rules govern the conversion: + * + * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be + * used instead.
    + * (If the object has a `valueOf()` method that returns another object, then the returned object + * will be used in subsequent steps.) + * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that + * returns a primitive, its return value will be used instead.
    + * (If the object has a `toString()` method that returns another object, then the returned object + * will be used in subsequent steps.) + * 3. No conversion; the object itself is used. + * + * ### The default comparator + * + * The default, built-in comparator should be sufficient for most usecases. In short, it compares + * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to + * using their index in the original collection, and sorts values of different types by type. + * + * More specifically, it follows these steps to determine the relative order of items: + * + * 1. If the compared values are of different types, compare the types themselves alphabetically. + * 2. If both values are of type `string`, compare them alphabetically in a case- and + * locale-insensitive way. + * 3. If both values are objects, compare their indices instead. + * 4. Otherwise, return: + * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`). + * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator). + * - `1`, otherwise. + * + * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being + * saved as numbers and not strings. + * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e. + * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to + * other values. + * + * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort. + * @param {(Function|string|Array.)=} expression - A predicate (or list of + * predicates) to be used by the comparator to determine the order of elements. + * + * Can be one of: + * + * - `Function`: A getter function. This function will be called with each item as argument and + * the return value will be used for sorting. + * - `string`: An AngularJS expression. This expression will be evaluated against each item and the + * result will be used for sorting. For example, use `'label'` to sort by a property called + * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label` + * property.
    + * (The result of a constant expression is interpreted as a property name to be used for + * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a + * property called `special name`.)
    + * An expression can be optionally prefixed with `+` or `-` to control the sorting direction, + * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided, + * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons. + * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the + * relative order of two items, the next predicate is used as a tie-breaker. + * + * **Note:** If the predicate is missing or empty then it defaults to `'+'`. + * + * @param {boolean=} reverse - If `true`, reverse the sorting order. + * @param {(Function)=} comparator - The comparator function used to determine the relative order of + * value pairs. If omitted, the built-in comparator will be used. + * + * @returns {Array} - The sorted array. + * + * + * @example + * ### Ordering a table with `ngRepeat` + * + * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by + * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means + * it defaults to the built-in comparator. + * + + +
    + + + + + + + + + + + +
    NamePhone NumberAge
    {{friend.name}}{{friend.phone}}{{friend.age}}
    +
    +
    + + angular.module('orderByExample1', []) + .controller('ExampleController', ['$scope', function($scope) { + $scope.friends = [ + {name: 'John', phone: '555-1212', age: 10}, + {name: 'Mary', phone: '555-9876', age: 19}, + {name: 'Mike', phone: '555-4321', age: 21}, + {name: 'Adam', phone: '555-5678', age: 35}, + {name: 'Julie', phone: '555-8765', age: 29} + ]; + }]); + + + .friends { + border-collapse: collapse; + } + + .friends th { + border-bottom: 1px solid; + } + .friends td, .friends th { + border-left: 1px solid; + padding: 5px 10px; + } + .friends td:first-child, .friends th:first-child { + border-left: none; + } + + + // Element locators + var names = element.all(by.repeater('friends').column('friend.name')); + + it('should sort friends by age in reverse order', function() { + expect(names.get(0).getText()).toBe('Adam'); + expect(names.get(1).getText()).toBe('Julie'); + expect(names.get(2).getText()).toBe('Mike'); + expect(names.get(3).getText()).toBe('Mary'); + expect(names.get(4).getText()).toBe('John'); + }); + +
    + *
    * - * To be secure by default, you want to ensure that any such bindings are disallowed unless you can - * determine that something explicitly says it's safe to use a value for binding in that - * context. You can then audit your code (a simple grep would do) to ensure that this is only done - * for those values that you can easily tell are safe - because they were received from your server, - * sanitized by your library, etc. You can organize your codebase to help with this - perhaps - * allowing only the files in a specific directory to do this. Ensuring that the internal API - * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. + * @example + * ### Changing parameters dynamically * - * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} - * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to - * obtain values that will be accepted by SCE / privileged contexts. + * All parameters can be changed dynamically. The next example shows how you can make the columns of + * a table sortable, by binding the `expression` and `reverse` parameters to scope properties. + * + + +
    +
    Sort by = {{propertyName}}; reverse = {{reverse}}
    +
    + +
    + + + + + + + + + + + +
    + + + + + + + + +
    {{friend.name}}{{friend.phone}}{{friend.age}}
    +
    +
    + + angular.module('orderByExample2', []) + .controller('ExampleController', ['$scope', function($scope) { + var friends = [ + {name: 'John', phone: '555-1212', age: 10}, + {name: 'Mary', phone: '555-9876', age: 19}, + {name: 'Mike', phone: '555-4321', age: 21}, + {name: 'Adam', phone: '555-5678', age: 35}, + {name: 'Julie', phone: '555-8765', age: 29} + ]; + + $scope.propertyName = 'age'; + $scope.reverse = true; + $scope.friends = friends; + + $scope.sortBy = function(propertyName) { + $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false; + $scope.propertyName = propertyName; + }; + }]); + + + .friends { + border-collapse: collapse; + } + + .friends th { + border-bottom: 1px solid; + } + .friends td, .friends th { + border-left: 1px solid; + padding: 5px 10px; + } + .friends td:first-child, .friends th:first-child { + border-left: none; + } + + .sortorder:after { + content: '\25b2'; // BLACK UP-POINTING TRIANGLE + } + .sortorder.reverse:after { + content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE + } + + + // Element locators + var unsortButton = element(by.partialButtonText('unsorted')); + var nameHeader = element(by.partialButtonText('Name')); + var phoneHeader = element(by.partialButtonText('Phone')); + var ageHeader = element(by.partialButtonText('Age')); + var firstName = element(by.repeater('friends').column('friend.name').row(0)); + var lastName = element(by.repeater('friends').column('friend.name').row(4)); + + it('should sort friends by some property, when clicking on the column header', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + phoneHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Mary'); + + nameHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('Mike'); + + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); + }); + + it('should sort friends in reverse order, when clicking on the same column', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); + + ageHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + }); + + it('should restore the original order, when clicking "Set to unsorted"', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + unsortButton.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Julie'); + }); + +
    + *
    + * + * @example + * ### Using `orderBy` inside a controller + * + * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and + * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory + * and retrieve the `orderBy` filter with `$filter('orderBy')`.) + * + + +
    +
    Sort by = {{propertyName}}; reverse = {{reverse}}
    +
    + +
    + + + + + + + + + + + +
    + + + + + + + + +
    {{friend.name}}{{friend.phone}}{{friend.age}}
    +
    +
    + + angular.module('orderByExample3', []) + .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) { + var friends = [ + {name: 'John', phone: '555-1212', age: 10}, + {name: 'Mary', phone: '555-9876', age: 19}, + {name: 'Mike', phone: '555-4321', age: 21}, + {name: 'Adam', phone: '555-5678', age: 35}, + {name: 'Julie', phone: '555-8765', age: 29} + ]; + + $scope.propertyName = 'age'; + $scope.reverse = true; + $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse); + + $scope.sortBy = function(propertyName) { + $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName) + ? !$scope.reverse : false; + $scope.propertyName = propertyName; + $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse); + }; + }]); + + + .friends { + border-collapse: collapse; + } + + .friends th { + border-bottom: 1px solid; + } + .friends td, .friends th { + border-left: 1px solid; + padding: 5px 10px; + } + .friends td:first-child, .friends th:first-child { + border-left: none; + } + + .sortorder:after { + content: '\25b2'; // BLACK UP-POINTING TRIANGLE + } + .sortorder.reverse:after { + content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE + } + + + // Element locators + var unsortButton = element(by.partialButtonText('unsorted')); + var nameHeader = element(by.partialButtonText('Name')); + var phoneHeader = element(by.partialButtonText('Phone')); + var ageHeader = element(by.partialButtonText('Age')); + var firstName = element(by.repeater('friends').column('friend.name').row(0)); + var lastName = element(by.repeater('friends').column('friend.name').row(4)); + + it('should sort friends by some property, when clicking on the column header', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + phoneHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Mary'); + + nameHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('Mike'); + + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); + }); + + it('should sort friends in reverse order, when clicking on the same column', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); + + ageHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + }); + + it('should restore the original order, when clicking "Set to unsorted"', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + unsortButton.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Julie'); + }); + +
    + *
    + * + * @example + * ### Using a custom comparator + * + * If you have very specific requirements about the way items are sorted, you can pass your own + * comparator function. For example, you might need to compare some strings in a locale-sensitive + * way. (When specifying a custom comparator, you also need to pass a value for the `reverse` + * argument - passing `false` retains the default sorting order, i.e. ascending.) + * + + +
    +
    +

    Locale-sensitive Comparator

    + + + + + + + + + +
    NameFavorite Letter
    {{friend.name}}{{friend.favoriteLetter}}
    +
    +
    +

    Default Comparator

    + + + + + + + + + +
    NameFavorite Letter
    {{friend.name}}{{friend.favoriteLetter}}
    +
    +
    +
    + + angular.module('orderByExample4', []) + .controller('ExampleController', ['$scope', function($scope) { + $scope.friends = [ + {name: 'John', favoriteLetter: 'Ä'}, + {name: 'Mary', favoriteLetter: 'Ü'}, + {name: 'Mike', favoriteLetter: 'Ö'}, + {name: 'Adam', favoriteLetter: 'H'}, + {name: 'Julie', favoriteLetter: 'Z'} + ]; + + $scope.localeSensitiveComparator = function(v1, v2) { + // If we don't get strings, just compare by index + if (v1.type !== 'string' || v2.type !== 'string') { + return (v1.index < v2.index) ? -1 : 1; + } + + // Compare strings alphabetically, taking locale into account + return v1.value.localeCompare(v2.value); + }; + }]); + + + .friends-container { + display: inline-block; + margin: 0 30px; + } + + .friends { + border-collapse: collapse; + } + + .friends th { + border-bottom: 1px solid; + } + .friends td, .friends th { + border-left: 1px solid; + padding: 5px 10px; + } + .friends td:first-child, .friends th:first-child { + border-left: none; + } + + + // Element locators + var container = element(by.css('.custom-comparator')); + var names = container.all(by.repeater('friends').column('friend.name')); + + it('should sort friends by favorite letter (in correct alphabetical order)', function() { + expect(names.get(0).getText()).toBe('John'); + expect(names.get(1).getText()).toBe('Adam'); + expect(names.get(2).getText()).toBe('Mike'); + expect(names.get(3).getText()).toBe('Mary'); + expect(names.get(4).getText()).toBe('Julie'); + }); + +
    * + */ + orderByFilter.$inject = ['$parse']; + function orderByFilter($parse) { + return function(array, sortPredicate, reverseOrder, compareFn) { + + if (array == null) return array; + if (!isArrayLike(array)) { + throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array); + } + + if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; } + if (sortPredicate.length === 0) { sortPredicate = ['+']; } + + var predicates = processPredicates(sortPredicate); + + var descending = reverseOrder ? -1 : 1; + + // Define the `compare()` function. Use a default comparator if none is specified. + var compare = isFunction(compareFn) ? compareFn : defaultCompare; + + // The next three lines are a version of a Swartzian Transform idiom from Perl + // (sometimes called the Decorate-Sort-Undecorate idiom) + // See https://en.wikipedia.org/wiki/Schwartzian_transform + var compareValues = Array.prototype.map.call(array, getComparisonObject); + compareValues.sort(doComparison); + array = compareValues.map(function(item) { return item.value; }); + + return array; + + function getComparisonObject(value, index) { + // NOTE: We are adding an extra `tieBreaker` value based on the element's index. + // This will be used to keep the sort stable when none of the input predicates can + // distinguish between two elements. + return { + value: value, + tieBreaker: {value: index, type: 'number', index: index}, + predicateValues: predicates.map(function(predicate) { + return getPredicateValue(predicate.get(value), index); + }) + }; + } + + function doComparison(v1, v2) { + for (var i = 0, ii = predicates.length; i < ii; i++) { + var result = compare(v1.predicateValues[i], v2.predicateValues[i]); + if (result) { + return result * predicates[i].descending * descending; + } + } + + return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending; + } + }; + + function processPredicates(sortPredicates) { + return sortPredicates.map(function(predicate) { + var descending = 1, get = identity; + + if (isFunction(predicate)) { + get = predicate; + } else if (isString(predicate)) { + if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) { + descending = predicate.charAt(0) === '-' ? -1 : 1; + predicate = predicate.substring(1); + } + if (predicate !== '') { + get = $parse(predicate); + if (get.constant) { + var key = get(); + get = function(value) { return value[key]; }; + } + } + } + return {get: get, descending: descending}; + }); + } + + function isPrimitive(value) { + switch (typeof value) { + case 'number': /* falls through */ + case 'boolean': /* falls through */ + case 'string': + return true; + default: + return false; + } + } + + function objectValue(value) { + // If `valueOf` is a valid function use that + if (isFunction(value.valueOf)) { + value = value.valueOf(); + if (isPrimitive(value)) return value; + } + // If `toString` is a valid function and not the one from `Object.prototype` use that + if (hasCustomToString(value)) { + value = value.toString(); + if (isPrimitive(value)) return value; + } + + return value; + } + + function getPredicateValue(value, index) { + var type = typeof value; + if (value === null) { + type = 'string'; + value = 'null'; + } else if (type === 'object') { + value = objectValue(value); + } + return {value: value, type: type, index: index}; + } + + function defaultCompare(v1, v2) { + var result = 0; + var type1 = v1.type; + var type2 = v2.type; + + if (type1 === type2) { + var value1 = v1.value; + var value2 = v2.value; + + if (type1 === 'string') { + // Compare strings case-insensitively + value1 = value1.toLowerCase(); + value2 = value2.toLowerCase(); + } else if (type1 === 'object') { + // For basic objects, use the position of the object + // in the collection instead of the value + if (isObject(value1)) value1 = v1.index; + if (isObject(value2)) value2 = v2.index; + } + + if (value1 !== value2) { + result = value1 < value2 ? -1 : 1; + } + } else { + result = type1 < type2 ? -1 : 1; + } + + return result; + } + } + + function ngDirective(directive) { + if (isFunction(directive)) { + directive = { + link: directive + }; + } + directive.restrict = directive.restrict || 'AC'; + return valueFn(directive); + } + + /** + * @ngdoc directive + * @name a + * @restrict E + * + * @description + * Modifies the default behavior of the html a tag so that the default action is prevented when + * the href attribute is empty. + * + * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive. + */ + var htmlAnchorDirective = valueFn({ + restrict: 'E', + compile: function(element, attr) { + if (!attr.href && !attr.xlinkHref) { + return function(scope, element) { + // If the linked element is not an anchor tag anymore, do nothing + if (element[0].nodeName.toLowerCase() !== 'a') return; + + // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. + var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? + 'xlink:href' : 'href'; + element.on('click', function(event) { + // if we have no href url, then don't navigate anywhere. + if (!element.attr(href)) { + event.preventDefault(); + } + }); + }; + } + } + }); + + /** + * @ngdoc directive + * @name ngHref + * @restrict A + * @priority 99 + * + * @description + * Using AngularJS markup like `{{hash}}` in an href attribute will + * make the link go to the wrong URL if the user clicks it before + * AngularJS has a chance to replace the `{{hash}}` markup with its + * value. Until AngularJS replaces the markup the link will be broken + * and will most likely return a 404 error. The `ngHref` directive + * solves this problem. + * + * The wrong way to write it: + * ```html + * link1 + * ``` + * + * The correct way to write it: + * ```html + * link1 + * ``` + * + * @element A + * @param {template} ngHref any string which can contain `{{}}` markup. + * + * @example + * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes + * in links and their different behaviors: + + +
    + link 1 (link, don't reload)
    + link 2 (link, don't reload)
    + link 3 (link, reload!)
    + anchor (link, don't reload)
    + anchor (no link)
    + link (link, change location) +
    + + it('should execute ng-click but not reload when href without value', function() { + element(by.id('link-1')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('1'); + expect(element(by.id('link-1')).getAttribute('href')).toBe(''); + }); + + it('should execute ng-click but not reload when href empty string', function() { + element(by.id('link-2')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('2'); + expect(element(by.id('link-2')).getAttribute('href')).toBe(''); + }); + + it('should execute ng-click and change url when ng-href specified', function() { + expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); + + element(by.id('link-3')).click(); + + // At this point, we navigate away from an AngularJS page, so we need + // to use browser.driver to get the base webdriver. + + browser.wait(function() { + return browser.driver.getCurrentUrl().then(function(url) { + return url.match(/\/123$/); + }); + }, 5000, 'page should navigate to /123'); + }); + + it('should execute ng-click but not reload when href empty string and name specified', function() { + element(by.id('link-4')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('4'); + expect(element(by.id('link-4')).getAttribute('href')).toBe(''); + }); + + it('should execute ng-click but not reload when no href but name specified', function() { + element(by.id('link-5')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('5'); + expect(element(by.id('link-5')).getAttribute('href')).toBe(null); + }); + + it('should only change url when only ng-href', function() { + element(by.model('value')).clear(); + element(by.model('value')).sendKeys('6'); + expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); + + element(by.id('link-6')).click(); + + // At this point, we navigate away from an AngularJS page, so we need + // to use browser.driver to get the base webdriver. + browser.wait(function() { + return browser.driver.getCurrentUrl().then(function(url) { + return url.match(/\/6$/); + }); + }, 5000, 'page should navigate to /6'); + }); + +
    + */ + + /** + * @ngdoc directive + * @name ngSrc + * @restrict A + * @priority 99 * - * ## How does it work? + * @description + * Using AngularJS markup like `{{hash}}` in a `src` attribute doesn't + * work right: The browser will fetch from the URL with the literal + * text `{{hash}}` until AngularJS replaces the expression inside + * `{{hash}}`. The `ngSrc` directive solves this problem. * - * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted - * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link - * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the - * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. + * The buggy way to write it: + * ```html + * Description + * ``` * - * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link - * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly - * simplified): + * The correct way to write it: + * ```html + * Description + * ``` * - *
    -     *   var ngBindHtmlDirective = ['$sce', function($sce) {
    - *     return function(scope, element, attr) {
    - *       scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
    - *         element.html(value || '');
    - *       });
    - *     };
    - *   }];
    -     * 
    + * @element IMG + * @param {template} ngSrc any string which can contain `{{}}` markup. + */ + + /** + * @ngdoc directive + * @name ngSrcset + * @restrict A + * @priority 99 * - * ## Impact on loading templates + * @description + * Using AngularJS markup like `{{hash}}` in a `srcset` attribute doesn't + * work right: The browser will fetch from the URL with the literal + * text `{{hash}}` until AngularJS replaces the expression inside + * `{{hash}}`. The `ngSrcset` directive solves this problem. * - * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as - * `templateUrl`'s specified by {@link guide/directive directives}. + * The buggy way to write it: + * ```html + * Description + * ``` * - * By default, Angular only loads templates from the same domain and protocol as the application - * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl - * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or - * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist - * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. + * The correct way to write it: + * ```html + * Description + * ``` * - * *Please note*: - * The browser's - * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) - * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) - * policy apply in addition to this and may further restrict whether the template is successfully - * loaded. This means that without the right CORS policy, loading templates from a different domain - * won't work on all browsers. Also, loading templates from `file://` URL does not work on some - * browsers. + * @element IMG + * @param {template} ngSrcset any string which can contain `{{}}` markup. + */ + + /** + * @ngdoc directive + * @name ngDisabled + * @restrict A + * @priority 100 * - * ## This feels like too much overhead for the developer? + * @description * - * It's important to remember that SCE only applies to interpolation expressions. + * This directive sets the `disabled` attribute on the element (typically a form control, + * e.g. `input`, `button`, `select` etc.) if the + * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy. * - * If your expressions are constant literals, they're automatically trusted and you don't need to - * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g. - * `
    `) just works. + * A special directive is necessary because we cannot use interpolation inside the `disabled` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. * - * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them - * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. + * @example + + +
    + +
    + + it('should toggle button', function() { + expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); + element(by.model('checked')).click(); + expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); + }); + +
    * - * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load - * templates in `ng-include` from your application's domain without having to even know about SCE. - * It blocks loading templates from other domains or loading templates over http from an https - * served document. You can change these by setting your own custom {@link - * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link - * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. + * @element INPUT + * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, + * then the `disabled` attribute will be set on the element + */ + + + /** + * @ngdoc directive + * @name ngChecked + * @restrict A + * @priority 100 * - * This significantly reduces the overhead. It is far easier to pay the small overhead and have an - * application that's secure and can be audited to verify that with much more ease than bolting - * security onto an application later. + * @description + * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy. * - * - * ## What trusted context types are supported? + * Note that this directive should not be used together with {@link ngModel `ngModel`}, + * as this can lead to unexpected behavior. * - * | Context | Notes | - * |---------------------|----------------| - * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. | - * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | - * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
    Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | - * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | + * A special directive is necessary because we cannot use interpolation inside the `checked` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. * - * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
    + * @example + + +
    + +
    + + it('should check both checkBoxes', function() { + expect(element(by.id('checkFollower')).getAttribute('checked')).toBeFalsy(); + element(by.model('leader')).click(); + expect(element(by.id('checkFollower')).getAttribute('checked')).toBeTruthy(); + }); + +
    * - * Each element in these arrays must be one of the following: + * @element INPUT + * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, + * then the `checked` attribute will be set on the element + */ + + + /** + * @ngdoc directive + * @name ngReadonly + * @restrict A + * @priority 100 * - * - **'self'** - * - The special **string**, `'self'`, can be used to match against all URLs of the **same - * domain** as the application document using the **same protocol**. - * - **String** (except the special value `'self'`) - * - The string is matched against the full *normalized / absolute URL* of the resource - * being tested (substring matches are not good enough.) - * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters - * match themselves. - * - `*`: matches zero or more occurrences of any character other than one of the following 6 - * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use - * in a whitelist. - * - `**`: matches zero or more occurrences of *any* character. As such, it's not - * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. - * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might - * not have been the intention.) It's usage at the very end of the path is ok. (e.g. - * http://foo.example.com/templates/**). - * - **RegExp** (*see caveat below*) - * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax - * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to - * accidentally introduce a bug when one updates a complex expression (imho, all regexes should - * have good test coverage.). For instance, the use of `.` in the regex is correct only in a - * small number of cases. A `.` character in the regex used when matching the scheme or a - * subdomain could be matched against a `:` or literal `.` that was likely not intended. It - * is highly recommended to use the string patterns and only fall back to regular expressions - * if they as a last resort. - * - The regular expression must be an instance of RegExp (i.e. not a string.) It is - * matched against the **entire** *normalized / absolute URL* of the resource being tested - * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags - * present on the RegExp (such as multiline, global, ignoreCase) are ignored. - * - If you are generating your JavaScript from some other templating engine (not - * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), - * remember to escape your regular expression (and be aware that you might need more than - * one level of escaping depending on your templating engine and the way you interpolated - * the value.) Do make use of your platform's escaping mechanism as it might be good - * enough before coding your own. e.g. Ruby has - * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) - * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). - * Javascript lacks a similar built in function for escaping. Take a look at Google - * Closure library's [goog.string.regExpEscape(s)]( - * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). + * @description * - * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. + * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy. + * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on + * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information. * - * ## Show me an example using SCE. + * A special directive is necessary because we cannot use interpolation inside the `readonly` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. * * @example - + -
    -

    - User comments
    - By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when - $sanitize is available. If $sanitize isn't available, this results in an error instead of an - exploit. -
    -
    - {{userComment.name}}: - -
    -
    -
    -
    +
    +
    - - - var mySceApp = angular.module('mySceApp', ['ngSanitize']); - - mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) { - var self = this; - $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { - self.userComments = userComments; - }); - self.explicitlyTrustedHtml = $sce.trustAsHtml( - 'Hover over this text.'); - }); + + it('should toggle readonly attr', function() { + expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); + element(by.model('checked')).click(); + expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); + }); +
    + * + * @element INPUT + * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, + * then special attribute "readonly" will be set on the element + */ - - [ - { "name": "Alice", - "htmlComment": - "Is anyone reading this?" - }, - { "name": "Bob", - "htmlComment": "Yes! Am I the only other one?" - } - ] - + /** + * @ngdoc directive + * @name ngSelected + * @restrict A + * @priority 100 + * + * @description + * + * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy. + * + * A special directive is necessary because we cannot use interpolation inside the `selected` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. + * + *
    + * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only + * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you + * should not use `ngSelected` on the options, as `ngModel` will set the select value and + * selected options. + *
    + * + * @example + + +
    + +
    - describe('SCE doc demo', function() { - it('should sanitize untrusted values', function() { - expect(element(by.css('.htmlComment')).getInnerHtml()) - .toBe('Is anyone reading this?'); - }); - - it('should NOT sanitize explicitly trusted values', function() { - expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe( - 'Hover over this text.'); - }); - }); + it('should select Greetings!', function() { + expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); + element(by.model('selected')).click(); + expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); + });
    * + * @element OPTION + * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, + * then special attribute "selected" will be set on the element + */ + + /** + * @ngdoc directive + * @name ngOpen + * @restrict A + * @priority 100 + * + * @description * + * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy. * - * ## Can I disable SCE completely? + * A special directive is necessary because we cannot use interpolation inside the `open` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. * - * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits - * for little coding overhead. It will be much harder to take an SCE disabled application and - * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE - * for cases where you have a lot of existing code that was written before SCE was introduced and - * you're migrating them a module at a time. + * ## A note about browser compatibility * - * That said, here's how you can completely disable SCE: + * Internet Explorer and Edge do not support the `details` element, it is + * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead. * - *
    -     *   angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
    - *     // Completely disable SCE.  For demonstration purposes only!
    - *     // Do not use in new projects.
    - *     $sceProvider.enabled(false);
    - *   });
    -     * 
    + * @example + + +
    +
    + List +
      +
    • Apple
    • +
    • Orange
    • +
    • Durian
    • +
    +
    +
    + + it('should toggle open', function() { + expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); + element(by.model('open')).click(); + expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); + }); + +
    * + * @element DETAILS + * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, + * then special attribute "open" will be set on the element */ - /* jshint maxlen: 100 */ - - function $SceProvider() { - var enabled = true; - - /** - * @ngdoc method - * @name $sceProvider#enabled - * @function - * - * @param {boolean=} value If provided, then enables/disables SCE. - * @return {boolean} true if SCE is enabled, false otherwise. - * - * @description - * Enables/disables SCE and returns the current value. - */ - this.enabled = function (value) { - if (arguments.length) { - enabled = !!value; - } - return enabled; - }; - - - /* Design notes on the default implementation for SCE. - * - * The API contract for the SCE delegate - * ------------------------------------- - * The SCE delegate object must provide the following 3 methods: - * - * - trustAs(contextEnum, value) - * This method is used to tell the SCE service that the provided value is OK to use in the - * contexts specified by contextEnum. It must return an object that will be accepted by - * getTrusted() for a compatible contextEnum and return this value. - * - * - valueOf(value) - * For values that were not produced by trustAs(), return them as is. For values that were - * produced by trustAs(), return the corresponding input value to trustAs. Basically, if - * trustAs is wrapping the given values into some type, this operation unwraps it when given - * such a value. - * - * - getTrusted(contextEnum, value) - * This function should return the a value that is safe to use in the context specified by - * contextEnum or throw and exception otherwise. - * - * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be - * opaque or wrapped in some holder object. That happens to be an implementation detail. For - * instance, an implementation could maintain a registry of all trusted objects by context. In - * such a case, trustAs() would return the same object that was passed in. getTrusted() would - * return the same object passed in if it was found in the registry under a compatible context or - * throw an exception otherwise. An implementation might only wrap values some of the time based - * on some criteria. getTrusted() might return a value and not throw an exception for special - * constants or objects even if not wrapped. All such implementations fulfill this contract. - * - * - * A note on the inheritance model for SCE contexts - * ------------------------------------------------ - * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This - * is purely an implementation details. - * - * The contract is simply this: - * - * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) - * will also succeed. - * - * Inheritance happens to capture this in a natural way. In some future, we - * may not use inheritance anymore. That is OK because no code outside of - * sce.js and sceSpecs.js would need to be aware of this detail. - */ - this.$get = ['$parse', '$sniffer', '$sceDelegate', function( - $parse, $sniffer, $sceDelegate) { - // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows - // the "expression(javascript expression)" syntax which is insecure. - if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) { - throw $sceMinErr('iequirks', - 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' + - 'mode. You can fix this by adding the text to the top of your HTML ' + - 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); - } + var ngAttributeAliasDirectives = {}; - var sce = copy(SCE_CONTEXTS); +// boolean attrs are evaluated + forEach(BOOLEAN_ATTR, function(propName, attrName) { + // binding to multiple is not supported + if (propName === 'multiple') return; - /** - * @ngdoc method - * @name $sce#isEnabled - * @function - * - * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you - * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. - * - * @description - * Returns a boolean indicating if SCE is enabled. - */ - sce.isEnabled = function () { - return enabled; - }; - sce.trustAs = $sceDelegate.trustAs; - sce.getTrusted = $sceDelegate.getTrusted; - sce.valueOf = $sceDelegate.valueOf; + function defaultLinkFn(scope, element, attr) { + scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { + attr.$set(attrName, !!value); + }); + } - if (!enabled) { - sce.trustAs = sce.getTrusted = function(type, value) { return value; }; - sce.valueOf = identity; - } + var normalized = directiveNormalize('ng-' + attrName); + var linkFn = defaultLinkFn; - /** - * @ngdoc method - * @name $sce#parse - * - * @description - * Converts Angular {@link guide/expression expression} into a function. This is like {@link - * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it - * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, - * *result*)} - * - * @param {string} type The kind of SCE context in which this result will be used. - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - sce.parseAs = function sceParseAs(type, expr) { - var parsed = $parse(expr); - if (parsed.literal && parsed.constant) { - return parsed; - } else { - return function sceParseAsTrusted(self, locals) { - return sce.getTrusted(type, parsed(self, locals)); - }; + if (propName === 'checked') { + linkFn = function(scope, element, attr) { + // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input + if (attr.ngModel !== attr[normalized]) { + defaultLinkFn(scope, element, attr); } }; + } - /** - * @ngdoc method - * @name $sce#trustAs - * - * @description - * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, - * returns an object that is trusted by angular for use in specified strict contextual - * escaping contexts (such as ng-bind-html, ng-include, any src attribute - * interpolation, any dom event binding attribute interpolation such as for onclick, etc.) - * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual - * escaping. - * - * @param {string} type The kind of context in which this value is safe for use. e.g. url, - * resource_url, html, js and css. - * @param {*} value The value that that should be considered trusted/safe. - * @returns {*} A value that can be used to stand in for the provided `value` in places - * where Angular expects a $sce.trustAs() return value. - */ - - /** - * @ngdoc method - * @name $sce#trustAsHtml - * - * @description - * Shorthand method. `$sce.trustAsHtml(value)` → - * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} - * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml - * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name $sce#trustAsUrl - * - * @description - * Shorthand method. `$sce.trustAsUrl(value)` → - * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} - * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl - * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name $sce#trustAsResourceUrl - * - * @description - * Shorthand method. `$sce.trustAsResourceUrl(value)` → - * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} - * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl - * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the return - * value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name $sce#trustAsJs - * - * @description - * Shorthand method. `$sce.trustAsJs(value)` → - * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} - * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs - * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name $sce#getTrusted - * - * @description - * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, - * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the - * originally supplied value if the queried context type is a supertype of the created type. - * If this condition isn't satisfied, throws an exception. - * - * @param {string} type The kind of context in which this value is to be used. - * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} - * call. - * @returns {*} The value the was originally provided to - * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context. - * Otherwise, throws an exception. - */ - - /** - * @ngdoc method - * @name $sce#getTrustedHtml - * - * @description - * Shorthand method. `$sce.getTrustedHtml(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} - * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` - */ - - /** - * @ngdoc method - * @name $sce#getTrustedCss - * - * @description - * Shorthand method. `$sce.getTrustedCss(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} - * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` - */ - - /** - * @ngdoc method - * @name $sce#getTrustedUrl - * - * @description - * Shorthand method. `$sce.getTrustedUrl(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} - * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` - */ - - /** - * @ngdoc method - * @name $sce#getTrustedResourceUrl - * - * @description - * Shorthand method. `$sce.getTrustedResourceUrl(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} - * - * @param {*} value The value to pass to `$sceDelegate.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` - */ - - /** - * @ngdoc method - * @name $sce#getTrustedJs - * - * @description - * Shorthand method. `$sce.getTrustedJs(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} - * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` - */ + ngAttributeAliasDirectives[normalized] = function() { + return { + restrict: 'A', + priority: 100, + link: linkFn + }; + }; + }); - /** - * @ngdoc method - * @name $sce#parseAsHtml - * - * @description - * Shorthand method. `$sce.parseAsHtml(expression string)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ +// aliased input attrs are evaluated + forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { + ngAttributeAliasDirectives[ngAttr] = function() { + return { + priority: 100, + link: function(scope, element, attr) { + //special case ngPattern when a literal regular expression value + //is used as the expression (this way we don't have to watch anything). + if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') { + var match = attr.ngPattern.match(REGEX_STRING_REGEXP); + if (match) { + attr.$set('ngPattern', new RegExp(match[1], match[2])); + return; + } + } - /** - * @ngdoc method - * @name $sce#parseAsCss - * - * @description - * Shorthand method. `$sce.parseAsCss(value)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ + scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { + attr.$set(ngAttr, value); + }); + } + }; + }; + }); - /** - * @ngdoc method - * @name $sce#parseAsUrl - * - * @description - * Shorthand method. `$sce.parseAsUrl(value)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ +// ng-src, ng-srcset, ng-href are interpolated + forEach(['src', 'srcset', 'href'], function(attrName) { + var normalized = directiveNormalize('ng-' + attrName); + ngAttributeAliasDirectives[normalized] = function() { + return { + priority: 99, // it needs to run after the attributes are interpolated + link: function(scope, element, attr) { + var propName = attrName, + name = attrName; - /** - * @ngdoc method - * @name $sce#parseAsResourceUrl - * - * @description - * Shorthand method. `$sce.parseAsResourceUrl(value)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ + if (attrName === 'href' && + toString.call(element.prop('href')) === '[object SVGAnimatedString]') { + name = 'xlinkHref'; + attr.$attr[name] = 'xlink:href'; + propName = null; + } - /** - * @ngdoc method - * @name $sce#parseAsJs - * - * @description - * Shorthand method. `$sce.parseAsJs(value)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`} - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ + attr.$observe(normalized, function(value) { + if (!value) { + if (attrName === 'href') { + attr.$set(name, null); + } + return; + } - // Shorthand delegations. - var parse = sce.parseAs, - getTrusted = sce.getTrusted, - trustAs = sce.trustAs; + attr.$set(name, value); - forEach(SCE_CONTEXTS, function (enumValue, name) { - var lName = lowercase(name); - sce[camelCase("parse_as_" + lName)] = function (expr) { - return parse(enumValue, expr); - }; - sce[camelCase("get_trusted_" + lName)] = function (value) { - return getTrusted(enumValue, value); - }; - sce[camelCase("trust_as_" + lName)] = function (value) { - return trustAs(enumValue, value); - }; - }); + // Support: IE 9-11 only + // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist + // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need + // to set the property as well to achieve the desired effect. + // We use attr[attrName] value since $set can sanitize the url. + if (msie && propName) element.prop(propName, attr[name]); + }); + } + }; + }; + }); - return sce; - }]; + /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS + */ + var nullFormCtrl = { + $addControl: noop, + $$renameControl: nullFormRenameControl, + $removeControl: noop, + $setValidity: noop, + $setDirty: noop, + $setPristine: noop, + $setSubmitted: noop + }, + PENDING_CLASS = 'ng-pending', + SUBMITTED_CLASS = 'ng-submitted'; + + function nullFormRenameControl(control, name) { + control.$name = name; } /** - * !!! This is an undocumented "private" service !!! + * @ngdoc type + * @name form.FormController * - * @name $sniffer - * @requires $window - * @requires $document + * @property {boolean} $pristine True if user has not interacted with the form yet. + * @property {boolean} $dirty True if user has already interacted with the form. + * @property {boolean} $valid True if all of the containing forms and controls are valid. + * @property {boolean} $invalid True if at least one containing control or form is invalid. + * @property {boolean} $submitted True if user has submitted the form even if its invalid. * - * @property {boolean} history Does the browser support html5 history api ? - * @property {boolean} hashchange Does the browser support hashchange event ? - * @property {boolean} transitions Does the browser support CSS transition events ? - * @property {boolean} animations Does the browser support CSS animation events ? + * @property {Object} $pending An object hash, containing references to controls or forms with + * pending validators, where: + * + * - keys are validations tokens (error names). + * - values are arrays of controls or forms that have a pending validator for the given error name. + * + * See {@link form.FormController#$error $error} for a list of built-in validation tokens. + * + * @property {Object} $error An object hash, containing references to controls or forms with failing + * validators, where: + * + * - keys are validation tokens (error names), + * - values are arrays of controls or forms that have a failing validator for the given error name. + * + * Built-in validation tokens: + * - `email` + * - `max` + * - `maxlength` + * - `min` + * - `minlength` + * - `number` + * - `pattern` + * - `required` + * - `url` + * - `date` + * - `datetimelocal` + * - `time` + * - `week` + * - `month` * * @description - * This is very simple implementation of testing browser's features. + * `FormController` keeps track of all its controls and nested forms as well as the state of them, + * such as being valid/invalid or dirty/pristine. + * + * Each {@link ng.directive:form form} directive creates an instance + * of `FormController`. + * */ - function $SnifferProvider() { - this.$get = ['$window', '$document', function($window, $document) { - var eventSupport = {}, - android = - int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), - boxee = /Boxee/i.test(($window.navigator || {}).userAgent), - document = $document[0] || {}, - documentMode = document.documentMode, - vendorPrefix, - vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, - bodyStyle = document.body && document.body.style, - transitions = false, - animations = false, - match; - - if (bodyStyle) { - for(var prop in bodyStyle) { - if(match = vendorRegex.exec(prop)) { - vendorPrefix = match[0]; - vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); - break; - } - } - - if(!vendorPrefix) { - vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; - } +//asks for $scope to fool the BC controller module + FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; + function FormController($element, $attrs, $scope, $animate, $interpolate) { + this.$$controls = []; - transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); - animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); + // init state + this.$error = {}; + this.$$success = {}; + this.$pending = undefined; + this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope); + this.$dirty = false; + this.$pristine = true; + this.$valid = true; + this.$invalid = false; + this.$submitted = false; + this.$$parentForm = nullFormCtrl; + + this.$$element = $element; + this.$$animate = $animate; + + setupValidity(this); + } - if (android && (!transitions||!animations)) { - transitions = isString(document.body.style.webkitTransition); - animations = isString(document.body.style.webkitAnimation); - } - } + FormController.prototype = { + /** + * @ngdoc method + * @name form.FormController#$rollbackViewValue + * + * @description + * Rollback all form controls pending updates to the `$modelValue`. + * + * Updates may be pending by a debounced event or because the input is waiting for a some future + * event defined in `ng-model-options`. This method is typically needed by the reset button of + * a form that uses `ng-model-options` to pend updates. + */ + $rollbackViewValue: function() { + forEach(this.$$controls, function(control) { + control.$rollbackViewValue(); + }); + }, + /** + * @ngdoc method + * @name form.FormController#$commitViewValue + * + * @description + * Commit all form controls pending updates to the `$modelValue`. + * + * Updates may be pending by a debounced event or because the input is waiting for a some future + * event defined in `ng-model-options`. This method is rarely needed as `NgModelController` + * usually handles calling this in response to input events. + */ + $commitViewValue: function() { + forEach(this.$$controls, function(control) { + control.$commitViewValue(); + }); + }, - return { - // Android has history.pushState, but it does not update location correctly - // so let's not use the history API at all. - // http://code.google.com/p/android/issues/detail?id=17471 - // https://github.com/angular/angular.js/issues/904 + /** + * @ngdoc method + * @name form.FormController#$addControl + * @param {object} control control object, either a {@link form.FormController} or an + * {@link ngModel.NgModelController} + * + * @description + * Register a control with the form. Input elements using ngModelController do this automatically + * when they are linked. + * + * Note that the current state of the control will not be reflected on the new parent form. This + * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine` + * state. + * + * However, if the method is used programmatically, for example by adding dynamically created controls, + * or controls that have been previously removed without destroying their corresponding DOM element, + * it's the developers responsibility to make sure the current state propagates to the parent form. + * + * For example, if an input control is added that is already `$dirty` and has `$error` properties, + * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form. + */ + $addControl: function(control) { + // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored + // and not added to the scope. Now we throw an error. + assertNotHasOwnProperty(control.$name, 'input'); + this.$$controls.push(control); - // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has - // so let's not use the history API also - // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined - // jshint -W018 - history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), - // jshint +W018 - hashchange: 'onhashchange' in $window && - // IE8 compatible mode lies - (!documentMode || documentMode > 7), - hasEvent: function(event) { - // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have - // it. In particular the event is not fired when backspace or delete key are pressed or - // when cut operation is performed. - if (event == 'input' && msie == 9) return false; + if (control.$name) { + this[control.$name] = control; + } - if (isUndefined(eventSupport[event])) { - var divElm = document.createElement('div'); - eventSupport[event] = 'on' + event in divElm; - } + control.$$parentForm = this; + }, - return eventSupport[event]; - }, - csp: csp(), - vendorPrefix: vendorPrefix, - transitions : transitions, - animations : animations, - android: android, - msie : msie, - msieDocumentMode: documentMode - }; - }]; - } + // Private API: rename a form control + $$renameControl: function(control, newName) { + var oldName = control.$name; - function $TimeoutProvider() { - this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', - function($rootScope, $browser, $q, $exceptionHandler) { - var deferreds = {}; + if (this[oldName] === control) { + delete this[oldName]; + } + this[newName] = control; + control.$name = newName; + }, + /** + * @ngdoc method + * @name form.FormController#$removeControl + * @param {object} control control object, either a {@link form.FormController} or an + * {@link ngModel.NgModelController} + * + * @description + * Deregister a control from the form. + * + * Input elements using ngModelController do this automatically when they are destroyed. + * + * Note that only the removed control's validation state (`$errors`etc.) will be removed from the + * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be + * different from case to case. For example, removing the only `$dirty` control from a form may or + * may not mean that the form is still `$dirty`. + */ + $removeControl: function(control) { + if (control.$name && this[control.$name] === control) { + delete this[control.$name]; + } + forEach(this.$pending, function(value, name) { + // eslint-disable-next-line no-invalid-this + this.$setValidity(name, null, control); + }, this); + forEach(this.$error, function(value, name) { + // eslint-disable-next-line no-invalid-this + this.$setValidity(name, null, control); + }, this); + forEach(this.$$success, function(value, name) { + // eslint-disable-next-line no-invalid-this + this.$setValidity(name, null, control); + }, this); + + arrayRemove(this.$$controls, control); + control.$$parentForm = nullFormCtrl; + }, - /** - * @ngdoc service - * @name $timeout - * - * @description - * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch - * block and delegates any exceptions to - * {@link ng.$exceptionHandler $exceptionHandler} service. - * - * The return value of registering a timeout function is a promise, which will be resolved when - * the timeout is reached and the timeout function is executed. - * - * To cancel a timeout request, call `$timeout.cancel(promise)`. - * - * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to - * synchronously flush the queue of deferred functions. - * - * @param {function()} fn A function, whose execution should be delayed. - * @param {number=} [delay=0] Delay in milliseconds. - * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise - * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. - * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this - * promise will be resolved with is the return value of the `fn` function. - * - */ - function timeout(fn, delay, invokeApply) { - var deferred = $q.defer(), - promise = deferred.promise, - skipApply = (isDefined(invokeApply) && !invokeApply), - timeoutId; + /** + * @ngdoc method + * @name form.FormController#$setDirty + * + * @description + * Sets the form to a dirty state. + * + * This method can be called to add the 'ng-dirty' class and set the form to a dirty + * state (ng-dirty class). This method will also propagate to parent forms. + */ + $setDirty: function() { + this.$$animate.removeClass(this.$$element, PRISTINE_CLASS); + this.$$animate.addClass(this.$$element, DIRTY_CLASS); + this.$dirty = true; + this.$pristine = false; + this.$$parentForm.$setDirty(); + }, - timeoutId = $browser.defer(function() { - try { - deferred.resolve(fn()); - } catch(e) { - deferred.reject(e); - $exceptionHandler(e); - } - finally { - delete deferreds[promise.$$timeoutId]; - } + /** + * @ngdoc method + * @name form.FormController#$setPristine + * + * @description + * Sets the form to its pristine state. + * + * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes + * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted` + * state to false. + * + * This method will also propagate to all the controls contained in this form. + * + * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after + * saving or resetting it. + */ + $setPristine: function() { + this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); + this.$dirty = false; + this.$pristine = true; + this.$submitted = false; + forEach(this.$$controls, function(control) { + control.$setPristine(); + }); + }, - if (!skipApply) $rootScope.$apply(); - }, delay); + /** + * @ngdoc method + * @name form.FormController#$setUntouched + * + * @description + * Sets the form to its untouched state. + * + * This method can be called to remove the 'ng-touched' class and set the form controls to their + * untouched state (ng-untouched class). + * + * Setting a form controls back to their untouched state is often useful when setting the form + * back to its pristine state. + */ + $setUntouched: function() { + forEach(this.$$controls, function(control) { + control.$setUntouched(); + }); + }, - promise.$$timeoutId = timeoutId; - deferreds[timeoutId] = deferred; + /** + * @ngdoc method + * @name form.FormController#$setSubmitted + * + * @description + * Sets the form to its submitted state. + */ + $setSubmitted: function() { + this.$$animate.addClass(this.$$element, SUBMITTED_CLASS); + this.$submitted = true; + this.$$parentForm.$setSubmitted(); + } + }; - return promise; + /** + * @ngdoc method + * @name form.FormController#$setValidity + * + * @description + * Change the validity state of the form, and notify the parent form (if any). + * + * Application developers will rarely need to call this method directly. It is used internally, by + * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a + * control's validity state to the parent `FormController`. + * + * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be + * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for + * unfulfilled `$asyncValidators`), so that it is available for data-binding. The + * `validationErrorKey` should be in camelCase and will get converted into dash-case for + * class name. Example: `myError` will result in `ng-valid-my-error` and + * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`. + * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending + * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`. + * Skipped is used by AngularJS when validators do not run because of parse errors and when + * `$asyncValidators` do not run because any of the `$validators` failed. + * @param {NgModelController | FormController} controller - The controller whose validity state is + * triggering the change. + */ + addSetValidityMethod({ + clazz: FormController, + set: function(object, property, controller) { + var list = object[property]; + if (!list) { + object[property] = [controller]; + } else { + var index = list.indexOf(controller); + if (index === -1) { + list.push(controller); } + } + }, + unset: function(object, property, controller) { + var list = object[property]; + if (!list) { + return; + } + arrayRemove(list, controller); + if (list.length === 0) { + delete object[property]; + } + } + }); - - /** - * @ngdoc method - * @name $timeout#cancel - * - * @description - * Cancels a task associated with the `promise`. As a result of this, the promise will be - * resolved with a rejection. - * - * @param {Promise=} promise Promise returned by the `$timeout` function. - * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully - * canceled. - */ - timeout.cancel = function(promise) { - if (promise && promise.$$timeoutId in deferreds) { - deferreds[promise.$$timeoutId].reject('canceled'); - delete deferreds[promise.$$timeoutId]; - return $browser.defer.cancel(promise.$$timeoutId); - } - return false; - }; - - return timeout; - }]; - } - -// NOTE: The usage of window and document instead of $window and $document here is -// deliberate. This service depends on the specific behavior of anchor nodes created by the -// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and -// cause us to break tests. In addition, when the browser resolves a URL for XHR, it -// doesn't know about mocked locations and resolves URLs to the real document - which is -// exactly the behavior needed here. There is little value is mocking these out for this -// service. - var urlParsingNode = document.createElement("a"); - var originUrl = urlResolve(window.location.href, true); - + /** + * @ngdoc directive + * @name ngForm + * @restrict EAC + * + * @description + * Nestable alias of {@link ng.directive:form `form`} directive. HTML + * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a + * sub-group of controls needs to be determined. + * + * Note: the purpose of `ngForm` is to group controls, + * but not to be a replacement for the `
    ` tag with all of its capabilities + * (e.g. posting to the server, ...). + * + * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into + * related scope, under this name. + * + */ /** + * @ngdoc directive + * @name form + * @restrict E * - * Implementation Notes for non-IE browsers - * ---------------------------------------- - * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, - * results both in the normalizing and parsing of the URL. Normalizing means that a relative - * URL will be resolved into an absolute URL in the context of the application document. - * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related - * properties are all populated to reflect the normalized URL. This approach has wide - * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See - * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * @description + * Directive that instantiates + * {@link form.FormController FormController}. * - * Implementation Notes for IE - * --------------------------- - * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other - * browsers. However, the parsed components will not be set if the URL assigned did not specify - * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We - * work around that by performing the parsing in a 2nd step by taking a previously normalized - * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the - * properties such as protocol, hostname, port, etc. + * If the `name` attribute is specified, the form controller is published onto the current scope under + * this name. * - * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one - * uses the inner HTML approach to assign the URL as part of an HTML snippet - - * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. - * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. - * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that - * method and IE < 8 is unsupported. + * ## Alias: {@link ng.directive:ngForm `ngForm`} * - * References: - * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement - * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html - * http://url.spec.whatwg.org/#urlutils - * https://github.com/angular/angular.js/pull/2902 - * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ + * In AngularJS, forms can be nested. This means that the outer form is valid when all of the child + * forms are valid as well. However, browsers do not allow nesting of `` elements, so + * AngularJS provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to + * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group + * of controls needs to be determined. * - * @function - * @param {string} url The URL to be parsed. - * @description Normalizes and parses a URL. - * @returns {object} Returns the normalized URL as a dictionary. + * ## CSS classes + * - `ng-valid` is set if the form is valid. + * - `ng-invalid` is set if the form is invalid. + * - `ng-pending` is set if the form is pending. + * - `ng-pristine` is set if the form is pristine. + * - `ng-dirty` is set if the form is dirty. + * - `ng-submitted` is set if the form was submitted. * - * | member name | Description | - * |---------------|----------------| - * | href | A normalized version of the provided URL if it was not an absolute URL | - * | protocol | The protocol including the trailing colon | - * | host | The host and port (if the port is non-default) of the normalizedUrl | - * | search | The search params, minus the question mark | - * | hash | The hash string, minus the hash symbol - * | hostname | The hostname - * | port | The port, without ":" - * | pathname | The pathname, beginning with "/" + * Keep in mind that ngAnimate can detect each of these classes when added and removed. + * + * + * ## Submitting a form and preventing the default action + * + * Since the role of forms in client-side AngularJS applications is different than in classical + * roundtrip apps, it is desirable for the browser not to translate the form submission into a full + * page reload that sends the data to the server. Instead some javascript logic should be triggered + * to handle the form submission in an application-specific way. + * + * For this reason, AngularJS prevents the default action (form submission to the server) unless the + * `` element has an `action` attribute specified. + * + * You can use one of the following two ways to specify what javascript method should be called when + * a form is submitted: + * + * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element + * - {@link ng.directive:ngClick ngClick} directive on the first + * button or input field of type submit (input[type=submit]) + * + * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} + * or {@link ng.directive:ngClick ngClick} directives. + * This is because of the following form submission rules in the HTML specification: + * + * - If a form has only one input field then hitting enter in this field triggers form submit + * (`ngSubmit`) + * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter + * doesn't trigger submit + * - if a form has one or more input fields and one or more buttons or input[type=submit] then + * hitting enter in any of the input fields will trigger the click handler on the *first* button or + * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) + * + * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is + * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` + * to have access to the updated model. + * + * @animations + * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. + * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any + * other validations that are performed within the form. Animations in ngForm are similar to how + * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well + * as JS animations. + * + * The following example shows a simple way to utilize CSS transitions to style a form element + * that has been rendered as invalid after it has been validated: + * + *
    +     * //be sure to include ngAnimate as a module to hook into more
    +     * //advanced animations
    +     * .my-form {
    +     *   transition:0.5s linear all;
    +     *   background: white;
    +     * }
    +     * .my-form.ng-invalid {
    +     *   background: red;
    +     *   color:white;
    +     * }
    +     * 
    + * + * @example + + + + + + userType: + Required!
    + userType = {{userType}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    + +
    + + it('should initialize to model', function() { + var userType = element(by.binding('userType')); + var valid = element(by.binding('myForm.input.$valid')); + + expect(userType.getText()).toContain('guest'); + expect(valid.getText()).toContain('true'); + }); + + it('should be invalid if empty', function() { + var userType = element(by.binding('userType')); + var valid = element(by.binding('myForm.input.$valid')); + var userInput = element(by.model('userType')); + + userInput.clear(); + userInput.sendKeys(''); + + expect(userType.getText()).toEqual('userType ='); + expect(valid.getText()).toContain('false'); + }); + +
    * + * @param {string=} name Name of the form. If specified, the form controller will be published into + * related scope, under this name. */ - function urlResolve(url, base) { - var href = url; + var formDirectiveFactory = function(isNgForm) { + return ['$timeout', '$parse', function($timeout, $parse) { + var formDirective = { + name: 'form', + restrict: isNgForm ? 'EAC' : 'E', + require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form + controller: FormController, + compile: function ngFormCompile(formElement, attr) { + // Setup initial state of the control + formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); + + var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false); + + return { + pre: function ngFormPreLink(scope, formElement, attr, ctrls) { + var controller = ctrls[0]; + + // if `action` attr is not present on the form, prevent the default action (submission) + if (!('action' in attr)) { + // we can't use jq events because if a form is destroyed during submission the default + // action is not prevented. see #1238 + // + // IE 9 is not affected because it doesn't fire a submit event and try to do a full + // page reload if the form was destroyed by submission of the form via a click handler + // on a button in the form. Looks like an IE9 specific bug. + var handleFormSubmission = function(event) { + scope.$apply(function() { + controller.$commitViewValue(); + controller.$setSubmitted(); + }); + + event.preventDefault(); + }; + + formElement[0].addEventListener('submit', handleFormSubmission); + + // unregister the preventDefault listener so that we don't not leak memory but in a + // way that will achieve the prevention of the default action. + formElement.on('$destroy', function() { + $timeout(function() { + formElement[0].removeEventListener('submit', handleFormSubmission); + }, 0, false); + }); + } - if (msie) { - // Normalize before parse. Refer Implementation Notes on why this is - // done in two steps on IE. - urlParsingNode.setAttribute("href", href); - href = urlParsingNode.href; - } + var parentFormCtrl = ctrls[1] || controller.$$parentForm; + parentFormCtrl.$addControl(controller); - urlParsingNode.setAttribute('href', href); + var setter = nameAttr ? getSetter(controller.$name) : noop; - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') - ? urlParsingNode.pathname - : '/' + urlParsingNode.pathname - }; - } + if (nameAttr) { + setter(scope, controller); + attr.$observe(nameAttr, function(newValue) { + if (controller.$name === newValue) return; + setter(scope, undefined); + controller.$$parentForm.$$renameControl(controller, newValue); + setter = getSetter(controller.$name); + setter(scope, controller); + }); + } + formElement.on('$destroy', function() { + controller.$$parentForm.$removeControl(controller); + setter(scope, undefined); + extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards + }); + } + }; + } + }; - /** - * Parse a request URL and determine whether this is a same-origin request as the application document. - * - * @param {string|object} requestUrl The url of the request as a string that will be resolved - * or a parsed URL object. - * @returns {boolean} Whether the request is for the same origin as the application document. - */ - function urlIsSameOrigin(requestUrl) { - var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; - return (parsed.protocol === originUrl.protocol && - parsed.host === originUrl.host); + return formDirective; + + function getSetter(expression) { + if (expression === '') { + //create an assignable expression, so forms with an empty name can be renamed later + return $parse('this[""]').assign; + } + return $parse(expression).assign || noop; + } + }]; + }; + + var formDirective = formDirectiveFactory(); + var ngFormDirective = formDirectiveFactory(true); + + + +// helper methods + function setupValidity(instance) { + instance.$$classCache = {}; + instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS)); } + function addSetValidityMethod(context) { + var clazz = context.clazz, + set = context.set, + unset = context.unset; + + clazz.prototype.$setValidity = function(validationErrorKey, state, controller) { + if (isUndefined(state)) { + createAndSet(this, '$pending', validationErrorKey, controller); + } else { + unsetAndCleanup(this, '$pending', validationErrorKey, controller); + } + if (!isBoolean(state)) { + unset(this.$error, validationErrorKey, controller); + unset(this.$$success, validationErrorKey, controller); + } else { + if (state) { + unset(this.$error, validationErrorKey, controller); + set(this.$$success, validationErrorKey, controller); + } else { + set(this.$error, validationErrorKey, controller); + unset(this.$$success, validationErrorKey, controller); + } + } + if (this.$pending) { + cachedToggleClass(this, PENDING_CLASS, true); + this.$valid = this.$invalid = undefined; + toggleValidationCss(this, '', null); + } else { + cachedToggleClass(this, PENDING_CLASS, false); + this.$valid = isObjectEmpty(this.$error); + this.$invalid = !this.$valid; + toggleValidationCss(this, '', this.$valid); + } - /** - * @ngdoc service - * @name $window - * - * @description - * A reference to the browser's `window` object. While `window` - * is globally available in JavaScript, it causes testability problems, because - * it is a global variable. In angular we always refer to it through the - * `$window` service, so it may be overridden, removed or mocked for testing. - * - * Expressions, like the one defined for the `ngClick` directive in the example - * below, are evaluated with respect to the current scope. Therefore, there is - * no risk of inadvertently coding in a dependency on a global value in such an - * expression. - * - * @example - - - -
    - - -
    -
    - - it('should display the greeting in the input box', function() { - element(by.model('greeting')).sendKeys('Hello, E2E Tests'); - // If we click the button it will block the test runner - // element(':button').click(); - }); - -
    - */ - function $WindowProvider(){ - this.$get = valueFn(window); + // re-read the state as the set/unset methods could have + // combined state in this.$error[validationError] (used for forms), + // where setting/unsetting only increments/decrements the value, + // and does not replace it. + var combinedState; + if (this.$pending && this.$pending[validationErrorKey]) { + combinedState = undefined; + } else if (this.$error[validationErrorKey]) { + combinedState = false; + } else if (this.$$success[validationErrorKey]) { + combinedState = true; + } else { + combinedState = null; + } + + toggleValidationCss(this, validationErrorKey, combinedState); + this.$$parentForm.$setValidity(validationErrorKey, combinedState, this); + }; + + function createAndSet(ctrl, name, value, controller) { + if (!ctrl[name]) { + ctrl[name] = {}; + } + set(ctrl[name], value, controller); + } + + function unsetAndCleanup(ctrl, name, value, controller) { + if (ctrl[name]) { + unset(ctrl[name], value, controller); + } + if (isObjectEmpty(ctrl[name])) { + ctrl[name] = undefined; + } + } + + function cachedToggleClass(ctrl, className, switchValue) { + if (switchValue && !ctrl.$$classCache[className]) { + ctrl.$$animate.addClass(ctrl.$$element, className); + ctrl.$$classCache[className] = true; + } else if (!switchValue && ctrl.$$classCache[className]) { + ctrl.$$animate.removeClass(ctrl.$$element, className); + ctrl.$$classCache[className] = false; + } + } + + function toggleValidationCss(ctrl, validationErrorKey, isValid) { + validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; + + cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true); + cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false); + } } - /** - * @ngdoc provider - * @name $filterProvider - * @description - * - * Filters are just functions which transform input to an output. However filters need to be - * Dependency Injected. To achieve this a filter definition consists of a factory function which is - * annotated with dependencies and is responsible for creating a filter function. - * - * ```js - * // Filter registration - * function MyModule($provide, $filterProvider) { - * // create a service to demonstrate injection (not always needed) - * $provide.value('greet', function(name){ - * return 'Hello ' + name + '!'; - * }); - * - * // register a filter factory which uses the - * // greet service to demonstrate DI. - * $filterProvider.register('greet', function(greet){ - * // return the filter function which uses the greet service - * // to generate salutation - * return function(text) { - * // filters need to be forgiving so check input validity - * return text && greet(text) || text; - * }; - * }); - * } - * ``` - * - * The filter function is registered with the `$injector` under the filter name suffix with - * `Filter`. - * - * ```js - * it('should be the same instance', inject( - * function($filterProvider) { - * $filterProvider.register('reverse', function(){ - * return ...; - * }); - * }, - * function($filter, reverseFilter) { - * expect($filter('reverse')).toBe(reverseFilter); - * }); - * ``` - * - * - * For more information about how angular filters work, and how to create your own filters, see - * {@link guide/filter Filters} in the Angular Developer Guide. - */ - /** - * @ngdoc method - * @name $filterProvider#register - * @description - * Register filter factory function. - * - * @param {String} name Name of the filter. - * @param {Function} fn The filter factory function which is injectable. - */ + function isObjectEmpty(obj) { + if (obj) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + return false; + } + } + } + return true; + } + /* global + VALID_CLASS: false, + INVALID_CLASS: false, + PRISTINE_CLASS: false, + DIRTY_CLASS: false, + ngModelMinErr: false +*/ + +// Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231 + var ISO_DATE_REGEXP = /^\d{4,}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)$/; +// See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987) +// Note: We are being more lenient, because browsers are too. +// 1. Scheme +// 2. Slashes +// 3. Username +// 4. Password +// 5. Hostname +// 6. Port +// 7. Path +// 8. Query +// 9. Fragment +// 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999 + var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i; +// eslint-disable-next-line max-len + var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/; + var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/; + var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/; + var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; + var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/; + var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/; + var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; + + var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown'; + var PARTIAL_VALIDATION_TYPES = createMap(); + forEach('date,datetime-local,month,time,week'.split(','), function(type) { + PARTIAL_VALIDATION_TYPES[type] = true; + }); - /** - * @ngdoc service - * @name $filter - * @function - * @description - * Filters are used for formatting data displayed to the user. - * - * The general syntax in templates is as follows: - * - * {{ expression [| filter_name[:parameter_value] ... ] }} - * - * @param {String} name Name of the filter function to retrieve - * @return {Function} the filter function - */ - $FilterProvider.$inject = ['$provide']; - function $FilterProvider($provide) { - var suffix = 'Filter'; + var inputType = { /** - * @ngdoc method - * @name $controllerProvider#register - * @param {string|Object} name Name of the filter function, or an object map of filters where - * the keys are the filter names and the values are the filter factories. - * @returns {Object} Registered filter instance, or if a map of filters was provided then a map - * of the registered filter instances. + * @ngdoc input + * @name input[text] + * + * @description + * Standard HTML text input with AngularJS data binding, inherited by most of the `input` elements. + * + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Adds `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of + * any length. + * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string + * that contains the regular expression body that will be converted to a regular expression + * as in the ngPattern directive. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
    + * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input. + * This parameter is ignored for input[type=password] controls, which will never trim the + * input. + * + * @example + + + +
    + +
    + + Required! + + Single word only! +
    + text = {{example.text}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + var text = element(by.binding('example.text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('example.text')); + + it('should initialize to model', function() { + expect(text.getText()).toContain('guest'); + expect(valid.getText()).toContain('true'); + }); + + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); + }); + + it('should be invalid if multi word', function() { + input.clear(); + input.sendKeys('hello world'); + + expect(valid.getText()).toContain('false'); + }); + +
    */ - function register(name, factory) { - if(isObject(name)) { - var filters = {}; - forEach(name, function(filter, key) { - filters[key] = register(key, filter); - }); - return filters; - } else { - return $provide.factory(name + suffix, factory); - } + 'text': textInputType, + + /** + * @ngdoc input + * @name input[date] + * + * @description + * Input with date validation and transformation. In browsers that do not yet support + * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 + * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many + * modern browsers do not yet support this input type, it is important to provide cues to users on the + * expected input format via a placeholder or label. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a + * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute + * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5 + * constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be + * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute + * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5 + * constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string + * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string + * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + + +
    + + Required! + + Not a valid date! +
    + value = {{example.value | date: "yyyy-MM-dd"}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + var value = element(by.binding('example.value | date: "yyyy-MM-dd"')); + var valid = element(by.binding('myForm.input.$valid')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (see https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); } - this.register = register; - this.$get = ['$injector', function($injector) { - return function(name) { - return $injector.get(name + suffix); - }; - }]; + it('should initialize to model', function() { + expect(value.getText()).toContain('2013-10-22'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - //////////////////////////////////////// + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); - /* global - currencyFilter: false, - dateFilter: false, - filterFilter: false, - jsonFilter: false, - limitToFilter: false, - lowercaseFilter: false, - numberFilter: false, - orderByFilter: false, - uppercaseFilter: false, + it('should be invalid if over max', function() { + setInput('2015-01-01'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + +
    */ + 'date': createDateInputType('date', DATE_REGEXP, + createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']), + 'yyyy-MM-dd'), - register('currency', currencyFilter); - register('date', dateFilter); - register('filter', filterFilter); - register('json', jsonFilter); - register('limitTo', limitToFilter); - register('lowercase', lowercaseFilter); - register('number', numberFilter); - register('orderBy', orderByFilter); - register('uppercase', uppercaseFilter); - } + /** + * @ngdoc input + * @name input[datetime-local] + * + * @description + * Input with datetime validation and transformation. In browsers that do not yet support + * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 + * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation + * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`). + * Note that `min` will also add native HTML5 constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation + * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`). + * Note that `max` will also add native HTML5 constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string + * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string + * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + + +
    + + Required! + + Not a valid date! +
    + value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"')); + var valid = element(by.binding('myForm.input.$valid')); - /** - * @ngdoc filter - * @name filter - * @function - * - * @description - * Selects a subset of items from `array` and returns it as a new array. - * - * @param {Array} array The source array. - * @param {string|Object|function()} expression The predicate to be used for selecting items from - * `array`. - * - * Can be one of: - * - * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against - * the contents of the `array`. All strings or objects with string properties in `array` that contain this string - * will be returned. The predicate can be negated by prefixing the string with `!`. - * - * - `Object`: A pattern object can be used to filter specific properties on objects contained - * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items - * which have property `name` containing "M" and property `phone` containing "1". A special - * property name `$` can be used (as in `{$:"text"}`) to accept a match against any - * property of the object. That's equivalent to the simple substring match with a `string` - * as described above. - * - * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is - * called for each element of `array`. The final result is an array of those elements that - * the predicate returned true for. - * - * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in - * determining if the expected value (from the filter expression) and actual value (from - * the object in the array) should be considered a match. - * - * Can be one of: - * - * - `function(actual, expected)`: - * The function will be given the object value and the predicate value to compare and - * should return true if the item should be included in filtered result. - * - * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`. - * this is essentially strict comparison of expected and actual. - * - * - `false|undefined`: A short hand for a function which will look for a substring match in case - * insensitive way. - * - * @example - - -
    + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); + } - Search: - - - - - - -
    NamePhone
    {{friend.name}}{{friend.phone}}
    -
    - Any:
    - Name only
    - Phone only
    - Equality
    - - - - - - -
    NamePhone
    {{friendObj.name}}{{friendObj.phone}}
    -
    - - var expectFriendNames = function(expectedNames, key) { - element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { - arr.forEach(function(wd, i) { - expect(wd.getText()).toMatch(expectedNames[i]); - }); - }); - }; + it('should initialize to model', function() { + expect(value.getText()).toContain('2010-12-28T14:57:00'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - it('should search across all fields when filtering with a string', function() { - var searchText = element(by.model('searchText')); - searchText.clear(); - searchText.sendKeys('m'); - expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); - searchText.clear(); - searchText.sendKeys('76'); - expectFriendNames(['John', 'Julie'], 'friend'); - }); + it('should be invalid if over max', function() { + setInput('2015-01-01T23:59:00'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + +
    + */ + 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP, + createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']), + 'yyyy-MM-ddTHH:mm:ss.sss'), - it('should search in specific fields when filtering with a predicate object', function() { - var searchAny = element(by.model('search.$')); - searchAny.clear(); - searchAny.sendKeys('i'); - expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); - }); - it('should use a equal comparison when comparator is true', function() { - var searchName = element(by.model('search.name')); - var strict = element(by.model('strict')); - searchName.clear(); - searchName.sendKeys('Julie'); - strict.click(); - expectFriendNames(['Julie'], 'friendObj'); - }); -
    -
    - */ - function filterFilter() { - return function(array, expression, comparator) { - if (!isArray(array)) return array; + /** + * @ngdoc input + * @name input[time] + * + * @description + * Input with time validation and transformation. In browsers that do not yet support + * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 + * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a + * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this + * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add + * native HTML5 constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this + * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add + * native HTML5 constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the + * `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the + * `ngMax` expression evaluates to. Note that it does not set the `max` attribute. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + + +
    + + Required! + + Not a valid date! +
    + value = {{example.value | date: "HH:mm:ss"}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + var value = element(by.binding('example.value | date: "HH:mm:ss"')); + var valid = element(by.binding('myForm.input.$valid')); - var comparatorType = typeof(comparator), - predicates = []; + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); + } - predicates.check = function(value) { - for (var j = 0; j < predicates.length; j++) { - if(!predicates[j](value)) { - return false; - } - } - return true; - }; + it('should initialize to model', function() { + expect(value.getText()).toContain('14:57:00'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - if (comparatorType !== 'function') { - if (comparatorType === 'boolean' && comparator) { - comparator = function(obj, text) { - return angular.equals(obj, text); - }; - } else { - comparator = function(obj, text) { - if (obj && text && typeof obj === 'object' && typeof text === 'object') { - for (var objKey in obj) { - if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) && - comparator(obj[objKey], text[objKey])) { - return true; - } - } - return false; - } - text = (''+text).toLowerCase(); - return (''+obj).toLowerCase().indexOf(text) > -1; - }; - } - } + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); - var search = function(obj, text){ - if (typeof text == 'string' && text.charAt(0) === '!') { - return !search(obj, text.substr(1)); - } - switch (typeof obj) { - case "boolean": - case "number": - case "string": - return comparator(obj, text); - case "object": - switch (typeof text) { - case "object": - return comparator(obj, text); - default: - for ( var objKey in obj) { - if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { - return true; - } - } - break; - } - return false; - case "array": - for ( var i = 0; i < obj.length; i++) { - if (search(obj[i], text)) { - return true; - } - } - return false; - default: - return false; - } - }; - switch (typeof expression) { - case "boolean": - case "number": - case "string": - // Set up expression object and fall through - expression = {$:expression}; - // jshint -W086 - case "object": - // jshint +W086 - for (var key in expression) { - (function(path) { - if (typeof expression[path] == 'undefined') return; - predicates.push(function(value) { - return search(path == '$' ? value : (value && value[path]), expression[path]); - }); - })(key); - } - break; - case 'function': - predicates.push(expression); - break; - default: - return array; - } - var filtered = []; - for ( var j = 0; j < array.length; j++) { - var value = array[j]; - if (predicates.check(value)) { - filtered.push(value); - } - } - return filtered; - }; - } + it('should be invalid if over max', function() { + setInput('23:59:00'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + +
    + */ + 'time': createDateInputType('time', TIME_REGEXP, + createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']), + 'HH:mm:ss.sss'), + + /** + * @ngdoc input + * @name input[week] + * + * @description + * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support + * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 + * week format (yyyy-W##), for example: `2013-W02`. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this + * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add + * native HTML5 constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this + * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add + * native HTML5 constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string + * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string + * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + +
    + + Required! + + Not a valid date! +
    + value = {{example.value | date: "yyyy-Www"}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + var value = element(by.binding('example.value | date: "yyyy-Www"')); + var valid = element(by.binding('myForm.input.$valid')); - /** - * @ngdoc filter - * @name currency - * @function - * - * @description - * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default - * symbol for current locale is used. - * - * @param {number} amount Input to filter. - * @param {string=} symbol Currency symbol or identifier to be displayed. - * @returns {string} Formatted number. - * - * - * @example - - - -
    -
    - default currency symbol ($): {{amount | currency}}
    - custom currency identifier (USD$): {{amount | currency:"USD$"}} -
    -
    - - it('should init with 1234.56', function() { - expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); - expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56'); - }); - it('should update', function() { - if (browser.params.browser == 'safari') { - // Safari does not understand the minus key. See - // https://github.com/angular/protractor/issues/481 - return; - } - element(by.model('amount')).clear(); - element(by.model('amount')).sendKeys('-1234'); - expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)'); - expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)'); - }); - -
    - */ - currencyFilter.$inject = ['$locale']; - function currencyFilter($locale) { - var formats = $locale.NUMBER_FORMATS; - return function(amount, currencySymbol){ - if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; - return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). - replace(/\u00A4/g, currencySymbol); - }; - } + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); + } - /** - * @ngdoc filter - * @name number - * @function - * - * @description - * Formats a number as text. - * - * If the input is not a number an empty string is returned. - * - * @param {number|string} number Number to format. - * @param {(number|string)=} fractionSize Number of decimal places to round the number to. - * If this is not provided then the fraction size is computed from the current locale's number - * formatting pattern. In the case of the default locale, it will be 3. - * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. - * - * @example - - - -
    - Enter number:
    - Default formatting: {{val | number}}
    - No fractions: {{val | number:0}}
    - Negative number: {{-val | number:4}} -
    -
    - - it('should format numbers', function() { - expect(element(by.id('number-default')).getText()).toBe('1,234.568'); - expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); - expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); - }); + it('should initialize to model', function() { + expect(value.getText()).toContain('2013-W01'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - it('should update', function() { - element(by.model('val')).clear(); - element(by.model('val')).sendKeys('3374.333'); - expect(element(by.id('number-default')).getText()).toBe('3,374.333'); - expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); - expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - -
    - */ + it('should be invalid if over max', function() { + setInput('2015-W01'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); +
    +
    + */ + 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'), - numberFilter.$inject = ['$locale']; - function numberFilter($locale) { - var formats = $locale.NUMBER_FORMATS; - return function(number, fractionSize) { - return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, - fractionSize); - }; - } + /** + * @ngdoc input + * @name input[month] + * + * @description + * Input with month validation and transformation. In browsers that do not yet support + * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 + * month format (yyyy-MM), for example: `2009-01`. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * If the model is not set to the first of the month, the next view to model update will set it + * to the first of the month. + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this + * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add + * native HTML5 constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this + * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add + * native HTML5 constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string + * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string + * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. - var DECIMAL_SEP = '.'; - function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { - if (number == null || !isFinite(number) || isObject(number)) return ''; - - var isNegative = number < 0; - number = Math.abs(number); - var numStr = number + '', - formatedText = '', - parts = []; - - var hasExponent = false; - if (numStr.indexOf('e') !== -1) { - var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); - if (match && match[2] == '-' && match[3] > fractionSize + 1) { - numStr = '0'; - } else { - formatedText = numStr; - hasExponent = true; - } - } + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + + +
    + + Required! + + Not a valid month! +
    + value = {{example.value | date: "yyyy-MM"}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + var value = element(by.binding('example.value | date: "yyyy-MM"')); + var valid = element(by.binding('myForm.input.$valid')); - if (!hasExponent) { - var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); + } - // determine fractionSize if it is not specified - if (isUndefined(fractionSize)) { - fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); - } + it('should initialize to model', function() { + expect(value.getText()).toContain('2013-10'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - var pow = Math.pow(10, fractionSize); - number = Math.round(number * pow) / pow; - var fraction = ('' + number).split(DECIMAL_SEP); - var whole = fraction[0]; - fraction = fraction[1] || ''; + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); - var i, pos = 0, - lgroup = pattern.lgSize, - group = pattern.gSize; + it('should be invalid if over max', function() { + setInput('2015-01'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + +
    + */ + 'month': createDateInputType('month', MONTH_REGEXP, + createDateParser(MONTH_REGEXP, ['yyyy', 'MM']), + 'yyyy-MM'), - if (whole.length >= (lgroup + group)) { - pos = whole.length - lgroup; - for (i = 0; i < pos; i++) { - if ((pos - i)%group === 0 && i !== 0) { - formatedText += groupSep; - } - formatedText += whole.charAt(i); - } - } + /** + * @ngdoc input + * @name input[number] + * + * @description + * Text input with number validation and transformation. Sets the `number` validation + * error if not a valid number. + * + *
    + * The model must always be of type `number` otherwise AngularJS will throw an error. + * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt} + * error docs for more information and an example of how to convert your model if necessary. + *
    + * + * ## Issues with HTML5 constraint validation + * + * In browsers that follow the + * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29), + * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}. + * If a non-number is entered in the input, the browser will report the value as an empty string, + * which means the view / model values in `ngModel` and subsequently the scope value + * will also be an empty string. + * + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * Can be interpolated. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * Can be interpolated. + * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`, + * but does not trigger HTML5 native validation. Takes an expression. + * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`, + * but does not trigger HTML5 native validation. Takes an expression. + * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint. + * Can be interpolated. + * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint, + * but does not trigger HTML5 native validation. Takes an expression. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of + * any length. + * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string + * that contains the regular expression body that will be converted to a regular expression + * as in the ngPattern directive. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
    + * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + +
    + + Required! + + Not valid number! +
    + value = {{example.value}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    +
    +
    + + var value = element(by.binding('example.value')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('example.value')); - for (i = pos; i < whole.length; i++) { - if ((whole.length - i)%lgroup === 0 && i !== 0) { - formatedText += groupSep; - } - formatedText += whole.charAt(i); - } + it('should initialize to model', function() { + expect(value.getText()).toContain('12'); + expect(valid.getText()).toContain('true'); + }); - // format fraction part. - while(fraction.length < fractionSize) { - fraction += '0'; - } + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('false'); + }); - if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); - } else { + it('should be invalid if over max', function() { + input.clear(); + input.sendKeys('123'); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('false'); + }); + +
    + */ + 'number': numberInputType, - if (fractionSize > 0 && number > -1 && number < 1) { - formatedText = number.toFixed(fractionSize); - } - } - parts.push(isNegative ? pattern.negPre : pattern.posPre); - parts.push(formatedText); - parts.push(isNegative ? pattern.negSuf : pattern.posSuf); - return parts.join(''); - } + /** + * @ngdoc input + * @name input[url] + * + * @description + * Text input with URL validation. Sets the `url` validation error key if the content is not a + * valid URL. + * + *
    + * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex + * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify + * the built-in validators (see the {@link guide/forms Forms guide}) + *
    + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of + * any length. + * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string + * that contains the regular expression body that will be converted to a regular expression + * as in the ngPattern directive. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
    + * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    +
    + + var text = element(by.binding('url.text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('url.text')); + + it('should initialize to model', function() { + expect(text.getText()).toContain('http://google.com'); + expect(valid.getText()).toContain('true'); + }); - function padNumber(num, digits, trim) { - var neg = ''; - if (num < 0) { - neg = '-'; - num = -num; - } - num = '' + num; - while(num.length < digits) num = '0' + num; - if (trim) - num = num.substr(num.length - digits); - return neg + num; - } + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); + }); - function dateGetter(name, size, offset, trim) { - offset = offset || 0; - return function(date) { - var value = date['get' + name](); - if (offset > 0 || value > -offset) - value += offset; - if (value === 0 && offset == -12 ) value = 12; - return padNumber(value, size, trim); - }; - } + it('should be invalid if not url', function() { + input.clear(); + input.sendKeys('box'); - function dateStrGetter(name, shortForm) { - return function(date, formats) { - var value = date['get' + name](); - var get = uppercase(shortForm ? ('SHORT' + name) : name); + expect(valid.getText()).toContain('false'); + }); + +
    + */ + 'url': urlInputType, - return formats[get][value]; - }; - } - function timeZoneGetter(date) { - var zone = -1 * date.getTimezoneOffset(); - var paddedZone = (zone >= 0) ? "+" : ""; + /** + * @ngdoc input + * @name input[email] + * + * @description + * Text input with email validation. Sets the `email` validation error key if not a valid email + * address. + * + *
    + * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex + * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can + * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide}) + *
    + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of + * any length. + * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string + * that contains the regular expression body that will be converted to a regular expression + * as in the ngPattern directive. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
    + * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    + +
    + + Required! + + Not valid email! +
    + text = {{email.text}}
    + myForm.input.$valid = {{myForm.input.$valid}}
    + myForm.input.$error = {{myForm.input.$error}}
    + myForm.$valid = {{myForm.$valid}}
    + myForm.$error.required = {{!!myForm.$error.required}}
    + myForm.$error.email = {{!!myForm.$error.email}}
    +
    +
    + + var text = element(by.binding('email.text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('email.text')); - paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + - padNumber(Math.abs(zone % 60), 2); + it('should initialize to model', function() { + expect(text.getText()).toContain('me@example.com'); + expect(valid.getText()).toContain('true'); + }); - return paddedZone; - } + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); + }); - function ampmGetter(date, formats) { - return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; - } + it('should be invalid if not email', function() { + input.clear(); + input.sendKeys('xxx'); - var DATE_FORMATS = { - yyyy: dateGetter('FullYear', 4), - yy: dateGetter('FullYear', 2, 0, true), - y: dateGetter('FullYear', 1), - MMMM: dateStrGetter('Month'), - MMM: dateStrGetter('Month', true), - MM: dateGetter('Month', 2, 1), - M: dateGetter('Month', 1, 1), - dd: dateGetter('Date', 2), - d: dateGetter('Date', 1), - HH: dateGetter('Hours', 2), - H: dateGetter('Hours', 1), - hh: dateGetter('Hours', 2, -12), - h: dateGetter('Hours', 1, -12), - mm: dateGetter('Minutes', 2), - m: dateGetter('Minutes', 1), - ss: dateGetter('Seconds', 2), - s: dateGetter('Seconds', 1), - // while ISO 8601 requires fractions to be prefixed with `.` or `,` - // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions - sss: dateGetter('Milliseconds', 3), - EEEE: dateStrGetter('Day'), - EEE: dateStrGetter('Day', true), - a: ampmGetter, - Z: timeZoneGetter - }; + expect(valid.getText()).toContain('false'); + }); + +
    + */ + 'email': emailInputType, - var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, - NUMBER_STRING = /^\-?\d+$/; - /** - * @ngdoc filter - * @name date - * @function - * - * @description - * Formats `date` to a string based on the requested `format`. - * - * `format` string can be composed of the following elements: - * - * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) - * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) - * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) - * * `'MMMM'`: Month in year (January-December) - * * `'MMM'`: Month in year (Jan-Dec) - * * `'MM'`: Month in year, padded (01-12) - * * `'M'`: Month in year (1-12) - * * `'dd'`: Day in month, padded (01-31) - * * `'d'`: Day in month (1-31) - * * `'EEEE'`: Day in Week,(Sunday-Saturday) - * * `'EEE'`: Day in Week, (Sun-Sat) - * * `'HH'`: Hour in day, padded (00-23) - * * `'H'`: Hour in day (0-23) - * * `'hh'`: Hour in am/pm, padded (01-12) - * * `'h'`: Hour in am/pm, (1-12) - * * `'mm'`: Minute in hour, padded (00-59) - * * `'m'`: Minute in hour (0-59) - * * `'ss'`: Second in minute, padded (00-59) - * * `'s'`: Second in minute (0-59) - * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) - * * `'a'`: am/pm marker - * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) - * - * `format` string can also be one of the following predefined - * {@link guide/i18n localizable formats}: - * - * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale - * (e.g. Sep 3, 2010 12:05:08 pm) - * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) - * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale - * (e.g. Friday, September 3, 2010) - * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) - * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) - * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) - * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) - * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) - * - * `format` string can contain literal values. These need to be quoted with single quotes (e.g. - * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence - * (e.g. `"h 'o''clock'"`). - * - * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or - * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its - * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is - * specified in the string input, the time is considered to be in the local timezone. - * @param {string=} format Formatting rules (see Description). If not specified, - * `mediumDate` is used. - * @returns {string} Formatted string or the input if input is not recognized as date/millis. - * - * @example - - - {{1288323623006 | date:'medium'}}: - {{1288323623006 | date:'medium'}}
    - {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: - {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
    - {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: - {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
    -
    - - it('should format date', function() { - expect(element(by.binding("1288323623006 | date:'medium'")).getText()). - toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); - expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). - toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); - expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). - toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); - }); - -
    - */ - dateFilter.$inject = ['$locale']; - function dateFilter($locale) { + /** + * @ngdoc input + * @name input[radio] + * + * @description + * HTML radio button. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string} value The value to which the `ngModel` expression should be set when selected. + * Note that `value` only supports `string` values, i.e. the scope model needs to be a string, + * too. Use `ngValue` if you need complex models (`number`, `object`, ...). + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * @param {string} ngValue AngularJS expression to which `ngModel` will be be set when the radio + * is selected. Should be used instead of the `value` attribute if you need + * a non-string `ngModel` (`boolean`, `array`, ...). + * + * @example + + + +
    +
    +
    +
    + color = {{color.name | json}}
    +
    + Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. +
    + + it('should change state', function() { + var inputs = element.all(by.model('color.name')); + var color = element(by.binding('color.name')); + expect(color.getText()).toContain('blue'); - var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; - // 1 2 3 4 5 6 7 8 9 10 11 - function jsonStringToDate(string) { - var match; - if (match = string.match(R_ISO8601_STR)) { - var date = new Date(0), - tzHour = 0, - tzMin = 0, - dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, - timeSetter = match[8] ? date.setUTCHours : date.setHours; + inputs.get(0).click(); + expect(color.getText()).toContain('red'); - if (match[9]) { - tzHour = int(match[9] + match[10]); - tzMin = int(match[9] + match[11]); - } - dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); - var h = int(match[4]||0) - tzHour; - var m = int(match[5]||0) - tzMin; - var s = int(match[6]||0); - var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); - timeSetter.call(date, h, m, s, ms); - return date; - } - return string; - } + inputs.get(1).click(); + expect(color.getText()).toContain('green'); + }); + +
    + */ + 'radio': radioInputType, + /** + * @ngdoc input + * @name input[range] + * + * @description + * Native range input with validation and transformation. + * + * The model for the range input must always be a `Number`. + * + * IE9 and other browsers that do not support the `range` type fall back + * to a text input without any default values for `min`, `max` and `step`. Model binding, + * validation and number parsing are nevertheless supported. + * + * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]` + * in a way that never allows the input to hold an invalid value. That means: + * - any non-numerical value is set to `(max + min) / 2`. + * - any numerical value that is less than the current min val, or greater than the current max val + * is set to the min / max val respectively. + * - additionally, the current `step` is respected, so the nearest value that satisfies a step + * is used. + * + * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range)) + * for more info. + * + * This has the following consequences for AngularJS: + * + * Since the element value should always reflect the current model value, a range input + * will set the bound ngModel expression to the value that the browser has set for the + * input element. For example, in the following input ``, + * if the application sets `model.value = null`, the browser will set the input to `'50'`. + * AngularJS will then set the model to `50`, to prevent input and model value being out of sync. + * + * That means the model for range will immediately be set to `50` after `ngModel` has been + * initialized. It also means a range input can never have the required error. + * + * This does not only affect changes to the model value, but also to the values of the `min`, + * `max`, and `step` attributes. When these change in a way that will cause the browser to modify + * the input value, AngularJS will also update the model value. + * + * Automatic value adjustment also means that a range input element can never have the `required`, + * `min`, or `max` errors. + * + * However, `step` is currently only fully implemented by Firefox. Other browsers have problems + * when the step value changes dynamically - they do not adjust the element value correctly, but + * instead may set the `stepMismatch` error. If that's the case, the AngularJS will set the `step` + * error on the input, and set the model to `undefined`. + * + * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do + * not set the `min` and `max` attributes, which means that the browser won't automatically adjust + * the input value based on their values, and will always assume min = 0, max = 100, and step = 1. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation to ensure that the value entered is greater + * than `min`. Can be interpolated. + * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`. + * Can be interpolated. + * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step` + * Can be interpolated. + * @param {string=} ngChange AngularJS expression to be executed when the ngModel value changes due + * to user interaction with the input element. + * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the + * element. **Note** : `ngChecked` should not be used alongside `ngModel`. + * Checkout {@link ng.directive:ngChecked ngChecked} for usage. + * + * @example + + + +
    + + Model as range: +
    + Model as number:
    + Min:
    + Max:
    + value = {{value}}
    + myForm.range.$valid = {{myForm.range.$valid}}
    + myForm.range.$error = {{myForm.range.$error}} +
    +
    +
    - return function(date, format) { - var text = '', - parts = [], - fn, match; + * ## Range Input with ngMin & ngMax attributes - format = format || 'mediumDate'; - format = $locale.DATETIME_FORMATS[format] || format; - if (isString(date)) { - if (NUMBER_STRING.test(date)) { - date = int(date); - } else { - date = jsonStringToDate(date); - } - } + * @example + + + +
    + Model as range: +
    + Model as number:
    + Min:
    + Max:
    + value = {{value}}
    + myForm.range.$valid = {{myForm.range.$valid}}
    + myForm.range.$error = {{myForm.range.$error}} +
    +
    +
    - if (isNumber(date)) { - date = new Date(date); - } + */ + 'range': rangeInputType, - if (!isDate(date)) { - return date; - } + /** + * @ngdoc input + * @name input[checkbox] + * + * @description + * HTML checkbox. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {expression=} ngTrueValue The value to which the expression should be set when selected. + * @param {expression=} ngFalseValue The value to which the expression should be set when not selected. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
    +
    +
    + value1 = {{checkboxModel.value1}}
    + value2 = {{checkboxModel.value2}}
    +
    +
    + + it('should change state', function() { + var value1 = element(by.binding('checkboxModel.value1')); + var value2 = element(by.binding('checkboxModel.value2')); - while(format) { - match = DATE_FORMATS_SPLIT.exec(format); - if (match) { - parts = concat(parts, match, 1); - format = parts.pop(); - } else { - parts.push(format); - format = null; - } - } + expect(value1.getText()).toContain('true'); + expect(value2.getText()).toContain('YES'); - forEach(parts, function(value){ - fn = DATE_FORMATS[value]; - text += fn ? fn(date, $locale.DATETIME_FORMATS) - : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); - }); + element(by.model('checkboxModel.value1')).click(); + element(by.model('checkboxModel.value2')).click(); - return text; - }; - } + expect(value1.getText()).toContain('false'); + expect(value2.getText()).toContain('NO'); + }); + +
    + */ + 'checkbox': checkboxInputType, + 'hidden': noop, + 'button': noop, + 'submit': noop, + 'reset': noop, + 'file': noop + }; - /** - * @ngdoc filter - * @name json - * @function - * - * @description - * Allows you to convert a JavaScript object into JSON string. - * - * This filter is mostly useful for debugging. When using the double curly {{value}} notation - * the binding is automatically converted to JSON. - * - * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. - * @returns {string} JSON string. - * - * - * @example - - -
    {{ {'name':'value'} | json }}
    -
    - - it('should jsonify filtered objects', function() { - expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/); - }); - -
    - * - */ - function jsonFilter() { - return function(object) { - return toJson(object, true); - }; + function stringBasedInputType(ctrl) { + ctrl.$formatters.push(function(value) { + return ctrl.$isEmpty(value) ? value : value.toString(); + }); } + function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); + } - /** - * @ngdoc filter - * @name lowercase - * @function - * @description - * Converts string to lowercase. - * @see angular.lowercase - */ - var lowercaseFilter = valueFn(lowercase); - - - /** - * @ngdoc filter - * @name uppercase - * @function - * @description - * Converts string to uppercase. - * @see angular.uppercase - */ - var uppercaseFilter = valueFn(uppercase); - - /** - * @ngdoc filter - * @name limitTo - * @function - * - * @description - * Creates a new array or string containing only a specified number of elements. The elements - * are taken from either the beginning or the end of the source array or string, as specified by - * the value and sign (positive or negative) of `limit`. - * - * @param {Array|string} input Source array or string to be limited. - * @param {string|number} limit The length of the returned array or string. If the `limit` number - * is positive, `limit` number of items from the beginning of the source array/string are copied. - * If the number is negative, `limit` number of items from the end of the source array/string - * are copied. The `limit` will be trimmed if it exceeds `array.length` - * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array - * had less than `limit` elements. - * - * @example - - - -
    - Limit {{numbers}} to: -

    Output numbers: {{ numbers | limitTo:numLimit }}

    - Limit {{letters}} to: -

    Output letters: {{ letters | limitTo:letterLimit }}

    -
    -
    - - var numLimitInput = element(by.model('numLimit')); - var letterLimitInput = element(by.model('letterLimit')); - var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); - var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); + function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) { + var type = lowercase(element[0].type); - it('should limit the number array to first three items', function() { - expect(numLimitInput.getAttribute('value')).toBe('3'); - expect(letterLimitInput.getAttribute('value')).toBe('3'); - expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); - expect(limitedLetters.getText()).toEqual('Output letters: abc'); - }); + // In composition mode, users are still inputting intermediate text buffer, + // hold the listener until composition is done. + // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent + if (!$sniffer.android) { + var composing = false; - it('should update the output when -3 is entered', function() { - numLimitInput.clear(); - numLimitInput.sendKeys('-3'); - letterLimitInput.clear(); - letterLimitInput.sendKeys('-3'); - expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); - expect(limitedLetters.getText()).toEqual('Output letters: ghi'); - }); + element.on('compositionstart', function() { + composing = true; + }); - it('should not exceed the maximum size of input array', function() { - numLimitInput.clear(); - numLimitInput.sendKeys('100'); - letterLimitInput.clear(); - letterLimitInput.sendKeys('100'); - expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); - expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); - }); - -
    - */ - function limitToFilter(){ - return function(input, limit) { - if (!isArray(input) && !isString(input)) return input; + element.on('compositionend', function() { + composing = false; + listener(); + }); + } - limit = int(limit); + var timeout; - if (isString(input)) { - //NaN check on limit - if (limit) { - return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); - } else { - return ""; - } + var listener = function(ev) { + if (timeout) { + $browser.defer.cancel(timeout); + timeout = null; } + if (composing) return; + var value = element.val(), + event = ev && ev.type; - var out = [], - i, n; - - // if abs(limit) exceeds maximum length, trim it - if (limit > input.length) - limit = input.length; - else if (limit < -input.length) - limit = -input.length; - - if (limit > 0) { - i = 0; - n = limit; - } else { - i = input.length + limit; - n = input.length; + // By default we will trim the value + // If the attribute ng-trim exists we will avoid trimming + // If input type is 'password', the value is never trimmed + if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) { + value = trim(value); } - for (; i} expression A predicate to be - * used by the comparator to determine the order of elements. - * - * Can be one of: - * - * - `function`: Getter function. The result of this function will be sorted using the - * `<`, `=`, `>` operator. - * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' - * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control - * ascending or descending sort order (for example, +name or -name). - * - `Array`: An array of function or string predicates. The first predicate in the array - * is used for sorting, but when two items are equivalent, the next predicate is used. - * - * @param {boolean=} reverse Reverse the order of the array. - * @returns {Array} Sorted copy of the source array. - * - * @example - - - -
    -
    Sorting predicate = {{predicate}}; reverse = {{reverse}}
    -
    - [ unsorted ] - - - - - - - - - - - -
    Name - (^)Phone NumberAge
    {{friend.name}}{{friend.phone}}{{friend.age}}
    -
    -
    -
    - */ - orderByFilter.$inject = ['$parse']; - function orderByFilter($parse){ - return function(array, sortPredicate, reverseOrder) { - if (!isArray(array)) return array; - if (!sortPredicate) return array; - sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; - sortPredicate = map(sortPredicate, function(predicate){ - var descending = false, get = predicate || identity; - if (isString(predicate)) { - if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { - descending = predicate.charAt(0) == '-'; - predicate = predicate.substring(1); - } - get = $parse(predicate); - if (get.constant) { - var key = get(); - return reverseComparator(function(a,b) { - return compare(a[key], b[key]); - }, descending); - } - } - return reverseComparator(function(a,b){ - return compare(get(a),get(b)); - }, descending); - }); - var arrayCopy = []; - for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } - return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); - - function comparator(o1, o2){ - for ( var i = 0; i < sortPredicate.length; i++) { - var comp = sortPredicate[i](o1, o2); - if (comp !== 0) return comp; - } - return 0; - } - function reverseComparator(comp, descending) { - return toBoolean(descending) - ? function(a,b){return comp(b,a);} - : comp; - } - function compare(v1, v2){ - var t1 = typeof v1; - var t2 = typeof v2; - if (t1 == t2) { - if (t1 == "string") { - v1 = v1.toLowerCase(); - v2 = v2.toLowerCase(); - } - if (v1 === v2) return 0; - return v1 < v2 ? -1 : 1; - } else { - return t1 < t2 ? -1 : 1; + // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the + // input event on backspace, delete or cut + if ($sniffer.hasEvent('input')) { + element.on('input', listener); + } else { + var deferListener = function(ev, input, origValue) { + if (!timeout) { + timeout = $browser.defer(function() { + timeout = null; + if (!input || input.value !== origValue) { + listener(ev); + } + }); } - } - }; - } - - function ngDirective(directive) { - if (isFunction(directive)) { - directive = { - link: directive }; - } - directive.restrict = directive.restrict || 'AC'; - return valueFn(directive); - } - /** - * @ngdoc directive - * @name a - * @restrict E - * - * @description - * Modifies the default behavior of the html A tag so that the default action is prevented when - * the href attribute is empty. - * - * This change permits the easy creation of action links with the `ngClick` directive - * without changing the location or causing page reloads, e.g.: - * `Add Item` - */ - var htmlAnchorDirective = valueFn({ - restrict: 'E', - compile: function(element, attr) { + element.on('keydown', /** @this */ function(event) { + var key = event.keyCode; - if (msie <= 8) { + // ignore + // command modifiers arrows + if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; - // turn link into a stylable link in IE - // but only if it doesn't have name attribute, in which case it's an anchor - if (!attr.href && !attr.name) { - attr.$set('href', ''); - } + deferListener(event, this, this.value); + }); - // add a comment node to anchors to workaround IE bug that causes element content to be reset - // to new attribute content if attribute is updated with value containing @ and element also - // contains value with @ - // see issue #1949 - element.append(document.createComment('IE fix')); + // if user modifies input value using context menu in IE, we need "paste", "cut" and "drop" events to catch it + if ($sniffer.hasEvent('paste')) { + element.on('paste cut drop', deferListener); } + } - if (!attr.href && !attr.xlinkHref && !attr.name) { - return function(scope, element) { - // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. - var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? - 'xlink:href' : 'href'; - element.on('click', function(event){ - // if we have no href url, then don't navigate anywhere. - if (!element.attr(href)) { - event.preventDefault(); + // if user paste into input using mouse on older browser + // or form autocomplete on newer browser, we need "change" event to catch it + element.on('change', listener); + + // Some native input types (date-family) have the ability to change validity without + // firing any input/change events. + // For these event types, when native validators are present and the browser supports the type, + // check for validity changes on various DOM events. + if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) { + element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) { + if (!timeout) { + var validity = this[VALIDITY_STATE_PROPERTY]; + var origBadInput = validity.badInput; + var origTypeMismatch = validity.typeMismatch; + timeout = $browser.defer(function() { + timeout = null; + if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) { + listener(ev); } }); - }; - } + } + }); } - }); - /** - * @ngdoc directive - * @name ngHref - * @restrict A - * @priority 99 - * - * @description - * Using Angular markup like `{{hash}}` in an href attribute will - * make the link go to the wrong URL if the user clicks it before - * Angular has a chance to replace the `{{hash}}` markup with its - * value. Until Angular replaces the markup the link will be broken - * and will most likely return a 404 error. - * - * The `ngHref` directive solves this problem. - * - * The wrong way to write it: - * ```html - * - * ``` - * - * The correct way to write it: - * ```html - * - * ``` - * - * @element A - * @param {template} ngHref any string which can contain `{{}}` markup. - * - * @example - * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes - * in links and their different behaviors: - - -
    -
    link 1 (link, don't reload)
    - link 2 (link, don't reload)
    - link 3 (link, reload!)
    - anchor (link, don't reload)
    - anchor (no link)
    - link (link, change location) - - - it('should execute ng-click but not reload when href without value', function() { - element(by.id('link-1')).click(); - expect(element(by.model('value')).getAttribute('value')).toEqual('1'); - expect(element(by.id('link-1')).getAttribute('href')).toBe(''); - }); + ctrl.$render = function() { + // Workaround for Firefox validation #12102. + var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue; + if (element.val() !== value) { + element.val(value); + } + }; + } - it('should execute ng-click but not reload when href empty string', function() { - element(by.id('link-2')).click(); - expect(element(by.model('value')).getAttribute('value')).toEqual('2'); - expect(element(by.id('link-2')).getAttribute('href')).toBe(''); - }); + function weekParser(isoWeek, existingDate) { + if (isDate(isoWeek)) { + return isoWeek; + } - it('should execute ng-click and change url when ng-href specified', function() { - expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); + if (isString(isoWeek)) { + WEEK_REGEXP.lastIndex = 0; + var parts = WEEK_REGEXP.exec(isoWeek); + if (parts) { + var year = +parts[1], + week = +parts[2], + hours = 0, + minutes = 0, + seconds = 0, + milliseconds = 0, + firstThurs = getFirstThursdayOfYear(year), + addDays = (week - 1) * 7; + + if (existingDate) { + hours = existingDate.getHours(); + minutes = existingDate.getMinutes(); + seconds = existingDate.getSeconds(); + milliseconds = existingDate.getMilliseconds(); + } - element(by.id('link-3')).click(); + return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds); + } + } - // At this point, we navigate away from an Angular page, so we need - // to use browser.driver to get the base webdriver. + return NaN; + } - browser.wait(function() { - return browser.driver.getCurrentUrl().then(function(url) { - return url.match(/\/123$/); - }); - }, 1000, 'page should navigate to /123'); - }); + function createDateParser(regexp, mapping) { + return function(iso, date) { + var parts, map; - xit('should execute ng-click but not reload when href empty string and name specified', function() { - element(by.id('link-4')).click(); - expect(element(by.model('value')).getAttribute('value')).toEqual('4'); - expect(element(by.id('link-4')).getAttribute('href')).toBe(''); - }); + if (isDate(iso)) { + return iso; + } - it('should execute ng-click but not reload when no href but name specified', function() { - element(by.id('link-5')).click(); - expect(element(by.model('value')).getAttribute('value')).toEqual('5'); - expect(element(by.id('link-5')).getAttribute('href')).toBe(null); - }); + if (isString(iso)) { + // When a date is JSON'ified to wraps itself inside of an extra + // set of double quotes. This makes the date parsing code unable + // to match the date string and parse it as a date. + if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') { + iso = iso.substring(1, iso.length - 1); + } + if (ISO_DATE_REGEXP.test(iso)) { + return new Date(iso); + } + regexp.lastIndex = 0; + parts = regexp.exec(iso); + + if (parts) { + parts.shift(); + if (date) { + map = { + yyyy: date.getFullYear(), + MM: date.getMonth() + 1, + dd: date.getDate(), + HH: date.getHours(), + mm: date.getMinutes(), + ss: date.getSeconds(), + sss: date.getMilliseconds() / 1000 + }; + } else { + map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 }; + } - it('should only change url when only ng-href', function() { - element(by.model('value')).clear(); - element(by.model('value')).sendKeys('6'); - expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); + forEach(parts, function(part, index) { + if (index < mapping.length) { + map[mapping[index]] = +part; + } + }); + return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0); + } + } - element(by.id('link-6')).click(); + return NaN; + }; + } - // At this point, we navigate away from an Angular page, so we need - // to use browser.driver to get the base webdriver. - browser.wait(function() { - return browser.driver.getCurrentUrl().then(function(url) { - return url.match(/\/6$/); + function createDateInputType(type, regexp, parseDate, format) { + return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) { + badInputChecker(scope, element, attr, ctrl); + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + var timezone = ctrl && ctrl.$options.getOption('timezone'); + var previousDate; + + ctrl.$$parserName = type; + ctrl.$parsers.push(function(value) { + if (ctrl.$isEmpty(value)) return null; + if (regexp.test(value)) { + // Note: We cannot read ctrl.$modelValue, as there might be a different + // parser/formatter in the processing chain so that the model + // contains some different data format! + var parsedDate = parseDate(value, previousDate); + if (timezone) { + parsedDate = convertTimezoneToLocal(parsedDate, timezone); + } + return parsedDate; + } + return undefined; }); - }, 1000, 'page should navigate to /6'); - }); - -
    - */ - - /** - * @ngdoc directive - * @name ngSrc - * @restrict A - * @priority 99 - * - * @description - * Using Angular markup like `{{hash}}` in a `src` attribute doesn't - * work right: The browser will fetch from the URL with the literal - * text `{{hash}}` until Angular replaces the expression inside - * `{{hash}}`. The `ngSrc` directive solves this problem. - * - * The buggy way to write it: - * ```html - * - * ``` - * - * The correct way to write it: - * ```html - * - * ``` - * - * @element IMG - * @param {template} ngSrc any string which can contain `{{}}` markup. - */ - - /** - * @ngdoc directive - * @name ngSrcset - * @restrict A - * @priority 99 - * - * @description - * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't - * work right: The browser will fetch from the URL with the literal - * text `{{hash}}` until Angular replaces the expression inside - * `{{hash}}`. The `ngSrcset` directive solves this problem. - * - * The buggy way to write it: - * ```html - * - * ``` - * - * The correct way to write it: - * ```html - * - * ``` - * - * @element IMG - * @param {template} ngSrcset any string which can contain `{{}}` markup. - */ - /** - * @ngdoc directive - * @name ngDisabled - * @restrict A - * @priority 100 - * - * @description - * - * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: - * ```html - *
    - * - *
    - * ``` - * - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as disabled. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngDisabled` directive solves this problem for the `disabled` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * - * @example - - - Click me to toggle:
    - -
    - - it('should toggle button', function() { - expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); - element(by.model('checked')).click(); - expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); - }); - -
    - * - * @element INPUT - * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, - * then special attribute "disabled" will be set on the element - */ + ctrl.$formatters.push(function(value) { + if (value && !isDate(value)) { + throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value); + } + if (isValidDate(value)) { + previousDate = value; + if (previousDate && timezone) { + previousDate = convertTimezoneToLocal(previousDate, timezone, true); + } + return $filter('date')(value, format, timezone); + } else { + previousDate = null; + return ''; + } + }); + if (isDefined(attr.min) || attr.ngMin) { + var minVal; + ctrl.$validators.min = function(value) { + return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal; + }; + attr.$observe('min', function(val) { + minVal = parseObservedDateValue(val); + ctrl.$validate(); + }); + } - /** - * @ngdoc directive - * @name ngChecked - * @restrict A - * @priority 100 - * - * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as checked. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngChecked` directive solves this problem for the `checked` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * @example - - - Check me to check both:
    - -
    - - it('should check both checkBoxes', function() { - expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); - element(by.model('master')).click(); - expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); - }); - -
    - * - * @element INPUT - * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, - * then special attribute "checked" will be set on the element - */ + if (isDefined(attr.max) || attr.ngMax) { + var maxVal; + ctrl.$validators.max = function(value) { + return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal; + }; + attr.$observe('max', function(val) { + maxVal = parseObservedDateValue(val); + ctrl.$validate(); + }); + } + function isValidDate(value) { + // Invalid Date: getTime() returns NaN + return value && !(value.getTime && value.getTime() !== value.getTime()); + } - /** - * @ngdoc directive - * @name ngReadonly - * @restrict A - * @priority 100 - * - * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as readonly. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngReadonly` directive solves this problem for the `readonly` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * @example - - - Check me to make text readonly:
    - -
    - - it('should toggle readonly attr', function() { - expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); - element(by.model('checked')).click(); - expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); - }); - -
    - * - * @element INPUT - * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, - * then special attribute "readonly" will be set on the element - */ + function parseObservedDateValue(val) { + return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val; + } + }; + } + function badInputChecker(scope, element, attr, ctrl) { + var node = element[0]; + var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity); + if (nativeValidation) { + ctrl.$parsers.push(function(value) { + var validity = element.prop(VALIDITY_STATE_PROPERTY) || {}; + return validity.badInput || validity.typeMismatch ? undefined : value; + }); + } + } - /** - * @ngdoc directive - * @name ngSelected - * @restrict A - * @priority 100 - * - * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as selected. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngSelected` directive solves this problem for the `selected` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * - * @example - - - Check me to select:
    - -
    - - it('should select Greetings!', function() { - expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); - element(by.model('selected')).click(); - expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); + function numberFormatterParser(ctrl) { + ctrl.$$parserName = 'number'; + ctrl.$parsers.push(function(value) { + if (ctrl.$isEmpty(value)) return null; + if (NUMBER_REGEXP.test(value)) return parseFloat(value); + return undefined; }); - -
    - * - * @element OPTION - * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, - * then special attribute "selected" will be set on the element - */ - /** - * @ngdoc directive - * @name ngOpen - * @restrict A - * @priority 100 - * - * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as open. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngOpen` directive solves this problem for the `open` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * @example - - - Check me check multiple:
    -
    - Show/Hide me -
    -
    - - it('should toggle open', function() { - expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); - element(by.model('open')).click(); - expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); - }); - -
    - * - * @element DETAILS - * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, - * then special attribute "open" will be set on the element - */ + ctrl.$formatters.push(function(value) { + if (!ctrl.$isEmpty(value)) { + if (!isNumber(value)) { + throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value); + } + value = value.toString(); + } + return value; + }); + } - var ngAttributeAliasDirectives = {}; + function parseNumberAttrVal(val) { + if (isDefined(val) && !isNumber(val)) { + val = parseFloat(val); + } + return !isNumberNaN(val) ? val : undefined; + } + function isNumberInteger(num) { + // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066 + // (minus the assumption that `num` is a number) -// boolean attrs are evaluated - forEach(BOOLEAN_ATTR, function(propName, attrName) { - // binding to multiple is not supported - if (propName == "multiple") return; + // eslint-disable-next-line no-bitwise + return (num | 0) === num; + } - var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { - return { - priority: 100, - link: function(scope, element, attr) { - scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { - attr.$set(attrName, !!value); - }); + function countDecimals(num) { + var numString = num.toString(); + var decimalSymbolIndex = numString.indexOf('.'); + + if (decimalSymbolIndex === -1) { + if (-1 < num && num < 1) { + // It may be in the exponential notation format (`1e-X`) + var match = /e-(\d+)$/.exec(numString); + + if (match) { + return Number(match[1]); } - }; - }; - }); + } + return 0; + } -// ng-src, ng-srcset, ng-href are interpolated - forEach(['src', 'srcset', 'href'], function(attrName) { - var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { - return { - priority: 99, // it needs to run after the attributes are interpolated - link: function(scope, element, attr) { - var propName = attrName, - name = attrName; + return numString.length - decimalSymbolIndex - 1; + } - if (attrName === 'href' && - toString.call(element.prop('href')) === '[object SVGAnimatedString]') { - name = 'xlinkHref'; - attr.$attr[name] = 'xlink:href'; - propName = null; - } + function isValidForStep(viewValue, stepBase, step) { + // At this point `stepBase` and `step` are expected to be non-NaN values + // and `viewValue` is expected to be a valid stringified number. + var value = Number(viewValue); - attr.$observe(normalized, function(value) { - if (!value) - return; + var isNonIntegerValue = !isNumberInteger(value); + var isNonIntegerStepBase = !isNumberInteger(stepBase); + var isNonIntegerStep = !isNumberInteger(step); - attr.$set(name, value); + // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or + // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers. + if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) { + var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0; + var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0; + var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0; - // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist - // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need - // to set the property as well to achieve the desired effect. - // we use attr[attrName] value since $set can sanitize the url. - if (msie && propName) element.prop(propName, attr[name]); - }); - } + var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals); + var multiplier = Math.pow(10, decimalCount); + + value = value * multiplier; + stepBase = stepBase * multiplier; + step = step * multiplier; + + if (isNonIntegerValue) value = Math.round(value); + if (isNonIntegerStepBase) stepBase = Math.round(stepBase); + if (isNonIntegerStep) step = Math.round(step); + } + + return (value - stepBase) % step === 0; + } + + function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { + badInputChecker(scope, element, attr, ctrl); + numberFormatterParser(ctrl); + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + + var minVal; + var maxVal; + + if (isDefined(attr.min) || attr.ngMin) { + ctrl.$validators.min = function(value) { + return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal; }; - }; - }); - /* global -nullFormCtrl */ - var nullFormCtrl = { - $addControl: noop, - $removeControl: noop, - $setValidity: noop, - $setDirty: noop, - $setPristine: noop - }; + attr.$observe('min', function(val) { + minVal = parseNumberAttrVal(val); + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + }); + } - /** - * @ngdoc type - * @name form.FormController - * - * @property {boolean} $pristine True if user has not interacted with the form yet. - * @property {boolean} $dirty True if user has already interacted with the form. - * @property {boolean} $valid True if all of the containing forms and controls are valid. - * @property {boolean} $invalid True if at least one containing control or form is invalid. - * - * @property {Object} $error Is an object hash, containing references to all invalid controls or - * forms, where: - * - * - keys are validation tokens (error names), - * - values are arrays of controls or forms that are invalid for given error name. - * - * - * Built-in validation tokens: - * - * - `email` - * - `max` - * - `maxlength` - * - `min` - * - `minlength` - * - `number` - * - `pattern` - * - `required` - * - `url` - * - * @description - * `FormController` keeps track of all its controls and nested forms as well as state of them, - * such as being valid/invalid or dirty/pristine. - * - * Each {@link ng.directive:form form} directive creates an instance - * of `FormController`. - * - */ -//asks for $scope to fool the BC controller module - FormController.$inject = ['$element', '$attrs', '$scope', '$animate']; - function FormController(element, attrs, $scope, $animate) { - var form = this, - parentForm = element.parent().controller('form') || nullFormCtrl, - invalidCount = 0, // used to easily determine if we are valid - errors = form.$error = {}, - controls = []; + if (isDefined(attr.max) || attr.ngMax) { + ctrl.$validators.max = function(value) { + return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal; + }; - // init state - form.$name = attrs.name || attrs.ngForm; - form.$dirty = false; - form.$pristine = true; - form.$valid = true; - form.$invalid = false; + attr.$observe('max', function(val) { + maxVal = parseNumberAttrVal(val); + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + }); + } + + if (isDefined(attr.step) || attr.ngStep) { + var stepVal; + ctrl.$validators.step = function(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) || + isValidForStep(viewValue, minVal || 0, stepVal); + }; - parentForm.$addControl(form); + attr.$observe('step', function(val) { + stepVal = parseNumberAttrVal(val); + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + }); + } + } - // Setup initial state of the control - element.addClass(PRISTINE_CLASS); - toggleValidCss(true); + function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) { + badInputChecker(scope, element, attr, ctrl); + numberFormatterParser(ctrl); + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + + var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range', + minVal = supportsRange ? 0 : undefined, + maxVal = supportsRange ? 100 : undefined, + stepVal = supportsRange ? 1 : undefined, + validity = element[0].validity, + hasMinAttr = isDefined(attr.min), + hasMaxAttr = isDefined(attr.max), + hasStepAttr = isDefined(attr.step); + + var originalRender = ctrl.$render; + + ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ? + //Browsers that implement range will set these values automatically, but reading the adjusted values after + //$render would cause the min / max validators to be applied with the wrong value + function rangeRender() { + originalRender(); + ctrl.$setViewValue(element.val()); + } : + originalRender; + + if (hasMinAttr) { + ctrl.$validators.min = supportsRange ? + // Since all browsers set the input to a valid value, we don't need to check validity + function noopMinValidator() { return true; } : + // non-support browsers validate the min val + function minValidator(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal; + }; - // convenience method for easy toggling of classes - function toggleValidCss(isValid, validationErrorKey) { - validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; - $animate.removeClass(element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); - $animate.addClass(element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); + setInitialValueAndObserver('min', minChange); } - /** - * @ngdoc method - * @name form.FormController#$addControl - * - * @description - * Register a control with the form. - * - * Input elements using ngModelController do this automatically when they are linked. - */ - form.$addControl = function(control) { - // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored - // and not added to the scope. Now we throw an error. - assertNotHasOwnProperty(control.$name, 'input'); - controls.push(control); + if (hasMaxAttr) { + ctrl.$validators.max = supportsRange ? + // Since all browsers set the input to a valid value, we don't need to check validity + function noopMaxValidator() { return true; } : + // non-support browsers validate the max val + function maxValidator(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal; + }; - if (control.$name) { - form[control.$name] = control; + setInitialValueAndObserver('max', maxChange); + } + + if (hasStepAttr) { + ctrl.$validators.step = supportsRange ? + function nativeStepValidator() { + // Currently, only FF implements the spec on step change correctly (i.e. adjusting the + // input element value to a valid value). It's possible that other browsers set the stepMismatch + // validity error instead, so we can at least report an error in that case. + return !validity.stepMismatch; + } : + // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would + function stepValidator(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) || + isValidForStep(viewValue, minVal || 0, stepVal); + }; + + setInitialValueAndObserver('step', stepChange); + } + + function setInitialValueAndObserver(htmlAttrName, changeFn) { + // interpolated attributes set the attribute value only after a digest, but we need the + // attribute value when the input is first rendered, so that the browser can adjust the + // input value based on the min/max value + element.attr(htmlAttrName, attr[htmlAttrName]); + attr.$observe(htmlAttrName, changeFn); + } + + function minChange(val) { + minVal = parseNumberAttrVal(val); + // ignore changes before model is initialized + if (isNumberNaN(ctrl.$modelValue)) { + return; } - }; - /** - * @ngdoc method - * @name form.FormController#$removeControl - * - * @description - * Deregister a control from the form. - * - * Input elements using ngModelController do this automatically when they are destroyed. - */ - form.$removeControl = function(control) { - if (control.$name && form[control.$name] === control) { - delete form[control.$name]; + if (supportsRange) { + var elVal = element.val(); + // IE11 doesn't set the el val correctly if the minVal is greater than the element value + if (minVal > elVal) { + elVal = minVal; + element.val(elVal); + } + ctrl.$setViewValue(elVal); + } else { + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); } - forEach(errors, function(queue, validationToken) { - form.$setValidity(validationToken, true, control); - }); + } - arrayRemove(controls, control); - }; + function maxChange(val) { + maxVal = parseNumberAttrVal(val); + // ignore changes before model is initialized + if (isNumberNaN(ctrl.$modelValue)) { + return; + } - /** - * @ngdoc method - * @name form.FormController#$setValidity - * - * @description - * Sets the validity of a form control. - * - * This method will also propagate to parent forms. - */ - form.$setValidity = function(validationToken, isValid, control) { - var queue = errors[validationToken]; - - if (isValid) { - if (queue) { - arrayRemove(queue, control); - if (!queue.length) { - invalidCount--; - if (!invalidCount) { - toggleValidCss(isValid); - form.$valid = true; - form.$invalid = false; - } - errors[validationToken] = false; - toggleValidCss(true, validationToken); - parentForm.$setValidity(validationToken, true, form); - } + if (supportsRange) { + var elVal = element.val(); + // IE11 doesn't set the el val correctly if the maxVal is less than the element value + if (maxVal < elVal) { + element.val(maxVal); + // IE11 and Chrome don't set the value to the minVal when max < min + elVal = maxVal < minVal ? minVal : maxVal; } + ctrl.$setViewValue(elVal); + } else { + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + } + } + + function stepChange(val) { + stepVal = parseNumberAttrVal(val); + // ignore changes before model is initialized + if (isNumberNaN(ctrl.$modelValue)) { + return; + } + // Some browsers don't adjust the input value correctly, but set the stepMismatch error + if (supportsRange && ctrl.$viewValue !== element.val()) { + ctrl.$setViewValue(element.val()); } else { - if (!invalidCount) { - toggleValidCss(isValid); - } - if (queue) { - if (includes(queue, control)) return; - } else { - errors[validationToken] = queue = []; - invalidCount++; - toggleValidCss(false, validationToken); - parentForm.$setValidity(validationToken, false, form); + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + } + } + } + + function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { + // Note: no badInputChecker here by purpose as `url` is only a validation + // in browsers, i.e. we can always read out input.value even if it is not valid! + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); + + ctrl.$$parserName = 'url'; + ctrl.$validators.url = function(modelValue, viewValue) { + var value = modelValue || viewValue; + return ctrl.$isEmpty(value) || URL_REGEXP.test(value); + }; + } + + function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { + // Note: no badInputChecker here by purpose as `url` is only a validation + // in browsers, i.e. we can always read out input.value even if it is not valid! + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); + + ctrl.$$parserName = 'email'; + ctrl.$validators.email = function(modelValue, viewValue) { + var value = modelValue || viewValue; + return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); + }; + } + + function radioInputType(scope, element, attr, ctrl) { + var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false'; + // make the name unique, if not defined + if (isUndefined(attr.name)) { + element.attr('name', nextUid()); + } + + var listener = function(ev) { + var value; + if (element[0].checked) { + value = attr.value; + if (doTrim) { + value = trim(value); } - queue.push(control); + ctrl.$setViewValue(value, ev && ev.type); + } + }; + + element.on('click', listener); + + ctrl.$render = function() { + var value = attr.value; + if (doTrim) { + value = trim(value); + } + element[0].checked = (value === ctrl.$viewValue); + }; - form.$valid = false; - form.$invalid = true; + attr.$observe('value', ctrl.$render); + } + + function parseConstantExpr($parse, context, name, expression, fallback) { + var parseFn; + if (isDefined(expression)) { + parseFn = $parse(expression); + if (!parseFn.constant) { + throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' + + '`{1}`.', name, expression); } + return parseFn(context); + } + return fallback; + } + + function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { + var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true); + var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false); + + var listener = function(ev) { + ctrl.$setViewValue(element[0].checked, ev && ev.type); }; - /** - * @ngdoc method - * @name form.FormController#$setDirty - * - * @description - * Sets the form to a dirty state. - * - * This method can be called to add the 'ng-dirty' class and set the form to a dirty - * state (ng-dirty class). This method will also propagate to parent forms. - */ - form.$setDirty = function() { - $animate.removeClass(element, PRISTINE_CLASS); - $animate.addClass(element, DIRTY_CLASS); - form.$dirty = true; - form.$pristine = false; - parentForm.$setDirty(); + element.on('click', listener); + + ctrl.$render = function() { + element[0].checked = ctrl.$viewValue; }; - /** - * @ngdoc method - * @name form.FormController#$setPristine - * - * @description - * Sets the form to its pristine state. - * - * This method can be called to remove the 'ng-dirty' class and set the form to its pristine - * state (ng-pristine class). This method will also propagate to all the controls contained - * in this form. - * - * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after - * saving or resetting it. - */ - form.$setPristine = function () { - $animate.removeClass(element, DIRTY_CLASS); - $animate.addClass(element, PRISTINE_CLASS); - form.$dirty = false; - form.$pristine = true; - forEach(controls, function(control) { - control.$setPristine(); - }); + // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false` + // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert + // it to a boolean. + ctrl.$isEmpty = function(value) { + return value === false; }; + + ctrl.$formatters.push(function(value) { + return equals(value, trueValue); + }); + + ctrl.$parsers.push(function(value) { + return value ? trueValue : falseValue; + }); } /** * @ngdoc directive - * @name ngForm - * @restrict EAC + * @name textarea + * @restrict E * * @description - * Nestable alias of {@link ng.directive:form `form`} directive. HTML - * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a - * sub-group of controls needs to be determined. + * HTML textarea element control with AngularJS data-binding. The data-binding and validation + * properties of this element are exactly the same as those of the + * {@link ng.directive:input input element}. * - * Note: the purpose of `ngForm` is to group controls, - * but not to be a replacement for the `
    ` tag with all of its capabilities - * (e.g. posting to the server, ...). + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any + * length. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
    + * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input. * - * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into - * related scope, under this name. + * @knownIssue * + * When specifying the `placeholder` attribute of ` -
    + + count: {{count}} - - it('should data-bind and become invalid', function() { - if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') { - // SafariDriver can't handle contenteditable - // and Firefox driver can't clear contenteditables very well - return; - } - var contentEditable = element(by.css('[contenteditable]')); - var content = 'Change me!'; + + */ - expect(contentEditable.getText()).toEqual(content); - contentEditable.clear(); - contentEditable.sendKeys(protractor.Key.BACK_SPACE); - expect(contentEditable.getText()).toEqual(''); - expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); - }); - - * + /** + * @ngdoc directive + * @name ngMouseleave + * @restrict A + * @element ANY + * @priority 0 + * + * @description + * Specify custom behavior on mouseleave event. * + * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon + * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) * + * @example + + + + count: {{count}} + + */ - var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', - function($scope, $exceptionHandler, $attr, $element, $parse, $animate) { - this.$viewValue = Number.NaN; - this.$modelValue = Number.NaN; - this.$parsers = []; - this.$formatters = []; - this.$viewChangeListeners = []; - this.$pristine = true; - this.$dirty = false; - this.$valid = true; - this.$invalid = false; - this.$name = $attr.name; - - var ngModelGet = $parse($attr.ngModel), - ngModelSet = ngModelGet.assign; - - if (!ngModelSet) { - throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}", - $attr.ngModel, startingTag($element)); - } - - /** - * @ngdoc method - * @name ngModel.NgModelController#$render - * - * @description - * Called when the view needs to be updated. It is expected that the user of the ng-model - * directive will implement this method. - */ - this.$render = noop; - - /** - * @ngdoc method - * @name ngModel.NgModelController#$isEmpty - * - * @description - * This is called when we need to determine if the value of the input is empty. - * - * For instance, the required directive does this to work out if the input has data or not. - * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. - * - * You can override this for input directives whose concept of being empty is different to the - * default. The `checkboxInputType` directive does this because in its case a value of `false` - * implies empty. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is empty. - */ - this.$isEmpty = function(value) { - return isUndefined(value) || value === '' || value === null || value !== value; - }; - - var parentForm = $element.inheritedData('$formController') || nullFormCtrl, - invalidCount = 0, // used to easily determine if we are valid - $error = this.$error = {}; // keep invalid keys here - - - // Setup initial state of the control - $element.addClass(PRISTINE_CLASS); - toggleValidCss(true); - - // convenience method for easy toggling of classes - function toggleValidCss(isValid, validationErrorKey) { - validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; - $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); - $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); - } - - /** - * @ngdoc method - * @name ngModel.NgModelController#$setValidity - * - * @description - * Change the validity state, and notifies the form when the control changes validity. (i.e. it - * does not notify form if given validator is already marked as invalid). - * - * This method should be called by validators - i.e. the parser or formatter functions. - * - * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign - * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. - * The `validationErrorKey` should be in camelCase and will get converted into dash-case - * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` - * class and can be bound to as `{{someForm.someControl.$error.myError}}` . - * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). - */ - this.$setValidity = function(validationErrorKey, isValid) { - // Purposeful use of ! here to cast isValid to boolean in case it is undefined - // jshint -W018 - if ($error[validationErrorKey] === !isValid) return; - // jshint +W018 - - if (isValid) { - if ($error[validationErrorKey]) invalidCount--; - if (!invalidCount) { - toggleValidCss(true); - this.$valid = true; - this.$invalid = false; - } - } else { - toggleValidCss(false); - this.$invalid = true; - this.$valid = false; - invalidCount++; - } - - $error[validationErrorKey] = !isValid; - toggleValidCss(isValid, validationErrorKey); - - parentForm.$setValidity(validationErrorKey, isValid, this); - }; - - /** - * @ngdoc method - * @name ngModel.NgModelController#$setPristine - * - * @description - * Sets the control to its pristine state. - * - * This method can be called to remove the 'ng-dirty' class and set the control to its pristine - * state (ng-pristine class). - */ - this.$setPristine = function () { - this.$dirty = false; - this.$pristine = true; - $animate.removeClass($element, DIRTY_CLASS); - $animate.addClass($element, PRISTINE_CLASS); - }; - /** - * @ngdoc method - * @name ngModel.NgModelController#$setViewValue - * - * @description - * Update the view value. - * - * This method should be called when the view value changes, typically from within a DOM event handler. - * For example {@link ng.directive:input input} and - * {@link ng.directive:select select} directives call it. - * - * It will update the $viewValue, then pass this value through each of the functions in `$parsers`, - * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to - * `$modelValue` and the **expression** specified in the `ng-model` attribute. - * - * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. - * - * Note that calling this function does not trigger a `$digest`. - * - * @param {string} value Value from the view. - */ - this.$setViewValue = function(value) { - this.$viewValue = value; - - // change to dirty - if (this.$pristine) { - this.$dirty = true; - this.$pristine = false; - $animate.removeClass($element, PRISTINE_CLASS); - $animate.addClass($element, DIRTY_CLASS); - parentForm.$setDirty(); - } - forEach(this.$parsers, function(fn) { - value = fn(value); - }); - - if (this.$modelValue !== value) { - this.$modelValue = value; - ngModelSet($scope, value); - forEach(this.$viewChangeListeners, function(listener) { - try { - listener(); - } catch(e) { - $exceptionHandler(e); - } - }); - } - }; + /** + * @ngdoc directive + * @name ngMousemove + * @restrict A + * @element ANY + * @priority 0 + * + * @description + * Specify custom behavior on mousemove event. + * + * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon + * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ - // model -> value - var ctrl = this; - $scope.$watch(function ngModelWatch() { - var value = ngModelGet($scope); + /** + * @ngdoc directive + * @name ngKeydown + * @restrict A + * @element ANY + * @priority 0 + * + * @description + * Specify custom behavior on keydown event. + * + * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon + * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + + + + key down count: {{count}} + + + */ - // if scope model value and ngModel value are out of sync - if (ctrl.$modelValue !== value) { - var formatters = ctrl.$formatters, - idx = formatters.length; + /** + * @ngdoc directive + * @name ngKeyup + * @restrict A + * @element ANY + * @priority 0 + * + * @description + * Specify custom behavior on keyup event. + * + * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon + * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + + +

    Typing in the input box below updates the key count

    + key up count: {{count}} - ctrl.$modelValue = value; - while(idx--) { - value = formatters[idx](value); - } +

    Typing in the input box below updates the keycode

    + +

    event keyCode: {{ event.keyCode }}

    +

    event altKey: {{ event.altKey }}

    +
    +
    + */ - if (ctrl.$viewValue !== value) { - ctrl.$viewValue = value; - ctrl.$render(); - } - } - return value; - }); - }]; + /** + * @ngdoc directive + * @name ngKeypress + * @restrict A + * @element ANY + * + * @description + * Specify custom behavior on keypress event. + * + * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon + * keypress. ({@link guide/expression#-event- Event object is available as `$event`} + * and can be interrogated for keyCode, altKey, etc.) + * + * @example + + + + key press count: {{count}} + + + */ /** * @ngdoc directive - * @name ngModel - * - * @element input + * @name ngSubmit + * @restrict A + * @element form + * @priority 0 * * @description - * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a - * property on the scope using {@link ngModel.NgModelController NgModelController}, - * which is created and exposed by this directive. + * Enables binding AngularJS expressions to onsubmit events. * - * `ngModel` is responsible for: + * Additionally it prevents the default action (which for form means sending the request to the + * server and reloading the current page), but only if the form does not contain `action`, + * `data-action`, or `x-action` attributes. * - * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` - * require. - * - Providing validation behavior (i.e. required, number, email, url). - * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors). - * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations. - * - Registering the control with its parent {@link ng.directive:form form}. + *
    + * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and + * `ngSubmit` handlers together. See the + * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} + * for a detailed discussion of when `ngSubmit` may be triggered. + *
    * - * Note: `ngModel` will try to bind to the property given by evaluating the expression on the - * current scope. If the property doesn't already exist on this scope, it will be created - * implicitly and added to the scope. + * @param {expression} ngSubmit {@link guide/expression Expression} to eval. + * ({@link guide/expression#-event- Event object is available as `$event`}) * - * For best practices on using `ngModel`, see: + * @example + + + +
    + Enter text and hit enter: + + +
    list={{list}}
    +
    +
    + + it('should check ng-submit', function() { + expect(element(by.binding('list')).getText()).toBe('list=[]'); + element(by.css('#submit')).click(); + expect(element(by.binding('list')).getText()).toContain('hello'); + expect(element(by.model('text')).getAttribute('value')).toBe(''); + }); + it('should ignore empty strings', function() { + expect(element(by.binding('list')).getText()).toBe('list=[]'); + element(by.css('#submit')).click(); + element(by.css('#submit')).click(); + expect(element(by.binding('list')).getText()).toContain('hello'); + }); + +
    + */ + + /** + * @ngdoc directive + * @name ngFocus + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 * - * - [https://github.com/angular/angular.js/wiki/Understanding-Scopes] + * @description + * Specify custom behavior on focus event. * - * For basic examples, how to use `ngModel`, see: + * Note: As the `focus` event is executed synchronously when calling `input.focus()` + * AngularJS executes the expression using `scope.$evalAsync` if the event is fired + * during an `$apply` to ensure a consistent state. * - * - {@link ng.directive:input input} - * - {@link input[text] text} - * - {@link input[checkbox] checkbox} - * - {@link input[radio] radio} - * - {@link input[number] number} - * - {@link input[email] email} - * - {@link input[url] url} - * - {@link ng.directive:select select} - * - {@link ng.directive:textarea textarea} + * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon + * focus. ({@link guide/expression#-event- Event object is available as `$event`}) * - * # CSS classes - * The following CSS classes are added and removed on the associated input/select/textarea element - * depending on the validity of the model. + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + /** + * @ngdoc directive + * @name ngBlur + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 * - * - `ng-valid` is set if the model is valid. - * - `ng-invalid` is set if the model is invalid. - * - `ng-pristine` is set if the model is pristine. - * - `ng-dirty` is set if the model is dirty. + * @description + * Specify custom behavior on blur event. * - * Keep in mind that ngAnimate can detect each of these classes when added and removed. + * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when + * an element has lost focus. * - * ## Animation Hooks + * Note: As the `blur` event is executed synchronously also during DOM manipulations + * (e.g. removing a focussed input), + * AngularJS executes the expression using `scope.$evalAsync` if the event is fired + * during an `$apply` to ensure a consistent state. * - * Animations within models are triggered when any of the associated CSS classes are added and removed - * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`, - * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. - * The animations that are triggered within ngModel are similar to how they work in ngClass and - * animations can be hooked into using CSS transitions, keyframes as well as JS animations. + * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon + * blur. ({@link guide/expression#-event- Event object is available as `$event`}) * - * The following example shows a simple way to utilize CSS transitions to style an input element - * that has been rendered as invalid after it has been validated: + * @example + * See {@link ng.directive:ngClick ngClick} + */ + + /** + * @ngdoc directive + * @name ngCopy + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 * - *
    -     * //be sure to include ngAnimate as a module to hook into more
    -     * //advanced animations
    -     * .my-input {
    - *   transition:0.5s linear all;
    - *   background: white;
    - * }
    -     * .my-input.ng-invalid {
    - *   background: red;
    - *   color:white;
    - * }
    -     * 
    + * @description + * Specify custom behavior on copy event. + * + * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon + * copy. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example - * + - - - Update input to see transitions when valid/invalid. - Integer is a valid value. -
    - -
    + + copied: {{copied}}
    - *
    +
    */ - var ngModelDirective = function() { - return { - require: ['ngModel', '^?form'], - controller: NgModelController, - link: function(scope, element, attr, ctrls) { - // notify others, especially parent forms - - var modelCtrl = ctrls[0], - formCtrl = ctrls[1] || nullFormCtrl; - formCtrl.$addControl(modelCtrl); - - scope.$on('$destroy', function() { - formCtrl.$removeControl(modelCtrl); - }); - } - }; - }; + /** + * @ngdoc directive + * @name ngCut + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 + * + * @description + * Specify custom behavior on cut event. + * + * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon + * cut. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + cut: {{cut}} + + + */ + /** + * @ngdoc directive + * @name ngPaste + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 + * + * @description + * Specify custom behavior on paste event. + * + * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon + * paste. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + pasted: {{paste}} + + + */ /** * @ngdoc directive - * @name ngChange + * @name ngIf + * @restrict A + * @multiElement * * @description - * Evaluate the given expression when the user changes the input. - * The expression is evaluated immediately, unlike the JavaScript onchange event - * which only triggers at the end of a change (usually, when the user leaves the - * form element or presses the return key). - * The expression is not evaluated when the value change is coming from the model. + * The `ngIf` directive removes or recreates a portion of the DOM tree based on an + * {expression}. If the expression assigned to `ngIf` evaluates to a false + * value then the element is removed from the DOM, otherwise a clone of the + * element is reinserted into the DOM. + * + * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the + * element in the DOM rather than changing its visibility via the `display` css property. A common + * case when this difference is significant is when using css selectors that rely on an element's + * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. * - * Note, this directive requires `ngModel` to be present. + * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope + * is created when the element is restored. The scope created within `ngIf` inherits from + * its parent scope using + * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance). + * An important implication of this is if `ngModel` is used within `ngIf` to bind to + * a javascript primitive defined in the parent scope. In this case any modifications made to the + * variable within the child scope will override (hide) the value in the parent scope. * - * @element input - * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change - * in input value. + * Also, `ngIf` recreates elements using their compiled state. An example of this behavior + * is if an element's class attribute is directly modified after it's compiled, using something like + * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element + * the added class will be lost because the original compiled state is used to regenerate the element. * - * @example - * - * - * - *
    - * - * - *
    - * debug = {{confirmed}}
    - * counter = {{counter}}
    - *
    - *
    - * - * var counter = element(by.binding('counter')); - * var debug = element(by.binding('confirmed')); + * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` + * and `leave` effects. * - * it('should evaluate the expression if changing from view', function() { - * expect(counter.getText()).toContain('0'); - * - * element(by.id('ng-change-example1')).click(); - * - * expect(counter.getText()).toContain('1'); - * expect(debug.getText()).toContain('true'); - * }); + * @animations + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container | + * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM | * - * it('should not evaluate the expression if changing from model', function() { - * element(by.id('ng-change-example2')).click(); + * @element ANY + * @scope + * @priority 600 + * @param {expression} ngIf If the {@link guide/expression expression} is falsy then + * the element is removed from the DOM tree. If it is truthy a copy of the compiled + * element is added to the DOM tree. + * + * @example + + +
    + Show when checked: + + This is removed when the checkbox is unchecked. + +
    + + .animate-if { + background:white; + border:1px solid black; + padding:10px; + } - * expect(counter.getText()).toContain('0'); - * expect(debug.getText()).toContain('true'); - * }); - * - *
    - */ - var ngChangeDirective = valueFn({ - require: 'ngModel', - link: function(scope, element, attr, ctrl) { - ctrl.$viewChangeListeners.push(function() { - scope.$eval(attr.ngChange); - }); - } - }); + .animate-if.ng-enter, .animate-if.ng-leave { + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + .animate-if.ng-enter, + .animate-if.ng-leave.ng-leave-active { + opacity:0; + } - var requiredDirective = function() { + .animate-if.ng-leave, + .animate-if.ng-enter.ng-enter-active { + opacity:1; + } +
    +
    + */ + var ngIfDirective = ['$animate', '$compile', function($animate, $compile) { return { - require: '?ngModel', - link: function(scope, elm, attr, ctrl) { - if (!ctrl) return; - attr.required = true; // force truthy in case we are on non input element + multiElement: true, + transclude: 'element', + priority: 600, + terminal: true, + restrict: 'A', + $$tlb: true, + link: function($scope, $element, $attr, ctrl, $transclude) { + var block, childScope, previousElements; + $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { - var validator = function(value) { - if (attr.required && ctrl.$isEmpty(value)) { - ctrl.$setValidity('required', false); - return; + if (value) { + if (!childScope) { + $transclude(function(clone, newScope) { + childScope = newScope; + clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf); + // Note: We only need the first/last node of the cloned nodes. + // However, we need to keep the reference to the jqlite wrapper as it might be changed later + // by a directive with templateUrl when its template arrives. + block = { + clone: clone + }; + $animate.enter(clone, $element.parent(), $element); + }); + } } else { - ctrl.$setValidity('required', true); - return value; + if (previousElements) { + previousElements.remove(); + previousElements = null; + } + if (childScope) { + childScope.$destroy(); + childScope = null; + } + if (block) { + previousElements = getBlockNodes(block.clone); + $animate.leave(previousElements).done(function(response) { + if (response !== false) previousElements = null; + }); + block = null; + } } - }; - - ctrl.$formatters.push(validator); - ctrl.$parsers.unshift(validator); - - attr.$observe('required', function() { - validator(ctrl.$viewValue); }); } }; - }; - + }]; /** * @ngdoc directive - * @name ngList + * @name ngInclude + * @restrict ECA + * @scope + * @priority -400 * * @description - * Text input that converts between a delimited string and an array of strings. The delimiter - * can be a fixed string (by default a comma) or a regular expression. + * Fetches, compiles and includes an external HTML fragment. + * + * By default, the template URL is restricted to the same domain and protocol as the + * application document. This is done by calling {@link $sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols + * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or + * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to AngularJS's {@link + * ng.$sce Strict Contextual Escaping}. + * + * In addition, the browser's + * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) + * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) + * policy may further restrict whether the template is successfully loaded. + * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` + * access on some browsers. + * + * @animations + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#enter enter} | when the expression changes, on the new include | + * | {@link ng.$animate#leave leave} | when the expression changes, on the old include | + * + * The enter and leave animation occur concurrently. + * + * @param {string} ngInclude|src AngularJS expression evaluating to URL. If the source is a string constant, + * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. + * @param {string=} onload Expression to evaluate when a new partial is loaded. + *
    + * **Note:** When using onload on SVG elements in IE11, the browser will try to call + * a function with the name on the window element, which will usually throw a + * "function is undefined" error. To fix this, you can instead use `data-onload` or a + * different form that {@link guide/directive#normalization matches} `onload`. + *
    * - * @element input - * @param {string=} ngList optional delimiter that should be used to split the value. If - * specified in form `/something/` then the value will be converted into a regular expression. + * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll + * $anchorScroll} to scroll the viewport after the content is loaded. + * + * - If the attribute is not set, disable scrolling. + * - If the attribute is set without value, enable scrolling. + * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example - + - -
    - List: - - Required! -
    - names = {{names}}
    - myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
    - myForm.namesInput.$error = {{myForm.namesInput.$error}}
    - myForm.$valid = {{myForm.$valid}}
    - myForm.$error.required = {{!!myForm.$error.required}}
    -
    +
    + + url of the template: {{template.url}} +
    +
    +
    +
    +
    +
    + + angular.module('includeExample', ['ngAnimate']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.templates = + [{ name: 'template1.html', url: 'template1.html'}, + { name: 'template2.html', url: 'template2.html'}]; + $scope.template = $scope.templates[0]; + }]); + + + Content of template1.html + + + Content of template2.html + + + .slide-animate-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .slide-animate { + padding:10px; + } + + .slide-animate.ng-enter, .slide-animate.ng-leave { + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + display:block; + padding:10px; + } + + .slide-animate.ng-enter { + top:-50px; + } + .slide-animate.ng-enter.ng-enter-active { + top:0; + } + + .slide-animate.ng-leave { + top:0; + } + .slide-animate.ng-leave.ng-leave-active { + top:50px; + } - var listInput = element(by.model('names')); - var names = element(by.binding('{{names}}')); - var valid = element(by.binding('myForm.namesInput.$valid')); - var error = element(by.css('span.error')); + var templateSelect = element(by.model('template')); + var includeElem = element(by.css('[ng-include]')); - it('should initialize to model', function() { - expect(names.getText()).toContain('["igor","misko","vojta"]'); - expect(valid.getText()).toContain('true'); - expect(error.getCssValue('display')).toBe('none'); - }); + it('should load template1.html', function() { + expect(includeElem.getText()).toMatch(/Content of template1.html/); + }); - it('should be invalid if empty', function() { - listInput.clear(); - listInput.sendKeys(''); + it('should load template2.html', function() { + if (browser.params.browser === 'firefox') { + // Firefox can't handle using selects + // See https://github.com/angular/protractor/issues/480 + return; + } + templateSelect.click(); + templateSelect.all(by.css('option')).get(2).click(); + expect(includeElem.getText()).toMatch(/Content of template2.html/); + }); - expect(names.getText()).toContain(''); - expect(valid.getText()).toContain('false'); - expect(error.getCssValue('display')).not.toBe('none'); }); + it('should change to blank', function() { + if (browser.params.browser === 'firefox') { + // Firefox can't handle using selects + return; + } + templateSelect.click(); + templateSelect.all(by.css('option')).get(0).click(); + expect(includeElem.isPresent()).toBe(false); + });
    */ - var ngListDirective = function() { - return { - require: 'ngModel', - link: function(scope, element, attr, ctrl) { - var match = /\/(.*)\//.exec(attr.ngList), - separator = match && new RegExp(match[1]) || attr.ngList || ','; - var parse = function(viewValue) { - // If the viewValue is invalid (say required but empty) it will be `undefined` - if (isUndefined(viewValue)) return; - var list = []; + /** + * @ngdoc event + * @name ngInclude#$includeContentRequested + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted every time the ngInclude content is requested. + * + * @param {Object} angularEvent Synthetic event object. + * @param {String} src URL of content to load. + */ + + + /** + * @ngdoc event + * @name ngInclude#$includeContentLoaded + * @eventType emit on the current ngInclude scope + * @description + * Emitted every time the ngInclude content is reloaded. + * + * @param {Object} angularEvent Synthetic event object. + * @param {String} src URL of content to load. + */ + + + /** + * @ngdoc event + * @name ngInclude#$includeContentError + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299) + * + * @param {Object} angularEvent Synthetic event object. + * @param {String} src URL of content to load. + */ + var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', + function($templateRequest, $anchorScroll, $animate) { + return { + restrict: 'ECA', + priority: 400, + terminal: true, + transclude: 'element', + controller: angular.noop, + compile: function(element, attr) { + var srcExp = attr.ngInclude || attr.src, + onloadExp = attr.onload || '', + autoScrollExp = attr.autoscroll; - if (viewValue) { - forEach(viewValue.split(separator), function(value) { - if (value) list.push(trim(value)); - }); - } + return function(scope, $element, $attr, ctrl, $transclude) { + var changeCounter = 0, + currentScope, + previousElement, + currentElement; - return list; - }; + var cleanupLastIncludeContent = function() { + if (previousElement) { + previousElement.remove(); + previousElement = null; + } + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if (currentElement) { + $animate.leave(currentElement).done(function(response) { + if (response !== false) previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + }; - ctrl.$parsers.push(parse); - ctrl.$formatters.push(function(value) { - if (isArray(value)) { - return value.join(', '); - } + scope.$watch(srcExp, function ngIncludeWatchAction(src) { + var afterAnimation = function(response) { + if (response !== false && isDefined(autoScrollExp) && + (!autoScrollExp || scope.$eval(autoScrollExp))) { + $anchorScroll(); + } + }; + var thisChangeId = ++changeCounter; - return undefined; - }); + if (src) { + //set the 2nd param to true to ignore the template request error so that the inner + //contents and scope can be cleaned up. + $templateRequest(src, true).then(function(response) { + if (scope.$$destroyed) return; - // Override the standard $isEmpty because an empty array means the input is empty. - ctrl.$isEmpty = function(value) { - return !value || !value.length; - }; - } - }; - }; + if (thisChangeId !== changeCounter) return; + var newScope = scope.$new(); + ctrl.template = response; + // Note: This will also link all children of ng-include that were contained in the original + // html. If that content contains controllers, ... they could pollute/change the scope. + // However, using ng-include on an element with additional content does not make sense... + // Note: We can't remove them in the cloneAttchFn of $transclude as that + // function is called before linking the content, which would apply child + // directives to non existing elements. + var clone = $transclude(newScope, function(clone) { + cleanupLastIncludeContent(); + $animate.enter(clone, null, $element).done(afterAnimation); + }); - var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; - /** - * @ngdoc directive - * @name ngValue - * - * @description - * Binds the given expression to the value of `input[select]` or `input[radio]`, so - * that when the element is selected, the `ngModel` of that element is set to the - * bound value. - * - * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as - * shown below. - * - * @element input - * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute - * of the `input` element - * - * @example - - - -
    -

    Which is your favorite?

    - -
    You chose {{my.favorite}}
    -
    -
    - - var favorite = element(by.binding('my.favorite')); + currentScope = newScope; + currentElement = clone; - it('should initialize to model', function() { - expect(favorite.getText()).toContain('unicorns'); - }); - it('should bind the values to the inputs', function() { - element.all(by.model('my.favorite')).get(0).click(); - expect(favorite.getText()).toContain('pizza'); - }); - -
    - */ - var ngValueDirective = function() { - return { - priority: 100, - compile: function(tpl, tplAttr) { - if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { - return function ngValueConstantLink(scope, elm, attr) { - attr.$set('value', scope.$eval(attr.ngValue)); - }; - } else { - return function ngValueLink(scope, elm, attr) { - scope.$watch(attr.ngValue, function valueWatchAction(value) { - attr.$set('value', value); + currentScope.$emit('$includeContentLoaded', src); + scope.$eval(onloadExp); + }, function() { + if (scope.$$destroyed) return; + + if (thisChangeId === changeCounter) { + cleanupLastIncludeContent(); + scope.$emit('$includeContentError', src); + } + }); + scope.$emit('$includeContentRequested', src); + } else { + cleanupLastIncludeContent(); + ctrl.template = null; + } }); }; } - } - }; - }; + }; + }]; + +// This directive is called during the $transclude call of the first `ngInclude` directive. +// It will replace and compile the content of the element with the loaded template. +// We need this directive so that the element content is already filled when +// the link function of another directive on the same element as ngInclude +// is called. + var ngIncludeFillContentDirective = ['$compile', + function($compile) { + return { + restrict: 'ECA', + priority: -400, + require: 'ngInclude', + link: function(scope, $element, $attr, ctrl) { + if (toString.call($element[0]).match(/SVG/)) { + // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not + // support innerHTML, so detect this here and try to generate the contents + // specially. + $element.empty(); + $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope, + function namespaceAdaptedClone(clone) { + $element.append(clone); + }, {futureParentElement: $element}); + return; + } + + $element.html(ctrl.template); + $compile($element.contents())(scope); + } + }; + }]; /** * @ngdoc directive - * @name ngBind + * @name ngInit * @restrict AC - * - * @description - * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element - * with the value of a given expression, and to update the text content when the value of that - * expression changes. - * - * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like - * `{{ expression }}` which is similar but less verbose. - * - * It is preferable to use `ngBind` instead of `{{ expression }}` when a template is momentarily - * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an - * element attribute, it makes the bindings invisible to the user while the page is loading. - * - * An alternative solution to this problem would be using the - * {@link ng.directive:ngCloak ngCloak} directive. - * - * + * @priority 450 * @element ANY - * @param {expression} ngBind {@link guide/expression Expression} to evaluate. * - * @example - * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. - - - -
    - Enter name:
    - Hello ! -
    -
    - - it('should check ng-bind', function() { - var nameInput = element(by.model('name')); - - expect(element(by.binding('name')).getText()).toBe('Whirled'); - nameInput.clear(); - nameInput.sendKeys('world'); - expect(element(by.binding('name')).getText()).toBe('world'); - }); - -
    - */ - var ngBindDirective = ngDirective(function(scope, element, attr) { - element.addClass('ng-binding').data('$binding', attr.ngBind); - scope.$watch(attr.ngBind, function ngBindWatchAction(value) { - // We are purposefully using == here rather than === because we want to - // catch when value is "null or undefined" - // jshint -W041 - element.text(value == undefined ? '' : value); - }); - }); - - - /** - * @ngdoc directive - * @name ngBindTemplate + * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @description - * The `ngBindTemplate` directive specifies that the element - * text content should be replaced with the interpolation of the template - * in the `ngBindTemplate` attribute. - * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` - * expressions. This directive is needed since some HTML elements - * (such as TITLE and OPTION) cannot contain SPAN elements. + * The `ngInit` directive allows you to evaluate an expression in the + * current scope. * - * @element ANY - * @param {string} ngBindTemplate template of form - * {{ expression }} to eval. + *
    + * This directive can be abused to add unnecessary amounts of logic into your templates. + * There are only a few appropriate uses of `ngInit`: + *
      + *
    • aliasing special properties of {@link ng.directive:ngRepeat `ngRepeat`}, + * as seen in the demo below.
    • + *
    • initializing data during development, or for examples, as seen throughout these docs.
    • + *
    • injecting data via server side scripting.
    • + *
    + * + * Besides these few cases, you should use {@link guide/component Components} or + * {@link guide/controller Controllers} rather than `ngInit` to initialize values on a scope. + *
    + * + *
    + * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make + * sure you have parentheses to ensure correct operator precedence: + *
    +     * `
    ` + *
    + *
    * * @example - * Try it here: enter text in text box and watch the greeting change. - + -
    - Salutation:
    - Name:
    -
    
    +     
    +
    +
    + list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}}; +
    +
    - it('should check ng-bind', function() { - var salutationElem = element(by.binding('salutation')); - var salutationInput = element(by.model('salutation')); - var nameInput = element(by.model('name')); - - expect(salutationElem.getText()).toBe('Hello World!'); - - salutationInput.clear(); - salutationInput.sendKeys('Greetings'); - nameInput.clear(); - nameInput.sendKeys('user'); - - expect(salutationElem.getText()).toBe('Greetings user!'); + it('should alias index positions', function() { + var elements = element.all(by.css('.example-init')); + expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); + expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); + expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); + expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); }); */ - var ngBindTemplateDirective = ['$interpolate', function($interpolate) { - return function(scope, element, attr) { - // TODO: move this to scenario runner - var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); - element.addClass('ng-binding').data('$binding', interpolateFn); - attr.$observe('ngBindTemplate', function(value) { - element.text(value); - }); - }; - }]; - + var ngInitDirective = ngDirective({ + priority: 450, + compile: function() { + return { + pre: function(scope, element, attrs) { + scope.$eval(attrs.ngInit); + } + }; + } + }); /** * @ngdoc directive - * @name ngBindHtml + * @name ngList + * @restrict A + * @priority 100 + * + * @param {string=} ngList optional delimiter that should be used to split the value. * * @description - * Creates a binding that will innerHTML the result of evaluating the `expression` into the current - * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link - * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` - * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in - * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to - * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example - * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. + * Text input that converts between a delimited string and an array of strings. The default + * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom + * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`. + * + * The behaviour of the directive is affected by the use of the `ngTrim` attribute. + * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each + * list item is respected. This implies that the user of the directive is responsible for + * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a + * tab or newline character. + * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected + * when joining the list items back together) and whitespace around each list item is stripped + * before it is added to the model. * - * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you - * will have an exception (instead of an exploit.) + * @example + * ### Validation + * + * + * + * angular.module('listExample', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.names = ['morpheus', 'neo', 'trinity']; + * }]); + * + * + *
    + * + * + * + * Required! + * + *
    + * names = {{names}}
    + * myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
    + * myForm.namesInput.$error = {{myForm.namesInput.$error}}
    + * myForm.$valid = {{myForm.$valid}}
    + * myForm.$error.required = {{!!myForm.$error.required}}
    + *
    + *
    + * + * var listInput = element(by.model('names')); + * var names = element(by.exactBinding('names')); + * var valid = element(by.binding('myForm.namesInput.$valid')); + * var error = element(by.css('span.error')); + * + * it('should initialize to model', function() { + * expect(names.getText()).toContain('["morpheus","neo","trinity"]'); + * expect(valid.getText()).toContain('true'); + * expect(error.getCssValue('display')).toBe('none'); + * }); * - * @element ANY - * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. + * it('should be invalid if empty', function() { + * listInput.clear(); + * listInput.sendKeys(''); + * + * expect(names.getText()).toContain(''); + * expect(valid.getText()).toContain('false'); + * expect(error.getCssValue('display')).not.toBe('none'); + * }); + * + *
    * * @example - Try it here: enter text in text box and watch the greeting change. + * ### Splitting on newline + * + * + * + * + *
    {{ list | json }}
    + *
    + * + * it("should split the text by newlines", function() { + * var listInput = element(by.model('list')); + * var output = element(by.binding('list | json')); + * listInput.sendKeys('abc\ndef\nghi'); + * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]'); + * }); + * + *
    + * + */ + var ngListDirective = function() { + return { + restrict: 'A', + priority: 100, + require: 'ngModel', + link: function(scope, element, attr, ctrl) { + var ngList = attr.ngList || ', '; + var trimValues = attr.ngTrim !== 'false'; + var separator = trimValues ? trim(ngList) : ngList; - - -
    -

    -
    -
    + var parse = function(viewValue) { + // If the viewValue is invalid (say required but empty) it will be `undefined` + if (isUndefined(viewValue)) return; - - angular.module('ngBindHtmlExample', ['ngSanitize']) + var list = []; - .controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) { - $scope.myHTML = - 'I am an HTMLstring with links! and other stuff'; - }]); - + if (viewValue) { + forEach(viewValue.split(separator), function(value) { + if (value) list.push(trimValues ? trim(value) : value); + }); + } - - it('should check ng-bind-html', function() { - expect(element(by.binding('myHTML')).getText()).toBe( - 'I am an HTMLstring with links! and other stuff'); - }); - -
    - */ - var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) { - return function(scope, element, attr) { - element.addClass('ng-binding').data('$binding', attr.ngBindHtml); + return list; + }; - var parsed = $parse(attr.ngBindHtml); - function getStringValue() { return (parsed(scope) || '').toString(); } + ctrl.$parsers.push(parse); + ctrl.$formatters.push(function(value) { + if (isArray(value)) { + return value.join(ngList); + } - scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) { - element.html($sce.getTrustedHtml(parsed(scope)) || ''); - }); - }; - }]; + return undefined; + }); - function classDirective(name, selector) { - name = 'ngClass' + name; - return ['$animate', function($animate) { - return { - restrict: 'AC', - link: function(scope, element, attr) { - var oldVal; + // Override the standard $isEmpty because an empty array means the input is empty. + ctrl.$isEmpty = function(value) { + return !value || !value.length; + }; + } + }; + }; - scope.$watch(attr[name], ngClassWatchAction, true); + /* global VALID_CLASS: true, + INVALID_CLASS: true, + PRISTINE_CLASS: true, + DIRTY_CLASS: true, + UNTOUCHED_CLASS: true, + TOUCHED_CLASS: true, + PENDING_CLASS: true, + addSetValidityMethod: true, + setupValidity: true, + defaultModelOptions: false +*/ - attr.$observe('class', function(value) { - ngClassWatchAction(scope.$eval(attr[name])); - }); + var VALID_CLASS = 'ng-valid', + INVALID_CLASS = 'ng-invalid', + PRISTINE_CLASS = 'ng-pristine', + DIRTY_CLASS = 'ng-dirty', + UNTOUCHED_CLASS = 'ng-untouched', + TOUCHED_CLASS = 'ng-touched', + EMPTY_CLASS = 'ng-empty', + NOT_EMPTY_CLASS = 'ng-not-empty'; - if (name !== 'ngClass') { - scope.$watch('$index', function($index, old$index) { - // jshint bitwise: false - var mod = $index & 1; - if (mod !== old$index & 1) { - var classes = arrayClasses(scope.$eval(attr[name])); - mod === selector ? - addClasses(classes) : - removeClasses(classes); - } - }); - } + var ngModelMinErr = minErr('ngModel'); - function addClasses(classes) { - var newClasses = digestClassCounts(classes, 1); - attr.$addClass(newClasses); - } + /** + * @ngdoc type + * @name ngModel.NgModelController + * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a + * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue + * is set. + * + * @property {*} $modelValue The value in the model that the control is bound to. + * + * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever + * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue + `$viewValue`} from the DOM, usually via user input. + See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation. + Note that the `$parsers` are not called when the bound ngModel expression changes programmatically. - function removeClasses(classes) { - var newClasses = digestClassCounts(classes, -1); - attr.$removeClass(newClasses); - } + The functions are called in array order, each passing + its return value through to the next. The last return value is forwarded to the + {@link ngModel.NgModelController#$validators `$validators`} collection. - function digestClassCounts (classes, count) { - var classCounts = element.data('$classCounts') || {}; - var classesToUpdate = []; - forEach(classes, function (className) { - if (count > 0 || classCounts[className]) { - classCounts[className] = (classCounts[className] || 0) + count; - if (classCounts[className] === +(count > 0)) { - classesToUpdate.push(className); - } - } - }); - element.data('$classCounts', classCounts); - return classesToUpdate.join(' '); - } + Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue + `$viewValue`}. - function updateClasses (oldClasses, newClasses) { - var toAdd = arrayDifference(newClasses, oldClasses); - var toRemove = arrayDifference(oldClasses, newClasses); - toRemove = digestClassCounts(toRemove, -1); - toAdd = digestClassCounts(toAdd, 1); + Returning `undefined` from a parser means a parse error occurred. In that case, + no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel` + will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`} + is set to `true`. The parse error is stored in `ngModel.$error.parse`. - if (toAdd.length === 0) { - $animate.removeClass(element, toRemove); - } else if (toRemove.length === 0) { - $animate.addClass(element, toAdd); - } else { - $animate.setClass(element, toAdd, toRemove); - } - } + This simple example shows a parser that would convert text input value to lowercase: + * ```js + * function parse(value) { + * if (value) { + * return value.toLowerCase(); + * } + * } + * ngModelController.$parsers.push(parse); + * ``` - function ngClassWatchAction(newVal) { - if (selector === true || scope.$index % 2 === selector) { - var newClasses = arrayClasses(newVal || []); - if (!oldVal) { - addClasses(newClasses); - } else if (!equals(newVal,oldVal)) { - var oldClasses = arrayClasses(oldVal); - updateClasses(oldClasses, newClasses); - } - } - oldVal = copy(newVal); - } - } - }; + * + * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever + the bound ngModel expression changes programmatically. The `$formatters` are not called when the + value of the control is changed by user interaction. - function arrayDifference(tokens1, tokens2) { - var values = []; + Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue + `$modelValue`} for display in the control. - outer: - for(var i = 0; i < tokens1.length; i++) { - var token = tokens1[i]; - for(var j = 0; j < tokens2.length; j++) { - if(token == tokens2[j]) continue outer; - } - values.push(token); - } - return values; - } + The functions are called in reverse array order, each passing the value through to the + next. The last return value is used as the actual DOM value. - function arrayClasses (classVal) { - if (isArray(classVal)) { - return classVal; - } else if (isString(classVal)) { - return classVal.split(' '); - } else if (isObject(classVal)) { - var classes = [], i = 0; - forEach(classVal, function(v, k) { - if (v) { - classes.push(k); - } - }); - return classes; - } - return classVal; - } - }]; - } + This simple example shows a formatter that would convert the model value to uppercase: - /** - * @ngdoc directive - * @name ngClass - * @restrict AC + * ```js + * function format(value) { + * if (value) { + * return value.toUpperCase(); + * } + * } + * ngModel.$formatters.push(format); + * ``` * - * @description - * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding - * an expression that represents all classes to be added. + * @property {Object.} $validators A collection of validators that are applied + * whenever the model value changes. The key value within the object refers to the name of the + * validator while the function refers to the validation operation. The validation operation is + * provided with the model value as an argument and must return a true or false value depending + * on the response of that validation. * - * The directive operates in three different ways, depending on which of three types the expression - * evaluates to: + * ```js + * ngModel.$validators.validCharacters = function(modelValue, viewValue) { + * var value = modelValue || viewValue; + * return /[0-9]+/.test(value) && + * /[a-z]+/.test(value) && + * /[A-Z]+/.test(value) && + * /\W+/.test(value); + * }; + * ``` * - * 1. If the expression evaluates to a string, the string should be one or more space-delimited class - * names. + * @property {Object.} $asyncValidators A collection of validations that are expected to + * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided + * is expected to return a promise when it is run during the model validation process. Once the promise + * is delivered then the validation status will be set to true when fulfilled and false when rejected. + * When the asynchronous validators are triggered, each of the validators will run in parallel and the model + * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator + * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators + * will only run once all synchronous validators have passed. * - * 2. If the expression evaluates to an array, each element of the array should be a string that is - * one or more space-delimited class names. + * Please note that if $http is used then it is important that the server returns a success HTTP response code + * in order to fulfill the validation and a status level of `4xx` in order to reject the validation. * - * 3. If the expression evaluates to an object, then for each key-value pair of the - * object with a truthy value the corresponding key is used as a class name. + * ```js + * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { + * var value = modelValue || viewValue; + * + * // Lookup user by username + * return $http.get('/api/users/' + value). + * then(function resolved() { + * //username exists, this means validation fails + * return $q.reject('exists'); + * }, function rejected() { + * //username does not exist, therefore this validation passes + * return true; + * }); + * }; + * ``` * - * The directive won't add duplicate classes if a particular class was already set. + * @property {Array.} $viewChangeListeners Array of functions to execute whenever + * a change to {@link ngModel.NgModelController#$viewValue `$viewValue`} has caused a change + * to {@link ngModel.NgModelController#$modelValue `$modelValue`}. + * It is called with no arguments, and its return value is ignored. + * This can be used in place of additional $watches against the model value. * - * When the expression changes, the previously added classes are removed and only then the - * new classes are added. + * @property {Object} $error An object hash with all failing validator ids as keys. + * @property {Object} $pending An object hash with all pending validator ids as keys. * - * @animations - * add - happens just before the class is applied to the element - * remove - happens just before the class is removed from the element + * @property {boolean} $untouched True if control has not lost focus yet. + * @property {boolean} $touched True if control has lost focus. + * @property {boolean} $pristine True if user has not interacted with the control yet. + * @property {boolean} $dirty True if user has already interacted with the control. + * @property {boolean} $valid True if there is no error. + * @property {boolean} $invalid True if at least one error on the control. + * @property {string} $name The name attribute of the control. * - * @element ANY - * @param {expression} ngClass {@link guide/expression Expression} to eval. The result - * of the evaluation can be a string representing space delimited class - * names, an array, or a map of class names to boolean values. In the case of a map, the - * names of the properties whose values are truthy will be added as css classes to the - * element. + * @description + * + * `NgModelController` provides API for the {@link ngModel `ngModel`} directive. + * The controller contains services for data-binding, validation, CSS updates, and value formatting + * and parsing. It purposefully does not contain any logic which deals with DOM rendering or + * listening to DOM events. + * Such DOM related logic should be provided by other directives which make use of + * `NgModelController` for data-binding to control elements. + * AngularJS provides this DOM logic for most {@link input `input`} elements. + * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example + * custom control example} that uses `ngModelController` to bind to `contenteditable` elements. + * + * @example + * ### Custom Control Example + * This example shows how to use `NgModelController` with a custom control to achieve + * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) + * collaborate together to achieve the desired result. + * + * `contenteditable` is an HTML5 attribute, which tells the browser to let the element + * contents be edited in place by the user. * - * @example Example that demonstrates basic bindings via ngClass directive. - + * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} + * module to automatically remove "bad" content like inline event listener (e.g. ``). + * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks + * that content using the `$sce` service. + * + * + + [contenteditable] { + border: 1px solid black; + background-color: white; + min-height: 20px; + } + + .ng-invalid { + border: 1px solid red; + } + + + + angular.module('customControl', ['ngSanitize']). + directive('contenteditable', ['$sce', function($sce) { + return { + restrict: 'A', // only activate on element attribute + require: '?ngModel', // get a hold of NgModelController + link: function(scope, element, attrs, ngModel) { + if (!ngModel) return; // do nothing if no ng-model + + // Specify how UI should be updated + ngModel.$render = function() { + element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); + }; + + // Listen for change events to enable binding + element.on('blur keyup change', function() { + scope.$evalAsync(read); + }); + read(); // initialize + + // Write data to the model + function read() { + var html = element.html(); + // When we clear the content editable the browser leaves a
    behind + // If strip-br attribute is provided then we strip this out + if (attrs.stripBr && html === '
    ') { + html = ''; + } + ngModel.$setViewValue(html); + } + } + }; + }]); +
    -

    Map Syntax Example

    - deleted (apply "strike" class)
    - important (apply "bold" class)
    - error (apply "red" class) -
    -

    Using String Syntax

    - +
    +
    Change me!
    + Required!
    -

    Using Array Syntax

    -
    -
    -
    + +
    - - .strike { - text-decoration: line-through; - } - .bold { - font-weight: bold; - } - .red { - color: red; - } + + it('should data-bind and become invalid', function() { + if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') { + // SafariDriver can't handle contenteditable + // and Firefox driver can't clear contenteditables very well + return; + } + var contentEditable = element(by.css('[contenteditable]')); + var content = 'Change me!'; + + expect(contentEditable.getText()).toEqual(content); + + contentEditable.clear(); + contentEditable.sendKeys(protractor.Key.BACK_SPACE); + expect(contentEditable.getText()).toEqual(''); + expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); + }); - - var ps = element.all(by.css('p')); + *
    + * + * + */ + NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate']; + function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) { + this.$viewValue = Number.NaN; + this.$modelValue = Number.NaN; + this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity. + this.$validators = {}; + this.$asyncValidators = {}; + this.$parsers = []; + this.$formatters = []; + this.$viewChangeListeners = []; + this.$untouched = true; + this.$touched = false; + this.$pristine = true; + this.$dirty = false; + this.$valid = true; + this.$invalid = false; + this.$error = {}; // keep invalid keys here + this.$$success = {}; // keep valid keys here + this.$pending = undefined; // keep pending keys here + this.$name = $interpolate($attr.name || '', false)($scope); + this.$$parentForm = nullFormCtrl; + this.$options = defaultModelOptions; + this.$$updateEvents = ''; + // Attach the correct context to the event handler function for updateOn + this.$$updateEventHandler = this.$$updateEventHandler.bind(this); + + this.$$parsedNgModel = $parse($attr.ngModel); + this.$$parsedNgModelAssign = this.$$parsedNgModel.assign; + this.$$ngModelGet = this.$$parsedNgModel; + this.$$ngModelSet = this.$$parsedNgModelAssign; + this.$$pendingDebounce = null; + this.$$parserValid = undefined; + + this.$$currentValidationRunId = 0; + + // https://github.com/angular/angular.js/issues/15833 + // Prevent `$$scope` from being iterated over by `copy` when NgModelController is deep watched + Object.defineProperty(this, '$$scope', {value: $scope}); + this.$$attr = $attr; + this.$$element = $element; + this.$$animate = $animate; + this.$$timeout = $timeout; + this.$$parse = $parse; + this.$$q = $q; + this.$$exceptionHandler = $exceptionHandler; + + setupValidity(this); + setupModelWatcher(this); + } - it('should let you toggle the class', function() { + NgModelController.prototype = { + $$initGetterSetters: function() { + if (this.$options.getOption('getterSetter')) { + var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'), + invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)'); - expect(ps.first().getAttribute('class')).not.toMatch(/bold/); - expect(ps.first().getAttribute('class')).not.toMatch(/red/); + this.$$ngModelGet = function($scope) { + var modelValue = this.$$parsedNgModel($scope); + if (isFunction(modelValue)) { + modelValue = invokeModelGetter($scope); + } + return modelValue; + }; + this.$$ngModelSet = function($scope, newValue) { + if (isFunction(this.$$parsedNgModel($scope))) { + invokeModelSetter($scope, {$$$p: newValue}); + } else { + this.$$parsedNgModelAssign($scope, newValue); + } + }; + } else if (!this.$$parsedNgModel.assign) { + throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}', + this.$$attr.ngModel, startingTag(this.$$element)); + } + }, - element(by.model('important')).click(); - expect(ps.first().getAttribute('class')).toMatch(/bold/); - element(by.model('error')).click(); - expect(ps.first().getAttribute('class')).toMatch(/red/); - }); + /** + * @ngdoc method + * @name ngModel.NgModelController#$render + * + * @description + * Called when the view needs to be updated. It is expected that the user of the ng-model + * directive will implement this method. + * + * The `$render()` method is invoked in the following situations: + * + * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last + * committed value then `$render()` is called to update the input control. + * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and + * the `$viewValue` are different from last time. + * + * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of + * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue` + * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be + * invoked if you only change a property on the objects. + */ + $render: noop, - it('should let you toggle string example', function() { - expect(ps.get(1).getAttribute('class')).toBe(''); - element(by.model('style')).clear(); - element(by.model('style')).sendKeys('red'); - expect(ps.get(1).getAttribute('class')).toBe('red'); - }); + /** + * @ngdoc method + * @name ngModel.NgModelController#$isEmpty + * + * @description + * This is called when we need to determine if the value of an input is empty. + * + * For instance, the required directive does this to work out if the input has data or not. + * + * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. + * + * You can override this for input directives whose concept of being empty is different from the + * default. The `checkboxInputType` directive does this because in its case a value of `false` + * implies empty. + * + * @param {*} value The value of the input to check for emptiness. + * @returns {boolean} True if `value` is "empty". + */ + $isEmpty: function(value) { + // eslint-disable-next-line no-self-compare + return isUndefined(value) || value === '' || value === null || value !== value; + }, - it('array example should have 3 classes', function() { - expect(ps.last().getAttribute('class')).toBe(''); - element(by.model('style1')).sendKeys('bold'); - element(by.model('style2')).sendKeys('strike'); - element(by.model('style3')).sendKeys('red'); - expect(ps.last().getAttribute('class')).toBe('bold strike red'); - }); - -
    + $$updateEmptyClasses: function(value) { + if (this.$isEmpty(value)) { + this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS); + this.$$animate.addClass(this.$$element, EMPTY_CLASS); + } else { + this.$$animate.removeClass(this.$$element, EMPTY_CLASS); + this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS); + } + }, - ## Animations + /** + * @ngdoc method + * @name ngModel.NgModelController#$setPristine + * + * @description + * Sets the control to its pristine state. + * + * This method can be called to remove the `ng-dirty` class and set the control to its pristine + * state (`ng-pristine` class). A model is considered to be pristine when the control + * has not been changed from when first compiled. + */ + $setPristine: function() { + this.$dirty = false; + this.$pristine = true; + this.$$animate.removeClass(this.$$element, DIRTY_CLASS); + this.$$animate.addClass(this.$$element, PRISTINE_CLASS); + }, - The example below demonstrates how to perform animations using ngClass. + /** + * @ngdoc method + * @name ngModel.NgModelController#$setDirty + * + * @description + * Sets the control to its dirty state. + * + * This method can be called to remove the `ng-pristine` class and set the control to its dirty + * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed + * from when first compiled. + */ + $setDirty: function() { + this.$dirty = true; + this.$pristine = false; + this.$$animate.removeClass(this.$$element, PRISTINE_CLASS); + this.$$animate.addClass(this.$$element, DIRTY_CLASS); + this.$$parentForm.$setDirty(); + }, - - - - -
    - Sample Text -
    - - .base-class { - -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - } + /** + * @ngdoc method + * @name ngModel.NgModelController#$setUntouched + * + * @description + * Sets the control to its untouched state. + * + * This method can be called to remove the `ng-touched` class and set the control to its + * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched + * by default, however this function can be used to restore that state if the model has + * already been touched by the user. + */ + $setUntouched: function() { + this.$touched = false; + this.$untouched = true; + this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS); + }, - .base-class.my-class { - color: red; - font-size:3em; - } - - - it('should check ng-class', function() { - expect(element(by.css('.base-class')).getAttribute('class')).not. - toMatch(/my-class/); + /** + * @ngdoc method + * @name ngModel.NgModelController#$setTouched + * + * @description + * Sets the control to its touched state. + * + * This method can be called to remove the `ng-untouched` class and set the control to its + * touched state (`ng-touched` class). A model is considered to be touched when the user has + * first focused the control element and then shifted focus away from the control (blur event). + */ + $setTouched: function() { + this.$touched = true; + this.$untouched = false; + this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS); + }, - element(by.id('setbtn')).click(); + /** + * @ngdoc method + * @name ngModel.NgModelController#$rollbackViewValue + * + * @description + * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`, + * which may be caused by a pending debounced event or because the input is waiting for some + * future event. + * + * If you have an input that uses `ng-model-options` to set up debounced updates or updates that + * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of + * sync with the ngModel's `$modelValue`. + * + * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update + * and reset the input to the last committed view value. + * + * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue` + * programmatically before these debounced/future events have resolved/occurred, because AngularJS's + * dirty checking mechanism is not able to tell whether the model has actually changed or not. + * + * The `$rollbackViewValue()` method should be called before programmatically changing the model of an + * input which may have such events pending. This is important in order to make sure that the + * input field will be updated with the new model value and any pending operations are cancelled. + * + * @example + * + * + * angular.module('cancel-update-example', []) + * + * .controller('CancelUpdateController', ['$scope', function($scope) { + * $scope.model = {value1: '', value2: ''}; + * + * $scope.setEmpty = function(e, value, rollback) { + * if (e.keyCode === 27) { + * e.preventDefault(); + * if (rollback) { + * $scope.myForm[value].$rollbackViewValue(); + * } + * $scope.model[value] = ''; + * } + * }; + * }]); + * + * + *
    + *

    Both of these inputs are only updated if they are blurred. Hitting escape should + * empty them. Follow these steps and observe the difference:

    + *
      + *
    1. Type something in the input. You will see that the model is not yet updated
    2. + *
    3. Press the Escape key. + *
        + *
      1. In the first example, nothing happens, because the model is already '', and no + * update is detected. If you blur the input, the model will be set to the current view. + *
      2. + *
      3. In the second example, the pending update is cancelled, and the input is set back + * to the last committed view value (''). Blurring the input does nothing. + *
      4. + *
      + *
    4. + *
    + * + *
    + *
    + *

    Without $rollbackViewValue():

    + * + * value1: "{{ model.value1 }}" + *
    + * + *
    + *

    With $rollbackViewValue():

    + * + * value2: "{{ model.value2 }}" + *
    + *
    + *
    + *
    + + div { + display: table-cell; + } + div:nth-child(1) { + padding-right: 30px; + } - expect(element(by.css('.base-class')).getAttribute('class')). - toMatch(/my-class/); + + *
    + */ + $rollbackViewValue: function() { + this.$$timeout.cancel(this.$$pendingDebounce); + this.$viewValue = this.$$lastCommittedViewValue; + this.$render(); + }, - element(by.id('clearbtn')).click(); + /** + * @ngdoc method + * @name ngModel.NgModelController#$validate + * + * @description + * Runs each of the registered validators (first synchronous validators and then + * asynchronous validators). + * If the validity changes to invalid, the model will be set to `undefined`, + * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`. + * If the validity changes to valid, it will set the model to the last available valid + * `$modelValue`, i.e. either the last parsed value or the last value set from the scope. + */ + $validate: function() { + // ignore $validate before model is initialized + if (isNumberNaN(this.$modelValue)) { + return; + } - expect(element(by.css('.base-class')).getAttribute('class')).not. - toMatch(/my-class/); - }); -
    -
    + var viewValue = this.$$lastCommittedViewValue; + // Note: we use the $$rawModelValue as $modelValue might have been + // set to undefined during a view -> model update that found validation + // errors. We can't parse the view here, since that could change + // the model although neither viewValue nor the model on the scope changed + var modelValue = this.$$rawModelValue; + + var prevValid = this.$valid; + var prevModelValue = this.$modelValue; + + var allowInvalid = this.$options.getOption('allowInvalid'); + + var that = this; + this.$$runValidators(modelValue, viewValue, function(allValid) { + // If there was no change in validity, don't update the model + // This prevents changing an invalid modelValue to undefined + if (!allowInvalid && prevValid !== allValid) { + // Note: Don't check this.$valid here, as we could have + // external validators (e.g. calculated on the server), + // that just call $setValidity and need the model value + // to calculate their validity. + that.$modelValue = allValid ? modelValue : undefined; + + if (that.$modelValue !== prevModelValue) { + that.$$writeModelToScope(); + } + } + }); + }, + $$runValidators: function(modelValue, viewValue, doneCallback) { + this.$$currentValidationRunId++; + var localValidationRunId = this.$$currentValidationRunId; + var that = this; - ## ngClass and pre-existing CSS3 Transitions/Animations - The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. - Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder - any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure - to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and - {@link ngAnimate.$animate#removeclass $animate.removeClass}. - */ - var ngClassDirective = classDirective('', true); + // check parser error + if (!processParseErrors()) { + validationDone(false); + return; + } + if (!processSyncValidators()) { + validationDone(false); + return; + } + processAsyncValidators(); - /** - * @ngdoc directive - * @name ngClassOdd - * @restrict AC - * - * @description - * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except they work in - * conjunction with `ngRepeat` and take effect only on odd (even) rows. - * - * This directive can be applied only within the scope of an - * {@link ng.directive:ngRepeat ngRepeat}. - * - * @element ANY - * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result - * of the evaluation can be a string representing space delimited class names or an array. - * - * @example - - -
      -
    1. - - {{name}} - -
    2. -
    -
    - - .odd { - color: red; - } - .even { - color: blue; - } - - - it('should check ng-class-odd and ng-class-even', function() { - expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). - toMatch(/odd/); - expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). - toMatch(/even/); - }); - -
    - */ - var ngClassOddDirective = classDirective('Odd', 0); + function processParseErrors() { + var errorKey = that.$$parserName || 'parse'; + if (isUndefined(that.$$parserValid)) { + setValidity(errorKey, null); + } else { + if (!that.$$parserValid) { + forEach(that.$validators, function(v, name) { + setValidity(name, null); + }); + forEach(that.$asyncValidators, function(v, name) { + setValidity(name, null); + }); + } + // Set the parse error last, to prevent unsetting it, should a $validators key == parserName + setValidity(errorKey, that.$$parserValid); + return that.$$parserValid; + } + return true; + } - /** - * @ngdoc directive - * @name ngClassEven - * @restrict AC - * - * @description - * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except they work in - * conjunction with `ngRepeat` and take effect only on odd (even) rows. - * - * This directive can be applied only within the scope of an - * {@link ng.directive:ngRepeat ngRepeat}. - * - * @element ANY - * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The - * result of the evaluation can be a string representing space delimited class names or an array. - * - * @example - - -
      -
    1. - - {{name}}       - -
    2. -
    -
    - - .odd { - color: red; - } - .even { - color: blue; - } - - - it('should check ng-class-odd and ng-class-even', function() { - expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). - toMatch(/odd/); - expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). - toMatch(/even/); - }); - -
    - */ - var ngClassEvenDirective = classDirective('Even', 1); + function processSyncValidators() { + var syncValidatorsValid = true; + forEach(that.$validators, function(validator, name) { + var result = Boolean(validator(modelValue, viewValue)); + syncValidatorsValid = syncValidatorsValid && result; + setValidity(name, result); + }); + if (!syncValidatorsValid) { + forEach(that.$asyncValidators, function(v, name) { + setValidity(name, null); + }); + return false; + } + return true; + } - /** - * @ngdoc directive - * @name ngCloak - * @restrict AC - * - * @description - * The `ngCloak` directive is used to prevent the Angular html template from being briefly - * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this - * directive to avoid the undesirable flicker effect caused by the html template display. - * - * The directive can be applied to the `` element, but the preferred usage is to apply - * multiple `ngCloak` directives to small portions of the page to permit progressive rendering - * of the browser view. - * - * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and - * `angular.min.js`. - * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). - * - * ```css - * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { - * display: none !important; - * } - * ``` - * - * When this css rule is loaded by the browser, all html elements (including their children) that - * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive - * during the compilation of the template it deletes the `ngCloak` element attribute, making - * the compiled element visible. - * - * For the best result, the `angular.js` script must be loaded in the head section of the html - * document; alternatively, the css rule above must be included in the external stylesheet of the - * application. - * - * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they - * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css - * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. - * - * @element ANY - * - * @example - - -
    {{ 'hello' }}
    -
    {{ 'hello IE7' }}
    -
    - - it('should remove the template directive and css class', function() { - expect($('#template1').getAttribute('ng-cloak')). - toBeNull(); - expect($('#template2').getAttribute('ng-cloak')). - toBeNull(); - }); - -
    - * - */ - var ngCloakDirective = ngDirective({ - compile: function(element, attr) { - attr.$set('ngCloak', undefined); - element.removeClass('ng-cloak'); - } - }); + function processAsyncValidators() { + var validatorPromises = []; + var allValid = true; + forEach(that.$asyncValidators, function(validator, name) { + var promise = validator(modelValue, viewValue); + if (!isPromiseLike(promise)) { + throw ngModelMinErr('nopromise', + 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise); + } + setValidity(name, undefined); + validatorPromises.push(promise.then(function() { + setValidity(name, true); + }, function() { + allValid = false; + setValidity(name, false); + })); + }); + if (!validatorPromises.length) { + validationDone(true); + } else { + that.$$q.all(validatorPromises).then(function() { + validationDone(allValid); + }, noop); + } + } - /** - * @ngdoc directive - * @name ngController - * - * @description - * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular - * supports the principles behind the Model-View-Controller design pattern. - * - * MVC components in angular: - * - * * Model — The Model is scope properties; scopes are attached to the DOM where scope properties - * are accessed through bindings. - * * View — The template (HTML with data bindings) that is rendered into the View. - * * Controller — The `ngController` directive specifies a Controller class; the class contains business - * logic behind the application to decorate the scope with functions and values - * - * Note that you can also attach controllers to the DOM by declaring it in a route definition - * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller - * again using `ng-controller` in the template itself. This will cause the controller to be attached - * and executed twice. - * - * @element ANY - * @scope - * @param {expression} ngController Name of a globally accessible constructor function or an - * {@link guide/expression expression} that on the current scope evaluates to a - * constructor function. The controller instance can be published into a scope property - * by specifying `as propertyName`. - * - * @example - * Here is a simple form for editing user contact information. Adding, removing, clearing, and - * greeting are methods declared on the controller (see source tab). These methods can - * easily be called from the angular markup. Notice that the scope becomes the `this` for the - * controller's instance. This allows for easy access to the view data from the controller. Also - * notice that any changes to the data are automatically reflected in the View without the need - * for a manual update. The example is shown in two different declaration styles you may use - * according to preference. - - - -
    - Name: - [ greet ]
    - Contact: -
      -
    • - - - [ clear - | X ] -
    • -
    • [ add ]
    • -
    -
    -
    - - it('should check controller as', function() { - var container = element(by.id('ctrl-as-exmpl')); + /** + * @ngdoc method + * @name ngModel.NgModelController#$commitViewValue + * + * @description + * Commit a pending update to the `$modelValue`. + * + * Updates may be pending by a debounced event or because the input is waiting for a some future + * event defined in `ng-model-options`. this method is rarely needed as `NgModelController` + * usually handles calling this in response to input events. + */ + $commitViewValue: function() { + var viewValue = this.$viewValue; - expect(container.findElement(by.model('settings.name')) - .getAttribute('value')).toBe('John Smith'); + this.$$timeout.cancel(this.$$pendingDebounce); - var firstRepeat = - container.findElement(by.repeater('contact in settings.contacts').row(0)); - var secondRepeat = - container.findElement(by.repeater('contact in settings.contacts').row(1)); + // If the view value has not changed then we should just exit, except in the case where there is + // a native validator on the element. In this case the validation state may have changed even though + // the viewValue has stayed empty. + if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) { + return; + } + this.$$updateEmptyClasses(viewValue); + this.$$lastCommittedViewValue = viewValue; - expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe('408 555 1212'); - expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe('john.smith@example.org'); + // change to dirty + if (this.$pristine) { + this.$setDirty(); + } + this.$$parseAndValidate(); + }, - firstRepeat.findElement(by.linkText('clear')).click(); + $$parseAndValidate: function() { + var viewValue = this.$$lastCommittedViewValue; + var modelValue = viewValue; + var that = this; - expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe(''); + this.$$parserValid = isUndefined(modelValue) ? undefined : true; - container.findElement(by.linkText('add')).click(); + if (this.$$parserValid) { + for (var i = 0; i < this.$parsers.length; i++) { + modelValue = this.$parsers[i](modelValue); + if (isUndefined(modelValue)) { + this.$$parserValid = false; + break; + } + } + } + if (isNumberNaN(this.$modelValue)) { + // this.$modelValue has not been touched yet... + this.$modelValue = this.$$ngModelGet(this.$$scope); + } + var prevModelValue = this.$modelValue; + var allowInvalid = this.$options.getOption('allowInvalid'); + this.$$rawModelValue = modelValue; - expect(container.findElement(by.repeater('contact in settings.contacts').row(2)) - .findElement(by.model('contact.value')) - .getAttribute('value')) - .toBe('yourname@example.org'); - }); - -
    - - - -
    - Name: - [ greet ]
    - Contact: -
      -
    • - - - [ clear - | X ] -
    • -
    • [ add ]
    • -
    -
    -
    - - it('should check controller', function() { - var container = element(by.id('ctrl-exmpl')); + $$writeModelToScope: function() { + this.$$ngModelSet(this.$$scope, this.$modelValue); + forEach(this.$viewChangeListeners, function(listener) { + try { + listener(); + } catch (e) { + // eslint-disable-next-line no-invalid-this + this.$$exceptionHandler(e); + } + }, this); + }, - expect(container.findElement(by.model('name')) - .getAttribute('value')).toBe('John Smith'); + /** + * @ngdoc method + * @name ngModel.NgModelController#$setViewValue + * + * @description + * Update the view value. + * + * This method should be called when a control wants to change the view value; typically, + * this is done from within a DOM event handler. For example, the {@link ng.directive:input input} + * directive calls it when the value of the input changes and {@link ng.directive:select select} + * calls it when an option is selected. + * + * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers` + * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged + * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and + * `$asyncValidators` are called and the value is applied to `$modelValue`. + * Finally, the value is set to the **expression** specified in the `ng-model` attribute and + * all the registered change listeners, in the `$viewChangeListeners` list are called. + * + * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn` + * and the `default` trigger is not listed, all those actions will remain pending until one of the + * `updateOn` events is triggered on the DOM element. + * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions} + * directive is used with a custom debounce for this particular event. + * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce` + * is specified, once the timer runs out. + * + * When used with standard inputs, the view value will always be a string (which is in some cases + * parsed into another type, such as a `Date` object for `input[date]`.) + * However, custom controls might also pass objects to this method. In this case, we should make + * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not + * perform a deep watch of objects, it only looks for a change of identity. If you only change + * the property of the object then ngModel will not realize that the object has changed and + * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should + * not change properties of the copy once it has been passed to `$setViewValue`. + * Otherwise you may cause the model value on the scope to change incorrectly. + * + *
    + * In any case, the value passed to the method should always reflect the current value + * of the control. For example, if you are calling `$setViewValue` for an input element, + * you should pass the input DOM value. Otherwise, the control and the scope model become + * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change + * the control's DOM value in any way. If we want to change the control's DOM value + * programmatically, we should update the `ngModel` scope expression. Its new value will be + * picked up by the model controller, which will run it through the `$formatters`, `$render` it + * to update the DOM, and finally call `$validate` on it. + *
    + * + * @param {*} value value from the view. + * @param {string} trigger Event that triggered the update. + */ + $setViewValue: function(value, trigger) { + this.$viewValue = value; + if (this.$options.getOption('updateOnDefault')) { + this.$$debounceViewValueCommit(trigger); + } + }, - var firstRepeat = - container.findElement(by.repeater('contact in contacts').row(0)); - var secondRepeat = - container.findElement(by.repeater('contact in contacts').row(1)); + $$debounceViewValueCommit: function(trigger) { + var debounceDelay = this.$options.getOption('debounce'); - expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe('408 555 1212'); - expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe('john.smith@example.org'); + if (isNumber(debounceDelay[trigger])) { + debounceDelay = debounceDelay[trigger]; + } else if (isNumber(debounceDelay['default'])) { + debounceDelay = debounceDelay['default']; + } - firstRepeat.findElement(by.linkText('clear')).click(); + this.$$timeout.cancel(this.$$pendingDebounce); + var that = this; + if (debounceDelay > 0) { // this fails if debounceDelay is an object + this.$$pendingDebounce = this.$$timeout(function() { + that.$commitViewValue(); + }, debounceDelay); + } else if (this.$$scope.$root.$$phase) { + this.$commitViewValue(); + } else { + this.$$scope.$apply(function() { + that.$commitViewValue(); + }); + } + }, - expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe(''); + /** + * @ngdoc method + * + * @name ngModel.NgModelController#$overrideModelOptions + * + * @description + * + * Override the current model options settings programmatically. + * + * The previous `ModelOptions` value will not be modified. Instead, a + * new `ModelOptions` object will inherit from the previous one overriding + * or inheriting settings that are defined in the given parameter. + * + * See {@link ngModelOptions} for information about what options can be specified + * and how model option inheritance works. + * + *
    + * **Note:** this function only affects the options set on the `ngModelController`, + * and not the options on the {@link ngModelOptions} directive from which they might have been + * obtained initially. + *
    + * + *
    + * **Note:** it is not possible to override the `getterSetter` option. + *
    + * + * @param {Object} options a hash of settings to override the previous options + * + */ + $overrideModelOptions: function(options) { + this.$options = this.$options.createChild(options); + this.$$setUpdateOnEvents(); + }, - container.findElement(by.linkText('add')).click(); + /** + * @ngdoc method + * + * @name ngModel.NgModelController#$processModelValue - expect(container.findElement(by.repeater('contact in contacts').row(2)) - .findElement(by.model('contact.value')) - .getAttribute('value')) - .toBe('yourname@example.org'); - }); -
    -
    + * @description + * + * Runs the model -> view pipeline on the current + * {@link ngModel.NgModelController#$modelValue $modelValue}. + * + * The following actions are performed by this method: + * + * - the `$modelValue` is run through the {@link ngModel.NgModelController#$formatters $formatters} + * and the result is set to the {@link ngModel.NgModelController#$viewValue $viewValue} + * - the `ng-empty` or `ng-not-empty` class is set on the element + * - if the `$viewValue` has changed: + * - {@link ngModel.NgModelController#$render $render} is called on the control + * - the {@link ngModel.NgModelController#$validators $validators} are run and + * the validation status is set. + * + * This method is called by ngModel internally when the bound scope value changes. + * Application developers usually do not have to call this function themselves. + * + * This function can be used when the `$viewValue` or the rendered DOM value are not correctly + * formatted and the `$modelValue` must be run through the `$formatters` again. + * + * @example + * Consider a text input with an autocomplete list (for fruit), where the items are + * objects with a name and an id. + * A user enters `ap` and then selects `Apricot` from the list. + * Based on this, the autocomplete widget will call `$setViewValue({name: 'Apricot', id: 443})`, + * but the rendered value will still be `ap`. + * The widget can then call `ctrl.$processModelValue()` to run the model -> view + * pipeline again, which formats the object to the string `Apricot`, + * then updates the `$viewValue`, and finally renders it in the DOM. + * + * + +
    +
    + Search Fruit: + +
    +
    + Model:
    +
    {{selectedFruit | json}}
    +
    +
    +
    + + angular.module('inputExample', []) + .controller('inputController', function($scope) { + $scope.items = [ + {name: 'Apricot', id: 443}, + {name: 'Clementine', id: 972}, + {name: 'Durian', id: 169}, + {name: 'Jackfruit', id: 982}, + {name: 'Strawberry', id: 863} + ]; + }) + .component('basicAutocomplete', { + bindings: { + items: '<', + onSelect: '&' + }, + templateUrl: 'autocomplete.html', + controller: function($element, $scope) { + var that = this; + var ngModel; + + that.$postLink = function() { + ngModel = $element.find('input').controller('ngModel'); + + ngModel.$formatters.push(function(value) { + return (value && value.name) || value; + }); + + ngModel.$parsers.push(function(value) { + var match = value; + for (var i = 0; i < that.items.length; i++) { + if (that.items[i].name === value) { + match = that.items[i]; + break; + } + } + + return match; + }); + }; + + that.selectItem = function(item) { + ngModel.$setViewValue(item); + ngModel.$processModelValue(); + that.onSelect({item: item}); + }; + } + }); + + +
    + +
      +
    • + +
    • +
    +
    +
    + *
    + * + */ + $processModelValue: function() { + var viewValue = this.$$format(); + + if (this.$viewValue !== viewValue) { + this.$$updateEmptyClasses(viewValue); + this.$viewValue = this.$$lastCommittedViewValue = viewValue; + this.$render(); + // It is possible that model and view value have been updated during render + this.$$runValidators(this.$modelValue, this.$viewValue, noop); + } + }, + + /** + * This method is called internally to run the $formatters on the $modelValue + */ + $$format: function() { + var formatters = this.$formatters, + idx = formatters.length; + + var viewValue = this.$modelValue; + while (idx--) { + viewValue = formatters[idx](viewValue); + } + + return viewValue; + }, + + /** + * This method is called internally when the bound scope value changes. + */ + $$setModelValue: function(modelValue) { + this.$modelValue = this.$$rawModelValue = modelValue; + this.$$parserValid = undefined; + this.$processModelValue(); + }, + + $$setUpdateOnEvents: function() { + if (this.$$updateEvents) { + this.$$element.off(this.$$updateEvents, this.$$updateEventHandler); + } + + this.$$updateEvents = this.$options.getOption('updateOn'); + if (this.$$updateEvents) { + this.$$element.on(this.$$updateEvents, this.$$updateEventHandler); + } + }, + + $$updateEventHandler: function(ev) { + this.$$debounceViewValueCommit(ev && ev.type); + } + }; + + function setupModelWatcher(ctrl) { + // model -> value + // Note: we cannot use a normal scope.$watch as we want to detect the following: + // 1. scope value is 'a' + // 2. user enters 'b' + // 3. ng-change kicks in and reverts scope value to 'a' + // -> scope value did not change since the last digest as + // ng-change executes in apply phase + // 4. view should be changed back to 'a' + ctrl.$$scope.$watch(function ngModelWatch(scope) { + var modelValue = ctrl.$$ngModelGet(scope); + + // if scope model value and ngModel value are out of sync + // This cannot be moved to the action function, because it would not catch the + // case where the model is changed in the ngChange function or the model setter + if (modelValue !== ctrl.$modelValue && + // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator + // eslint-disable-next-line no-self-compare + (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue) + ) { + ctrl.$$setModelValue(modelValue); + } + + return modelValue; + }); + } + /** + * @ngdoc method + * @name ngModel.NgModelController#$setValidity + * + * @description + * Change the validity state, and notify the form. + * + * This method can be called within $parsers/$formatters or a custom validation implementation. + * However, in most cases it should be sufficient to use the `ngModel.$validators` and + * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically. + * + * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned + * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` + * (for unfulfilled `$asyncValidators`), so that it is available for data-binding. + * The `validationErrorKey` should be in camelCase and will get converted into dash-case + * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` + * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`. + * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined), + * or skipped (null). Pending is used for unfulfilled `$asyncValidators`. + * Skipped is used by AngularJS when validators do not run because of parse errors and + * when `$asyncValidators` do not run because any of the `$validators` failed. */ - var ngControllerDirective = [function() { - return { - scope: true, - controller: '@', - priority: 500 - }; - }]; + addSetValidityMethod({ + clazz: NgModelController, + set: function(object, property) { + object[property] = true; + }, + unset: function(object, property) { + delete object[property]; + } + }); + /** * @ngdoc directive - * @name ngCsp + * @name ngModel + * @restrict A + * @priority 1 + * @param {expression} ngModel assignable {@link guide/expression Expression} to bind to. * - * @element html * @description - * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. + * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a + * property on the scope using {@link ngModel.NgModelController NgModelController}, + * which is created and exposed by this directive. * - * This is necessary when developing things like Google Chrome Extensions. + * `ngModel` is responsible for: * - * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). - * For us to be compatible, we just need to implement the "getterFn" in $parse without violating - * any of these restrictions. + * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` + * require. + * - Providing validation behavior (i.e. required, number, email, url). + * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). + * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, + * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations. + * - Registering the control with its parent {@link ng.directive:form form}. * - * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` - * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will - * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will - * be raised. + * Note: `ngModel` will try to bind to the property given by evaluating the expression on the + * current scope. If the property doesn't already exist on this scope, it will be created + * implicitly and added to the scope. * - * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically - * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). - * To make those directives work in CSP mode, include the `angular-csp.css` manually. + * For best practices on using `ngModel`, see: * - * In order to use this feature put the `ngCsp` directive on the root element of the application. + * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes) * - * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* + * For basic examples, how to use `ngModel`, see: * - * @example - * This example shows how to apply the `ngCsp` directive to the `html` tag. - ```html - - - ... - ... - - ``` - */ - -// ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap -// the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute -// anywhere in the current doc - - /** - * @ngdoc directive - * @name ngClick + * - {@link ng.directive:input input} + * - {@link input[text] text} + * - {@link input[checkbox] checkbox} + * - {@link input[radio] radio} + * - {@link input[number] number} + * - {@link input[email] email} + * - {@link input[url] url} + * - {@link input[date] date} + * - {@link input[datetime-local] datetime-local} + * - {@link input[time] time} + * - {@link input[month] month} + * - {@link input[week] week} + * - {@link ng.directive:select select} + * - {@link ng.directive:textarea textarea} * - * @description - * The ngClick directive allows you to specify custom behavior when - * an element is clicked. + * ## Complex Models (objects or collections) * - * @element ANY - * @priority 0 - * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon - * click. ({@link guide/expression#-event- Event object is available as `$event`}) + * By default, `ngModel` watches the model by reference, not value. This is important to know when + * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the + * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered. * - * @example - - - - count: {{count}} - - - it('should check ng-click', function() { - expect(element(by.binding('count')).getText()).toMatch('0'); - element(by.css('button')).click(); - expect(element(by.binding('count')).getText()).toMatch('1'); - }); - - - */ - /* - * A directive that allows creation of custom onclick handlers that are defined as angular - * expressions and are compiled and executed within the current scope. + * The model must be assigned an entirely new object or collection before a re-rendering will occur. * - * Events that are handled via these handler are always configured not to propagate further. - */ - var ngEventDirectives = {}; - forEach( - 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), - function(name) { - var directiveName = directiveNormalize('ng-' + name); - ngEventDirectives[directiveName] = ['$parse', function($parse) { - return { - compile: function($element, attr) { - var fn = $parse(attr[directiveName]); - return function(scope, element, attr) { - element.on(lowercase(name), function(event) { - scope.$apply(function() { - fn(scope, {$event:event}); - }); - }); - }; - } - }; - }]; - } - ); - - /** - * @ngdoc directive - * @name ngDblclick + * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression + * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or + * if the select is given the `multiple` attribute. * - * @description - * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. + * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the + * first level of the object (or only changing the properties of an item in the collection if it's an array) will still + * not trigger a re-rendering of the model. * - * @element ANY - * @priority 0 - * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon - * a dblclick. (The Event object is available as `$event`) + * ## CSS classes + * The following CSS classes are added and removed on the associated input/select/textarea element + * depending on the validity of the model. * - * @example - - - - count: {{count}} - - - */ - - - /** - * @ngdoc directive - * @name ngMousedown + * - `ng-valid`: the model is valid + * - `ng-invalid`: the model is invalid + * - `ng-valid-[key]`: for each valid key added by `$setValidity` + * - `ng-invalid-[key]`: for each invalid key added by `$setValidity` + * - `ng-pristine`: the control hasn't been interacted with yet + * - `ng-dirty`: the control has been interacted with + * - `ng-touched`: the control has been blurred + * - `ng-untouched`: the control hasn't been blurred + * - `ng-pending`: any `$asyncValidators` are unfulfilled + * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined + * by the {@link ngModel.NgModelController#$isEmpty} method + * - `ng-not-empty`: the view contains a non-empty value * - * @description - * The ngMousedown directive allows you to specify custom behavior on mousedown event. + * Keep in mind that ngAnimate can detect each of these classes when added and removed. * - * @element ANY - * @priority 0 - * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon - * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) + * @animations + * Animations within models are triggered when any of the associated CSS classes are added and removed + * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`, + * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. + * The animations that are triggered within ngModel are similar to how they work in ngClass and + * animations can be hooked into using CSS transitions, keyframes as well as JS animations. + * + * The following example shows a simple way to utilize CSS transitions to style an input element + * that has been rendered as invalid after it has been validated: + * + *
    +     * //be sure to include ngAnimate as a module to hook into more
    +     * //advanced animations
    +     * .my-input {
    +     *   transition:0.5s linear all;
    +     *   background: white;
    +     * }
    +     * .my-input.ng-invalid {
    +     *   background: red;
    +     *   color:white;
    +     * }
    +     * 
    * * @example - + * ### Basic Usage + * - - count: {{count}} + + +

    + Update input to see transitions when valid/invalid. + Integer is a valid value. +

    +
    + +
    -
    - */ - - - /** - * @ngdoc directive - * @name ngMouseup + *
    * - * @description - * Specify custom behavior on mouseup event. + * @example + * ### Binding to a getter/setter * - * @element ANY - * @priority 0 - * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon - * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) + * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a + * function that returns a representation of the model when called with zero arguments, and sets + * the internal state of a model when called with an argument. It's sometimes useful to use this + * for models that have an internal representation that's different from what the model exposes + * to the view. + * + *
    + * **Best Practice:** It's best to keep getters fast because AngularJS is likely to call them more + * frequently than other parts of your code. + *
    + * + * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that + * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to + * a `
    `, which will enable this behavior for all ``s within it. See + * {@link ng.directive:ngModelOptions `ngModelOptions`} for more. + * + * The following example shows how to use `ngModel` with a getter/setter: * * @example - + * - - count: {{count}} +
    + + + +
    user.name = 
    +
    -
    + + angular.module('getterSetterExample', []) + .controller('ExampleController', ['$scope', function($scope) { + var _name = 'Brian'; + $scope.user = { + name: function(newName) { + // Note that newName can be undefined for two reasons: + // 1. Because it is called as a getter and thus called with no arguments + // 2. Because the property should actually be set to undefined. This happens e.g. if the + // input is invalid + return arguments.length ? (_name = newName) : _name; + } + }; + }]); + + *
    */ + var ngModelDirective = ['$rootScope', function($rootScope) { + return { + restrict: 'A', + require: ['ngModel', '^?form', '^?ngModelOptions'], + controller: NgModelController, + // Prelink needs to run before any input directive + // so that we can set the NgModelOptions in NgModelController + // before anyone else uses it. + priority: 1, + compile: function ngModelCompile(element) { + // Setup initial state of the control + element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS); + + return { + pre: function ngModelPreLink(scope, element, attr, ctrls) { + var modelCtrl = ctrls[0], + formCtrl = ctrls[1] || modelCtrl.$$parentForm, + optionsCtrl = ctrls[2]; + + if (optionsCtrl) { + modelCtrl.$options = optionsCtrl.$options; + } + + modelCtrl.$$initGetterSetters(); + + // notify others, especially parent forms + formCtrl.$addControl(modelCtrl); + + attr.$observe('name', function(newValue) { + if (modelCtrl.$name !== newValue) { + modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue); + } + }); + + scope.$on('$destroy', function() { + modelCtrl.$$parentForm.$removeControl(modelCtrl); + }); + }, + post: function ngModelPostLink(scope, element, attr, ctrls) { + var modelCtrl = ctrls[0]; + modelCtrl.$$setUpdateOnEvents(); + + function setTouched() { + modelCtrl.$setTouched(); + } + + element.on('blur', function() { + if (modelCtrl.$touched) return; + + if ($rootScope.$$phase) { + scope.$evalAsync(setTouched); + } else { + scope.$apply(setTouched); + } + }); + } + }; + } + }; + }]; + + /* exported defaultModelOptions */ + var defaultModelOptions; + var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; /** - * @ngdoc directive - * @name ngMouseover - * + * @ngdoc type + * @name ModelOptions * @description - * Specify custom behavior on mouseover event. - * - * @element ANY - * @priority 0 - * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon - * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - - - - count: {{count}} - - + * A container for the options set by the {@link ngModelOptions} directive */ + function ModelOptions(options) { + this.$$options = options; + } + + ModelOptions.prototype = { + + /** + * @ngdoc method + * @name ModelOptions#getOption + * @param {string} name the name of the option to retrieve + * @returns {*} the value of the option + * @description + * Returns the value of the given option + */ + getOption: function(name) { + return this.$$options[name]; + }, + + /** + * @ngdoc method + * @name ModelOptions#createChild + * @param {Object} options a hash of options for the new child that will override the parent's options + * @return {ModelOptions} a new `ModelOptions` object initialized with the given options. + */ + createChild: function(options) { + var inheritAll = false; + + // make a shallow copy + options = extend({}, options); + + // Inherit options from the parent if specified by the value `"$inherit"` + forEach(options, /* @this */ function(option, key) { + if (option === '$inherit') { + if (key === '*') { + inheritAll = true; + } else { + options[key] = this.$$options[key]; + // `updateOn` is special so we must also inherit the `updateOnDefault` option + if (key === 'updateOn') { + options.updateOnDefault = this.$$options.updateOnDefault; + } + } + } else { + if (key === 'updateOn') { + // If the `updateOn` property contains the `default` event then we have to remove + // it from the event list and set the `updateOnDefault` flag. + options.updateOnDefault = false; + options[key] = trim(option.replace(DEFAULT_REGEXP, function() { + options.updateOnDefault = true; + return ' '; + })); + } + } + }, this); + + if (inheritAll) { + // We have a property of the form: `"*": "$inherit"` + delete options['*']; + defaults(options, this.$$options); + } + + // Finally add in any missing defaults + defaults(options, defaultModelOptions.$$options); + + return new ModelOptions(options); + } + }; + + + defaultModelOptions = new ModelOptions({ + updateOn: '', + updateOnDefault: true, + debounce: 0, + getterSetter: false, + allowInvalid: false, + timezone: null + }); /** * @ngdoc directive - * @name ngMouseenter + * @name ngModelOptions + * @restrict A + * @priority 10 * * @description - * Specify custom behavior on mouseenter event. + * This directive allows you to modify the behaviour of {@link ngModel} directives within your + * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel} + * directives will use the options of their nearest `ngModelOptions` ancestor. * - * @element ANY - * @priority 0 - * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon - * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) + * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as + * an AngularJS expression. This expression should evaluate to an object, whose properties contain + * the settings. For example: `
    - - - count: {{count}} - - - */ - - - /** - * @ngdoc directive - * @name ngMouseleave + * ## Inheriting Options * - * @description - * Specify custom behavior on mouseleave event. + * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions` + * directive by giving it the value of `"$inherit"`. + * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the + * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings + * will be used. * - * @element ANY - * @priority 0 - * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon - * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) + * For example given the following fragment of HTML * - * @example - - - - count: {{count}} - - - */ - - - /** - * @ngdoc directive - * @name ngMousemove * - * @description - * Specify custom behavior on mousemove event. + * ```html + *
    + *
    + * + *
    + *
    + * ``` * - * @element ANY - * @priority 0 - * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon - * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) + * the `input` element will have the following settings * - * @example - - - - count: {{count}} - - - */ - - - /** - * @ngdoc directive - * @name ngKeydown + * ```js + * { allowInvalid: true, updateOn: 'default', debounce: 0 } + * ``` * - * @description - * Specify custom behavior on keydown event. + * Notice that the `debounce` setting was not inherited and used the default value instead. * - * @element ANY - * @priority 0 - * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon - * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * You can specify that all undefined settings are automatically inherited from an ancestor by + * including a property with key of `"*"` and value of `"$inherit"`. * - * @example - - - - key down count: {{count}} - - - */ - - - /** - * @ngdoc directive - * @name ngKeyup + * For example given the following fragment of HTML * - * @description - * Specify custom behavior on keyup event. * - * @element ANY - * @priority 0 - * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon - * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * ```html + *
    + *
    + * + *
    + *
    + * ``` * - * @example - - - - key up count: {{count}} - - - */ - - - /** - * @ngdoc directive - * @name ngKeypress + * the `input` element will have the following settings * - * @description - * Specify custom behavior on keypress event. + * ```js + * { allowInvalid: true, updateOn: 'default', debounce: 200 } + * ``` * - * @element ANY - * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon - * keypress. ({@link guide/expression#-event- Event object is available as `$event`} - * and can be interrogated for keyCode, altKey, etc.) + * Notice that the `debounce` setting now inherits the value from the outer `
    ` element. * - * @example - - - - key press count: {{count}} - - - */ - - - /** - * @ngdoc directive - * @name ngSubmit + * If you are creating a reusable component then you should be careful when using `"*": "$inherit"` + * since you may inadvertently inherit a setting in the future that changes the behavior of your component. * - * @description - * Enables binding angular expressions to onsubmit events. * - * Additionally it prevents the default action (which for form means sending the request to the - * server and reloading the current page), but only if the form does not contain `action`, - * `data-action`, or `x-action` attributes. + * ## Triggering and debouncing model updates * - * @element form - * @priority 0 - * @param {expression} ngSubmit {@link guide/expression Expression} to eval. - * ({@link guide/expression#-event- Event object is available as `$event`}) + * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will + * trigger a model update and/or a debouncing delay so that the actual update only takes place when + * a timer expires; this timer will be reset after another change takes place. * - * @example - - - -
    - Enter text and hit enter: - - -
    list={{list}}
    -
    -
    - - it('should check ng-submit', function() { - expect(element(by.binding('list')).getText()).toBe('list=[]'); - element(by.css('#submit')).click(); - expect(element(by.binding('list')).getText()).toContain('hello'); - expect(element(by.input('text')).getAttribute('value')).toBe(''); - }); - it('should ignore empty strings', function() { - expect(element(by.binding('list')).getText()).toBe('list=[]'); - element(by.css('#submit')).click(); - element(by.css('#submit')).click(); - expect(element(by.binding('list')).getText()).toContain('hello'); - }); - -
    - */ - - /** - * @ngdoc directive - * @name ngFocus + * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might + * be different from the value in the actual model. This means that if you update the model you + * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in + * order to make sure it is synchronized with the model and that any debounced action is canceled. * - * @description - * Specify custom behavior on focus event. + * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue} + * method is by making sure the input is placed inside a form that has a `name` attribute. This is + * important because `form` controllers are published to the related scope under the name in their + * `name` attribute. * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon - * focus. ({@link guide/expression#-event- Event object is available as `$event`}) + * Any pending changes will take place immediately when an enclosing form is submitted via the + * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` + * to have access to the updated model. * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - /** - * @ngdoc directive - * @name ngBlur + * ### Overriding immediate updates * - * @description - * Specify custom behavior on blur event. + * The following example shows how to override immediate updates. Changes on the inputs within the + * form will update the model only when the control loses focus (blur event). If `escape` key is + * pressed while the input field is focused, the value is reset to the value in the current model. * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon - * blur. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * + *
    + *
    + *
    + *
    + *
    + *
    user.name = 
    + *
    + *
    + * + * angular.module('optionsExample', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.user = { name: 'say', data: '' }; + * + * $scope.cancel = function(e) { + * if (e.keyCode === 27) { + * $scope.userForm.userName.$rollbackViewValue(); + * } + * }; + * }]); + * + * + * var model = element(by.binding('user.name')); + * var input = element(by.model('user.name')); + * var other = element(by.model('user.data')); + * + * it('should allow custom events', function() { + * input.sendKeys(' hello'); + * input.click(); + * expect(model.getText()).toEqual('say'); + * other.click(); + * expect(model.getText()).toEqual('say hello'); + * }); * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - - /** - * @ngdoc directive - * @name ngCopy + * it('should $rollbackViewValue when model changes', function() { + * input.sendKeys(' hello'); + * expect(input.getAttribute('value')).toEqual('say hello'); + * input.sendKeys(protractor.Key.ESCAPE); + * expect(input.getAttribute('value')).toEqual('say'); + * other.click(); + * expect(model.getText()).toEqual('say'); + * }); + * + *
    * - * @description - * Specify custom behavior on copy event. + * ### Debouncing updates * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon - * copy. ({@link guide/expression#-event- Event object is available as `$event`}) + * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change. + * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. + * + * + * + *
    + *
    + * Name: + * + *
    + *
    + *
    user.name = 
    + *
    + *
    + * + * angular.module('optionsExample', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.user = { name: 'say' }; + * }]); + * + *
    + * + * + * ## Model updates and validation + * + * The default behaviour in `ngModel` is that the model value is set to `undefined` when the + * validation determines that the value is invalid. By setting the `allowInvalid` property to true, + * the model will still be updated even if the value is invalid. + * + * + * ## Connecting to the scope + * + * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression + * on the scope refers to a "getter/setter" function rather than the value itself. + * + * The following example shows how to bind to getter/setters: + * + * + * + *
    + *
    + * + *
    + *
    user.name = 
    + *
    + *
    + * + * angular.module('getterSetterExample', []) + * .controller('ExampleController', ['$scope', function($scope) { + * var _name = 'Brian'; + * $scope.user = { + * name: function(newName) { + * return angular.isDefined(newName) ? (_name = newName) : _name; + * } + * }; + * }]); + * + *
    + * + * + * ## Specifying timezones + * + * You can specify the timezone that date/time input directives expect by providing its name in the + * `timezone` property. + * + * + * ## Programmatically changing options + * + * The `ngModelOptions` expression is only evaluated once when the directive is linked; it is not + * watched for changes. However, it is possible to override the options on a single + * {@link ngModel.NgModelController} instance with + * {@link ngModel.NgModelController#$overrideModelOptions `NgModelController#$overrideModelOptions()`}. + * + * + * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and + * and its descendents. Valid keys are: + * - `updateOn`: string specifying which event should the input be bound to. You can set several + * events using an space delimited list. There is a special event called `default` that + * matches the default events belonging to the control. These are the events that are bound to + * the control, and when fired, update the `$viewValue` via `$setViewValue`. + * + * `ngModelOptions` considers every event that is not listed in `updateOn` a "default" event, + * since different control types use different default events. + * + * See also the section {@link ngModelOptions#triggering-and-debouncing-model-updates + * Triggering and debouncing model updates}. + * + * - `debounce`: integer value which contains the debounce model update value in milliseconds. A + * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a + * custom value for each event. For example: + * ``` + * ng-model-options="{ + * updateOn: 'default blur click', + * debounce: { 'default': 500, 'blur': 0 } + * }" + * ``` + * + * "default" also applies to all events that are listed in `updateOn` but are not + * listed in `debounce`, i.e. "click" would also be debounced by 500 milliseconds. + * + * - `allowInvalid`: boolean value which indicates that the model can be set with values that did + * not validate correctly instead of the default behavior of setting the model to undefined. + * - `getterSetter`: boolean value which determines whether or not to treat functions bound to + * `ngModel` as getters/setters. + * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for + * ``, ``, ... . It understands UTC/GMT and the + * continental US time zone abbreviations, but for general use, use a time zone offset, for + * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian) + * If not specified, the timezone of the browser will be used. * - * @example - - - - copied: {{copied}} - - */ + var ngModelOptionsDirective = function() { + NgModelOptionsController.$inject = ['$attrs', '$scope']; + function NgModelOptionsController($attrs, $scope) { + this.$$attrs = $attrs; + this.$$scope = $scope; + } + NgModelOptionsController.prototype = { + $onInit: function() { + var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions; + var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions); + + this.$options = parentOptions.createChild(modelOptionsDefinition); + } + }; + + return { + restrict: 'A', + // ngModelOptions needs to run before ngModel and input directives + priority: 10, + require: {parentCtrl: '?^^ngModelOptions'}, + bindToController: true, + controller: NgModelOptionsController + }; + }; + + +// shallow copy over values from `src` that are not already specified on `dst` + function defaults(dst, src) { + forEach(src, function(value, key) { + if (!isDefined(dst[key])) { + dst[key] = value; + } + }); + } /** * @ngdoc directive - * @name ngCut + * @name ngNonBindable + * @restrict AC + * @priority 1000 + * @element ANY * * @description - * Specify custom behavior on cut event. - * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon - * cut. ({@link guide/expression#-event- Event object is available as `$event`}) + * The `ngNonBindable` directive tells AngularJS not to compile or bind the contents of the current + * DOM element, including directives on the element itself that have a lower priority than + * `ngNonBindable`. This is useful if the element contains what appears to be AngularJS directives + * and bindings but which should be ignored by AngularJS. This could be the case if you have a site + * that displays snippets of code, for instance. * * @example - + * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, + * but the one wrapped in `ngNonBindable` is left alone. + * + - - cut: {{cut}} +
    Normal: {{1 + 2}}
    +
    Ignored: {{1 + 2}}
    +
    + + it('should check ng-non-bindable', function() { + expect(element(by.binding('1 + 2')).getText()).toContain('3'); + expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); + });
    */ + var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); + + /* exported ngOptionsDirective */ + + /* global jqLiteRemove */ + + var ngOptionsMinErr = minErr('ngOptions'); /** * @ngdoc directive - * @name ngPaste + * @name ngOptions + * @restrict A * * @description - * Specify custom behavior on paste event. * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon - * paste. ({@link guide/expression#-event- Event object is available as `$event`}) + * The `ngOptions` attribute can be used to dynamically generate a list of `
    - */ - - /** - * @ngdoc directive - * @name ngIf - * @restrict A + * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `` + * DOM element. + * * `disable`: The result of this expression will be used to disable the rendered `
    - \ No newline at end of file + diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml index b5bd6721401d6..b87b89a0017d6 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml @@ -15,5 +15,6 @@ + diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml new file mode 100644 index 0000000000000..888f66d1d03d3 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml @@ -0,0 +1,87 @@ + + + + + + + + <description value="Country filter on Customers page when allowed countries restriction for a default website is applied"/> + <features value="Customer"/> + <severity value="MAJOR"/> + <testCaseId value="MC-17282"/> + <useCaseId value="MAGETWO-86624"/> + <group value="customer"/> + </annotations> + <before> + <createData entity="CustomerAccountSharingDefault" stepKey="setCustomerAccountSharingToDefault"/> + <createData entity="Simple_Customer_Without_Address" stepKey="createCustomer"/> + <actionGroup ref="LoginActionGroup" stepKey="loginToAdmin"/> + + <!--Create new website,store and store view--> + <actionGroup ref="AdminCreateWebsiteActionGroup" stepKey="adminCreateNewWebsite"> + <argument name="newWebsiteName" value="{{CustomWebSite.name}}"/> + <argument name="websiteCode" value="{{CustomWebSite.code}}"/> + </actionGroup> + <actionGroup ref="AdminCreateNewStoreGroupActionGroup" stepKey="adminCreateNewStore"> + <argument name="website" value="{{CustomWebSite.name}}"/> + <argument name="storeGroupName" value="{{customStore.name}}"/> + <argument name="storeGroupCode" value="{{customStore.code}}"/> + </actionGroup> + <actionGroup ref="AdminCreateStoreViewActionGroup" stepKey="adminCreateNewStoreView"> + <argument name="storeGroup" value="customStore"/> + </actionGroup> + </before> + <after> + <!--Delete all created data and set main website country options to default--> + <comment userInput="Delete all created data and set main website country options to default" stepKey="resetConfigToDefault"/> + <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> + <createData entity="CustomerAccountSharingSystemValue" stepKey="setAccountSharingToSystemValue"/> + <actionGroup ref="AdminDeleteWebsiteActionGroup" stepKey="deleteWebsite"> + <argument name="websiteName" value="{{CustomWebSite.name}}"/> + </actionGroup> + <actionGroup ref="NavigateToConfigurationGeneralPage" stepKey="navigateToConfigGeneralPage"/> + <actionGroup ref="AdminSwitchWebsiteActionGroup" stepKey="adminSwitchWebsiteActionGroup"> + <argument name="scopeName" value="_defaultWebsite.name"/> + </actionGroup> + <actionGroup ref="SetWebsiteCountryOptionsToDefaultActionGroup" stepKey="setCountryOptionsToDefault"/> + <actionGroup ref="logout" stepKey="logoutFromAdmin"/> + </after> + + <!--Check that all countries are allowed initially and get amount--> + <actionGroup ref="NavigateToConfigurationGeneralPage" stepKey="navigateToConfigGeneralPage"/> + <executeJS function="return document.querySelectorAll('{{CountryOptionsSection.allowedCountries}} option').length" stepKey="countriesAmount"/> + + <!-- Switch to first website, allow only Canada and set Canada as default country --> + <actionGroup ref="AdminSwitchWebsiteActionGroup" stepKey="adminSwitchWebsite"> + <argument name="scopeName" value="_defaultWebsite.name"/> + </actionGroup> + <actionGroup ref="AllowOnlyOneCountryActionGroup" stepKey="allowCanadaCountry"> + <argument name="country" value="Canada"/> + </actionGroup> + + <!--Switch to second website and allow all countries except Canada--> + <actionGroup ref="AdminSwitchWebsiteActionGroup" stepKey="adminSwitchToSecondWebsite"> + <argument name="scopeName" value="CustomWebSite.name"/> + </actionGroup> + <actionGroup ref="AllowAllCountriesExceptOneActionGroup" stepKey="allowAllCountriesExceptCanada"> + <argument name="country" value="Canada"/> + </actionGroup> + + <!--Open created customer details page and add Canada address--> + <amOnPage url="{{AdminEditCustomerPage.url($$createCustomer.id$$)}}" stepKey="goToCustomerEditPage"/> + <actionGroup ref="AdminAddCustomerAddressWithRegionTypeSelectActionGroup" stepKey="addAddressForCustomer"> + <argument name="customerAddress" value="Canada_Address"/> + </actionGroup> + + <!--Go to Customers grid and check that filter countries amount is the same as initial allowed countries amount--> + <amOnPage url="{{AdminCustomerPage.url}}" stepKey="goToCustomersGrid"/> + <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openFiltersSectionOnCustomersGrid"/> + <executeJS function="var len = document.querySelectorAll('{{AdminCustomerFiltersSection.countryOptions}}').length; return len-1;" stepKey="actualCountriesAmount"/> + <assertEquals expected='($countriesAmount)' actual="($actualCountriesAmount)" stepKey="assertCountryAmounts"/> + </test> +</tests> diff --git a/app/code/Magento/Customer/view/adminhtml/ui_component/customer_listing.xml b/app/code/Magento/Customer/view/adminhtml/ui_component/customer_listing.xml index f8aa078f45e4d..0e6f31a90243f 100644 --- a/app/code/Magento/Customer/view/adminhtml/ui_component/customer_listing.xml +++ b/app/code/Magento/Customer/view/adminhtml/ui_component/customer_listing.xml @@ -174,6 +174,7 @@ </column> <column name="billing_country_id" component="Magento_Ui/js/grid/columns/select" sortOrder="80"> <settings> + <options class="Magento\Customer\Model\ResourceModel\Address\Attribute\Source\CountryWithWebsites"/> <filter>select</filter> <dataType>select</dataType> <label translate="true">Country</label> From 08ecfe1efad526cb83fe0495e6e6f1459516b760 Mon Sep 17 00:00:00 2001 From: Serhii Balko <serhii.balko@transoftgroup.com> Date: Fri, 7 Jun 2019 11:37:53 +0300 Subject: [PATCH 1892/2092] MAGETWO-99111: Payment Method Not Showing Admin Sales Grid only check method showing --- app/code/Magento/Payment/Helper/Data.php | 31 ++++++++--- .../Magento/Payment/Helper/DataTest.php | 53 ++++++++++++++++--- 2 files changed, 68 insertions(+), 16 deletions(-) diff --git a/app/code/Magento/Payment/Helper/Data.php b/app/code/Magento/Payment/Helper/Data.php index 97dac29b4918b..5a3e76e8d89a1 100644 --- a/app/code/Magento/Payment/Helper/Data.php +++ b/app/code/Magento/Payment/Helper/Data.php @@ -147,7 +147,7 @@ public function getStoreMethods($store = null, $quote = null) } $res[] = $methodInstance; } - + // phpcs:ignore Generic.PHP.NoSilencedErrors @uasort( $res, function (MethodInterface $a, MethodInterface $b) { @@ -267,14 +267,12 @@ public function getPaymentMethodList($sorted = true, $asLabelValue = false, $wit $groupRelations = []; foreach ($this->getPaymentMethods() as $code => $data) { - if (!empty($data['active'])) { - $storedTitle = $this->getMethodInstance($code)->getConfigData('title', $store); - if (!empty($storedTitle)) { - $methods[$code] = $storedTitle; - } elseif (!empty($data['title'])) { - $methods[$code] = $data['title']; - } + $storeId = $store ? (int)$store->getId() : null; + $storedTitle = $this->getMethodStoreTitle($code, $storeId); + if (!empty($storedTitle)) { + $methods[$code] = $storedTitle; } + if ($asLabelValue && $withGroups && isset($data['group'])) { $groupRelations[$code] = $data['group']; } @@ -356,4 +354,21 @@ public function getZeroSubTotalPaymentAutomaticInvoice($store = null) $store ); } + + /** + * Get config title of payment method + * + * @param string $code + * @param int|null $storeId + * @return string + */ + private function getMethodStoreTitle(string $code, $storeId = null): string + { + $configPath = sprintf('%s/%s/title', self::XML_PATH_PAYMENT_METHODS, $code); + return (string) $this->scopeConfig->getValue( + $configPath, + \Magento\Store\Model\ScopeInterface::SCOPE_STORE, + $storeId + ); + } } diff --git a/dev/tests/integration/testsuite/Magento/Payment/Helper/DataTest.php b/dev/tests/integration/testsuite/Magento/Payment/Helper/DataTest.php index e6689b37151b7..18e230feea20c 100644 --- a/dev/tests/integration/testsuite/Magento/Payment/Helper/DataTest.php +++ b/dev/tests/integration/testsuite/Magento/Payment/Helper/DataTest.php @@ -3,22 +3,59 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +namespace Magento\Payment\Helper; + +use PHPUnit\Framework\TestCase; +use Magento\OfflinePayments\Block\Info\Checkmo; +use Magento\Payment\Model\Info; +use Magento\TestFramework\Helper\Bootstrap; /** * Test class for \Magento\Payment\Helper\Data */ -namespace Magento\Payment\Helper; - -class DataTest extends \PHPUnit\Framework\TestCase +class DataTest extends TestCase { + /** + * @var Data + */ + private $helper; + + /** + * @inheritdoc + */ + protected function setUp() + { + parent::setUp(); + + $this->helper = Bootstrap::getObjectManager()->get(Data::class); + } + + /** + * @return void + */ public function testGetInfoBlock() { - $helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Payment\Helper\Data::class); - $paymentInfo = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( - \Magento\Payment\Model\Info::class + $paymentInfo = Bootstrap::getObjectManager()->create( + Info::class ); $paymentInfo->setMethod('checkmo'); - $result = $helper->getInfoBlock($paymentInfo); - $this->assertInstanceOf(\Magento\OfflinePayments\Block\Info\Checkmo::class, $result); + $result = $this->helper->getInfoBlock($paymentInfo); + $this->assertInstanceOf(Checkmo::class, $result); + } + + /** + * Test to load Payment method title from the store config + * + * @magentoConfigFixture current_store payment/cashondelivery/title Cash On Delivery Title Of The Method + */ + public function testPaymentMethodLabelByStore() + { + $result = $this->helper->getPaymentMethodList(true, true); + $this->assertArrayHasKey('cashondelivery', $result, 'Payment info does not exist'); + $this->assertEquals( + 'Cash On Delivery Title Of The Method', + $result['cashondelivery']['label'], + 'Payment method title is not loaded from the store config' + ); } } From 08daad82fdfde389be7695dcab5765de4f5326a1 Mon Sep 17 00:00:00 2001 From: Serhii Balko <serhii.balko@transoftgroup.com> Date: Fri, 7 Jun 2019 13:14:00 +0300 Subject: [PATCH 1893/2092] MAGETWO-99111: Payment Method Not Showing Admin Sales Grid only check method showing --- .../Payment/Test/Unit/Helper/DataTest.php | 83 +++++++++---------- 1 file changed, 38 insertions(+), 45 deletions(-) diff --git a/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php b/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php index 1df07f87a3054..690f67fe28cac 100644 --- a/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php @@ -6,9 +6,9 @@ namespace Magento\Payment\Test\Unit\Helper; -use \Magento\Payment\Helper\Data; - use Magento\Framework\TestFramework\Unit\Matcher\MethodInvokedAtIndex; +use Magento\Payment\Helper\Data; +use Magento\Store\Model\ScopeInterface; class DataTest extends \PHPUnit\Framework\TestCase { @@ -37,6 +37,9 @@ class DataTest extends \PHPUnit\Framework\TestCase */ private $appEmulation; + /** + * @inheritDoc + */ protected function setUp() { $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); @@ -57,6 +60,9 @@ protected function setUp() $this->helper = $objectManagerHelper->getObject($className, $arguments); } + /** + * @return void + */ public function testGetMethodInstance() { list($code, $class, $methodInstance) = ['method_code', 'method_class', 'method_instance']; @@ -170,6 +176,9 @@ public function testSortMethods(array $methodA, array $methodB) ); } + /** + * @return void + */ public function testGetMethodFormBlock() { list($blockType, $methodCode) = ['method_block_type', 'method_code']; @@ -195,6 +204,9 @@ public function testGetMethodFormBlock() $this->assertSame($blockMock, $this->helper->getMethodFormBlock($methodMock, $layoutMock)); } + /** + * @return void` + */ public function testGetInfoBlock() { $blockType = 'method_block_type'; @@ -220,6 +232,9 @@ public function testGetInfoBlock() $this->assertSame($blockMock, $this->helper->getInfoBlock($infoMock)); } + /** + * @return void + */ public function testGetInfoBlockHtml() { list($storeId, $blockHtml, $secureMode, $blockType) = [1, 'HTML MARKUP', true, 'method_block_type']; @@ -257,6 +272,23 @@ public function testGetInfoBlockHtml() $this->assertEquals($blockHtml, $this->helper->getInfoBlockHtml($infoMock, $storeId)); } + /** + * @return array + */ + public function getSortMethodsDataProvider() + { + return [ + [ + ['code' => 'methodA', 'data' => ['sort_order' => 0]], + ['code' => 'methodB', 'data' => ['sort_order' => 1]] + ], + [ + ['code' => 'methodA', 'data' => ['sort_order' => 2]], + ['code' => 'methodB', 'data' => ['sort_order' => 1]], + ] + ]; + } + /** * @param bool $sorted * @param bool $asLabelValue @@ -288,17 +320,10 @@ public function testGetPaymentMethodList( ] ); + $titlePath = sprintf('%s/%s/title', Data::XML_PATH_PAYMENT_METHODS, $paymentMethod['code']); $this->scopeConfig->method('getValue') - ->with(sprintf('%s/%s/model', Data::XML_PATH_PAYMENT_METHODS, $paymentMethod['code'])) - ->willReturn(\Magento\Payment\Model\Method\AbstractMethod::class); - - $methodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) - ->getMockForAbstractClass(); - $methodInstanceMock->method('getConfigData') - ->with('title', null) + ->with($titlePath, ScopeInterface::SCOPE_STORE, null) ->willReturn($configTitle); - $this->methodFactory->method('create') - ->willReturn($methodInstanceMock); $this->paymentConfig->method('getGroups') ->willReturn($groups); @@ -307,23 +332,6 @@ public function testGetPaymentMethodList( $this->assertEquals($expectedPaymentMethodList, $paymentMethodList); } - /** - * @return array - */ - public function getSortMethodsDataProvider() - { - return [ - [ - ['code' => 'methodA', 'data' => ['sort_order' => 0]], - ['code' => 'methodB', 'data' => ['sort_order' => 1]] - ], - [ - ['code' => 'methodA', 'data' => ['sort_order' => 2]], - ['code' => 'methodB', 'data' => ['sort_order' => 1]], - ] - ]; - } - /** * @return array */ @@ -345,27 +353,12 @@ public function paymentMethodListDataProvider(): array ], ['payment_method' => 'Config Payment Title'], ], - 'Payment method with default title' => - [ - true, - false, - false, - null, - [ - 'code' => 'payment_method', - 'data' => [ - 'active' => 1, - 'title' => 'Payment Title', - ], - ], - ['payment_method' => 'Payment Title'], - ], 'Payment method as value => label' => [ true, true, false, - null, + 'Payment Title', [ 'code' => 'payment_method', 'data' => [ @@ -385,7 +378,7 @@ public function paymentMethodListDataProvider(): array true, true, true, - null, + 'Payment Title', [ 'code' => 'payment_method', 'data' => [ From 851bf23727aa82f032f6226876790c62cae0bf0f Mon Sep 17 00:00:00 2001 From: Andrea Parmeggiani <info@textarea.it> Date: Fri, 10 May 2019 18:03:38 +0200 Subject: [PATCH 1894/2092] Updated customer_account_forgotpassword.xml Missing question mark in Customer Account Forgot Password page title --- .../view/frontend/layout/customer_account_forgotpassword.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Customer/view/frontend/layout/customer_account_forgotpassword.xml b/app/code/Magento/Customer/view/frontend/layout/customer_account_forgotpassword.xml index 9a701c14a0307..24cede5f0232a 100644 --- a/app/code/Magento/Customer/view/frontend/layout/customer_account_forgotpassword.xml +++ b/app/code/Magento/Customer/view/frontend/layout/customer_account_forgotpassword.xml @@ -7,7 +7,7 @@ --> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> - <title>Forgot Your Password + Forgot Your Password? From f1e8d055cbe9b7890afa675d35d25f3c175672b5 Mon Sep 17 00:00:00 2001 From: Arvinda kumar Date: Sat, 4 May 2019 11:23:36 +0530 Subject: [PATCH 1895/2092] Issue fixed #22636 Issue fixed #22636 --- .../web/css/source/module/main/_collapsible-blocks.less | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less index 248c7d2947174..aa92fecef4ccf 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less +++ b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less @@ -105,11 +105,17 @@ // .admin__collapsible-block-wrapper { + .admin__collapsible-title[aria-expanded="true"]{ + &:before { + content: @icon-expand-close__content; + } + } + .__collapsible-block-wrapper-pattern(); .admin__collapsible-title { .__collapsible-title-pattern(); } - + &.opened, &._show { > .fieldset-wrapper-title { From f4653b1997ad523bd69046e5854477643b9f285a Mon Sep 17 00:00:00 2001 From: Arvinda kumar Date: Sat, 4 May 2019 12:48:32 +0530 Subject: [PATCH 1896/2092] _collapsible-blocks.less updated _collapsible-blocks.less updated --- .../web/css/source/module/main/_collapsible-blocks.less | 1 - 1 file changed, 1 deletion(-) diff --git a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less index aa92fecef4ccf..ecc66aaefcc55 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less +++ b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less @@ -115,7 +115,6 @@ .admin__collapsible-title { .__collapsible-title-pattern(); } - &.opened, &._show { > .fieldset-wrapper-title { From eff816e8863a6a5330e0b863906aa18f18f95c7b Mon Sep 17 00:00:00 2001 From: nmalevanec Date: Mon, 6 May 2019 11:47:48 +0300 Subject: [PATCH 1897/2092] Fix static tests. --- .../web/css/source/module/main/_collapsible-blocks.less | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less index ecc66aaefcc55..4f173dcb3adaa 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less +++ b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less @@ -105,7 +105,7 @@ // .admin__collapsible-block-wrapper { - .admin__collapsible-title[aria-expanded="true"]{ + .admin__collapsible-title[aria-expanded='true'] { &:before { content: @icon-expand-close__content; } From 70d0992d84a9fe149550ca2a22de54e0f2e7b068 Mon Sep 17 00:00:00 2001 From: mahesh Date: Tue, 7 May 2019 19:27:04 +0530 Subject: [PATCH 1898/2092] fixed issue #22767, changed the magic method type changed the magic method type for Block Model as well --- app/code/Magento/Cms/Model/Block.php | 4 ++-- app/code/Magento/Cms/Model/Page.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/code/Magento/Cms/Model/Block.php b/app/code/Magento/Cms/Model/Block.php index 3795409a95d2b..41eb509d08061 100644 --- a/app/code/Magento/Cms/Model/Block.php +++ b/app/code/Magento/Cms/Model/Block.php @@ -12,8 +12,8 @@ /** * CMS block model * - * @method Block setStoreId(array $storeId) - * @method array getStoreId() + * @method Block setStoreId(int $storeId) + * @method int getStoreId() */ class Block extends AbstractModel implements BlockInterface, IdentityInterface { diff --git a/app/code/Magento/Cms/Model/Page.php b/app/code/Magento/Cms/Model/Page.php index d950f484cd1d9..61c33deee593f 100644 --- a/app/code/Magento/Cms/Model/Page.php +++ b/app/code/Magento/Cms/Model/Page.php @@ -16,8 +16,8 @@ * Cms Page Model * * @api - * @method Page setStoreId(array $storeId) - * @method array getStoreId() + * @method Page setStoreId(int $storeId) + * @method int getStoreId() * @SuppressWarnings(PHPMD.ExcessivePublicCount) * @since 100.0.2 */ From 70aacf1090f7b8269f71a6be883bbfab2ba9d262 Mon Sep 17 00:00:00 2001 From: Nazarn96 Date: Fri, 24 May 2019 11:17:18 +0300 Subject: [PATCH 1899/2092] magento/magento2#22772 static-test-fix --- app/code/Magento/Cms/Model/Block.php | 2 ++ app/code/Magento/Cms/Model/Page.php | 10 +++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/app/code/Magento/Cms/Model/Block.php b/app/code/Magento/Cms/Model/Block.php index 41eb509d08061..a8b8661bfb913 100644 --- a/app/code/Magento/Cms/Model/Block.php +++ b/app/code/Magento/Cms/Model/Block.php @@ -41,6 +41,8 @@ class Block extends AbstractModel implements BlockInterface, IdentityInterface protected $_eventPrefix = 'cms_block'; /** + * Construct. + * * @return void */ protected function _construct() diff --git a/app/code/Magento/Cms/Model/Page.php b/app/code/Magento/Cms/Model/Page.php index 61c33deee593f..8eefe26236ba5 100644 --- a/app/code/Magento/Cms/Model/Page.php +++ b/app/code/Magento/Cms/Model/Page.php @@ -103,8 +103,7 @@ public function getStores() } /** - * Check if page identifier exist for specific store - * return page id if page exists + * Check if page identifier exist for specific store return page id if page exists * * @param string $identifier * @param int $storeId @@ -116,8 +115,7 @@ public function checkIdentifier($identifier, $storeId) } /** - * Prepare page's statuses. - * Available event cms_page_get_available_statuses to customize statuses. + * Prepare page's statuses, available event cms_page_get_available_statuses to customize statuses. * * @return array */ @@ -538,7 +536,7 @@ public function setIsActive($isActive) } /** - * {@inheritdoc} + * @inheritdoc * @since 101.0.0 */ public function beforeSave() @@ -571,6 +569,8 @@ public function beforeSave() } /** + * Returns scope config. + * * @return ScopeConfigInterface */ private function getScopeConfig() From 3cf349fb4adc54b30956a9ee03444af6d4f0e71a Mon Sep 17 00:00:00 2001 From: Serhii Balko Date: Fri, 7 Jun 2019 16:03:13 +0300 Subject: [PATCH 1900/2092] MAGETWO-96662: UrlRewrite removes query string from url, if url has trailing slash --- .../Magento/UrlRewrite/Controller/Router.php | 37 ++++- .../Test/Unit/Controller/RouterTest.php | 142 ++++++++++++++---- .../UrlRewrite/Controller/UrlRewriteTest.php | 32 +++- .../_files/url_rewrite_rollback.php | 1 - 4 files changed, 169 insertions(+), 43 deletions(-) diff --git a/app/code/Magento/UrlRewrite/Controller/Router.php b/app/code/Magento/UrlRewrite/Controller/Router.php index ed2a56d9b5229..a9ac991b428e7 100644 --- a/app/code/Magento/UrlRewrite/Controller/Router.php +++ b/app/code/Magento/UrlRewrite/Controller/Router.php @@ -6,6 +6,7 @@ namespace Magento\UrlRewrite\Controller; use Magento\Framework\App\Request\Http as HttpRequest; +use Magento\Framework\App\RequestInterface; use Magento\Framework\App\Response\Http as HttpResponse; use Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite; use Magento\UrlRewrite\Model\UrlFinderInterface; @@ -70,13 +71,13 @@ public function __construct( /** * Match corresponding URL Rewrite and modify request * - * @param \Magento\Framework\App\RequestInterface|HttpRequest $request + * @param RequestInterface|HttpRequest $request * @return ActionInterface|null */ - public function match(\Magento\Framework\App\RequestInterface $request) + public function match(RequestInterface $request) { $rewrite = $this->getRewrite( - $request->getPathInfo(), + $this->getNormalizedPathInfo($request), $this->storeManager->getStore()->getId() ); if ($rewrite === null) { @@ -101,7 +102,7 @@ public function match(\Magento\Framework\App\RequestInterface $request) } /** - * @param \Magento\Framework\App\RequestInterface $request + * @param RequestInterface $request * @param UrlRewrite $rewrite * @return ActionInterface|null */ @@ -117,7 +118,7 @@ protected function processRedirect($request, $rewrite) } /** - * @param \Magento\Framework\App\RequestInterface|HttpRequest $request + * @param RequestInterface|HttpRequest $request * @param string $url * @param int $code * @return ActionInterface @@ -142,4 +143,30 @@ protected function getRewrite($requestPath, $storeId) UrlRewrite::STORE_ID => $storeId, ]); } + + /** + * Get normalized request path + * + * @param RequestInterface|HttpRequest $request + * @return string + */ + private function getNormalizedPathInfo(RequestInterface $request): string + { + $path = (string)$request->getPathInfo(); + /** + * If request contains query params then we need to trim a slash in end of the path. + * For example: + * the original request is: http://my-host.com/category-url-key.html/?color=black + * where the original path is: category-url-key.html/ + * and the result path will be: category-url-key.html + * + * It need to except a redirect like this: + * http://my-host.com/category-url-key.html/?color=black => http://my-host.com/category-url-key.html + */ + if (!empty($path) && $request->getQuery()->count()) { + $path = rtrim($path, '/'); + } + + return $path; + } } diff --git a/app/code/Magento/UrlRewrite/Test/Unit/Controller/RouterTest.php b/app/code/Magento/UrlRewrite/Test/Unit/Controller/RouterTest.php index 60b371ae9a893..c6691f6e370d1 100644 --- a/app/code/Magento/UrlRewrite/Test/Unit/Controller/RouterTest.php +++ b/app/code/Magento/UrlRewrite/Test/Unit/Controller/RouterTest.php @@ -3,57 +3,87 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\UrlRewrite\Test\Unit\Controller; use Magento\Framework\App\Action\Forward; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\UrlInterface; use Magento\UrlRewrite\Service\V1\Data\UrlRewrite; use Magento\Store\Model\Store; +use PHPUnit\Framework\MockObject\MockObject; +use Zend\Stdlib\ParametersInterface; /** + * Test class for UrlRewrite Controller Router + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class RouterTest extends \PHPUnit\Framework\TestCase { - /** @var \Magento\UrlRewrite\Controller\Router */ - protected $router; + /** + * @var \Magento\UrlRewrite\Controller\Router + */ + private $router; + + /** + * @var \Magento\Framework\App\ActionFactory|MockObject + */ + private $actionFactory; - /** @var \Magento\Framework\App\ActionFactory|\PHPUnit_Framework_MockObject_MockObject */ - protected $actionFactory; + /** + * @var UrlInterface|MockObject + */ + private $url; - /** @var \Magento\Framework\UrlInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $url; + /** + * @var \Magento\Store\Model\StoreManagerInterface|MockObject + */ + private $storeManager; - /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $storeManager; + /** + * @var Store|MockObject + */ + private $store; - /** @var Store|\PHPUnit_Framework_MockObject_MockObject */ - protected $store; + /** + * @var \Magento\Framework\App\ResponseInterface|MockObject + */ + private $response; - /** @var \Magento\Framework\App\ResponseInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $response; + /** + * @var \Magento\Framework\App\RequestInterface|MockObject + */ + private $request; - /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $request; + /** + * @var ParametersInterface|MockObject + */ + private $requestQuery; - /** @var \Magento\UrlRewrite\Model\UrlFinderInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $urlFinder; + /** + * @var \Magento\UrlRewrite\Model\UrlFinderInterface|MockObject + */ + private $urlFinder; + /** + * @inheritDoc + */ protected function setUp() { $this->actionFactory = $this->createMock(\Magento\Framework\App\ActionFactory::class); - $this->url = $this->createMock(\Magento\Framework\UrlInterface::class); + $this->url = $this->createMock(UrlInterface::class); $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); $this->response = $this->createPartialMock( \Magento\Framework\App\ResponseInterface::class, ['setRedirect', 'sendResponse'] ); + $this->requestQuery = $this->createMock(ParametersInterface::class); $this->request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) ->disableOriginalConstructor()->getMock(); + $this->request->method('getQuery')->willReturn($this->requestQuery); $this->urlFinder = $this->createMock(\Magento\UrlRewrite\Model\UrlFinderInterface::class); $this->store = $this->getMockBuilder( - \Magento\Store\Model\Store::class + Store::class )->disableOriginalConstructor()->getMock(); $this->router = (new ObjectManager($this))->getObject( @@ -158,17 +188,17 @@ public function testNoRewriteAfterStoreSwitcherWhenNoOldRewrite() $this->request->expects($this->any())->method('getPathInfo')->will($this->returnValue('request-path')); $this->request->expects($this->any())->method('getParam')->with('___from_store') ->will($this->returnValue('old-store')); - $oldStore = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $oldStore = $this->getMockBuilder(Store::class)->disableOriginalConstructor()->getMock(); $this->storeManager->expects($this->any())->method('getStore') ->will($this->returnValueMap([['old-store', $oldStore], [null, $this->store]])); $oldStore->expects($this->any())->method('getId')->will($this->returnValue('old-store-id')); $this->store->expects($this->any())->method('getId')->will($this->returnValue('current-store-id')); - $oldUrlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $oldUrlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor()->getMock(); $oldUrlRewrite->expects($this->any())->method('getEntityType')->will($this->returnValue('entity-type')); $oldUrlRewrite->expects($this->any())->method('getEntityId')->will($this->returnValue('entity-id')); $oldUrlRewrite->expects($this->any())->method('getRequestPath')->will($this->returnValue('request-path')); - $urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $urlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor()->getMock(); $urlRewrite->expects($this->any())->method('getRequestPath')->will($this->returnValue('request-path')); @@ -180,17 +210,17 @@ public function testNoRewriteAfterStoreSwitcherWhenOldRewriteEqualsToNewOne() $this->request->expects($this->any())->method('getPathInfo')->will($this->returnValue('request-path')); $this->request->expects($this->any())->method('getParam')->with('___from_store') ->will($this->returnValue('old-store')); - $oldStore = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); + $oldStore = $this->getMockBuilder(Store::class)->disableOriginalConstructor()->getMock(); $this->storeManager->expects($this->any())->method('getStore') ->will($this->returnValueMap([['old-store', $oldStore], [null, $this->store]])); $oldStore->expects($this->any())->method('getId')->will($this->returnValue('old-store-id')); $this->store->expects($this->any())->method('getId')->will($this->returnValue('current-store-id')); - $oldUrlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $oldUrlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor()->getMock(); $oldUrlRewrite->expects($this->any())->method('getEntityType')->will($this->returnValue('entity-type')); $oldUrlRewrite->expects($this->any())->method('getEntityId')->will($this->returnValue('entity-id')); $oldUrlRewrite->expects($this->any())->method('getRequestPath')->will($this->returnValue('old-request-path')); - $urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $urlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor()->getMock(); $urlRewrite->expects($this->any())->method('getRequestPath')->will($this->returnValue('old-request-path')); @@ -218,7 +248,7 @@ public function testNoRewriteAfterStoreSwitcherWhenOldRewriteEqualsToNewOne() public function testMatchWithRedirect() { $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); - $urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $urlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor()->getMock(); $urlRewrite->expects($this->any())->method('getRedirectType')->will($this->returnValue('redirect-code')); $urlRewrite->expects($this->any())->method('getTargetPath')->will($this->returnValue('target-path')); @@ -237,7 +267,7 @@ public function testMatchWithRedirect() public function testMatchWithCustomInternalRedirect() { $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); - $urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $urlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor()->getMock(); $urlRewrite->expects($this->any())->method('getEntityType')->will($this->returnValue('custom')); $urlRewrite->expects($this->any())->method('getRedirectType')->will($this->returnValue('redirect-code')); @@ -259,7 +289,7 @@ public function testMatchWithCustomInternalRedirect() public function testMatchWithCustomExternalRedirect($targetPath) { $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); - $urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $urlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor()->getMock(); $urlRewrite->expects($this->any())->method('getEntityType')->will($this->returnValue('custom')); $urlRewrite->expects($this->any())->method('getRedirectType')->will($this->returnValue('redirect-code')); @@ -288,7 +318,7 @@ public function externalRedirectTargetPathDataProvider() public function testMatch() { $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($this->store)); - $urlRewrite = $this->getMockBuilder(\Magento\UrlRewrite\Service\V1\Data\UrlRewrite::class) + $urlRewrite = $this->getMockBuilder(UrlRewrite::class) ->disableOriginalConstructor()->getMock(); $urlRewrite->expects($this->any())->method('getRedirectType')->will($this->returnValue(0)); $urlRewrite->expects($this->any())->method('getTargetPath')->will($this->returnValue('target-path')); @@ -296,10 +326,60 @@ public function testMatch() $this->urlFinder->expects($this->any())->method('findOneByData')->will($this->returnValue($urlRewrite)); $this->request->expects($this->once())->method('setPathInfo')->with('/target-path'); $this->request->expects($this->once())->method('setAlias') - ->with(\Magento\Framework\UrlInterface::REWRITE_REQUEST_PATH_ALIAS, 'request-path'); + ->with(UrlInterface::REWRITE_REQUEST_PATH_ALIAS, 'request-path'); $this->actionFactory->expects($this->once())->method('create') - ->with(\Magento\Framework\App\Action\Forward::class); + ->with(Forward::class); + + $this->router->match($this->request); + } + + /** + * Test to match corresponding URL Rewrite on request with query params + * + * @param string $originalRequestPath + * @param string $requestPath + * @param int $countOfQueryParams + * @dataProvider matchWithQueryParamsDataProvider + */ + public function testMatchWithQueryParams(string $originalRequestPath, string $requestPath, int $countOfQueryParams) + { + $targetPath = 'target-path'; + + $this->storeManager->method('getStore')->willReturn($this->store); + $urlRewrite = $this->createMock(UrlRewrite::class); + $urlRewrite->method('getRedirectType')->willReturn(0); + $urlRewrite->method('getTargetPath')->willReturn($targetPath); + $urlRewrite->method('getRequestPath')->willReturn($requestPath); + $this->urlFinder->method('findOneByData') + ->with([UrlRewrite::REQUEST_PATH => $requestPath, UrlRewrite::STORE_ID => $this->store->getId()]) + ->willReturn($urlRewrite); + + $this->requestQuery->method('count')->willReturn($countOfQueryParams); + $this->request->method('getPathInfo') + ->willReturn($originalRequestPath); + $this->request->expects($this->once()) + ->method('setPathInfo') + ->with('/' . $targetPath); + $this->request->expects($this->once()) + ->method('setAlias') + ->with(UrlInterface::REWRITE_REQUEST_PATH_ALIAS, $requestPath); + $this->actionFactory->expects($this->once()) + ->method('create') + ->with(Forward::class); $this->router->match($this->request); } + + /** + * Data provider for Test to match corresponding URL Rewrite on request with query params + * + * @return array + */ + public function matchWithQueryParamsDataProvider(): array + { + return [ + ['/category.html/', 'category.html/', 0], + ['/category.html/', 'category.html', 1], + ]; + } } diff --git a/dev/tests/integration/testsuite/Magento/UrlRewrite/Controller/UrlRewriteTest.php b/dev/tests/integration/testsuite/Magento/UrlRewrite/Controller/UrlRewriteTest.php index c0ceb022dad45..e02550a20f6d9 100644 --- a/dev/tests/integration/testsuite/Magento/UrlRewrite/Controller/UrlRewriteTest.php +++ b/dev/tests/integration/testsuite/Magento/UrlRewrite/Controller/UrlRewriteTest.php @@ -5,6 +5,9 @@ */ namespace Magento\UrlRewrite\Controller; +/** + * Class to test Match corresponding URL Rewrite + */ class UrlRewriteTest extends \Magento\TestFramework\TestCase\AbstractController { /** @@ -26,14 +29,26 @@ public function testMatchUrlRewrite( $expectedCode = 301 ) { $this->dispatch($request); - $code = $this->getResponse()->getHttpResponseCode(); - $location = $this->getResponse()->getHeader('Location')->getFieldValue(); - + $response = $this->getResponse(); + $code = $response->getHttpResponseCode(); $this->assertEquals($expectedCode, $code, 'Invalid response code'); - $this->assertStringEndsWith($redirect, $location, 'Invalid location header'); + + if ($expectedCode !== 200) { + $location = $response->getHeader('Location')->getFieldValue(); + $this->assertStringEndsWith( + $redirect, + $location, + 'Invalid location header' + ); + } } - public function requestDataProvider() + /** + * Data provider for testMatchUrlRewrite + * + * @return array + */ + public function requestDataProvider(): array { return [ 'Use Case #1: Rewrite: page-one/ --(301)--> page-a/; Request: page-one/ --(301)--> page-a/' => [ @@ -59,7 +74,12 @@ public function requestDataProvider() 'Use Case #6: Rewrite: page-similar/ --(301)--> page-b; Request: page-similar/ --(301)--> page-b' => [ 'request' => '/page-similar/', 'redirect' => '/page-b', - ] + ], + 'Use Case #7: Request with query params' => [ + 'request' => '/enable-cookies/?test-param', + 'redirect' => '', + 200, + ], ]; } } diff --git a/dev/tests/integration/testsuite/Magento/UrlRewrite/_files/url_rewrite_rollback.php b/dev/tests/integration/testsuite/Magento/UrlRewrite/_files/url_rewrite_rollback.php index 6938cf9512de7..c37a4100bb214 100644 --- a/dev/tests/integration/testsuite/Magento/UrlRewrite/_files/url_rewrite_rollback.php +++ b/dev/tests/integration/testsuite/Magento/UrlRewrite/_files/url_rewrite_rollback.php @@ -20,7 +20,6 @@ $collection = $urlRewriteCollection ->addFieldToFilter('entity_type', 'custom') ->addFieldToFilter('request_path', ['page-a', 'page-b', 'page-c']) - ->addFieldToFilter('entity_id', '333') ->load() ->walk('delete'); From af9949fc10b53a528b2e9a3d3204efc5c5c26d4a Mon Sep 17 00:00:00 2001 From: Roman Lytvynenko Date: Fri, 7 Jun 2019 11:35:29 -0500 Subject: [PATCH 1901/2092] MAGETWO-99491: Configurable options attribute position is not saved correctly via API --- .../ConfigurableProduct/Model/LinkManagement.php | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/app/code/Magento/ConfigurableProduct/Model/LinkManagement.php b/app/code/Magento/ConfigurableProduct/Model/LinkManagement.php index fcbd0075b4cd0..7e11fd02793ea 100644 --- a/app/code/Magento/ConfigurableProduct/Model/LinkManagement.php +++ b/app/code/Magento/ConfigurableProduct/Model/LinkManagement.php @@ -131,15 +131,17 @@ public function addChild($sku, $childSku) throw new StateException(__('Parent product does not have configurable product options')); } - $attributeIds = []; + $attributeData = []; foreach ($configurableProductOptions as $configurableProductOption) { $attributeCode = $configurableProductOption->getProductAttribute()->getAttributeCode(); if (!$child->getData($attributeCode)) { throw new StateException(__('Child product does not have attribute value %1', $attributeCode)); } - $attributeIds[] = $configurableProductOption->getAttributeId(); + $attributeData[$configurableProductOption->getAttributeId()] = [ + 'position' => $configurableProductOption->getPosition() + ]; } - $configurableOptionData = $this->getConfigurableAttributesData($attributeIds); + $configurableOptionData = $this->getConfigurableAttributesData($attributeData); /** @var \Magento\ConfigurableProduct\Helper\Product\Options\Factory $optionFactory */ $optionFactory = $this->getOptionsFactory(); @@ -203,16 +205,16 @@ private function getOptionsFactory() /** * Get Configurable Attribute Data * - * @param int[] $attributeIds + * @param int[] $attributeData * @return array */ - private function getConfigurableAttributesData($attributeIds) + private function getConfigurableAttributesData($attributeData) { $configurableAttributesData = []; $attributeValues = []; $attributes = $this->attributeFactory->create() ->getCollection() - ->addFieldToFilter('attribute_id', $attributeIds) + ->addFieldToFilter('attribute_id', array_keys($attributeData)) ->getItems(); foreach ($attributes as $attribute) { foreach ($attribute->getOptions() as $option) { @@ -229,6 +231,7 @@ private function getConfigurableAttributesData($attributeIds) 'attribute_id' => $attribute->getId(), 'code' => $attribute->getAttributeCode(), 'label' => $attribute->getStoreLabel(), + 'position' => $attributeData[$attribute->getId()]['position'], 'values' => $attributeValues, ]; } From f7bfb8a9ab25ebe19cbc6a4f596b3100efb407cd Mon Sep 17 00:00:00 2001 From: Roman Lytvynenko Date: Fri, 7 Jun 2019 13:12:39 -0500 Subject: [PATCH 1902/2092] MAGETWO-99491: Configurable options attribute position is not saved correctly via API --- .../Test/Unit/Model/LinkManagementTest.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/LinkManagementTest.php b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/LinkManagementTest.php index acbb976318b3b..279880d546424 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Unit/Model/LinkManagementTest.php +++ b/app/code/Magento/ConfigurableProduct/Test/Unit/Model/LinkManagementTest.php @@ -158,7 +158,7 @@ public function testAddChild() ->getMock(); $optionMock = $this->getMockBuilder(\Magento\ConfigurableProduct\Api\Data\Option::class) ->disableOriginalConstructor() - ->setMethods(['getProductAttribute', 'getAttributeId']) + ->setMethods(['getProductAttribute', 'getPosition', 'getAttributeId']) ->getMock(); $productAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) ->disableOriginalConstructor() @@ -216,6 +216,7 @@ public function testAddChild() $productAttributeMock->expects($this->any())->method('getAttributeCode')->willReturn('color'); $simple->expects($this->any())->method('getData')->willReturn('color'); $optionMock->expects($this->any())->method('getAttributeId')->willReturn('1'); + $optionMock->expects($this->any())->method('getPosition')->willReturn('0'); $optionsFactoryMock->expects($this->any())->method('create')->willReturn([$optionMock]); $attributeFactoryMock->expects($this->any())->method('create')->willReturn($attributeMock); @@ -223,6 +224,7 @@ public function testAddChild() $attributeCollectionMock->expects($this->any())->method('addFieldToFilter')->willReturnSelf(); $attributeCollectionMock->expects($this->any())->method('getItems')->willReturn([$attributeMock]); + $attributeMock->expects($this->any())->method('getId')->willReturn(1); $attributeMock->expects($this->any())->method('getOptions')->willReturn([$attributeOptionMock]); $extensionAttributesMock->expects($this->any())->method('setConfigurableProductOptions'); From 6ac6f221758baa5626c42a67008636bb9108ad47 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov Date: Fri, 7 Jun 2019 16:52:32 -0500 Subject: [PATCH 1903/2092] MAGETWO-99930: Configuarable product stock status stays 'In Stock' --- .../Model/Inventory/ParentItemProcessor.php | 18 ++-- .../SaveInventoryDataObserverTest.php | 85 +++++++++++++++++++ 2 files changed, 95 insertions(+), 8 deletions(-) create mode 100644 dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php diff --git a/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php b/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php index fbc38d353e248..53e25a3501a0f 100644 --- a/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php +++ b/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php @@ -73,20 +73,22 @@ public function process(Product $product) */ private function processStockForParent(int $productId) { - $childrenIds = $this->configurableType->getChildrenIds($productId); - $allIds = $childrenIds; - $allIds[] = $productId; - $criteria = $this->criteriaInterfaceFactory->create(); - $criteria->setProductsFilter($allIds); $criteria->setScopeFilter($this->stockConfiguration->getDefaultScopeId()); + + $criteria->setProductsFilter($productId); $stockItemCollection = $this->stockItemRepository->getList($criteria); $allItems = $stockItemCollection->getItems(); - if (empty($allItems[$productId])) { + if (empty($allItems)) { return; } - $parentStockItem = $allItems[$productId]; - unset($allItems[$productId]); + $parentStockItem = array_shift($allItems); + + $childrenIds = $this->configurableType->getChildrenIds($productId); + $criteria->setProductsFilter($childrenIds); + $stockItemCollection = $this->stockItemRepository->getList($criteria); + $allItems = $stockItemCollection->getItems(); + $childrenIsInStock = false; foreach ($allItems as $childItem) { diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php new file mode 100644 index 0000000000000..1b986b7670a1c --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php @@ -0,0 +1,85 @@ +productRepository = Bootstrap::getObjectManager() + ->get(ProductRepositoryInterface::class); + $this->stockItemRepository = Bootstrap::getObjectManager() + ->get(StockItemRepositoryInterface::class); + } + + /** + * Check that parent product will be out of stock + * + * @magentoAppArea adminhtml + * @magentoAppIsolation enabled + * @magentoDataFixture Magento/CatalogInventory/_files/configurable_options_with_low_stock.php + * @throws NoSuchEntityException + * @throws InputException + * @throws StateException + * @throws CouldNotSaveException + * @return void + */ + public function testAutoChangingIsInStockForParent() + { + /** @var ProductInterface $product */ + $product = $this->productRepository->get('simple_10'); + + /** @var ProductExtensionInterface $attributes*/ + $attributes = $product->getExtensionAttributes(); + + /** @var StockItemInterface $stockItem */ + $stockItem = $attributes->getStockItem(); + $stockItem->setQty(0); + $stockItem->setIsInStock(false); + $attributes->setStockItem($stockItem); + $product->setExtensionAttributes($attributes); + $this->productRepository->save($product); + + /** @var ProductInterface $product */ + $parentProduct = $this->productRepository->get('configurable'); + + $parentProductStockItem = $this->stockItemRepository->get( + $parentProduct->getExtensionAttributes()->getStockItem()->getItemId() + ); + $this->assertSame(false, $parentProductStockItem->getIsInStock()); + } +} From 974e6f5b78dc63f669b4439fba8254bee9b40ded Mon Sep 17 00:00:00 2001 From: DianaRusin Date: Mon, 10 Jun 2019 10:22:17 +0300 Subject: [PATCH 1904/2092] MAGETWO-86624: [2.2] Allowed countries restriction for a default website is applied to backend customer grid --- .../ActionGroup/ConfigurationActionGroup.xml | 5 --- .../AdminWebsiteCountryOptionsActionGroup.xml | 32 +++++++++---------- .../Config/Test/Mftf/Page/AdminConfigPage.xml | 3 -- .../Test/Mftf/Section/GeneralSection.xml | 10 ------ .../Section/AdminCustomerFiltersSection.xml | 2 +- ...CountriesRestrictionApplyOnBackendTest.xml | 7 ++-- .../AdminConfigurationGeneralSectionPage.xml | 1 + ...figurationGeneralCountryOptionsSection.xml | 21 ++++++++++++ 8 files changed, 42 insertions(+), 39 deletions(-) create mode 100644 app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/ConfigurationActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/ConfigurationActionGroup.xml index 1f6b992df61e6..6164cdde22e60 100644 --- a/app/code/Magento/Backend/Test/Mftf/ActionGroup/ConfigurationActionGroup.xml +++ b/app/code/Magento/Backend/Test/Mftf/ActionGroup/ConfigurationActionGroup.xml @@ -7,11 +7,6 @@ --> - - - - - diff --git a/app/code/Magento/Config/Test/Mftf/ActionGroup/AdminWebsiteCountryOptionsActionGroup.xml b/app/code/Magento/Config/Test/Mftf/ActionGroup/AdminWebsiteCountryOptionsActionGroup.xml index ec7ac620fd66d..8dda48399d2ef 100644 --- a/app/code/Magento/Config/Test/Mftf/ActionGroup/AdminWebsiteCountryOptionsActionGroup.xml +++ b/app/code/Magento/Config/Test/Mftf/ActionGroup/AdminWebsiteCountryOptionsActionGroup.xml @@ -12,29 +12,27 @@ - - - - - - - - - + + + + + + + + - + - - - - - - - + + + + + + diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml index efd1ceda79a75..ded825ea89098 100644 --- a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml @@ -9,7 +9,4 @@
    - -
    - diff --git a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml index df8ef03a07015..18a124ac669ec 100644 --- a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml +++ b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml @@ -32,14 +32,4 @@
    -
    - - - - - - - - -
    diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml index b87b89a0017d6..dccf879280876 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml @@ -7,7 +7,7 @@ --> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd">
    diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml index 888f66d1d03d3..1a5374ca19831 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml @@ -12,6 +12,7 @@ <description value="Country filter on Customers page when allowed countries restriction for a default website is applied"/> <features value="Customer"/> + <stories value="Customer grid filter by country"/> <severity value="MAJOR"/> <testCaseId value="MC-17282"/> <useCaseId value="MAGETWO-86624"/> @@ -44,7 +45,7 @@ <actionGroup ref="AdminDeleteWebsiteActionGroup" stepKey="deleteWebsite"> <argument name="websiteName" value="{{CustomWebSite.name}}"/> </actionGroup> - <actionGroup ref="NavigateToConfigurationGeneralPage" stepKey="navigateToConfigGeneralPage"/> + <amOnPage url="{{AdminConfigurationGeneralSectionPage.url('#general_country-link')}}" stepKey="goToConfigurationSectionPage"/> <actionGroup ref="AdminSwitchWebsiteActionGroup" stepKey="adminSwitchWebsiteActionGroup"> <argument name="scopeName" value="_defaultWebsite.name"/> </actionGroup> @@ -53,8 +54,8 @@ </after> <!--Check that all countries are allowed initially and get amount--> - <actionGroup ref="NavigateToConfigurationGeneralPage" stepKey="navigateToConfigGeneralPage"/> - <executeJS function="return document.querySelectorAll('{{CountryOptionsSection.allowedCountries}} option').length" stepKey="countriesAmount"/> + <amOnPage url="{{AdminConfigurationGeneralSectionPage.url('#general_country-link')}}" stepKey="goToCountryConfigurationSectionPage"/> + <executeJS function="return document.querySelectorAll('{{AdminConfigurationGeneralCountryOptionsSection.allowedCountries}} option').length" stepKey="countriesAmount"/> <!-- Switch to first website, allow only Canada and set Canada as default country --> <actionGroup ref="AdminSwitchWebsiteActionGroup" stepKey="adminSwitchWebsite"> diff --git a/app/code/Magento/Directory/Test/Mftf/Page/AdminConfigurationGeneralSectionPage.xml b/app/code/Magento/Directory/Test/Mftf/Page/AdminConfigurationGeneralSectionPage.xml index 732a27504a97d..30016d9fa650a 100644 --- a/app/code/Magento/Directory/Test/Mftf/Page/AdminConfigurationGeneralSectionPage.xml +++ b/app/code/Magento/Directory/Test/Mftf/Page/AdminConfigurationGeneralSectionPage.xml @@ -9,5 +9,6 @@ xsi:noNamespaceSchemaLocation="../../../../../../../dev/tests/acceptance/vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Page/etc/PageObject.xsd"> <page name="AdminConfigurationGeneralSectionPage" url="admin/system_config/edit/section/general/{{group_anchor}}" parameterized="true" area="admin" module="Magento_Config"> <section name="AdminConfigurationGeneralSectionStateOptionsGroupSection"/> + <section name="AdminConfigurationGeneralCountryOptionsSection"/> </page> </pages> diff --git a/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml b/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml new file mode 100644 index 0000000000000..1e7c3abaaa77a --- /dev/null +++ b/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> + <!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + --> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminConfigurationGeneralCountryOptionsSection"> + <element name="allowedCountries" type="select" selector="#general_country_allow"/> + <element name="notAllowedCountry" type="button" selector="#general_country_allow option:not([selected])"/> + <element name="generalCountryAllowInherit" type="checkbox" selector="#general_country_allow_inherit"/> + <element name="generalCountryDefaultInherit" type="checkbox" selector="#general_country_default_inherit"/> + <element name="generalCountryDefault" type="select" selector="#general_country_default"/> + <element name="countryOptions" type="button" selector="#general_country-head"/> + <element name="countryOptionsOpen" type="button" selector="#general_country-head.open"/> + <element name="topDestinations" type="select" selector="#general_country_destinations"/> + </section> +</sections> From 523a0c0b7ebcfdc633aebafa113e791205268cd9 Mon Sep 17 00:00:00 2001 From: Pavel Bystritsky <p.bystritsky@yandex.ru> Date: Mon, 10 Jun 2019 12:41:42 +0300 Subject: [PATCH 1905/2092] magento/magento2#22430: Static test fix. --- app/code/Magento/Review/Block/Adminhtml/Edit/Form.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/code/Magento/Review/Block/Adminhtml/Edit/Form.php b/app/code/Magento/Review/Block/Adminhtml/Edit/Form.php index ba0ed2700f72f..c2cbce09a6930 100644 --- a/app/code/Magento/Review/Block/Adminhtml/Edit/Form.php +++ b/app/code/Magento/Review/Block/Adminhtml/Edit/Form.php @@ -4,6 +4,7 @@ * See COPYING.txt for license details. */ + /** * Adminhtml Review Edit Form */ @@ -69,6 +70,7 @@ public function __construct( * * @return $this * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + * @SuppressWarnings(PHPMD.RequestAwareBlockMethod) */ protected function _prepareForm() { From c6cc171cec8d7196fde62da94ba91b455d69aace Mon Sep 17 00:00:00 2001 From: Viktor Petryk <victor.petryk@transoftgroup.com> Date: Mon, 10 Jun 2019 13:13:11 +0300 Subject: [PATCH 1906/2092] MAGETWO-73047: [GITHUB] Product Edit Page Can't Load #5967 --- .../Translation/Model/Js/PreProcessor.php | 6 +- .../Test/Unit/Model/Js/PreProcessorTest.php | 85 -------- app/code/Magento/Translation/etc/di.xml | 4 +- .../Translation/Model/Js/PreProcessorTest.php | 192 ++++++++++++++++++ 4 files changed, 198 insertions(+), 89 deletions(-) delete mode 100644 app/code/Magento/Translation/Test/Unit/Model/Js/PreProcessorTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Translation/Model/Js/PreProcessorTest.php diff --git a/app/code/Magento/Translation/Model/Js/PreProcessor.php b/app/code/Magento/Translation/Model/Js/PreProcessor.php index e85d022627621..b79e17c4f5303 100644 --- a/app/code/Magento/Translation/Model/Js/PreProcessor.php +++ b/app/code/Magento/Translation/Model/Js/PreProcessor.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Translation\Model\Js; use Magento\Framework\App\AreaList; @@ -85,13 +87,13 @@ public function translate($content) } /** - * Replace callback for preg_replace_callback function + * Replace callback for preg_replace_callback function. * * @param array $matches * @return string */ protected function replaceCallback($matches) { - return '"' . __($matches[1]) . '"'; + return '\'' . __($matches['translate']) . '\''; } } diff --git a/app/code/Magento/Translation/Test/Unit/Model/Js/PreProcessorTest.php b/app/code/Magento/Translation/Test/Unit/Model/Js/PreProcessorTest.php deleted file mode 100644 index 713086f298806..0000000000000 --- a/app/code/Magento/Translation/Test/Unit/Model/Js/PreProcessorTest.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Translation\Test\Unit\Model\Js; - -use Magento\Translation\Model\Js\PreProcessor; -use Magento\Translation\Model\Js\Config; -use Magento\Framework\App\AreaList; -use Magento\Framework\TranslateInterface; - -class PreProcessorTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var PreProcessor - */ - protected $model; - - /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject - */ - protected $configMock; - - /** - * @var AreaList|\PHPUnit_Framework_MockObject_MockObject - */ - protected $areaListMock; - - /** - * @var TranslateInterface|\PHPUnit_Framework_MockObject_MockObject - */ - protected $translateMock; - - protected function setUp() - { - $this->configMock = $this->createMock(\Magento\Translation\Model\Js\Config::class); - $this->areaListMock = $this->createMock(\Magento\Framework\App\AreaList::class); - $this->translateMock = $this->getMockForAbstractClass(\Magento\Framework\TranslateInterface::class); - $this->model = new PreProcessor($this->configMock, $this->areaListMock, $this->translateMock); - } - - public function testGetData() - { - $asset = $this->createMock(\Magento\Framework\View\Asset\File::class); - $chain = $this->createMock(\Magento\Framework\View\Asset\PreProcessor\Chain::class); - $context = $this->createMock(\Magento\Framework\View\Asset\File\FallbackContext::class); - $originalContent = 'content$.mage.__("hello1")content'; - $translatedContent = 'content"hello1"content'; - $patterns = ['~\$\.mage\.__\([\'|\"](.+?)[\'|\"]\)~']; - $areaCode = 'adminhtml'; - $area = $this->createMock(\Magento\Framework\App\Area::class); - - $chain->expects($this->once()) - ->method('getAsset') - ->willReturn($asset); - $asset->expects($this->once()) - ->method('getContext') - ->willReturn($context); - $context->expects($this->once()) - ->method('getAreaCode') - ->willReturn($areaCode); - - $this->configMock->expects($this->once()) - ->method('isEmbeddedStrategy') - ->willReturn(true); - $chain->expects($this->once()) - ->method('getContent') - ->willReturn($originalContent); - $this->configMock->expects($this->once()) - ->method('getPatterns') - ->willReturn($patterns); - - $this->areaListMock->expects($this->once()) - ->method('getArea') - ->with($areaCode) - ->willReturn($area); - - $chain->expects($this->once()) - ->method('setContent') - ->with($translatedContent); - - $this->model->process($chain); - } -} diff --git a/app/code/Magento/Translation/etc/di.xml b/app/code/Magento/Translation/etc/di.xml index 6d3ca03953cf9..93ca7c7b6b736 100644 --- a/app/code/Magento/Translation/etc/di.xml +++ b/app/code/Magento/Translation/etc/di.xml @@ -65,8 +65,8 @@ <argument name="patterns" xsi:type="array"> <item name="i18n_translation" xsi:type="string"><![CDATA[~i18n\:\s*(["'])(.*?)(?<!\\)\1~]]></item> <item name="translate_wrapping" xsi:type="string"><![CDATA[~translate\=("')([^\'].*?)\'\"~]]></item> - <item name="mage_translation_widget" xsi:type="string"><![CDATA[~(?:\$|jQuery)\.mage\.__\((?s)[^'"]*?(['"])(.+?)(?<!\\)\1(?s).*?\)~]]></item> - <item name="mage_translation_static" xsi:type="string"><![CDATA[~\$t\((?s)[^'"]*?(["'])(.+?)\1(?s).*?\)~]]></item> + <item name="mage_translation_widget" xsi:type="string"><![CDATA[~(?s)(?:\$|jQuery)\.mage\.__\(\s*(['"])(?<translate>.+?)(?<!\\)\1\s*(*SKIP)\)\s*(?s)~]]></item> + <item name="mage_translation_static" xsi:type="string"><![CDATA[~(?s)\$t\(\s*(['"])(?<translate>.+?)(?<!\\)\1\s*(*SKIP)\)(?s)~]]></item> <item name="translate_args" xsi:type="string"><![CDATA[~translate args\=("|'|"')([^\'].*?)('"|'|")~]]></item> </argument> </arguments> diff --git a/dev/tests/integration/testsuite/Magento/Translation/Model/Js/PreProcessorTest.php b/dev/tests/integration/testsuite/Magento/Translation/Model/Js/PreProcessorTest.php new file mode 100644 index 0000000000000..cb37dd5e0a319 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Translation/Model/Js/PreProcessorTest.php @@ -0,0 +1,192 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Translation\Model\Js; + +use Magento\Framework\App\AreaList; +use Magento\Framework\Phrase; +use Magento\Framework\Phrase\RendererInterface; +use Magento\Framework\Translate; +use Magento\Framework\View\FileSystem; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\Helper\CacheCleaner; + +/** + * Class for testing translation. + */ +class PreProcessorTest extends \PHPUnit\Framework\TestCase +{ + /** + * @var PreProcessor + */ + private $model; + + /** + * @var RendererInterface + */ + private $origRenderer; + + /** + * @inheritdoc + */ + protected function setUp() + { + $viewFileSystem = $this->createPartialMock(FileSystem::class, ['getLocaleFileName']); + $viewFileSystem->expects($this->any()) + ->method('getLocaleFileName') + ->willReturn( + // phpcs:ignore Magento2.Functions.DiscouragedFunction + dirname(__DIR__) . '/_files/Magento/Store/i18n/en_AU.csv' + ); + + $objectManager = Bootstrap::getObjectManager(); + $objectManager->addSharedInstance($viewFileSystem, FileSystem::class); + $translator = $objectManager->create(Translate::class); + $objectManager->addSharedInstance($translator, Translate::class); + $areaList = $this->getMockBuilder(AreaList::class) + ->disableOriginalConstructor() + ->getMock(); + $this->origRenderer = Phrase::getRenderer(); + Phrase::setRenderer( + $objectManager->get(RendererInterface::class) + ); + + $this->model = $objectManager->create( + PreProcessor::class, + [ + 'translate' => $translator, + 'areaList' => $areaList, + ] + ); + + $translator->setLocale('en_AU'); + $translator->loadData(); + } + + /** + * @inheritdoc + */ + protected function tearDown() + { + Phrase::setRenderer($this->origRenderer); + } + + /** + * Test for backend translation strategy. + * + * @param string $content + * @param string $translation + * @return void + * @dataProvider contentForTranslateDataProvider + */ + public function testProcess(string $content, string $translation) + { + CacheCleaner::cleanAll(); + $this->assertEquals($translation, $this->model->translate($content)); + } + + /** + * Data provider for translation. + * + * @return array + */ + public function contentForTranslateDataProvider(): array + { + return [ + 'i18n_js_file_error' => [ + 'setTranslateProp = function (el, original) { + var location = $(el).prop(\'tagName\').toLowerCase(), + translated = $.mage.__(original), + translationData = { + shown: translated, + translated: translated, + original: original + }, + translateAttr = composeTranslateAttr(translationData, location); + $(el).attr(\'data-translate\', translateAttr); + setText(el, translationData.shown); + },', + 'setTranslateProp = function (el, original) { + var location = $(el).prop(\'tagName\').toLowerCase(), + translated = $.mage.__(original), + translationData = { + shown: translated, + translated: translated, + original: original + }, + translateAttr = composeTranslateAttr(translationData, location); + $(el).attr(\'data-translate\', translateAttr); + setText(el, translationData.shown); + },', + ], + 'checkTranslationWithWhiteSpaces' => [ + <<<i18n + title: $.mage.__( + 'Original value for Magento_Store module' + ), + title: \$t( + 'Original value for Magento_Store module' + ); + title: jQuery.mage.__( + 'Original value for Magento_Store module' + ); +i18n + , + <<<i18n + title: 'Translated value for Magento_Store module in en_AU', + title: 'Translated value for Magento_Store module in en_AU'; + title: 'Translated value for Magento_Store module in en_AU'; +i18n + , + ], + 'checkTranslationWithReplace' => [ + <<<i18n + $.mage.__('The maximum you may purchase is %1.').replace('%1', params.maxAllowed); + \$t('The maximum you may purchase is %1.').replace('%1', params.maxAllowed); +i18n + , + <<<i18n + 'The maximum you may purchase is %1.'.replace('%1', params.maxAllowed); + 'The maximum you may purchase is %1.'.replace('%1', params.maxAllowed); +i18n + , + ], + 'checkAvoidingMatchingWithJsInString' => [ + <<<i18n + \$t('Payment ' + this.getTitle() + ' can\'t be initialized') + \$t( + 'Set unique country-state combinations within the same fixed product tax. ' + + 'Verify the combinations and try again.' + ) +i18n + , + <<<i18n + \$t('Payment ' + this.getTitle() + ' can\'t be initialized') + \$t( + 'Set unique country-state combinations within the same fixed product tax. ' + + 'Verify the combinations and try again.' + ) +i18n + , + ], + 'checkAvoidMatchingPhtml' => [ + <<<i18n + globalMessageList.addErrorMessage({ + message: \$t(<?= /* @noEscape */ json_encode(\$params['error_msg'])?>) + }); +i18n + , + <<<i18n + globalMessageList.addErrorMessage({ + message: \$t(<?= /* @noEscape */ json_encode(\$params['error_msg'])?>) + }); +i18n + , + ] + ]; + } +} From d717117fe80626d555cd84a796a243c4d92fac70 Mon Sep 17 00:00:00 2001 From: Karan Shah <karan.shah@krishtechnolabs.com> Date: Mon, 10 Jun 2019 18:13:28 +0530 Subject: [PATCH 1907/2092] backport-Apply-coupoun-and-scroll-top-to-check.-applied-successfully-or-not --- .../Magento/Sales/view/adminhtml/web/order/create/scripts.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/code/Magento/Sales/view/adminhtml/web/order/create/scripts.js b/app/code/Magento/Sales/view/adminhtml/web/order/create/scripts.js index c508a5ecdfa58..23912c9071553 100644 --- a/app/code/Magento/Sales/view/adminhtml/web/order/create/scripts.js +++ b/app/code/Magento/Sales/view/adminhtml/web/order/create/scripts.js @@ -561,6 +561,9 @@ define([ applyCoupon : function(code){ this.loadArea(['items', 'shipping_method', 'totals', 'billing_method'], true, {'order[coupon][code]':code, reset_shipping: 0}); this.orderItemChanged = false; + jQuery('html, body').animate({ + scrollTop: 0 + }); }, addProduct : function(id){ From fa31c72ded93b6c8e9dcd92174d6e199e31e0377 Mon Sep 17 00:00:00 2001 From: Viktor Petryk <victor.petryk@transoftgroup.com> Date: Mon, 10 Jun 2019 16:16:55 +0300 Subject: [PATCH 1908/2092] MAGETWO-73047: [GITHUB] Product Edit Page Can't Load #5967 --- app/code/Magento/Translation/Model/Js/PreProcessor.php | 1 - 1 file changed, 1 deletion(-) diff --git a/app/code/Magento/Translation/Model/Js/PreProcessor.php b/app/code/Magento/Translation/Model/Js/PreProcessor.php index b79e17c4f5303..e2ff5a9ce78dc 100644 --- a/app/code/Magento/Translation/Model/Js/PreProcessor.php +++ b/app/code/Magento/Translation/Model/Js/PreProcessor.php @@ -3,7 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -declare(strict_types=1); namespace Magento\Translation\Model\Js; From 8b34ffb70b94092cc29446881ed13137ff25f8d8 Mon Sep 17 00:00:00 2001 From: DianaRusin <rusind95@gmail.com> Date: Mon, 10 Jun 2019 16:17:25 +0300 Subject: [PATCH 1909/2092] MAGETWO-86624: [2.2] Allowed countries restriction for a default website is applied to backend customer grid --- .../Mftf/ActionGroup/AdminWebsiteCountryOptionsActionGroup.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/code/Magento/Config/Test/Mftf/ActionGroup/AdminWebsiteCountryOptionsActionGroup.xml b/app/code/Magento/Config/Test/Mftf/ActionGroup/AdminWebsiteCountryOptionsActionGroup.xml index 8dda48399d2ef..d80736529173f 100644 --- a/app/code/Magento/Config/Test/Mftf/ActionGroup/AdminWebsiteCountryOptionsActionGroup.xml +++ b/app/code/Magento/Config/Test/Mftf/ActionGroup/AdminWebsiteCountryOptionsActionGroup.xml @@ -19,6 +19,7 @@ <uncheckOption selector="{{AdminConfigurationGeneralCountryOptionsSection.generalCountryAllowInherit}}" stepKey="uncheckAllowInheritCheckbox"/> <selectOption selector="{{AdminConfigurationGeneralCountryOptionsSection.allowedCountries}}" userInput="{{country}}" stepKey="chooseAllowedCountries"/> <click selector="{{AdminMainActionsSection.save}}" stepKey="saveConfig"/> + <waitForElementVisible selector="{{AdminMessagesSection.successMessage}}" stepKey="waitForSuccessMessage"/> <see selector="{{AdminMessagesSection.successMessage}}" userInput="You saved the configuration." stepKey="seeSuccessMessage"/> </actionGroup> <actionGroup name="AllowAllCountriesExceptOneActionGroup" extends="AllowOnlyOneCountryActionGroup"> @@ -33,6 +34,7 @@ <checkOption selector="{{AdminConfigurationGeneralCountryOptionsSection.generalCountryAllowInherit}}" stepKey="setAllowInheritToDefault"/> <checkOption selector="{{AdminConfigurationGeneralCountryOptionsSection.generalCountryDefaultInherit}}" stepKey="setDefaultCountryInheritToDefault"/> <click selector="{{AdminMainActionsSection.save}}" stepKey="saveConfig"/> + <waitForElementVisible selector="{{AdminMessagesSection.successMessage}}" stepKey="waitForSuccessMessage"/> <see selector="{{AdminMessagesSection.successMessage}}" userInput="You saved the configuration." stepKey="seeSuccessMessage"/> </actionGroup> </actionGroups> From f64ab974fc4cc239f1dbb7a03d70b0b3335fa23f Mon Sep 17 00:00:00 2001 From: DianaRusin <rusind95@gmail.com> Date: Mon, 10 Jun 2019 16:27:56 +0300 Subject: [PATCH 1910/2092] MAGETWO-86624: [2.2] Allowed countries restriction for a default website is applied to backend customer grid --- ...dminConfigurationGeneralCountryOptionsSection.xml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml b/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml index 1e7c3abaaa77a..1e2408ec2fd42 100644 --- a/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml +++ b/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml @@ -1,10 +1,10 @@ <?xml version="1.0" encoding="UTF-8"?> - <!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> From e1d4d68a3f243ffecfd6d0c96d27346037b211f1 Mon Sep 17 00:00:00 2001 From: OlgaVasyltsun <olga.vasyltsun@gmail.com> Date: Mon, 10 Jun 2019 17:09:25 +0300 Subject: [PATCH 1911/2092] MAGETWO-93755: Catalog grid page number resets after Save and Close action. --- .../AdminProductGridActionGroup.xml | 9 ++++- .../Test/Mftf/Data/ProductGridData.xml | 4 +-- ...dPageNumberAfterSaveAndCloseActionTest.xml | 29 +++++++--------- .../AdminDataGridPaginationActionGroup.xml | 34 +++++++++---------- .../AdminDataGridPaginationSection.xml | 17 +++++----- 5 files changed, 49 insertions(+), 44 deletions(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductGridActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductGridActionGroup.xml index 0613d54a6ca83..c7361e700078a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductGridActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductGridActionGroup.xml @@ -104,13 +104,20 @@ <waitForPageLoad stepKey="waitForPageLoad"/> </actionGroup> - <actionGroup name="DeleteProductsIfTheyExist"> + <actionGroup name="DeleteAllProducts"> <conditionalClick selector="{{AdminProductGridSection.multicheckDropdown}}" dependentSelector="{{AdminDataGridTableSection.firstRow}}" visible="true" stepKey="openMulticheckDropdown"/> <conditionalClick selector="{{AdminProductGridSection.multicheckOption('Select All')}}" dependentSelector="{{AdminDataGridTableSection.firstRow}}" visible="true" stepKey="selectAllProductInFilteredGrid"/> <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickActionDropdown"/> <click selector="{{AdminProductGridSection.bulkActionOption('Delete')}}" stepKey="clickDeleteAction"/> <waitForElementVisible selector="{{AdminConfirmationModalSection.ok}}" stepKey="waitForModalPopUp"/> + <grabTextFrom selector="{{AdminConfirmationModalSection.message}}" stepKey="grabConfirmationMessage"/> <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="confirmProductDelete"/> + <executeInSelenium function="function () use ($I, $grabConfirmationMessage) { + if ($grabConfirmationMessage !== 'You haven\'t selected any items!') { + $I->waitForElementVisible('#messages div.message-success'); + $I->see('record(s) have been deleted.', '#messages div.message-success'); + } + }" stepKey="waitSuccessMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/ProductGridData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/ProductGridData.xml index c0c3efc4217b5..9f74a86802e0f 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/ProductGridData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/ProductGridData.xml @@ -8,7 +8,7 @@ <entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> - <entity name="ProductPerPage"> - <data key="productCount">1</data> + <entity name="ProductGridPagerData"> + <data key="pageSize">1</data> </entity> </entities> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminGridPageNumberAfterSaveAndCloseActionTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminGridPageNumberAfterSaveAndCloseActionTest.xml index bd0c9dcd361ef..128429e3344ba 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminGridPageNumberAfterSaveAndCloseActionTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminGridPageNumberAfterSaveAndCloseActionTest.xml @@ -17,7 +17,7 @@ <severity value="MAJOR"/> <testCaseId value="MC-17278"/> <useCaseId value="MAGETWO-93755"/> - <group value="Catalog"/> + <group value="catalog"/> </annotations> <before> <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> @@ -25,28 +25,25 @@ <comment userInput="Clear product grid" stepKey="commentClearProductsGrid"/> <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToProductsGridPage"/> <actionGroup ref="clearFiltersAdminDataGrid" stepKey="clearProductsFilters"/> - <actionGroup ref="DeleteProductsIfTheyExist" stepKey="deleteProductIfTheyExist"/> + <actionGroup ref="DeleteAllProducts" stepKey="deleteProductsIfTheyExist"/> <!--Create products--> - <createData entity="SimpleSubCategory" stepKey="createCategory1"/> - <createData entity="SimpleProduct" stepKey="createProduct1"> - <requiredEntity createDataKey="createCategory1"/> - </createData> - <createData entity="SimpleSubCategory" stepKey="createCategory2"/> - <createData entity="SimpleProduct" stepKey="createProduct2"> - <requiredEntity createDataKey="createCategory2"/> - </createData> + <createData entity="SimpleProduct3" stepKey="createProduct1"/> + <createData entity="SimpleProduct3" stepKey="createProduct2"/> <!--Update product count per page--> - <actionGroup ref="AdminDataGridSelectCustomPerPage" stepKey="select1OrderPerPage"/> + <actionGroup ref="AdminDataGridSelectCustomPageSize" stepKey="selectCustomPageSize"> + <argument name="pageSize" value="{{ProductGridPagerData.pageSize}}"/> + </actionGroup> </before> <after> <!--Delete created data--> - <deleteData stepKey="deleteCategory1" createDataKey="createCategory1"/> <deleteData stepKey="deleteProduct1" createDataKey="createProduct1"/> - <deleteData stepKey="deleteCategory2" createDataKey="createCategory2"/> <deleteData stepKey="deleteProduct2" createDataKey="createProduct2"/> <!--Revert products count per page --> + <conditionalClick selector="{{AdminDataGridPaginationSection.previousPage}}" dependentSelector="{{AdminDataGridPaginationSection.previousPage}}" visible="true" stepKey="clickPrevPageOrderGrid"/> <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="goToProductsGridPage"/> - <actionGroup ref="AdminDataGridDeleteCustomPerPage" stepKey="deleteCustomAddedPerPage"/> + <actionGroup ref="AdminDataGridDeleteCustomPageSize" stepKey="deleteCustomAddedPageSize"> + <argument name="pageSize" value="{{ProductGridPagerData.pageSize}}"/> + </actionGroup> <actionGroup ref="logout" stepKey="logout"/> </after> @@ -54,13 +51,13 @@ <!--Go to the next page and edit the product--> <comment userInput="Go to the next page and edit the product" stepKey="commentEdiProduct"/> <click selector="{{AdminDataGridPaginationSection.nextPage}}" stepKey="clickNextPageOrderGrid"/> + <waitForElementVisible selector="{{AdminDataGridPaginationSection.currentPage}}" stepKey="waitCurrentPageNumberAppeares"/> <seeInField selector="{{AdminDataGridPaginationSection.currentPage}}" userInput="2" stepKey="seeOnSecondPageOrderGrid"/> - <waitForPageLoad stepKey="waitForPageLoad"/> <actionGroup ref="OpenEditProductOnBackendActionGroup" stepKey="openEditProduct2"> <argument name="product" value="$$createProduct2$$"/> </actionGroup> <actionGroup ref="AdminFormSaveAndClose" stepKey="saveAndCloseProduct"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> + <waitForElementVisible selector="{{AdminDataGridPaginationSection.currentPage}}" stepKey="waitCurrentPageNumberAppearesAfterProductEdit"/> <seeInField selector="{{AdminDataGridPaginationSection.currentPage}}" userInput="2" stepKey="seeOnSecondPageOrderGridAfterProductSaved"/> </test> </tests> diff --git a/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminDataGridPaginationActionGroup.xml b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminDataGridPaginationActionGroup.xml index 5690406715319..e4f6bd0c60546 100644 --- a/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminDataGridPaginationActionGroup.xml +++ b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminDataGridPaginationActionGroup.xml @@ -8,28 +8,28 @@ <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminDataGridSelectCustomPerPage"> + <actionGroup name="AdminDataGridSelectCustomPageSize"> <arguments> - <argument name="perPage" defaultValue="{{ProductPerPage.productCount}}" type="string"/> + <argument name="pageSize" type="string"/> </arguments> - <click selector="{{AdminDataGridPaginationSection.perPageDropdown}}" stepKey="clickPerPageDropdown"/> - <click selector="{{AdminDataGridPaginationSection.perPageOption('Custom')}}" stepKey="selectCustomPerPage"/> - <waitForElementVisible selector="{{AdminDataGridPaginationSection.perPageInput}}" stepKey="waitForInputVisible"/> - <fillField selector="{{AdminDataGridPaginationSection.perPageInput}}" userInput="{{perPage}}" stepKey="fillCustomPerPage"/> - <click selector="{{AdminDataGridPaginationSection.perPageApplyInput}}" stepKey="applyCustomPerPage"/> - <waitForLoadingMaskToDisappear stepKey="waitForGridLoad"/> - <seeInField selector="{{AdminDataGridPaginationSection.perPageDropDownValue}}" userInput="{{perPage}}" stepKey="seePerPageValueInDropDown"/> + <click selector="{{AdminDataGridPaginationSection.pageSizeDropdown}}" stepKey="clickPageSizeDropdown"/> + <waitForElementVisible selector="{{AdminDataGridPaginationSection.pageSizeOption('Custom')}}" stepKey="waitCustomPageSizeOptionAppear"/> + <click selector="{{AdminDataGridPaginationSection.pageSizeOption('Custom')}}" stepKey="selectCustomPageSize"/> + <waitForElementVisible selector="{{AdminDataGridPaginationSection.pageSizeInput}}" stepKey="waitForInputVisible"/> + <fillField selector="{{AdminDataGridPaginationSection.pageSizeInput}}" userInput="{{pageSize}}" stepKey="fillCustomPageSize"/> + <click selector="{{AdminDataGridPaginationSection.pageSizeApplyInput}}" stepKey="applyCustomPageSize"/> + <seeInField selector="{{AdminDataGridPaginationSection.pageSizeDropDownValue}}" userInput="{{pageSize}}" stepKey="seePageSizeValueInDropDown"/> </actionGroup> - <actionGroup name="AdminDataGridDeleteCustomPerPage"> + <actionGroup name="AdminDataGridDeleteCustomPageSize"> <arguments> - <argument name="perPage" defaultValue="{{ProductPerPage.productCount}}" type="string"/> + <argument name="pageSize" type="string"/> </arguments> - <click selector="{{AdminDataGridPaginationSection.perPageDropdown}}" stepKey="clickPerPageDropdown"/> - <click selector="{{AdminDataGridPaginationSection.perPageEditCustomValue(perPage)}}" stepKey="clickToEditCustomPerPage"/> - <waitForElementVisible selector="{{AdminDataGridPaginationSection.perPageDeleteCustomValue(perPage)}}" stepKey="waitForDeleteButtonVisible"/> - <click selector="{{AdminDataGridPaginationSection.perPageDeleteCustomValue(perPage)}}" stepKey="clickToDeleteCustomPerPage"/> - <click selector="{{AdminDataGridPaginationSection.perPageDropdown}}" stepKey="clickPerPageDropdown1"/> - <dontSeeElement selector="{{AdminDataGridPaginationSection.perPageDropDownItem(perPage)}}" stepKey="dontSeeDropDownItem"/> + <click selector="{{AdminDataGridPaginationSection.pageSizeDropdown}}" stepKey="clickPageSizeDropdown"/> + <click selector="{{AdminDataGridPaginationSection.pageSizeEditCustomValue(pageSize)}}" stepKey="clickToEditCustomPageSize"/> + <waitForElementVisible selector="{{AdminDataGridPaginationSection.pageSizeDeleteCustomValue(pageSize)}}" stepKey="waitForDeleteButtonVisible"/> + <click selector="{{AdminDataGridPaginationSection.pageSizeDeleteCustomValue(pageSize)}}" stepKey="clickToDeleteCustomPageSize"/> + <click selector="{{AdminDataGridPaginationSection.pageSizeDropdown}}" stepKey="clickPageSizeDropdownAfterCustomPageSizeDeleted"/> + <dontSeeElement selector="{{AdminDataGridPaginationSection.pageSizeDropDownItem(pageSize)}}" stepKey="dontSeeDropDownItem"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridPaginationSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridPaginationSection.xml index 48f3252338548..ca1ec145c3e0d 100644 --- a/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridPaginationSection.xml +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridPaginationSection.xml @@ -9,15 +9,16 @@ <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminDataGridPaginationSection"> - <element name="perPageDropdown" type="select" selector=".admin__data-grid-pager-wrap .selectmenu"/> - <element name="perPageOption" type="button" selector="//div[@class='admin__data-grid-pager-wrap']//div[@class='selectmenu-items _active']//li//button[text()='{{var1}}']" parameterized="true"/> - <element name="perPageInput" type="input" selector="div.admin__data-grid-pager-wrap div.selectmenu-items._active li._edit div.selectmenu-item-edit input" timeout="30"/> - <element name="perPageApplyInput" type="button" selector="div.admin__data-grid-pager-wrap div.selectmenu-items._active li._edit div.selectmenu-item-edit button"/> - <element name="perPageDropDownItem" type="button" selector="//*[contains(@class, 'selectmenu-items _active')]//button[contains(@class, 'selectmenu-item-action') and text()='{{dropDownItem}}']" parameterized="true"/> - <element name="perPageEditCustomValue" type="button" selector="//div[contains(@class, 'selectmenu-items _active')]//div[contains(@class, 'selectmenu-item')]//button[text()='{{perPageCustomValue}}']/following-sibling::button[contains(@class, 'action-edit')]" parameterized="true"/> - <element name="perPageDeleteCustomValue" type="button" selector="//div[contains(@class, 'selectmenu-items _active')]//div[contains(@class, 'selectmenu-item')]//button[text()='{{perPageCustomValue}}']/parent::div/preceding-sibling::div/button[contains(@class, 'action-delete')]" parameterized="true" timeout="30"/> + <element name="pageSizeDropdown" type="select" selector=".admin__data-grid-pager-wrap .selectmenu"/> + <element name="pageSizeOption" type="button" selector="//div[@class='admin__data-grid-pager-wrap']//div[@class='selectmenu-items _active']//li//button[text()='{{var1}}']" parameterized="true"/> + <element name="pageSizeInput" type="input" selector="div.admin__data-grid-pager-wrap div.selectmenu-items._active li._edit div.selectmenu-item-edit input"/> + <element name="pageSizeApplyInput" type="button" selector="div.admin__data-grid-pager-wrap div.selectmenu-items._active li._edit div.selectmenu-item-edit button" timeout="30"/> + <element name="pageSizeDropDownItem" type="button" selector="//*[contains(@class, 'selectmenu-items _active')]//button[contains(@class, 'selectmenu-item-action') and text()='{{dropDownItem}}']" parameterized="true"/> + <element name="pageSizeEditCustomValue" type="button" selector="//div[contains(@class, 'selectmenu-items _active')]//div[contains(@class, 'selectmenu-item')]//button[text()='{{perPageCustomValue}}']/following-sibling::button[contains(@class, 'action-edit')]" parameterized="true"/> + <element name="pageSizeDeleteCustomValue" type="button" selector="//div[contains(@class, 'selectmenu-items _active')]//div[contains(@class, 'selectmenu-item')]//button[text()='{{perPageCustomValue}}']/parent::div/preceding-sibling::div/button[contains(@class, 'action-delete')]" parameterized="true" timeout="30"/> <element name="nextPage" type="button" selector="div.admin__data-grid-pager > button.action-next" timeout="30"/> + <element name="previousPage" type="button" selector=".admin__data-grid-header:nth-of-type(2) div.admin__data-grid-pager > button.action-previous:not(disabled)" timeout="30"/> <element name="currentPage" type="input" selector="div.admin__data-grid-pager > input[data-ui-id='current-page-input']"/> - <element name="perPageDropDownValue" type="input" selector=".admin__data-grid-pager-wrap .selectmenu-value input" timeout="30"/> + <element name="pageSizeDropDownValue" type="input" selector=".admin__data-grid-pager-wrap .selectmenu-value input" timeout="30"/> </section> </sections> From 862a9d2995e2259fd39416a7c7bd667889988671 Mon Sep 17 00:00:00 2001 From: Dave Macaulay <macaulay@adobe.com> Date: Mon, 20 May 2019 17:18:59 +0200 Subject: [PATCH 1912/2092] MC-17242: Eliminate @escapeNotVerified in Sales-related Modules --- .../templates/items/column/name.phtml | 24 +- .../templates/items/column/qty.phtml | 63 +++-- .../adminhtml/templates/items/price/row.phtml | 7 +- .../templates/items/price/total.phtml | 7 +- .../templates/items/price/unit.phtml | 6 +- .../templates/items/renderer/default.phtml | 24 +- .../templates/order/address/form.phtml | 7 +- .../templates/order/comments/view.phtml | 40 ++-- .../templates/order/create/abstract.phtml | 7 +- .../order/create/billing/method/form.phtml | 22 +- .../templates/order/create/comment.phtml | 10 +- .../templates/order/create/coupons/form.phtml | 25 +- .../templates/order/create/data.phtml | 26 +-- .../templates/order/create/form.phtml | 10 +- .../templates/order/create/form/account.phtml | 6 +- .../templates/order/create/form/address.phtml | 72 +++--- .../templates/order/create/giftmessage.phtml | 38 +-- .../templates/order/create/items.phtml | 6 +- .../templates/order/create/items/grid.phtml | 218 +++++++++--------- .../order/create/items/price/row.phtml | 7 +- .../order/create/items/price/total.phtml | 7 +- .../order/create/items/price/unit.phtml | 6 +- .../adminhtml/templates/order/create/js.phtml | 10 +- .../order/create/newsletter/form.phtml | 5 +- .../order/create/shipping/method/form.phtml | 61 +++-- .../templates/order/create/sidebar.phtml | 22 +- .../order/create/sidebar/items.phtml | 77 +++---- .../templates/order/create/store/select.phtml | 21 +- .../templates/order/create/totals.phtml | 17 +- .../order/create/totals/default.phtml | 19 +- .../order/create/totals/grandtotal.phtml | 56 +++-- .../order/create/totals/shipping.phtml | 36 ++- .../order/create/totals/subtotal.phtml | 28 ++- .../templates/order/create/totals/tax.phtml | 75 +++--- .../order/creditmemo/create/form.phtml | 31 +-- .../order/creditmemo/create/items.phtml | 64 +++-- .../create/items/renderer/default.phtml | 17 +- .../create/totals/adjustments.phtml | 22 +- .../order/creditmemo/view/form.phtml | 43 ++-- .../order/creditmemo/view/items.phtml | 29 ++- .../view/items/renderer/default.phtml | 9 +- .../adminhtml/templates/order/details.phtml | 66 +++--- .../templates/order/giftoptions.phtml | 9 +- .../templates/order/invoice/create/form.phtml | 83 +++---- .../order/invoice/create/items.phtml | 112 +++++---- .../create/items/renderer/default.phtml | 13 +- .../templates/order/invoice/view/form.phtml | 35 +-- .../templates/order/invoice/view/items.phtml | 31 ++- .../invoice/view/items/renderer/default.phtml | 9 +- .../adminhtml/templates/order/totalbar.phtml | 11 +- .../adminhtml/templates/order/totals.phtml | 63 +++-- .../templates/order/totals/discount.phtml | 15 +- .../templates/order/totals/due.phtml | 9 +- .../templates/order/totals/grand.phtml | 13 +- .../templates/order/totals/item.phtml | 23 +- .../templates/order/totals/paid.phtml | 9 +- .../templates/order/totals/refunded.phtml | 9 +- .../templates/order/totals/shipping.phtml | 9 +- .../templates/order/totals/tax.phtml | 66 +++--- .../templates/order/view/giftmessage.phtml | 97 ++++---- .../templates/order/view/history.phtml | 45 ++-- .../adminhtml/templates/order/view/info.phtml | 39 ++-- .../templates/order/view/items.phtml | 15 +- .../order/view/items/renderer/default.phtml | 9 +- .../templates/order/view/tab/history.phtml | 41 ++-- .../templates/order/view/tab/info.phtml | 22 +- .../templates/page/js/components.phtml | 5 - .../templates/rss/order/grid/link.phtml | 6 +- .../templates/transactions/detail.phtml | 25 +- .../templates/email/creditmemo/items.phtml | 14 +- .../templates/email/invoice/items.phtml | 12 +- .../view/frontend/templates/email/items.phtml | 31 +-- .../email/items/creditmemo/default.phtml | 18 +- .../email/items/invoice/default.phtml | 21 +- .../templates/email/items/order/default.phtml | 33 +-- .../templates/email/items/price/row.phtml | 5 +- .../email/items/shipment/default.phtml | 18 +- .../templates/email/shipment/items.phtml | 10 +- .../templates/email/shipment/track.phtml | 44 ++-- .../view/frontend/templates/guest/form.phtml | 27 +-- .../frontend/templates/items/price/row.phtml | 4 +- .../items/price/total_after_discount.phtml | 8 +- .../frontend/templates/items/price/unit.phtml | 4 +- .../frontend/templates/js/components.phtml | 3 - .../frontend/templates/order/comments.phtml | 14 +- .../frontend/templates/order/creditmemo.phtml | 6 +- .../templates/order/creditmemo/items.phtml | 81 ++++--- .../creditmemo/items/renderer/default.phtml | 67 +++--- .../frontend/templates/order/history.phtml | 51 ++-- .../view/frontend/templates/order/info.phtml | 47 ++-- .../templates/order/info/buttons.phtml | 17 +- .../templates/order/info/buttons/rss.phtml | 10 +- .../frontend/templates/order/invoice.phtml | 6 +- .../templates/order/invoice/items.phtml | 77 +++---- .../invoice/items/renderer/default.phtml | 53 ++--- .../view/frontend/templates/order/items.phtml | 60 ++--- .../order/items/renderer/default.phtml | 72 +++--- .../templates/order/order_comments.phtml | 15 +- .../frontend/templates/order/order_date.phtml | 6 +- .../templates/order/order_status.phtml | 2 +- .../templates/order/print/creditmemo.phtml | 49 ++-- .../templates/order/print/invoice.phtml | 55 +++-- .../templates/order/print/shipment.phtml | 129 +++++------ .../frontend/templates/order/recent.phtml | 55 ++--- .../shipment/items/renderer/default.phtml | 55 +++-- .../frontend/templates/order/totals.phtml | 34 ++- .../view/frontend/templates/order/view.phtml | 30 ++- .../frontend/templates/reorder/sidebar.phtml | 20 +- .../templates/widget/guest/form.phtml | 24 +- .../_files/whitelist/exempt_modules/ce.php | 1 - 110 files changed, 1633 insertions(+), 1824 deletions(-) diff --git a/app/code/Magento/Sales/view/adminhtml/templates/items/column/name.phtml b/app/code/Magento/Sales/view/adminhtml/templates/items/column/name.phtml index 98cc0d1d0ad07..52cee7971c9f9 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/items/column/name.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/items/column/name.phtml @@ -4,32 +4,28 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +// phpcs:disable Magento2.Templates.ThisInTemplate ?> <?php -/** - * @see \Magento\Sales\Block\Adminhtml\Items\Column\Name - */ +/* @var $block \Magento\Sales\Block\Adminhtml\Items\Column\Name */ ?> - -<?php if ($_item = $block->getItem()): ?> - <div id="order_item_<?= $block->escapeHtml($_item->getId()) ?>_title" +<?php if ($_item = $block->getItem()) : ?> + <div id="order_item_<?= (int) $_item->getId() ?>_title" class="product-title"> <?= $block->escapeHtml($_item->getName()) ?> </div> <div class="product-sku-block"> - <span><?= $block->escapeHtml(__('SKU'))?>:</span> <?= implode('<br />', $this->helper('Magento\Catalog\Helper\Data')->splitSku($block->escapeHtml($block->getSku()))) ?> + <span><?= $block->escapeHtml(__('SKU'))?>:</span> <?= /* @noEscape */ implode('<br />', $this->helper(\Magento\Catalog\Helper\Data::class)->splitSku($block->escapeHtml($block->getSku()))) ?> </div> - <?php if ($block->getOrderOptions()): ?> + <?php if ($block->getOrderOptions()) : ?> <dl class="item-options"> - <?php foreach ($block->getOrderOptions() as $_option): ?> + <?php foreach ($block->getOrderOptions() as $_option) : ?> <dt><?= $block->escapeHtml($_option['label']) ?>:</dt> <dd> - <?php if (isset($_option['custom_view']) && $_option['custom_view']): ?> - <?= /* @escapeNotVerified */ $block->getCustomizedOptionValue($_option) ?> - <?php else: ?> + <?php if (isset($_option['custom_view']) && $_option['custom_view']) : ?> + <?= /* @noEscape */ $block->getCustomizedOptionValue($_option) ?> + <?php else : ?> <?php $_option = $block->getFormattedOption($_option['value']); ?> <?= $block->escapeHtml($_option['value']) ?> <?php if (isset($_option['remainder']) && $_option['remainder']): ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/items/column/qty.phtml b/app/code/Magento/Sales/view/adminhtml/templates/items/column/qty.phtml index 9bf4856795197..645cdb9aac624 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/items/column/qty.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/items/column/qty.phtml @@ -3,44 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> -<?php if ($item = $block->getItem()): ?> -<table class="qty-table"> - <tr> - <th><?= $block->escapeHtml(__('Ordered')); ?></th> - <td><?= /* @noEscape */ $item->getQtyOrdered()*1 ?></td> - </tr> - - <?php if ((float) $item->getQtyInvoiced()): ?> +<?php if ($item = $block->getItem()) : ?> + <table class="qty-table"> <tr> - <th><?= $block->escapeHtml(__('Invoiced')); ?></th> - <td><?= /* @noEscape */ $item->getQtyInvoiced()*1 ?></td> + <th><?= $block->escapeHtml(__('Ordered')); ?></th> + <td><?= (int) $item->getQtyOrdered() ?></td> </tr> - <?php endif; ?> - <?php if ((float) $item->getQtyShipped()): ?> - <tr> - <th><?= $block->escapeHtml(__('Shipped')); ?></th> - <td><?= /* @noEscape */ $item->getQtyShipped()*1 ?></td> - </tr> - <?php endif; ?> + <?php if ((float)$item->getQtyInvoiced()) : ?> + <tr> + <th><?= $block->escapeHtml(__('Invoiced')); ?></th> + <td><?= (int) $item->getQtyInvoiced() ?></td> + </tr> + <?php endif; ?> - <?php if ((float) $item->getQtyRefunded()): ?> - <tr> - <th><?= $block->escapeHtml(__('Refunded')); ?></th> - <td><?= /* @noEscape */ $item->getQtyRefunded()*1 ?></td> - </tr> - <?php endif; ?> + <?php if ((float)$item->getQtyShipped()) : ?> + <tr> + <th><?= $block->escapeHtml(__('Shipped')); ?></th> + <td><?= (int) $item->getQtyShipped() ?></td> + </tr> + <?php endif; ?> - <?php if ((float) $item->getQtyCanceled()): ?> - <tr> - <th><?= $block->escapeHtml(__('Canceled')); ?></th> - <td><?= /* @noEscape */ $item->getQtyCanceled()*1 ?></td> - </tr> - <?php endif; ?> + <?php if ((float)$item->getQtyRefunded()) : ?> + <tr> + <th><?= $block->escapeHtml(__('Refunded')); ?></th> + <td><?= (int) $item->getQtyRefunded() ?></td> + </tr> + <?php endif; ?> + + <?php if ((float)$item->getQtyCanceled()) : ?> + <tr> + <th><?= $block->escapeHtml(__('Canceled')); ?></th> + <td><?= (int) $item->getQtyCanceled() ?></td> + </tr> + <?php endif; ?> -</table> + </table> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/items/price/row.phtml b/app/code/Magento/Sales/view/adminhtml/templates/items/price/row.phtml index 54e95876d7626..fba82ce89be58 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/items/price/row.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/items/price/row.phtml @@ -3,16 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var \Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn $block */ - $_item = $block->getItem(); ?> - <div class="price-excl-tax"> - <?= /* @escapeNotVerified */ $block->displayPrices($_item->getBaseRowTotal(), $_item->getRowTotal()) ?> + <?= /* @noEscape */ $block->displayPrices($_item->getBaseRowTotal(), $_item->getRowTotal()) ?> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/items/price/total.phtml b/app/code/Magento/Sales/view/adminhtml/templates/items/price/total.phtml index 46a0a0926f4c7..74574e5e870a2 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/items/price/total.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/items/price/total.phtml @@ -3,14 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var \Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn $block */ - $_item = $block->getItem(); ?> - -<?= /* @escapeNotVerified */ $block->displayPrices($block->getBaseTotalAmount($_item), $block->getTotalAmount($_item)) ?> +<?= /* @noEscape */ $block->displayPrices($block->getBaseTotalAmount($_item), $block->getTotalAmount($_item)) ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/items/price/unit.phtml b/app/code/Magento/Sales/view/adminhtml/templates/items/price/unit.phtml index 444310c80884a..9146fe6713225 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/items/price/unit.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/items/price/unit.phtml @@ -3,15 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var \Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn $block */ - $_item = $block->getItem(); ?> <div class="price-excl-tax"> -<?= /* @escapeNotVerified */ $block->displayPrices($_item->getBasePrice(), $_item->getPrice()) ?> +<?= /* @noEscape */ $block->displayPrices($_item->getBasePrice(), $_item->getPrice()) ?> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/items/renderer/default.phtml b/app/code/Magento/Sales/view/adminhtml/templates/items/renderer/default.phtml index 09f6ee5d6a49a..0c5b276bf382b 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/items/renderer/default.phtml @@ -4,21 +4,19 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +// phpcs:disable Magento2.Templates.ThisInTemplate ?> - -<?= /* @escapeNotVerified */ $block->getItem()->getName() ?> -<div><strong><?= /* @escapeNotVerified */ __('SKU') ?>:</strong> <?= implode('<br />', $this->helper('Magento\Catalog\Helper\Data')->splitSku($block->escapeHtml($block->getItem()->getSku()))) ?></div> -<?php if ($block->getOrderOptions()): ?> +<?= $block->escapeHtml($block->getItem()->getName()) ?> +<div><strong><?= $block->escapeHtml(__('SKU')) ?>:</strong> <?= /* @noEscape */ implode('<br />', $this->helper(\Magento\Catalog\Helper\Data::class)->splitSku($block->escapeHtml($block->getItem()->getSku()))) ?></div> +<?php if ($block->getOrderOptions()) : ?> <ul class="item-options"> - <?php foreach ($block->getOrderOptions() as $option): ?> - <li><strong><?= /* @escapeNotVerified */ $option['label'] ?>:</strong><br /> - <?php if (is_array($option['value'])): ?> - <?php foreach ($option['value'] as $item): ?> - <?= $block->getValueHtml($item) ?><br /> - <?php endforeach; ?> - <?php else: ?> + <?php foreach ($block->getOrderOptions() as $option) : ?> + <li><strong><?= $block->escapeHtml($option['label']) ?>:</strong><br /> + <?php if (is_array($option['value'])) : ?> + <?php foreach ($option['value'] as $item) : ?> + <?= $block->getValueHtml($item) ?><br /> + <?php endforeach; ?> + <?php else : ?> <?= $block->escapeHtml($option['value']) ?> <?php endif; ?> </li> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/address/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/address/form.phtml index ff79e2f89cd20..a7f3b3c1cc8f5 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/address/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/address/form.phtml @@ -3,19 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <div class="message message-notice"> <div class="message-inner"> - <div class="message-content"><?= /* @escapeNotVerified */ __('Changing address information will not recalculate shipping, tax or other order amount.') ?></div> + <div class="message-content"><?= $block->escapeHtml(__('Changing address information will not recalculate shipping, tax or other order amount.')) ?></div> </div> </div> <fieldset class="fieldset admin__fieldset-wrapper"> <legend class="legend admin__legend"> - <span><?= /* @escapeNotVerified */ $block->getHeaderText() ?></span> + <span><?= $block->escapeHtml($block->getHeaderText()) ?></span> </legend> <br> <div class="form-inline" data-mage-init='{"Magento_Sales/order/edit/address/form":{}}'> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/comments/view.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/comments/view.phtml index f01e1c274a1de..05e753c78f4a3 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/comments/view.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/comments/view.phtml @@ -3,16 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> -<?php if ($_entity = $block->getEntity()): ?> +<?php if ($_entity = $block->getEntity()) : ?> <div id="comments_block" class="edit-order-comments"> <div class="order-history-block"> <div class="admin__field field-row"> <label class="admin__field-label" - for="history_comment"><?= /* @escapeNotVerified */ __('Comment Text') ?></label> + for="history_comment"><?= $block->escapeHtml(__('Comment Text')) ?></label> <div class="admin__field-control"> <textarea name="comment[comment]" class="admin__control-textarea" @@ -23,7 +20,7 @@ </div> <div class="admin__field"> <div class="order-history-comments-options"> - <?php if ($block->canSendCommentEmail()): ?> + <?php if ($block->canSendCommentEmail()) : ?> <div class="admin__field admin__field-option"> <input name="comment[is_customer_notified]" type="checkbox" @@ -31,7 +28,7 @@ id="history_notify" value="1" /> <label class="admin__field-label" - for="history_notify"><?= /* @escapeNotVerified */ __('Notify Customer by Email') ?></label> + for="history_notify"><?= $block->escapeHtml(__('Notify Customer by Email')) ?></label> </div> <?php endif; ?> <div class="admin__field admin__field-option"> @@ -41,7 +38,7 @@ class="admin__control-checkbox" value="1" /> <label class="admin__field-label" - for="history_visible"> <?= /* @escapeNotVerified */ __('Visible on Storefront') ?></label> + for="history_visible"> <?= $block->escapeHtml(__('Visible on Storefront')) ?></label> </div> </div> <div class="order-history-comments-actions"> @@ -51,16 +48,16 @@ </div> <ul class="note-list"> - <?php foreach ($_entity->getCommentsCollection(true) as $_comment): ?> + <?php foreach ($_entity->getCommentsCollection(true) as $_comment) : ?> <li> <span class="note-list-date"><?= /* @noEscape */ $block->formatDate($_comment->getCreatedAt(), \IntlDateFormatter::MEDIUM) ?></span> <span class="note-list-time"><?= /* @noEscape */ $block->formatTime($_comment->getCreatedAt(), \IntlDateFormatter::MEDIUM) ?></span> <span class="note-list-customer"> - <?= /* @escapeNotVerified */ __('Customer') ?> - <?php if ($_comment->getIsCustomerNotified()): ?> - <span class="note-list-customer-notified"><?= /* @escapeNotVerified */ __('Notified') ?></span> - <?php else: ?> - <span class="note-list-customer-not-notified"><?= /* @escapeNotVerified */ __('Not Notified') ?></span> + <?= $block->escapeHtml(__('Customer')) ?> + <?php if ($_comment->getIsCustomerNotified()) : ?> + <span class="note-list-customer-notified"><?= $block->escapeHtml(__('Notified')) ?></span> + <?php else : ?> + <span class="note-list-customer-not-notified"><?= $block->escapeHtml(__('Not Notified')) ?></span> <?php endif; ?> </span> <div class="note-list-comment"><?= $block->escapeHtml($_comment->getComment(), ['b', 'br', 'strong', 'i', 'u', 'a']) ?></div> @@ -70,15 +67,12 @@ </div> <script> require(['prototype'], function(){ - -submitComment = function() { - submitAndReloadArea($('comments_block').parentNode, '<?= /* @escapeNotVerified */ $block->getSubmitUrl() ?>') -} - -if ($('submit_comment_button')) { - $('submit_comment_button').observe('click', submitComment); -} - + submitComment = function() { + submitAndReloadArea($('comments_block').parentNode, '<?= $block->escapeUrl($block->getSubmitUrl()) ?>') + }; + if ($('submit_comment_button')) { + $('submit_comment_button').observe('click', submitComment); + } }); </script> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/abstract.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/abstract.phtml index 13433846d6ac4..6083a37efeabc 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/abstract.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/abstract.phtml @@ -3,14 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ $block->getHeaderText() ?></span> - <?php if($block->getButtonsHtml()): ?> + <span class="title"><?= $block->escapeHtml($block->getHeaderText()) ?></span> + <?php if ($block->getButtonsHtml()) : ?> <div class="actions"><?= $block->getButtonsHtml() ?></div> <?php endif; ?> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/billing/method/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/billing/method/form.phtml index 2133d7996f470..f4989bfc4b447 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/billing/method/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/billing/method/form.phtml @@ -20,32 +20,32 @@ ?> <dt class="admin__field-option"> <?php if ($_methodsCount > 1) : ?> - <input id="p_method_<?= $block->escapeHtml($_code); ?>" - value="<?= $block->escapeHtml($_code); ?>" + <input id="p_method_<?= $block->escapeHtmlAttr($_code); ?>" + value="<?= $block->escapeHtmlAttr($_code); ?>" type="radio" name="payment[method]" - title="<?= $block->escapeHtml($_method->getTitle()); ?>" - onclick="payment.switchMethod('<?= $block->escapeHtml($_code); ?>')" + title="<?= $block->escapeHtmlAttr($_method->getTitle()); ?>" + onclick="payment.switchMethod('<?= $block->escapeJs($_code); ?>')" <?php if ($block->getSelectedMethodCode() == $_code) : ?> checked="checked" <?php endif; ?> <?php $className = ($_counter == $_methodsCount) ? ' validate-one-required-by-name' : ''; ?> - class="admin__control-radio<?= $block->escapeHtml($className); ?>"/> + class="admin__control-radio<?= $block->escapeHtmlAttr($className); ?>"/> <?php else : ?> <span class="no-display"> - <input id="p_method_<?= $block->escapeHtml($_code); ?>" - value="<?= $block->escapeHtml($_code); ?>" + <input id="p_method_<?= $block->escapeHtmlAttr($_code); ?>" + value="<?= $block->escapeHtmlAttr($_code); ?>" type="radio" name="payment[method]" class="admin__control-radio" checked="checked"/> </span> <?php endif; ?> - <label class="admin__field-label" for="p_method_<?= $block->escapeHtml($_code); ?>"> + <label class="admin__field-label" for="p_method_<?= $block->escapeHtmlAttr($_code); ?>"> <?= $block->escapeHtml($_method->getTitle()) ?> </label> </dt> <dd class="admin__payment-method-wrapper"> - <?= /* @noEscape */ $block->getChildHtml('payment.method.' . $_code) ?> + <?= $block->getChildHtml('payment.method.' . $_code) ?> </dd> <?php endforeach; ?> </dl> @@ -57,9 +57,9 @@ ], function(mage) { mage.apply(); <?php if ($_methodsCount != 1) : ?> - order.setPaymentMethod('<?= $block->escapeHtml($currentSelectedMethod); ?>'); + order.setPaymentMethod('<?= $block->escapeJs($currentSelectedMethod); ?>'); <?php else : ?> - payment.switchMethod('<?= $block->escapeHtml($currentSelectedMethod); ?>'); + payment.switchMethod('<?= $block->escapeJs($currentSelectedMethod); ?>'); <?php endif; ?> }); </script> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/comment.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/comment.phtml index 2cf09583bd902..dfa6b5e6fff79 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/comment.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/comment.phtml @@ -4,18 +4,16 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Comment $block */ +?> - ?> - -<?php /* <h4 class="icon-head fieldset-legend <?= $block->getHeaderCssClass() ?>"><?= $block->getHeaderText() ?></h4> */ ?> <div class="admin__field field-comment"> - <label for="order-comment" class="admin__field-label"><span><?= /* @escapeNotVerified */ __('Order Comments') ?></span></label> + <label for="order-comment" class="admin__field-label"><span><?= $block->escapeHtml(__('Order Comments')) ?></span></label> <div class="admin__field-control"> <textarea id="order-comment" name="order[comment][customer_note]" - class="admin__control-textarea"><?= /* @escapeNotVerified */ $block->getCommentNote() ?></textarea> + class="admin__control-textarea"><?= $block->escapeHtml($block->getCommentNote()) ?></textarea> </div> </div> <script> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml index d499df585e565..e88b6ee330e97 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml @@ -3,35 +3,26 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php -/** - * \Magento\Sales\Block\Adminhtml\Order\Create\Coupons - * - */ +/* @var \Magento\Sales\Block\Adminhtml\Order\Create\Coupons $block */ ?> - <div class="admin__field field-apply-coupon-code"> - <label class="admin__field-label"><span><?= /* @escapeNotVerified */ __('Apply Coupon Code') ?></span></label> + <label class="admin__field-label"><span><?= $block->escapeHtml(__('Apply Coupon Code')) ?></span></label> <div class="admin__field-control"> <input type="text" class="admin__control-text" id="coupons:code" value="" name="coupon_code" /> <?= $block->getButtonHtml(__('Apply'), 'order.applyCoupon($F(\'coupons:code\'))') ?> - <?php if ($block->getCouponCode()): ?> + <?php if ($block->getCouponCode()) : ?> <p class="added-coupon-code"> <span><?= $block->escapeHtml($block->getCouponCode()) ?></span> - <a href="#" onclick="order.applyCoupon(''); return false;" title="<?= /* @escapeNotVerified */ __('Remove Coupon Code') ?>" - class="action-remove"><span><?= /* @escapeNotVerified */ __('Remove') ?></span></a> + <a href="#" onclick="order.applyCoupon(''); return false;" title="<?= $block->escapeHtmlAttr(__('Remove Coupon Code')) ?>" + class="action-remove"><span><?= $block->escapeHtml(__('Remove')) ?></span></a> </p> <?php endif; ?> <script> - require(["Magento_Sales/order/create/form"], function(){ - - order.overlay('shipping-method-overlay', <?php if ($block->getQuote()->isVirtual()): ?>false<?php else: ?>true<?php endif; ?>); - order.overlay('address-shipping-overlay', <?php if ($block->getQuote()->isVirtual()): ?>false<?php else: ?>true<?php endif; ?>); - + require(["Magento_Sales/order/create/form"], function() { + order.overlay('shipping-method-overlay', <?php if ($block->getQuote()->isVirtual()) : ?>false<?php else : ?>true<?php endif; ?>); + order.overlay('address-shipping-overlay', <?php if ($block->getQuote()->isVirtual()) : ?>false<?php else : ?>true<?php endif; ?>); }); </script> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/data.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/data.phtml index 170fea937348d..bd5baf397fcec 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/data.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/data.phtml @@ -4,16 +4,15 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Data $block */ ?> <div class="page-create-order"> <script> require(["Magento_Sales/order/create/form"], function(){ - order.setCurrencySymbol('<?= /* @escapeNotVerified */ $block->getCurrencySymbol($block->getCurrentCurrencyCode()) ?>') + order.setCurrencySymbol('<?= $block->escapeJs($block->getCurrencySymbol($block->getCurrentCurrencyCode())) ?>') }); </script> - <div class="order-details<?php if ($block->getCustomerId()): ?> order-details-existing-customer<?php endif; ?>"> + <div class="order-details<?php if ($block->getCustomerId()) : ?> order-details-existing-customer<?php endif; ?>"> <div id="order-additional_area" style="display: none" class="admin__page-section order-additional-area"> <?= $block->getChildHtml('additional_area') ?> @@ -35,7 +34,7 @@ <section id="order-addresses" class="admin__page-section order-addresses"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Address Information') ?></span> + <span class="title"><?= $block->escapeHtml(__('Address Information')) ?></span> </div> <div class="admin__page-section-content"> <div id="order-billing_address" class="admin__page-section-item order-billing-address"> @@ -59,7 +58,7 @@ </div> </section> - <?php if ($block->getChildBlock('card_validation')): ?> + <?php if ($block->getChildBlock('card_validation')) : ?> <section id="order-card_validation" class="admin__page-section order-card-validation"> <?= $block->getChildHtml('card_validation') ?> </section> @@ -69,11 +68,11 @@ <section class="admin__page-section order-summary"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Order Total') ?></span> + <span class="title"><?= $block->escapeHtml(__('Order Total')) ?></span> </div> <div class="admin__page-section-content"> <fieldset class="admin__fieldset order-history" id="order-comment"> - <legend class="admin__legend"><span><?= /* @escapeNotVerified */ __('Order History') ?></span></legend> + <legend class="admin__legend"><span><?= $block->escapeHtml(__('Order History')) ?></span></legend> <br> <?= $block->getChildHtml('comment') ?> </fieldset> @@ -84,19 +83,19 @@ </section> </div> - <?php if ($block->getCustomerId()): ?> + <?php if ($block->getCustomerId()) : ?> <div class="order-sidebar"> <div class="store-switcher order-currency"> <label class="admin__field-label" for="currency_switcher"> - <?= /* @escapeNotVerified */ __('Order Currency:') ?> + <?= $block->escapeHtml(__('Order Currency:')) ?> </label> <select id="currency_switcher" class="admin__control-select" name="order[currency]" onchange="order.setCurrencyId(this.value); order.setCurrencySymbol(this.options[this.selectedIndex].getAttribute('symbol'));"> - <?php foreach ($block->getAvailableCurrencies() as $_code): ?> - <option value="<?= /* @escapeNotVerified */ $_code ?>"<?php if ($_code == $block->getCurrentCurrencyCode()): ?> selected="selected"<?php endif; ?> symbol="<?= /* @escapeNotVerified */ $block->getCurrencySymbol($_code) ?>"> - <?= /* @escapeNotVerified */ $block->getCurrencyName($_code) ?> + <?php foreach ($block->getAvailableCurrencies() as $_code) : ?> + <option value="<?= $block->escapeHtmlAttr($_code) ?>"<?php if ($_code == $block->getCurrentCurrencyCode()) : ?> selected="selected"<?php endif; ?> symbol="<?= $block->escapeHtmlAttr($block->getCurrencySymbol($_code)) ?>"> + <?= $block->escapeHtml($block->getCurrencyName($_code)) ?> </option> <?php endforeach; ?> </select> @@ -106,5 +105,4 @@ </div> </div> <?php endif; ?> - </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form.phtml index f46e1f74ca8d5..c38acb9b79e47 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form.phtml @@ -4,22 +4,20 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** @var \Magento\Sales\Block\Adminhtml\Order\Create\Form $block */ ?> -<form id="edit_form" data-order-config='<?= $block->escapeHtml($block->getOrderDataJson()) ?>' data-load-base-url="<?= /* @escapeNotVerified */ $block->getLoadBlockUrl() ?>" action="<?= /* @escapeNotVerified */ $block->getSaveUrl() ?>" method="post" enctype="multipart/form-data"> +<form id="edit_form" data-order-config='<?= $block->escapeHtml($block->getOrderDataJson()) ?>' data-load-base-url="<?= $block->escapeUrl($block->getLoadBlockUrl()) ?>" action="<?= $block->escapeUrl($block->getSaveUrl()) ?>" method="post" enctype="multipart/form-data"> <?= $block->getBlockHtml('formkey') ?> <div id="order-message"> <?= $block->getChildHtml('message') ?> </div> - <div id="order-customer-selector" class="fieldset-wrapper order-customer-selector" style="display:<?= /* @escapeNotVerified */ $block->getCustomerSelectorDisplay() ?>"> + <div id="order-customer-selector" class="fieldset-wrapper order-customer-selector" style="display:<?= /* @noEscape */ $block->getCustomerSelectorDisplay() ?>"> <?= $block->getChildHtml('customer.grid.container') ?> </div> - <div id="order-store-selector" class="fieldset-wrapper" style="display:<?= /* @escapeNotVerified */ $block->getStoreSelectorDisplay() ?>"> + <div id="order-store-selector" class="fieldset-wrapper" style="display:<?= /* @noEscape */ $block->getStoreSelectorDisplay() ?>"> <?= $block->getChildHtml('store') ?> </div> - <div id="order-data" style="display:<?= /* @escapeNotVerified */ $block->getDataSelectorDisplay() ?>"> + <div id="order-data" style="display:<?= /* @noEscape */ $block->getDataSelectorDisplay() ?>"> <?= $block->getChildHtml('data') ?> </div> </form> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/account.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/account.phtml index 0d2ee1f24d5b3..f9611a02c53e4 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/account.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/account.phtml @@ -3,10 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +/** @var $block \Magento\Sales\Block\Adminhtml\Order\Create\Form\Account */ ?> -<div class="admin__page-section-title <?= /* @escapeNotVerified */ $block->getHeaderCssClass() ?>"> - <span class="title"><?= /* @escapeNotVerified */ $block->getHeaderText() ?></span> +<div class="admin__page-section-title <?= $block->escapeHtmlAttr($block->getHeaderCssClass()) ?>"> + <span class="title"><?= $block->escapeHtml($block->getHeaderText()) ?></span> <div class="actions"></div> </div> <div id="customer_account_fieds" class="admin__page-section-content"> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml index 1fd466c096663..5ce001474f5f5 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml @@ -4,7 +4,7 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Form\Address $block */ /** * @var \Magento\Customer\Model\ResourceModel\Address\Collection $addressCollection @@ -12,9 +12,9 @@ $addressCollection = $block->getData('customerAddressCollection'); $addressArray = []; -if ($block->getCustomerId()) { +if ($block->getCustomerId()) : $addressArray = $addressCollection->setCustomerFilter([$block->getCustomerId()])->toArray(); -} +endif; /** * @var \Magento\Sales\ViewModel\Customer\AddressFormatter $customerAddressFormatter @@ -24,60 +24,58 @@ $customerAddressFormatter = $block->getData('customerAddressFormatter'); /** * @var \Magento\Sales\Block\Adminhtml\Order\Create\Billing\Address|\Magento\Sales\Block\Adminhtml\Order\Create\Shipping\Address $block */ -if ($block->getIsShipping()): +if ($block->getIsShipping()) : $_fieldsContainerId = 'order-shipping_address_fields'; $_addressChoiceContainerId = 'order-shipping_address_choice'; ?> <script> require(["Magento_Sales/order/create/form"], function(){ - - order.shippingAddressContainer = '<?= /* @escapeNotVerified */ $_fieldsContainerId ?>'; - order.setAddresses(<?= /* @noEscape */ $block->getAddressCollectionJson() ?>); - + order.shippingAddressContainer = '<?= $block->escapeJs($_fieldsContainerId) ?>'; + order.setAddresses(<?= /* @noEscape */ $block->getAddressCollectionJson() ?>); }); </script> <?php -else: +else : $_fieldsContainerId = 'order-billing_address_fields'; $_addressChoiceContainerId = 'order-billing_address_choice'; ?> <script> require(["Magento_Sales/order/create/form"], function(){ - order.billingAddressContainer = '<?= /* @escapeNotVerified */ $_fieldsContainerId ?>'; + order.billingAddressContainer = '<?= $block->escapeJs($_fieldsContainerId) ?>'; }); </script> <?php endif; ?> <fieldset class="admin__fieldset"> - <legend class="admin__legend <?= /* @escapeNotVerified */ $block->getHeaderCssClass() ?>"> - <span><?= /* @escapeNotVerified */ $block->getHeaderText() ?></span> + <legend class="admin__legend <?= $block->escapeHtmlAttr($block->getHeaderCssClass()) ?>"> + <span><?= $block->escapeHtml($block->getHeaderText()) ?></span> </legend><br> - <fieldset id="<?= /* @escapeNotVerified */ $_addressChoiceContainerId ?>" class="admin__fieldset order-choose-address"> - <?php if ($block->getIsShipping()): ?> + <fieldset id="<?= $block->escapeHtmlAttr($_addressChoiceContainerId) ?>" class="admin__fieldset order-choose-address"> + <?php if ($block->getIsShipping()) : ?> <div class="admin__field admin__field-option admin__field-shipping-same-as-billing"> <input type="checkbox" id="order-shipping_same_as_billing" name="shipping_same_as_billing" onclick="order.setShippingAsBilling(this.checked)" class="admin__control-checkbox" - <?php if ($block->getIsAsBilling()): ?>checked<?php endif; ?> /> + <?php if ($block->getIsAsBilling()) : ?>checked<?php endif; ?> /> <label for="order-shipping_same_as_billing" class="admin__field-label"> - <?= /* @escapeNotVerified */ __('Same As Billing Address') ?> + <?= $block->escapeHtml(__('Same As Billing Address')) ?> </label> </div> <?php endif; ?> <div class="admin__field admin__field-select-from-existing-address"> - <label class="admin__field-label"><?= /* @escapeNotVerified */ __('Select from existing customer addresses:') ?></label> + <label class="admin__field-label"><?= $block->escapeHtml(__('Select from existing customer addresses:')) ?></label> <?php $_id = $block->getForm()->getHtmlIdPrefix() . 'customer_address_id' ?> <div class="admin__field-control"> - <select id="<?= /* @escapeNotVerified */ $_id ?>" - name="<?= $block->getForm()->getHtmlNamePrefix() ?>[customer_address_id]" - onchange="order.selectAddress(this, '<?= /* @escapeNotVerified */ $_fieldsContainerId ?>')" + <select id="<?= $block->escapeHtmlAttr($_id) ?>" + name="<?= $block->escapeHtmlAttr($block->getForm()->getHtmlNamePrefix()) ?>[customer_address_id]" + onchange="order.selectAddress(this, '<?= $block->escapeJs($_fieldsContainerId) ?>')" class="admin__control-select"> - <option value=""><?= /* @escapeNotVerified */ __('Add New Address') ?></option> - <?php foreach ($addressArray as $addressId => $address): ?> + <option value=""><?= $block->escapeHtml(__('Add New Address')) ?></option> + <?php foreach ($addressArray as $addressId => $address) : ?> <option - value="<?= /* @escapeNotVerified */ $addressId ?>"<?php if ($addressId == $block->getAddressId()): ?> selected="selected"<?php endif; ?>> - <?= /* @escapeNotVerified */ $block->escapeHtml($customerAddressFormatter->getAddressAsString($address)) ?> + value="<?= $block->escapeHtmlAttr($addressId) ?>"<?php if ($addressId == $block->getAddressId()) : ?> selected="selected"<?php endif; ?>> + <?= $block->escapeHtml($customerAddressFormatter->getAddressAsString($address)) ?> </option> <?php endforeach; ?> </select> @@ -85,31 +83,27 @@ endif; ?> </div> </fieldset> - <div class="order-address admin__fieldset" id="<?= /* @escapeNotVerified */ $_fieldsContainerId ?>"> + <div class="order-address admin__fieldset" id="<?= $block->escapeHtmlAttr($_fieldsContainerId) ?>"> <?= $block->getForm()->toHtml() ?> <div class="admin__field admin__field-option order-save-in-address-book"> - <input name="<?= $block->getForm()->getHtmlNamePrefix() ?>[save_in_address_book]" type="checkbox" - id="<?= $block->getForm()->getHtmlIdPrefix() ?>save_in_address_book" - value="1" - <?php if (!$block->getDontSaveInAddressBook() && $block->getAddress()->getSaveInAddressBook()): ?> checked="checked"<?php endif; ?> - class="admin__control-checkbox"/> - <label for="<?= $block->getForm()->getHtmlIdPrefix() ?>save_in_address_book" - class="admin__field-label"><?= /* @escapeNotVerified */ __('Save in address book') ?></label> + <input name="<?= $block->escapeHtmlAttr($block->getForm()->getHtmlNamePrefix()) ?>[save_in_address_book]" type="checkbox" id="<?= $block->escapeHtmlAttr($block->getForm()->getHtmlIdPrefix()) ?>save_in_address_book" value="1"<?php if (!$block->getDontSaveInAddressBook()) : ?> checked="checked"<?php endif; ?> class="admin__control-checkbox"/> + <label for="<?= $block->escapeHtmlAttr($block->getForm()->getHtmlIdPrefix()) ?>save_in_address_book" + class="admin__field-label"><?= $block->escapeHtml(__('Save in address book')) ?></label> </div> </div> <?php $hideElement = 'address-' . ($block->getIsShipping() ? 'shipping' : 'billing') . '-overlay'; ?> - <div style="display: none;" id="<?= /* @escapeNotVerified */ $hideElement ?>" class="order-methods-overlay"> - <span><?= /* @escapeNotVerified */ __('You don\'t need to select a shipping address.') ?></span> + <div style="display: none;" id="<?= /* @noEscape */ $hideElement ?>" class="order-methods-overlay"> + <span><?= $block->escapeHtml(__('You don\'t need to select a shipping address.')) ?></span> </div> <script> require(["Magento_Sales/order/create/form"], function(){ - order.bindAddressFields('<?= /* @escapeNotVerified */ $_fieldsContainerId ?>'); - order.bindAddressFields('<?= /* @escapeNotVerified */ $_addressChoiceContainerId ?>'); - <?php if ($block->getIsShipping() && $block->getIsAsBilling()): ?> - order.disableShippingAddress(true); - <?php endif; ?> + order.bindAddressFields('<?= $block->escapeJs($_fieldsContainerId) ?>'); + order.bindAddressFields('<?= $block->escapeJs($_addressChoiceContainerId) ?>'); + <?php if ($block->getIsShipping() && $block->getIsAsBilling()) : ?> + order.disableShippingAddress(true); + <?php endif; ?> }); </script> </fieldset> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/giftmessage.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/giftmessage.phtml index 14d020c4763f5..d27782fd20b15 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/giftmessage.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/giftmessage.phtml @@ -4,25 +4,25 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate +/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Giftmessage $block */ ?> -<?php if ($this->helper('Magento\GiftMessage\Helper\Message')->isMessagesAllowed('main', $block->getQuote(), $block->getStoreId())): ?> -<?php $_items = $block->getItems(); ?> -<div id="order-giftmessage" class="giftmessage-order-create"> - <fieldset class="admin__fieldset"> - <legend class="admin__legend"><span><?= /* @escapeNotVerified */ __('Gift Message for the Entire Order') ?></span></legend> - <br> - <?php if ($this->helper('Magento\GiftMessage\Helper\Message')->isMessagesAllowed('main', $block->getQuote(), $block->getStoreId())): ?> - <p><?= /* @escapeNotVerified */ __('Leave this box blank if you don\'t want to leave a gift message for the entire order.') ?></p> - <?= $block->getFormHtml($block->getQuote(), 'main') ?> - <?php endif; ?> - </fieldset> -<script> -require(['Magento_Sales/order/create/form'], function(){ - - order.giftmessageFieldsBind('order-giftmessage'); -}); -</script> -</div> +<?php if ($this->helper(\Magento\GiftMessage\Helper\Message::class)->isMessagesAllowed('main', $block->getQuote(), $block->getStoreId())) : ?> + <?php $_items = $block->getItems(); ?> + <div id="order-giftmessage" class="giftmessage-order-create"> + <fieldset class="admin__fieldset"> + <legend class="admin__legend"><span><?= $block->escapeHtml(__('Gift Message for the Entire Order')) ?></span></legend> + <br> + <?php if ($this->helper(\Magento\GiftMessage\Helper\Message::class)->isMessagesAllowed('main', $block->getQuote(), $block->getStoreId())) : ?> + <p><?= $block->escapeHtml(__('Leave this box blank if you don\'t want to leave a gift message for the entire order.')) ?></p> + <?= $block->getFormHtml($block->getQuote(), 'main') ?> + <?php endif; ?> + </fieldset> + <script> + require(['Magento_Sales/order/create/form'], function(){ + order.giftmessageFieldsBind('order-giftmessage'); + }); + </script> + </div> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items.phtml index de7af269538d9..4c31e34d38654 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items.phtml @@ -4,12 +4,10 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Items $block */ ?> - <div class="admin__page-section-title"> - <strong class="title"><?= /* @escapeNotVerified */ $block->getHeaderText() ?></strong> + <strong class="title"><?= $block->escapeHtml($block->getHeaderText()) ?></strong> <div class="actions"> <?= $block->getButtonsHtml() ?> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/grid.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/grid.phtml index 02cf697b0e74a..cd7d215b36af5 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/grid.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/grid.phtml @@ -4,8 +4,7 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +// phpcs:disable Magento2.Templates.ThisInTemplate ?> <?php /** @@ -14,32 +13,32 @@ ?> <?php $_items = $block->getItems() ?> -<?php if (empty($_items)): ?> +<?php if (empty($_items)) : ?> <div id="order-items_grid"> <div class="admin__table-wrapper"> <table class="data-table admin__table-primary order-tables"> <thead> <tr class="headings"> - <th class="col-product"><span><?= /* @escapeNotVerified */ __('Product') ?></span></th> - <th class="col-price"><span><?= /* @escapeNotVerified */ __('Price') ?></span></th> - <th class="col-qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></th> - <th class="col-subtotal"><span><?= /* @escapeNotVerified */ __('Subtotal') ?></span></th> - <th class="col-discount"><span><?= /* @escapeNotVerified */ __('Discount') ?></span></th> - <th class="col-row-total"><span><?= /* @escapeNotVerified */ __('Row Subtotal') ?></span></th> - <th class="col-action"><span><?= /* @escapeNotVerified */ __('Action') ?></span></th> + <th class="col-product"><span><?= $block->escapeHtml(__('Product')) ?></span></th> + <th class="col-price"><span><?= $block->escapeHtml(__('Price')) ?></span></th> + <th class="col-qty"><span><?= $block->escapeHtml(__('Qty')) ?></span></th> + <th class="col-subtotal"><span><?= $block->escapeHtml(__('Subtotal')) ?></span></th> + <th class="col-discount"><span><?= $block->escapeHtml(__('Discount')) ?></span></th> + <th class="col-row-total"><span><?= $block->escapeHtml(__('Row Subtotal')) ?></span></th> + <th class="col-action"><span><?= $block->escapeHtml(__('Action')) ?></span></th> </tr> </thead> <tbody> <tr class="even"> - <td class="empty-text" colspan="100"><?= /* @escapeNotVerified */ __('No ordered items') ?></td> + <td class="empty-text" colspan="100"><?= $block->escapeHtml(__('No ordered items')) ?></td> </tr> </tbody> </table> </div> </div> -<?php else: ?> +<?php else : ?> <div class="admin__table-wrapper" id="order-items_grid"> - <?php if (count($_items)>10): ?> + <?php if (count($_items) > 10) : ?> <div class="actions update actions-update"> <?= $block->getButtonHtml(__('Update Items and Quantities'), 'order.itemsUpdate()', 'action-secondary') ?> </div> @@ -47,37 +46,34 @@ <table class="data-table admin__table-primary order-tables"> <thead> <tr class="headings"> - <th class="col-product"><span><?= /* @escapeNotVerified */ __('Product') ?></span></th> - <th class="col-price"><span><?= /* @escapeNotVerified */ __('Price') ?></span></th> - <th class="col-qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></th> - <th class="col-subtotal"><span><?= /* @escapeNotVerified */ __('Subtotal') ?></span></th> - <th class="col-discount"><span><?= /* @escapeNotVerified */ __('Discount') ?></span></th> - <th class="col-row-total"><span><?= /* @escapeNotVerified */ __('Row Subtotal') ?></span></th> - <th class="col-action"><span><?= /* @escapeNotVerified */ __('Action') ?></span></th> + <th class="col-product"><span><?= $block->escapeHtml(__('Product')) ?></span></th> + <th class="col-price"><span><?= $block->escapeHtml(__('Price')) ?></span></th> + <th class="col-qty"><span><?= $block->escapeHtml(__('Qty')) ?></span></th> + <th class="col-subtotal"><span><?= $block->escapeHtml(__('Subtotal')) ?></span></th> + <th class="col-discount"><span><?= $block->escapeHtml(__('Discount')) ?></span></th> + <th class="col-row-total"><span><?= $block->escapeHtml(__('Row Subtotal')) ?></span></th> + <th class="col-action"><span><?= $block->escapeHtml(__('Action')) ?></span></th> </tr> </thead> <tfoot> <tr> - <td class="col-total"><?= /* @escapeNotVerified */ __('Total %1 product(s)', count($_items)) ?></td> - <td colspan="2" class="col-subtotal"><?= /* @escapeNotVerified */ __('Subtotal:') ?></td> - <td class="col-price"><strong><?= /* @escapeNotVerified */ $block->formatPrice($block->getSubtotal()) ?></strong></td> - <td class="col-price"><strong><?= /* @escapeNotVerified */ $block->formatPrice($block->getDiscountAmount()) ?></strong></td> - <td class="col-price"><strong> - <?php - /* @escapeNotVerified */ echo $block->formatPrice($block->getSubtotalWithDiscount()); - ?></strong></td> + <td class="col-total"><?= $block->escapeHtml(__('Total %1 product(s)', count($_items))) ?></td> + <td colspan="2" class="col-subtotal"><?= $block->escapeHtml(__('Subtotal:')) ?></td> + <td class="col-price"><strong><?= /* @noEscape */ $block->formatPrice($block->getSubtotal()) ?></strong></td> + <td class="col-price"><strong><?= /* @noEscape */ $block->formatPrice($block->getDiscountAmount()) ?></strong></td> + <td class="col-price"><strong><?= /* @noEscape */ $block->formatPrice($block->getSubtotalWithDiscount()); ?></strong></td> <td colspan="2"> </td> </tr> </tfoot> <?php $i = 0 ?> - <?php foreach ($_items as $_item):$i++ ?> - <tbody class="<?= /* @escapeNotVerified */ ($i%2) ? 'even' : 'odd' ?>"> + <?php foreach ($_items as $_item) : $i++ ?> + <tbody class="<?= /* @noEscape */ ($i%2) ? 'even' : 'odd' ?>"> <tr> <td class="col-product"> - <span id="order_item_<?= /* @escapeNotVerified */ $_item->getId() ?>_title"><?= $block->escapeHtml($_item->getName()) ?></span> + <span id="order_item_<?= (int) $_item->getId() ?>_title"><?= $block->escapeHtml($_item->getName()) ?></span> <div class="product-sku-block"> - <span><?= /* @escapeNotVerified */ __('SKU') ?>:</span> - <?= implode('<br />', $this->helper('Magento\Catalog\Helper\Data')->splitSku($block->escapeHtml($_item->getSku()))) ?> + <span><?= $block->escapeHtml(__('SKU')) ?>:</span> + <?= /* @noEscape */ implode('<br />', $this->helper(\Magento\Catalog\Helper\Data::class)->splitSku($block->escapeHtml($_item->getSku()))) ?> </div> <div class="product-configure-block"> <?= $block->getConfigureButtonHtml($_item) ?> @@ -88,56 +84,56 @@ <?= $block->getItemUnitPriceHtml($_item) ?> <?php $_isCustomPrice = $block->usedCustomPriceForItem($_item) ?> - <?php if ($_tier = $block->getTierHtml($_item)): ?> - <div id="item_tier_block_<?= /* @escapeNotVerified */ $_item->getId() ?>"<?php if ($_isCustomPrice): ?> style="display:none"<?php endif; ?>> - <a href="#" onclick="$('item_tier_<?= /* @escapeNotVerified */ $_item->getId() ?>').toggle();return false;"><?= /* @escapeNotVerified */ __('Tier Pricing') ?></a> - <div style="display:none" id="item_tier_<?= /* @escapeNotVerified */ $_item->getId() ?>"><?= /* @escapeNotVerified */ $_tier ?></div> + <?php if ($_tier = $block->getTierHtml($_item)) : ?> + <div id="item_tier_block_<?= (int) $_item->getId() ?>"<?php if ($_isCustomPrice) : ?> style="display:none"<?php endif; ?>> + <a href="#" onclick="$('item_tier_<?= (int) $_item->getId() ?>').toggle();return false;"><?= $block->escapeHtml(__('Tier Pricing')) ?></a> + <div style="display:none" id="item_tier_<?= (int) $_item->getId() ?>"><?= /* @noEscape */ $_tier ?></div> </div> <?php endif; ?> - <?php if ($block->canApplyCustomPrice($_item)): ?> + <?php if ($block->canApplyCustomPrice($_item)) : ?> <div class="custom-price-block"> <input type="checkbox" class="admin__control-checkbox" - id="item_use_custom_price_<?= /* @escapeNotVerified */ $_item->getId() ?>" - <?php if ($_isCustomPrice): ?> checked="checked"<?php endif; ?> - onclick="order.toggleCustomPrice(this, 'item_custom_price_<?= /* @escapeNotVerified */ $_item->getId() ?>', 'item_tier_block_<?= /* @escapeNotVerified */ $_item->getId() ?>');"/> + id="item_use_custom_price_<?= (int) $_item->getId() ?>" + <?php if ($_isCustomPrice) : ?> checked="checked"<?php endif; ?> + onclick="order.toggleCustomPrice(this, 'item_custom_price_<?= (int) $_item->getId() ?>', 'item_tier_block_<?= (int) $_item->getId() ?>');"/> <label class="normal admin__field-label" - for="item_use_custom_price_<?= /* @escapeNotVerified */ $_item->getId() ?>"> - <span><?= /* @escapeNotVerified */ __('Custom Price') ?>*</span></label> + for="item_use_custom_price_<?= (int) $_item->getId() ?>"> + <span><?= $block->escapeHtml(__('Custom Price')) ?>*</span></label> </div> <?php endif; ?> - <input id="item_custom_price_<?= /* @escapeNotVerified */ $_item->getId() ?>" - name="item[<?= /* @escapeNotVerified */ $_item->getId() ?>][custom_price]" - value="<?= /* @escapeNotVerified */ sprintf("%.2f", $block->getOriginalEditablePrice($_item)) ?>" - <?php if (!$_isCustomPrice): ?> - style="display:none" - disabled="disabled" - <?php endif; ?> - class="input-text item-price admin__control-text"/> + <input id="item_custom_price_<?= (int) $_item->getId() ?>" + name="item[<?= (int) $_item->getId() ?>][custom_price]" + value="<?= /* @noEscape */ sprintf("%.2f", $block->getOriginalEditablePrice($_item)) ?>" + <?php if (!$_isCustomPrice) : ?> + style="display:none" + disabled="disabled" + <?php endif; ?> + class="input-text item-price admin__control-text"/> </td> <td class="col-qty"> - <input name="item[<?= /* @escapeNotVerified */ $_item->getId() ?>][qty]" + <input name="item[<?= (int) $_item->getId() ?>][qty]" class="input-text item-qty admin__control-text" - value="<?= /* @escapeNotVerified */ $_item->getQty()*1 ?>" + value="<?= (int) $_item->getQty() ?>" maxlength="12" /> </td> <td class="col-subtotal col-price"> <?= $block->getItemRowTotalHtml($_item) ?> </td> <td class="col-discount col-price"> - <?= /* @escapeNotVerified */ $block->formatPrice(-$_item->getTotalDiscountAmount()) ?> + <?= /* @noEscape */ $block->formatPrice(-$_item->getTotalDiscountAmount()) ?> <div class="discount-price-block"> - <input id="item_use_discount_<?= /* @escapeNotVerified */ $_item->getId() ?>" + <input id="item_use_discount_<?= (int) $_item->getId() ?>" class="admin__control-checkbox" - name="item[<?= /* @escapeNotVerified */ $_item->getId() ?>][use_discount]" - <?php if (!$_item->getNoDiscount()): ?>checked="checked"<?php endif; ?> + name="item[<?= (int) $_item->getId() ?>][use_discount]" + <?php if (!$_item->getNoDiscount()) : ?>checked="checked"<?php endif; ?> value="1" type="checkbox" /> <label - for="item_use_discount_<?= /* @escapeNotVerified */ $_item->getId() ?>" + for="item_use_discount_<?= (int) $_item->getId() ?>" class="normal admin__field-label"> - <span><?= /* @escapeNotVerified */ __('Apply') ?></span></label> + <span><?= $block->escapeHtml(__('Apply')) ?></span></label> </div> </td> @@ -145,19 +141,19 @@ <?= $block->getItemRowTotalWithDiscountHtml($_item) ?> </td> <td class="col-actions last"> - <select class="admin__control-select" name="item[<?= /* @escapeNotVerified */ $_item->getId() ?>][action]"> - <option value=""><?= /* @escapeNotVerified */ __('Please select') ?></option> - <option value="remove"><?= /* @escapeNotVerified */ __('Remove') ?></option> - <?php if ($block->getCustomerId() && $block->getMoveToCustomerStorage()): ?> - <option value="cart"><?= /* @escapeNotVerified */ __('Move to Shopping Cart') ?></option> - <?php if ($block->isMoveToWishlistAllowed($_item)): ?> + <select class="admin__control-select" name="item[<?= (int) $_item->getId() ?>][action]"> + <option value=""><?= $block->escapeHtml(__('Please select')) ?></option> + <option value="remove"><?= $block->escapeHtml(__('Remove')) ?></option> + <?php if ($block->getCustomerId() && $block->getMoveToCustomerStorage()) : ?> + <option value="cart"><?= $block->escapeHtml(__('Move to Shopping Cart')) ?></option> + <?php if ($block->isMoveToWishlistAllowed($_item)) : ?> <?php $wishlists = $block->getCustomerWishlists();?> - <?php if (count($wishlists) <= 1):?> - <option value="wishlist"><?= /* @escapeNotVerified */ __('Move to Wish List') ?></option> - <?php else: ?> - <optgroup label="<?= /* @escapeNotVerified */ __('Move to Wish List') ?>"> - <?php foreach ($wishlists as $wishlist):?> - <option value="wishlist_<?= /* @escapeNotVerified */ $wishlist->getId() ?>"><?= $block->escapeHtml($wishlist->getName()) ?></option> + <?php if (count($wishlists) <= 1) : ?> + <option value="wishlist"><?= $block->escapeHtml(__('Move to Wish List')) ?></option> + <?php else : ?> + <optgroup label="<?= $block->escapeHtml(__('Move to Wish List')) ?>"> + <?php foreach ($wishlists as $wishlist) :?> + <option value="wishlist_<?= (int) $wishlist->getId() ?>"><?= $block->escapeHtml($wishlist->getName()) ?></option> <?php endforeach;?> </optgroup> <?php endif; ?> @@ -168,22 +164,21 @@ </tr> <?php $hasMessageError = false; ?> - <?php foreach ($_item->getMessage(false) as $messageError):?> - <?php if (!empty($messageError)) { + <?php foreach ($_item->getMessage(false) as $messageError) : ?> + <?php if (!empty($messageError)) : $hasMessageError = true; - } - ?> + endif; ?> <?php endforeach; ?> - <?php if ($hasMessageError):?> + <?php if ($hasMessageError) : ?> <tr class="row-messages-error"> <td colspan="100"> <!-- ToDo UI: remove the 100 --> - <?php foreach ($_item->getMessage(false) as $message): + <?php foreach ($_item->getMessage(false) as $message) : if (empty($message)) { continue; } ?> - <div class="message <?php if ($_item->getHasError()): ?>message-error<?php else: ?>message-notice<?php endif; ?>"> + <div class="message <?php if ($_item->getHasError()) : ?>message-error<?php else : ?>message-notice<?php endif; ?>"> <?= $block->escapeHtml($message) ?> </div> <?php endforeach; ?> @@ -195,7 +190,7 @@ </tbody> <?php endforeach; ?> </table> - <p><small><?= /* @escapeNotVerified */ $block->getInclExclTaxMessage() ?></small></p> + <p><small><?= $block->escapeHtml($block->getInclExclTaxMessage()) ?></small></p> </div> <div class="order-discounts"> @@ -210,43 +205,42 @@ order.itemsOnchangeBind() }); </script> + <?php if ($block->isGiftMessagesAvailable()) : ?> + <script> + require([ + "prototype", + "Magento_Sales/order/giftoptions_tooltip" + ], function(){ -<?php if ($block->isGiftMessagesAvailable()) : ?> -<script> -require([ - "prototype", - "Magento_Sales/order/giftoptions_tooltip" -], function(){ - -//<![CDATA[ - /** - * Retrieve gift options tooltip content - */ - function getGiftOptionsTooltipContent(itemId) { - var contentLines = []; - var headerLine = null; - var contentLine = null; - - $$('#gift_options_data_' + itemId + ' .gift-options-tooltip-content').each(function (element) { - if (element.down(0)) { - headerLine = element.down(0).innerHTML; - contentLine = element.down(0).next().innerHTML; - if (contentLine.length > 30) { - contentLine = contentLine.slice(0,30) + '...'; - } - contentLines.push(headerLine + ' ' + contentLine); + //<![CDATA[ + /** + * Retrieve gift options tooltip content + */ + function getGiftOptionsTooltipContent(itemId) { + var contentLines = []; + var headerLine = null; + var contentLine = null; + + $$('#gift_options_data_' + itemId + ' .gift-options-tooltip-content').each(function (element) { + if (element.down(0)) { + headerLine = element.down(0).innerHTML; + contentLine = element.down(0).next().innerHTML; + if (contentLine.length > 30) { + contentLine = contentLine.slice(0,30) + '...'; + } + contentLines.push(headerLine + ' ' + contentLine); + } + }); + return contentLines.join('<br/>'); } - }); - return contentLines.join('<br/>'); - } - giftOptionsTooltip.setTooltipContentLoaderFunction(getGiftOptionsTooltipContent); + giftOptionsTooltip.setTooltipContentLoaderFunction(getGiftOptionsTooltipContent); - window.getGiftOptionsTooltipContent = getGiftOptionsTooltipContent; + window.getGiftOptionsTooltipContent = getGiftOptionsTooltipContent; -//]]> + //]]> -}); -</script> -<?php endif; ?> + }); + </script> + <?php endif; ?> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/row.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/row.phtml index 2e1f058e17128..6a0715a056558 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/row.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/row.phtml @@ -3,16 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var \Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid $block */ - $_item = $block->getItem(); ?> - <div class="price-excl-tax"> - <?= /* @escapeNotVerified */ $block->formatPrice($_item->getRowTotal()) ?> + <?= /* @noEscape */ $block->formatPrice($_item->getRowTotal()) ?> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/total.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/total.phtml index aafd3afd2783c..7fdf39ed2bc21 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/total.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/total.phtml @@ -3,15 +3,10 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var \Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid $block */ - $_item = $block->getItem(); ?> - <?php $_rowTotalWithoutDiscount = $_item->getRowTotal() - $_item->getTotalDiscountAmount(); ?> -<?= /* @escapeNotVerified */ $block->formatPrice(max(0, $_rowTotalWithoutDiscount)) ?> +<?= /* @noEscape */ $block->formatPrice(max(0, $_rowTotalWithoutDiscount)) ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/unit.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/unit.phtml index 0ecefcf5273f1..b5871518cf596 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/unit.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/unit.phtml @@ -3,15 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var \Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid $block */ - $_item = $block->getItem(); ?> <div class="price-excl-tax"> -<?= /* @escapeNotVerified */ $block->formatPrice($_item->getCalculationPrice()) ?> +<?= /* @noEscape */ $block->formatPrice($_item->getCalculationPrice()) ?> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/js.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/js.phtml index 374684d351b49..eb39f71265cd6 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/js.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/js.phtml @@ -3,9 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> +?> <script> require([ "prototype", @@ -13,16 +11,14 @@ require([ "Magento_Catalog/catalog/product/composite/configure", "domReady!" ], function(){ - order.sidebarHide(); if (window.productConfigure) { productConfigure.addListType('product_to_add', { - urlFetch: '<?= /* @escapeNotVerified */ $block->getUrl('sales/order_create/configureProductToAdd') ?>' + urlFetch: '<?= $block->escapeJs($block->escapeUrl($block->getUrl('sales/order_create/configureProductToAdd'))) ?>' }); productConfigure.addListType('quote_items', { - urlFetch: '<?= /* @escapeNotVerified */ $block->getUrl('sales/order_create/configureQuoteItems') ?>' + urlFetch: '<?= $block->escapeJs($block->escapeUrl($block->getUrl('sales/order_create/configureQuoteItems'))) ?>' }); } - }); </script> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/newsletter/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/newsletter/form.phtml index 973758a66947c..1dcf57d879543 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/newsletter/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/newsletter/form.phtml @@ -3,8 +3,5 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> -<input type="checkbox" name="newsletter:subscribe"> <label for="newsletter:subscribe" style="width: 90%; float: none;"><?= /* @escapeNotVerified */ __('Subscribe to Newsletter') ?></label><br/> +<input type="checkbox" name="newsletter:subscribe"> <label for="newsletter:subscribe" style="width: 90%; float: none;"><?= $block->escapeHtml(__('Subscribe to Newsletter')) ?></label><br/> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/shipping/method/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/shipping/method/form.phtml index 65d3a612e5133..baaf4c078f2c7 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/shipping/method/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/shipping/method/form.phtml @@ -4,46 +4,45 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +// phpcs:disable Magento2.Templates.ThisInTemplate ?> <?php /** @var $block \Magento\Sales\Block\Adminhtml\Order\Create\Shipping\Method\Form */ ?> <?php $_shippingRateGroups = $block->getShippingRates(); ?> -<?php if ($_shippingRateGroups): ?> +<?php if ($_shippingRateGroups) : ?> <div id="order-shipping-method-choose" class="control" style="display:none"> <dl class="admin__order-shipment-methods"> - <?php foreach ($_shippingRateGroups as $code => $_rates): ?> + <?php foreach ($_shippingRateGroups as $code => $_rates) : ?> <dt class="admin__order-shipment-methods-title"><?= $block->escapeHtml($block->getCarrierName($code)) ?></dt> <dd class="admin__order-shipment-methods-options"> <ul class="admin__order-shipment-methods-options-list"> - <?php foreach ($_rates as $_rate): ?> + <?php foreach ($_rates as $_rate) : ?> <?php $_radioProperty = 'name="order[shipping_method]" type="radio" onclick="order.setShippingMethod(this.value)"' ?> <?php $_code = $_rate->getCode() ?> <li class="admin__field-option"> - <?php if ($_rate->getErrorMessage()): ?> - <div class="messages"> + <?php if ($_rate->getErrorMessage()) : ?> + <div class="messages"> <div class="message message-error error"> <div><?= $block->escapeHtml($_rate->getErrorMessage()) ?></div> </div> - </div> - <?php else: ?> + </div> + <?php else : ?> <?php $_checked = $block->isMethodActive($_code) ? 'checked="checked"' : '' ?> - <input <?= /* @escapeNotVerified */ $_radioProperty ?> value="<?= /* @escapeNotVerified */ $_code ?>" - id="s_method_<?= /* @escapeNotVerified */ $_code ?>" <?= /* @escapeNotVerified */ $_checked ?> + <input <?= /* @noEscape */ $_radioProperty ?> value="<?= $block->escapeHtmlAttr($_code) ?>" + id="s_method_<?= $block->escapeHtmlAttr($_code) ?>" <?= /* @noEscape */ $_checked ?> class="admin__control-radio required-entry"/> - <label class="admin__field-label" for="s_method_<?= /* @escapeNotVerified */ $_code ?>"> + <label class="admin__field-label" for="s_method_<?= $block->escapeHtmlAttr($_code) ?>"> <?= $block->escapeHtml($_rate->getMethodTitle() ? $_rate->getMethodTitle() : $_rate->getMethodDescription()) ?> - <strong> - <?php $_excl = $block->getShippingPrice($_rate->getPrice(), $this->helper('Magento\Tax\Helper\Data')->displayShippingPriceIncludingTax()); ?> + <?php $_excl = $block->getShippingPrice($_rate->getPrice(), $this->helper(\Magento\Tax\Helper\Data::class)->displayShippingPriceIncludingTax()); ?> <?php $_incl = $block->getShippingPrice($_rate->getPrice(), true); ?> - <?= /* @escapeNotVerified */ $_excl ?> - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayShippingBothPrices() && $_incl != $_excl): ?> - (<?= /* @escapeNotVerified */ __('Incl. Tax') ?> <?= /* @escapeNotVerified */ $_incl ?>) + <?= /* @noEscape */ $_excl ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayShippingBothPrices() && $_incl != $_excl) : ?> + (<?= $block->escapeHtml(__('Incl. Tax')) ?> <?= /* @noEscape */ $_incl ?>) <?php endif; ?> </strong> </label> - <?php endif ?> + <?php endif; ?> </li> <?php endforeach; ?> </ul> @@ -51,7 +50,7 @@ <?php endforeach; ?> </dl> </div> - <?php if ($_rate = $block->getActiveMethodRate()): ?> + <?php if ($_rate = $block->getActiveMethodRate()) : ?> <div id="order-shipping-method-info" class="order-shipping-method-info"> <dl class="admin__order-shipment-methods"> <dt class="admin__order-shipment-methods-title"> @@ -60,12 +59,12 @@ <dd class="admin__order-shipment-methods-options"> <?= $block->escapeHtml($_rate->getMethodTitle() ? $_rate->getMethodTitle() : $_rate->getMethodDescription()) ?> - <strong> - <?php $_excl = $block->getShippingPrice($_rate->getPrice(), $this->helper('Magento\Tax\Helper\Data')->displayShippingPriceIncludingTax()); ?> + <?php $_excl = $block->getShippingPrice($_rate->getPrice(), $this->helper(\Magento\Tax\Helper\Data::class)->displayShippingPriceIncludingTax()); ?> <?php $_incl = $block->getShippingPrice($_rate->getPrice(), true); ?> - <?= /* @escapeNotVerified */ $_excl ?> - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayShippingBothPrices() && $_incl != $_excl): ?> - (<?= /* @escapeNotVerified */ __('Incl. Tax') ?> <?= /* @escapeNotVerified */ $_incl ?>) + <?= /* @noEscape */ $_excl ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayShippingBothPrices() && $_incl != $_excl) : ?> + (<?= $block->escapeHtml(__('Incl. Tax')) ?> <?= /* @noEscape */ $_incl ?>) <?php endif; ?> </strong> </dd> @@ -73,35 +72,35 @@ <a href="#" onclick="$('order-shipping-method-info').hide();$('order-shipping-method-choose').show();return false" class="action-default"> - <span><?= /* @escapeNotVerified */ __('Click to change shipping method') ?></span> + <span><?= $block->escapeHtml(__('Click to change shipping method')) ?></span> </a> </div> - <?php else: ?> + <?php else : ?> <script> require(['prototype'], function(){ $('order-shipping-method-choose').show(); }); </script> <?php endif; ?> -<?php elseif ($block->getIsRateRequest()): ?> +<?php elseif ($block->getIsRateRequest()) : ?> <div class="order-shipping-method-summary"> - <strong class="order-shipping-method-not-available"><?= /* @escapeNotVerified */ __('Sorry, no quotes are available for this order.') ?></strong> + <strong class="order-shipping-method-not-available"><?= $block->escapeHtml(__('Sorry, no quotes are available for this order.')) ?></strong> </div> -<?php else: ?> +<?php else : ?> <div id="order-shipping-method-summary" class="order-shipping-method-summary"> <a href="#" onclick="order.loadShippingRates();return false" class="action-default"> - <span><?= /* @escapeNotVerified */ __('Get shipping methods and rates') ?></span> + <span><?= $block->escapeHtml(__('Get shipping methods and rates')) ?></span> </a> <input type="hidden" name="order[has_shipping]" value="" class="required-entry" /> </div> <?php endif; ?> <div style="display: none;" id="shipping-method-overlay" class="order-methods-overlay"> - <span><?= /* @escapeNotVerified */ __('You don\'t need to select a shipping method.') ?></span> + <span><?= $block->escapeHtml(__('You don\'t need to select a shipping method.')) ?></span> </div> <script> require(["Magento_Sales/order/create/form"], function(){ - order.overlay('shipping-method-overlay', <?php if ($block->getQuote()->isVirtual()): ?>false<?php else: ?>true<?php endif; ?>); - order.overlay('address-shipping-overlay', <?php if ($block->getQuote()->isVirtual()): ?>false<?php else: ?>true<?php endif; ?>); + order.overlay('shipping-method-overlay', <?php if ($block->getQuote()->isVirtual()) : ?>false<?php else : ?>true<?php endif; ?>); + order.overlay('address-shipping-overlay', <?php if ($block->getQuote()->isVirtual()) : ?>false<?php else : ?>true<?php endif; ?>); order.isOnlyVirtualProduct = <?= /* @noEscape */ $block->getQuote()->isVirtual() ? 'true' : 'false'; ?>; }); </script> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar.phtml index 48823de3f4db2..d4dea4eb85a57 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar.phtml @@ -4,18 +4,16 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - -/** @var $block \Magento\Sales\Block\Adminhtml\Order\Create\Sidebar */ +/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Sidebar $block */ ?> <div class="customer-current-activity-inner"> - <h4 class="customer-activity-title"><?= /* @escapeNotVerified */ __('Customer\'s Activities') ?></h4> + <h4 class="customer-activity-title"><?= $block->escapeHtml(__('Customer\'s Activities')) ?></h4> <div class="create-order-sidebar-container"> <?= $block->getChildHtml('top_button') ?> - <?php foreach ($block->getLayout()->getChildBlocks($block->getNameInLayout()) as $_alias => $_child): ?> - <?php if ($_alias != 'top_button' && $_alias != 'bottom_button'): ?> - <?php if ($block->canDisplay($_child)): ?> - <div class="order-sidebar-block" id="order-sidebar_<?= /* @escapeNotVerified */ $_alias ?>"> + <?php foreach ($block->getLayout()->getChildBlocks($block->getNameInLayout()) as $_alias => $_child) : ?> + <?php if ($_alias != 'top_button' && $_alias != 'bottom_button') : ?> + <?php if ($block->canDisplay($_child)) : ?> + <div class="order-sidebar-block" id="order-sidebar_<?= $block->escapeHtmlAttr($_alias) ?>"> <?= $block->getChildHtml($_alias) ?> </div> <?php endif; ?> @@ -32,12 +30,12 @@ require([ function addSidebarCompositeListType() { productConfigure.addListType('sidebar', { - urlFetch: '<?= /* @escapeNotVerified */ $block->getUrl('sales/order_create/configureProductToAdd') ?>', - urlConfirm: '<?= /* @escapeNotVerified */ $block->getUrl('sales/order_create/addConfigured') ?>' + urlFetch: '<?= $block->escapeJs($block->escapeUrl($block->getUrl('sales/order_create/configureProductToAdd'))) ?>', + urlConfirm: '<?= $block->escapeJs($block->escapeUrl($block->getUrl('sales/order_create/addConfigured'))) ?>' }); productConfigure.addListType('sidebar_wishlist', { - urlFetch: '<?= /* @escapeNotVerified */ $block->getUrl('customer/wishlist_product_composite_wishlist/configure') ?>', - urlConfirm: '<?= /* @escapeNotVerified */ $block->getUrl('sales/order_create/addConfigured') ?>' + urlFetch: '<?= $block->escapeJs($block->escapeUrl($block->getUrl('customer/wishlist_product_composite_wishlist/configure'))) ?>', + urlConfirm: '<?= $block->escapeJs($block->escapeUrl($block->getUrl('sales/order_create/addConfigured'))) ?>' }); } diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar/items.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar/items.phtml index 2dbf717f73439..5e26e2fa23064 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar/items.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar/items.phtml @@ -3,44 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /* @var $block \Magento\Sales\Block\Adminhtml\Order\Create\Sidebar\AbstractSidebar */ ?> -<div class="create-order-sidebar-block" id="sidebar_data_<?= /* @escapeNotVerified */ $block->getDataId() ?>"> +<div class="create-order-sidebar-block" id="sidebar_data_<?= $block->escapeHtmlAttr($block->getDataId()) ?>"> <div class="head sidebar-title-block"> <a href="#" class="action-refresh" title="<?= $block->escapeHtml(__('Refresh')) ?>" - onclick="order.loadArea('sidebar_<?= /* @escapeNotVerified */ $block->getDataId() ?>', 'sidebar_data_<?= /* @escapeNotVerified */ $block->getDataId() ?>');return false;"> - <span><?= /* @escapeNotVerified */ __('Refresh') ?></span> + onclick="order.loadArea('sidebar_<?= $block->escapeJs($block->getDataId()) ?>', 'sidebar_data_<?= $block->escapeJs($block->getDataId()) ?>');return false;"> + <span><?= $block->escapeHtml(__('Refresh')) ?></span> </a> <h5 class="create-order-sidebar-label"> - <?= /* @escapeNotVerified */ $block->getHeaderText() ?> - <span class="normal">(<?= /* @escapeNotVerified */ $block->getItemCount() ?>)</span> + <?= $block->escapeHtml($block->getHeaderText()) ?> + <span class="normal">(<?= $block->escapeHtml($block->getItemCount()) ?>)</span> </h5> </div> <div class="content"> <div class="auto-scroll"> - <?php if ($block->getItemCount()): ?> + <?php if ($block->getItemCount()) : ?> <table class="admin__table-primary"> <thead> <tr> - <th class="col-item"><?= /* @escapeNotVerified */ __('Item') ?></th> + <th class="col-item"><?= $block->escapeHtml(__('Item')) ?></th> - <?php if ($block->canDisplayItemQty()): ?> - <th class="col-qty"><?= /* @escapeNotVerified */ __('Qty') ?></th> + <?php if ($block->canDisplayItemQty()) : ?> + <th class="col-qty"><?= $block->escapeHtml(__('Qty')) ?></th> <?php endif; ?> - <?php if ($block->canDisplayPrice()): ?> - <th class="col-price"><?= /* @escapeNotVerified */ __('Price') ?></th> + <?php if ($block->canDisplayPrice()) : ?> + <th class="col-price"><?= $block->escapeHtml(__('Price')) ?></th> <?php endif; ?> - <?php if ($block->canRemoveItems()): ?> + <?php if ($block->canRemoveItems()) : ?> <th class="col-remove"> <span title="<?= $block->escapeHtml(__('Remove')) ?>" class="icon icon-remove"> - <span><?= /* @escapeNotVerified */ __('Remove') ?></span> + <span><?= $block->escapeHtml(__('Remove')) ?></span> </span> </th> <?php endif; ?> @@ -48,40 +45,40 @@ <th class="col-add"> <span title="<?= $block->escapeHtml(__('Add To Order')) ?>" class="icon icon-add"> - <span><?= /* @escapeNotVerified */ __('Add To Order') ?></span> + <span><?= $block->escapeHtml(__('Add To Order')) ?></span> </span> </th> </tr> </thead> <tbody> - <?php foreach ($block->getItems() as $_item): ?> + <?php foreach ($block->getItems() as $_item) : ?> <tr> <td class="col-item"><?= $block->escapeHtml($_item->getName()) ?></td> - <?php if ($block->canDisplayItemQty()): ?> + <?php if ($block->canDisplayItemQty()) : ?> <td class="col-qty"> - <?= /* @escapeNotVerified */ $block->getItemQty($_item) ?> + <?= (int) $block->getItemQty($_item) ?> </td> <?php endif; ?> - <?php if ($block->canDisplayPrice()): ?> + <?php if ($block->canDisplayPrice()) : ?> <td class="col-price"> <?= /* @noEscape */ $block->getItemPrice($block->getProduct($_item)) ?> </td> <?php endif; ?> - <?php if ($block->canRemoveItems()): ?> + <?php if ($block->canRemoveItems()) : ?> <td class="col-remove"> <div class="admin__field-option"> - <input id="sidebar-remove-<?= /* @escapeNotVerified */ $block->getSidebarStorageAction() ?>-<?= /* @escapeNotVerified */ $block->getItemId($_item) ?>" + <input id="sidebar-remove-<?= $block->escapeHtmlAttr($block->getSidebarStorageAction()) ?>-<?= (int) $block->getItemId($_item) ?>" type="checkbox" class="admin__control-checkbox" - name="sidebar[remove][<?= /* @escapeNotVerified */ $block->getItemId($_item) ?>]" - value="<?= /* @escapeNotVerified */ $block->getDataId() ?>" + name="sidebar[remove][<?= (int) $block->getItemId($_item) ?>]" + value="<?= $block->escapeHtmlAttr($block->getDataId()) ?>" title="<?= $block->escapeHtml(__('Remove')) ?>" /> <label class="admin__field-label" - for="sidebar-remove-<?= /* @escapeNotVerified */ $block->getSidebarStorageAction() ?>-<?= /* @escapeNotVerified */ $block->getItemId($_item) ?>"> + for="sidebar-remove-<?= $block->escapeHtmlAttr($block->getSidebarStorageAction()) ?>-<?= (int) $block->getItemId($_item) ?>"> </label> </div> </td> @@ -89,29 +86,29 @@ <td class="col-add"> <div class="admin__field-option"> - <?php if ($block->isConfigurationRequired($_item->getTypeId()) && $block->getDataId() == 'wishlist'): ?> + <?php if ($block->isConfigurationRequired($_item->getTypeId()) && $block->getDataId() == 'wishlist') : ?> <a href="#" class="icon icon-configure" title="<?= $block->escapeHtml(__('Configure and Add to Order')) ?>" - onclick="order.sidebarConfigureProduct('<?= 'sidebar_wishlist' ?>', <?= /* @escapeNotVerified */ $block->getProductId($_item) ?>, <?= /* @escapeNotVerified */ $block->getItemId($_item) ?>); return false;"> - <span><?= /* @escapeNotVerified */ __('Configure and Add to Order') ?></span> + onclick="order.sidebarConfigureProduct('sidebar_wishlist', <?= (int) $block->getProductId($_item) ?>, <?= (int) $block->getItemId($_item) ?>); return false;"> + <span><?= $block->escapeHtml(__('Configure and Add to Order')) ?></span> </a> - <?php elseif ($block->isConfigurationRequired($_item->getTypeId())): ?> + <?php elseif ($block->isConfigurationRequired($_item->getTypeId())) : ?> <a href="#" class="icon icon-configure" title="<?= $block->escapeHtml(__('Configure and Add to Order')) ?>" - onclick="order.sidebarConfigureProduct('<?= 'sidebar' ?>', <?= /* @escapeNotVerified */ $block->getProductId($_item) ?>); return false;"> - <span><?= /* @escapeNotVerified */ __('Configure and Add to Order') ?></span> + onclick="order.sidebarConfigureProduct('sidebar', <?= (int) $block->getProductId($_item) ?>); return false;"> + <span><?= $block->escapeHtml(__('Configure and Add to Order')) ?></span> </a> - <?php else: ?> - <input id="sidebar-<?= /* @escapeNotVerified */ $block->getSidebarStorageAction() ?>-<?= /* @escapeNotVerified */ $block->getIdentifierId($_item) ?>" + <?php else : ?> + <input id="sidebar-<?= $block->escapeHtmlAttr($block->getSidebarStorageAction()) ?>-<?= (int) $block->getIdentifierId($_item) ?>" type="checkbox" class="admin__control-checkbox" - name="sidebar[<?= /* @escapeNotVerified */ $block->getSidebarStorageAction() ?>][<?= /* @escapeNotVerified */ $block->getIdentifierId($_item) ?>]" - value="<?= /* @escapeNotVerified */ $block->canDisplayItemQty() ? $_item->getQty()*1 : 1 ?>" + name="sidebar[<?= $block->escapeHtmlAttr($block->getSidebarStorageAction()) ?>][<?= (int) $block->getIdentifierId($_item) ?>]" + value="<?= $block->canDisplayItemQty() ? (int) $_item->getQty() : 1 ?>" title="<?= $block->escapeHtml(__('Add To Order')) ?>"/> <label class="admin__field-label" - for="sidebar-<?= /* @escapeNotVerified */ $block->getSidebarStorageAction() ?>-<?= /* @escapeNotVerified */ $block->getIdentifierId($_item) ?>"> + for="sidebar-<?= $block->escapeHtmlAttr($block->getSidebarStorageAction()) ?>-<?= (int) $block->getIdentifierId($_item) ?>"> </label> <?php endif; ?> </div> @@ -120,11 +117,11 @@ <?php endforeach; ?> </tbody> </table> - <?php else: ?> - <span class="no-items"><?= /* @escapeNotVerified */ __('No items') ?></span> + <?php else : ?> + <span class="no-items"><?= $block->escapeHtml(__('No items')) ?></span> <?php endif ?> </div> - <?php if ($block->getItemCount() && $block->canRemoveItems()): ?> + <?php if ($block->getItemCount() && $block->canRemoveItems()) : ?> <?= $block->getChildHtml('empty_customer_cart_button') ?> <?php endif; ?> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/store/select.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/store/select.phtml index 1de681bdb2084..407bd0272e9fd 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/store/select.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/store/select.phtml @@ -3,20 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /* @var $block \Magento\Sales\Block\Adminhtml\Order\Create\Store\Select */ ?> <div class="store-scope form-inline"> <div class="admin__fieldset tree-store-scope"> <?php $showHelpHint = 0; ?> - <?php foreach ($block->getWebsiteCollection() as $_website): ?> + <?php foreach ($block->getWebsiteCollection() as $_website) : ?> <?php $showWebsite = false; ?> - <?php foreach ($block->getGroupCollection($_website) as $_group): ?> + <?php foreach ($block->getGroupCollection($_website) as $_group) : ?> <?php $showGroup = false; ?> - <?php foreach ($block->getStoreCollection($_group) as $_store): ?> - <?php if ($showWebsite == false): ?> + <?php foreach ($block->getStoreCollection($_group) as $_store) : ?> + <?php if ($showWebsite == false) : ?> <?php $showWebsite = true; ?> <div class="admin__field field-website_label"> <label class="admin__field-label" for=""> @@ -24,7 +21,7 @@ </label> <div class="admin__field-control"> <div class="admin__field admin__field-option"> - <?php if ($showHelpHint == 0): + <?php if ($showHelpHint == 0) : echo $block->getHintHtml(); $showHelpHint = 1; endif; ?> @@ -33,7 +30,7 @@ </div> <?php endif; ?> - <?php if ($showGroup == false): ?> + <?php if ($showGroup == false) : ?> <?php $showGroup = true; ?> <div class="admin__field field-group_label"> <label class="admin__field-label" for=""><span><?= $block->escapeHtml($_group->getName()) ?></span></label> @@ -46,8 +43,8 @@ <div class="admin__field-control"> <div class="nested"> <div class="admin__field admin__field-option"> - <input type="radio" id="store_<?= /* @escapeNotVerified */ $_store->getId() ?>" class="admin__control-radio" onclick="order.setStoreId('<?= /* @escapeNotVerified */ $_store->getId() ?>')"/> - <label class="admin__field-label" for="store_<?= /* @escapeNotVerified */ $_store->getId() ?>"> + <input type="radio" id="store_<?= (int) $_store->getId() ?>" class="admin__control-radio" onclick="order.setStoreId('<?= (int) $_store->getId() ?>')"/> + <label class="admin__field-label" for="store_<?= (int) $_store->getId() ?>"> <?= $block->escapeHtml($_store->getName()) ?> </label> </div> @@ -55,7 +52,7 @@ </div> </div> <?php endforeach; ?> - <?php if ($showGroup): ?> + <?php if ($showGroup) : ?> <?php endif; ?> <?php endforeach; ?> <?php endforeach; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals.phtml index 02433edf82346..9a901d99ae8f8 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals.phtml @@ -4,31 +4,30 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Totals $block */ ?> -<legend class="admin__legend"><span><?= /* @escapeNotVerified */ __('Order Totals') ?></span></legend> +<legend class="admin__legend"><span><?= $block->escapeHtml(__('Order Totals')) ?></span></legend> <br> <table class="admin__table-secondary data-table"> <tbody> - <?= /* @escapeNotVerified */ $block->renderTotals() ?> - <?= /* @escapeNotVerified */ $block->renderTotals('footer') ?> + <?= /* @noEscape */ $block->renderTotals() ?> + <?= /* @noEscape */ $block->renderTotals('footer') ?> </tbody> </table> <div class="order-totals-actions"> <div class="admin__field admin__field-option field-append-comments"> <input type="checkbox" id="notify_customer" name="order[comment][customer_note_notify]" - value="1"<?php if ($block->getNoteNotify()): ?> checked="checked"<?php endif; ?> + value="1"<?php if ($block->getNoteNotify()) : ?> checked="checked"<?php endif; ?> class="admin__control-checkbox"/> - <label for="notify_customer" class="admin__field-label"><?= /* @escapeNotVerified */ __('Append Comments') ?></label> + <label for="notify_customer" class="admin__field-label"><?= $block->escapeHtml(__('Append Comments')) ?></label> </div> - <?php if ($block->canSendNewOrderConfirmationEmail()): ?> + <?php if ($block->canSendNewOrderConfirmationEmail()) : ?> <div class="admin__field admin__field-option field-email-order-confirmation"> <input type="checkbox" id="send_confirmation" name="order[send_confirmation]" value="1" checked="checked" class="admin__control-checkbox"/> - <label for="send_confirmation" class="admin__field-label"><?= /* @escapeNotVerified */ __('Email Order Confirmation') ?></label> + <label for="send_confirmation" class="admin__field-label"><?= $block->escapeHtml(__('Email Order Confirmation')) ?></label> </div> <?php endif; ?> <div class="actions"> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/default.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/default.phtml index 9ab8a6552539d..4a55eb609924f 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/default.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/default.phtml @@ -3,19 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> -<tr class="<?= /* @escapeNotVerified */ $block->getTotal()->getCode() ?> row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getTotal()->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <?php if ($block->getRenderingArea() == $block->getTotal()->getArea()): ?><strong><?php endif; ?> +<tr class="<?= $block->escapeHtmlAttr($block->getTotal()->getCode()) ?> row-totals"> + <td style="<?= $block->escapeHtmlAttr($block->getTotal()->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <?php if ($block->getRenderingArea() == $block->getTotal()->getArea()) : ?><strong><?php endif; ?> <?= $block->escapeHtml($block->getTotal()->getTitle()) ?> - <?php if ($block->getRenderingArea() == $block->getTotal()->getArea()): ?></strong><?php endif; ?> + <?php if ($block->getRenderingArea() == $block->getTotal()->getArea()) : ?></strong><?php endif; ?> </td> - <td style="<?= /* @escapeNotVerified */ $block->getTotal()->getStyle() ?>" class="admin__total-amount"> - <?php if ($block->getRenderingArea() == $block->getTotal()->getArea()): ?><strong><?php endif; ?> - <?= /* @escapeNotVerified */ $block->formatPrice($block->getTotal()->getValue()) ?> - <?php if ($block->getRenderingArea() == $block->getTotal()->getArea()): ?></strong><?php endif; ?> + <td style="<?= $block->escapeHtmlAttr($block->getTotal()->getStyle()) ?>" class="admin__total-amount"> + <?php if ($block->getRenderingArea() == $block->getTotal()->getArea()) : ?><strong><?php endif; ?> + <?= /* @noEscape */ $block->formatPrice($block->getTotal()->getValue()) ?> + <?php if ($block->getRenderingArea() == $block->getTotal()->getArea()) : ?></strong><?php endif; ?> </td> </tr> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/grandtotal.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/grandtotal.phtml index 7486edd732706..4c4f94b5b3bb1 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/grandtotal.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/grandtotal.phtml @@ -4,38 +4,36 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** * @var $block \Magento\Tax\Block\Checkout\Grandtotal * @see \Magento\Tax\Block\Checkout\Grandtotal */ ?> -<?php if ($block->includeTax() && $block->getTotalExclTax() >= 0):?> -<tr class="row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <strong><?= /* @escapeNotVerified */ __('Grand Total Excl. Tax') ?></strong> - </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <strong><?= /* @escapeNotVerified */ $block->formatPrice($block->getTotalExclTax()) ?></strong> - </td> -</tr> -<?= /* @escapeNotVerified */ $block->renderTotals('taxes', $block->getColspan()) ?> -<tr class="row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <strong><?= /* @escapeNotVerified */ __('Grand Total Incl. Tax') ?></strong> - </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <strong><?= /* @escapeNotVerified */ $block->formatPrice($block->getTotal()->getValue()) ?></strong> - </td> -</tr> -<?php else:?> -<tr class="row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <strong><?= /* @escapeNotVerified */ $block->getTotal()->getTitle() ?></strong> - </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <strong><?= /* @escapeNotVerified */ $block->formatPrice($block->getTotal()->getValue()) ?></strong> - </td> -</tr> +<?php if ($block->includeTax() && $block->getTotalExclTax() >= 0) : ?> + <tr class="row-totals"> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <strong><?= $block->escapeHtml(__('Grand Total Excl. Tax')) ?></strong> + </td> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <strong><?= /* @noEscape */ $block->formatPrice($block->getTotalExclTax()) ?></strong> + </td> + </tr> + <?= /* @noEscape */ $block->renderTotals('taxes', $block->getColspan()) ?> + <tr class="row-totals"> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <strong><?= $block->escapeHtml(__('Grand Total Incl. Tax')) ?></strong> + </td> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <strong><?= /* @noEscape */ $block->formatPrice($block->getTotal()->getValue()) ?></strong> + </td> + </tr> + <?php else : ?> + <tr class="row-totals"> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <strong><?= $block->escapeHtml($block->getTotal()->getTitle()) ?></strong> + </td> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <strong><?= /* @noEscape */ $block->formatPrice($block->getTotal()->getValue()) ?></strong> + </td> + </tr> <?php endif;?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/shipping.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/shipping.phtml index 2235a428e1e75..db204a46f1f94 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/shipping.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/shipping.phtml @@ -4,46 +4,44 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** * @var $block \Magento\Tax\Block\Checkout\Shipping * @see \Magento\Tax\Block\Checkout\Shipping */ ?> -<?php if ($block->displayBoth()):?> +<?php if ($block->displayBoth()) :?> <tr class="row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <?= /* @escapeNotVerified */ $block->getExcludeTaxLabel() ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <?= $block->escapeHtml($block->getExcludeTaxLabel()) ?> </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <?= /* @escapeNotVerified */ $block->formatPrice($block->getShippingExcludeTax()) ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <?= /* @noEscape */ $block->formatPrice($block->getShippingExcludeTax()) ?> </td> </tr> <tr class="row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <?= /* @escapeNotVerified */ $block->getIncludeTaxLabel() ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <?= $block->escapeHtml($block->getIncludeTaxLabel()) ?> </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <?= /* @escapeNotVerified */ $block->formatPrice($block->getShippingIncludeTax()) ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <?= /* @noEscape */ $block->formatPrice($block->getShippingIncludeTax()) ?> </td> </tr> <?php elseif ($block->displayIncludeTax()) : ?> <tr> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <?= /* @escapeNotVerified */ $block->getTotal()->getTitle() ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <?= $block->escapeHtml($block->getTotal()->getTitle()) ?> </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <?= /* @escapeNotVerified */ $block->formatPrice($block->getShippingIncludeTax()) ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <?= /* @noEscape */ $block->formatPrice($block->getShippingIncludeTax()) ?> </td> </tr> -<?php else:?> +<?php else : ?> <tr class="row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> <?= $block->escapeHtml($block->getTotal()->getTitle()) ?> </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <?= /* @escapeNotVerified */ $block->formatPrice($block->getShippingExcludeTax()) ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <?= /* @noEscape */ $block->formatPrice($block->getShippingExcludeTax()) ?> </td> </tr> <?php endif;?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/subtotal.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/subtotal.phtml index 380a7dc6fcbf9..a63458491baea 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/subtotal.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/subtotal.phtml @@ -4,37 +4,35 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** * @var $block \Magento\Sales\Block\Adminhtml\Order\Create\Totals\Subtotal * @see \Magento\Sales\Block\Adminhtml\Order\Create\Totals\Subtotal */ ?> -<?php if ($block->displayBoth()):?> +<?php if ($block->displayBoth()) : ?> <tr class="row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <?= /* @escapeNotVerified */ __('Subtotal (Excl. Tax)') ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <?= $block->escapeHtml(__('Subtotal (Excl. Tax)')) ?> </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <?= /* @escapeNotVerified */ $block->formatPrice($block->getTotal()->getValueExclTax()) ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <?= /* @noEscape */ $block->formatPrice($block->getTotal()->getValueExclTax()) ?> </td> </tr> <tr class="row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <?= /* @escapeNotVerified */ __('Subtotal (Incl. Tax)') ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <?= $block->escapeHtml(__('Subtotal (Incl. Tax)')) ?> </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <?= /* @escapeNotVerified */ $block->formatPrice($block->getTotal()->getValueInclTax()) ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <?= /* @noEscape */ $block->formatPrice($block->getTotal()->getValueInclTax()) ?> </td> </tr> <?php else : ?> <tr class="row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <?= /* @escapeNotVerified */ $block->getTotal()->getTitle() ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <?= $block->escapeHtml($block->getTotal()->getTitle()) ?> </td> - <td style="<?= /* @escapeNotVerified */ $block->getStyle() ?>" class="admin__total-amount"> - <?= /* @escapeNotVerified */ $block->formatPrice($block->getTotal()->getValue()) ?> + <td style="<?= $block->escapeHtmlAttr($block->getStyle()) ?>" class="admin__total-amount"> + <?= /* @noEscape */ $block->formatPrice($block->getTotal()->getValue()) ?> </td> </tr> <?php endif;?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/tax.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/tax.phtml index 643146f7bb5cb..042b2f5113cac 100755 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/tax.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/totals/tax.phtml @@ -4,52 +4,59 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate +// phpcs:disable Squiz.PHP.GlobalKeyword.NotAllowed + +/** @var \Magento\Sales\Block\Adminhtml\Order\Create\Totals\Tax $block */ $taxAmount = $block->getTotal()->getValue(); ?> -<?php if (($taxAmount == 0 && $this->helper('Magento\Tax\Helper\Data')->displayZeroTax()) || ($taxAmount > 0)): ?> -<?php global $taxIter; $taxIter++; ?> -<?php $class = "{$block->getTotal()->getCode()} " . ($this->helper('Magento\Tax\Helper\Data')->displayFullSummary() ? 'summary-total' : ''); ?> -<tr<?php if ($this->helper('Magento\Tax\Helper\Data')->displayFullSummary()): ?> - onclick="expandDetails(this, '.summary-details-<?= /* @escapeNotVerified */ $taxIter ?>')" -<?php endif; ?> - class="<?= /* @escapeNotVerified */ $class ?> row-totals"> - <td style="<?= /* @escapeNotVerified */ $block->getTotal()->getStyle() ?>" class="admin__total-mark" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayFullSummary()): ?> - <div class="summary-collapse"><?= /* @escapeNotVerified */ $block->getTotal()->getTitle() ?></div> - <?php else: ?> - <?= /* @escapeNotVerified */ $block->getTotal()->getTitle() ?> - <?php endif;?> - </td> - <td style="<?= /* @escapeNotVerified */ $block->getTotal()->getStyle() ?>" class="admin__total-amount"><?= /* @escapeNotVerified */ $block->formatPrice($block->getTotal()->getValue()) ?></td> -</tr> -<?php if ($this->helper('Magento\Tax\Helper\Data')->displayFullSummary()): ?> +<?php if (($taxAmount == 0 && $this->helper(\Magento\Tax\Helper\Data::class)->displayZeroTax()) || ($taxAmount > 0)) : + global $taxIter; + $taxIter++; + ?> + <?php $class = $block->escapeHtmlAttr("{$block->getTotal()->getCode()} " . ($this->helper(\Magento\Tax\Helper\Data::class)->displayFullSummary() ? 'summary-total' : '')); ?> + <tr<?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayFullSummary()) : ?> + onclick="expandDetails(this, '.summary-details-<?= $block->escapeJs($taxIter) ?>')" + <?php endif; ?> + class="<?= /* @noEscape */ $class ?> row-totals"> + <td style="<?= $block->escapeHtmlAttr($block->getTotal()->getStyle()) ?>" class="admin__total-mark" colspan="<?= (int) $block->getColspan() ?>"> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayFullSummary()) : ?> + <div class="summary-collapse"><?= $block->escapeHtml($block->getTotal()->getTitle()) ?></div> + <?php else : ?> + <?= $block->escapeHtml($block->getTotal()->getTitle()) ?> + <?php endif;?> + </td> + <td style="<?= $block->escapeHtmlAttr($block->getTotal()->getStyle()) ?>" class="admin__total-amount"> + <?= /* @noEscape */ $block->formatPrice($block->getTotal()->getValue()) ?> + </td> + </tr> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayFullSummary()) : ?> <?php $isTop = 1; ?> - <?php foreach ($block->getTotal()->getFullInfo() as $info): ?> - <?php if (isset($info['hidden']) && $info['hidden']) { - continue; - } ?> - <?php $percent = $info['percent']; ?> - <?php $amount = $info['amount']; ?> - <?php $rates = $info['rates']; ?> + <?php foreach ($block->getTotal()->getFullInfo() as $info) : ?> + <?php if (isset($info['hidden']) && $info['hidden']) : + continue; + endif; ?> + <?php $percent = $info['percent']; ?> + <?php $amount = $info['amount']; ?> + <?php $rates = $info['rates']; ?> - <?php foreach ($rates as $rate): ?> - <tr class="summary-details-<?= /* @escapeNotVerified */ $taxIter ?> summary-details<?php if ($isTop): echo ' summary-details-first'; endif; ?>" style="display:none;"> - <td class="admin__total-mark" style="<?= /* @escapeNotVerified */ $block->getTotal()->getStyle() ?>" colspan="<?= /* @escapeNotVerified */ $block->getColspan() ?>"> + <?php foreach ($rates as $rate) : ?> + <tr class="summary-details-<?= $block->escapeHtmlAttr($taxIter) ?> summary-details<?= ($isTop ? ' summary-details-first' : '') ?>" style="display:none;"> + <td class="admin__total-mark" style="<?= $block->escapeHtmlAttr($block->getTotal()->getStyle()) ?>" colspan="<?= (int) $block->getColspan() ?>"> <?= $block->escapeHtml($rate['title']) ?> - <?php if (!is_null($rate['percent'])): ?> - (<?= (float)$rate['percent'] ?>%) + <?php if ($rate['percent'] !== null) : ?> + (<?= (float) $rate['percent'] ?>%) <?php endif; ?> <br /> </td> - <td style="<?= /* @escapeNotVerified */ $block->getTotal()->getStyle() ?>" class="admin__total-amount"> - <?= /* @escapeNotVerified */ $block->formatPrice(($amount*(float)$rate['percent'])/$percent) ?> + <td style="<?= $block->escapeHtmlAttr($block->getTotal()->getStyle()) ?>" class="admin__total-amount"> + <?= /* @noEscape */ $block->formatPrice(($amount*(float)$rate['percent'])/$percent) ?> </td> </tr> <?php $isTop = 0; ?> - <?php endforeach; ?> + <?php endforeach; ?> <?php endforeach; ?> -<?php endif;?> + <?php endif;?> <?php endif;?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/form.phtml index 2f32483e11a50..050098078b3f3 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/form.phtml @@ -4,10 +4,11 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate +/* @var \Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create\Form $block */ ?> -<form id="edit_form" method="post" action="<?= /* @escapeNotVerified */ $block->getSaveUrl() ?>"> +<form id="edit_form" method="post" action="<?= $block->escapeUrl($block->getSaveUrl()) ?>"> <?= $block->getBlockHtml('formkey') ?> <?php $_order = $block->getCreditmemo()->getOrder() ?> @@ -15,23 +16,23 @@ <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment & Shipping Method') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment & Shipping Method')) ?></span> </div> <div class="admin__page-section-content"> - <?php if (!$_order->getIsVirtual()): ?> + <?php if (!$_order->getIsVirtual()) : ?> <div class="admin__page-section-item order-payment-method"> - <?php else: ?> + <?php else : ?> <div class="admin__page-section-item order-payment-method order-payment-method-virtual"> <?php endif; ?> <?php /* Billing Address */ ?> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment Information') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment Information')) ?></span> </div> <div class="admin__page-section-item-content"> <div class="order-payment-method-title"><?= $block->getChildHtml('order_payment') ?></div> <div class="order-payment-currency"> - <?= /* @escapeNotVerified */ __('The order was placed using %1.', $_order->getOrderCurrencyCode()) ?> + <?= $block->escapeHtml(__('The order was placed using %1.', $_order->getOrderCurrencyCode())) ?> </div> <div class="order-payment-additional"> <?= $block->getChildHtml('order_payment_additional') ?> @@ -39,27 +40,27 @@ </div> </div> - <?php if (!$_order->getIsVirtual()): ?> + <?php if (!$_order->getIsVirtual()) : ?> <div class="admin__page-section-item order-shipping-address"> <?php /* Shipping Address */ ?> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Shipping Information') ?></span> + <span class="title"><?= $block->escapeHtml(__('Shipping Information')) ?></span> </div> <div class="admin__page-section-item-content shipping-description-wrapper"> <div class="shipping-description-title"><?= $block->escapeHtml($_order->getShippingDescription()) ?></div> <div class="shipping-description-content"> - <?= /* @escapeNotVerified */ __('Total Shipping Charges') ?>: + <?= $block->escapeHtml(__('Total Shipping Charges')) ?>: - <?php if ($this->helper('Magento\Tax\Helper\Data')->displaySalesPriceInclTax($block->getSource()->getStoreId())): ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displaySalesPriceInclTax($block->getSource()->getStoreId())) : ?> <?php $_excl = $block->displayShippingPriceInclTax($_order); ?> - <?php else: ?> + <?php else : ?> <?php $_excl = $block->displayPriceAttribute('shipping_amount', false, ' '); ?> <?php endif; ?> <?php $_incl = $block->displayShippingPriceInclTax($_order); ?> - <?= /* @escapeNotVerified */ $_excl ?> - <?php if ($this->helper('Magento\Tax\Helper\Data')->displaySalesBothPrices($block->getSource()->getStoreId()) && $_incl != $_excl): ?> - (<?= /* @escapeNotVerified */ __('Incl. Tax') ?> <?= /* @escapeNotVerified */ $_incl ?>) + <?= /* @noEscape */ $_excl ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displaySalesBothPrices($block->getSource()->getStoreId()) && $_incl != $_excl) : ?> + (<?= $block->escapeHtml(__('Incl. Tax')) ?> <?= /* @noEscape */ $_incl ?>) <?php endif; ?> </div> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items.phtml index b0b52b199978a..893634635f32b 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items.phtml @@ -4,17 +4,13 @@ * See COPYING.txt for license details. */ -/** - * @var Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create\Items $block - */ -// @codingStandardsIgnoreFile - +/* @var \Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create\Items $block */ ?> <?php $_items = $block->getCreditmemo()->getAllItems() ?> <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Items to Refund') ?></span> + <span class="title"><?= $block->escapeHtml(__('Items to Refund')) ?></span> </div> <?php if (count($_items)) : ?> @@ -22,20 +18,20 @@ <table class="data-table admin__table-primary order-creditmemo-tables"> <thead> <tr class="headings"> - <th class="col-product"><span><?= /* @escapeNotVerified */ __('Product') ?></span></th> - <th class="col-price"><span><?= /* @escapeNotVerified */ __('Price') ?></span></th> - <th class="col-ordered-qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></th> + <th class="col-product"><span><?= $block->escapeHtml(__('Product')) ?></span></th> + <th class="col-price"><span><?= $block->escapeHtml(__('Price')) ?></span></th> + <th class="col-ordered-qty"><span><?= $block->escapeHtml(__('Qty')) ?></span></th> <?php if ($block->canReturnToStock()) : ?> - <th class="col-return-to-stock"><span><?= /* @escapeNotVerified */ __('Return to Stock') ?></span></th> + <th class="col-return-to-stock"><span><?= $block->escapeHtml(__('Return to Stock')) ?></span></th> <?php endif; ?> - <th class="col-refund"><span><?= /* @escapeNotVerified */ __('Qty to Refund') ?></span></th> - <th class="col-subtotal"><span><?= /* @escapeNotVerified */ __('Subtotal') ?></span></th> - <th class="col-tax-amount"><span><?= /* @escapeNotVerified */ __('Tax Amount') ?></span></th> - <th class="col-discont"><span><?= /* @escapeNotVerified */ __('Discount Amount') ?></span></th> - <th class="col-total last"><span><?= /* @escapeNotVerified */ __('Row Total') ?></span></th> + <th class="col-refund"><span><?= $block->escapeHtml(__('Qty to Refund')) ?></span></th> + <th class="col-subtotal"><span><?= $block->escapeHtml(__('Subtotal')) ?></span></th> + <th class="col-tax-amount"><span><?= $block->escapeHtml(__('Tax Amount')) ?></span></th> + <th class="col-discont"><span><?= $block->escapeHtml(__('Discount Amount')) ?></span></th> + <th class="col-total last"><span><?= $block->escapeHtml(__('Row Total')) ?></span></th> </tr> </thead> - <?php if ($block->canEditQty()): ?> + <?php if ($block->canEditQty()) : ?> <tfoot> <tr> <td colspan="3"> </td> @@ -46,13 +42,13 @@ </tr> </tfoot> <?php endif; ?> - <?php $i = 0; foreach ($_items as $_item): ?> - <?php if ($_item->getOrderItem()->getParentItem()) { - continue; - } else { - $i++; - } ?> - <tbody class="<?= /* @escapeNotVerified */ $i%2 ? 'even' : 'odd' ?>"> + <?php $i = 0; foreach ($_items as $_item) : ?> + <?php if ($_item->getOrderItem()->getParentItem()) : + continue; + else : + $i++; + endif; ?> + <tbody class="<?= /* @noEscape */ $i%2 ? 'even' : 'odd' ?>"> <?= $block->getItemHtml($_item) ?> <?= $block->getItemExtraInfoHtml($_item->getOrderItem()) ?> </tbody> @@ -61,47 +57,47 @@ </div> <?php else : ?> <div class="no-items"> - <?= /* @escapeNotVerified */ __('No Items To Refund') ?> + <?= $block->escapeHtml(__('No Items To Refund')) ?> </div> <?php endif; ?> </section> <?php $orderTotalBar = $block->getChildHtml('order_totalbar'); ?> -<?php if (!empty($orderTotalBar)): ?> +<?php if (!empty($orderTotalBar)) : ?> <section class="fieldset-wrapper"> - <?= /* @escapeNotVerified */ $orderTotalBar ?> + <?= /* @noEscape */ $orderTotalBar ?> </section> <?php endif; ?> <section class="admin__page-section"> <input type="hidden" name="creditmemo[do_offline]" id="creditmemo_do_offline" value="0" /> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Order Total') ?></span> + <span class="title"><?= $block->escapeHtml(__('Order Total')) ?></span> </div> <div class="admin__page-section-content"> <div class="admin__page-section-item order-comments-history"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Credit Memo Comments') ?></span> + <span class="title"><?= $block->escapeHtml(__('Credit Memo Comments')) ?></span> </div> <div id="history_form" class="admin__fieldset-wrapper-content"> <div class="admin__field"> <label class="normal admin__field-label" for="creditmemo_comment_text"> - <span><?= /* @escapeNotVerified */ __('Comment Text') ?></span></label> + <span><?= $block->escapeHtml(__('Comment Text')) ?></span></label> <div class="admin__field-control"> <textarea id="creditmemo_comment_text" class="admin__control-textarea" name="creditmemo[comment_text]" rows="3" - cols="5"><?= /* @escapeNotVerified */ $block->getCreditmemo()->getCommentText() ?></textarea> + cols="5"><?= $block->escapeHtml($block->getCreditmemo()->getCommentText()) ?></textarea> </div> </div> </div> </div> <div class="admin__page-section-item order-totals creditmemo-totals"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Refund Totals') ?></span> + <span class="title"><?= $block->escapeHtml(__('Refund Totals')) ?></span> </div> <?= $block->getChildHtml('creditmemo_totals') ?> <div class="totals-actions"><?= $block->getUpdateTotalsButtonHtml() ?></div> @@ -113,10 +109,10 @@ value="1" type="checkbox" /> <label for="notify_customer" class="admin__field-label"> - <span><?= /* @escapeNotVerified */ __('Append Comments') ?></span> + <span><?= $block->escapeHtml(__('Append Comments')) ?></span> </label> </div> - <?php if ($block->canSendCreditmemoEmail()):?> + <?php if ($block->canSendCreditmemoEmail()) :?> <div class="field choice admin__field admin__field-option field-email-copy"> <input id="send_email" class="admin__control-checkbox" @@ -124,7 +120,7 @@ value="1" type="checkbox" /> <label for="send_email" class="admin__field-label"> - <span><?= /* @escapeNotVerified */ __('Email Copy of Credit Memo') ?></span> + <span><?= $block->escapeHtml(__('Email Copy of Credit Memo')) ?></span> </label> </div> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items/renderer/default.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items/renderer/default.phtml index b27a07c4bf824..65c28578b68b3 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items/renderer/default.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var $block \Magento\Sales\Block\Adminhtml\Items\Renderer\DefaultRenderer */ ?> <?php $_item = $block->getItem() ?> @@ -21,8 +18,8 @@ <?php if ($block->canReturnItemToStock($_item)) : ?> <input type="checkbox" class="admin__control-checkbox" - name="creditmemo[items][<?= /* @escapeNotVerified */ $_item->getOrderItemId() ?>][back_to_stock]" - value="1"<?php if ($_item->getBackToStock()):?> checked<?php endif;?>/> + name="creditmemo[items][<?= (int) $_item->getOrderItemId() ?>][back_to_stock]" + value="1"<?php if ($_item->getBackToStock()) : ?> checked<?php endif; ?>/> <label class="admin__field-label"></label> <?php endif; ?> </td> @@ -31,17 +28,17 @@ <?php if ($block->canEditQty()) : ?> <input type="text" class="input-text admin__control-text qty-input" - name="creditmemo[items][<?= /* @escapeNotVerified */ $_item->getOrderItemId() ?>][qty]" - value="<?= /* @escapeNotVerified */ $_item->getQty()*1 ?>"/> + name="creditmemo[items][<?= (int) $_item->getOrderItemId() ?>][qty]" + value="<?= (int) $_item->getQty() ?>"/> <?php else : ?> - <?= /* @escapeNotVerified */ $_item->getQty()*1 ?> + <?= (int) $_item->getQty() ?> <?php endif; ?> </td> <td class="col-subtotal"> <?= $block->getColumnHtml($_item, 'subtotal') ?> </td> - <td class="col-tax-amount"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('tax_amount') ?></td> - <td class="col-discont"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('discount_amount') ?></td> + <td class="col-tax-amount"><?= /* @noEscape */ $block->displayPriceAttribute('tax_amount') ?></td> + <td class="col-discont"><?= /* @noEscape */ $block->displayPriceAttribute('discount_amount') ?></td> <td class="col-total last"> <?= $block->getColumnHtml($_item, 'total') ?> </td> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml index 0b2a3ef24ae32..187cb96f32aa0 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml @@ -4,40 +4,36 @@ * See COPYING.txt for license details. */ -/** - * @var \Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create\Adjustments $block - * @codingStandardsIgnoreFile - */ - +/* @var \Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create\Adjustments $block */ ?> <?php $_source = $block->getSource() ?> -<?php if ($_source): ?> +<?php if ($_source) : ?> <tr> - <td class="label"><?= /* @escapeNotVerified */ $block->getShippingLabel() ?><div id="shipping_amount_adv"></div></td> + <td class="label"><?= $block->escapeHtml($block->getShippingLabel()) ?><div id="shipping_amount_adv"></div></td> <td> <input type="text" name="creditmemo[shipping_amount]" - value="<?= /* @escapeNotVerified */ $block->getShippingAmount() ?>" + value="<?= $block->escapeHtmlAttr($block->getShippingAmount()) ?>" class="input-text admin__control-text not-negative-amount" id="shipping_amount" /> </td> </tr> <tr> - <td class="label"><?= /* @escapeNotVerified */ __('Adjustment Refund') ?><div id="adjustment_positive_adv"></div></td> + <td class="label"><?= $block->escapeHtml(__('Adjustment Refund')) ?><div id="adjustment_positive_adv"></div></td> <td> <input type="text" name="creditmemo[adjustment_positive]" - value="<?= /* @escapeNotVerified */ $_source->getBaseAdjustmentPositive()*1 ?>" + value="<?= $block->escapeHtmlAttr($_source->getBaseAdjustmentPositive()) ?>" class="input-text admin__control-text not-negative-amount" id="adjustment_positive" /> </td> </tr> <tr> - <td class="label"><?= /* @escapeNotVerified */ __('Adjustment Fee') ?><div id="adjustment_negative_adv"></div></td> + <td class="label"><?= $block->escapeHtml(__('Adjustment Fee')) ?><div id="adjustment_negative_adv"></div></td> <td> <input type="text" name="creditmemo[adjustment_negative]" - value="<?= /* @escapeNotVerified */ $_source->getBaseAdjustmentNegative()*1 ?>" + value="<?= $block->escapeHtmlAttr($_source->getBaseAdjustmentNegative()) ?>" class="input-text admin__control-text not-negative-amount" id="adjustment_negative"/> <script> @@ -45,7 +41,7 @@ //<![CDATA[ Validation.addAllThese([ - ['not-negative-amount', '<?= /* @escapeNotVerified */ __('Please enter a positive number in this field.') ?>', function(v) { + ['not-negative-amount', '<?= $block->escapeJs(__('Please enter a positive number in this field.')) ?>', function(v) { if(v.length) return /^\s*\d+([,.]\d+)*\s*%?\s*$/.test(v); else diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/form.phtml index 7f5c54a3236e0..7e3dc7ea0be0e 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/form.phtml @@ -4,54 +4,55 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate +/* @var \Magento\Sales\Block\Adminhtml\Order\Creditmemo\View\Form $block */ ?> <?php $_order = $block->getCreditmemo()->getOrder() ?> <?= $block->getChildHtml('order_info') ?> <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment & Shipping Method') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment & Shipping Method')) ?></span> </div> <div class="admin__page-section-content"> - <?php if (!$_order->getIsVirtual()): ?> + <?php if (!$_order->getIsVirtual()) : ?> <div class="admin__page-section-item order-payment-method"> - <?php else: ?> + <?php else : ?> <div class="admin__page-section-item order-payment-method order-payment-method-virtual"> <?php endif; ?> <?php /* Billing Address */?> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment Information') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment Information')) ?></span> </div> <div class="admin__page-section-item-content"> <div class="order-payment-method-title"><?= $block->getChildHtml('order_payment') ?></div> - <div class="order-payment-currency"><?= /* @escapeNotVerified */ __('The order was placed using %1.', $_order->getOrderCurrencyCode()) ?></div> + <div class="order-payment-currency"><?= $block->escapeHtml(__('The order was placed using %1.', $_order->getOrderCurrencyCode())) ?></div> <div class="order-payment-additional"><?= $block->getChildHtml('order_payment_additional') ?></div> </div> </div> - <?php if (!$_order->getIsVirtual()): ?> + <?php if (!$_order->getIsVirtual()) : ?> <div class="admin__page-section-item order-shipping-address"> <?php /* Shipping Address */ ?> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Shipping Information') ?></span> + <span class="title"><?= $block->escapeHtml(__('Shipping Information')) ?></span> </div> <div class="shipping-description-wrapper admin__page-section-item-content"> <div class="shipping-description-title"><?= $block->escapeHtml($_order->getShippingDescription()) ?></div> <div class="shipping-description-content"> - <?= /* @escapeNotVerified */ __('Total Shipping Charges') ?>: + <?= $block->escapeHtml(__('Total Shipping Charges')) ?>: - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayShippingPriceIncludingTax()): ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayShippingPriceIncludingTax()) : ?> <?php $_excl = $block->displayShippingPriceInclTax($_order); ?> - <?php else: ?> + <?php else : ?> <?php $_excl = $block->displayPriceAttribute('shipping_amount', false, ' '); ?> <?php endif; ?> <?php $_incl = $block->displayShippingPriceInclTax($_order); ?> - <?= /* @escapeNotVerified */ $_excl ?> - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayShippingBothPrices() && $_incl != $_excl): ?> - (<?= /* @escapeNotVerified */ __('Incl. Tax') ?> <?= /* @escapeNotVerified */ $_incl ?>) + <?= /* @noEscape */ $_excl ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayShippingBothPrices() && $_incl != $_excl) : ?> + (<?= $block->escapeHtml(__('Incl. Tax')) ?> <?= /* @noEscape */ $_incl ?>) <?php endif; ?> </div> </div> @@ -61,33 +62,33 @@ </section> <?php $_items = $block->getCreditmemo()->getAllItems() ?> -<?php if (count($_items)): ?> +<?php if (count($_items)) : ?> <div id="creditmemo_items_container"> <?= $block->getChildHtml('creditmemo_items') ?> </div> -<?php else: ?> +<?php else : ?> <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Items Refunded') ?></span> + <span class="title"><?= $block->escapeHtml(__('Items Refunded')) ?></span> </div> - <div class="no-items admin__page-section-content"><?= /* @escapeNotVerified */ __('No Items') ?></div> + <div class="no-items admin__page-section-content"><?= $block->escapeHtml(__('No Items')) ?></div> </section> <?php endif; ?> <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Memo Total') ?></span> + <span class="title"><?= $block->escapeHtml(__('Memo Total')) ?></span> </div> <div class="admin__page-section-content"> <div class="admin__page-section-item order-comments-history"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Credit Memo History') ?></span> + <span class="title"><?= $block->escapeHtml(__('Credit Memo History')) ?></span> </div> <div class="admin__page-section-item-content"><?= $block->getChildHtml('order_comments') ?></div> </div> <div class="admin__page-section-item order-totals" id="history_form"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Credit Memo Totals') ?></span> + <span class="title"><?= $block->escapeHtml(__('Credit Memo Totals')) ?></span> </div> <div class="admin__page-section-content"><?= $block->getChildHtml('creditmemo_totals') ?></div> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/items.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/items.phtml index d77f2fbde22e4..1471197982898 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/items.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/items.phtml @@ -4,35 +4,34 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/* @var \Magento\Sales\Block\Adminhtml\Order\Creditmemo\View\Items $block */ ?> <?php $_items = $block->getCreditmemo()->getAllItems() ?> <div class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Items Refunded') ?></span> + <span class="title"><?= $block->escapeHtml(__('Items Refunded')) ?></span> </div> <div class="admin__page-section-content"> <div class="admin__table-wrapper"> <table class="data-table admin__table-primary order-creditmemo-tables"> <thead> <tr class="headings"> - <th class="col-product"><span><?= /* @escapeNotVerified */ __('Product') ?></span></th> - <th class="col-price"><span><?= /* @escapeNotVerified */ __('Price') ?></span></th> - <th class="col-qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></th> - <th class="col-subtotal"><span><?= /* @escapeNotVerified */ __('Subtotal') ?></span></th> - <th class="col-tax"><span><?= /* @escapeNotVerified */ __('Tax Amount') ?></span></th> - <th class="col-discount"><span><?= /* @escapeNotVerified */ __('Discount Amount') ?></span></th> - <th class="col-total last"><span><?= /* @escapeNotVerified */ __('Row Total') ?></span></th> + <th class="col-product"><span><?= $block->escapeHtml(__('Product')) ?></span></th> + <th class="col-price"><span><?= $block->escapeHtml(__('Price')) ?></span></th> + <th class="col-qty"><span><?= $block->escapeHtml(__('Qty')) ?></span></th> + <th class="col-subtotal"><span><?= $block->escapeHtml(__('Subtotal')) ?></span></th> + <th class="col-tax"><span><?= $block->escapeHtml(__('Tax Amount')) ?></span></th> + <th class="col-discount"><span><?= $block->escapeHtml(__('Discount Amount')) ?></span></th> + <th class="col-total last"><span><?= $block->escapeHtml(__('Row Total')) ?></span></th> </tr> </thead> - <?php $i = 0; foreach ($_items as $_item): ?> - <?php if ($_item->getOrderItem()->getParentItem()) { + <?php $i = 0; foreach ($_items as $_item) : ?> + <?php if ($_item->getOrderItem()->getParentItem()) : continue; - } else { + else : $i++; - } ?> - <tbody class="<?= /* @escapeNotVerified */ $i%2 ? 'even' : 'odd' ?>"> + endif; ?> + <tbody class="<?= /* @noEscape */ $i%2 ? 'even' : 'odd' ?>"> <?= $block->getItemHtml($_item) ?> <?= $block->getItemExtraInfoHtml($_item->getOrderItem()) ?> </tbody> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/items/renderer/default.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/items/renderer/default.phtml index d39d41fe9c392..80ad5302392ae 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/view/items/renderer/default.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var $block \Magento\Sales\Block\Adminhtml\Items\Renderer\DefaultRenderer */ ?> <?php $_item = $block->getItem() ?> @@ -16,12 +13,12 @@ <td class="col-price"> <?= $block->getColumnHtml($_item, 'price') ?> </td> - <td class="col-qty"><?= /* @escapeNotVerified */ $_item->getQty()*1 ?></td> + <td class="col-qty"><?= (int) $_item->getQty() ?></td> <td class="col-subtotal"> <?= $block->getColumnHtml($_item, 'subtotal') ?> </td> - <td class="col-tax"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('tax_amount') ?></td> - <td class="col-discount"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('discount_amount') ?></td> + <td class="col-tax"><?= /* @noEscape */ $block->displayPriceAttribute('tax_amount') ?></td> + <td class="col-discount"><?= /* @noEscape */ $block->displayPriceAttribute('discount_amount') ?></td> <td class="col-total last"> <?= $block->getColumnHtml($_item, 'total') ?> </td> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/details.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/details.phtml index 2372087de5d79..961baf5499652 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/details.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/details.phtml @@ -4,18 +4,22 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate /* store view name = $_order->getStore()->getName() web site name = $_order->getStore()->getWebsite()->getName() store name = $_order->getStore()->getGroup()->getName() */ + +/* @var \Magento\Sales\Block\Adminhtml\Order\Details $block */ ?> -<?php $_order = $block->getOrder() ?> +<?php +/* @var \Magento\Sales\Model\Order $_order */ +$_order = $block->getOrder() ?> <div> -<?= __('Customer Name: %1', $block->escapeHtml($_order->getCustomerFirstname() ? $_order->getCustomerName() : $_order->getBillingAddress()->getName())) ?><br /> -<?= __('Purchased From: %1', $block->escapeHtml($_order->getStore()->getGroup()->getName())) ?><br /> +<?= $block->escapeHtml(__('Customer Name: %1', $_order->getCustomerFirstname() ? $_order->getCustomerName() : $_order->getBillingAddress()->getName())) ?><br /> +<?= $block->escapeHtml(__('Purchased From: %1', $_order->getStore()->getGroup()->getName())) ?><br /> </div> <table cellpadding="0" border="0" width="100%" style="border:1px solid #bebcb7; background:#f8f7f5;"> <thead> @@ -27,58 +31,58 @@ store name = $_order->getStore()->getGroup()->getName() </thead> <tbody> -<?php $i = 0; foreach ($_order->getAllItems() as $_item): $i++ ?> +<?php $i = 0; foreach ($_order->getAllItems() as $_item) : $i++ ?> <tr <?= $i%2 ? 'bgcolor="#eeeded"' : '' ?>> <td align="left" valign="top" style="padding:3px 9px"><strong><?= $block->escapeHtml($_item->getName()) ?></strong> - <?php if ($_item->getGiftMessageId() && $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_item->getGiftMessageId())): ?> - <br /><strong><?= /* @escapeNotVerified */ __('Gift Message') ?></strong> - <br /><?= /* @escapeNotVerified */ __('From:') ?> <?= $block->escapeHtml($_giftMessage->getSender()) ?> - <br /><?= /* @escapeNotVerified */ __('To:') ?> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?> - <br /><?= /* @escapeNotVerified */ __('Message:') ?><br /> <?= $block->escapeHtml($_giftMessage->getMessage()) ?> + <?php if ($_item->getGiftMessageId() && $_giftMessage = $this->helper(\Magento\GiftMessage\Helper\Message::class)->getGiftMessage($_item->getGiftMessageId())) : ?> + <br /><strong><?= $block->escapeHtml(__('Gift Message')) ?></strong> + <br /><?= $block->escapeHtml(__('From:')) ?> <?= $block->escapeHtml($_giftMessage->getSender()) ?> + <br /><?= $block->escapeHtml(__('To:')) ?> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?> + <br /><?= $block->escapeHtml(__('Message:')) ?><br /> <?= $block->escapeHtml($_giftMessage->getMessage()) ?> <?php endif; ?> </td> - <td align="center" valign="top" style="padding:3px 9px"><?= /* @escapeNotVerified */ $_item->getQtyOrdered()*1 ?></td> - <td align="right" valign="top" style="padding:3px 9px"><?= /* @escapeNotVerified */ $_order->formatPrice($_item->getRowTotal()) ?></td> + <td align="center" valign="top" style="padding:3px 9px"><?= (int) $_item->getQtyOrdered() ?></td> + <td align="right" valign="top" style="padding:3px 9px"><?= /* @noEscape */ $_order->formatPrice($_item->getRowTotal()) ?></td> </tr> -<?php endforeach ?> +<?php endforeach; ?> </tbody> <tfoot> - <?php if ($_order->getGiftMessageId() && $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_order->getGiftMessageId())): ?> + <?php if ($_order->getGiftMessageId() && $_giftMessage = $this->helper(\Magento\GiftMessage\Helper\Message::class)->getGiftMessage($_order->getGiftMessageId())) : ?> <tr> <td colspan="3" align="left" style="padding:3px 9px"> - <strong><?= /* @escapeNotVerified */ __('Gift Message') ?></strong> - <br /><?= /* @escapeNotVerified */ __('From:') ?> <?= $block->escapeHtml($_giftMessage->getSender()) ?> - <br /><?= /* @escapeNotVerified */ __('To:') ?> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?> - <br /><?= /* @escapeNotVerified */ __('Message:') ?><br /> <?= $block->escapeHtml($_giftMessage->getMessage()) ?> + <strong><?= $block->escapeHtml(__('Gift Message')) ?></strong> + <br /><?= $block->escapeHtml(__('From:')) ?> <?= $block->escapeHtml($_giftMessage->getSender()) ?> + <br /><?= $block->escapeHtml(__('To:')) ?> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?> + <br /><?= $block->escapeHtml(__('Message:')) ?><br /> <?= $block->escapeHtml($_giftMessage->getMessage()) ?> </td> </tr> - <?php endif; ?> + <?php endif; ?> <tr> - <td colspan="2" align="right" style="padding:3px 9px"><?= /* @escapeNotVerified */ __('Subtotal') ?></td> - <td align="right" style="padding:3px 9px"><?= /* @escapeNotVerified */ $_order->formatPrice($_order->getSubtotal()) ?></td> + <td colspan="2" align="right" style="padding:3px 9px"><?= $block->escapeHtml(__('Subtotal')) ?></td> + <td align="right" style="padding:3px 9px"><?= /* @noEscape */ $_order->formatPrice($_order->getSubtotal()) ?></td> </tr> - <?php if ($_order->getDiscountAmount() > 0): ?> + <?php if ($_order->getDiscountAmount() > 0) : ?> <tr> - <td colspan="2" align="right" style="padding:3px 9px"><?= /* @escapeNotVerified */ (($_order->getCouponCode()) ? __('Discount (%1)', $_order->getCouponCode()) : __('Discount')) ?></td> - <td align="right" style="padding:3px 9px"><?= /* @escapeNotVerified */ $_order->formatPrice(0.00 - $_order->getDiscountAmount()) ?></td> + <td colspan="2" align="right" style="padding:3px 9px"><?= $block->escapeHtml((($_order->getCouponCode()) ? __('Discount (%1)', $_order->getCouponCode()) : __('Discount'))) ?></td> + <td align="right" style="padding:3px 9px"><?= /* @noEscape */ $_order->formatPrice(0.00 - $_order->getDiscountAmount()) ?></td> </tr> <?php endif; ?> <?php if ($_order->getShippingAmount() || $_order->getShippingDescription()) : ?> <tr> - <td colspan="2" align="right" style="padding:3px 9px"><?= /* @escapeNotVerified */ __('Shipping & Handling') ?></td> - <td align="right" style="padding:3px 9px"><?= /* @escapeNotVerified */ $_order->formatPrice($_order->getShippingAmount()) ?></td> + <td colspan="2" align="right" style="padding:3px 9px"><?= $block->escapeHtml(__('Shipping & Handling')) ?></td> + <td align="right" style="padding:3px 9px"><?= /* @noEscape */ $_order->formatPrice($_order->getShippingAmount()) ?></td> </tr> <?php endif; ?> - <?php if ($_order->getTaxAmount() > 0): ?> + <?php if ($_order->getTaxAmount() > 0) : ?> <tr> - <td colspan="2" align="right" style="padding:3px 9px"><?= /* @escapeNotVerified */ __('Tax') ?></td> - <td align="right" style="padding:3px 9px"><?= /* @escapeNotVerified */ $_order->formatPrice($_order->getTaxAmount()) ?></td> + <td colspan="2" align="right" style="padding:3px 9px"><?= $block->escapeHtml(__('Tax')) ?></td> + <td align="right" style="padding:3px 9px"><?= /* @noEscape */ $_order->formatPrice($_order->getTaxAmount()) ?></td> </tr> <?php endif; ?> <tr bgcolor="#DEE5E8"> - <td colspan="2" align="right" style="padding:3px 9px"><strong><big><?= /* @escapeNotVerified */ __('Grand Total') ?></big></strong></td> - <td align="right" style="padding:6px 9px"><strong><big><?= /* @escapeNotVerified */ $_order->formatPrice($_order->getGrandTotal()) ?></big></strong></td> + <td colspan="2" align="right" style="padding:3px 9px"><strong><big><?= $block->escapeHtml(__('Grand Total')) ?></big></strong></td> + <td align="right" style="padding:6px 9px"><strong><big><?= /* @noEscape */ $_order->formatPrice($_order->getGrandTotal()) ?></big></strong></td> </tr> </tfoot> </table> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/giftoptions.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/giftoptions.phtml index acce4571be005..1010eb339e26d 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/giftoptions.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/giftoptions.phtml @@ -3,13 +3,10 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> -<?php if ($block->getChildHtml()): ?> +<?php if ($block->getChildHtml()) : ?> <section class="admin__page-section order-gift-options"> - <div class="admin__page-section-title"><strong class="title"><?= /* @escapeNotVerified */ __('Gift Options') ?></strong></div> + <div class="admin__page-section-title"><strong class="title"><?= $block->escapeHtml(__('Gift Options')) ?></strong></div> <?= $block->getChildHtml() ?> </section> -<?php endif ?> +<?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/form.phtml index cabbb8df8573c..da9f0d273af24 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/form.phtml @@ -4,68 +4,69 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate +/* @var \Magento\Sales\Block\Adminhtml\Order\Invoice\Create\Form $block */ ?> -<form id="edit_form" class="order-invoice-edit" method="post" action="<?= /* @escapeNotVerified */ $block->getSaveUrl() ?>"> +<form id="edit_form" class="order-invoice-edit" method="post" action="<?= $block->escapeUrl($block->getSaveUrl()) ?>"> <?= $block->getBlockHtml('formkey') ?> <?php $_order = $block->getInvoice()->getOrder() ?> <?= $block->getChildHtml('order_info') ?> <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment & Shipping Method') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment & Shipping Method')) ?></span> </div> <div class="admin__page-section-content"> - <div class="admin__page-section-item order-payment-method<?php if ($_order->getIsVirtual()): ?> order-payment-method-virtual<?php endif; ?>"> + <div class="admin__page-section-item order-payment-method<?php if ($_order->getIsVirtual()) : ?> order-payment-method-virtual<?php endif; ?>"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment Information') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment Information')) ?></span> </div> <div class="admin__page-section-item-content"> <div class="order-payment-method-title"><?= $block->getChildHtml('order_payment') ?></div> - <div class="order-payment-currency"><?= /* @escapeNotVerified */ __('The order was placed using %1.', $_order->getOrderCurrencyCode()) ?></div> + <div class="order-payment-currency"><?= $block->escapeHtml(__('The order was placed using %1.', $_order->getOrderCurrencyCode())) ?></div> <div class="order-payment-additional"><?= $block->getChildHtml('order_payment_additional') ?></div> </div> </div> - <?php if (!$_order->getIsVirtual()): ?> - <div class="admin__page-section-item order-shipping-address"> - <?php /*Shipping Address */ ?> - <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Shipping Information') ?></span> - </div> - <div class="admin__page-section-item-content"> - <div class="shipping-description-wrapper"> - <div class="shipping-description-title"><?= $block->escapeHtml($_order->getShippingDescription()) ?></div> - <div class="shipping-description-content"> - <?= /* @escapeNotVerified */ __('Total Shipping Charges') ?>: + <?php if (!$_order->getIsVirtual()) : ?> + <div class="admin__page-section-item order-shipping-address"> + <?php /*Shipping Address */ ?> + <div class="admin__page-section-item-title"> + <span class="title"><?= $block->escapeHtml(__('Shipping Information')) ?></span> + </div> + <div class="admin__page-section-item-content"> + <div class="shipping-description-wrapper"> + <div class="shipping-description-title"><?= $block->escapeHtml($_order->getShippingDescription()) ?></div> + <div class="shipping-description-content"> + <?= $block->escapeHtml(__('Total Shipping Charges')) ?>: - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayShippingPriceIncludingTax()): ?> - <?php $_excl = $block->displayShippingPriceInclTax($_order); ?> - <?php else: ?> - <?php $_excl = $block->displayPriceAttribute('shipping_amount', false, ' '); ?> - <?php endif; ?> - <?php $_incl = $block->displayShippingPriceInclTax($_order); ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayShippingPriceIncludingTax()) : ?> + <?php $_excl = $block->displayShippingPriceInclTax($_order); ?> + <?php else : ?> + <?php $_excl = $block->displayPriceAttribute('shipping_amount', false, ' '); ?> + <?php endif; ?> + <?php $_incl = $block->displayShippingPriceInclTax($_order); ?> - <?= /* @escapeNotVerified */ $_excl ?> - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayShippingBothPrices() && $_incl != $_excl): ?> - (<?= /* @escapeNotVerified */ __('Incl. Tax') ?> <?= /* @escapeNotVerified */ $_incl ?>) - <?php endif; ?> + <?= /* @noEscape */ $_excl ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayShippingBothPrices() && $_incl != $_excl) : ?> + (<?= $block->escapeHtml(__('Incl. Tax')) ?> <?= /* @noEscape */ $_incl ?>) + <?php endif; ?> + </div> </div> - </div> - <?php if ($block->canCreateShipment() && $block->canShipPartiallyItem()): ?> - <div class="admin__field admin__field-option"> - <input type="checkbox" name="invoice[do_shipment]" id="invoice_do_shipment" value="1" - class="admin__control-checkbox" <?= $block->hasInvoiceShipmentTypeMismatch() ? ' disabled="disabled"' : '' ?> /> - <label for="invoice_do_shipment" - class="admin__field-label"><span><?= /* @escapeNotVerified */ __('Create Shipment') ?></span></label> - </div> - <?php if ($block->hasInvoiceShipmentTypeMismatch()): ?> - <small><?= /* @escapeNotVerified */ __('Invoice and shipment types do not match for some items on this order. You can create a shipment only after creating the invoice.') ?></small> + <?php if ($block->canCreateShipment() && $block->canShipPartiallyItem()) : ?> + <div class="admin__field admin__field-option"> + <input type="checkbox" name="invoice[do_shipment]" id="invoice_do_shipment" value="1" + class="admin__control-checkbox" <?= $block->hasInvoiceShipmentTypeMismatch() ? ' disabled="disabled"' : '' ?> /> + <label for="invoice_do_shipment" + class="admin__field-label"><span><?= $block->escapeHtml(__('Create Shipment')) ?></span></label> + </div> + <?php if ($block->hasInvoiceShipmentTypeMismatch()) : ?> + <small><?= $block->escapeHtml(__('Invoice and shipment types do not match for some items on this order. You can create a shipment only after creating the invoice.')) ?></small> + <?php endif; ?> <?php endif; ?> - <?php endif; ?> - <div id="tracking" style="display:none;"><?= $block->getChildHtml('tracking', false) ?></div> + <div id="tracking" style="display:none;"><?= $block->getChildHtml('tracking', false) ?></div> + </div> </div> - </div> <?php endif; ?> </div> </section> @@ -90,7 +91,7 @@ require(['prototype'], function(){ } /*forced creating of shipment*/ - var forcedShipmentCreate = <?= /* @escapeNotVerified */ $block->getForcedShipmentCreate() ?>; + var forcedShipmentCreate = <?= (int) $block->getForcedShipmentCreate() ?>; var shipmentElement = $('invoice_do_shipment'); if (forcedShipmentCreate && shipmentElement) { shipmentElement.checked = true; diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/items.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/items.phtml index 0d873645bce86..c54efa43e47e6 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/items.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/items.phtml @@ -3,48 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> - <section class="admin__page-section"> <div class="admin__page-section-title"> <?php $_itemsGridLabel = $block->getForcedShipmentCreate() ? 'Items to Invoice and Ship' : 'Items to Invoice'; ?> - <span class="title"><?= /* @escapeNotVerified */ __('%1', $_itemsGridLabel) ?></span> + <span class="title"><?= $block->escapeHtml(__('%1', $_itemsGridLabel)) ?></span> </div> <div class="admin__page-section-content grid"> <div class="admin__table-wrapper"> <table class="data-table admin__table-primary order-invoice-tables"> <thead> <tr class="headings"> - <th class="col-product"><span><?= /* @escapeNotVerified */ __('Product') ?></span></th> - <th class="col-price"><span><?= /* @escapeNotVerified */ __('Price') ?></span></th> - <th class="col-ordered-qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></th> - <th class="col-qty-invoice"><span><?= /* @escapeNotVerified */ __('Qty to Invoice') ?></span></th> - <th class="col-subtotal"><span><?= /* @escapeNotVerified */ __('Subtotal') ?></span></th> - <th class="col-tax"><span><?= /* @escapeNotVerified */ __('Tax Amount') ?></span></th> - <th class="col-discount"><span><?= /* @escapeNotVerified */ __('Discount Amount') ?></span></th> - <th class="col-total last"><span><?= /* @escapeNotVerified */ __('Row Total') ?></span></th> + <th class="col-product"><span><?= $block->escapeHtml(__('Product')) ?></span></th> + <th class="col-price"><span><?= $block->escapeHtml(__('Price')) ?></span></th> + <th class="col-ordered-qty"><span><?= $block->escapeHtml(__('Qty')) ?></span></th> + <th class="col-qty-invoice"><span><?= $block->escapeHtml(__('Qty to Invoice')) ?></span></th> + <th class="col-subtotal"><span><?= $block->escapeHtml(__('Subtotal')) ?></span></th> + <th class="col-tax"><span><?= $block->escapeHtml(__('Tax Amount')) ?></span></th> + <th class="col-discount"><span><?= $block->escapeHtml(__('Discount Amount')) ?></span></th> + <th class="col-total last"><span><?= $block->escapeHtml(__('Row Total')) ?></span></th> </tr> </thead> - <?php if ($block->canEditQty()): ?> - <tfoot> - <tr> - <td colspan="3"> </td> - <td><?= $block->getUpdateButtonHtml() ?></td> - <td colspan="4"> </td> - </tr> - </tfoot> + <?php if ($block->canEditQty()) : ?> + <tfoot> + <tr> + <td colspan="3"> </td> + <td><?= $block->getUpdateButtonHtml() ?></td> + <td colspan="4"> </td> + </tr> + </tfoot> <?php endif; ?> <?php $_items = $block->getInvoice()->getAllItems() ?> - <?php $_i = 0; foreach ($_items as $_item): ?> - <?php if ($_item->getOrderItem()->getParentItem()) { - continue; - } else { - $_i++; - } ?> - <tbody class="<?= /* @escapeNotVerified */ $_i%2 ? 'even' : 'odd' ?>"> + <?php $_i = 0; foreach ($_items as $_item) : ?> + <?php if ($_item->getOrderItem()->getParentItem()) : + continue; + else : + $_i++; + endif; ?> + <tbody class="<?= /* @noEscape */ $_i%2 ? 'even' : 'odd' ?>"> <?= $block->getItemHtml($_item) ?> <?= $block->getItemExtraInfoHtml($_item->getOrderItem()) ?> </tbody> @@ -56,29 +52,29 @@ <?php $orderTotalBar = $block->getChildHtml('order_totalbar'); ?> -<?php if (!empty($orderTotalBar)): ?> +<?php if (!empty($orderTotalBar)) : ?> <section class="admin__page-section"> - <?= /* @escapeNotVerified */ $orderTotalBar ?> + <?= /* @noEscape */ $orderTotalBar ?> </section> <?php endif; ?> <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Order Total') ?></span> + <span class="title"><?= $block->escapeHtml(__('Order Total')) ?></span> </div> <div class="admin__page-section-content"> <div class="admin__page-section-item order-comments-history"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Invoice History') ?></span> + <span class="title"><?= $block->escapeHtml(__('Invoice History')) ?></span> </div> <div id="history_form" class="admin__page-section-item-content order-history-form"> <div class="admin__field"> <label for="invoice_comment_text" class="admin__field-label"> - <span><?= /* @escapeNotVerified */ __('Invoice Comments') ?></span> + <span><?= $block->escapeHtml(__('Invoice Comments')) ?></span> </label> <div class="admin__field-control"> <textarea id="invoice_comment_text" name="invoice[comment_text]" class="admin__control-textarea" - rows="3" cols="5"><?= /* @escapeNotVerified */ $block->getInvoice()->getCommentText() ?></textarea> + rows="3" cols="5"><?= $block->escapeHtml($block->getInvoice()->getCommentText()) ?></textarea> </div> </div> </div> @@ -86,41 +82,41 @@ <div id="invoice_totals" class="admin__page-section-item order-totals"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Invoice Totals') ?></span> + <span class="title"><?= $block->escapeHtml(__('Invoice Totals')) ?></span> </div> <div class="admin__page-section-item-content order-totals-actions"> <?= $block->getChildHtml('invoice_totals') ?> - <?php if ($block->isCaptureAllowed()): ?> - <?php if ($block->canCapture()):?> - <div class="admin__field"> - <?php - /* - <label for="invoice_do_capture" class="normal"><?= __('Capture Amount') ?></label> - <input type="checkbox" name="invoice[do_capture]" id="invoice_do_capture" value="1" checked/> - */ - ?> - <label for="invoice_do_capture" class="admin__field-label"><?= /* @escapeNotVerified */ __('Amount') ?></label> - <select class="admin__control-select" name="invoice[capture_case]"> - <option value="online"><?= /* @escapeNotVerified */ __('Capture Online') ?></option> - <option value="offline"><?= /* @escapeNotVerified */ __('Capture Offline') ?></option> - <option value="not_capture"><?= /* @escapeNotVerified */ __('Not Capture') ?></option> - </select> - </div> - <?php elseif ($block->isGatewayUsed()):?> - <input type="hidden" name="invoice[capture_case]" value="offline"/> - <div><?= /* @escapeNotVerified */ __('The invoice will be created offline without the payment gateway.') ?></div> - <?php endif?> + <?php if ($block->isCaptureAllowed()) : ?> + <?php if ($block->canCapture()) : ?> + <div class="admin__field"> + <?php + /* + <label for="invoice_do_capture" class="normal"><?= __('Capture Amount') ?></label> + <input type="checkbox" name="invoice[do_capture]" id="invoice_do_capture" value="1" checked/> + */ + ?> + <label for="invoice_do_capture" class="admin__field-label"><?= $block->escapeHtml(__('Amount')) ?></label> + <select class="admin__control-select" name="invoice[capture_case]"> + <option value="online"><?= $block->escapeHtml(__('Capture Online')) ?></option> + <option value="offline"><?= $block->escapeHtml(__('Capture Offline')) ?></option> + <option value="not_capture"><?= $block->escapeHtml(__('Not Capture')) ?></option> + </select> + </div> + <?php elseif ($block->isGatewayUsed()) :?> + <input type="hidden" name="invoice[capture_case]" value="offline"/> + <div><?= $block->escapeHtml(__('The invoice will be created offline without the payment gateway.')) ?></div> + <?php endif; ?> <?php endif; ?> <div class="admin__field admin__field-option field-append"> <input id="notify_customer" name="invoice[comment_customer_notify]" value="1" type="checkbox" class="admin__control-checkbox" /> - <label class="admin__field-label" for="notify_customer"><?= /* @escapeNotVerified */ __('Append Comments') ?></label> + <label class="admin__field-label" for="notify_customer"><?= $block->escapeHtml(__('Append Comments')) ?></label> </div> - <?php if ($block->canSendInvoiceEmail()): ?> + <?php if ($block->canSendInvoiceEmail()) : ?> <div class="admin__field admin__field-option field-email"> <input id="send_email" name="invoice[send_email]" value="1" type="checkbox" class="admin__control-checkbox" /> - <label class="admin__field-label" for="send_email"><?= /* @escapeNotVerified */ __('Email Copy of Invoice') ?></label> + <label class="admin__field-label" for="send_email"><?= $block->escapeHtml(__('Email Copy of Invoice')) ?></label> </div> <?php endif; ?> <?= $block->getChildHtml('submit_before') ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/items/renderer/default.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/items/renderer/default.phtml index 5bfb5f130cedb..98ae143e30c0b 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/create/items/renderer/default.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var $block \Magento\Sales\Block\Adminhtml\Items\Renderer\DefaultRenderer */ ?> <?php $_item = $block->getItem() ?> @@ -18,17 +15,17 @@ <td class="col-qty-invoice"> <?php if ($block->canEditQty()) : ?> <input type="text" class="input-text admin__control-text qty-input" - name="invoice[items][<?= /* @escapeNotVerified */ $_item->getOrderItemId() ?>]" - value="<?= /* @escapeNotVerified */ $_item->getQty()*1 ?>"/> + name="invoice[items][<?= (int) $_item->getOrderItemId() ?>]" + value="<?= (int) $_item->getQty() ?>"/> <?php else : ?> - <?= /* @escapeNotVerified */ $_item->getQty()*1 ?> + <?= (int) $_item->getQty() ?> <?php endif; ?> </td> <td class="col-subtotal"> <?= $block->getColumnHtml($_item, 'subtotal') ?> </td> - <td class="col-tax"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('tax_amount') ?></td> - <td class="col-discount"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('discount_amount') ?></td> + <td class="col-tax"><?= /* @noEscape */ $block->displayPriceAttribute('tax_amount') ?></td> + <td class="col-discount"><?= /* @noEscape */ $block->displayPriceAttribute('discount_amount') ?></td> <td class="col-total last"> <?= $block->getColumnHtml($_item, 'total') ?> </td> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/form.phtml index e86a87f089897..784d3f892f2c4 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/form.phtml @@ -4,8 +4,9 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate +/* @var \Magento\Sales\Block\Adminhtml\Order\Invoice\View\Form $block */ ?> <?php $_invoice = $block->getInvoice() ?> <?php $_order = $_invoice->getOrder() ?> @@ -13,46 +14,46 @@ <section class="admin__page-section order-view-billing-shipping"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment & Shipping Method') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment & Shipping Method')) ?></span> </div> <div class="admin__page-section-content"> - <div class="admin__page-section-item order-payment-method<?php if ($_order->getIsVirtual()): ?> order-payment-method-virtual<?php endif; ?> admin__fieldset-wrapper"> + <div class="admin__page-section-item order-payment-method<?php if ($_order->getIsVirtual()) : ?> order-payment-method-virtual<?php endif; ?> admin__fieldset-wrapper"> <?php /*Billing Address */ ?> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment Information') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment Information')) ?></span> </div> <div class="admin__page-section-item-content"> <div class="order-payment-method-title"><?= $block->getChildHtml('order_payment') ?></div> <div class="order-payment-currency"> - <?= /* @escapeNotVerified */ __('The order was placed using %1.', $_order->getOrderCurrencyCode()) ?> + <?= $block->escapeHtml(__('The order was placed using %1.', $_order->getOrderCurrencyCode())) ?> </div> <div class="order-payment-additional"><?= $block->getChildHtml('order_payment_additional') ?></div> </div> </div> - <?php if (!$_order->getIsVirtual()): ?> + <?php if (!$_order->getIsVirtual()) : ?> <div class="admin__page-section-item order-shipping-address"> <?php /*Shipping Address */ ?> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Shipping Information') ?></span> + <span class="title"><?= $block->escapeHtml(__('Shipping Information')) ?></span> </div> <div class="admin__page-section-item-content shipping-description-wrapper"> <div class="shipping-description-title"> <?= $block->escapeHtml($_order->getShippingDescription()) ?> </div> <div class="shipping-description-content"> - <?= /* @escapeNotVerified */ __('Total Shipping Charges') ?>: + <?= $block->escapeHtml(__('Total Shipping Charges')) ?>: - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayShippingPriceIncludingTax()): ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayShippingPriceIncludingTax()) : ?> <?php $_excl = $block->displayShippingPriceInclTax($_order); ?> - <?php else: ?> + <?php else : ?> <?php $_excl = $block->displayPriceAttribute('shipping_amount', false, ' '); ?> <?php endif; ?> <?php $_incl = $block->displayShippingPriceInclTax($_order); ?> - <?= /* @escapeNotVerified */ $_excl ?> - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayShippingBothPrices() && $_incl != $_excl): ?> - (<?= /* @escapeNotVerified */ __('Incl. Tax') ?> <?= /* @escapeNotVerified */ $_incl ?>) + <?= /* @noEscape */ $_excl ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayShippingBothPrices() && $_incl != $_excl) : ?> + (<?= $block->escapeHtml(__('Incl. Tax')) ?> <?= /* @noEscape */ $_incl ?>) <?php endif; ?> <div><?= $block->getChildHtml('shipment_tracking') ?></div> </div> @@ -65,7 +66,7 @@ <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Items Invoiced') ?></span> + <span class="title"><?= $block->escapeHtml(__('Items Invoiced')) ?></span> </div> <div id="invoice_item_container" class="admin__page-section-content"> @@ -75,12 +76,12 @@ <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Order Total') ?></span> + <span class="title"><?= $block->escapeHtml(__('Order Total')) ?></span> </div> <div class="admin__page-section-content"> <div class="admin__page-section-item order-comments-history"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Invoice History') ?></span> + <span class="title"><?= $block->escapeHtml(__('Invoice History')) ?></span> </div> <div class="admin__page-section-item-content"> <?= $block->getChildHtml('order_comments') ?> @@ -89,7 +90,7 @@ <div id="history_form" class="admin__page-section-item order-totals"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Invoice Totals') ?></span> + <span class="title"><?= $block->escapeHtml(__('Invoice Totals')) ?></span> </div> <?= $block->getChildHtml('invoice_totals') ?> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/items.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/items.phtml index 63f33dbb74bad..6dbfd19e9a2c7 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/items.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/items.phtml @@ -4,30 +4,29 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/* @var \Magento\Sales\Block\Adminhtml\Order\Invoice\View\Items $block */ ?> <div class="admin__table-wrapper"> <table class="data-table admin__table-primary order-invoice-tables"> <thead> <tr class="headings"> - <th class="col-product"><span><?= /* @escapeNotVerified */ __('Product') ?></span></th> - <th class="col-price"><span><?= /* @escapeNotVerified */ __('Price') ?></span></th> - <th class="col-qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></th> - <th class="col-subtotal"><span><?= /* @escapeNotVerified */ __('Subtotal') ?></span></th> - <th class="col-tax"><span><?= /* @escapeNotVerified */ __('Tax Amount') ?></span></th> - <th class="col-discount"><span><?= /* @escapeNotVerified */ __('Discount Amount') ?></span></th> - <th class="col-total last"><span><?= /* @escapeNotVerified */ __('Row Total') ?></span></th> + <th class="col-product"><span><?= $block->escapeHtml(__('Product')) ?></span></th> + <th class="col-price"><span><?= $block->escapeHtml(__('Price')) ?></span></th> + <th class="col-qty"><span><?= $block->escapeHtml(__('Qty')) ?></span></th> + <th class="col-subtotal"><span><?= $block->escapeHtml(__('Subtotal')) ?></span></th> + <th class="col-tax"><span><?= $block->escapeHtml(__('Tax Amount')) ?></span></th> + <th class="col-discount"><span><?= $block->escapeHtml(__('Discount Amount')) ?></span></th> + <th class="col-total last"><span><?= $block->escapeHtml(__('Row Total')) ?></span></th> </tr> </thead> <?php $_items = $block->getInvoice()->getAllItems() ?> - <?php $i = 0; foreach ($_items as $_item): ?> - <?php if ($_item->getOrderItem()->getParentItem()) { - continue; - } else { - $i++; - } ?> - <tbody class="<?= /* @escapeNotVerified */ $i%2 ? 'even' : 'odd' ?>"> + <?php $i = 0; foreach ($_items as $_item) : ?> + <?php if ($_item->getOrderItem()->getParentItem()) : + continue; + else : + $i++; + endif; ?> + <tbody class="<?= /* @noEscape */ $i%2 ? 'even' : 'odd' ?>"> <?= $block->getItemHtml($_item) ?> <?= $block->getItemExtraInfoHtml($_item->getOrderItem()) ?> </tbody> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/items/renderer/default.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/items/renderer/default.phtml index af9e5b3bb702d..59301931c73c7 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/invoice/view/items/renderer/default.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var $block \Magento\Sales\Block\Adminhtml\Items\Renderer\DefaultRenderer */ ?> <?php $_item = $block->getItem() ?> @@ -16,12 +13,12 @@ <td class="col-price"> <?= $block->getColumnHtml($_item, 'price') ?> </td> - <td class="col-qty"><?= /* @escapeNotVerified */ $_item->getQty()*1 ?></td> + <td class="col-qty"><?= (int) $_item->getQty() ?></td> <td class="col-subtotal"> <?= $block->getColumnHtml($_item, 'subtotal') ?> </td> - <td class="col-tax"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('tax_amount') ?></td> - <td class="col-discount"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('discount_amount') ?></td> + <td class="col-tax"><?= /* @noEscape */ $block->displayPriceAttribute('tax_amount') ?></td> + <td class="col-discount"><?= /* @noEscape */ $block->displayPriceAttribute('discount_amount') ?></td> <td class="col-total last"> <?= $block->getColumnHtml($_item, 'total') ?> </td> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totalbar.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totalbar.phtml index 8ff360b9635c3..e3cfaa715cc32 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totalbar.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totalbar.phtml @@ -5,16 +5,15 @@ */ // @deprecated -// @codingStandardsIgnoreFile - +$totals = $block->getTotals(); ?> -<?php if (sizeof($block->getTotals()) > 0): ?> +<?php if (sizeof($block->getTotals()) > 0) : ?> <table class="items-to-invoice"> <tr> - <?php foreach ($block->getTotals() as $_total): ?> + <?php foreach ($block->getTotals() as $_total) : ?> <td <?php if ($_total['grand']): ?>class="grand-total"<?php endif; ?>> - <?= /* @escapeNotVerified */ $_total['label'] ?><br /> - <?= /* @escapeNotVerified */ $_total['value'] ?> + <?= $block->escapeHtml($_total['label']) ?><br /> + <?= $block->escapeHtml($_total['value']) ?> </td> <?php endforeach; ?> </tr> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totals.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totals.phtml index 27b82505a11d3..1f495b9c4a573 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totals.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totals.phtml @@ -4,59 +4,58 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/* @var \Magento\Sales\Block\Adminhtml\Order\Totals $block */ ?> <table class="data-table admin__table-secondary order-subtotal-table"> - <?php $_totals = $block->getTotals('footer')?> + <?php $_totals = $block->getTotals('footer') ?> - <?php if ($_totals):?> + <?php if ($_totals) : ?> <tfoot> - <?php foreach ($block->getTotals('footer') as $_code => $_total): ?> - <?php if ($_total->getBlockName()): ?> + <?php foreach ($block->getTotals('footer') as $_code => $_total) : ?> + <?php if ($_total->getBlockName()) : ?> <?= $block->getChildHtml($_total->getBlockName(), false) ?> - <?php else:?> - <tr class="col-<?= /* @escapeNotVerified */ $_code ?>"> - <td <?= /* @escapeNotVerified */ $block->getLabelProperties() ?> class="label"> + <?php else : ?> + <tr class="col-<?= $block->escapeHtmlAttr($_code) ?>"> + <td <?= /* @noEscape */ $block->getLabelProperties() ?> class="label"> <strong><?= $block->escapeHtml($_total->getLabel()) ?></strong> </td> - <td <?= /* @escapeNotVerified */ $block->getValueProperties() ?>> - <strong><?= /* @escapeNotVerified */ $block->formatValue($_total) ?></strong> + <td <?= /* @noEscape */ $block->getValueProperties() ?>> + <strong><?= /* @noEscape */ $block->formatValue($_total) ?></strong> </td> </tr> - <?php endif?> - <?php endforeach?> + <?php endif; ?> + <?php endforeach; ?> </tfoot> - <?php endif?> + <?php endif; ?> <?php $_totals = $block->getTotals('')?> - <?php if ($_totals):?> + <?php if ($_totals) : ?> <tbody> - <?php foreach ($_totals as $_code => $_total): ?> - <?php if ($_total->getBlockName()): ?> + <?php foreach ($_totals as $_code => $_total) : ?> + <?php if ($_total->getBlockName()) : ?> <?= $block->getChildHtml($_total->getBlockName(), false) ?> - <?php else:?> - <tr class="col-<?= /* @escapeNotVerified */ $_code ?>"> - <td <?= /* @escapeNotVerified */ $block->getLabelProperties() ?> class="label"> - <?php if ($_total->getStrong()):?> + <?php else : ?> + <tr class="col-<?= $block->escapeHtmlAttr($_code) ?>"> + <td <?= /* @noEscape */ $block->getLabelProperties() ?> class="label"> + <?php if ($_total->getStrong()) : ?> <strong><?= $block->escapeHtml($_total->getLabel()) ?></strong> - <?php else:?> + <?php else : ?> <?= $block->escapeHtml($_total->getLabel()) ?> <?php endif?> </td> - <?php if ($_total->getStrong()):?> - <td <?= /* @escapeNotVerified */ $block->getValueProperties() ?>> - <strong><?= /* @escapeNotVerified */ $block->formatValue($_total) ?></strong> + <?php if ($_total->getStrong()) : ?> + <td <?= /* @noEscape */ $block->getValueProperties() ?>> + <strong><?= /* @noEscape */ $block->formatValue($_total) ?></strong> </td> - <?php else:?> - <td <?= /* @escapeNotVerified */ $block->getValueProperties() ?>> - <span><?= /* @escapeNotVerified */ $block->formatValue($_total) ?></span> + <?php else : ?> + <td <?= /* @noEscape */ $block->getValueProperties() ?>> + <span><?= /* @noEscape */ $block->formatValue($_total) ?></span> </td> - <?php endif?> + <?php endif; ?> </tr> - <?php endif?> - <?php endforeach?> + <?php endif; ?> + <?php endforeach; ?> </tbody> - <?php endif?> + <?php endif; ?> </table> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/discount.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/discount.phtml index db2567a5f3dbf..9ff3a91eab7ce 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/discount.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/discount.phtml @@ -3,23 +3,20 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php $_source = $block->getSource() ?> <?php $_order = $block->getOrder() ?> <?php $block->setPriceDataObject($_source) ?> -<?php if ((float) $_source->getDiscountAmount()): ?> +<?php if ((float) $_source->getDiscountAmount()) : ?> <tr> <td class="label"> - <?php if ($_order->getCouponCode()): ?> - <?= /* @escapeNotVerified */ __('Discount (%1)', $_order->getCouponCode()) ?> - <?php else: ?> - <?= /* @escapeNotVerified */ __('Discount') ?> + <?php if ($_order->getCouponCode()) : ?> + <?= $block->escapeHtml(__('Discount (%1)', $_order->getCouponCode())) ?> + <?php else : ?> + <?= $block->escapeHtml(__('Discount')) ?> <?php endif; ?> </td> - <td><?= /* @escapeNotVerified */ $block->displayPriceAttribute('discount_amount') ?></td> + <td><?= /* @noEscape */ $block->displayPriceAttribute('discount_amount') ?></td> </tr> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/due.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/due.phtml index 81402e37288ef..87d7c85c2d9ed 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/due.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/due.phtml @@ -3,13 +3,10 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> -<?php if ($block->getCanDisplayTotalDue()): ?> +<?php if ($block->getCanDisplayTotalDue()) : ?> <tr> - <td class="label"><big><strong><?= /* @escapeNotVerified */ __('Total Due') ?></strong></big></td> - <td class="emph"><big><?= /* @escapeNotVerified */ $block->displayPriceAttribute('total_due', true) ?></big></td> + <td class="label"><big><strong><?= $block->escapeHtml(__('Total Due')) ?></strong></big></td> + <td class="emph"><big><?= /* @noEscape */ $block->displayPriceAttribute('total_due', true) ?></big></td> </tr> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/grand.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/grand.phtml index 519aa660fbf12..dc76799251c7a 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/grand.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/grand.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php $_source = $block->getSource() ?> <?php $block->setPriceDataObject($_source) ?> @@ -13,12 +10,12 @@ <tr> <td class="label"> <strong><big> - <?php if ($block->getGrandTotalTitle()): ?> - <?= /* @escapeNotVerified */ $block->getGrandTotalTitle() ?> - <?php else: ?> - <?= /* @escapeNotVerified */ __('Grand Total') ?> + <?php if ($block->getGrandTotalTitle()) : ?> + <?= $block->escapeHtml($block->getGrandTotalTitle()) ?> + <?php else : ?> + <?= $block->escapeHtml(__('Grand Total')) ?> <?php endif; ?> </big></strong> </td> - <td class="emph"><big><?= /* @escapeNotVerified */ $block->displayPriceAttribute('grand_total', true) ?></big></td> + <td class="emph"><big><?= /* @noEscape */ $block->displayPriceAttribute('grand_total', true) ?></big></td> </tr> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/item.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/item.phtml index 6c44e6ec632a7..f3590654181c2 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/item.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/item.phtml @@ -3,16 +3,25 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> -<?php $_source = $block->getSource() ?> +<?php $_source = $block->getSource() ?> <?php $block->setPriceDataObject($_source) ?> -<?php if ((float) $_source->getDataUsingMethod($block->getSourceField())): ?> +<?php if ((float) $_source->getDataUsingMethod($block->getSourceField())) : ?> <tr> - <td class="label"><?php if ($block->getStrong()) : ?><strong><?php endif; ?><?= /* @escapeNotVerified */ __($block->getLabel()) ?><?php if ($block->getStrong()) : ?></strong><?php endif; ?></td> - <td <?= $block->getHtmlClass() ? ('class="' . $block->getHtmlClass() . '"') : '' ?>><?php if ($block->getStrong()) : ?><strong><?php endif; ?><?= /* @escapeNotVerified */ $block->displayPriceAttribute($block->getSourceField()) ?><?php if ($block->getStrong()) : ?></strong><?php endif; ?></td> + <td class="label"> + <?php if ($block->getStrong()) : ?> + <strong> + <?php endif; ?> + <?= $block->escapeHtml(__($block->getLabel())) ?> + <?php if ($block->getStrong()) : ?> + </strong> + <?php endif; ?> + </td> + <td <?= $block->getHtmlClass() ? ('class="' . $block->escapeHtmlAttr($block->getHtmlClass()) . '"') : '' ?>> + <?php if ($block->getStrong()) : ?><strong><?php endif; ?> + <?= /* @noEscape */ $block->displayPriceAttribute($block->getSourceField()) ?> + <?php if ($block->getStrong()) : ?></strong><?php endif; ?> + </td> </tr> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/paid.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/paid.phtml index 8befc7cc0ccb4..9ede6e21e78af 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/paid.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/paid.phtml @@ -3,14 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> -<?php if ($block->getCanDisplayTotalPaid()): ?> +<?php if ($block->getCanDisplayTotalPaid()) : ?> <tr> - <td class="label"><strong><?= /* @escapeNotVerified */ __('Total Paid') ?></strong></td> - <td class="emph"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('total_paid', true) ?> + <td class="label"><strong><?= $block->escapeHtml(__('Total Paid')) ?></strong></td> + <td class="emph"><?= /* @noEscape */ $block->displayPriceAttribute('total_paid', true) ?> </td> </tr> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/refunded.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/refunded.phtml index e579578f711ae..1e7087c7222c3 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/refunded.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/refunded.phtml @@ -3,13 +3,10 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> -<?php if ($block->getCanDisplayTotalRefunded()): ?> +<?php if ($block->getCanDisplayTotalRefunded()) : ?> <tr> - <td class="label"><strong><?= /* @escapeNotVerified */ __('Total Refunded') ?></strong></td> - <td class="emph"><?= /* @escapeNotVerified */ $block->displayPriceAttribute('total_refunded', true) ?></td> + <td class="label"><strong><?= $block->escapeHtml(__('Total Refunded')) ?></strong></td> + <td class="emph"><?= /* @noEscape */ $block->displayPriceAttribute('total_refunded', true) ?></td> </tr> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/shipping.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/shipping.phtml index 47304bf7f4a7e..4250dc1d047ba 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/shipping.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/shipping.phtml @@ -3,16 +3,13 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php $_source = $block->getSource() ?> <?php $block->setPriceDataObject($_source) ?> -<?php if ((float) $_source->getShippingAmount() || $_source->getShippingDescription()): ?> +<?php if ((float) $_source->getShippingAmount() || $_source->getShippingDescription()) : ?> <tr> - <td class="label"><?= /* @escapeNotVerified */ __('Shipping & Handling') ?></td> - <td><?= /* @escapeNotVerified */ $block->displayPriceAttribute('shipping_amount') ?></td> + <td class="label"><?= $block->escapeHtml(__('Shipping & Handling')) ?></td> + <td><?= /* @noEscape */ $block->displayPriceAttribute('shipping_amount') ?></td> </tr> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/tax.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/tax.phtml index 284597027468d..a68fb09fd2058 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totals/tax.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totals/tax.phtml @@ -4,42 +4,41 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate /** @var $block \Magento\Sales\Block\Adminhtml\Order\Totals\Tax */ -?> -<?php + /** @var $_source \Magento\Sales\Model\Order\Invoice */ $_source = $block->getSource(); $_order = $block->getOrder(); $_fullInfo = $block->getFullTaxInfo(); ?> -<?php if ($block->displayFullSummary() && $_fullInfo): ?> +<?php if ($block->displayFullSummary() && $_fullInfo) : ?> <tr class="summary-total" onclick="expandDetails(this, '.summary-details')"> -<?php else: ?> +<?php else : ?> <tr> <?php endif; ?> <td class="label"> <div class="summary-collapse" tabindex="0"> - <?php if ($this->helper('Magento\Tax\Helper\Data')->displayFullSummary()): ?> - <?= /* @escapeNotVerified */ __('Total Tax') ?> - <?php else: ?> - <?= /* @escapeNotVerified */ __('Tax') ?> + <?php if ($this->helper(\Magento\Tax\Helper\Data::class)->displayFullSummary()) : ?> + <?= $block->escapeHtml(__('Total Tax')) ?> + <?php else : ?> + <?= $block->escapeHtml(__('Tax')) ?> <?php endif;?> </div> </td> <td> - <?= /* @escapeNotVerified */ $block->displayAmount($_source->getTaxAmount(), $_source->getBaseTaxAmount()) ?> + <?= /* @noEscape */ $block->displayAmount($_source->getTaxAmount(), $_source->getBaseTaxAmount()) ?> </td> </tr> -<?php if ($block->displayFullSummary()): ?> +<?php if ($block->displayFullSummary()) : ?> <?php $isTop = 1; ?> - <?php if (isset($_fullInfo[0]['rates'])): ?> - <?php foreach ($_fullInfo as $info): ?> - <?php if (isset($info['hidden']) && $info['hidden']) { + <?php if (isset($_fullInfo[0]['rates'])) : ?> + <?php foreach ($_fullInfo as $info) : ?> + <?php if (isset($info['hidden']) && $info['hidden']) : continue; - } ?> + endif; ?> <?php $percent = $info['percent']; $amount = $info['amount']; @@ -48,39 +47,38 @@ $_fullInfo = $block->getFullTaxInfo(); $isFirst = 1; ?> - <?php foreach ($rates as $rate): ?> - <tr class="summary-details<?php if ($isTop): echo ' summary-details-first'; endif; ?>" style="display:none;"> - <?php if (!is_null($rate['percent'])): ?> - <td class="admin__total-mark"><?= /* @escapeNotVerified */ $rate['title'] ?> (<?= (float)$rate['percent'] ?>%)<br /></td> - <?php else: ?> - <td class="admin__total-mark"><?= /* @escapeNotVerified */ $rate['title'] ?><br /></td> - <?php endif; ?> - <?php if ($isFirst): ?> - <td rowspan="<?= count($rates) ?>"><?= /* @escapeNotVerified */ $block->displayAmount($amount, $baseAmount) ?></td> - <?php endif; ?> - </tr> - <?php + <?php foreach ($rates as $rate) : ?> + <tr class="summary-details<?= ($isTop ? ' summary-details-first' : '') ?>" style="display:none;"> + <?php if ($rate['percent'] !== null) : ?> + <td class="admin__total-mark"><?= $block->escapeHtml($rate['title']) ?> (<?= (float)$rate['percent'] ?>%)<br /></td> + <?php else : ?> + <td class="admin__total-mark"><?= $block->escapeHtml($rate['title']) ?><br /></td> + <?php endif; ?> + <?php if ($isFirst) : ?> + <td rowspan="<?= count($rates) ?>"><?= /* @noEscape */ $block->displayAmount($amount, $baseAmount) ?></td> + <?php endif; ?> + </tr> + <?php $isFirst = 0; $isTop = 0; ?> <?php endforeach; ?> <?php endforeach; ?> - <?php else: ?> - <?php foreach ($_fullInfo as $info): ?> + <?php else : ?> + <?php foreach ($_fullInfo as $info) : ?> <?php $percent = $info['percent']; $amount = $info['tax_amount']; $baseAmount = $info['base_tax_amount']; $isFirst = 1; ?> - - <tr class="summary-details<?php if ($isTop): echo ' summary-details-first'; endif; ?>" style="display:none;"> - <?php if (!is_null($info['percent'])): ?> + <tr class="summary-details<?= ($isTop ? ' summary-details-first' : '') ?>" style="display:none;"> + <?php if ($info['percent'] !== null) : ?> <td class="admin__total-mark"><?= $block->escapeHtml($info['title']) ?> (<?= (float)$info['percent'] ?>%)<br /></td> - <?php else: ?> + <?php else : ?> <td class="admin__total-mark"><?= $block->escapeHtml($info['title']) ?><br /></td> <?php endif; ?> - <td><?= /* @escapeNotVerified */ $block->displayAmount($amount, $baseAmount) ?></td> + <td><?= /* @noEscape */ $block->displayAmount($amount, $baseAmount) ?></td> </tr> <?php $isFirst = 0; diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/view/giftmessage.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/view/giftmessage.phtml index 393af3e40d6eb..bf80f5df00b5e 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/view/giftmessage.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/view/giftmessage.phtml @@ -4,61 +4,60 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/** @var $block \Magento\Sales\Block\Adminhtml\Order\View\Giftmessage */ ?> -<?php if ($block->canDisplayGiftmessage()): ?> -<?php $_required = $block->getMessage()->getMessage() != ''?> -<div id="<?= $block->getHtmlId() ?>" class="admin__page-section-content giftmessage-whole-order-container"> - <form class="entry-edit form-inline" id="<?= /* @escapeNotVerified */ $block->getFieldId('form') ?>" action="<?= /* @escapeNotVerified */ $block->getSaveUrl() ?>"> - <fieldset class="admin__fieldset"> - <legend class="admin__legend"><span><?= /* @escapeNotVerified */ __('Gift Message for the Entire Order') ?></span></legend> - <br/> - - <input type="hidden" id="<?= /* @escapeNotVerified */ $block->getFieldId('type') ?>" - name="<?= /* @escapeNotVerified */ $block->getFieldName('type') ?>" - value="order"/> - - <div class="admin__field field-from-name<?= $_required ? ' required' : '' ?>"> - <label class="admin__field-label" - for="<?= /* @escapeNotVerified */ $block->getFieldId('sender') ?>"><span><?= /* @escapeNotVerified */ __('From Name') ?></span></label> - - <div class="admin__field-control"> - <input class="admin__control-text <?= $_required ? 'required-entry' : '' ?>" type="text" - id="<?= /* @escapeNotVerified */ $block->getFieldId('sender') ?>" - name="<?= /* @escapeNotVerified */ $block->getFieldName('sender') ?>" - value="<?= $block->escapeHtml($block->getMessage()->getSender()) ?>"/> +<?php if ($block->canDisplayGiftmessage()) : ?> + <?php $_required = $block->getMessage()->getMessage() != '' ?> + <div id="<?= $block->escapeHtmlAttr($block->getHtmlId()) ?>" class="admin__page-section-content giftmessage-whole-order-container"> + <form class="entry-edit form-inline" id="<?= $block->escapeHtmlAttr($block->getFieldId('form')) ?>" action="<?= $block->escapeUrl($block->getSaveUrl()) ?>"> + <fieldset class="admin__fieldset"> + <legend class="admin__legend"><span><?= $block->escapeHtml(__('Gift Message for the Entire Order')) ?></span></legend> + <br/> + + <input type="hidden" id="<?= $block->escapeHtmlAttr($block->getFieldId('type')) ?>" + name="<?= $block->escapeHtmlAttr($block->getFieldName('type')) ?>" + value="order"/> + + <div class="admin__field field-from-name<?= $_required ? ' required' : '' ?>"> + <label class="admin__field-label" + for="<?= $block->escapeHtmlAttr($block->getFieldId('sender')) ?>"><span><?= $block->escapeHtml(__('From Name')) ?></span></label> + + <div class="admin__field-control"> + <input class="admin__control-text <?= $_required ? 'required-entry' : '' ?>" type="text" + id="<?= $block->escapeHtmlAttr($block->getFieldId('sender')) ?>" + name="<?= $block->escapeHtmlAttr($block->getFieldName('sender')) ?>" + value="<?= $block->escapeHtml($block->getMessage()->getSender()) ?>"/> + </div> </div> - </div> - <div class="admin__field field-to-name<?= $_required ? ' required' : '' ?>"> - <label class="admin__field-label" - for="<?= /* @escapeNotVerified */ $block->getFieldId('recipient') ?>"><span><?= /* @escapeNotVerified */ __('To Name') ?></span></label> + <div class="admin__field field-to-name<?= $_required ? ' required' : '' ?>"> + <label class="admin__field-label" + for="<?= $block->escapeHtmlAttr($block->getFieldId('recipient')) ?>"><span><?= $block->escapeHtml(__('To Name')) ?></span></label> - <div class="admin__field-control"> - <input class="admin__control-text <?= $_required ? 'required-entry' : '' ?>" type="text" - id="<?= /* @escapeNotVerified */ $block->getFieldId('recipient') ?>" - name="<?= /* @escapeNotVerified */ $block->getFieldName('recipient') ?>" - value="<?= $block->escapeHtml($block->getMessage()->getRecipient()) ?>"/> + <div class="admin__field-control"> + <input class="admin__control-text <?= $_required ? 'required-entry' : '' ?>" type="text" + id="<?= $block->escapeHtmlAttr($block->getFieldId('recipient')) ?>" + name="<?= $block->escapeHtmlAttr($block->getFieldName('recipient')) ?>" + value="<?= $block->escapeHtml($block->getMessage()->getRecipient()) ?>"/> + </div> </div> - </div> - <div class="admin__field field-gift-message"> - <label class="admin__field-label" - for="<?= /* @escapeNotVerified */ $block->getFieldId('message') ?>"><span><?= /* @escapeNotVerified */ __('Gift Message') ?></span></label> - <div class="admin__field-control"> - <textarea id="<?= /* @escapeNotVerified */ $block->getFieldId('message') ?>" - name="<?= /* @escapeNotVerified */ $block->getFieldName('message') ?>" - class="admin__control-textarea" - rows="2" - cols="15"><?= $block->escapeHtml($block->getMessage()->getMessage()) ?></textarea> + <div class="admin__field field-gift-message"> + <label class="admin__field-label" + for="<?= $block->escapeHtmlAttr($block->getFieldId('message')) ?>"><span><?= $block->escapeHtml(__('Gift Message')) ?></span></label> + <div class="admin__field-control"> + <textarea id="<?= $block->escapeHtmlAttr($block->getFieldId('message')) ?>" + name="<?= $block->escapeHtmlAttr($block->getFieldName('message')) ?>" + class="admin__control-textarea" + rows="2" + cols="15"><?= $block->escapeHtml($block->getMessage()->getMessage()) ?></textarea> + </div> </div> - </div> - <div class="actions"> - <?= $block->getSaveButtonHtml() ?> - </div> - </fieldset> - </form> -</div> + <div class="actions"> + <?= $block->getSaveButtonHtml() ?> + </div> + </fieldset> + </form> + </div> <?php endif ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/view/history.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/view/history.phtml index 6ac6e13a873ed..16643a29a7fbe 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/view/history.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/view/history.phtml @@ -4,19 +4,18 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile /** @var \Magento\Sales\Block\Adminhtml\Order\View\History $block */ ?> <div id="order_history_block" class="edit-order-comments"> - <?php if ($block->canAddComment()):?> + <?php if ($block->canAddComment()) : ?> <div class="order-history-block" id="history_form"> <div class="admin__field"> - <label for="history_status" class="admin__field-label"><?= /* @noEscape */ __('Status') ?></label> + <label for="history_status" class="admin__field-label"><?= $block->escapeHtml(__('Status')) ?></label> <div class="admin__field-control"> <select name="history[status]" id="history_status" class="admin__control-select"> - <?php foreach ($block->getStatuses() as $_code => $_label): ?> - <option value="<?= $block->escapeHtml($_code) ?>"<?php if ($_code == $block->getOrder()->getStatus()): ?> selected="selected"<?php endif; ?>><?= $block->escapeHtml($_label) ?></option> + <?php foreach ($block->getStatuses() as $_code => $_label) : ?> + <option value="<?= $block->escapeHtmlAttr($_code) ?>"<?php if ($_code == $block->getOrder()->getStatus()) : ?> selected="selected"<?php endif; ?>><?= $block->escapeHtml($_label) ?></option> <?php endforeach; ?> </select> </div> @@ -24,7 +23,7 @@ <div class="admin__field"> <label for="history_comment" class="admin__field-label"> - <?= /* @noEscape */ __('Comment') ?> + <?= $block->escapeHtml(__('Comment')) ?> </label> <div class="admin__field-control"> <textarea name="history[comment]" @@ -38,14 +37,14 @@ <div class="admin__field"> <div class="order-history-comments-options"> <div class="admin__field admin__field-option"> - <?php if ($block->canSendCommentEmail()): ?> + <?php if ($block->canSendCommentEmail()) : ?> <input name="history[is_customer_notified]" type="checkbox" id="history_notify" class="admin__control-checkbox" value="1" /> <label class="admin__field-label" for="history_notify"> - <?= /* @noEscape */ __('Notify Customer by Email') ?> + <?= $block->escapeHtml(__('Notify Customer by Email')) ?> </label> <?php endif; ?> </div> @@ -57,7 +56,7 @@ class="admin__control-checkbox" value="1" /> <label class="admin__field-label" for="history_visible"> - <?= /* @noEscape */ __('Visible on Storefront') ?> + <?= $block->escapeHtml(__('Visible on Storefront')) ?> </label> </div> </div> @@ -70,32 +69,30 @@ <?php endif;?> <ul class="note-list"> - <?php foreach ($block->getOrder()->getStatusHistoryCollection(true) as $_item): ?> + <?php foreach ($block->getOrder()->getStatusHistoryCollection(true) as $_item) : ?> <li class="note-list-item"> <span class="note-list-date"><?= /* @noEscape */ $block->formatDate($_item->getCreatedAt(), \IntlDateFormatter::MEDIUM) ?></span> <span class="note-list-time"><?= /* @noEscape */ $block->formatTime($_item->getCreatedAt(), \IntlDateFormatter::MEDIUM) ?></span> <span class="note-list-status"><?= $block->escapeHtml($_item->getStatusLabel()) ?></span> <span class="note-list-customer"> - <?= /* @noEscape */ __('Customer') ?> - <?php if ($block->isCustomerNotificationNotApplicable($_item)): ?> - <span class="note-list-customer-notapplicable"><?= /* @noEscape */ __('Notification Not Applicable') ?></span> - <?php elseif ($_item->getIsCustomerNotified()): ?> - <span class="note-list-customer-notified"><?= /* @noEscape */ __('Notified') ?></span> - <?php else: ?> - <span class="note-list-customer-not-notified"><?= /* @noEscape */ __('Not Notified') ?></span> + <?= $block->escapeHtml(__('Customer')) ?> + <?php if ($block->isCustomerNotificationNotApplicable($_item)) : ?> + <span class="note-list-customer-notapplicable"><?= $block->escapeHtml(__('Notification Not Applicable')) ?></span> + <?php elseif ($_item->getIsCustomerNotified()) : ?> + <span class="note-list-customer-notified"><?= $block->escapeHtml(__('Notified')) ?></span> + <?php else : ?> + <span class="note-list-customer-not-notified"><?= $block->escapeHtml(__('Not Notified')) ?></span> <?php endif; ?> </span> - <?php if ($_item->getComment()): ?> + <?php if ($_item->getComment()) : ?> <div class="note-list-comment"><?= $block->escapeHtml($_item->getComment(), ['b', 'br', 'strong', 'i', 'u', 'a']) ?></div> <?php endif; ?> </li> <?php endforeach; ?> </ul> <script> -require(['prototype'], function(){ - - if($('order_status'))$('order_status').update('<?= $block->escapeJs($block->escapeHtml($block->getOrder()->getStatusLabel())) ?>'); - -}); -</script> + require(['prototype'], function(){ + if($('order_status'))$('order_status').update('<?= $block->escapeJs($block->escapeHtml($block->getOrder()->getStatusLabel())) ?>'); + }); + </script> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/view/info.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/view/info.phtml index bbd6394097f9e..508ac7c252de5 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/view/info.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/view/info.phtml @@ -7,9 +7,6 @@ /** * @var \Magento\Sales\Block\Adminhtml\Order\View\Info $block */ - -// @codingStandardsIgnoreFile - $order = $block->getOrder(); $orderAdminDate = $block->formatDate( @@ -38,10 +35,10 @@ $customerUrl = $block->getCustomerViewUrl(); <?php $confirmationEmailStatusMessage = $order->getEmailSent() ? __('The order confirmation email was sent') : __('The order confirmation email is not sent'); ?> <div class="admin__page-section-item-title"> <span class="title"> - <?php if ($block->getNoUseOrderLink()): ?> + <?php if ($block->getNoUseOrderLink()) : ?> <?= $block->escapeHtml(__('Order # %1', $order->getRealOrderId())) ?> (<span><?= $block->escapeHtml($confirmationEmailStatusMessage) ?></span>) - <?php else: ?> - <a href="<?= $block->escapeHtml($block->getViewUrl($order->getId())) ?>"><?= $block->escapeHtml(__('Order # %1', $order->getRealOrderId())) ?></a> + <?php else : ?> + <a href="<?= $block->escapeUrl($block->getViewUrl($order->getId())) ?>"><?= $block->escapeHtml(__('Order # %1', $order->getRealOrderId())) ?></a> <span>(<?= $block->escapeHtml($confirmationEmailStatusMessage) ?>)</span> <?php endif; ?> </span> @@ -52,7 +49,7 @@ $customerUrl = $block->getCustomerViewUrl(); <th><?= $block->escapeHtml(__('Order Date')) ?></th> <td><?= $block->escapeHtml($orderAdminDate) ?></td> </tr> - <?php if ($orderAdminDate != $orderStoreDate):?> + <?php if ($orderAdminDate != $orderStoreDate) : ?> <tr> <th><?= $block->escapeHtml(__('Order Date (%1)', $block->getTimezoneForStore($order->getStore()))) ?></th> <td><?= $block->escapeHtml($orderStoreDate) ?></td> @@ -63,45 +60,45 @@ $customerUrl = $block->getCustomerViewUrl(); <td><span id="order_status"><?= $block->escapeHtml($order->getStatusLabel()) ?></span></td> </tr> <?= $block->getChildHtml() ?> - <?php if ($block->isSingleStoreMode() == false):?> + <?php if ($block->isSingleStoreMode() == false) : ?> <tr> <th><?= $block->escapeHtml(__('Purchased From')) ?></th> <td><?= $block->escapeHtml($block->getOrderStoreName(), ['br']) ?></td> </tr> <?php endif; ?> - <?php if ($order->getRelationChildId()): ?> + <?php if ($order->getRelationChildId()) : ?> <tr> <th><?= $block->escapeHtml(__('Link to the New Order')) ?></th> <td> - <a href="<?= $block->escapeHtml($block->getViewUrl($order->getRelationChildId())) ?>"> + <a href="<?= $block->escapeUrl($block->getViewUrl($order->getRelationChildId())) ?>"> <?= $block->escapeHtml($order->getRelationChildRealId()) ?> </a> </td> </tr> <?php endif; ?> - <?php if ($order->getRelationParentId()): ?> + <?php if ($order->getRelationParentId()) : ?> <tr> <th><?= $block->escapeHtml(__('Link to the Previous Order')) ?></th> <td> - <a href="<?= $block->escapeHtml($block->getViewUrl($order->getRelationParentId())) ?>"> + <a href="<?= $block->escapeUrl($block->getViewUrl($order->getRelationParentId())) ?>"> <?= $block->escapeHtml($order->getRelationParentRealId()) ?> </a> </td> </tr> <?php endif; ?> - <?php if ($order->getRemoteIp() && $block->shouldDisplayCustomerIp()): ?> + <?php if ($order->getRemoteIp() && $block->shouldDisplayCustomerIp()) : ?> <tr> <th><?= $block->escapeHtml(__('Placed from IP')) ?></th> - <td><?= $block->escapeHtml($order->getRemoteIp()); echo $order->getXForwardedFor() ? ' (' . $block->escapeHtml($order->getXForwardedFor()) . ')' : ''; ?></td> + <td><?= $block->escapeHtml($order->getRemoteIp()); ?><?= $order->getXForwardedFor() ? ' (' . $block->escapeHtml($order->getXForwardedFor()) . ')' : ''; ?></td> </tr> <?php endif; ?> - <?php if ($order->getGlobalCurrencyCode() != $order->getBaseCurrencyCode()): ?> + <?php if ($order->getGlobalCurrencyCode() != $order->getBaseCurrencyCode()) : ?> <tr> <th><?= $block->escapeHtml(__('%1 / %2 rate:', $order->getGlobalCurrencyCode(), $order->getBaseCurrencyCode())) ?></th> <td><?= $block->escapeHtml($order->getBaseToGlobalRate()) ?></td> </tr> <?php endif; ?> - <?php if ($order->getBaseCurrencyCode() != $order->getOrderCurrencyCode()): ?> + <?php if ($order->getBaseCurrencyCode() != $order->getOrderCurrencyCode()) : ?> <tr> <th><?= $block->escapeHtml(__('%1 / %2 rate:', $order->getOrderCurrencyCode(), $order->getBaseCurrencyCode())) ?></th> <td><?= $block->escapeHtml($order->getBaseToOrderRate()) ?></td> @@ -128,18 +125,18 @@ $customerUrl = $block->getCustomerViewUrl(); <tr> <th><?= $block->escapeHtml(__('Customer Name')) ?></th> <td> - <?php if ($customerUrl): ?> + <?php if ($customerUrl) : ?> <a href="<?= $block->escapeUrl($customerUrl) ?>" target="_blank"> <span><?= $block->escapeHtml($order->getCustomerName()) ?></span> </a> - <?php else: ?> + <?php else : ?> <?= $block->escapeHtml($order->getCustomerName()) ?> <?php endif; ?> </td> </tr> <tr> <th><?= $block->escapeHtml(__('Email')) ?></th> - <td><a href="mailto:<?php echo $block->escapeHtml($order->getCustomerEmail()) ?>"><?php echo $block->escapeHtml($order->getCustomerEmail()) ?></a></td> + <td><a href="mailto:<?= $block->escapeHtmlAttr($order->getCustomerEmail()) ?>"><?= $block->escapeHtml($order->getCustomerEmail()) ?></a></td> </tr> <?php if ($groupName = $block->getCustomerGroupName()) : ?> <tr> @@ -147,7 +144,7 @@ $customerUrl = $block->getCustomerViewUrl(); <td><?= $block->escapeHtml($groupName) ?></td> </tr> <?php endif; ?> - <?php foreach ($block->getCustomerAccountData() as $data):?> + <?php foreach ($block->getCustomerAccountData() as $data) : ?> <tr> <th><?= $block->escapeHtml($data['label']) ?></th> <td><?= $block->escapeHtml($data['value'], ['br']) ?></td> @@ -173,7 +170,7 @@ $customerUrl = $block->getCustomerViewUrl(); </div> <address class="admin__page-section-item-content"><?= /* @noEscape */ $block->getFormattedAddress($order->getBillingAddress()); ?></address> </div> - <?php if (!$block->getOrder()->getIsVirtual()): ?> + <?php if (!$block->getOrder()->getIsVirtual()) : ?> <div class="admin__page-section-item order-shipping-address"> <?php /* Shipping Address */ ?> <div class="admin__page-section-item-title"> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/view/items.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/view/items.phtml index dc62bce78ea1e..734ad24b02fcf 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/view/items.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/view/items.phtml @@ -4,9 +4,6 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile -?> -<?php /** * @var \Magento\Sales\Block\Adminhtml\Order\View\Items $block */ @@ -18,19 +15,19 @@ $_order = $block->getOrder() ?> <?php $i = 0; $columns = $block->getColumns(); $lastItemNumber = count($columns) ?> - <?php foreach ($columns as $columnName => $columnTitle):?> + <?php foreach ($columns as $columnName => $columnTitle) : ?> <?php $i++; ?> - <th class="col-<?= /* @noEscape */ $columnName ?><?= /* @noEscape */ ($i === $lastItemNumber ? ' last' : '') ?>"><span><?= /* @noEscape */ $columnTitle ?></span></th> + <th class="col-<?= $block->escapeHtmlAttr($columnName) ?><?= /* @noEscape */ ($i === $lastItemNumber ? ' last' : '') ?>"><span><?= $block->escapeHtml($columnTitle) ?></span></th> <?php endforeach; ?> </tr> </thead> <?php $_items = $block->getItemsCollection();?> - <?php $i = 0; foreach ($_items as $_item):?> - <?php if ($_item->getParentItem()) { + <?php $i = 0; foreach ($_items as $_item) : ?> + <?php if ($_item->getParentItem()) : continue; - } else { + else : $i++; - }?> + endif; ?> <tbody class="<?= /* @noEscape */ $i%2 ? 'even' : 'odd' ?>"> <?= $block->getItemHtml($_item) ?> <?= $block->getItemExtraInfoHtml($_item) ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/view/items/renderer/default.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/view/items/renderer/default.phtml index 387aab3d9616f..c54e23d141e0d 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/view/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/view/items/renderer/default.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var \Magento\Sales\Block\Adminhtml\Order\View\Items\Renderer\DefaultRenderer $block */ ?> <?php $_item = $block->getItem() ?> @@ -14,8 +11,10 @@ <?php $i = 0; $columns = $block->getColumns(); $lastItemNumber = count($columns) ?> - <?php foreach ($columns as $columnName => $columnClass):?> + <?php foreach ($columns as $columnName => $columnClass) : ?> <?php $i++; ?> - <td class="<?= /* @noEscape */ $columnClass ?><?= /* @noEscape */ ($i === $lastItemNumber ? ' last' : '') ?>"><?= /* @escapeNotVerified */ $block->getColumnHtml($_item, $columnName) ?></td> + <td class="<?= /* @noEscape */ $columnClass ?><?= /* @noEscape */ ($i === $lastItemNumber ? ' last' : '') ?>"> + <?= $block->getColumnHtml($_item, $columnName) ?> + </td> <?php endforeach; ?> </tr> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/view/tab/history.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/view/tab/history.phtml index 87feaa857ef0e..0a93d25a7a021 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/view/tab/history.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/view/tab/history.phtml @@ -4,25 +4,24 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/** @var \Magento\Sales\Block\Adminhtml\Order\View\Tab\History $block */ ?> <section class="admin__page-section edit-order-comments"> <ul class="note-list"> - <?php foreach ($block->getFullHistory() as $_item): ?> + <?php foreach ($block->getFullHistory() as $_item) : ?> <li class="note-list-item"> - <span class="note-list-date"><?= /* @escapeNotVerified */ $block->getItemCreatedAt($_item) ?></span> - <span class="note-list-time"><?= /* @escapeNotVerified */ $block->getItemCreatedAt($_item, 'time') ?></span> - <span class="note-list-status"><?= /* @escapeNotVerified */ $block->getItemTitle($_item) ?></span> - <?php if ($block->isItemNotified($_item, false)): ?> + <span class="note-list-date"><?= /* @noEscape */ $block->getItemCreatedAt($_item) ?></span> + <span class="note-list-time"><?= /* @noEscape */ $block->getItemCreatedAt($_item, 'time') ?></span> + <span class="note-list-status"><?= /* @noEscape */ $block->getItemTitle($_item) ?></span> + <?php if ($block->isItemNotified($_item, false)) : ?> <span class="note-list-customer"> - <?= /* @escapeNotVerified */ __('Customer') ?> - <?php if ($block->isCustomerNotificationNotApplicable($_item)): ?> - <span class="note-list-customer-notapplicable"><?= /* @escapeNotVerified */ __('Notification Not Applicable') ?></span> - <?php elseif ($block->isItemNotified($_item)): ?> - <span class="note-list-customer-notified"><?= /* @escapeNotVerified */ __('Notified') ?></span> - <?php else: ?> - <span class="note-list-customer-not-notified"><?= /* @escapeNotVerified */ __('Not Notified') ?></span> + <?= $block->escapeHtml(__('Customer')) ?> + <?php if ($block->isCustomerNotificationNotApplicable($_item)) : ?> + <span class="note-list-customer-notapplicable"><?= $block->escapeHtml(__('Notification Not Applicable')) ?></span> + <?php elseif ($block->isItemNotified($_item)) : ?> + <span class="note-list-customer-notified"><?= $block->escapeHtml(__('Notified')) ?></span> + <?php else : ?> + <span class="note-list-customer-not-notified"><?= $block->escapeHtml(__('Not Notified')) ?></span> <?php endif; ?> </span> <?php endif; ?> @@ -31,18 +30,18 @@ </ul> <div class="edit-order-comments-block"> <div class="edit-order-comments-block-title"> - <?= /* @escapeNotVerified */ __('Notes for this Order') ?> + <?= $block->escapeHtml(__('Notes for this Order')) ?> </div> - <?php foreach ($block->getFullHistory() as $_item): ?> - <?php if ($_comment = $block->getItemComment($_item)): ?> + <?php foreach ($block->getFullHistory() as $_item) : ?> + <?php if ($_comment = $block->getItemComment($_item)) : ?> <div class="comments-block-item"> <div class="comments-block-item-comment"> - <?= /* @escapeNotVerified */ $_comment ?> + <?= /* @noEscape */ $_comment ?> </div> <span class="comments-block-item-date-time"> - <?= /* @escapeNotVerified */ __('Comment added') ?> - <?= /* @escapeNotVerified */ $block->getItemCreatedAt($_item) ?> - <?= /* @escapeNotVerified */ $block->getItemCreatedAt($_item, 'time') ?> + <?= $block->escapeHtml(__('Comment added')) ?> + <?= /* @noEscape */ $block->getItemCreatedAt($_item) ?> + <?= /* @noEscape */ $block->getItemCreatedAt($_item, 'time') ?> </span> </div> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/view/tab/info.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/view/tab/info.phtml index 434ca127832a1..390adb7d5cfce 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/view/tab/info.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/view/tab/info.phtml @@ -4,10 +4,8 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/** @var $block \Magento\Sales\Block\Adminhtml\Order\View\Tab\Info */ ?> -<?php /** @var $block \Magento\Sales\Block\Adminhtml\Order\View\Tab\Info */ ?> <?php $_order = $block->getOrder() ?> <div id="order-messages"> @@ -15,21 +13,21 @@ </div> <?= $block->getChildHtml('order_info') ?> -<input type="hidden" name="order_id" value="<?= /* @escapeNotVerified */ $_order->getId() ?>"/> +<input type="hidden" name="order_id" value="<?= (int) $_order->getId() ?>"/> <section class="admin__page-section order-view-billing-shipping"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment & Shipping Method') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment & Shipping Method')) ?></span> </div> <div class="admin__page-section-content"> - <div class="admin__page-section-item order-payment-method<?php if ($_order->getIsVirtual()): ?> order-payment-method-virtual<?php endif; ?>"> + <div class="admin__page-section-item order-payment-method<?= ($_order->getIsVirtual() ? ' order-payment-method-virtual' : '') ?>"> <?php /* Payment Method */ ?> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Payment Information') ?></span> + <span class="title"><?= $block->escapeHtml(__('Payment Information')) ?></span> </div> <div class="admin__page-section-item-content"> <div class="order-payment-method-title"><?= $block->getPaymentHtml() ?></div> - <div class="order-payment-currency"><?= /* @escapeNotVerified */ __('The order was placed using %1.', $_order->getOrderCurrencyCode()) ?></div> + <div class="order-payment-currency"><?= $block->escapeHtml(__('The order was placed using %1.', $_order->getOrderCurrencyCode())) ?></div> <div class="order-payment-additional"> <?= $block->getChildHtml('order_payment_additional') ?> <?= $block->getChildHtml('payment_additional_info') ?> @@ -46,26 +44,26 @@ <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Items Ordered') ?></span> + <span class="title"><?= $block->escapeHtml(__('Items Ordered')) ?></span> </div> <?= $block->getItemsHtml() ?> </section> <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Order Total') ?></span> + <span class="title"><?= $block->escapeHtml(__('Order Total')) ?></span> </div> <div class="admin__page-section-content"> <div class="admin__page-section-item order-comments-history"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Notes for this Order') ?></span> + <span class="title"><?= $block->escapeHtml(__('Notes for this Order')) ?></span> </div> <?= $block->getChildHtml('order_history') ?> </div> <div class="admin__page-section-item order-totals"> <div class="admin__page-section-item-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Order Totals') ?></span> + <span class="title"><?= $block->escapeHtml(__('Order Totals')) ?></span> </div> <?= $block->getChildHtml('order_totals') ?> </div> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/page/js/components.phtml b/app/code/Magento/Sales/view/adminhtml/templates/page/js/components.phtml index 1194e72e27c62..5902a9f25cc4b 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/page/js/components.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/page/js/components.phtml @@ -1,12 +1,7 @@ <?php /** - * @category design - * @package default_default * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?= $block->getChildHtml() ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/rss/order/grid/link.phtml b/app/code/Magento/Sales/view/adminhtml/templates/rss/order/grid/link.phtml index 872f70d1d693a..231eb274290cf 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/rss/order/grid/link.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/rss/order/grid/link.phtml @@ -4,10 +4,8 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** @var $block \Magento\Sales\Block\Adminhtml\Rss\Order\Grid\Link */ ?> -<?php if ($block->isRssAllowed() && $block->getLink()): ?> -<a href="<?= /* @escapeNotVerified */ $block->getLink() ?>" class="link-feed"><?= /* @escapeNotVerified */ $block->getLabel() ?></a> +<?php if ($block->isRssAllowed() && $block->getLink()) : ?> +<a href="<?= $block->escapeUrl($block->getLink()) ?>" class="link-feed"><?= $block->escapeHtml($block->getLabel()) ?></a> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/transactions/detail.phtml b/app/code/Magento/Sales/view/adminhtml/templates/transactions/detail.phtml index c46ff775f6f9a..01b7548be15cd 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/transactions/detail.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/transactions/detail.phtml @@ -4,35 +4,34 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +/* @var \Magento\Sales\Block\Adminhtml\Transactions\Detail $block */ ?> <div data-mage-init='{"floatingHeader": {}}' class="page-actions"><?= $block->getButtonsHtml() ?></div> <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Transaction Data') ?></span> + <span class="title"><?= $block->escapeHtml(__('Transaction Data')) ?></span> </div> <div id="log_details_fieldset" class="admin__page-section-content log-details"> <table class="log-info data-table admin__table-secondary"> <tbody> <tr> - <th><?= /* @escapeNotVerified */ __('Transaction ID') ?></th> + <th><?= $block->escapeHtml(__('Transaction ID')) ?></th> <td><?= $block->getTxnIdHtml() ?></td> </tr> <tr> - <th><?= /* @escapeNotVerified */ __('Parent Transaction ID') ?></th> + <th><?= $block->escapeHtml(__('Parent Transaction ID')) ?></th> <td> - <?php if ($block->getParentTxnIdHtml()): ?> + <?php if ($block->getParentTxnIdHtml()) : ?> <a href="<?= $block->getParentTxnIdUrlHtml() ?>"> <?= $block->getParentTxnIdHtml() ?> </a> <?php else : ?> - <?= /* @escapeNotVerified */ __('N/A') ?> + <?= $block->escapeHtml(__('N/A')) ?> <?php endif; ?> </td> </tr> <tr> - <th><?= /* @escapeNotVerified */ __('Order ID') ?></th> + <th><?= $block->escapeHtml(__('Order ID')) ?></th> <td> <a href="<?= $block->getOrderIdUrlHtml() ?>"> <?= $block->getOrderIncrementIdHtml() ?> @@ -40,15 +39,15 @@ </td> </tr> <tr> - <th><?= /* @escapeNotVerified */ __('Transaction Type') ?></th> + <th><?= $block->escapeHtml(__('Transaction Type')) ?></th> <td><?= $block->getTxnTypeHtml() ?></td> </tr> <tr> - <th><?= /* @escapeNotVerified */ __('Is Closed') ?></th> + <th><?= $block->escapeHtml(__('Is Closed')) ?></th> <td><?= $block->getIsClosedHtml() ?></td> </tr> <tr> - <th><?= /* @escapeNotVerified */ __('Created At') ?></th> + <th><?= $block->escapeHtml(__('Created At')) ?></th> <td><?= $block->getCreatedAtHtml() ?></td> </tr> </tbody> @@ -58,7 +57,7 @@ <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Child Transactions') ?></span> + <span class="title"><?= $block->escapeHtml(__('Child Transactions')) ?></span> </div> <div class="admin__page-section-content log-details-grid"> <?= $block->getChildHtml('child_grid') ?> @@ -67,7 +66,7 @@ <section class="admin__page-section"> <div class="admin__page-section-title"> - <span class="title"><?= /* @escapeNotVerified */ __('Transaction Details') ?></span> + <span class="title"><?= $block->escapeHtml(__('Transaction Details')) ?></span> </div> <div class="admin__page-section-content log-details-grid"> <?= $block->getChildHtml('detail_grid') ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/creditmemo/items.phtml b/app/code/Magento/Sales/view/frontend/templates/email/creditmemo/items.phtml index 8cef5d57664a9..90c3ddeee5a30 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/creditmemo/items.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/creditmemo/items.phtml @@ -4,28 +4,26 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - ?> <?php $_creditmemo = $block->getCreditmemo() ?> <?php $_order = $block->getOrder() ?> -<?php if ($_creditmemo && $_order): ?> +<?php if ($_creditmemo && $_order) : ?> <table class="email-items"> <thead> <tr> <th class="item-info"> - <?= /* @escapeNotVerified */ __('Items') ?> + <?= $block->escapeHtml(__('Items')) ?> </th> <th class="item-qty"> - <?= /* @escapeNotVerified */ __('Qty') ?> + <?= $block->escapeHtml(__('Qty')) ?> </th> <th class="item-subtotal"> - <?= /* @escapeNotVerified */ __('Subtotal') ?> + <?= $block->escapeHtml(__('Subtotal')) ?> </th> </tr> </thead> - <?php foreach ($_creditmemo->getAllItems() as $_item): ?> - <?php if (!$_item->getOrderItem()->getParentItem()) : ?> + <?php foreach ($_creditmemo->getAllItems() as $_item) : ?> + <?php if (!$_item->getOrderItem()->getParentItem()) : ?> <tbody> <?= $block->getItemHtml($_item) ?> </tbody> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/invoice/items.phtml b/app/code/Magento/Sales/view/frontend/templates/email/invoice/items.phtml index 4c377dea47da2..e2efd650295d4 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/invoice/items.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/invoice/items.phtml @@ -4,27 +4,25 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - ?> <?php $_invoice = $block->getInvoice() ?> <?php $_order = $block->getOrder() ?> -<?php if ($_invoice && $_order): ?> +<?php if ($_invoice && $_order) : ?> <table class="email-items"> <thead> <tr> <th class="item-info"> - <?= /* @escapeNotVerified */ __('Items') ?> + <?= $block->escapeHtml(__('Items')) ?> </th> <th class="item-qty"> - <?= /* @escapeNotVerified */ __('Qty') ?> + <?= $block->escapeHtml(__('Qty')) ?> </th> <th class="item-subtotal"> - <?= /* @escapeNotVerified */ __('Subtotal') ?> + <?= $block->escapeHtml(__('Subtotal')) ?> </th> </tr> </thead> - <?php foreach ($_invoice->getAllItems() as $_item): ?> + <?php foreach ($_invoice->getAllItems() as $_item) : ?> <?php if (!$_item->getOrderItem()->getParentItem()) : ?> <tbody> <?= $block->getItemHtml($_item) ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/items.phtml b/app/code/Magento/Sales/view/frontend/templates/email/items.phtml index 37469582865dc..1bba8166762c7 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/items.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/items.phtml @@ -4,27 +4,28 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate +/** @var $block \Magento\Sales\Block\Order\Email\Items */ ?> <?php $_order = $block->getOrder() ?> -<?php if ($_order): ?> +<?php if ($_order) : ?> <?php $_items = $_order->getAllItems(); ?> <table class="email-items"> <thead> <tr> <th class="item-info"> - <?= /* @escapeNotVerified */ __('Items') ?> + <?= $block->escapeHtml(__('Items')) ?> </th> <th class="item-qty"> - <?= /* @escapeNotVerified */ __('Qty') ?> + <?= $block->escapeHtml(__('Qty')) ?> </th> <th class="item-price"> - <?= /* @escapeNotVerified */ __('Price') ?> + <?= $block->escapeHtml(__('Price')) ?> </th> </tr> </thead> - <?php foreach ($_items as $_item): ?> + <?php foreach ($_items as $_item) : ?> <?php if (!$_item->getParentItem()) : ?> <tbody> <?= $block->getItemHtml($_item) ?> @@ -35,17 +36,21 @@ <?= $block->getChildHtml('order_totals') ?> </tfoot> </table> - <?php if ($this->helper('Magento\GiftMessage\Helper\Message')->isMessagesAllowed('order', $_order, $_order->getStore()) && $_order->getGiftMessageId()): ?> - <?php $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_order->getGiftMessageId()); ?> - <?php if ($_giftMessage): ?> + <?php if ($this->helper(\Magento\GiftMessage\Helper\Message::class) + ->isMessagesAllowed('order', $_order, $_order->getStore()) + && $_order->getGiftMessageId() + ) : ?> + <?php $_giftMessage = $this->helper(\Magento\GiftMessage\Helper\Message::class) + ->getGiftMessage($_order->getGiftMessageId()); ?> + <?php if ($_giftMessage) : ?> <br /> <table class="message-gift"> <tr> <td> - <h3><?= /* @escapeNotVerified */ __('Gift Message for this Order') ?></h3> - <strong><?= /* @escapeNotVerified */ __('From:') ?></strong> <?= $block->escapeHtml($_giftMessage->getSender()) ?> - <br /><strong><?= /* @escapeNotVerified */ __('To:') ?></strong> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?> - <br /><strong><?= /* @escapeNotVerified */ __('Message:') ?></strong> + <h3><?= $block->escapeHtml(__('Gift Message for this Order')) ?></h3> + <strong><?= $block->escapeHtml(__('From:')) ?></strong> <?= $block->escapeHtml($_giftMessage->getSender()) ?> + <br /><strong><?= $block->escapeHtml(__('To:')) ?></strong> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?> + <br /><strong><?= $block->escapeHtml(__('Message:')) ?></strong> <br /><?= $block->escapeHtml($_giftMessage->getMessage()) ?> </td> </tr> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/items/creditmemo/default.phtml b/app/code/Magento/Sales/view/frontend/templates/email/items/creditmemo/default.phtml index 1fca65932b0b0..1066a8dc9b1be 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/items/creditmemo/default.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/items/creditmemo/default.phtml @@ -4,21 +4,19 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - ?> <?php $_item = $block->getItem() ?> <?php $_order = $block->getItem()->getOrder(); ?> <tr> - <td class="item-info<?php if ($block->getItemOptions()): ?> has-extra<?php endif; ?>"> + <td class="item-info<?= ($block->getItemOptions() ? ' has-extra' : '') ?>"> <p class="product-name"><?= $block->escapeHtml($_item->getName()) ?></p> - <p class="sku"><?= /* @escapeNotVerified */ __('SKU') ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> - <?php if ($block->getItemOptions()): ?> + <p class="sku"><?= $block->escapeHtml(__('SKU')) ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> + <?php if ($block->getItemOptions()) : ?> <dl> - <?php foreach ($block->getItemOptions() as $option): ?> - <dt><strong><em><?= /* @escapeNotVerified */ $option['label'] ?></em></strong></dt> + <?php foreach ($block->getItemOptions() as $option) : ?> + <dt><strong><em><?= $block->escapeHtml($option['label']) ?></em></strong></dt> <dd> - <?= /* @escapeNotVerified */ nl2br($option['value']) ?> + <?= /* @noEscape */ nl2br($block->escapeHtml($option['value'])) ?> </dd> <?php endforeach; ?> </dl> @@ -29,8 +27,8 @@ <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="item-qty"><?= /* @escapeNotVerified */ $_item->getQty() * 1 ?></td> + <td class="item-qty"><?= (int) $_item->getQty() ?></td> <td class="item-price"> - <?= /* @escapeNotVerified */ $block->getItemPrice($_item->getOrderItem()) ?> + <?= /* @noEscape */ $block->getItemPrice($_item) ?> </td> </tr> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/items/invoice/default.phtml b/app/code/Magento/Sales/view/frontend/templates/email/items/invoice/default.phtml index 1fca65932b0b0..e0a25ce52068d 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/items/invoice/default.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/items/invoice/default.phtml @@ -3,34 +3,31 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php $_item = $block->getItem() ?> <?php $_order = $block->getItem()->getOrder(); ?> <tr> - <td class="item-info<?php if ($block->getItemOptions()): ?> has-extra<?php endif; ?>"> + <td class="item-info<?= ($block->getItemOptions() ? ' has-extra' : '') ?>"> <p class="product-name"><?= $block->escapeHtml($_item->getName()) ?></p> - <p class="sku"><?= /* @escapeNotVerified */ __('SKU') ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> - <?php if ($block->getItemOptions()): ?> + <p class="sku"><?= $block->escapeHtml(__('SKU')) ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> + <?php if ($block->getItemOptions()) : ?> <dl> - <?php foreach ($block->getItemOptions() as $option): ?> - <dt><strong><em><?= /* @escapeNotVerified */ $option['label'] ?></em></strong></dt> + <?php foreach ($block->getItemOptions() as $option) : ?> + <dt><strong><em><?= $block->escapeHtml($option['label']) ?></em></strong></dt> <dd> - <?= /* @escapeNotVerified */ nl2br($option['value']) ?> + <?= /* @noEscape */ nl2br($block->escapeHtml($option['value'])) ?> </dd> <?php endforeach; ?> </dl> <?php endif; ?> <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?> - <?php if ($addInfoBlock) :?> + <?php if ($addInfoBlock) : ?> <?= $addInfoBlock->setItem($_item->getOrderItem())->toHtml() ?> <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="item-qty"><?= /* @escapeNotVerified */ $_item->getQty() * 1 ?></td> + <td class="item-qty"><?= (int) $_item->getQty() ?></td> <td class="item-price"> - <?= /* @escapeNotVerified */ $block->getItemPrice($_item->getOrderItem()) ?> + <?= /* @noEscape */ $block->getItemPrice($_item->getOrderItem()) ?> </td> </tr> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/items/order/default.phtml b/app/code/Magento/Sales/view/frontend/templates/email/items/order/default.phtml index 2974e4cd7ad80..a39442136e2f0 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/items/order/default.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/items/order/default.phtml @@ -4,7 +4,7 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate /** @var $block \Magento\Sales\Block\Order\Email\Items\DefaultItems */ @@ -13,15 +13,15 @@ $_item = $block->getItem(); $_order = $_item->getOrder(); ?> <tr> - <td class="item-info<?php if ($block->getItemOptions()): ?> has-extra<?php endif; ?>"> + <td class="item-info<?= ($block->getItemOptions() ? ' has-extra' : '') ?>"> <p class="product-name"><?= $block->escapeHtml($_item->getName()) ?></p> - <p class="sku"><?= /* @escapeNotVerified */ __('SKU') ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> - <?php if ($block->getItemOptions()): ?> + <p class="sku"><?= $block->escapeHtml(__('SKU')) ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> + <?php if ($block->getItemOptions()) : ?> <dl class="item-options"> - <?php foreach ($block->getItemOptions() as $option): ?> - <dt><strong><em><?= /* @escapeNotVerified */ $option['label'] ?></em></strong></dt> + <?php foreach ($block->getItemOptions() as $option) : ?> + <dt><strong><em><?= $block->escapeHtml($option['label']) ?></em></strong></dt> <dd> - <?= /* @escapeNotVerified */ nl2br($option['value']) ?> + <?= /* @noEscape */ nl2br($block->escapeHtml($option['value'])) ?> </dd> <?php endforeach; ?> </dl> @@ -32,21 +32,24 @@ $_order = $_item->getOrder(); <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="item-qty"><?= /* @escapeNotVerified */ $_item->getQtyOrdered() * 1 ?></td> + <td class="item-qty"><?= (int) $_item->getQtyOrdered() ?></td> <td class="item-price"> - <?= /* @escapeNotVerified */ $block->getItemPrice($_item) ?> + <?= /* @noEscape */ $block->getItemPrice($_item) ?> </td> </tr> -<?php if ($_item->getGiftMessageId() && $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_item->getGiftMessageId())): ?> -<tr> +<?php if ($_item->getGiftMessageId() + && $_giftMessage = $this->helper(\Magento\GiftMessage\Helper\Message::class) + ->getGiftMessage($_item->getGiftMessageId()) +) : ?> + <tr> <td colspan="3" class="item-extra"> <table class="message-gift"> <tr> <td> - <h3><?= /* @escapeNotVerified */ __('Gift Message') ?></h3> - <strong><?= /* @escapeNotVerified */ __('From:') ?></strong> <?= $block->escapeHtml($_giftMessage->getSender()) ?> - <br /><strong><?= /* @escapeNotVerified */ __('To:') ?></strong> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?> - <br /><strong><?= /* @escapeNotVerified */ __('Message:') ?></strong> + <h3><?= $block->escapeHtml(__('Gift Message')) ?></h3> + <strong><?= $block->escapeHtml(__('From:')) ?></strong> <?= $block->escapeHtml($_giftMessage->getSender()) ?> + <br /><strong><?= $block->escapeHtml(__('To:')) ?></strong> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?> + <br /><strong><?= $block->escapeHtml(__('Message:')) ?></strong> <br /><?= $block->escapeHtml($_giftMessage->getMessage()) ?> </td> </tr> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/items/price/row.phtml b/app/code/Magento/Sales/view/frontend/templates/email/items/price/row.phtml index 106aeb16c2897..a2148a4f8fcb9 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/items/price/row.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/items/price/row.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var \Magento\Sales\Block\Order\Email\Items\DefaultItems $block */ @@ -16,4 +13,4 @@ $_item = $block->getItem(); $_order = $_item->getOrder(); ?> -<?= /* @escapeNotVerified */ $_order->formatPrice($_item->getRowTotal()) ?> +<?= /* @noEscape */ $_order->formatPrice($_item->getRowTotal()) ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/items/shipment/default.phtml b/app/code/Magento/Sales/view/frontend/templates/email/items/shipment/default.phtml index f41a09f5da0f3..3cab6ae1ed993 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/items/shipment/default.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/items/shipment/default.phtml @@ -4,29 +4,27 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** @var $_item \Magento\Sales\Model\Order\Item */ $_item = $block->getItem() ?> <tr> - <td class="item-info<?php if ($block->getItemOptions()): ?> has-extra<?php endif; ?>"> + <td class="item-info<?= ($block->getItemOptions() ? ' has-extra' : '') ?>"> <p class="product-name"><?= $block->escapeHtml($_item->getName()) ?></p> - <p class="sku"><?= /* @escapeNotVerified */ __('SKU') ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> - <?php if ($block->getItemOptions()): ?> + <p class="sku"><?= $block->escapeHtml(__('SKU')) ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> + <?php if ($block->getItemOptions()) : ?> <dl class="item-options"> - <?php foreach ($block->getItemOptions() as $option): ?> - <dt><strong><em><?= /* @escapeNotVerified */ $option['label'] ?></em></strong></dt> + <?php foreach ($block->getItemOptions() as $option) : ?> + <dt><strong><em><?= $block->escapeHtml($option['label']) ?></em></strong></dt> <dd> - <?= /* @escapeNotVerified */ nl2br($option['value']) ?> + <?= /* @noEscape */ nl2br($option['value']) ?> </dd> <?php endforeach; ?> </dl> <?php endif; ?> <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?> - <?php if ($addInfoBlock) :?> + <?php if ($addInfoBlock) : ?> <?= $addInfoBlock->setItem($_item->getOrderItem())->toHtml() ?> <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="item-qty"><?= /* @escapeNotVerified */ $_item->getQty() * 1 ?></td> + <td class="item-qty"><?= (int) $_item->getQty() ?></td> </tr> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/shipment/items.phtml b/app/code/Magento/Sales/view/frontend/templates/email/shipment/items.phtml index 022511ae3cfd0..956705fb7b55d 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/shipment/items.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/shipment/items.phtml @@ -4,24 +4,22 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - ?> <?php $_shipment = $block->getShipment() ?> <?php $_order = $block->getOrder() ?> -<?php if ($_shipment && $_order): ?> +<?php if ($_shipment && $_order) : ?> <table class="email-items"> <thead> <tr> <th class="item-info"> - <?= /* @escapeNotVerified */ __('Items') ?> + <?= $block->escapeHtml(__('Items')) ?> </th> <th class="item-qty"> - <?= /* @escapeNotVerified */ __('Qty') ?> + <?= $block->escapeHtml(__('Qty')) ?> </th> </tr> </thead> - <?php foreach ($_shipment->getAllItems() as $_item): ?> + <?php foreach ($_shipment->getAllItems() as $_item) : ?> <?php if (!$_item->getOrderItem()->getParentItem()) : ?> <tbody> <?= $block->getItemHtml($_item) ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/shipment/track.phtml b/app/code/Magento/Sales/view/frontend/templates/email/shipment/track.phtml index 6de8e42dea583..7b3769b2971e5 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/shipment/track.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/shipment/track.phtml @@ -4,30 +4,30 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - ?> <?php $_shipment = $block->getShipment() ?> -<?php $_order = $block->getOrder() ?> -<?php if ($_shipment && $_order): ?> -<?php $trackCollection = $_order->getTracksCollection($_shipment->getId()) ?> -<?php if ($trackCollection): ?> - <br /> - <table class="shipment-track"> - <thead> - <tr> - <th><?= /* @escapeNotVerified */ __('Shipped By') ?></th> - <th><?= /* @escapeNotVerified */ __('Tracking Number') ?></th> - </tr> - </thead> - <tbody> - <?php foreach ($trackCollection as $_item): ?> +<?php +/* @var \Magento\Sales\Model\Order $_order */ +$_order = $block->getOrder() ?> +<?php if ($_shipment && $_order) : ?> + <?php $trackCollection = $_order->getTracksCollection($_shipment->getId()) ?> + <?php if ($trackCollection) : ?> + <br /> + <table class="shipment-track"> + <thead> <tr> - <td><?= $block->escapeHtml($_item->getTitle()) ?>:</td> - <td><?= $block->escapeHtml($_item->getNumber()) ?></td> + <th><?= $block->escapeHtml(__('Shipped By')) ?></th> + <th><?= $block->escapeHtml(__('Tracking Number')) ?></th> </tr> - <?php endforeach ?> - </tbody> - </table> -<?php endif; ?> + </thead> + <tbody> + <?php foreach ($trackCollection as $_item) : ?> + <tr> + <td><?= $block->escapeHtml($_item->getTitle()) ?>:</td> + <td><?= $block->escapeHtml($_item->getNumber()) ?></td> + </tr> + <?php endforeach ?> + </tbody> + </table> + <?php endif; ?> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/guest/form.phtml b/app/code/Magento/Sales/view/frontend/templates/guest/form.phtml index 89be190588677..a8dd694f13e60 100644 --- a/app/code/Magento/Sales/view/frontend/templates/guest/form.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/guest/form.phtml @@ -4,17 +4,18 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - ?> -<form class="form form-orders-search" id="oar-widget-orders-and-returns-form" data-mage-init='{"ordersReturns":{}, "validation":{}}' action="<?= /* @escapeNotVerified */ $block->getActionUrl() ?>" +<form class="form form-orders-search" + id="oar-widget-orders-and-returns-form" + data-mage-init='{"ordersReturns":{}, "validation":{}}' + action="<?= $block->escapeUrl($block->getActionUrl()) ?>" method="post" name="guest_post"> <fieldset class="fieldset"> - <legend class="legend"><span><?= /* @escapeNotVerified */ __('Order Information') ?></span></legend> + <legend class="legend"><span><?= $block->escapeHtml(__('Order Information')) ?></span></legend> <br> <div class="field id required"> - <label class="label" for="oar-order-id"><span><?= /* @escapeNotVerified */ __('Order ID') ?></span></label> + <label class="label" for="oar-order-id"><span><?= $block->escapeHtml(__('Order ID')) ?></span></label> <div class="control"> <input type="text" class="input-text" id="oar-order-id" name="oar_order_id" @@ -22,7 +23,7 @@ </div> </div> <div class="field lastname required"> - <label class="label" for="oar-billing-lastname"><span><?= /* @escapeNotVerified */ __('Billing Last Name') ?></span></label> + <label class="label" for="oar-billing-lastname"><span><?= $block->escapeHtml(__('Billing Last Name')) ?></span></label> <div class="control"> <input type="text" class="input-text" id="oar-billing-lastname" name="oar_billing_lastname" @@ -30,17 +31,17 @@ </div> </div> <div class="field find required"> - <label class="label" for="quick-search-type-id"><span><?= /* @escapeNotVerified */ __('Find Order By') ?></span></label> + <label class="label" for="quick-search-type-id"><span><?= $block->escapeHtml(__('Find Order By')) ?></span></label> <div class="control"> <select name="oar_type" id="quick-search-type-id" class="select"> - <option value="email"><?= /* @escapeNotVerified */ __('Email') ?></option> - <option value="zip"><?= /* @escapeNotVerified */ __('ZIP Code') ?></option> + <option value="email"><?= $block->escapeHtml(__('Email')) ?></option> + <option value="zip"><?= $block->escapeHtml(__('ZIP Code')) ?></option> </select> </div> </div> <div id="oar-email" class="field email required"> - <label class="label" for="oar_email"><span><?= /* @escapeNotVerified */ __('Email') ?></span></label> + <label class="label" for="oar_email"><span><?= $block->escapeHtml(__('Email')) ?></span></label> <div class="control"> <input type="email" class="input-text" id="oar_email" name="oar_email" @@ -48,7 +49,7 @@ </div> </div> <div id="oar-zip" class="field zip required"> - <label class="label" for="oar_zip"><span><?= /* @escapeNotVerified */ __('Billing ZIP Code') ?></span></label> + <label class="label" for="oar_zip"><span><?= $block->escapeHtml(__('Billing ZIP Code')) ?></span></label> <div class="control"> <input type="text" class="input-text" id="oar_zip" name="oar_zip" data-validate="{required:true}"/> @@ -57,8 +58,8 @@ </fieldset> <div class="actions-toolbar"> <div class="primary"> - <button type="submit" title="<?= /* @escapeNotVerified */ __('Continue') ?>" class="action submit primary"> - <span><?= /* @escapeNotVerified */ __('Continue') ?></span> + <button type="submit" title="<?= $block->escapeHtml(__('Continue')) ?>" class="action submit primary"> + <span><?= $block->escapeHtml(__('Continue')) ?></span> </button> </div> </div> diff --git a/app/code/Magento/Sales/view/frontend/templates/items/price/row.phtml b/app/code/Magento/Sales/view/frontend/templates/items/price/row.phtml index bcf740307af15..73350c5b0c47f 100644 --- a/app/code/Magento/Sales/view/frontend/templates/items/price/row.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/items/price/row.phtml @@ -4,13 +4,11 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** @var \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer $block */ $_item = $block->getItem(); ?> <span class="price-excluding-tax" data-label="<?= $block->escapeHtml(__('Excl. Tax')) ?>"> <span class="cart-price"> - <?= /* @escapeNotVerified */ $block->getOrder()->formatPrice($block->getItem()->getRowTotal()) ?> + <?= /* @noEscape */ $block->getOrder()->formatPrice($block->getItem()->getRowTotal()) ?> </span> </span> diff --git a/app/code/Magento/Sales/view/frontend/templates/items/price/total_after_discount.phtml b/app/code/Magento/Sales/view/frontend/templates/items/price/total_after_discount.phtml index dfb476ee381c1..493f30fba59ba 100644 --- a/app/code/Magento/Sales/view/frontend/templates/items/price/total_after_discount.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/items/price/total_after_discount.phtml @@ -4,10 +4,10 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** @var \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer $block */ $_item = $block->getItem(); ?> -<?php $_order = $block->getItem()->getOrderItem()->getOrder() ?> -<?= /* @escapeNotVerified */ $_order->formatPrice($block->getTotalAmount($_item)) ?> +<?php +/** @var \Magento\Sales\Model\Order $_order */ +$_order = $block->getItem()->getOrderItem()->getOrder() ?> +<?= /* @noEscape */ $_order->formatPrice($block->getTotalAmount($_item)) ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/items/price/unit.phtml b/app/code/Magento/Sales/view/frontend/templates/items/price/unit.phtml index 7a484fed719f8..1b2f15133da8c 100644 --- a/app/code/Magento/Sales/view/frontend/templates/items/price/unit.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/items/price/unit.phtml @@ -4,13 +4,11 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** @var \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer $block */ $_item = $block->getItem(); ?> <span class="price-excluding-tax" data-label="<?= $block->escapeHtml(__('Excl. Tax')) ?>"> <span class="cart-price"> - <?= /* @escapeNotVerified */ $block->getOrder()->formatPrice($block->getItem()->getPrice()) ?> + <?= /* @noEscape */ $block->getOrder()->formatPrice($block->getItem()->getPrice()) ?> </span> </span> diff --git a/app/code/Magento/Sales/view/frontend/templates/js/components.phtml b/app/code/Magento/Sales/view/frontend/templates/js/components.phtml index bad5acc209b5f..5902a9f25cc4b 100644 --- a/app/code/Magento/Sales/view/frontend/templates/js/components.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/js/components.phtml @@ -3,8 +3,5 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?= $block->getChildHtml() ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/comments.phtml b/app/code/Magento/Sales/view/frontend/templates/order/comments.phtml index 589b857239971..448ced1d35f8f 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/comments.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/comments.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @@ -13,12 +10,15 @@ * @see \Magento\Sales\Block\Order\Comments */ ?> -<?php if ($block->hasComments()):?> +<?php if ($block->hasComments()) : ?> <div class="order additional details comments"> - <h3 class="subtitle"><?= /* @escapeNotVerified */ $block->getTitle() ?></h3> + <h3 class="subtitle"><?= $block->escapeHtml($block->getTitle()) ?></h3> <dl class="order comments"> - <?php foreach ($block->getComments() as $_commentItem): ?> - <dt class="comment date"><?= /* @escapeNotVerified */ $block->formatDate($_commentItem->getCreatedAt(), \IntlDateFormatter::MEDIUM, true) ?></dt> + <?php foreach ($block->getComments() as $_commentItem) : ?> + <dt class="comment date"> + <?= /* @noEscape */ + $block->formatDate($_commentItem->getCreatedAt(), \IntlDateFormatter::MEDIUM, true) ?> + </dt> <dd class="comment text"><?= $block->escapeHtml($_commentItem->getComment()) ?></dd> <?php endforeach; ?> </dl> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/creditmemo.phtml b/app/code/Magento/Sales/view/frontend/templates/order/creditmemo.phtml index a6a9b64d2c784..3d8853bbe0366 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/creditmemo.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/creditmemo.phtml @@ -3,13 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +/* @var $block \Magento\Sales\Block\Order\Creditmemo */ ?> <div class="order-details-items creditmemo"> <?= $block->getChildHtml('creditmemo_items') ?> <div class="actions-toolbar"> <div class="secondary"> - <a href="<?= /* @escapeNotVerified */ $block->getBackUrl() ?>" class="action back"> - <span><?= /* @escapeNotVerified */ $block->getBackTitle() ?></span> + <a href="<?= $block->escapeUrl($block->getBackUrl()) ?>" class="action back"> + <span><?= $block->escapeHtml($block->getBackTitle()) ?></span> </a> </div> </div> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/creditmemo/items.phtml b/app/code/Magento/Sales/view/frontend/templates/order/creditmemo/items.phtml index dc2cf2433ac8d..019baeea54e23 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/creditmemo/items.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/creditmemo/items.phtml @@ -3,54 +3,51 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php $_order = $block->getOrder() ?> <div class="actions-toolbar"> - <a href="<?= /* @escapeNotVerified */ $block->getPrintAllCreditmemosUrl($_order) ?>" + <a href="<?= $block->escapeUrl($block->getPrintAllCreditmemosUrl($_order)) ?>" onclick="this.target='_blank'" class="action print"> - <span><?= /* @escapeNotVerified */ __('Print All Refunds') ?></span> - </a> -</div> -<?php foreach ($_order->getCreditmemosCollection() as $_creditmemo): ?> -<div class="order-title"> - <strong><?= /* @escapeNotVerified */ __('Refund #') ?><?= /* @escapeNotVerified */ $_creditmemo->getIncrementId() ?> </strong> - <a href="<?= /* @escapeNotVerified */ $block->getPrintCreditmemoUrl($_creditmemo) ?>" - onclick="this.target='_blank'" - class="action print"> - <span><?= /* @escapeNotVerified */ __('Print Refund') ?></span> + <span><?= $block->escapeHtml(__('Print All Refunds')) ?></span> </a> </div> +<?php foreach ($_order->getCreditmemosCollection() as $_creditmemo) : ?> + <div class="order-title"> + <strong><?= $block->escapeHtml(__('Refund #')) ?><?= $block->escapeHtml($_creditmemo->getIncrementId()) ?> </strong> + <a href="<?= $block->escapeUrl($block->getPrintCreditmemoUrl($_creditmemo)) ?>" + onclick="this.target='_blank'" + class="action print"> + <span><?= $block->escapeHtml(__('Print Refund')) ?></span> + </a> + </div> -<div class="table-wrapper order-items-creditmemo"> - <table class="data table table-order-items creditmemo" id="my-refund-table-<?= /* @escapeNotVerified */ $_creditmemo->getId() ?>"> - <caption class="table-caption"><?= /* @escapeNotVerified */ __('Items Refunded') ?></caption> - <thead> - <tr> - <th class="col name"><?= /* @escapeNotVerified */ __('Product Name') ?></th> - <th class="col sku"><?= /* @escapeNotVerified */ __('SKU') ?></th> - <th class="col price"><?= /* @escapeNotVerified */ __('Price') ?></th> - <th class="col qty"><?= /* @escapeNotVerified */ __('Qty') ?></th> - <th class="col subtotal"><?= /* @escapeNotVerified */ __('Subtotal') ?></th> - <th class="col discount"><?= /* @escapeNotVerified */ __('Discount Amount') ?></th> - <th class="col total"><?= /* @escapeNotVerified */ __('Row Total') ?></th> - </tr> - </thead> - <?php $_items = $_creditmemo->getAllItems(); ?> - <?php foreach ($_items as $_item): ?> - <?php if (!$_item->getOrderItem()->getParentItem()): ?> - <tbody> - <?= $block->getItemHtml($_item) ?> - </tbody> - <?php endif; ?> - <?php endforeach; ?> - <tfoot> - <?= $block->getTotalsHtml($_creditmemo) ?> - </tfoot> - </table> -</div> -<?= $block->getCommentsHtml($_creditmemo) ?> + <div class="table-wrapper order-items-creditmemo"> + <table class="data table table-order-items creditmemo" id="my-refund-table-<?= (int) $_creditmemo->getId() ?>"> + <caption class="table-caption"><?= $block->escapeHtml(__('Items Refunded')) ?></caption> + <thead> + <tr> + <th class="col name"><?= $block->escapeHtml(__('Product Name')) ?></th> + <th class="col sku"><?= $block->escapeHtml(__('SKU')) ?></th> + <th class="col price"><?= $block->escapeHtml(__('Price')) ?></th> + <th class="col qty"><?= $block->escapeHtml(__('Qty')) ?></th> + <th class="col subtotal"><?= $block->escapeHtml(__('Subtotal')) ?></th> + <th class="col discount"><?= $block->escapeHtml(__('Discount Amount')) ?></th> + <th class="col total"><?= $block->escapeHtml(__('Row Total')) ?></th> + </tr> + </thead> + <?php $_items = $_creditmemo->getAllItems(); ?> + <?php foreach ($_items as $_item) : ?> + <?php if (!$_item->getOrderItem()->getParentItem()) : ?> + <tbody> + <?= $block->getItemHtml($_item) ?> + </tbody> + <?php endif; ?> + <?php endforeach; ?> + <tfoot> + <?= $block->getTotalsHtml($_creditmemo) ?> + </tfoot> + </table> + </div> + <?= $block->getCommentsHtml($_creditmemo) ?> <?php endforeach; ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/creditmemo/items/renderer/default.phtml b/app/code/Magento/Sales/view/frontend/templates/order/creditmemo/items/renderer/default.phtml index 5542439da17fd..27e7715c2dc33 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/creditmemo/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/creditmemo/items/renderer/default.phtml @@ -3,45 +3,44 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var $block \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer */ ?> <?php $_item = $block->getItem() ?> <?php $_order = $block->getItem()->getOrderItem()->getOrder() ?> -<tr id="order-item-row-<?= /* @escapeNotVerified */ $_item->getId() ?>"> - <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> +<tr id="order-item-row-<?= (int) $_item->getId() ?>"> + <td class="col name" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> - <?php if ($_options = $block->getItemOptions()): ?> - <dl class="item-options"> - <?php foreach ($_options as $_option) : ?> - <dt><?= $block->escapeHtml($_option['label']) ?></dt> - <?php if (!$block->getPrintStatus()): ?> - <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> - <dd<?php if (isset($_formatedOptionValue['full_view'])): ?> class="tooltip wrapper"<?php endif; ?>> - <?= /* @escapeNotVerified */ $_formatedOptionValue['value'] ?> - <?php if (isset($_formatedOptionValue['full_view'])): ?> - <div class="tooltip content"> - <dl class="item options"> - <dt><?= $block->escapeHtml($_option['label']) ?></dt> - <dd><?= /* @escapeNotVerified */ $_formatedOptionValue['full_view'] ?></dd> - </dl> - </div> - <?php endif; ?> - </dd> - <?php else: ?> - <dd><?= $block->escapeHtml((isset($_option['print_value']) ? $_option['print_value'] : $_option['value'])) ?></dd> - <?php endif; ?> - <?php endforeach; ?> - </dl> + <?php if ($_options = $block->getItemOptions()) : ?> + <dl class="item-options"> + <?php foreach ($_options as $_option) : ?> + <dt><?= $block->escapeHtml($_option['label']) ?></dt> + <?php if (!$block->getPrintStatus()) : ?> + <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> + <dd<?= (isset($_formatedOptionValue['full_view']) ? ' class="tooltip wrapper"' : '') ?>> + <?= $block->escapeHtml($_formatedOptionValue['value']) ?> + <?php if (isset($_formatedOptionValue['full_view'])) : ?> + <div class="tooltip content"> + <dl class="item options"> + <dt><?= $block->escapeHtml($_option['label']) ?></dt> + <dd><?= $block->escapeHtml($_formatedOptionValue['full_view']) ?></dd> + </dl> + </div> + <?php endif; ?> + </dd> + <?php else : ?> + <dd> + <?= $block->escapeHtml($_option['print_value'] ?? $_option['value']) ?> + </dd> + <?php endif; ?> + <?php endforeach; ?> + </dl> <?php endif; ?> <?php /* downloadable */ ?> - <?php if ($links = $block->getLinks()): ?> + <?php if ($links = $block->getLinks()) : ?> <dl class="item options"> - <dt><?= /* @escapeNotVerified */ $block->getLinksTitle() ?></dt> - <?php foreach ($links->getPurchasedItems() as $link): ?> + <dt><?= $block->escapeHtml($block->getLinksTitle()) ?></dt> + <?php foreach ($links->getPurchasedItems() as $link) : ?> <dd><?= $block->escapeHtml($link->getLinkTitle()) ?></dd> <?php endforeach; ?> </dl> @@ -49,20 +48,20 @@ <?php /* EOF downloadable */ ?> <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?> - <?php if ($addInfoBlock) :?> + <?php if ($addInfoBlock) : ?> <?= $addInfoBlock->setItem($_item->getOrderItem())->toHtml() ?> <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @escapeNotVerified */ $block->prepareSku($block->getSku()) ?></td> + <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> <?= $block->getItemPriceHtml() ?> </td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"><?= /* @escapeNotVerified */ $_item->getQty()*1 ?></td> + <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"><?= (int) $_item->getQty() ?></td> <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> <?= $block->getItemRowTotalHtml() ?> </td> - <td class="col discount" data-th="<?= $block->escapeHtml(__('Discount Amount')) ?>"><?= /* @escapeNotVerified */ $_order->formatPrice(-$_item->getDiscountAmount()) ?></td> + <td class="col discount" data-th="<?= $block->escapeHtml(__('Discount Amount')) ?>"><?= /* @noEscape */ $_order->formatPrice(-$_item->getDiscountAmount()) ?></td> <td class="col total" data-th="<?= $block->escapeHtml(__('Row Total')) ?>"> <?= $block->getItemRowTotalAfterDiscountHtml() ?> </td> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/history.phtml b/app/code/Magento/Sales/view/frontend/templates/order/history.phtml index 1c02a5c31ea6b..ef56ad69dcb1b 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/history.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/history.phtml @@ -4,49 +4,50 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate +/** @var \Magento\Sales\Block\Order\History $block */ ?> <?php $_orders = $block->getOrders(); ?> <?= $block->getChildHtml('info') ?> -<?php if ($_orders && count($_orders)): ?> +<?php if ($_orders && count($_orders)) : ?> <div class="table-wrapper orders-history"> <table class="data table table-order-items history" id="my-orders-table"> - <caption class="table-caption"><?= /* @escapeNotVerified */ __('Orders') ?></caption> + <caption class="table-caption"><?= $block->escapeHtml(__('Orders')) ?></caption> <thead> <tr> - <th scope="col" class="col id"><?= /* @escapeNotVerified */ __('Order #') ?></th> - <th scope="col" class="col date"><?= /* @escapeNotVerified */ __('Date') ?></th> - <?= /* @noEscape */ $block->getChildHtml('extra.column.header') ?> - <th scope="col" class="col shipping"><?= /* @escapeNotVerified */ __('Ship To') ?></th> - <th scope="col" class="col total"><?= /* @escapeNotVerified */ __('Order Total') ?></th> - <th scope="col" class="col status"><?= /* @escapeNotVerified */ __('Status') ?></th> - <th scope="col" class="col actions"><?= /* @escapeNotVerified */ __('Action') ?></th> + <th scope="col" class="col id"><?= $block->escapeHtml(__('Order #')) ?></th> + <th scope="col" class="col date"><?= $block->escapeHtml(__('Date')) ?></th> + <?= $block->getChildHtml('extra.column.header') ?> + <th scope="col" class="col shipping"><?= $block->escapeHtml(__('Ship To')) ?></th> + <th scope="col" class="col total"><?= $block->escapeHtml(__('Order Total')) ?></th> + <th scope="col" class="col status"><?= $block->escapeHtml(__('Status')) ?></th> + <th scope="col" class="col actions"><?= $block->escapeHtml(__('Action')) ?></th> </tr> </thead> <tbody> - <?php foreach ($_orders as $_order): ?> + <?php foreach ($_orders as $_order) : ?> <tr> - <td data-th="<?= $block->escapeHtml(__('Order #')) ?>" class="col id"><?= /* @escapeNotVerified */ $_order->getRealOrderId() ?></td> - <td data-th="<?= $block->escapeHtml(__('Date')) ?>" class="col date"><?= /* @escapeNotVerified */ $block->formatDate($_order->getCreatedAt()) ?></td> + <td data-th="<?= $block->escapeHtml(__('Order #')) ?>" class="col id"><?= $block->escapeHtml($_order->getRealOrderId()) ?></td> + <td data-th="<?= $block->escapeHtml(__('Date')) ?>" class="col date"><?= /* @noEscape */ $block->formatDate($_order->getCreatedAt()) ?></td> <?php $extra = $block->getChildBlock('extra.container'); ?> - <?php if ($extra): ?> + <?php if ($extra) : ?> <?php $extra->setOrder($_order); ?> - <?= /* @noEscape */ $extra->getChildHtml() ?> + <?= $extra->getChildHtml() ?> <?php endif; ?> <td data-th="<?= $block->escapeHtml(__('Ship To')) ?>" class="col shipping"><?= $_order->getShippingAddress() ? $block->escapeHtml($_order->getShippingAddress()->getName()) : ' ' ?></td> - <td data-th="<?= $block->escapeHtml(__('Order Total')) ?>" class="col total"><?= /* @escapeNotVerified */ $_order->formatPrice($_order->getGrandTotal()) ?></td> - <td data-th="<?= $block->escapeHtml(__('Status')) ?>" class="col status"><?= /* @escapeNotVerified */ $_order->getStatusLabel() ?></td> + <td data-th="<?= $block->escapeHtml(__('Order Total')) ?>" class="col total"><?= /* @noEscape */ $_order->formatPrice($_order->getGrandTotal()) ?></td> + <td data-th="<?= $block->escapeHtml(__('Status')) ?>" class="col status"><?= $block->escapeHtml($_order->getStatusLabel()) ?></td> <td data-th="<?= $block->escapeHtml(__('Actions')) ?>" class="col actions"> - <a href="<?= /* @escapeNotVerified */ $block->getViewUrl($_order) ?>" class="action view"> - <span><?= /* @escapeNotVerified */ __('View Order') ?></span> + <a href="<?= $block->escapeUrl($block->getViewUrl($_order)) ?>" class="action view"> + <span><?= $block->escapeHtml(__('View Order')) ?></span> </a> - <?php if ($this->helper('Magento\Sales\Helper\Reorder')->canReorder($_order->getEntityId())) : ?> - <a href="#" data-post='<?php /* @escapeNotVerified */ echo + <?php if ($this->helper(\Magento\Sales\Helper\Reorder::class)->canReorder($_order->getEntityId())) : ?> + <a href="#" data-post='<?= /* @noEscape */ $this->helper(\Magento\Framework\Data\Helper\PostHelper::class) ->getPostData($block->getReorderUrl($_order)) ?>' class="action order"> - <span><?= /* @escapeNotVerified */ __('Reorder') ?></span> + <span><?= $block->escapeHtml(__('Reorder')) ?></span> </a> <?php endif ?> </td> @@ -55,9 +56,9 @@ </tbody> </table> </div> - <?php if ($block->getPagerHtml()): ?> + <?php if ($block->getPagerHtml()) : ?> <div class="order-products-toolbar toolbar bottom"><?= $block->getPagerHtml() ?></div> <?php endif ?> -<?php else: ?> - <div class="message info empty"><span><?= /* @escapeNotVerified */ __('You have placed no orders.') ?></span></div> +<?php else : ?> + <div class="message info empty"><span><?= $block->escapeHtml(__('You have placed no orders.')) ?></span></div> <?php endif ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/info.phtml b/app/code/Magento/Sales/view/frontend/templates/order/info.phtml index 2a31814d9a054..1bf05f4fed7f7 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/info.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/info.phtml @@ -3,50 +3,47 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var $block \Magento\Sales\Block\Order\Info */ ?> <?php $_order = $block->getOrder() ?> <div class="block block-order-details-view"> <div class="block-title"> - <strong><?= /* @escapeNotVerified */ __('Order Information') ?></strong> + <strong><?= $block->escapeHtml(__('Order Information')) ?></strong> </div> <div class="block-content"> - <?php if (!$_order->getIsVirtual()): ?> - <div class="box box-order-shipping-address"> - <strong class="box-title"><span><?= /* @escapeNotVerified */ __('Shipping Address') ?></span></strong> - <div class="box-content"> - <address><?= /* @escapeNotVerified */ $block->getFormattedAddress($_order->getShippingAddress()) ?></address> + <?php if (!$_order->getIsVirtual()) : ?> + <div class="box box-order-shipping-address"> + <strong class="box-title"><span><?= $block->escapeHtml(__('Shipping Address')) ?></span></strong> + <div class="box-content"> + <address><?= /* @noEscape */ $block->getFormattedAddress($_order->getShippingAddress()) ?></address> + </div> </div> - </div> - <div class="box box-order-shipping-method"> - <strong class="box-title"> - <span><?= /* @escapeNotVerified */ __('Shipping Method') ?></span> - </strong> - <div class="box-content"> - <?php if ($_order->getShippingDescription()): ?> - <?= $block->escapeHtml($_order->getShippingDescription()) ?> - <?php else: ?> - <?= /* @escapeNotVerified */ __('No shipping information available') ?> - <?php endif; ?> + <div class="box box-order-shipping-method"> + <strong class="box-title"> + <span><?= $block->escapeHtml(__('Shipping Method')) ?></span> + </strong> + <div class="box-content"> + <?php if ($_order->getShippingDescription()) : ?> + <?= $block->escapeHtml($_order->getShippingDescription()) ?> + <?php else : ?> + <?= $block->escapeHtml(__('No shipping information available')) ?> + <?php endif; ?> + </div> </div> - </div> - <?php endif; ?> + <?php endif; ?> <div class="box box-order-billing-address"> <strong class="box-title"> - <span><?= /* @escapeNotVerified */ __('Billing Address') ?></span> + <span><?= $block->escapeHtml(__('Billing Address')) ?></span> </strong> <div class="box-content"> - <address><?= /* @escapeNotVerified */ $block->getFormattedAddress($_order->getBillingAddress()) ?></address> + <address><?= /* @noEscape */ $block->getFormattedAddress($_order->getBillingAddress()) ?></address> </div> </div> <div class="box box-order-billing-method"> <strong class="box-title"> - <span><?= /* @escapeNotVerified */ __('Payment Method') ?></span> + <span><?= $block->escapeHtml(__('Payment Method')) ?></span> </strong> <div class="box-content"> <?= $block->getPaymentInfoHtml() ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/info/buttons.phtml b/app/code/Magento/Sales/view/frontend/templates/order/info/buttons.phtml index fa3f63b61cd07..6b87d3c22331c 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/info/buttons.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/info/buttons.phtml @@ -4,23 +4,22 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +// phpcs:disable Magento2.Templates.ThisInTemplate ?> <div class="actions"> - <?php $_order = $block->getOrder() ?> - <?php if ($this->helper('Magento\Sales\Helper\Reorder')->canReorder($_order->getEntityId())) : ?> - <a href="#" data-post='<?php /* @escapeNotVerified */ echo - $this->helper(\Magento\Framework\Data\Helper\PostHelper::class) + <?php $_order = $block->getOrder() ?> + <?php if ($this->helper(\Magento\Sales\Helper\Reorder::class)->canReorder($_order->getEntityId())) : ?> + <a href="#" data-post='<?= + /* @noEscape */ $this->helper(\Magento\Framework\Data\Helper\PostHelper::class) ->getPostData($block->getReorderUrl($_order)) ?>' class="action order"> - <span><?= /* @escapeNotVerified */ __('Reorder') ?></span> + <span><?= $block->escapeHtml(__('Reorder')) ?></span> </a> <?php endif ?> <a class="action print" - href="<?= /* @escapeNotVerified */ $block->getPrintUrl($_order) ?>" + href="<?= $block->escapeUrl($block->getPrintUrl($_order)) ?>" onclick="this.target='_blank';"> - <span><?= /* @escapeNotVerified */ __('Print Order') ?></span> + <span><?= $block->escapeHtml(__('Print Order')) ?></span> </a> <?= $block->getChildHtml() ?> </div> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/info/buttons/rss.phtml b/app/code/Magento/Sales/view/frontend/templates/order/info/buttons/rss.phtml index 3ea1bf6452c03..e29d1aa1f849f 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/info/buttons/rss.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/info/buttons/rss.phtml @@ -4,12 +4,10 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** @var $block \Magento\Sales\Block\Order\Info\Buttons\Rss */ ?> -<?php if ($block->isRssAllowed() && $block->getLink()): ?> -<a href="<?= /* @escapeNotVerified */ $block->getLink() ?>" class="action rss"> - <span><?= /* @escapeNotVerified */ $block->getLabel() ?></span> -</a> +<?php if ($block->isRssAllowed() && $block->getLink()) : ?> + <a href="<?= $block->escapeHtmlAttr($block->getLink()) ?>" class="action rss"> + <span><?= $block->escapeHtml($block->getLabel()) ?></span> + </a> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/invoice.phtml b/app/code/Magento/Sales/view/frontend/templates/order/invoice.phtml index 699067dc9612c..017331ad72b76 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/invoice.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/invoice.phtml @@ -3,13 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +/* @var $block \Magento\Sales\Block\Order\Invoice */ ?> <div class="order-details-items invoice"> <?= $block->getChildHtml('invoice_items') ?> <div class="actions-toolbar"> <div class="secondary"> - <a href="<?= /* @escapeNotVerified */ $block->getBackUrl() ?>" class="action back"> - <span><?= /* @escapeNotVerified */ $block->getBackTitle() ?></span> + <a href="<?= $block->escapeUrl($block->getBackUrl()) ?>" class="action back"> + <span><?= $block->escapeHtml($block->getBackTitle()) ?></span> </a> </div> </div> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/invoice/items.phtml b/app/code/Magento/Sales/view/frontend/templates/order/invoice/items.phtml index 0f3236ec25bc3..419060bfba713 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/invoice/items.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/invoice/items.phtml @@ -3,51 +3,48 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php $_order = $block->getOrder() ?> <div class="actions-toolbar"> - <a href="<?= /* @escapeNotVerified */ $block->getPrintAllInvoicesUrl($_order) ?>" + <a href="<?= $block->escapeUrl($block->getPrintAllInvoicesUrl($_order)) ?>" target="_blank" class="action print"> - <span><?= /* @escapeNotVerified */ __('Print All Invoices') ?></span> + <span><?= $block->escapeHtml(__('Print All Invoices')) ?></span> </a> </div> -<?php foreach ($_order->getInvoiceCollection() as $_invoice): ?> -<div class="order-title"> - <strong><?= /* @escapeNotVerified */ __('Invoice #') ?><?= /* @escapeNotVerified */ $_invoice->getIncrementId() ?></strong> - <a href="<?= /* @escapeNotVerified */ $block->getPrintInvoiceUrl($_invoice) ?>" - onclick="this.target='_blank'" - class="action print"> - <span><?= /* @escapeNotVerified */ __('Print Invoice') ?></span> - </a> -</div> -<div class="table-wrapper table-order-items invoice"> - <table class="data table table-order-items invoice" id="my-invoice-table-<?= /* @escapeNotVerified */ $_invoice->getId() ?>"> - <caption class="table-caption"><?= /* @escapeNotVerified */ __('Items Invoiced') ?></caption> - <thead> - <tr> - <th class="col name"><?= /* @escapeNotVerified */ __('Product Name') ?></th> - <th class="col sku"><?= /* @escapeNotVerified */ __('SKU') ?></th> - <th class="col price"><?= /* @escapeNotVerified */ __('Price') ?></th> - <th class="col qty"><?= /* @escapeNotVerified */ __('Qty Invoiced') ?></th> - <th class="col subtotal"><?= /* @escapeNotVerified */ __('Subtotal') ?></th> - </tr> - </thead> - <?php $_items = $_invoice->getAllItems(); ?> - <?php foreach ($_items as $_item): ?> - <?php if (!$_item->getOrderItem()->getParentItem()) : ?> - <tbody> - <?= $block->getItemHtml($_item) ?> - </tbody> - <?php endif; ?> - <?php endforeach; ?> - <tfoot> - <?= $block->getInvoiceTotalsHtml($_invoice) ?> - </tfoot> - </table> -</div> -<?= $block->getInvoiceCommentsHtml($_invoice) ?> +<?php foreach ($_order->getInvoiceCollection() as $_invoice) : ?> + <div class="order-title"> + <strong><?= $block->escapeHtml(__('Invoice #')) ?><?= $block->escapeHtml($_invoice->getIncrementId()) ?></strong> + <a href="<?= $block->escapeUrl($block->getPrintInvoiceUrl($_invoice)) ?>" + onclick="this.target='_blank'" + class="action print"> + <span><?= $block->escapeHtml(__('Print Invoice')) ?></span> + </a> + </div> + <div class="table-wrapper table-order-items invoice"> + <table class="data table table-order-items invoice" id="my-invoice-table-<?= (int) $_invoice->getId() ?>"> + <caption class="table-caption"><?= $block->escapeHtml(__('Items Invoiced')) ?></caption> + <thead> + <tr> + <th class="col name"><?= $block->escapeHtml(__('Product Name')) ?></th> + <th class="col sku"><?= $block->escapeHtml(__('SKU')) ?></th> + <th class="col price"><?= $block->escapeHtml(__('Price')) ?></th> + <th class="col qty"><?= $block->escapeHtml(__('Qty Invoiced')) ?></th> + <th class="col subtotal"><?= $block->escapeHtml(__('Subtotal')) ?></th> + </tr> + </thead> + <?php $_items = $_invoice->getAllItems(); ?> + <?php foreach ($_items as $_item) : ?> + <?php if (!$_item->getOrderItem()->getParentItem()) : ?> + <tbody> + <?= $block->getItemHtml($_item) ?> + </tbody> + <?php endif; ?> + <?php endforeach; ?> + <tfoot> + <?= $block->getInvoiceTotalsHtml($_invoice) ?> + </tfoot> + </table> + </div> + <?= $block->getInvoiceCommentsHtml($_invoice) ?> <?php endforeach; ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/invoice/items/renderer/default.phtml b/app/code/Magento/Sales/view/frontend/templates/order/invoice/items/renderer/default.phtml index 4f95f3d93e2c2..ece72e9119d1e 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/invoice/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/invoice/items/renderer/default.phtml @@ -3,38 +3,35 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var $block \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer */ ?> <?php $_item = $block->getItem() ?> <?php $_order = $block->getItem()->getOrderItem()->getOrder() ?> -<tr id="order-item-row-<?= /* @escapeNotVerified */ $_item->getId() ?>"> +<tr id="order-item-row-<?= (int) $_item->getId() ?>"> <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> - <?php if ($_options = $block->getItemOptions()): ?> - <dl class="item-options"> - <?php foreach ($_options as $_option) : ?> - <dt><?= $block->escapeHtml($_option['label']) ?></dt> - <?php if (!$block->getPrintStatus()): ?> - <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> - <dd<?php if (isset($_formatedOptionValue['full_view'])): ?> class="tooltip wrapper"<?php endif; ?>> - <?= /* @escapeNotVerified */ $_formatedOptionValue['value'] ?> - <?php if (isset($_formatedOptionValue['full_view'])): ?> - <div class="tooltip content"> - <dl class="item options"> - <dt><?= $block->escapeHtml($_option['label']) ?></dt> - <dd><?= /* @escapeNotVerified */ $_formatedOptionValue['full_view'] ?></dd> - </dl> - </div> - <?php endif; ?> - </dd> - <?php else: ?> - <dd><?= $block->escapeHtml((isset($_option['print_value']) ? $_option['print_value'] : $_option['value'])) ?></dd> - <?php endif; ?> - <?php endforeach; ?> - </dl> + <?php if ($_options = $block->getItemOptions()) : ?> + <dl class="item-options"> + <?php foreach ($_options as $_option) : ?> + <dt><?= $block->escapeHtml($_option['label']) ?></dt> + <?php if (!$block->getPrintStatus()) : ?> + <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> + <dd<?= (isset($_formatedOptionValue['full_view']) ? ' class="tooltip wrapper"' : '') ?>> + <?= $block->escapeHtml($_formatedOptionValue['value']) ?> + <?php if (isset($_formatedOptionValue['full_view'])) : ?> + <div class="tooltip content"> + <dl class="item options"> + <dt><?= $block->escapeHtml($_option['label']) ?></dt> + <dd><?= $block->escapeHtml($_formatedOptionValue['full_view']) ?></dd> + </dl> + </div> + <?php endif; ?> + </dd> + <?php else : ?> + <dd><?= $block->escapeHtml($_option['print_value'] ?? $_option['value']) ?></dd> + <?php endif; ?> + <?php endforeach; ?> + </dl> <?php endif; ?> <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?> <?php if ($addInfoBlock) :?> @@ -42,12 +39,12 @@ <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @escapeNotVerified */ $block->prepareSku($block->getSku()) ?></td> + <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> <?= $block->getItemPriceHtml() ?> </td> <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"> - <span class="qty summary"><?= /* @escapeNotVerified */ $_item->getQty()*1 ?></span> + <span class="qty summary"><?= (int) $_item->getQty() ?></span> </td> <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> <?= $block->getItemRowTotalHtml() ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/items.phtml b/app/code/Magento/Sales/view/frontend/templates/order/items.phtml index dc179b6ee4ac1..98a1f1ebb7545 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/items.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/items.phtml @@ -4,15 +4,15 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate /** @var \Magento\Sales\Block\Order\Items $block */ ?> <div class="table-wrapper order-items"> - <table class="data table table-order-items" id="my-orders-table" summary="<?= /* @escapeNotVerified */ __('Items Ordered') ?>"> - <caption class="table-caption"><?= /* @escapeNotVerified */ __('Items Ordered') ?></caption> + <table class="data table table-order-items" id="my-orders-table" summary="<?= $block->escapeHtml(__('Items Ordered')) ?>"> + <caption class="table-caption"><?= $block->escapeHtml(__('Items Ordered')) ?></caption> <thead> - <?php if($block->isPagerDisplayed()): ?> + <?php if ($block->isPagerDisplayed()) : ?> <tr> <td colspan="5" data-block="order-items-pager-top" class="order-pager-wrapper order-pager-wrapper-top"> <?= $block->getPagerHtml() ?> @@ -20,44 +20,46 @@ </tr> <?php endif ?> <tr> - <th class="col name"><?= /* @escapeNotVerified */ __('Product Name') ?></th> - <th class="col sku"><?= /* @escapeNotVerified */ __('SKU') ?></th> - <th class="col price"><?= /* @escapeNotVerified */ __('Price') ?></th> - <th class="col qty"><?= /* @escapeNotVerified */ __('Qty') ?></th> - <th class="col subtotal"><?= /* @escapeNotVerified */ __('Subtotal') ?></th> + <th class="col name"><?= $block->escapeHtml(__('Product Name')) ?></th> + <th class="col sku"><?= $block->escapeHtml(__('SKU')) ?></th> + <th class="col price"><?= $block->escapeHtml(__('Price')) ?></th> + <th class="col qty"><?= $block->escapeHtml(__('Qty')) ?></th> + <th class="col subtotal"><?= $block->escapeHtml(__('Subtotal')) ?></th> </tr> </thead> <?php $items = $block->getItems(); ?> <?php $giftMessage = ''?> <tbody> - <?php foreach ($items as $item): ?> - <?php if ($item->getParentItem()) continue; ?> - + <?php foreach ($items as $item) : + if ($item->getParentItem()) : + continue; + endif; + ?> <?= $block->getItemHtml($item) ?> - <?php if ($this->helper('Magento\GiftMessage\Helper\Message')->isMessagesAllowed('order_item', $item) && $item->getGiftMessageId()): ?> - <?php $giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessageForEntity($item); ?> + <?php if ($this->helper(\Magento\GiftMessage\Helper\Message::class)->isMessagesAllowed('order_item', $item) && $item->getGiftMessageId()) : ?> + <?php $giftMessage = $this->helper(\Magento\GiftMessage\Helper\Message::class)->getGiftMessageForEntity($item); ?> <tr> <td class="col options" colspan="5"> <a href="#" - id="order-item-gift-message-link-<?= /* @escapeNotVerified */ $item->getId() ?>" + id="order-item-gift-message-link-<?= (int) $item->getId() ?>" class="action show" - aria-controls="order-item-gift-message-<?= /* @escapeNotVerified */ $item->getId() ?>" - data-item-id="<?= /* @escapeNotVerified */ $item->getId() ?>"> - <?= /* @escapeNotVerified */ __('Gift Message') ?> + aria-controls="order-item-gift-message-<?= (int) $item->getId() ?>" + data-item-id="<?= (int) $item->getId() ?>"> + <?= $block->escapeHtml(__('Gift Message')) ?> </a> - <?php $giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessageForEntity($item); ?> - <div class="order-gift-message" id="order-item-gift-message-<?= /* @escapeNotVerified */ $item->getId() ?>" role="region" aria-expanded="false" tabindex="-1"> + <?php $giftMessage = $this->helper(\Magento\GiftMessage\Helper\Message::class)->getGiftMessageForEntity($item); ?> + <div class="order-gift-message" id="order-item-gift-message-<?= (int) $item->getId() ?>" role="region" aria-expanded="false" tabindex="-1"> <a href="#" - title="<?= /* @escapeNotVerified */ __('Close') ?>" - aria-controls="order-item-gift-message-<?= /* @escapeNotVerified */ $item->getId() ?>" - data-item-id="<?= /* @escapeNotVerified */ $item->getId() ?>" + title="<?= $block->escapeHtml(__('Close')) ?>" + aria-controls="order-item-gift-message-<?= (int) $item->getId() ?>" + data-item-id="<?= (int) $item->getId() ?>" class="action close"> - <?= /* @escapeNotVerified */ __('Close') ?> + <?= $block->escapeHtml(__('Close')) ?> </a> <dl class="item-options"> - <dt class="item-sender"><strong class="label"><?= /* @escapeNotVerified */ __('From') ?></strong><?= $block->escapeHtml($giftMessage->getSender()) ?></dt> - <dt class="item-recipient"><strong class="label"><?= /* @escapeNotVerified */ __('To') ?></strong><?= $block->escapeHtml($giftMessage->getRecipient()) ?></dt> - <dd class="item-message"><?= /* @escapeNotVerified */ $this->helper('Magento\GiftMessage\Helper\Message')->getEscapedGiftMessage($item) ?></dd> + <dt class="item-sender"><strong class="label"><?= $block->escapeHtml(__('From')) ?></strong><?= $block->escapeHtml($giftMessage->getSender()) ?></dt> + <dt class="item-recipient"><strong class="label"><?= $block->escapeHtml(__('To')) ?></strong><?= $block->escapeHtml($giftMessage->getRecipient()) ?></dt> + <dd class="item-message"><?= /* @noEscape */ $this->helper(\Magento\GiftMessage\Helper\Message::class)->getEscapedGiftMessage($item) ?></dd> </dl> </div> </td> @@ -66,7 +68,7 @@ <?php endforeach; ?> </tbody> <tfoot> - <?php if($block->isPagerDisplayed()): ?> + <?php if ($block->isPagerDisplayed()) : ?> <tr> <td colspan="5" data-block="order-items-pager-bottom" class="order-pager-wrapper order-pager-wrapper-bottom"> <?= $block->getPagerHtml() ?> @@ -77,7 +79,7 @@ </tfoot> </table> </div> -<?php if ($giftMessage): ?> +<?php if ($giftMessage) : ?> <script type="text/x-magento-init"> { "a.action.show, a.action.close": { diff --git a/app/code/Magento/Sales/view/frontend/templates/order/items/renderer/default.phtml b/app/code/Magento/Sales/view/frontend/templates/order/items/renderer/default.phtml index d4550dd4f01c3..aec0ec6b4fe2d 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/items/renderer/default.phtml @@ -4,69 +4,67 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** @var $block \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer */ $_item = $block->getItem(); ?> -<tr id="order-item-row-<?= /* @escapeNotVerified */ $_item->getId() ?>"> +<tr id="order-item-row-<?= (int) $_item->getId() ?>"> <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> - <?php if ($_options = $block->getItemOptions()): ?> - <dl class="item-options"> - <?php foreach ($_options as $_option) : ?> - <dt><?= $block->escapeHtml($_option['label']) ?></dt> - <?php if (!$block->getPrintStatus()): ?> - <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> - <dd> - <?php if (isset($_formatedOptionValue['full_view'])): ?> - <?= /* @escapeNotVerified */ $_formatedOptionValue['full_view'] ?> - <?php else: ?> - <?= /* @escapeNotVerified */ $_formatedOptionValue['value'] ?> - <?php endif; ?> - </dd> - <?php else: ?> - <dd> - <?= nl2br($block->escapeHtml((isset($_option['print_value']) ? $_option['print_value'] : $_option['value']))) ?> - </dd> - <?php endif; ?> - <?php endforeach; ?> - </dl> + <?php if ($_options = $block->getItemOptions()) : ?> + <dl class="item-options"> + <?php foreach ($_options as $_option) : ?> + <dt><?= $block->escapeHtml($_option['label']) ?></dt> + <?php if (!$block->getPrintStatus()) : ?> + <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> + <dd> + <?php if (isset($_formatedOptionValue['full_view'])) : ?> + <?= $block->escapeHtml($_formatedOptionValue['full_view'], ['a']) ?> + <?php else : ?> + <?=$block->escapeHtml($_formatedOptionValue['value'], ['a']) ?> + <?php endif; ?> + </dd> + <?php else : ?> + <dd> + <?= /* @noEscape */ nl2br($block->escapeHtml($_option['print_value'] ?? $_option['value'])) ?> + </dd> + <?php endif; ?> + <?php endforeach; ?> + </dl> <?php endif; ?> <?php $addtInfoBlock = $block->getProductAdditionalInformationBlock(); ?> - <?php if ($addtInfoBlock) :?> + <?php if ($addtInfoBlock) : ?> <?= $addtInfoBlock->setItem($_item)->toHtml() ?> <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @escapeNotVerified */ $block->prepareSku($block->getSku()) ?></td> + <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> <?= $block->getItemPriceHtml() ?> </td> <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"> <ul class="items-qty"> - <?php if ($block->getItem()->getQtyOrdered() > 0): ?> + <?php if ($block->getItem()->getQtyOrdered() > 0) : ?> <li class="item"> - <span class="title"><?= /* @escapeNotVerified */ __('Ordered') ?></span> - <span class="content"><?= /* @escapeNotVerified */ $block->getItem()->getQtyOrdered()*1 ?></span> + <span class="title"><?= $block->escapeHtml(__('Ordered')) ?></span> + <span class="content"><?= (int) $block->getItem()->getQtyOrdered() ?></span> </li> <?php endif; ?> - <?php if ($block->getItem()->getQtyShipped() > 0): ?> + <?php if ($block->getItem()->getQtyShipped() > 0) : ?> <li class="item"> - <span class="title"><?= /* @escapeNotVerified */ __('Shipped') ?></span> - <span class="content"><?= /* @escapeNotVerified */ $block->getItem()->getQtyShipped()*1 ?></span> + <span class="title"><?= $block->escapeHtml(__('Shipped')) ?></span> + <span class="content"><?= (int) $block->getItem()->getQtyShipped() ?></span> </li> <?php endif; ?> - <?php if ($block->getItem()->getQtyCanceled() > 0): ?> + <?php if ($block->getItem()->getQtyCanceled() > 0) : ?> <li class="item"> - <span class="title"><?= /* @escapeNotVerified */ __('Canceled') ?></span> - <span class="content"><?= /* @escapeNotVerified */ $block->getItem()->getQtyCanceled()*1 ?></span> + <span class="title"><?= $block->escapeHtml(__('Canceled')) ?></span> + <span class="content"><?= (int) $block->getItem()->getQtyCanceled() ?></span> </li> <?php endif; ?> - <?php if ($block->getItem()->getQtyRefunded() > 0): ?> + <?php if ($block->getItem()->getQtyRefunded() > 0) : ?> <li class="item"> - <span class="title"><?= /* @escapeNotVerified */ __('Refunded') ?></span> - <span class="content"><?= /* @escapeNotVerified */ $block->getItem()->getQtyRefunded()*1 ?></span> + <span class="title"><?= $block->escapeHtml(__('Refunded')) ?></span> + <span class="content"><?= (int) $block->getItem()->getQtyRefunded() ?></span> </li> <?php endif; ?> </ul> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/order_comments.phtml b/app/code/Magento/Sales/view/frontend/templates/order/order_comments.phtml index 8a8e7b1194caa..6f2d8d87ade86 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/order_comments.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/order_comments.phtml @@ -3,24 +3,23 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var $block \Magento\Sales\Block\Order\View*/?> <?php $_history = $block->getOrder()->getVisibleStatusHistory() ?> -<?php if (count($_history)): ?> +<?php if (!empty($_history)) : ?> <div class="block block-order-details-comments"> - <div class="block-title"><strong><?= /* @escapeNotVerified */ __('About Your Order') ?></strong></div> + <div class="block-title"><strong><?= $block->escapeHtml(__('About Your Order')) ?></strong></div> <div class="block-content"> <dl class="order-comments"> - <?php foreach ($_history as $_historyItem): ?> - <dt class="comment-date"><?= /* @escapeNotVerified */ $block->formatDate($_historyItem->getCreatedAt(), \IntlDateFormatter::MEDIUM, true) ?></dt> + <?php foreach ($_history as $_historyItem) : ?> + <dt class="comment-date"> + <?= /* @noEscape */ + $block->formatDate($_historyItem->getCreatedAt(), \IntlDateFormatter::MEDIUM, true) ?> + </dt> <dd class="comment-content"><?= $block->escapeHtml($_historyItem->getComment()) ?></dd> <?php endforeach; ?> </dl> - </div> </div> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/order_date.phtml b/app/code/Magento/Sales/view/frontend/templates/order/order_date.phtml index bcd7cc6e0260d..80a0ea02499cc 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/order_date.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/order_date.phtml @@ -3,11 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> - <div class="order-date"> - <?= /* @escapeNotVerified */ __('<span class="label">Order Date:</span> %1', '<date>' . $block->formatDate($block->getOrder()->getCreatedAt(), \IntlDateFormatter::LONG) . '</date>') ?> + <?= $block->escapeHtml(__('<span class="label">Order Date:</span> %1', '<date>' . $block->formatDate($block->getOrder()->getCreatedAt(), \IntlDateFormatter::LONG) . '</date>'), ['span', 'date']) ?> </div> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/order_status.phtml b/app/code/Magento/Sales/view/frontend/templates/order/order_status.phtml index c77014d1bf8c9..7a3ff4398d983 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/order_status.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/order_status.phtml @@ -6,4 +6,4 @@ ?> <?php /** @var $block \Magento\Sales\Block\Order\Info */ ?> -<span class="order-status"><?= /* @escapeNotVerified */ $block->getOrder()->getStatusLabel() ?></span> +<span class="order-status"><?= $block->escapeHtml($block->getOrder()->getStatusLabel()) ?></span> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/print/creditmemo.phtml b/app/code/Magento/Sales/view/frontend/templates/order/print/creditmemo.phtml index 567dfc20f2de2..05c6048ee15ae 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/print/creditmemo.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/print/creditmemo.phtml @@ -3,39 +3,36 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php $_order = $block->getOrder() ?> <?php $_creditmemo = $block->getCreditmemo() ?> -<?php if ($_creditmemo): ?> +<?php if ($_creditmemo) : ?> <?php $_creditmemos = [$_creditmemo]; ?> -<?php else: ?> +<?php else : ?> <?php $_creditmemos = $_order->getCreditmemosCollection() ?> <?php endif; ?> -<?php foreach ($_creditmemos as $_creditmemo): ?> +<?php foreach ($_creditmemos as $_creditmemo) : ?> <div class="order-details-items creditmemo"> <div class="order-title"> - <strong><?= /* @escapeNotVerified */ __('Refund #%1', $_creditmemo->getIncrementId()) ?></strong> + <strong><?= $block->escapeHtml(__('Refund #%1', $_creditmemo->getIncrementId())) ?></strong> </div> <div class="table-wrapper order-items-creditmemo"> - <table class="data table table-order-items creditmemo" id="my-refund-table-<?= /* @escapeNotVerified */ $_creditmemo->getId() ?>"> - <caption class="table-caption"><?= /* @escapeNotVerified */ __('Items Refunded') ?></caption> + <table class="data table table-order-items creditmemo" id="my-refund-table-<?= (int) $_creditmemo->getId() ?>"> + <caption class="table-caption"><?= $block->escapeHtml(__('Items Refunded')) ?></caption> <thead> <tr> - <th class="col name"><?= /* @escapeNotVerified */ __('Product Name') ?></th> - <th class="col sku"><?= /* @escapeNotVerified */ __('SKU') ?></th> - <th class="col price"><?= /* @escapeNotVerified */ __('Price') ?></th> - <th class="col qty"><?= /* @escapeNotVerified */ __('Qty') ?></th> - <th class="col subtotal"><?= /* @escapeNotVerified */ __('Subtotal') ?></th> - <th class="col discount"><?= /* @escapeNotVerified */ __('Discount Amount') ?></th> - <th class="col rowtotal"><?= /* @escapeNotVerified */ __('Row Total') ?></th> + <th class="col name"><?= $block->escapeHtml(__('Product Name')) ?></th> + <th class="col sku"><?= $block->escapeHtml(__('SKU')) ?></th> + <th class="col price"><?= $block->escapeHtml(__('Price')) ?></th> + <th class="col qty"><?= $block->escapeHtml(__('Qty')) ?></th> + <th class="col subtotal"><?= $block->escapeHtml(__('Subtotal')) ?></th> + <th class="col discount"><?= $block->escapeHtml(__('Discount Amount')) ?></th> + <th class="col rowtotal"><?= $block->escapeHtml(__('Row Total')) ?></th> </tr> </thead> <?php $_items = $_creditmemo->getAllItems(); ?> - <?php foreach ($_items as $_item): ?> - <?php if (!$_item->getOrderItem()->getParentItem()): ?> + <?php foreach ($_items as $_item) : ?> + <?php if (!$_item->getOrderItem()->getParentItem()) : ?> <tbody> <?= $block->getItemHtml($_item) ?> </tbody> @@ -48,22 +45,22 @@ </div> <div class="block block-order-details-view"> <div class="block-title"> - <strong><?= /* @escapeNotVerified */ __('Order Information') ?></strong> + <strong><?= $block->escapeHtml(__('Order Information')) ?></strong> </div> <div class="block-content"> - <?php if (!$_order->getIsVirtual()): ?> + <?php if (!$_order->getIsVirtual()) : ?> <div class="box box-order-shipping-address"> <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Shipping Address') ?></strong> + <strong><?= $block->escapeHtml(__('Shipping Address')) ?></strong> </div> <div class="box-content"> <?php $_shipping = $_creditmemo->getShippingAddress() ?> - <address><?= /* @escapeNotVerified */ $block->formatAddress($_shipping, 'html') ?></address> + <address><?= /* @noEscape */ $block->formatAddress($_shipping, 'html') ?></address> </div> </div> <div class="box box-order-shipping-method"> <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Shipping Method') ?></strong> + <strong><?= $block->escapeHtml(__('Shipping Method')) ?></strong> </div> <div class="box-content"> <?= $block->escapeHtml($_order->getShippingDescription()) ?> @@ -72,16 +69,16 @@ <?php endif; ?> <div class="box box-order-billing-address"> <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Billing Address') ?></strong> + <strong><?= $block->escapeHtml(__('Billing Address')) ?></strong> </div> <div class="box-content"> <?php $_billing = $_creditmemo->getbillingAddress() ?> - <address><?= /* @escapeNotVerified */ $block->formatAddress($_order->getBillingAddress(), 'html') ?></address> + <address><?= /* @noEscape */ $block->formatAddress($_order->getBillingAddress(), 'html') ?></address> </div> </div> <div class="box box-order-billing-method"> <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Payment Method') ?></strong> + <strong><?= $block->escapeHtml(__('Payment Method')) ?></strong> </div> <div class="box-content"> <?= $block->getPaymentInfoHtml() ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/print/invoice.phtml b/app/code/Magento/Sales/view/frontend/templates/order/print/invoice.phtml index 6fe6da9e75209..3c0196d59329c 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/print/invoice.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/print/invoice.phtml @@ -3,37 +3,34 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php $_order = $block->getOrder() ?> <?php $_invoice = $block->getInvoice() ?> -<?php if ($_invoice): ?> -<?php $_invoices = [$_invoice]; ?> -<?php else: ?> -<?php $_invoices = $_order->getInvoiceCollection() ?> +<?php if ($_invoice) : ?> + <?php $_invoices = [$_invoice]; ?> +<?php else : ?> + <?php $_invoices = $_order->getInvoiceCollection() ?> <?php endif; ?> -<?php foreach ($_invoices as $_invoice): ?> +<?php foreach ($_invoices as $_invoice) : ?> <div class="order-details-items invoice"> <div class="order-title"> - <strong><?= /* @escapeNotVerified */ __('Invoice #') ?><?= /* @escapeNotVerified */ $_invoice->getIncrementId() ?></strong> + <strong><?= $block->escapeHtml(__('Invoice #')) ?><?= (int) $_invoice->getIncrementId() ?></strong> </div> <div class="table-wrapper table-order-items invoice"> - <table class="data table table-order-items invoice" id="my-invoice-table-<?= /* @escapeNotVerified */ $_invoice->getId() ?>"> - <caption class="table-caption"><?= /* @escapeNotVerified */ __('Items Invoiced') ?></caption> + <table class="data table table-order-items invoice" id="my-invoice-table-<?= (int) $_invoice->getId() ?>"> + <caption class="table-caption"><?= $block->escapeHtml(__('Items Invoiced')) ?></caption> <thead> <tr> - <th class="col name"><?= /* @escapeNotVerified */ __('Product Name') ?></th> - <th class="col sku"><?= /* @escapeNotVerified */ __('SKU') ?></th> - <th class="col price"><?= /* @escapeNotVerified */ __('Price') ?></th> - <th class="col qty"><?= /* @escapeNotVerified */ __('Qty Invoiced') ?></th> - <th class="col subtotal"><?= /* @escapeNotVerified */ __('Subtotal') ?></th> + <th class="col name"><?= $block->escapeHtml(__('Product Name')) ?></th> + <th class="col sku"><?= $block->escapeHtml(__('SKU')) ?></th> + <th class="col price"><?= $block->escapeHtml(__('Price')) ?></th> + <th class="col qty"><?= $block->escapeHtml(__('Qty Invoiced')) ?></th> + <th class="col subtotal"><?= $block->escapeHtml(__('Subtotal')) ?></th> </tr> </thead> <?php $_items = $_invoice->getItemsCollection(); ?> - <?php foreach ($_items as $_item): ?> - <?php if (!$_item->getOrderItem()->getParentItem()): ?> + <?php foreach ($_items as $_item) : ?> + <?php if (!$_item->getOrderItem()->getParentItem()) : ?> <tbody> <?= $block->getItemHtml($_item) ?> </tbody> @@ -46,46 +43,46 @@ </div> <div class="block block-order-details-view"> <div class="block-title"> - <strong><?= /* @escapeNotVerified */ __('Order Information') ?></strong> + <strong><?= $block->escapeHtml(__('Order Information')) ?></strong> </div> <div class="block-content"> - <?php if (!$_order->getIsVirtual()): ?> + <?php if (!$_order->getIsVirtual()) : ?> <div class="box box-order-shipping-address"> <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Shipping Address') ?></strong> + <strong><?= $block->escapeHtml(__('Shipping Address')) ?></strong> </div> <div class="box-content"> <?php $_shipping = $_invoice->getShippingAddress() ?> - <address><?= /* @escapeNotVerified */ $block->formatAddress($_shipping, 'html') ?></address> + <address><?= /* @noEscape */ $block->formatAddress($_shipping, 'html') ?></address> </div> </div> <div class="box box-order-shipping-method"> <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Shipping Method') ?></strong> + <strong><?= $block->escapeHtml(__('Shipping Method')) ?></strong> </div> <div class="box-content"> - <?php if ($_order->getShippingDescription()): ?> + <?php if ($_order->getShippingDescription()) : ?> <?= $block->escapeHtml($_order->getShippingDescription()) ?> - <?php else: ?> - <?= /* @escapeNotVerified */ __('No shipping information available') ?> + <?php else : ?> + <?= $block->escapeHtml(__('No shipping information available')) ?> <?php endif; ?> </div> </div> <?php endif; ?> <div class="box box-order-billing-address"> <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Billing Address') ?></strong> + <strong><?= $block->escapeHtml(__('Billing Address')) ?></strong> </div> <div class="box-content"> <?php $_billing = $_invoice->getbillingAddress() ?> - <address><?= /* @escapeNotVerified */ $block->formatAddress($_order->getBillingAddress(), 'html') ?></address> + <address><?= /* @noEscape */ $block->formatAddress($_order->getBillingAddress(), 'html') ?></address> </div> </div> <div class="box box-order-billing-method"> <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Payment Method') ?></strong> + <strong><?= $block->escapeHtml(__('Payment Method')) ?></strong> </div> <div class="box-content"> <?= $block->getPaymentInfoHtml() ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/print/shipment.phtml b/app/code/Magento/Sales/view/frontend/templates/order/print/shipment.phtml index d1110d1a8d380..3f12ca1f7b270 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/print/shipment.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/print/shipment.phtml @@ -3,86 +3,83 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /* @var $block \Magento\Sales\Block\Order\PrintOrder\Shipment */ ?> <?php $order = $block->getOrder(); ?> -<?php if (!$block->getObjectData($order, 'is_virtual')): ?> -<?php foreach ($block->getShipmentsCollection() as $shipment): ?> - <div class="order-details-items shipments"> - <div class="order-title"> - <strong><?= /* @escapeNotVerified */ __('Shipment #%1', $block->getObjectData($shipment, 'increment_id')) ?></strong> - </div> - <div class="table-wrapper order-items-shipment"> - <table class="data table table-order-items shipment" id="my-shipment-table-<?= /* @escapeNotVerified */ $block->getObjectData($shipment, 'id') ?>"> - <caption class="table-caption"><?= /* @escapeNotVerified */ __('Items Invoiced') ?></caption> - <thead> - <tr> - <th class="col name"><?= /* @escapeNotVerified */ __('Product Name') ?></th> - <th class="col sku"><?= /* @escapeNotVerified */ __('SKU') ?></th> - <th class="col price"><?= /* @escapeNotVerified */ __('Qty Shipped') ?></th> - </tr> - </thead> - <?php foreach ($block->getShipmentItems($shipment) as $item): ?> - <tbody> - <?= $block->getItemHtml($item) ?> - </tbody> - <?php endforeach; ?> - </table> - </div> - <div class="block block-order-details-view"> - <div class="block-title"> - <strong><?= /* @escapeNotVerified */ __('Order Information') ?></strong> +<?php if (!$block->getObjectData($order, 'is_virtual')) : ?> + <?php foreach ($block->getShipmentsCollection() as $shipment) : ?> + <div class="order-details-items shipments"> + <div class="order-title"> + <strong><?= $block->escapeHtml(__('Shipment #%1', $block->getObjectData($shipment, 'increment_id'))) ?></strong> </div> - <div class="block-content"> - <div class="box box-order-shipping-address"> - <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Shipping Address') ?></strong> - </div> - <div class="box-content"> - <address><?= $block->getShipmentAddressFormattedHtml($shipment) ?></address> - </div> + <div class="table-wrapper order-items-shipment"> + <table class="data table table-order-items shipment" id="my-shipment-table-<?= (int) $block->getObjectData($shipment, 'id') ?>"> + <caption class="table-caption"><?= $block->escapeHtml(__('Items Invoiced')) ?></caption> + <thead> + <tr> + <th class="col name"><?= $block->escapeHtml(__('Product Name')) ?></th> + <th class="col sku"><?= $block->escapeHtml(__('SKU')) ?></th> + <th class="col price"><?= $block->escapeHtml(__('Qty Shipped')) ?></th> + </tr> + </thead> + <?php foreach ($block->getShipmentItems($shipment) as $item) : ?> + <tbody> + <?= $block->getItemHtml($item) ?> + </tbody> + <?php endforeach; ?> + </table> + </div> + <div class="block block-order-details-view"> + <div class="block-title"> + <strong><?= $block->escapeHtml(__('Order Information')) ?></strong> </div> - - <div class="box box-order-shipping-method"> - <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Shipping Method') ?></strong> + <div class="block-content"> + <div class="box box-order-shipping-address"> + <div class="box-title"> + <strong><?= $block->escapeHtml(__('Shipping Address')) ?></strong> + </div> + <div class="box-content"> + <address><?= $block->getShipmentAddressFormattedHtml($shipment) ?></address> + </div> </div> - <div class="box-content"> - <?= $block->escapeHtml($block->getObjectData($order, 'shipping_description')) ?> - <?php $tracks = $block->getShipmentTracks($shipment); - if ($tracks): ?> - <dl class="order-tracking"> - <?php foreach ($tracks as $track): ?> - <dt class="tracking-title"><?= $block->escapeHtml($block->getObjectData($track, 'title')) ?></dt> - <dd class="tracking-content"><?= $block->escapeHtml($block->getObjectData($track, 'number')) ?></dd> + + <div class="box box-order-shipping-method"> + <div class="box-title"> + <strong><?= $block->escapeHtml(__('Shipping Method')) ?></strong> + </div> + <div class="box-content"> + <?= $block->escapeHtml($block->getObjectData($order, 'shipping_description')) ?> + <?php $tracks = $block->getShipmentTracks($shipment); + if ($tracks) : ?> + <dl class="order-tracking"> + <?php foreach ($tracks as $track) : ?> + <dt class="tracking-title"><?= $block->escapeHtml($block->getObjectData($track, 'title')) ?></dt> + <dd class="tracking-content"><?= $block->escapeHtml($block->getObjectData($track, 'number')) ?></dd> <?php endforeach; ?> - </dl> - <?php endif; ?> + </dl> + <?php endif; ?> + </div> </div> - </div> - <div class="box box-order-billing-method"> - <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Billing Address') ?></strong> + <div class="box box-order-billing-method"> + <div class="box-title"> + <strong><?= $block->escapeHtml(__('Billing Address')) ?></strong> + </div> + <div class="box-content"> + <address><?= $block->getBillingAddressFormattedHtml($order) ?></address> + </div> </div> - <div class="box-content"> - <address><?= $block->getBillingAddressFormattedHtml($order) ?></address> - </div> - </div> - <div class="box box-order-billing-method"> - <div class="box-title"> - <strong><?= /* @escapeNotVerified */ __('Payment Method') ?></strong> - </div> - <div class="box-content"> - <?= $block->getPaymentInfoHtml() ?> + <div class="box box-order-billing-method"> + <div class="box-title"> + <strong><?= $block->escapeHtml(__('Payment Method')) ?></strong> + </div> + <div class="box-content"> + <?= $block->getPaymentInfoHtml() ?> + </div> </div> </div> </div> </div> - </div> <?php endforeach; ?> <?php endif; ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/recent.phtml b/app/code/Magento/Sales/view/frontend/templates/order/recent.phtml index bb354e920c529..0702724e79e38 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/recent.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/recent.phtml @@ -4,8 +4,9 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile +// phpcs:disable Magento2.Templates.ThisInTemplate +/** @var $block \Magento\Sales\Block\Order\Recent */ ?> <div class="block block-dashboard-orders"> <?php @@ -13,47 +14,49 @@ $count = count($_orders); ?> <div class="block-title order"> - <strong><?= /* @escapeNotVerified */ __('Recent Orders') ?></strong> - <?php if ($count > 0): ?> - <a class="action view" href="<?= /* @escapeNotVerified */ $block->getUrl('sales/order/history') ?>"> - <span><?= /* @escapeNotVerified */ __('View All') ?></span> + <strong><?= $block->escapeHtml(__('Recent Orders')) ?></strong> + <?php if ($count > 0) : ?> + <a class="action view" href="<?= $block->escapeUrl($block->getUrl('sales/order/history')) ?>"> + <span><?= $block->escapeHtml(__('View All')) ?></span> </a> <?php endif; ?> </div> <div class="block-content"> <?= $block->getChildHtml() ?> - <?php if ($count > 0): ?> + <?php if ($count > 0) : ?> <div class="table-wrapper orders-recent"> <table class="data table table-order-items recent" id="my-orders-table"> - <caption class="table-caption"><?= /* @escapeNotVerified */ __('Recent Orders') ?></caption> + <caption class="table-caption"><?= $block->escapeHtml(__('Recent Orders')) ?></caption> <thead> <tr> - <th scope="col" class="col id"><?= /* @escapeNotVerified */ __('Order #') ?></th> - <th scope="col" class="col date"><?= /* @escapeNotVerified */ __('Date') ?></th> - <th scope="col" class="col shipping"><?= /* @escapeNotVerified */ __('Ship To') ?></th> - <th scope="col" class="col total"><?= /* @escapeNotVerified */ __('Order Total') ?></th> - <th scope="col" class="col status"><?= /* @escapeNotVerified */ __('Status') ?></th> - <th scope="col" class="col actions"><?= /* @escapeNotVerified */ __('Action') ?></th> + <th scope="col" class="col id"><?= $block->escapeHtml(__('Order #')) ?></th> + <th scope="col" class="col date"><?= $block->escapeHtml(__('Date')) ?></th> + <th scope="col" class="col shipping"><?= $block->escapeHtml(__('Ship To')) ?></th> + <th scope="col" class="col total"><?= $block->escapeHtml(__('Order Total')) ?></th> + <th scope="col" class="col status"><?= $block->escapeHtml(__('Status')) ?></th> + <th scope="col" class="col actions"><?= $block->escapeHtml(__('Action')) ?></th> </tr> </thead> <tbody> - <?php foreach ($_orders as $_order): ?> + <?php foreach ($_orders as $_order) : ?> <tr> - <td data-th="<?= $block->escapeHtml(__('Order #')) ?>" class="col id"><?= /* @escapeNotVerified */ $_order->getRealOrderId() ?></td> - <td data-th="<?= $block->escapeHtml(__('Date')) ?>" class="col date"><?= /* @escapeNotVerified */ $block->formatDate($_order->getCreatedAt()) ?></td> - <td data-th="<?= $block->escapeHtml(__('Ship To')) ?>" class="col shipping"><?= $_order->getShippingAddress() ? $block->escapeHtml($_order->getShippingAddress()->getName()) : ' ' ?></td> - <td data-th="<?= $block->escapeHtml(__('Order Total')) ?>" class="col total"><?= /* @escapeNotVerified */ $_order->formatPrice($_order->getGrandTotal()) ?></td> - <td data-th="<?= $block->escapeHtml(__('Status')) ?>" class="col status"><?= /* @escapeNotVerified */ $_order->getStatusLabel() ?></td> + <td data-th="<?= $block->escapeHtml(__('Order #')) ?>" class="col id"><?= $block->escapeHtml($_order->getRealOrderId()) ?></td> + <td data-th="<?= $block->escapeHtml(__('Date')) ?>" class="col date"><?= $block->escapeHtml($block->formatDate($_order->getCreatedAt())) ?></td> + <td data-th="<?= $block->escapeHtml(__('Ship To')) ?>" class="col shipping"><?= $_order->getShippingAddress() ? $block->escapeHtml($_order->getShippingAddress()->getName()) : " " ?></td> + <td data-th="<?= $block->escapeHtml(__('Order Total')) ?>" class="col total"><?= /* @noEscape */ $_order->formatPrice($_order->getGrandTotal()) ?></td> + <td data-th="<?= $block->escapeHtml(__('Status')) ?>" class="col status"><?= $block->escapeHtml($_order->getStatusLabel()) ?></td> <td data-th="<?= $block->escapeHtml(__('Actions')) ?>" class="col actions"> - <a href="<?= /* @escapeNotVerified */ $block->getViewUrl($_order) ?>" class="action view"> - <span><?= /* @escapeNotVerified */ __('View Order') ?></span> + <a href="<?= $block->escapeUrl($block->getViewUrl($_order)) ?>" class="action view"> + <span><?= $block->escapeHtml(__('View Order')) ?></span> </a> - <?php if ($this->helper('Magento\Sales\Helper\Reorder')->canReorder($_order->getEntityId())) : ?> - <a href="#" data-post='<?php /* @escapeNotVerified */ echo + <?php if ($this->helper(\Magento\Sales\Helper\Reorder::class) + ->canReorder($_order->getEntityId()) + ) : ?> + <a href="#" data-post='<?= /* @noEscape */ $this->helper(\Magento\Framework\Data\Helper\PostHelper::class) ->getPostData($block->getReorderUrl($_order)) ?>' class="action order"> - <span><?= /* @escapeNotVerified */ __('Reorder') ?></span> + <span><?= $block->escapeHtml(__('Reorder')) ?></span> </a> <?php endif ?> </td> @@ -62,8 +65,8 @@ </tbody> </table> </div> - <?php else: ?> - <div class="message info empty"><span><?= /* @escapeNotVerified */ __('You have placed no orders.') ?></span></div> + <?php else : ?> + <div class="message info empty"><span><?= $block->escapeHtml(__('You have placed no orders.')) ?></span></div> <?php endif; ?> </div> </div> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/shipment/items/renderer/default.phtml b/app/code/Magento/Sales/view/frontend/templates/order/shipment/items/renderer/default.phtml index b46e8d115480e..57aeffb26f823 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/shipment/items/renderer/default.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/shipment/items/renderer/default.phtml @@ -3,44 +3,41 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php $_item = $block->getItem() ?> <?php $_order = $block->getItem()->getOrderItem()->getOrder() ?> -<tr id="order-item-row-<?= /* @escapeNotVerified */ $_item->getId() ?>"> +<tr id="order-item-row-<?= (int) $_item->getId() ?>"> <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> - <?php if ($_options = $block->getItemOptions()): ?> - <dl class="item options"> - <?php foreach ($_options as $_option) : ?> - <dt><?= $block->escapeHtml($_option['label']) ?></dt> - <?php if (!$block->getPrintStatus()): ?> - <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> - <dd<?php if (isset($_formatedOptionValue['full_view'])): ?> class="tooltip wrapper"<?php endif; ?>> - <?= /* @escapeNotVerified */ $_formatedOptionValue['value'] ?> - <?php if (isset($_formatedOptionValue['full_view'])): ?> - <div class="tooltip content"> - <dl class="item options"> - <dt><?= $block->escapeHtml($_option['label']) ?></dt> - <dd><?= /* @escapeNotVerified */ $_formatedOptionValue['full_view'] ?></dd> - </dl> - </div> - <?php endif; ?> - </dd> - <?php else: ?> - <dd><?= $block->escapeHtml((isset($_option['print_value']) ? $_option['print_value'] : $_option['value'])) ?></dd> - <?php endif; ?> - <?php endforeach; ?> - </dl> + <?php if ($_options = $block->getItemOptions()) : ?> + <dl class="item options"> + <?php foreach ($_options as $_option) : ?> + <dt><?= $block->escapeHtml($_option['label']) ?></dt> + <?php if (!$block->getPrintStatus()) : ?> + <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> + <dd<?= (isset($_formatedOptionValue['full_view']) ? ' class="tooltip wrapper"' : '') ?>> + <?= $block->escapeHtml($_formatedOptionValue['value']) ?> + <?php if (isset($_formatedOptionValue['full_view'])) : ?> + <div class="tooltip content"> + <dl class="item options"> + <dt><?= $block->escapeHtml($_option['label']) ?></dt> + <dd><?= $block->escapeHtml($_formatedOptionValue['full_view']) ?></dd> + </dl> + </div> + <?php endif; ?> + </dd> + <?php else : ?> + <dd><?= $block->escapeHtml((isset($_option['print_value']) ? $_option['print_value'] : $_option['value'])) ?></dd> + <?php endif; ?> + <?php endforeach; ?> + </dl> <?php endif; ?> <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?> - <?php if ($addInfoBlock) :?> + <?php if ($addInfoBlock) : ?> <?= $addInfoBlock->setItem($_item->getOrderItem())->toHtml() ?> <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @escapeNotVerified */ $block->prepareSku($block->getSku()) ?></td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Shipped')) ?>"><?= /* @escapeNotVerified */ $_item->getQty()*1 ?></td> + <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> + <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Shipped')) ?>"><?= (int) $_item->getQty() ?></td> </tr> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/totals.phtml b/app/code/Magento/Sales/view/frontend/templates/order/totals.phtml index 8f0e884a22953..7a88f14eb0715 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/totals.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/totals.phtml @@ -4,32 +4,30 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** * @var $block \Magento\Sales\Block\Order\Totals * @see \Magento\Sales\Block\Order\Totals */ ?> -<?php foreach ($block->getTotals() as $_code => $_total): ?> - <?php if ($_total->getBlockName()): ?> +<?php foreach ($block->getTotals() as $_code => $_total) : ?> + <?php if ($_total->getBlockName()) : ?> <?= $block->getChildHtml($_total->getBlockName(), false) ?> - <?php else:?> - <tr class="<?= /* @escapeNotVerified */ $_code ?>"> - <th <?= /* @escapeNotVerified */ $block->getLabelProperties() ?> scope="row"> - <?php if ($_total->getStrong()):?> - <strong><?= $block->escapeHtml($_total->getLabel()) ?></strong> - <?php else:?> - <?= $block->escapeHtml($_total->getLabel()) ?> - <?php endif?> + <?php else :?> + <tr class="<?= $block->escapeHtmlAttr($_code) ?>"> + <th <?= /* @noEscape */ $block->getLabelProperties() ?> scope="row"> + <?php if ($_total->getStrong()) : ?> + <strong><?= $block->escapeHtml($_total->getLabel()) ?></strong> + <?php else : ?> + <?= $block->escapeHtml($_total->getLabel()) ?> + <?php endif ?> </th> - <td <?= /* @escapeNotVerified */ $block->getValueProperties() ?> data-th="<?= $block->escapeHtml($_total->getLabel()) ?>"> - <?php if ($_total->getStrong()):?> - <strong><?= /* @escapeNotVerified */ $block->formatValue($_total) ?></strong> - <?php else:?> - <?= /* @escapeNotVerified */ $block->formatValue($_total) ?> + <td <?= /* @noEscape */ $block->getValueProperties() ?> data-th="<?= $block->escapeHtmlAttr($_total->getLabel()) ?>"> + <?php if ($_total->getStrong()) : ?> + <strong><?= /* @noEscape */ $block->formatValue($_total) ?></strong> + <?php else : ?> + <?= /* @noEscape */ $block->formatValue($_total) ?> <?php endif?> </td> </tr> - <?php endif?> + <?php endif; ?> <?php endforeach?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/view.phtml b/app/code/Magento/Sales/view/frontend/templates/order/view.phtml index 1cb8533763759..273554667ffe4 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/view.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/view.phtml @@ -4,31 +4,37 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - +// phpcs:disable Magento2.Templates.ThisInTemplate ?> <?php /** @var $block \Magento\Sales\Block\Order\View*/?> <div class="order-details-items ordered"> <?php $_order = $block->getOrder() ?> <div class="order-title"> - <strong><?= /* @escapeNotVerified */ __('Items Ordered') ?></strong> - <?php if ($_order->getTracksCollection()->count()) : ?> + <strong><?= $block->escapeHtml(__('Items Ordered')) ?></strong> + <?php if (!empty($_order->getTracksCollection()->getItems())) : ?> <?= $block->getChildHtml('tracking-info-link') ?> <?php endif; ?> </div> <?= $block->getChildHtml('order_items') ?> - <?php if ($this->helper('Magento\GiftMessage\Helper\Message')->isMessagesAllowed('order', $_order) && $_order->getGiftMessageId()): ?> + <?php if ($this->helper(\Magento\GiftMessage\Helper\Message::class)->isMessagesAllowed('order', $_order) + && $_order->getGiftMessageId() + ) : ?> <div class="block block-order-details-gift-message"> - <div class="block-title"><strong><?= /* @escapeNotVerified */ __('Gift Message for This Order') ?></strong></div> - <?php $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessageForEntity($_order); ?> + <div class="block-title"><strong><?= $block->escapeHtml(__('Gift Message for This Order')) ?></strong></div> + <?php + $_giftMessage = $this->helper(\Magento\GiftMessage\Helper\Message::class)->getGiftMessageForEntity($_order); + ?> <div class="block-content"> <dl class="item-options"> - <dt class="item-sender"><strong class="label"><?= /* @escapeNotVerified */ __('From') ?></strong><?= $block->escapeHtml($_giftMessage->getSender()) ?></dt> - <dt class="item-recipient"><strong class="label"><?= /* @escapeNotVerified */ __('To') ?></strong><?= $block->escapeHtml($_giftMessage->getRecipient()) ?></dt> - <dd class="item-message"><?= /* @escapeNotVerified */ $this->helper('Magento\GiftMessage\Helper\Message')->getEscapedGiftMessage($_order) ?></dd> + <dt class="item-sender"><strong class="label"><?= $block->escapeHtml(__('From')) ?></strong><?= $block->escapeHtml($_giftMessage->getSender()) ?></dt> + <dt class="item-recipient"><strong class="label"><?= $block->escapeHtml(__('To')) ?></strong><?= $block->escapeHtml($_giftMessage->getRecipient()) ?></dt> + <dd class="item-message"> + <?= /* @noEscape */ + $this->helper(\Magento\GiftMessage\Helper\Message::class)->getEscapedGiftMessage($_order) ?> + </dd> </dl> </div> </div> @@ -36,8 +42,8 @@ <div class="actions-toolbar"> <div class="secondary"> - <a class="action back" href="<?= /* @escapeNotVerified */ $block->getBackUrl() ?>"> - <span><?= /* @escapeNotVerified */ $block->getBackTitle() ?></span> + <a class="action back" href="<?= $block->escapeUrl($block->getBackUrl()) ?>"> + <span><?= $block->escapeHtml($block->getBackTitle()) ?></span> </a> </div> </div> diff --git a/app/code/Magento/Sales/view/frontend/templates/reorder/sidebar.phtml b/app/code/Magento/Sales/view/frontend/templates/reorder/sidebar.phtml index a2ab3d02b13ea..ba1204fac8ec5 100644 --- a/app/code/Magento/Sales/view/frontend/templates/reorder/sidebar.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/reorder/sidebar.phtml @@ -4,8 +4,6 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** * Last ordered items sidebar * @@ -15,27 +13,27 @@ <div class="block block-reorder" data-bind="scope: 'lastOrderedItems'"> <div class="block-title no-display" data-bind="css: {'no-display': !lastOrderedItems().items || lastOrderedItems().items.length === 0}"> - <strong id="block-reorder-heading" role="heading" aria-level="2"><?= /* @escapeNotVerified */ __('Recently Ordered') ?></strong> + <strong id="block-reorder-heading" role="heading" aria-level="2"><?= $block->escapeHtml(__('Recently Ordered')) ?></strong> </div> <div class="block-content no-display" data-bind="css: {'no-display': !lastOrderedItems().items || lastOrderedItems().items.length === 0}" aria-labelledby="block-reorder-heading"> <form method="post" class="form reorder" - action="<?= /* @escapeNotVerified */ $block->getFormActionUrl() ?>" id="reorder-validate-detail"> - <strong class="subtitle"><?= /* @escapeNotVerified */ __('Last Ordered Items') ?></strong> + action="<?= $block->escapeUrl($block->getFormActionUrl()) ?>" id="reorder-validate-detail"> + <strong class="subtitle"><?= $block->escapeHtml(__('Last Ordered Items')) ?></strong> <ol id="cart-sidebar-reorder" class="product-items product-items-names" data-bind="foreach: lastOrderedItems().items"> <li class="product-item"> <div class="field item choice"> <label class="label" data-bind="attr: {'for': 'reorder-item-' + id}"> - <span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span> + <span><?= $block->escapeHtml(__('Add to Cart')) ?></span> </label> <div class="control"> <input type="checkbox" name="order_items[]" data-bind="attr: { id: 'reorder-item-' + id, value: id, - title: is_saleable ? '<?= /* @escapeNotVerified */ __('Add to Cart') ?>' : '<?= /* @escapeNotVerified */ __('Product is not salable.') ?>' + title: is_saleable ? '<?= $block->escapeHtml(__('Add to Cart')) ?>' : '<?= $block->escapeHtml(__('Product is not salable.')) ?>' }, disable: !is_saleable" class="checkbox" data-validate='{"validate-one-checkbox-required-by-name": true}'/> @@ -52,13 +50,13 @@ <div class="actions-toolbar"> <div class="primary" data-bind="visible: isShowAddToCart"> - <button type="submit" title="<?= /* @escapeNotVerified */ __('Add to Cart') ?>" class="action tocart primary"> - <span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span> + <button type="submit" title="<?= $block->escapeHtml(__('Add to Cart')) ?>" class="action tocart primary"> + <span><?= $block->escapeHtml(__('Add to Cart')) ?></span> </button> </div> <div class="secondary"> - <a class="action view" href="<?= /* @escapeNotVerified */ $block->getUrl('customer/account') ?>#my-orders-table"> - <span><?= /* @escapeNotVerified */ __('View All') ?></span> + <a class="action view" href="<?= $block->escapeUrl($block->getUrl('customer/account')) ?>#my-orders-table"> + <span><?= $block->escapeHtml(__('View All')) ?></span> </a> </div> </div> diff --git a/app/code/Magento/Sales/view/frontend/templates/widget/guest/form.phtml b/app/code/Magento/Sales/view/frontend/templates/widget/guest/form.phtml index ac428283dfcb0..25926688c6f47 100644 --- a/app/code/Magento/Sales/view/frontend/templates/widget/guest/form.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/widget/guest/form.phtml @@ -4,31 +4,29 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** @var $block \Magento\Sales\Block\Widget\Guest\Form */ ?> -<?php if ($block->isEnable()): ?> +<?php if ($block->isEnable()) : ?> <div class="widget block block-orders-returns"> <div class="block-title"> - <strong role="heading" aria-level="2"><?= /* @escapeNotVerified */ __('Orders and Returns') ?></strong> + <strong role="heading" aria-level="2"><?= $block->escapeHtml(__('Orders and Returns')) ?></strong> </div> <div class="block-content"> - <form id="oar-widget-orders-and-returns-form" data-mage-init='{"ordersReturns":{},"validation":{}}' action="<?= /* @escapeNotVerified */ $block->getActionUrl() ?>" method="post" + <form id="oar-widget-orders-and-returns-form" data-mage-init='{"ordersReturns":{},"validation":{}}' action="<?= $block->escapeUrl($block->getActionUrl()) ?>" method="post" class="form form-orders-search" name="guest_post"> <fieldset class="fieldset"> <div class="field find required"> - <label class="label"><span><?= /* @escapeNotVerified */ __('Find Order By') ?></span></label> + <label class="label"><span><?= $block->escapeHtml(__('Find Order By')) ?></span></label> <div class="control"> <select name="oar_type" id="quick-search-type-id" class="select" title=""> - <option value="email"><?= /* @escapeNotVerified */ __('Email') ?></option> - <option value="zip"><?= /* @escapeNotVerified */ __('ZIP Code') ?></option> + <option value="email"><?= $block->escapeHtml(__('Email')) ?></option> + <option value="zip"><?= $block->escapeHtml(__('ZIP Code')) ?></option> </select> </div> </div> <div class="field id required"> - <label for="oar-order-id" class="label"><span><?= /* @escapeNotVerified */ __('Order ID') ?></span></label> + <label for="oar-order-id" class="label"><span><?= $block->escapeHtml(__('Order ID')) ?></span></label> <div class="control"> <input type="text" class="input-text" id="oar-order-id" name="oar_order_id" autocomplete="off" @@ -37,7 +35,7 @@ </div> <div class="field lastname required"> <label for="oar-billing-lastname" - class="label"><span><?= /* @escapeNotVerified */ __('Billing Last Name') ?></span></label> + class="label"><span><?= $block->escapeHtml(__('Billing Last Name')) ?></span></label> <div class="control"> <input type="text" class="input-text" id="oar-billing-lastname" name="oar_billing_lastname" @@ -45,7 +43,7 @@ </div> </div> <div id="oar-email" class="field email required"> - <label for="oar_email" class="label"><span><?= /* @escapeNotVerified */ __('Email') ?></span></label> + <label for="oar_email" class="label"><span><?= $block->escapeHtml(__('Email')) ?></span></label> <div class="control"> <input type="email" class="input-text" id="oar_email" name="oar_email" autocomplete="off" @@ -53,7 +51,7 @@ </div> </div> <div id="oar-zip" style="display: none;" class="field zip required"> - <label for="oar_zip" class="label"><span><?= /* @escapeNotVerified */ __('Billing ZIP Code') ?></span></label> + <label for="oar_zip" class="label"><span><?= $block->escapeHtml(__('Billing ZIP Code')) ?></span></label> <div class="control"> <input type="text" class="input-text" id="oar_zip" name="oar_zip" @@ -64,7 +62,7 @@ <div class="actions-toolbar"> <div class="primary"> <button type="submit" title="<?= $block->escapeHtml(__('Search')) ?>" class="action search"> - <span><?= /* @escapeNotVerified */ __('Search') ?></span> + <span><?= $block->escapeHtml(__('Search')) ?></span> </button> </div> </div> diff --git a/dev/tests/static/testsuite/Magento/Test/Php/_files/whitelist/exempt_modules/ce.php b/dev/tests/static/testsuite/Magento/Test/Php/_files/whitelist/exempt_modules/ce.php index 7e20e72ee121d..86b68c0ff7ea4 100644 --- a/dev/tests/static/testsuite/Magento/Test/Php/_files/whitelist/exempt_modules/ce.php +++ b/dev/tests/static/testsuite/Magento/Test/Php/_files/whitelist/exempt_modules/ce.php @@ -27,7 +27,6 @@ 'Magento_PageCache', 'Magento_Paypal', 'Magento_Reports', - 'Magento_Sales', 'Magento_Search', 'Magento_Store', 'Magento_Swagger', From 6e07739a0a9b58eeb0213475db608878ab0c7c84 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Mon, 10 Jun 2019 13:05:02 -0500 Subject: [PATCH 1913/2092] MAGETWO-99930: Configuarable product stock status stays 'In Stock' --- .../Magento/Catalog/_files/product_simple.php | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple.php index dd43b403749d7..d29dd2ef163c4 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple.php @@ -5,7 +5,7 @@ */ use Magento\Catalog\Api\Data\ProductTierPriceExtensionFactory; -use Magento\Catalog\Api\Data\ProductExtensionInterfaceFactory; +use Magento\Catalog\Api\Data\ProductExtension; \Magento\TestFramework\Helper\Bootstrap::getInstance()->reinitialize(); @@ -20,15 +20,14 @@ $tierPriceFactory = $objectManager->get(\Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory::class); /** @var $tpExtensionAttributes */ $tpExtensionAttributesFactory = $objectManager->get(ProductTierPriceExtensionFactory::class); -/** @var $productExtensionAttributes */ -$productExtensionAttributesFactory = $objectManager->get(ProductExtensionInterfaceFactory::class); $adminWebsite = $objectManager->get(\Magento\Store\Api\WebsiteRepositoryInterface::class)->get('admin'); $tierPriceExtensionAttributes1 = $tpExtensionAttributesFactory->create() ->setWebsiteId($adminWebsite->getId()); -$productExtensionAttributesWebsiteIds = $productExtensionAttributesFactory->create( - ['website_ids' => $adminWebsite->getId()] -); + +/** @var $productExtension */ +$productExtensionAttributesWebsiteIds = $objectManager->get(ProductExtension::class); +$productExtensionAttributesWebsiteIds->setWebsiteIds([$adminWebsite->getId()]); $tierPrices[] = $tierPriceFactory->create( [ From 7ba6fb2a5dd6cf05e0d7e85887242766246b39fa Mon Sep 17 00:00:00 2001 From: Andrew Molina <amolina@adobe.com> Date: Mon, 10 Jun 2019 16:15:13 -0500 Subject: [PATCH 1914/2092] MC-17330: Review Order For Multi-Address Checkout w/ FPT --- .../view/frontend/templates/cart/item/price/sidebar.phtml | 3 ++- .../Checkout/view/frontend/templates/item/price/row.phtml | 3 ++- .../Checkout/view/frontend/templates/item/price/unit.phtml | 3 ++- .../templates/onepage/review/item/price/row_excl_tax.phtml | 5 ++++- .../templates/onepage/review/item/price/row_incl_tax.phtml | 5 ++++- .../templates/onepage/review/item/price/unit_excl_tax.phtml | 3 ++- .../templates/onepage/review/item/price/unit_incl_tax.phtml | 5 ++++- .../Checkout/view/frontend/templates/total/default.phtml | 3 ++- 8 files changed, 22 insertions(+), 8 deletions(-) diff --git a/app/code/Magento/Checkout/view/frontend/templates/cart/item/price/sidebar.phtml b/app/code/Magento/Checkout/view/frontend/templates/cart/item/price/sidebar.phtml index f8e692fc6f71c..1d30cfc8dc45d 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/cart/item/price/sidebar.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/cart/item/price/sidebar.phtml @@ -13,7 +13,8 @@ <span class="price-label"><?= $block->escapeHtml(__('Price')) ?></span> <span class="price-wrapper"> <?= $block->escapeHtml( - $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getCalculationPrice()) + $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getCalculationPrice()), + ['span'] ) ?> </span> </div> diff --git a/app/code/Magento/Checkout/view/frontend/templates/item/price/row.phtml b/app/code/Magento/Checkout/view/frontend/templates/item/price/row.phtml index 25124d91b6ea7..533d75b6ae843 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/item/price/row.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/item/price/row.phtml @@ -13,7 +13,8 @@ $_item = $block->getItem(); <span class="price-excluding-tax" data-label="<?= $block->escapeHtml(__('Excl. Tax')) ?>"> <span class="cart-price"> <?= $block->escapeHtml( - $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getRowTotal()) + $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getRowTotal()), + ['span'] ) ?> </span> </span> diff --git a/app/code/Magento/Checkout/view/frontend/templates/item/price/unit.phtml b/app/code/Magento/Checkout/view/frontend/templates/item/price/unit.phtml index c6ee4beb00c5a..fafbe9c7c969d 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/item/price/unit.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/item/price/unit.phtml @@ -13,7 +13,8 @@ $_item = $block->getItem(); <span class="price-including-tax" data-label="<?= $block->escapeHtml(__('Excl. Tax')) ?>"> <span class="cart-price"> <?= $block->escapeHtml( - $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getCalculationPrice()) + $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getCalculationPrice()), + ['span'] ) ?> </span> </span> diff --git a/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/row_excl_tax.phtml b/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/row_excl_tax.phtml index 909631d06e68a..64eefd0dad011 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/row_excl_tax.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/row_excl_tax.phtml @@ -11,5 +11,8 @@ $_item = $block->getItem(); ?> <span class="cart-price"> - <?= $block->escapeHtml($this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getRowTotal())) ?> + <?= $block->escapeHtml( + $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getRowTotal()), + ['span'] + ) ?> </span> diff --git a/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/row_incl_tax.phtml b/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/row_incl_tax.phtml index 9f87ab7ef2ded..14deb07640e6d 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/row_incl_tax.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/row_incl_tax.phtml @@ -12,5 +12,8 @@ $_item = $block->getItem(); ?> <?php $_incl = $this->helper(Magento\Checkout\Helper\Data::class)->getSubtotalInclTax($_item); ?> <span class="cart-price"> - <?= $block->escapeHtml($this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_incl)) ?> + <?= $block->escapeHtml( + $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_incl), + ['span'] + ) ?> </span> diff --git a/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/unit_excl_tax.phtml b/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/unit_excl_tax.phtml index 9da1cfe85e56b..a65a5a50ae1a1 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/unit_excl_tax.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/unit_excl_tax.phtml @@ -12,6 +12,7 @@ $_item = $block->getItem(); ?> <span class="cart-price"> <?= $block->escapeHtml( - $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getCalculationPrice()) + $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_item->getCalculationPrice()), + ['span'] ) ?> </span> diff --git a/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/unit_incl_tax.phtml b/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/unit_incl_tax.phtml index 8de3176e0b963..b623e1f1c3fd9 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/unit_incl_tax.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/onepage/review/item/price/unit_incl_tax.phtml @@ -12,5 +12,8 @@ $_item = $block->getItem(); ?> <?php $_incl = $this->helper(Magento\Checkout\Helper\Data::class)->getPriceInclTax($_item); ?> <span class="cart-price"> - <?= $block->escapeHtml($this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_incl)) ?> + <?= $block->escapeHtml( + $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($_incl), + ['span'] + ) ?> </span> diff --git a/app/code/Magento/Checkout/view/frontend/templates/total/default.phtml b/app/code/Magento/Checkout/view/frontend/templates/total/default.phtml index eeee3e4bf0be9..0d9da171c11a8 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/total/default.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/total/default.phtml @@ -32,7 +32,8 @@ <?php endif; ?> <span> <?= $block->escapeHtml( - $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($block->getTotal()->getValue()) + $this->helper(Magento\Checkout\Helper\Data::class)->formatPrice($block->getTotal()->getValue()), + ['span'] ) ?> </span> <?php if ($block->getRenderingArea() == $block->getTotal()->getArea()) :?> From 3f8a8b4dcd94e5c2e2a5a30ca513003f320c21fa Mon Sep 17 00:00:00 2001 From: Dave Macaulay <macaulay@adobe.com> Date: Mon, 10 Jun 2019 16:18:42 -0500 Subject: [PATCH 1915/2092] MC-17242: Eliminate @escapeNotVerified in Sales-related Modules - Resolve static failures --- .../templates/items/column/name.phtml | 2 +- .../templates/items/price/total.phtml | 2 ++ .../order/create/billing/method/form.phtml | 4 ++-- .../templates/order/create/form/address.phtml | 3 +-- .../templates/order/create/items/grid.phtml | 18 +++++++++--------- .../order/create/items/price/total.phtml | 2 ++ .../adminhtml/templates/order/totalbar.phtml | 4 ++-- .../templates/page/js/components.phtml | 2 ++ .../templates/email/items/price/row.phtml | 2 ++ .../items/price/total_after_discount.phtml | 2 ++ .../frontend/templates/js/components.phtml | 2 ++ 11 files changed, 27 insertions(+), 16 deletions(-) diff --git a/app/code/Magento/Sales/view/adminhtml/templates/items/column/name.phtml b/app/code/Magento/Sales/view/adminhtml/templates/items/column/name.phtml index 52cee7971c9f9..aae4b0db648b3 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/items/column/name.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/items/column/name.phtml @@ -28,7 +28,7 @@ <?php else : ?> <?php $_option = $block->getFormattedOption($_option['value']); ?> <?= $block->escapeHtml($_option['value']) ?> - <?php if (isset($_option['remainder']) && $_option['remainder']): ?> + <?php if (isset($_option['remainder']) && $_option['remainder']) : ?> <?php $dots = 'dots' . uniqid(); ?> <span id="<?= /* @noEscape */ $dots; ?>"> ...</span> <?php $id = 'id' . uniqid(); ?> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/items/price/total.phtml b/app/code/Magento/Sales/view/adminhtml/templates/items/price/total.phtml index 74574e5e870a2..0bd5b8d9144de 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/items/price/total.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/items/price/total.phtml @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +// phpcs:disable PSR2.Files.ClosingTag ?> <?php /** @var \Magento\Sales\Block\Adminhtml\Items\Column\DefaultColumn $block */ diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/billing/method/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/billing/method/form.phtml index f4989bfc4b447..89cc9df2e8f23 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/billing/method/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/billing/method/form.phtml @@ -17,7 +17,7 @@ <?php foreach ($_methods as $_method) : $_code = $_method->getCode(); $_counter++; - ?> + ?> <dt class="admin__field-option"> <?php if ($_methodsCount > 1) : ?> <input id="p_method_<?= $block->escapeHtmlAttr($_code); ?>" @@ -45,7 +45,7 @@ </label> </dt> <dd class="admin__payment-method-wrapper"> - <?= $block->getChildHtml('payment.method.' . $_code) ?> + <?= /* @noEscape */ $block->getChildHtml('payment.method.' . $_code) ?> </dd> <?php endforeach; ?> </dl> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml index 5ce001474f5f5..7ae29e64083e1 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml @@ -56,8 +56,7 @@ endif; ?> <?php if ($block->getIsShipping()) : ?> <div class="admin__field admin__field-option admin__field-shipping-same-as-billing"> <input type="checkbox" id="order-shipping_same_as_billing" name="shipping_same_as_billing" - onclick="order.setShippingAsBilling(this.checked)" class="admin__control-checkbox" - <?php if ($block->getIsAsBilling()) : ?>checked<?php endif; ?> /> + onclick="order.setShippingAsBilling(this.checked)" class="admin__control-checkbox" <?php if ($block->getIsAsBilling()) : ?>checked<?php endif; ?> /> <label for="order-shipping_same_as_billing" class="admin__field-label"> <?= $block->escapeHtml(__('Same As Billing Address')) ?> </label> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/grid.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/grid.phtml index cd7d215b36af5..d6821303d8c16 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/grid.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/grid.phtml @@ -93,10 +93,10 @@ <?php if ($block->canApplyCustomPrice($_item)) : ?> <div class="custom-price-block"> <input type="checkbox" - class="admin__control-checkbox" - id="item_use_custom_price_<?= (int) $_item->getId() ?>" - <?php if ($_isCustomPrice) : ?> checked="checked"<?php endif; ?> - onclick="order.toggleCustomPrice(this, 'item_custom_price_<?= (int) $_item->getId() ?>', 'item_tier_block_<?= (int) $_item->getId() ?>');"/> + class="admin__control-checkbox" + id="item_use_custom_price_<?= (int) $_item->getId() ?>" + <?php if ($_isCustomPrice) : ?> checked="checked"<?php endif; ?> + onclick="order.toggleCustomPrice(this, 'item_custom_price_<?= (int) $_item->getId() ?>', 'item_tier_block_<?= (int) $_item->getId() ?>');"/> <label class="normal admin__field-label" for="item_use_custom_price_<?= (int) $_item->getId() ?>"> @@ -125,11 +125,11 @@ <?= /* @noEscape */ $block->formatPrice(-$_item->getTotalDiscountAmount()) ?> <div class="discount-price-block"> <input id="item_use_discount_<?= (int) $_item->getId() ?>" - class="admin__control-checkbox" - name="item[<?= (int) $_item->getId() ?>][use_discount]" - <?php if (!$_item->getNoDiscount()) : ?>checked="checked"<?php endif; ?> - value="1" - type="checkbox" /> + class="admin__control-checkbox" + name="item[<?= (int) $_item->getId() ?>][use_discount]" + <?php if (!$_item->getNoDiscount()) : ?>checked="checked"<?php endif; ?> + value="1" + type="checkbox" /> <label for="item_use_discount_<?= (int) $_item->getId() ?>" class="normal admin__field-label"> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/total.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/total.phtml index 7fdf39ed2bc21..ae4bcd26e7c1e 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/total.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/items/price/total.phtml @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +// phpcs:disable PSR2.Files.ClosingTag ?> <?php /** @var \Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid $block */ diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/totalbar.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/totalbar.phtml index e3cfaa715cc32..819718af2dde2 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/totalbar.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/totalbar.phtml @@ -7,11 +7,11 @@ // @deprecated $totals = $block->getTotals(); ?> -<?php if (sizeof($block->getTotals()) > 0) : ?> +<?php if (count($block->getTotals()) > 0) : ?> <table class="items-to-invoice"> <tr> <?php foreach ($block->getTotals() as $_total) : ?> - <td <?php if ($_total['grand']): ?>class="grand-total"<?php endif; ?>> + <td <?php if ($_total['grand']) : ?>class="grand-total"<?php endif; ?>> <?= $block->escapeHtml($_total['label']) ?><br /> <?= $block->escapeHtml($_total['value']) ?> </td> diff --git a/app/code/Magento/Sales/view/adminhtml/templates/page/js/components.phtml b/app/code/Magento/Sales/view/adminhtml/templates/page/js/components.phtml index 5902a9f25cc4b..13f44b97fc789 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/page/js/components.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/page/js/components.phtml @@ -3,5 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +// phpcs:disable PSR2.Files.ClosingTag ?> <?= $block->getChildHtml() ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/email/items/price/row.phtml b/app/code/Magento/Sales/view/frontend/templates/email/items/price/row.phtml index a2148a4f8fcb9..bafae71ba75b4 100644 --- a/app/code/Magento/Sales/view/frontend/templates/email/items/price/row.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/email/items/price/row.phtml @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +// phpcs:disable PSR2.Files.ClosingTag ?> <?php /** @var \Magento\Sales\Block\Order\Email\Items\DefaultItems $block */ diff --git a/app/code/Magento/Sales/view/frontend/templates/items/price/total_after_discount.phtml b/app/code/Magento/Sales/view/frontend/templates/items/price/total_after_discount.phtml index 493f30fba59ba..458c6d1e32fa8 100644 --- a/app/code/Magento/Sales/view/frontend/templates/items/price/total_after_discount.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/items/price/total_after_discount.phtml @@ -4,6 +4,8 @@ * See COPYING.txt for license details. */ +// phpcs:disable PSR2.Files.ClosingTag + /** @var \Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer $block */ $_item = $block->getItem(); ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/js/components.phtml b/app/code/Magento/Sales/view/frontend/templates/js/components.phtml index 5902a9f25cc4b..13f44b97fc789 100644 --- a/app/code/Magento/Sales/view/frontend/templates/js/components.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/js/components.phtml @@ -3,5 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +// phpcs:disable PSR2.Files.ClosingTag ?> <?= $block->getChildHtml() ?> From bace8e85c97033c1664641fc987f2c7a02e7d6d7 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Mon, 10 Jun 2019 16:28:50 -0500 Subject: [PATCH 1916/2092] MAGETWO-99930: Configuarable product stock status stays 'In Stock' --- .../SaveInventoryDataObserverTest.php | 85 ------------------- 1 file changed, 85 deletions(-) delete mode 100644 dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php diff --git a/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php b/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php deleted file mode 100644 index 1b986b7670a1c..0000000000000 --- a/dev/tests/integration/testsuite/Magento/CatalogInventory/Observer/SaveInventoryDataObserverTest.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -namespace Magento\CatalogInventory\Observer; - -use Magento\TestFramework\Helper\Bootstrap; -use PHPUnit\Framework\TestCase; -use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Catalog\Api\Data\ProductExtensionInterface; -use Magento\Catalog\Api\Data\ProductInterface; -use Magento\CatalogInventory\Api\Data\StockItemInterface; -use Magento\CatalogInventory\Api\StockItemRepositoryInterface; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Framework\Exception\InputException; -use Magento\Framework\Exception\StateException; -use Magento\Framework\Exception\CouldNotSaveException; - -/** - * Test for SaveInventoryDataObserver - */ -class SaveInventoryDataObserverTest extends TestCase -{ - /** - * @var ProductRepositoryInterface - */ - private $productRepository; - - /** - * @var StockItemRepositoryInterface - */ - private $stockItemRepository; - - /** - * @inheritDoc - */ - protected function setUp() - { - $this->productRepository = Bootstrap::getObjectManager() - ->get(ProductRepositoryInterface::class); - $this->stockItemRepository = Bootstrap::getObjectManager() - ->get(StockItemRepositoryInterface::class); - } - - /** - * Check that parent product will be out of stock - * - * @magentoAppArea adminhtml - * @magentoAppIsolation enabled - * @magentoDataFixture Magento/CatalogInventory/_files/configurable_options_with_low_stock.php - * @throws NoSuchEntityException - * @throws InputException - * @throws StateException - * @throws CouldNotSaveException - * @return void - */ - public function testAutoChangingIsInStockForParent() - { - /** @var ProductInterface $product */ - $product = $this->productRepository->get('simple_10'); - - /** @var ProductExtensionInterface $attributes*/ - $attributes = $product->getExtensionAttributes(); - - /** @var StockItemInterface $stockItem */ - $stockItem = $attributes->getStockItem(); - $stockItem->setQty(0); - $stockItem->setIsInStock(false); - $attributes->setStockItem($stockItem); - $product->setExtensionAttributes($attributes); - $this->productRepository->save($product); - - /** @var ProductInterface $product */ - $parentProduct = $this->productRepository->get('configurable'); - - $parentProductStockItem = $this->stockItemRepository->get( - $parentProduct->getExtensionAttributes()->getStockItem()->getItemId() - ); - $this->assertSame(false, $parentProductStockItem->getIsInStock()); - } -} From 4b0014c0807cdafa6d2ec922a2a51416c864ecc1 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Mon, 10 Jun 2019 17:11:26 -0500 Subject: [PATCH 1917/2092] MAGETWO-99930: Configuarable product stock status stays 'In Stock' --- .../Magento/Catalog/_files/product_simple.php | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple.php b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple.php index d29dd2ef163c4..dd43b403749d7 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/_files/product_simple.php @@ -5,7 +5,7 @@ */ use Magento\Catalog\Api\Data\ProductTierPriceExtensionFactory; -use Magento\Catalog\Api\Data\ProductExtension; +use Magento\Catalog\Api\Data\ProductExtensionInterfaceFactory; \Magento\TestFramework\Helper\Bootstrap::getInstance()->reinitialize(); @@ -20,14 +20,15 @@ $tierPriceFactory = $objectManager->get(\Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory::class); /** @var $tpExtensionAttributes */ $tpExtensionAttributesFactory = $objectManager->get(ProductTierPriceExtensionFactory::class); +/** @var $productExtensionAttributes */ +$productExtensionAttributesFactory = $objectManager->get(ProductExtensionInterfaceFactory::class); $adminWebsite = $objectManager->get(\Magento\Store\Api\WebsiteRepositoryInterface::class)->get('admin'); $tierPriceExtensionAttributes1 = $tpExtensionAttributesFactory->create() ->setWebsiteId($adminWebsite->getId()); - -/** @var $productExtension */ -$productExtensionAttributesWebsiteIds = $objectManager->get(ProductExtension::class); -$productExtensionAttributesWebsiteIds->setWebsiteIds([$adminWebsite->getId()]); +$productExtensionAttributesWebsiteIds = $productExtensionAttributesFactory->create( + ['website_ids' => $adminWebsite->getId()] +); $tierPrices[] = $tierPriceFactory->create( [ From 3347865aca67e0c3f381a6d880594de72a7c26f2 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Mon, 10 Jun 2019 17:44:09 -0500 Subject: [PATCH 1918/2092] MC-10023: Product Categories Indexer in Update on Schedule mode --- ...ignCategoryToProductAndSaveActionGroup.xml | 24 ++ ...ignCategoryOnProductAndSaveActionGroup.xml | 22 ++ .../StorefrontGoToCategoryPageActionGroup.xml | 27 ++ .../Section/AdminProductFormActionSection.xml | 1 + .../Mftf/Section/AdminProductFormSection.xml | 4 + .../Section/StorefrontCategoryMainSection.xml | 1 + ...egoryIndexerInUpdateOnScheduleModeTest.xml | 321 ++++++++++++++++++ ...witchAllIndexerToActionModeActionGroup.xml | 23 ++ ...inSwitchIndexerToActionModeActionGroup.xml | 22 ++ .../Section/AdminIndexManagementSection.xml | 1 + 10 files changed, 446 insertions(+) create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignCategoryToProductAndSaveActionGroup.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminUnassignCategoryOnProductAndSaveActionGroup.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontGoToCategoryPageActionGroup.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml create mode 100644 app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchAllIndexerToActionModeActionGroup.xml create mode 100644 app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignCategoryToProductAndSaveActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignCategoryToProductAndSaveActionGroup.xml new file mode 100644 index 0000000000000..3ac7aa6d37cba --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignCategoryToProductAndSaveActionGroup.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAssignCategoryToProductAndSaveActionGroup"> + <arguments> + <argument name="categoryName" type="string"/> + </arguments> + <!-- on edit Product page catalog/product/edit/id/{{product_id}}/ --> + <click selector="{{AdminProductFormSection.categoriesDropdown}}" stepKey="openDropDown"/> + <checkOption selector="{{AdminProductFormSection.selectCategory(categoryName)}}" stepKey="selectCategory"/> + <click selector="{{AdminProductFormSection.done}}" stepKey="clickDone"/> + <waitForPageLoad stepKey="waitForApplyCategory"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> + <waitForPageLoad stepKey="waitForSavingProduct"/> + <see userInput="You saved the product." selector="{{AdminProductFormActionSection.messageSuccessSavedProduct}}" stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminUnassignCategoryOnProductAndSaveActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminUnassignCategoryOnProductAndSaveActionGroup.xml new file mode 100644 index 0000000000000..503302b7f1e1a --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminUnassignCategoryOnProductAndSaveActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminUnassignCategoryOnProductAndSaveActionGroup"> + <arguments> + <argument name="categoryName" type="string"/> + </arguments> + <!-- on edit Product page catalog/product/edit/id/{{product_id}}/ --> + <click selector="{{AdminProductFormSection.unselectCategories(categoryName)}}" stepKey="clearCategory"/> + <waitForPageLoad stepKey="waitForDelete"/> + <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> + <waitForPageLoad stepKey="waitForSavingProduct"/> + <see userInput="You saved the product." selector="{{AdminProductFormActionSection.messageSuccessSavedProduct}}" stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontGoToCategoryPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontGoToCategoryPageActionGroup.xml new file mode 100644 index 0000000000000..1a8da822855ea --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontGoToCategoryPageActionGroup.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontGoToCategoryPageActionGroup"> + <arguments> + <argument name="categoryName" type="string"/> + </arguments> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="onFrontend"/> + <waitForPageLoad stepKey="waitForStorefrontPageLoad"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName(categoryName)}}" stepKey="toCategory"/> + <waitForPageLoad stepKey="waitForCategoryPage"/> + </actionGroup> + <actionGroup name="StorefrontGoToSubCategoryPageActionGroup" extends="StorefrontGoToCategoryPageActionGroup"> + <arguments> + <argument name="subCategoryName" type="string"/> + </arguments> + <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName(categoryName)}}" stepKey="toCategory"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName(subCategoryName)}}" stepKey="openSubCategory" after="toCategory"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormActionSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormActionSection.xml index 3eab31e32cc24..95a55c5bf17cd 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormActionSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormActionSection.xml @@ -15,5 +15,6 @@ <element name="changeStoreButton" type="button" selector="#store-change-button"/> <element name="selectStoreView" type="button" selector="//ul[@data-role='stores-list']/li/a[normalize-space(.)='{{var1}}']" timeout="10" parameterized="true"/> <element name="saveAndNew" type="button" selector="#save_and_new" timeout="30"/> + <element name="messageSuccessSavedProduct" type="button" selector="//div[@data-ui-id='messages-message-success']"/> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml index 4b754f97f8b89..5da8d8fdef12c 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml @@ -43,6 +43,10 @@ <element name="customAttributeDropdownField" type="select" selector="select[name='product[{{attributeCode}}]']" parameterized="true"/> <element name="customAttributeInputField" type="select" selector="input[name='product[{{attributeCode}}]']" parameterized="true"/> <element name="customAttributeSelectOptions" type="select" selector="select[name='product[{{attributeCode}}]'] option" parameterized="true"/> + <element name="enableProductLabel" type="checkbox" selector=".admin__actions-switch > input[name='product[status]']+label"/> + <element name="selectCategory" type="input" selector="//*[@data-index='category_ids']//label[contains(., '{{categoryName}}')]" parameterized="true"/> + <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button[@data-action='remove-selected-item']" parameterized="true" timeout="30"/> + <element name="done" type="button" selector="//*[@data-index='category_ids']//button[@data-action='close-advanced-select']" timeout="30"/> </section> <section name="ProductInWebsitesSection"> <element name="sectionHeader" type="button" selector="div[data-index='websites']" timeout="30"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryMainSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryMainSection.xml index 3c769f9dbc0ce..9f5271bc45342 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryMainSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryMainSection.xml @@ -23,5 +23,6 @@ <element name="categoryPageProductImage" type="text" selector=".products-grid img[src*='/{{var1}}']" parameterized="true"/> <element name="categoryPageProductName" type="text" selector=".products.list.items.product-items li:nth-of-type({{line}}) .product-item-link" timeout="30" parameterized="true"/> <element name="categoryEmptyMessage" type="text" selector=".column.main .message.info.empty"/> + <element name="productName" type="text" selector=".product-item-name"/> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml new file mode 100644 index 0000000000000..6b539f1884dfd --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml @@ -0,0 +1,321 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminProductCategoryIndexerInUpdateOnScheduleModeTest"> + <annotations> + <stories value="Product Categories Indexer"/> + <title value="Product Categories Indexer in Update on Schedule mode"/> + <description value="The test verifies that in Update on Schedule mode if displaying of category products on Storefront changes due to product properties change, + the changes are NOT applied immediately, but applied only after cron runs (twice)."/> + <severity value="CRITICAL"/> + <testCaseId value="MC-10023"/> + <group value="catalog"/> + <group value="indexer"/> + </annotations> + <before> + <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <!-- Create category A without products --> + <createData entity="_defaultCategory" stepKey="createCategoryA"/> + + <!-- Create product A1 not assigned to any category --> + <createData entity="SimpleProduct3" stepKey="createProductA1"/> + + <!-- Create anchor category B with subcategory C--> + <createData entity="_defaultCategory" stepKey="createCategoryB"/> + <createData entity="SubCategoryWithParent" stepKey="createCategoryC"> + <requiredEntity createDataKey="createCategoryB"/> + </createData> + + <!-- Assign product B1 to category B --> + <createData entity="ApiSimpleProduct" stepKey="createProductB1"> + <requiredEntity createDataKey="createCategoryB"/> + </createData> + + <!-- Assign product C1 to category C --> + <createData entity="ApiSimpleProduct" stepKey="createProductC1"> + <requiredEntity createDataKey="createCategoryC"/> + </createData> + + <!-- Assign product C2 to category C --> + <createData entity="ApiSimpleProduct" stepKey="createProductC2"> + <requiredEntity createDataKey="createCategoryC"/> + </createData> + + <!-- Switch indexers to "Update by Schedule" mode --> + <actionGroup ref="AdminSwitchAllIndexerToActionModeActionGroup" stepKey="onUpdateBySchedule"> + <argument name="action" value="Update by Schedule"/> + </actionGroup> + </before> + <after> + <!-- Switch indexers to "Update on Save" mode --> + <actionGroup ref="AdminSwitchAllIndexerToActionModeActionGroup" stepKey="onUpdateOnSave"> + <argument name="action" value="Update on Save"/> + </actionGroup> + <!-- Delete data --> + <deleteData createDataKey="createProductA1" stepKey="deleteProductA1"/> + <deleteData createDataKey="createProductB1" stepKey="deleteProductB1"/> + <deleteData createDataKey="createProductC1" stepKey="deleteProductC1"/> + <deleteData createDataKey="createProductC2" stepKey="deleteProductC2"/> + <deleteData createDataKey="createCategoryA" stepKey="deleteCategoryA"/> + <deleteData createDataKey="createCategoryC" stepKey="deleteCategoryC"/> + <deleteData createDataKey="createCategoryB" stepKey="deleteCategoryB"/> + <actionGroup ref="logout" stepKey="logout"/> + </after> + + <!-- Case: change product category from product page --> + <!-- 1. Open Admin > Catalog > Products > Product A1 --> + <amOnPage url="{{AdminProductEditPage.url($$createProductA1.id$$)}}" stepKey="goToProductA1"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + + <!-- 2. Assign category A to product A1. Save product --> + <actionGroup ref="AdminAssignCategoryToProductAndSaveActionGroup" stepKey="assignProduct"> + <argument name="categoryName" value="$$createCategoryA.name$$"/> + </actionGroup> + + <!-- 3. Open category A on Storefront --> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="goToCategoryA"> + <argument name="categoryName" value="$$createCategoryA.name$$"/> + </actionGroup> + + <!-- The category is still empty --> + <see userInput="$$createCategoryA.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeCategoryA1Name"/> + <see userInput="We can't find products matching the selection." stepKey="seeEmptyNotice"/> + <dontSee userInput="$$createProductA1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontseeProductA1"/> + + <!-- 4. Run cron to reindex --> + <wait time="60" stepKey="waitForChanges"/> + <magentoCLI command="cron:run" stepKey="runCron"/> + <magentoCLI command="cron:run" stepKey="runTwiceCron"/> + + <!-- 5. Open category A on Storefront again --> + <reloadPage stepKey="reloadCategoryA"/> + + <!-- Category A displays product A1 now --> + <see userInput="$$createCategoryA.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeTitleCategoryA1"/> + <see userInput="$$createProductA1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProductA1"/> + + <!--6. Open Admin > Catalog > Products > Product A1. Unassign category A from product A1 --> + <amOnPage url="{{AdminProductEditPage.url($$createProductA1.id$$)}}" stepKey="OnPageProductA1"/> + <waitForPageLoad stepKey="waitForProductA1PageLoad"/> + <actionGroup ref="AdminUnassignCategoryOnProductAndSaveActionGroup" stepKey="unassignCategoryA"> + <argument name="categoryName" value="$$createCategoryA.name$$"/> + </actionGroup> + + <!-- 7. Open category A on Storefront --> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="toCategoryA"> + <argument name="categoryName" value="$$createCategoryA.name$$"/> + </actionGroup> + + <!-- Category A still contains product A1 --> + <see userInput="$$createCategoryA.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeCategoryAOnPage"/> + <see userInput="$$createProductA1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeNameProductA1"/> + + <!-- 8. Run cron reindex (Ensure that at least one minute passed since last cron run) --> + <wait time="60" stepKey="waitOneMinute"/> + <magentoCLI command="cron:run" stepKey="runCron1"/> + <magentoCLI command="cron:run" stepKey="runTwiceCron1"/> + + <!-- 9. Open category A on Storefront again --> + <reloadPage stepKey="refreshCategoryAPage"/> + + <!-- Category A is empty now --> + <see userInput="$$createCategoryA.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeOnPageCategoryAName"/> + <see userInput="We can't find products matching the selection." stepKey="seeOnPageEmptyNotice"/> + <dontSee userInput="$$createProductA1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontseeProductA1OnPage"/> + + <!-- Case: change product status --> + <!-- 10. Open category B on Storefront --> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="toCategoryB"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + </actionGroup> + + <!-- Category B displays product B1, C1 and C2 --> + <see userInput="$$createCategoryB.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeCategoryBOnPage"/> + <see userInput="$$createProductB1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeNameProductB1"/> + <see userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeNameProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeNameProductC2"/> + + <!-- 11. Open product C1 in Admin. Make it disabled (Enable Product = No)--> + <amOnPage url="{{AdminProductEditPage.url($$createProductC1.id$$)}}" stepKey="goToProductC1"/> + <waitForPageLoad stepKey="waitForProductC1PageLoad"/> + <scrollToTopOfPage stepKey="scrollToTop"/> + <click selector="{{AdminProductFormSection.enableProductLabel}}" stepKey="clickOffEnableToggleAgain"/> + <!-- Saved successfully --> + <actionGroup ref="saveProductForm" stepKey="saveProductC1"/> + + <!-- 12. Open category B on Storefront --> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="toCategoryBStorefront"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + </actionGroup> + + <!-- Category B displays product B1, C1 and C2 --> + <see userInput="$$createCategoryB.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="categoryBOnPage"/> + <see userInput="$$createProductB1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProductB1"/> + <see userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProductC2"/> + + <!-- 13. Open category C on Storefront --> + <actionGroup ref="StorefrontGoToSubCategoryPageActionGroup" stepKey="goToCategoryC"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + <argument name="subCategoryName" value="$$createCategoryC.name$$"/> + </actionGroup> + + <!-- Category C still displays products C1 and C2 --> + <see userInput="$$createCategoryC.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="categoryCOnPage"/> + <see userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProductC1inCategoryC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProductC2InCategoryC2"/> + + <!-- 14. Run cron to reindex (Ensure that at least one minute passed since last cron run) --> + <wait time="60" stepKey="waitMinute"/> + <magentoCLI command="cron:run" stepKey="runCron2"/> + <magentoCLI command="cron:run" stepKey="runTwiceCron2"/> + + <!-- 15. Open category B on Storefront --> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="onPageCategoryB"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + </actionGroup> + + <!-- Category B displays product B1 and C2 only--> + <see userInput="$$createCategoryB.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeTitleCategoryBOnPage"/> + <see userInput="$$createProductB1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeOnCategoryBPageProductB1"/> + <dontSee userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontSeeOnCategoryBPageProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeOnCategoryBPageProductC2"/> + + <!-- 16. Open category C on Storefront --> + <actionGroup ref="StorefrontGoToSubCategoryPageActionGroup" stepKey="openCategoryC"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + <argument name="subCategoryName" value="$$createCategoryC.name$$"/> + </actionGroup> + + <!-- Category C displays only product C2 now --> + <see userInput="$$createCategoryC.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeTitleOnCategoryCPage"/> + <dontSee userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontSeeOnCategoryCPageProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeOnCategoryCPageProductC2"/> + + <!-- 17. Repeat steps 10-16, but enable products instead. --> + <!-- 17.11 Open product C1 in Admin. Make it enabled --> + <amOnPage url="{{AdminProductEditPage.url($$createProductC1.id$$)}}" stepKey="goToEditProductC1"/> + <waitForPageLoad stepKey="waitForProductC1Page"/> + <scrollToTopOfPage stepKey="scrollTopOfProductPage"/> + <click selector="{{AdminProductFormSection.enableProductLabel}}" stepKey="clickOnEnableToggleAgain"/> + + <!-- Saved successfully --> + <actionGroup ref="saveProductForm" stepKey="saveChangedProductC1"/> + + <!-- 17.12. Open category B on Storefront --> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="openCategoryB"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + </actionGroup> + + <!-- Category B displays product B1 and C2 --> + <see userInput="$$createCategoryB.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="titleCategoryBOnPage"/> + <see userInput="$$createProductB1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeCategoryBPageProductB1"/> + <dontSee userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontSeeCategoryBPageProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeCategoryBPageProductC2"/> + + <!-- 17.13. Open category C on Storefront --> + <actionGroup ref="StorefrontGoToSubCategoryPageActionGroup" stepKey="openToCategoryC"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + <argument name="subCategoryName" value="$$createCategoryC.name$$"/> + </actionGroup> + + <!-- Category C displays product C2 --> + <see userInput="$$createCategoryC.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="titleOnCategoryCPage"/> + <dontSee userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontSeeCategoryCPageProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeCategoryCPageProductC2"/> + + <!-- 17.14. Run cron to reindex (Ensure that at least one minute passed since last cron run) --> + <wait time="60" stepKey="waitForOneMinute"/> + <magentoCLI command="cron:run" stepKey="runCron3"/> + <magentoCLI command="cron:run" stepKey="runTwiceCron3"/> + + <!-- 17.15. Open category B on Storefront --> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="openPageCategoryB"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + </actionGroup> + + <!-- Category B displays products B1, C1, C2 again, but only after reindex. --> + <see userInput="$$createCategoryB.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="onPageSeeCategoryBTitle"/> + <see userInput="$$createProductB1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="onPageSeeCategoryBProductB1"/> + <see userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="onPageSeeCategoryBProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="onPageSeeCategoryBProductC2"/> + + <!-- 17.16. Open category C on Storefront --> + <actionGroup ref="StorefrontGoToSubCategoryPageActionGroup" stepKey="openOnStorefrontCategoryC"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + <argument name="subCategoryName" value="$$createCategoryC.name$$"/> + </actionGroup> + + <!-- Category C displays products C1, C2 again, but only after reindex.--> + <see userInput="$$createCategoryC.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="onPageSeeCategoryCTitle"/> + <see userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="onPageSeeCategoryCProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="onPageSeeCategoryCProductC2"/> + + <!-- Case: change product visibility --> + <!-- 18. Repeat steps 10-17 but change product Visibility instead of product status --> + <!-- 18.11 Open product C1 in Admin. Make it enabled --> + <amOnPage url="{{AdminProductEditPage.url($$createProductC1.id$$)}}" stepKey="editProductC1"/> + <waitForPageLoad stepKey="waitProductC1Page"/> + <selectOption selector="{{AdminProductFormSection.visibility}}" userInput="Search" + stepKey="changeVisibility"/> + + <!-- Saved successfully --> + <actionGroup ref="saveProductForm" stepKey="productC1Saved"/> + + <!-- 18.12. Open category B on Storefront --> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="goPageCategoryB"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + </actionGroup> + + <!-- Category B displays products B1, C1, C2 again, but only after reindex. --> + <see userInput="$$createCategoryB.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeCategoryBTitle"/> + <see userInput="$$createProductB1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeCategoryBProductB1"/> + <see userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeCategoryBProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeCategoryBProductC2"/> + + <!-- 18.13. Open category C on Storefront --> + <actionGroup ref="StorefrontGoToSubCategoryPageActionGroup" stepKey="goPageCategoryC"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + <argument name="subCategoryName" value="$$createCategoryC.name$$"/> + </actionGroup> + + <!-- Category C displays products C1, C2 again, but only after reindex.--> + <see userInput="$$createCategoryC.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeCategoryCTitle"/> + <see userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeOnCategoryCProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeOnCategoryCProductC2"/> + + <!-- 18.14. Run cron to reindex (Ensure that at least one minute passed since last cron run) --> + <wait time="60" stepKey="waitExtraMinute"/> + <magentoCLI command="cron:run" stepKey="runCron4"/> + <magentoCLI command="cron:run" stepKey="runTwiceCron4"/> + + <!-- 18.15. Open category B on Storefront --> + <actionGroup ref="StorefrontGoToCategoryPageActionGroup" stepKey="navigateToPageCategoryB"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + </actionGroup> + + <!-- Category B displays product B1 and C2 only--> + <see userInput="$$createCategoryB.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeTitleCategoryB"/> + <see userInput="$$createProductB1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeTitleProductB1"/> + <dontSee userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontseeCategoryBProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeTitleProductC2"/> + + <!-- 18.18. Open category C on Storefront --> + <actionGroup ref="StorefrontGoToSubCategoryPageActionGroup" stepKey="navigateToPageCategoryC"> + <argument name="categoryName" value="$$createCategoryB.name$$"/> + <argument name="subCategoryName" value="$$createCategoryC.name$$"/> + </actionGroup> + + <!-- Category C displays product C2 again, but only after reindex.--> + <see userInput="$$createCategoryC.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeTitleCategoryC"/> + <dontSee userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontSeeOnCategoryCProductC1"/> + <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeOnPageTitleProductC2"/> + </test> +</tests> diff --git a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchAllIndexerToActionModeActionGroup.xml b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchAllIndexerToActionModeActionGroup.xml new file mode 100644 index 0000000000000..ab6bee0bf234a --- /dev/null +++ b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchAllIndexerToActionModeActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSwitchAllIndexerToActionModeActionGroup"> + <arguments> + <argument name="action" type="string" defaultValue="Update by Schedule"/> + </arguments> + <amOnPage url="{{AdminIndexManagementPage.url}}" stepKey="onIndexManagement"/> + <waitForPageLoad stepKey="waitForManagementPage"/> + <selectOption userInput="selectAll" selector="{{AdminIndexManagementSection.selectMassAction}}" stepKey="checkIndexer"/> + <selectOption userInput="{{action}}" selector="{{AdminIndexManagementSection.massActionSelect}}" stepKey="selectAction"/> + <click selector="{{AdminIndexManagementSection.massActionSubmit}}" stepKey="clickSubmit"/> + <waitForPageLoad stepKey="waitForSubmit"/> + <see userInput="indexer(s) are in "{{action}}" mode." stepKey="seeMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml new file mode 100644 index 0000000000000..8137b292e7d71 --- /dev/null +++ b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSwitchIndexerToActionModeActionGroup"> + <arguments> + <argument name="indexerValue" type="string"/> + <argument name="action" type="string" defaultValue="Update by Schedule"/> + </arguments> + <checkOption selector="{{AdminIndexManagementSection.indexerCheckbox(indexerValue)}}" stepKey="checkIndexer"/> + <selectOption userInput="{{action}}" selector="{{AdminIndexManagementSection.massActionSelect}}" stepKey="selectAction"/> + <click selector="{{AdminIndexManagementSection.massActionSubmit}}" stepKey="clickSubmit"/> + <waitForPageLoad stepKey="waitForSubmit"/> + <see selector="{{AdminIndexManagementSection.successMessage}}" userInput="1 indexer(s) are in "{{action}}" mode." stepKey="seeMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml b/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml index 07d93ff850221..dad163107eb3e 100644 --- a/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml +++ b/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml @@ -12,5 +12,6 @@ <element name="indexerCheckbox" type="checkbox" selector="#gridIndexer_table input[value='{{indexerId}}']" parameterized="true"/> <element name="massActionSelect" type="select" selector="#gridIndexer_massaction-select"/> <element name="massActionSubmit" type="button" selector="#gridIndexer_massaction-form button" timeout="30"/> + <element name="selectMassAction" type="select" selector="#gridIndexer_massaction-mass-select"/> </section> </sections> From 67c15d8609f8aef01246bce4f3bebad12f8f3981 Mon Sep 17 00:00:00 2001 From: Viktor Sevch <svitja@ukr.net> Date: Tue, 11 Jun 2019 10:21:57 +0300 Subject: [PATCH 1919/2092] MAGETWO-86335: [2.2] Product belongs to categories with and without event does not shown --- .../StorefrontCategoryActionGroup.xml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml index e46bfc7ee8b02..8b55737fc373d 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml @@ -34,9 +34,26 @@ <seeElement selector="{{StorefrontCategoryProductSection.productTitleByName(product.name)}}" stepKey="assertProductName"/> <see userInput="${{product.price}}.00" selector="{{StorefrontCategoryProductSection.ProductPriceByName(product.name)}}" stepKey="AssertProductPrice"/> <moveMouseOver selector="{{StorefrontCategoryProductSection.ProductInfoByName(product.name)}}" stepKey="moveMouseOverProduct" /> + <executeInSelenium function="function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) use($I) { + $selProdName = '//main//li[.//a[contains(text(), \'' . {{product.name}} . '\' )]]//div[@data-container=\'product-grid\']'; + $I->assertEquals('2', $webdriver->findElement(\Facebook\WebDriver\WebDriverBy::xpath($selProdName))->getCSSValue('z-index')); + }" stepKey="assertProductContainerIsOpened"/> <seeElement selector="{{StorefrontCategoryProductSection.productAddToCartByName(product.name)}}" stepKey="AssertAddToCart" /> </actionGroup> + <actionGroup name="StorefrontCheckAddToCartButtonAbsence"> + <arguments> + <argument name="product" defaultValue="_defaultProduct"/> + </arguments> + <seeElement selector="{{StorefrontCategoryProductSection.productTitleByName(product.name)}}" stepKey="assertProductName"/> + <moveMouseOver selector="{{StorefrontCategoryProductSection.ProductInfoByName(product.name)}}" stepKey="moveMouseOverProduct" /> + <executeInSelenium function="function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) use($I) { + $selProdName = '//main//li[.//a[contains(text(), \'' . {{product.name}} . '\' )]]//div[@data-container=\'product-grid\']'; + $I->assertEquals('2', $webdriver->findElement(\Facebook\WebDriver\WebDriverBy::xpath($selProdName))->getCSSValue('z-index')); + }" stepKey="assertProductContainerIsOpened"/> + <dontSeeElement selector="{{StorefrontCategoryProductSection.productAddToCartByName(product.name)}}" stepKey="checkAddToCartButtonAbsence"/> + </actionGroup> + <actionGroup name="StorefrontSwitchCategoryViewToListMode"> <click selector="{{StorefrontCategoryMainSection.modeListButton}}" stepKey="switchCategoryViewToListMode"/> <seeElement selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="assertCategoryTitle"/> From b0c7449c853c0801d6754de93749ed45918263b0 Mon Sep 17 00:00:00 2001 From: DianaRusin <rusind95@gmail.com> Date: Tue, 11 Jun 2019 13:15:33 +0300 Subject: [PATCH 1920/2092] MAGETWO-86624: [2.2] Allowed countries restriction for a default website is applied to backend customer grid --- .../Backend/Test/Mftf/ActionGroup/ConfigurationActionGroup.xml | 2 +- app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml | 2 +- app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml | 2 +- .../Test/Mftf/Page/AdminConfigurationGeneralSectionPage.xml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/ConfigurationActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/ConfigurationActionGroup.xml index 6164cdde22e60..96eac98765d9d 100644 --- a/app/code/Magento/Backend/Test/Mftf/ActionGroup/ConfigurationActionGroup.xml +++ b/app/code/Magento/Backend/Test/Mftf/ActionGroup/ConfigurationActionGroup.xml @@ -6,7 +6,7 @@ */ --> -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../dev/tests/acceptance/vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Test/etc/actionGroupSchema.xsd"> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="SelectTopDestinationsCountry"> <arguments> <argument name="countries"/> diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml index ded825ea89098..90b4e6d0bdaa9 100644 --- a/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminConfigPage.xml @@ -5,7 +5,7 @@ * See COPYING.txt for license details. */ --> -<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../dev/tests/acceptance/vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Page/etc/PageObject.xsd"> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> <page name="AdminConfigPage" url="admin/system_config/" area="admin" module="Magento_Config"> <section name="AdminConfigSection"/> </page> diff --git a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml index 18a124ac669ec..409a9222eebec 100644 --- a/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml +++ b/app/code/Magento/Config/Test/Mftf/Section/GeneralSection.xml @@ -7,7 +7,7 @@ --> <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="../../../../../../../dev/tests/acceptance/vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Page/etc/SectionObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="ContentManagementSection"> <element name="WYSIWYGOptions" type="button" selector="#cms_wysiwyg-head"/> <element name="CheckIfTabExpand" type="button" selector="#cms_wysiwyg-head:not(.open)"/> diff --git a/app/code/Magento/Directory/Test/Mftf/Page/AdminConfigurationGeneralSectionPage.xml b/app/code/Magento/Directory/Test/Mftf/Page/AdminConfigurationGeneralSectionPage.xml index 30016d9fa650a..edbc33c1de339 100644 --- a/app/code/Magento/Directory/Test/Mftf/Page/AdminConfigurationGeneralSectionPage.xml +++ b/app/code/Magento/Directory/Test/Mftf/Page/AdminConfigurationGeneralSectionPage.xml @@ -6,7 +6,7 @@ */ --> <pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="../../../../../../../dev/tests/acceptance/vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Page/etc/PageObject.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> <page name="AdminConfigurationGeneralSectionPage" url="admin/system_config/edit/section/general/{{group_anchor}}" parameterized="true" area="admin" module="Magento_Config"> <section name="AdminConfigurationGeneralSectionStateOptionsGroupSection"/> <section name="AdminConfigurationGeneralCountryOptionsSection"/> From ea5b2bd47de8f732872d4469c6fa558731ecb368 Mon Sep 17 00:00:00 2001 From: DianaRusin <rusind95@gmail.com> Date: Tue, 11 Jun 2019 14:12:42 +0300 Subject: [PATCH 1921/2092] MAGETWO-86624: [2.2] Allowed countries restriction for a default website is applied to backend customer grid --- .../Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml index 1a5374ca19831..53bdf7c537520 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml @@ -12,7 +12,7 @@ <title value="Country filter on Customers page when allowed countries restriction for a default website is applied"/> <description value="Country filter on Customers page when allowed countries restriction for a default website is applied"/> <features value="Customer"/> - <stories value="Customer grid filter by country"/> + <stories value="Admin Customer Grid"/> <severity value="MAJOR"/> <testCaseId value="MC-17282"/> <useCaseId value="MAGETWO-86624"/> From 6f84c2cce82315c85500e23393ff54fde6b4b37e Mon Sep 17 00:00:00 2001 From: Viktor Sevch <svitja@ukr.net> Date: Tue, 11 Jun 2019 16:46:07 +0300 Subject: [PATCH 1922/2092] MC-17384: Eliminate @escapeNotVerified in Google-related Modules --- .../view/frontend/templates/code.phtml | 22 ++++++++++--------- .../view/frontend/templates/ga.phtml | 9 +++----- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/app/code/Magento/GoogleAdwords/view/frontend/templates/code.phtml b/app/code/Magento/GoogleAdwords/view/frontend/templates/code.phtml index 9388a3cb6fcfb..0ae26e92d487e 100644 --- a/app/code/Magento/GoogleAdwords/view/frontend/templates/code.phtml +++ b/app/code/Magento/GoogleAdwords/view/frontend/templates/code.phtml @@ -3,8 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile ?> <?php /** @var $block \Magento\GoogleAdwords\Block\Code */ @@ -12,19 +10,23 @@ <!-- Google Code for Sale Conversion Page --> <script> /* <![CDATA[ */ - var google_conversion_id = <?= /* @escapeNotVerified */ $block->getHelper()->getConversionId() ?>; - var google_conversion_language = "<?= /* @escapeNotVerified */ $block->getHelper()->getConversionLanguage() ?>"; - var google_conversion_format = "<?= /* @escapeNotVerified */ $block->getHelper()->getConversionFormat() ?>"; - var google_conversion_color = "<?= /* @escapeNotVerified */ $block->getHelper()->getConversionColor() ?>"; - var google_conversion_label = "<?= /* @escapeNotVerified */ $block->getHelper()->getConversionLabel() ?>"; - var google_conversion_value = <?= /* @escapeNotVerified */ $block->getHelper()->getConversionValue() ?>; + var google_conversion_id = <?= $block->escapeJs($block->getHelper()->getConversionId()) ?>; + var google_conversion_language = "<?= $block->escapeJs($block->getHelper()->getConversionLanguage()) ?>"; + var google_conversion_format = "<?= $block->escapeJs($block->getHelper()->getConversionFormat()) ?>"; + var google_conversion_color = "<?= $block->escapeJs($block->getHelper()->getConversionColor()) ?>"; + var google_conversion_label = "<?= $block->escapeJs($block->getHelper()->getConversionLabel()) ?>"; + var google_conversion_value = <?= $block->escapeJs($block->getHelper()->getConversionValue()) ?>; + <?php if ($block->getHelper()->hasSendConversionValueCurrency() + && $block->getHelper()->getConversionValueCurrency()) : ?> + var google_conversion_currency = "<?= $block->escapeJs($block->getHelper()->getConversionValueCurrency()) ?>"; + <?php endif; ?> /* ]]> */ </script> -<script src="<?= /* @escapeNotVerified */ $block->getHelper()->getConversionJsSrc() ?>"></script> +<script src="<?= $block->escapeHtmlAttr($block->getHelper()->getConversionJsSrc()) ?>"></script> <noscript> <div style="display:inline;"> <img height="1" width="1" style="border-style:none;" alt="" - src="<?= /* @escapeNotVerified */ $block->getHelper()->getConversionImgSrc() ?>"/> + src="<?= $block->escapeHtmlAttr($block->getHelper()->getConversionImgSrc()) ?>"/> </div> </noscript> <!-- END Google Code for Sale Conversion Page --> diff --git a/app/code/Magento/GoogleAnalytics/view/frontend/templates/ga.phtml b/app/code/Magento/GoogleAnalytics/view/frontend/templates/ga.phtml index ed8c0e3fe3cc8..f1c850087b347 100644 --- a/app/code/Magento/GoogleAnalytics/view/frontend/templates/ga.phtml +++ b/app/code/Magento/GoogleAnalytics/view/frontend/templates/ga.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var $block \Magento\GoogleAnalytics\Block\Ga */ ?> <?php $accountId = $block->getConfig(\Magento\GoogleAnalytics\Helper\Data::XML_PATH_ACCOUNT) ?> @@ -16,9 +13,9 @@ "Magento_GoogleAnalytics/js/google-analytics": { "isCookieRestrictionModeEnabled": <?= (int)$block->isCookieRestrictionModeEnabled() ?>, "currentWebsite": <?= (int)$block->getCurrentWebsiteId() ?>, - "cookieName": "<?= /* @escapeNotVerified */ \Magento\Cookie\Helper\Cookie::IS_USER_ALLOWED_SAVE_COOKIE ?>", - "ordersTrackingData": <?= /* @escapeNotVerified */ json_encode($block->getOrdersTrackingData()) ?>, - "pageTrackingData": <?= /* @escapeNotVerified */ json_encode($block->getPageTrackingData($accountId)) ?> + "cookieName": "<?= /* @noEscape */ \Magento\Cookie\Helper\Cookie::IS_USER_ALLOWED_SAVE_COOKIE ?>", + "ordersTrackingData": <?= /* @noEscape */ json_encode($block->getOrdersTrackingData()) ?>, + "pageTrackingData": <?= /* @noEscape */ json_encode($block->getPageTrackingData($accountId)) ?> } } } From 7e161cc52c9e720505a16ea113a7bf38c67091e1 Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Tue, 11 Jun 2019 08:47:07 -0500 Subject: [PATCH 1923/2092] MC-7710: There is no XSS vulnerability if Create Order with sample email --- .../OpenStorefrontProductPageActionGroup.xml | 17 +++++ ...ValidationMessageOnCheckoutActionGroup.xml | 18 ++++++ ...ValidationMessageOnCheckoutActionGroup.xml | 18 ++++++ ...ontFillEmailFieldOnCheckoutActionGroup.xml | 19 ++++++ ...ntCheckoutCheckoutCustomerLoginSection.xml | 16 +++++ .../Customer/Test/Mftf/Data/CustomerData.xml | 13 ++++ .../Section/AdminOrderFormAccountSection.xml | 1 + ...SSVulnerabilityDuringOrderCreationTest.xml | 62 +++++++++++++++++++ 8 files changed, 164 insertions(+) create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStorefrontProductPageActionGroup.xml create mode 100644 app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertAdminEmailValidationMessageOnCheckoutActionGroup.xml create mode 100644 app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertStorefrontEmailValidationMessageOnCheckoutActionGroup.xml create mode 100644 app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontFillEmailFieldOnCheckoutActionGroup.xml create mode 100644 app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutCheckoutCustomerLoginSection.xml create mode 100644 app/code/Magento/Sales/Test/Mftf/Test/CheckXSSVulnerabilityDuringOrderCreationTest.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStorefrontProductPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStorefrontProductPageActionGroup.xml new file mode 100644 index 0000000000000..7c40fc5796796 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStorefrontProductPageActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="OpenStorefrontProductPageActionGroup"> + <arguments> + <argument name="productUrlKey" type="string"/> + </arguments> + <amOnPage url="{{StorefrontProductPage.url(productUrlKey)}}" stepKey="amOnProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertAdminEmailValidationMessageOnCheckoutActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertAdminEmailValidationMessageOnCheckoutActionGroup.xml new file mode 100644 index 0000000000000..858dbfc5e76f3 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertAdminEmailValidationMessageOnCheckoutActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminEmailValidationMessageOnCheckoutActionGroup"> + <arguments> + <argument name="message" type="string" defaultValue="Please enter a valid email address (Ex: johndoe@domain.com)."/> + </arguments> + <waitForElementVisible selector="{{AdminOrderFormAccountSection.emailErrorMessage}}" stepKey="waitForFormValidation"/> + <see selector="{{AdminOrderFormAccountSection.emailErrorMessage}}" userInput="{{message}}" stepKey="seeTheErrorMessageIsDisplayed"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertStorefrontEmailValidationMessageOnCheckoutActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertStorefrontEmailValidationMessageOnCheckoutActionGroup.xml new file mode 100644 index 0000000000000..0f7e75f062ab4 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/AssertStorefrontEmailValidationMessageOnCheckoutActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertStorefrontEmailValidationMessageOnCheckoutActionGroup"> + <arguments> + <argument name="message" type="string" defaultValue="Please enter a valid email address (Ex: johndoe@domain.com)."/> + </arguments> + <waitForElementVisible selector="{{StorefrontCheckoutCheckoutCustomerLoginSection.emailErrorMessage}}" stepKey="waitForFormValidation"/> + <see selector="{{StorefrontCheckoutCheckoutCustomerLoginSection.emailErrorMessage}}" userInput="{{message}}" stepKey="seeTheErrorMessageIsDisplayed"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontFillEmailFieldOnCheckoutActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontFillEmailFieldOnCheckoutActionGroup.xml new file mode 100644 index 0000000000000..e1f532e7d495a --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/StorefrontFillEmailFieldOnCheckoutActionGroup.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontFillEmailFieldOnCheckoutActionGroup"> + <arguments> + <argument name="email" type="string"/> + </arguments> + <fillField selector="{{StorefrontCheckoutCheckoutCustomerLoginSection.email}}" userInput="{{email}}" stepKey="fillCustomerEmailField"/> + <doubleClick selector="{{StorefrontCheckoutCheckoutCustomerLoginSection.emailTooltipButton}}" stepKey="clickToMoveFocusFromEmailInput"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutCheckoutCustomerLoginSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutCheckoutCustomerLoginSection.xml new file mode 100644 index 0000000000000..afb660ecb057b --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutCheckoutCustomerLoginSection.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="StorefrontCheckoutCheckoutCustomerLoginSection"> + <element name="email" type="input" selector="form[data-role='email-with-possible-login'] input[name='username']"/> + <element name="emailErrorMessage" type="text" selector="#customer-email-error"/> + <element name="emailTooltipButton" type="button" selector="//form[@data-role='email-with-possible-login']//div[input[@name='username']]//*[contains(@class, 'action-help')]"/> + </section> +</sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Data/CustomerData.xml b/app/code/Magento/Customer/Test/Mftf/Data/CustomerData.xml index add5b01787e79..7cd8ca0a3690c 100644 --- a/app/code/Magento/Customer/Test/Mftf/Data/CustomerData.xml +++ b/app/code/Magento/Customer/Test/Mftf/Data/CustomerData.xml @@ -107,4 +107,17 @@ <data key="store_id">0</data> <data key="website_id">0</data> </entity> + <entity name="Simple_US_Customer_Incorrect_Email" type="customer"> + <data key="group_id">1</data> + <data key="default_billing">true</data> + <data key="default_shipping">true</data> + <data key="email">><script>alert(1);</script>@example.com</data> + <data key="firstname">John</data> + <data key="lastname">Doe</data> + <data key="fullname">John Doe</data> + <data key="password">pwdTest123!</data> + <data key="store_id">0</data> + <data key="website_id">0</data> + <requiredEntity type="address">US_Address_CA</requiredEntity> + </entity> </entities> diff --git a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormAccountSection.xml b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormAccountSection.xml index 49c15345b6714..e0830440e6395 100644 --- a/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormAccountSection.xml +++ b/app/code/Magento/Sales/Test/Mftf/Section/AdminOrderFormAccountSection.xml @@ -13,5 +13,6 @@ <element name="email" type="input" selector="#email"/> <element name="requiredGroup" type="text" selector=".admin__field.required[data-ui-id='billing-address-fieldset-element-form-field-group-id']"/> <element name="requiredEmail" type="text" selector=".admin__field.required[data-ui-id='billing-address-fieldset-element-form-field-email']"/> + <element name="emailErrorMessage" type="text" selector="#email-error"/> </section> </sections> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/CheckXSSVulnerabilityDuringOrderCreationTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/CheckXSSVulnerabilityDuringOrderCreationTest.xml new file mode 100644 index 0000000000000..4cf4109993c05 --- /dev/null +++ b/app/code/Magento/Sales/Test/Mftf/Test/CheckXSSVulnerabilityDuringOrderCreationTest.xml @@ -0,0 +1,62 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="CheckXSSVulnerabilityDuringOrderCreationTest"> + <annotations> + <features value="Sales"/> + <stories value="Create order"/> + <title value="Check XSS vulnerability during order creation test"/> + <description value="Order should not be created with XSS vulnerability in email address"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-7710"/> + <group value="sales"/> + </annotations> + <before> + <!-- Create product --> + <createData entity="SimpleProduct3" stepKey="createProduct"/> + </before> + <after> + <!-- Delete product --> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + + <!-- Log out --> + <actionGroup ref="logout" stepKey="adminLogout"/> + </after> + + <!-- Add product to the shopping cart --> + <actionGroup ref="OpenStorefrontProductPageActionGroup" stepKey="openProductPage"> + <argument name="productUrlKey" value="$$createProduct.custom_attributes[url_key]$$"/> + </actionGroup> + <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="addProductToCart"> + <argument name="product" value="$$createProduct$$"/> + <argument name="productCount" value="1"/> + </actionGroup> + + <!-- Try to create order on Storefront with provided email --> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> + <actionGroup ref="StorefrontFillEmailFieldOnCheckoutActionGroup" stepKey="fillIncorrectEmailStorefront"> + <argument name="email" value="{{Simple_US_Customer_Incorrect_Email.email}}"/> + </actionGroup> + + <!-- Order can not be created --> + <actionGroup ref="AssertStorefrontEmailValidationMessageOnCheckoutActionGroup" stepKey="assertErrorMessageStorefront"/> + + <!-- Login as admin --> + <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + + <!-- Try to create order in admin with provided email --> + <actionGroup ref="navigateToNewOrderPageNewCustomerSingleStore" stepKey="navigateToNewOrderPage"/> + <fillField selector="{{AdminOrderFormAccountSection.email}}" userInput="{{Simple_US_Customer_Incorrect_Email.email}}" stepKey="fillEmailAddressAdminPanel"/> + <click selector="{{AdminOrderFormActionSection.submitOrder}}" stepKey="clickSubmitOrder"/> + + <!-- Order can not be created --> + <actionGroup ref="AssertAdminEmailValidationMessageOnCheckoutActionGroup" stepKey="assertErrorMessageAdminPanel"/> + </test> +</tests> From 5e1354ace8327678b3c557f78de1850963d3106c Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Tue, 11 Jun 2019 09:10:05 -0500 Subject: [PATCH 1924/2092] MC-10141: Move Product between Categories (Cron is ON, Update by Schedule Mode) --- .../AdminAnchorCategoryActionGroup.xml | 29 +++ .../AdminProductGridActionGroup.xml | 17 ++ .../Catalog/Test/Mftf/Data/ProductData.xml | 13 + .../Section/AdminCategoryProductsSection.xml | 1 + .../Mftf/Section/AdminProductFormSection.xml | 6 + .../CategoryDisplaySettingsSection.xml | 15 ++ .../Section/StorefrontCategoryMainSection.xml | 2 + .../Section/StorefrontNavigationSection.xml | 1 + .../AdminMoveProductBetweenCategoriesTest.xml | 227 ++++++++++++++++++ .../AdminCatalogSearchConfigurationPage.xml | 12 + ...atalogSearchEngineConfigurationSection.xml | 15 ++ ...inSwitchIndexerToActionModeActionGroup.xml | 22 ++ .../Section/AdminIndexManagementSection.xml | 1 + .../Mftf/Page/AdminCacheManagementPage.xml | 14 ++ .../Section/AdminCacheManagementSection.xml | 4 + 15 files changed, 379 insertions(+) create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAnchorCategoryActionGroup.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/Section/CategoryDisplaySettingsSection.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml create mode 100644 app/code/Magento/Config/Test/Mftf/Page/AdminCatalogSearchConfigurationPage.xml create mode 100644 app/code/Magento/Config/Test/Mftf/Section/AdminCatalogSearchEngineConfigurationSection.xml create mode 100644 app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml create mode 100644 app/code/Magento/PageCache/Test/Mftf/Page/AdminCacheManagementPage.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAnchorCategoryActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAnchorCategoryActionGroup.xml new file mode 100644 index 0000000000000..45fe419ad14fe --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAnchorCategoryActionGroup.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminAnchorCategoryActionGroup"> + <arguments> + <argument name="categoryName" type="string"/> + </arguments> + <!--Open Category page--> + <amOnPage url="{{AdminCategoryPage.url}}" stepKey="openAdminCategoryIndexPage"/> + <waitForPageLoad stepKey="waitForPageToLoaded"/> + <click selector="{{AdminCategorySidebarTreeSection.expandAll}}" stepKey="clickOnExpandTree"/> + <waitForPageLoad stepKey="waitForCategoryToLoad"/> + <click selector="{{AdminCategorySidebarTreeSection.categoryInTree(categoryName)}}" stepKey="selectCategory"/> + <waitForPageLoad stepKey="waitForPageToLoad"/> + + <!--Enable Anchor for category --> + <scrollTo selector="{{CategoryDisplaySettingsSection.DisplaySettingTab}}" x="0" y="-80" stepKey="scrollToDisplaySetting"/> + <click selector="{{CategoryDisplaySettingsSection.DisplaySettingTab}}" stepKey="selectDisplaySetting"/> + <checkOption selector="{{CategoryDisplaySettingsSection.anchor}}" stepKey="enableAnchor"/> + <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveSubCategory"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductGridActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductGridActionGroup.xml index 45bf38a0c707e..c32ae3a2b4b08 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductGridActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductGridActionGroup.xml @@ -103,4 +103,21 @@ <conditionalClick selector="{{AdminProductGridTableHeaderSection.id('ascend')}}" dependentSelector="{{AdminProductGridTableHeaderSection.id('descend')}}" visible="false" stepKey="sortById"/> <waitForPageLoad stepKey="waitForPageLoad"/> </actionGroup> + + <!--Filter and select the the product --> + <actionGroup name="filterAndSelectProduct"> + <arguments> + <argument name="productSku" type="string"/> + </arguments> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> + <waitForPageLoad stepKey="waitForProductIndexPageToLoad"/> + <conditionalClick selector="{{AdminProductGridFilterSection.clearFilters}}" dependentSelector="{{AdminProductGridFilterSection.clearFilters}}" visible="true" stepKey="clickClearFilters"/> + <click selector="{{AdminProductGridFilterSection.filters}}" stepKey="openProductFilters"/> + <fillField selector="{{AdminProductGridFilterSection.skuFilter}}" userInput="{{productSku}}" stepKey="fillProductSkuFilter"/> + <click selector="{{AdminProductGridFilterSection.applyFilters}}" stepKey="clickApplyFilters"/> + <waitForElementNotVisible selector="{{AdminProductGridSection.loadingMask}}" stepKey="waitForFilteredGridLoad" time="30"/> + <click stepKey="openSelectedProduct" selector="{{AdminProductGridSection.productRowBySku(productSku)}}"/> + <waitForPageLoad stepKey="waitForProductToLoad"/> + <waitForElementVisible selector="{{AdminHeaderSection.pageTitle}}" stepKey="waitForProductTitle"/> + </actionGroup> </actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/ProductData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/ProductData.xml index f6fb47c731790..9d02fbd848345 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/ProductData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/ProductData.xml @@ -311,4 +311,17 @@ <requiredEntity type="product_option">ProductOptionField</requiredEntity> <requiredEntity type="product_option">ProductOptionField2</requiredEntity> </entity> + <entity name="defaultSimpleProduct" type="product"> + <data key="name" unique="suffix">Testp</data> + <data key="sku" unique="suffix">testsku</data> + <data key="type_id">simple</data> + <data key="attribute_set_id">4</data> + <data key="visibility">4</data> + <data key="price">560.00</data> + <data key="urlKey" unique="suffix">testurl-</data> + <data key="status">1</data> + <data key="quantity">25</data> + <data key="weight">1</data> + <requiredEntity type="product_extension_attribute">EavStock100</requiredEntity> + </entity> </entities> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryProductsSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryProductsSection.xml index bf6f3c692b6c3..ef339668b2c98 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryProductsSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminCategoryProductsSection.xml @@ -11,5 +11,6 @@ <section name="AdminCategoryProductsSection"> <element name="sectionHeader" type="button" selector="div[data-index='assign_products']" timeout="30"/> <element name="tabProductClosed" type="block" selector="div[data-index='assign_products'] [data-state-collapsible='closed']"/> + <element name="addProducts" type="button" selector="#catalog_category_add_product_tabs" timeout="30"/> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml index 4b754f97f8b89..ee9f39125b037 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml @@ -43,6 +43,12 @@ <element name="customAttributeDropdownField" type="select" selector="select[name='product[{{attributeCode}}]']" parameterized="true"/> <element name="customAttributeInputField" type="select" selector="input[name='product[{{attributeCode}}]']" parameterized="true"/> <element name="customAttributeSelectOptions" type="select" selector="select[name='product[{{attributeCode}}]'] option" parameterized="true"/> + <element name="currentCategory" type="text" selector=".admin__action-multiselect-crumb > span"/> + <element name="searchCategory" type="input" selector="//*[@data-index='category_ids']//input[contains(@class, 'multiselect-search')]"/> + <element name="selectCategory" type="input" selector="//*[@data-index='category_ids']//label[contains(., '{{categoryName}}')]" parameterized="true"/> + <element name="done" type="button" selector="//*[@data-index='category_ids']//button[@data-action='close-advanced-select']" timeout="30"/> + <element name="save" type="button" selector="#save-button"/> + <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button[@data-action='remove-selected-item']" parameterized="true" timeout="30"/> </section> <section name="ProductInWebsitesSection"> <element name="sectionHeader" type="button" selector="div[data-index='websites']" timeout="30"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/CategoryDisplaySettingsSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/CategoryDisplaySettingsSection.xml new file mode 100644 index 0000000000000..ea47c41816239 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Section/CategoryDisplaySettingsSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="CategoryDisplaySettingsSection"> + <element name="DisplaySettingTab" type="button" selector="//strong[@class='admin__collapsible-title']//span[text()='Display Settings']"/> + <element name="anchor" type="checkbox" selector="input[name='is_anchor']"/> + </section> +</sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryMainSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryMainSection.xml index 3c769f9dbc0ce..42b03cd14701b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryMainSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontCategoryMainSection.xml @@ -23,5 +23,7 @@ <element name="categoryPageProductImage" type="text" selector=".products-grid img[src*='/{{var1}}']" parameterized="true"/> <element name="categoryPageProductName" type="text" selector=".products.list.items.product-items li:nth-of-type({{line}}) .product-item-link" timeout="30" parameterized="true"/> <element name="categoryEmptyMessage" type="text" selector=".column.main .message.info.empty"/> + <element name="productName" type="text" selector=".product-item-name"/> + <element name="productLinkByHref" type="text" selector="a.product-item-link[href$='{{var1}}.html']" parameterized="true"/> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontNavigationSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontNavigationSection.xml index bf411a9cc48b2..7a8fa7bfc3c6a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontNavigationSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/StorefrontNavigationSection.xml @@ -12,5 +12,6 @@ <element name="topCategory" type="button" selector="//a[contains(@class,'level-top')]/span[contains(text(),'{{var1}}')]" parameterized="true"/> <element name="subCategory" type="button" selector="//ul[contains(@class,'submenu')]//span[contains(text(),'{{var1}}')]" parameterized="true"/> <element name="breadcrumbs" type="textarea" selector=".items"/> + <element name="categoryBreadcrumbs" type="textarea" selector=".breadcrumbs li"/> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml new file mode 100644 index 0000000000000..01d658ed5880f --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml @@ -0,0 +1,227 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminMoveProductBetweenCategoriesTest"> + <annotations> + <stories value="Move Product"/> + <title value="Move Product between Categories (Cron is ON, 'Update by Schedule' Mode)"/> + <description value="Verifies correctness of showing data (products, categories) on Storefront after moving an anchored category in terms of products/categories association"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-10141"/> + <group value="catalog"/> + </annotations> + + <before> + <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + <createData entity="defaultSimpleProduct" stepKey="simpleProduct"/> + <createData entity="_defaultCategory" stepKey="createAnchoredCategory1"/> + <createData entity="_defaultCategory" stepKey="createSecondCategory"/> + + <!-- Switch "Category Product" and "Product Category" indexers to "Update by Schedule" mode --> + <amOnPage url="{{AdminIndexManagementPage.url}}" stepKey="onIndexManagement"/> + <waitForPageLoad stepKey="waitForManagementPage"/> + + <actionGroup ref="AdminSwitchIndexerToActionModeActionGroup" stepKey="switchCategoryProduct"> + <argument name="indexerValue" value="catalog_category_product"/> + </actionGroup> + <actionGroup ref="AdminSwitchIndexerToActionModeActionGroup" stepKey="switchProductCategory"> + <argument name="indexerValue" value="catalog_product_category"/> + </actionGroup> + </before> + + <after> + <!-- Switch "Category Product" and "Product Category" indexers to "Update by Save" mode --> + <amOnPage url="{{AdminIndexManagementPage.url}}" stepKey="onIndexManagement"/> + <waitForPageLoad stepKey="waitForManagementPage"/> + + <actionGroup ref="AdminSwitchIndexerToActionModeActionGroup" stepKey="switchCategoryProduct"> + <argument name="indexerValue" value="catalog_category_product"/> + <argument name="action" value="Update on Save"/> + </actionGroup> + <actionGroup ref="AdminSwitchIndexerToActionModeActionGroup" stepKey="switchProductCategory"> + <argument name="indexerValue" value="catalog_product_category"/> + <argument name="action" value="Update on Save"/> + </actionGroup> + + <deleteData createDataKey="simpleProduct" stepKey="deleteProduct"/> + <deleteData createDataKey="createSecondCategory" stepKey="deleteSecondCategory"/> + <deleteData createDataKey="createAnchoredCategory1" stepKey="deleteAnchoredCategory1"/> + <actionGroup ref="logout" stepKey="logout"/> + </after> + <!-- Create the anchored category <Cat1_anchored> --> + <actionGroup ref="AdminAnchorCategoryActionGroup" stepKey="anchorCategory"> + <argument name="categoryName" value="$$createAnchoredCategory1.name$$"/> + </actionGroup> + + <!-- Create subcategory <Sub1> of the anchored category --> + <click selector="{{AdminCategorySidebarActionSection.AddSubcategoryButton}}" stepKey="clickOnAddSubCategoryButton"/> + <fillField selector="{{AdminCategoryBasicFieldSection.CategoryNameInput}}" userInput="{{SimpleSubCategory.name}}" stepKey="addSubCategoryName"/> + <click selector="{{AdminCategoryMainActionsSection.SaveButton}}" stepKey="saveSubCategory1"/> + <waitForPageLoad stepKey="waitForSecondCategoryToSave"/> + <seeElement selector="{{AdminCategoryMessagesSection.SuccessMessage}}" stepKey="seeSaveSuccessMessage"/> + + <!-- Assign <product1> to the <Sub1> --> + <amOnPage url="{{AdminProductEditPage.url($$simpleProduct.id$$)}}" stepKey="goToProduct"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + <click selector="{{AdminProductFormSection.categoriesDropdown}}" stepKey="activateDropDownCategory"/> + <fillField userInput="{{SimpleSubCategory.name}}" selector="{{AdminProductFormSection.searchCategory}}" stepKey="fillSearch"/> + <waitForPageLoad stepKey="waitForSubCategory"/> + <click selector="{{AdminProductFormSection.selectCategory(SimpleSubCategory.name)}}" stepKey="selectSub1Category"/> + <click selector="{{AdminProductFormSection.done}}" stepKey="clickDone"/> + <waitForPageLoad stepKey="waitForApplyCategory"/> + <click selector="{{AdminProductFormSection.save}}" stepKey="clickSave"/> + <waitForPageLoad stepKey="waitForSavingChanges"/> + + <!-- Enable `Use Categories Path for Product URLs` on Stores -> Configuration -> Catalog -> Catalog -> Search Engine Optimization --> + <amOnPage url="{{AdminCatalogSearchConfigurationPage.url}}" stepKey="onConfigPage"/> + <waitForPageLoad stepKey="waitForLoading"/> + <conditionalClick selector="{{AdminCatalogSearchEngineConfigurationSection.searchEngineOptimization}}" dependentSelector="{{AdminCatalogSearchEngineConfigurationSection.openedEngineOptimization}}" visible="false" stepKey="clickEngineOptimization"/> + <uncheckOption selector="{{AdminCatalogSearchEngineConfigurationSection.systemValueUseCategoriesPath}}" stepKey="uncheckDefault"/> + <selectOption userInput="Yes" selector="{{AdminCatalogSearchEngineConfigurationSection.selectUseCategoriesPatForProductUrls}}" stepKey="selectYes"/> + <click selector="{{AdminConfigSection.saveButton}}" stepKey="saveConfig"/> + <waitForPageLoad stepKey="waitForSaving"/> + <see selector="{{AdminIndexManagementSection.successMessage}}" userInput="You saved the configuration." stepKey="seeMessage"/> + + <!-- Navigate to the Catalog > Products --> + <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="onCatalogProductPage"/> + <waitForPageLoad stepKey="waitForProductPage"/> + + <!-- Click on <product1>: Product page opens--> + <actionGroup ref="filterProductGridByName" stepKey="filterProduct"> + <argument name="product" value="$$simpleProduct$$"/> + </actionGroup> + <click selector="{{AdminProductGridSection.productGridNameProduct($$simpleProduct.name$$)}}" stepKey="clickProduct1"/> + <waitForPageLoad stepKey="waitForProductLoad"/> + + <!-- Clear "Categories" field and assign the product to <Cat2> and save the product --> + <grabTextFrom selector="{{AdminProductFormSection.currentCategory}}" stepKey="grabNameSubCategory"/> + <click selector="{{AdminProductFormSection.unselectCategories(SimpleSubCategory.name)}}" stepKey="removeCategory"/> + <click selector="{{AdminProductFormSection.categoriesDropdown}}" stepKey="openDropDown"/> + <checkOption selector="{{AdminProductFormSection.selectCategory($$createSecondCategory.name$$)}}" stepKey="selectCategory"/> + <click selector="{{AdminProductFormSection.done}}" stepKey="pressButtonDone"/> + <waitForPageLoad stepKey="waitForApplyCategory2"/> + <click selector="{{AdminProductFormSection.save}}" stepKey="pushButtonSave"/> + <waitForPageLoad stepKey="waitForSavingProduct"/> + + <!--Product is saved --> + <see userInput="You saved the product." selector="{{AdminIndexManagementSection.successMessage}}" stepKey="seeSuccessMessage"/> + + <!-- Run cron --> + <magentoCLI command="cron:run" stepKey="runCron"/> + + <!-- Clear invalidated cache on System>Tools>Cache Management page --> + <amOnPage url="{{AdminCacheManagementPage.url}}" stepKey="onCachePage"/> + <waitForPageLoad stepKey="waitForCacheManagementPage"/> + + <checkOption selector="{{AdminCacheManagementSection.configurationCheckbox}}" stepKey="checkConfigCache"/> + <checkOption selector="{{AdminCacheManagementSection.pageCacheCheckbox}}" stepKey="checkPageCache"/> + + <selectOption userInput="Refresh" selector="{{AdminCacheManagementSection.massActionSelect}}" stepKey="selectRefresh"/> + <waitForElementVisible selector="{{AdminCacheManagementSection.massActionSubmit}}" stepKey="waitSubmitButton"/> + <click selector="{{AdminCacheManagementSection.massActionSubmit}}" stepKey="clickSubmit"/> + <waitForPageLoad stepKey="waitForRefresh"/> + + <see userInput="2 cache type(s) refreshed." stepKey="seeCacheRefreshedMessage"/> + <actionGroup ref="logout" stepKey="logout"/> + + <!-- Open frontend --> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="onFrontend"/> + <waitForPageLoad stepKey="waitForStorefrontPageLoad"/> + + <!-- Open <Cat2> from navigation menu --> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createSecondCategory.name$$)}}" stepKey="openCat2"/> + <waitForPageLoad stepKey="waitForCategory2Page"/> + + <!-- # <Cat 2> should open # <product1> should be present on the page --> + <see userInput="$$createSecondCategory.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeCategoryName"/> + <see userInput="$$simpleProduct.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProduct"/> + + <!-- Open <product1> --> + <click selector="{{StorefrontCategoryMainSection.productLinkByHref($$simpleProduct.urlKey$$)}}" stepKey="openProduct"/> + <waitForPageLoad stepKey="waitForProductPageLoading"/> + + <!-- # Product page should open successfully # Breadcrumb for product should be like <Cat 2> --> + <see selector="{{StorefrontProductInfoMainSection.productName}}" userInput="$$simpleProduct.name$$" stepKey="seeProductName"/> + <see userInput="$$createSecondCategory.name$$" selector="{{StorefrontNavigationSection.categoryBreadcrumbs}}" stepKey="seeCategoryInBreadcrumbs"/> + + <!-- Open <Cat1_anchored> category --> + <click selector="{{StorefrontNavigationSection.topCategory($$createAnchoredCategory1.name$$)}}" stepKey="clickCat1"/> + <waitForPageLoad stepKey="waitForCategory1PageLoad"/> + + <!-- # Category should open successfully # <product1> should be absent on the page --> + <see userInput="$$createAnchoredCategory1.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeCategory1Name"/> + <see userInput="We can't find products matching the selection." stepKey="seeEmptyNotice"/> + <dontSee userInput="$$simpleProduct.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontseeProduct"/> + + <!-- Log in to the backend: Admin user is logged in--> + <actionGroup ref="LoginAsAdmin" stepKey="LoginAdmin"/> + + <!-- Navigate to the Catalog > Products: Navigate to the Catalog>Products --> + <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="amOnProductPage"/> + <waitForPageLoad stepKey="waitForProductsPage"/> + + <!-- Click on <product1> --> + <actionGroup ref="filterAndSelectProduct" stepKey="openSimpleProduct"> + <argument name="productSku" value="$$simpleProduct.sku$$"/> + </actionGroup> + + <!-- Clear "Categories" field and assign the product to <Sub1> and save the product --> + <click selector="{{AdminProductFormSection.unselectCategories($$createSecondCategory.name$$)}}" stepKey="clearCategory"/> + <click selector="{{AdminProductFormSection.categoriesDropdown}}" stepKey="activateDropDown"/> + <fillField userInput="{$grabNameSubCategory}" selector="{{AdminProductFormSection.searchCategory}}" stepKey="fillSearchField"/> + <waitForPageLoad stepKey="waitForSearchSubCategory"/> + <click selector="{{AdminProductFormSection.selectCategory({$grabNameSubCategory})}}" stepKey="selectSubCategory"/> + <click selector="{{AdminProductFormSection.done}}" stepKey="clickButtonDone"/> + <waitForPageLoad stepKey="waitForCategoryApply"/> + <click selector="{{AdminProductFormSection.save}}" stepKey="clickButtonSave"/> + <waitForPageLoad stepKey="waitForSaveChanges"/> + + <!-- Product is saved successfully --> + <see userInput="You saved the product." selector="{{AdminIndexManagementSection.successMessage}}" stepKey="seeSaveMessage"/> + + <!-- Run cron --> + <magentoCLI command="cron:run" stepKey="runCron2"/> + + <!-- Open frontend --> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="onFrontendPage"/> + <waitForPageLoad stepKey="waitForFrontPageLoad"/> + + <!-- Open <Cat2> from navigation menu --> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createSecondCategory.name$$)}}" stepKey="openSecondCategory"/> + <waitForPageLoad stepKey="waitForSecondCategoryPage"/> + + <!-- # <Cat 2> should open # <product1> should be absent on the page --> + <see userInput="$$createSecondCategory.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeSecondCategory1Name"/> + <dontSee userInput="$$simpleProduct.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontseeSimpleProduct"/> + + <!-- Click on <Cat1_anchored> category --> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createAnchoredCategory1.name$$)}}" stepKey="clickAnchoredCategory"/> + <waitForPageLoad stepKey="waitForAnchoredCategoryPage"/> + + <!-- # Category should open successfully # <product1> should be present on the page --> + <see userInput="$$createAnchoredCategory1.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="see1CategoryName"/> + <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="$$simpleProduct.name$$" stepKey="seeProductNameOnCategory1Page"/> + + <!-- Breadcrumb for product should be like <Cat1_anchored>/<product> (if you clicks from anchor category) --> + <see userInput="$$createAnchoredCategory1.name$$" selector="{{StorefrontNavigationSection.categoryBreadcrumbs}}" stepKey="seeCat1inBreadcrumbs"/> + <dontSee userInput="{$grabNameSubCategory}" selector="{{StorefrontNavigationSection.categoryBreadcrumbs}}" stepKey="dontSeeSubCategoryInBreadCrumbs"/> + + <!-- <Cat1_anchored>/<Sub1>/<product> (if you clicks from Sub1 category) --> + <moveMouseOver selector="{{StorefrontHeaderSection.NavigationCategoryByName($$createAnchoredCategory1.name$$)}}" stepKey="hoverCategory1"/> + <click selector="{{StorefrontHeaderSection.NavigationCategoryByName({$grabNameSubCategory})}}" stepKey="clickSubCat"/> + <waitForPageLoad stepKey="waitForSubCategoryPageLoad"/> + + <see userInput="{$grabNameSubCategory}" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeSubCategoryName"/> + <see selector="{{StorefrontCategoryMainSection.productName}}" userInput="$$simpleProduct.name$$" stepKey="seeProductNameOnSubCategoryPage"/> + + <see userInput="{$grabNameSubCategory}" selector="{{StorefrontNavigationSection.categoryBreadcrumbs}}" stepKey="seeSubCategoryInBreadcrumbs"/> + <see userInput="$$createAnchoredCategory1.name$$" selector="{{StorefrontNavigationSection.categoryBreadcrumbs}}" stepKey="seeCat1InBreadcrumbs"/> + </test> +</tests> diff --git a/app/code/Magento/Config/Test/Mftf/Page/AdminCatalogSearchConfigurationPage.xml b/app/code/Magento/Config/Test/Mftf/Page/AdminCatalogSearchConfigurationPage.xml new file mode 100644 index 0000000000000..6b3c6e1a40871 --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Page/AdminCatalogSearchConfigurationPage.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminCatalogSearchConfigurationPage" url="admin/system_config/edit/section/catalog/" area="admin" module="Magento_Config"> + <section name="AdminCatalogSearchEngineConfigurationSection"/> + </page> +</pages> diff --git a/app/code/Magento/Config/Test/Mftf/Section/AdminCatalogSearchEngineConfigurationSection.xml b/app/code/Magento/Config/Test/Mftf/Section/AdminCatalogSearchEngineConfigurationSection.xml new file mode 100644 index 0000000000000..2cde11434b26d --- /dev/null +++ b/app/code/Magento/Config/Test/Mftf/Section/AdminCatalogSearchEngineConfigurationSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminCatalogSearchEngineConfigurationSection"> + <element name="searchEngineOptimization" type="button" selector="#catalog_seo-head"/> + <element name="openedEngineOptimization" type="button" selector="#catalog_seo-head.open"/> + <element name="systemValueUseCategoriesPath" type="checkbox" selector="#catalog_seo_product_use_categories_inherit"/> + <element name="selectUseCategoriesPatForProductUrls" type="select" selector="#catalog_seo_product_use_categories"/> + </section> +</sections> diff --git a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml new file mode 100644 index 0000000000000..8137b292e7d71 --- /dev/null +++ b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminSwitchIndexerToActionModeActionGroup"> + <arguments> + <argument name="indexerValue" type="string"/> + <argument name="action" type="string" defaultValue="Update by Schedule"/> + </arguments> + <checkOption selector="{{AdminIndexManagementSection.indexerCheckbox(indexerValue)}}" stepKey="checkIndexer"/> + <selectOption userInput="{{action}}" selector="{{AdminIndexManagementSection.massActionSelect}}" stepKey="selectAction"/> + <click selector="{{AdminIndexManagementSection.massActionSubmit}}" stepKey="clickSubmit"/> + <waitForPageLoad stepKey="waitForSubmit"/> + <see selector="{{AdminIndexManagementSection.successMessage}}" userInput="1 indexer(s) are in "{{action}}" mode." stepKey="seeMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml b/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml index 07d93ff850221..ff7ea677fbdc6 100644 --- a/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml +++ b/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml @@ -12,5 +12,6 @@ <element name="indexerCheckbox" type="checkbox" selector="#gridIndexer_table input[value='{{indexerId}}']" parameterized="true"/> <element name="massActionSelect" type="select" selector="#gridIndexer_massaction-select"/> <element name="massActionSubmit" type="button" selector="#gridIndexer_massaction-form button" timeout="30"/> + <element name="successMessage" type="text" selector="//*[@data-ui-id='messages-message-success']"/> </section> </sections> diff --git a/app/code/Magento/PageCache/Test/Mftf/Page/AdminCacheManagementPage.xml b/app/code/Magento/PageCache/Test/Mftf/Page/AdminCacheManagementPage.xml new file mode 100644 index 0000000000000..24fc5ffb04cb7 --- /dev/null +++ b/app/code/Magento/PageCache/Test/Mftf/Page/AdminCacheManagementPage.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminCacheManagementPage" url="/admin/cache" area="admin" module="PageCache"> + <section name="AdminCacheManagementSection"/> + </page> +</pages> diff --git a/app/code/Magento/PageCache/Test/Mftf/Section/AdminCacheManagementSection.xml b/app/code/Magento/PageCache/Test/Mftf/Section/AdminCacheManagementSection.xml index a553c2e20369a..bf0326f68bc97 100644 --- a/app/code/Magento/PageCache/Test/Mftf/Section/AdminCacheManagementSection.xml +++ b/app/code/Magento/PageCache/Test/Mftf/Section/AdminCacheManagementSection.xml @@ -9,5 +9,9 @@ <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../dev/tests/acceptance/vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Page/etc/SectionObject.xsd"> <section name="AdminCacheManagementSection"> <element name="FlushMagentoCache" type="button" selector="#flush_magento"/> + <element name="configurationCheckbox" type="checkbox" selector="input[value='config']"/> + <element name="pageCacheCheckbox" type="checkbox" selector="input[value='full_page']"/> + <element name="massActionSelect" type="select" selector="#cache_grid_massaction-form #cache_grid_massaction-select"/> + <element name="massActionSubmit" type="button" selector="#cache_grid_massaction-form button"/> </section> </sections> From e59255bb9e2bbc6182fab95e4ef1199444b306b2 Mon Sep 17 00:00:00 2001 From: Viktor Petryk <victor.petryk@transoftgroup.com> Date: Tue, 11 Jun 2019 17:11:28 +0300 Subject: [PATCH 1925/2092] MC-17385: Eliminate @escapeNotVerified in Product and Catalog Rules Modules --- .../adminhtml/templates/promo/fieldset.phtml | 18 +++---- .../view/adminhtml/templates/promo/form.phtml | 5 +- .../base/templates/product/price/msrp.phtml | 48 ++++++++++--------- .../frontend/templates/cart/subtotal.phtml | 2 +- .../view/frontend/templates/cart/totals.phtml | 6 +-- .../Msrp/view/frontend/templates/popup.phtml | 15 +++--- .../render/item/price_msrp_item.phtml | 45 +++++++++-------- .../render/item/price_msrp_rss.phtml | 9 ++-- 8 files changed, 75 insertions(+), 73 deletions(-) diff --git a/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/fieldset.phtml b/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/fieldset.phtml index 1798b1112426c..69199af271477 100644 --- a/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/fieldset.phtml +++ b/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/fieldset.phtml @@ -4,17 +4,16 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - -/**@var \Magento\Backend\Block\Widget\Form\Renderer\Fieldset $block */ +/** @var \Magento\Backend\Block\Widget\Form\Renderer\Fieldset $block */ ?> <?php $_element = $block->getElement() ?> <?php $_jsObjectName = $block->getFieldSetId() != null ? $block->getFieldSetId() : $_element->getHtmlId() ?> <div class="rule-tree"> - <fieldset id="<?= /* @escapeNotVerified */ $_jsObjectName ?>" <?= /* @escapeNotVerified */ $_element->serialize(['class']) ?> class="fieldset"> - <legend class="legend"><span><?= /* @escapeNotVerified */ $_element->getLegend() ?></span></legend> + <fieldset id="<?= $block->escapeHtmlAttr($_jsObjectName) ?>" + <?= /* @noEscape */ $_element->serialize(['class']) ?> class="fieldset"> + <legend class="legend"><span><?= $block->escapeHtmlAttr($_element->getLegend()) ?></span></legend> <br> - <?php if ($_element->getComment()): ?> + <?php if ($_element->getComment()) : ?> <div class="messages"> <div class="message message-notice"><?= $block->escapeHtml($_element->getComment()) ?></div> </div> @@ -30,9 +29,10 @@ require([ "prototype" ], function(VarienRulesForm){ -window.<?= /* @escapeNotVerified */ $_jsObjectName ?> = new VarienRulesForm('<?= /* @escapeNotVerified */ $_jsObjectName ?>', '<?= /* @escapeNotVerified */ $block->getNewChildUrl() ?>'); -<?php if ($_element->getReadonly()): ?> - <?= $_element->getHtmlId() ?>.setReadonly(true); +window.<?= /* @noEscape */ $_jsObjectName ?> = new VarienRulesForm('<?= /* @noEscape */ $_jsObjectName ?>', + '<?= /* @noEscape */ $block->getNewChildUrl() ?>'); +<?php if ($_element->getReadonly()) : ?> + <?= /* @noEscape */ $_element->getHtmlId() ?>.setReadonly(true); <?php endif; ?> }); diff --git a/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/form.phtml b/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/form.phtml index 1572c8f0d4e48..562e27c61b4c0 100644 --- a/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/form.phtml +++ b/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/form.phtml @@ -3,11 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <div class="entry-edit rule-tree"> -<?= $block->getFormHtml() ?> + <?= $block->getFormHtml() ?> </div> diff --git a/app/code/Magento/Msrp/view/base/templates/product/price/msrp.phtml b/app/code/Magento/Msrp/view/base/templates/product/price/msrp.phtml index ee282ebb82eb9..62e79be353230 100644 --- a/app/code/Magento/Msrp/view/base/templates/product/price/msrp.phtml +++ b/app/code/Magento/Msrp/view/base/templates/product/price/msrp.phtml @@ -4,20 +4,18 @@ * See COPYING.txt for license details. */ -// @codingStandardsIgnoreFile - /** - * Template for displaying product price at product view page, gift registry and wish-list + * Template for displaying product price at product view page, gift registry and wish-list. * - * @var $block \Magento\Catalog\Pricing\Render\PriceBox + * @var \Magento\Catalog\Pricing\Render\PriceBox $block */ ?> <?php -/** @var Magento\Msrp\Pricing\Price\MsrpPriceInterface $priceType */ +/** @var \Magento\Msrp\Pricing\Price\MsrpPriceInterface $priceType */ $priceType = $block->getPrice(); -/** @var $product \Magento\Catalog\Model\Product */ +/** @var \Magento\Catalog\Model\Product $product */ $product = $block->getSaleableItem(); $productId = $product->getId(); $amount = 0; @@ -46,23 +44,24 @@ $msrpPrice = $block->renderAmount( $priceElementIdPrefix = $block->getPriceElementIdPrefix() ? $block->getPriceElementIdPrefix() : 'product-price-'; ?> -<?php if ($amount): ?> - <span class="old-price map-old-price"><?= /* @escapeNotVerified */ $msrpPrice ?></span> - <span class="map-fallback-price normal-price"><?= /* @escapeNotVerified */ $msrpPrice ?></span> +<?php if ($amount) : ?> + <span class="old-price map-old-price"><?= /* @noEscape */ $msrpPrice ?></span> + <span class="map-fallback-price normal-price"><?= /* @noEscape */ $msrpPrice ?></span> <?php endif; ?> -<?php if ($priceType->isShowPriceOnGesture()): ?> +<?php if ($priceType->isShowPriceOnGesture()) : ?> <?php $addToCartUrl = ''; if ($product->isSaleable()) { /** @var Magento\Catalog\Block\Product\AbstractProduct $addToCartUrlGenerator */ - $addToCartUrlGenerator = $block->getLayout()->getBlockSingleton('Magento\Catalog\Block\Product\AbstractProduct'); + $addToCartUrlGenerator = $block->getLayout() + ->getBlockSingleton(\Magento\Catalog\Block\Product\AbstractProduct::class); $addToCartUrl = $addToCartUrlGenerator->getAddToCartUrl( $product, ['_query' => [ \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED => - $this->helper('Magento\Framework\Url\Helper\Data')->getEncodedUrl( + $this->helper(\Magento\Framework\Url\Helper\Data::class)->getEncodedUrl( $addToCartUrlGenerator->getAddToCartUrl($product) ), ]] @@ -90,30 +89,35 @@ $priceElementIdPrefix = $block->getPriceElementIdPrefix() ? $block->getPriceElem } else { $data['addToCart']['addToCartButton'] = sprintf( 'form:has(input[type="hidden"][name="product"][value="%s"]) button[type="submit"]', - (int) $productId + (int)$productId ); } ?> - <span id="<?= /* @escapeNotVerified */ $block->getPriceId() ? $block->getPriceId() : $priceElementId ?>" style="display:none"></span> + <span id="<?= $block->escapeHtmlAttr($block->getPriceId() ? $block->getPriceId() : $priceElementId) ?>" + style="display:none"></span> <a href="javascript:void(0);" - id="<?= /* @escapeNotVerified */ ($popupId) ?>" + id="<?= /* @noEscape */ ($popupId) ?>" class="action map-show-info" - data-mage-init='<?= /* @noEscape */ $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($data) ?>'><?= /* @escapeNotVerified */ __('Click for price') ?> + <?php // phpcs:disable ?> + data-mage-init='<?= /* @noEscape */ $this->helper(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($data) ?>'> + <?php //phpcs:enable ?> + <?= $block->escapeHtml(__('Click for price')) ?> </a> -<?php else: ?> +<?php else : ?> <span class="msrp-message"> - <?= /* @escapeNotVerified */ $priceType->getMsrpPriceMessage() ?> + <?= $block->escapeHtml($priceType->getMsrpPriceMessage()) ?> </span> <?php endif; ?> -<?php if ($block->getZone() == \Magento\Framework\Pricing\Render::ZONE_ITEM_VIEW): ?> +<?php if ($block->getZone() == \Magento\Framework\Pricing\Render::ZONE_ITEM_VIEW) : ?> <?php $helpLinkId = 'msrp-help-' . $productId . $block->getRandomString(20); ?> <a href="javascript:void(0);" - id="<?= /* @escapeNotVerified */ $helpLinkId ?>" + id="<?= /* @noEscape */ $helpLinkId ?>" class="action map-show-info" data-mage-init='{"addToCart":{"origin": "info", - "helpLinkId": "#<?= /* @escapeNotVerified */ $helpLinkId ?>", + "helpLinkId": "#<?= /* @noEscape */ $helpLinkId ?>", "productName": "<?= $block->escapeJs($block->escapeHtml($product->getName())) ?>", - "closeButtonId": "#map-popup-close"}}'><span><?= /* @escapeNotVerified */ __("What's this?") ?></span> + "closeButtonId": "#map-popup-close"}}'> + <span><?= $block->escapeHtml(__("What's this?")) ?></span> </a> <?php endif; ?> diff --git a/app/code/Magento/Msrp/view/frontend/templates/cart/subtotal.phtml b/app/code/Magento/Msrp/view/frontend/templates/cart/subtotal.phtml index 0bfd4589bb79f..0e00a2df8920c 100644 --- a/app/code/Magento/Msrp/view/frontend/templates/cart/subtotal.phtml +++ b/app/code/Magento/Msrp/view/frontend/templates/cart/subtotal.phtml @@ -6,6 +6,6 @@ ?> <div class="subtotal"> <span class="mark msrp"> - <?= /* @escapeNotVerified */ __('Order total will be displayed before you submit the order') ?> + <?= $block->escapeHtml(__('Order total will be displayed before you submit the order')) ?> </span> </div> diff --git a/app/code/Magento/Msrp/view/frontend/templates/cart/totals.phtml b/app/code/Magento/Msrp/view/frontend/templates/cart/totals.phtml index d632a2fe8c1aa..a0a2f9179dd87 100644 --- a/app/code/Magento/Msrp/view/frontend/templates/cart/totals.phtml +++ b/app/code/Magento/Msrp/view/frontend/templates/cart/totals.phtml @@ -3,9 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile ?> <div class="cart-totals"> - <div class="msrp totals"><?= /* @escapeNotVerified */ __('You will see the order total before you submit the order.') ?></div> + <div class="msrp totals"> + <?= $block->escapeHtml(__('You will see the order total before you submit the order.')) ?> + </div> </div> diff --git a/app/code/Magento/Msrp/view/frontend/templates/popup.phtml b/app/code/Magento/Msrp/view/frontend/templates/popup.phtml index 7ccd606b8f113..04f201736d373 100644 --- a/app/code/Magento/Msrp/view/frontend/templates/popup.phtml +++ b/app/code/Magento/Msrp/view/frontend/templates/popup.phtml @@ -3,14 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @var \Magento\Msrp\Block\Popup $block */ ?> -<?php if ($block->isEnabled()): ?> +<?php if ($block->isEnabled()) : ?> <script data-role="msrp-popup-template" type="text/x-magento-template"> <div id="map-popup-click-for-price" class="map-popup"> <div class="popup-header"> @@ -20,13 +17,13 @@ <div class="map-info-price" id="map-popup-content"> <div class="price-box"> <div class="map-msrp" id="map-popup-msrp-box"> - <span class="label"><?= /* @escapeNotVerified */ __('Price') ?></span> + <span class="label"><?= $block->escapeHtml(__('Price')) ?></span> <span class="old-price map-old-price" id="map-popup-msrp"> <span class="price"></span> </span> </div> <div class="map-price" id="map-popup-price-box"> - <span class="label"><?= /* @escapeNotVerified */ __('Actual Price') ?></span> + <span class="label"><?= $block->escapeHtml(__('Actual Price')) ?></span> <span id="map-popup-price" class="actual-price"></span> </div> </div> @@ -36,7 +33,7 @@ title="<?= $block->escapeHtml(__('Add to Cart')) ?>" class="action tocart primary" id="map-popup-button"> - <span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span> + <span><?= $block->escapeHtml(__('Add to Cart')) ?></span> </button> <div class="additional-addtocart-box"> <?= $block->getChildHtml() ?> @@ -44,7 +41,7 @@ </form> </div> <div class="map-text" id="map-popup-text"> - <?= /* @escapeNotVerified */ $block->getExplanationMessage() ?> + <?= /* @noEscape */ $block->getExplanationMessage() ?> </div> </div> </div> @@ -56,7 +53,7 @@ </div> <div class="popup-content"> <div class="map-help-text" id="map-popup-text-what-this"> - <?= /* @escapeNotVerified */ $block->getExplanationMessageWhatsThis() ?> + <?= /* @noEscape */ $block->getExplanationMessageWhatsThis() ?> </div> </div> </div> diff --git a/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_item.phtml b/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_item.phtml index 8f697001d30c4..8a08be0a6caf1 100644 --- a/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_item.phtml +++ b/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_item.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php @@ -16,10 +13,12 @@ */ ?> <?php + // phpcs:disable /** @var $pricingHelper \Magento\Framework\Pricing\Helper\Data */ - $pricingHelper = $this->helper('Magento\Framework\Pricing\Helper\Data'); + $pricingHelper = $this->helper(\Magento\Framework\Pricing\Helper\Data::class); /** @var $_catalogHelper \Magento\Catalog\Helper\Data */ - $_catalogHelper = $this->helper('Magento\Catalog\Helper\Data'); + $_catalogHelper = $this->helper(\Magento\Catalog\Helper\Data::class); + // phpcs:enable /** @var $_product \Magento\Catalog\Model\Product */ $_product = $block->getProduct(); @@ -27,29 +26,35 @@ $_msrpPrice = ''; ?> <div class="price-box msrp"> - <?php if ($_product->getMsrp()): ?> + <?php if ($_product->getMsrp()) : ?> <?php $_msrpPrice = $pricingHelper->currency($_product->getMsrp(), true, false) ?> - <span class="old-price"><?= /* @escapeNotVerified */ $_msrpPrice ?></span> + <span class="old-price"><?= /* @noEscape */ $_msrpPrice ?></span> <?php endif; ?> - <?php if ($_catalogHelper->isShowPriceOnGesture($_product)): ?> + <?php if ($_catalogHelper->isShowPriceOnGesture($_product)) : ?> <?php $priceElementId = 'product-price-' . $_id . $block->getIdSuffix(); ?> - <span id="<?= /* @escapeNotVerified */ $priceElementId ?>" style="display: none"></span> + <span id="<?= /* @noEscape */ $priceElementId ?>" style="display: none"></span> <?php $popupId = 'msrp-popup-' . $_id . $block->getRandomString(20); ?> <a href="javascript:void(0);" - id="<?= /* @escapeNotVerified */ ($popupId) ?>" - data-mage-init='{"addToCart":{"popupId": "#<?= /* @escapeNotVerified */ ($popupId) ?>", - "productName": "<?= /* @noEscape */ $block->escapeJs($block->escapeHtml($_product->getName())) ?>", - "realPrice": <?= /* @escapeNotVerified */ $block->getRealPriceJs($_product) ?>, - "msrpPrice": "<?= /* @escapeNotVerified */ $_msrpPrice ?>", - "priceElementId":"<?= /* @escapeNotVerified */ $priceElementId ?>", - "popupCartButtonId": "#map-popup-button", - "cartForm": "#wishlist-view-form"}}'><?= /* @escapeNotVerified */ __('Click for price') ?> + id="<?= /* @noEscape */ ($popupId) ?>" + data-mage-init='{"addToCart":{"popupId": "#<?= /* @noEscape */ ($popupId) ?>", + "productName": "<?= /* @noEscape */ $block->escapeJs($block->escapeHtml($_product->getName())) ?>", + "realPrice": <?= /* @noEscape */ $block->getRealPriceJs($_product) ?>, + "msrpPrice": "<?= /* @noEscape */ $_msrpPrice ?>", + "priceElementId":"<?= /* @noEscape */ $priceElementId ?>", + "popupCartButtonId": "#map-popup-button", + "cartForm": "#wishlist-view-form"}}'> + <?= $block->escapeHtml(__('Click for price')) ?> </a> - <?php else: ?> + <?php else : ?> <span class="msrp-message"> - <?= /* @escapeNotVerified */ $_catalogHelper->getMsrpPriceMessage($_product) ?> + <?= $block->escapeHtml($_catalogHelper->getMsrpPriceMessage($_product)) ?> </span> <?php endif; ?> <?php $helpLinkId = 'msrp-help-' . $_id . $block->getRandomString(20); ?> - <a href="javascript:void(0);" id="<?= /* @escapeNotVerified */ ($helpLinkId) ?>" data-mage-init='{"addToCart":{"helpLinkId": "#<?= /* @escapeNotVerified */ ($helpLinkId) ?>", "productName": "<?= /* @noEscape */ $block->escapeJs($block->escapeHtml($_product->getName())) ?>"}}' class="link tip"><?= /* @escapeNotVerified */ __("What's this?") ?></a> + <a href="javascript:void(0);" id="<?= /* @noEscape */ ($helpLinkId) ?>" + data-mage-init='{"addToCart":{"helpLinkId": "#<?= /* @noEscape */ ($helpLinkId) ?>", + "productName": "<?= /* @noEscape */ $block->escapeJs($block->escapeHtml($_product->getName())) ?>"}}' + class="link tip"> + <?= $block->escapeHtml(__("What's this?")) ?> + </a> </div> diff --git a/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_rss.phtml b/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_rss.phtml index d41bec0d9ebcc..584dea19bef4a 100644 --- a/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_rss.phtml +++ b/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_rss.phtml @@ -3,9 +3,6 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - ?> <?php /** @@ -15,7 +12,9 @@ */ ?> <div class="price-box msrp"> - <?php if ($this->helper('Magento\Msrp\Helper\Data')->canApplyMsrp($block->getProduct())): ?> - <a href="<?= /* @escapeNotVerified */ $block->getProduct()->getProductUrl() ?>"><?= /* @escapeNotVerified */ __('Click for price') ?></a> + <?php if ($this->helper(\Magento\Msrp\Helper\Data::class)->canApplyMsrp($block->getProduct())) : ?> + <a href="<?= $block->escapeUrl($block->getProduct()->getProductUrl()) ?>"> + <?= $block->escapeHtml(__('Click for price')) ?> + </a> <?php endif; ?> </div> From 3791c37e441f56bb8e98c7193e666f14b06a5156 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Tue, 11 Jun 2019 09:18:06 -0500 Subject: [PATCH 1926/2092] MAGETWO-99930: Configuarable product stock status stays 'In Stock' --- .../CatalogInventory/Observer/SaveInventoryDataObserver.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/CatalogInventory/Observer/SaveInventoryDataObserver.php b/app/code/Magento/CatalogInventory/Observer/SaveInventoryDataObserver.php index 67171d6432e58..fe620acb90d84 100644 --- a/app/code/Magento/CatalogInventory/Observer/SaveInventoryDataObserver.php +++ b/app/code/Magento/CatalogInventory/Observer/SaveInventoryDataObserver.php @@ -13,6 +13,7 @@ use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\CatalogInventory\Model\StockItemValidator; use Magento\Framework\Event\Observer as EventObserver; +use Magento\ConfigurableProduct\Model\Inventory\ParentItemProcessor; /** * Saves stock data from a product to the Stock Item @@ -40,7 +41,7 @@ class SaveInventoryDataObserver implements ObserverInterface private $stockItemValidator; /** - * @var array + * @var ParentItemProcessor[] */ private $parentItemProcessorPool; From 848235f0b266751daa016f8c1d5f4c9046d0a264 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Tue, 11 Jun 2019 09:18:06 -0500 Subject: [PATCH 1927/2092] MC-10023: Product Categories Indexer in Update on Schedule mode --- ...roductCategoryIndexerInUpdateOnScheduleModeTest.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml index 6b539f1884dfd..d920ed90c80c5 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminProductCategoryIndexerInUpdateOnScheduleModeTest.xml @@ -12,7 +12,7 @@ <annotations> <stories value="Product Categories Indexer"/> <title value="Product Categories Indexer in Update on Schedule mode"/> - <description value="The test verifies that in Update on Schedule mode if displaying of category products on Storefront changes due to product properties change, + <description value="Verifies that in Update on Schedule mode if displaying of category products on Storefront changes due to product properties change, the changes are NOT applied immediately, but applied only after cron runs (twice)."/> <severity value="CRITICAL"/> <testCaseId value="MC-10023"/> @@ -117,7 +117,7 @@ <see userInput="$$createCategoryA.name$$" selector="{{StorefrontCategoryMainSection.categoryTitle}}" stepKey="seeCategoryAOnPage"/> <see userInput="$$createProductA1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeNameProductA1"/> - <!-- 8. Run cron reindex (Ensure that at least one minute passed since last cron run) --> + <!-- 8. Run cron reindex --> <wait time="60" stepKey="waitOneMinute"/> <magentoCLI command="cron:run" stepKey="runCron1"/> <magentoCLI command="cron:run" stepKey="runTwiceCron1"/> @@ -172,7 +172,7 @@ <see userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProductC1inCategoryC1"/> <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeProductC2InCategoryC2"/> - <!-- 14. Run cron to reindex (Ensure that at least one minute passed since last cron run) --> + <!-- 14. Run cron to reindex --> <wait time="60" stepKey="waitMinute"/> <magentoCLI command="cron:run" stepKey="runCron2"/> <magentoCLI command="cron:run" stepKey="runTwiceCron2"/> @@ -231,7 +231,7 @@ <dontSee userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="dontSeeCategoryCPageProductC1"/> <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeCategoryCPageProductC2"/> - <!-- 17.14. Run cron to reindex (Ensure that at least one minute passed since last cron run) --> + <!-- 17.14. Run cron to reindex --> <wait time="60" stepKey="waitForOneMinute"/> <magentoCLI command="cron:run" stepKey="runCron3"/> <magentoCLI command="cron:run" stepKey="runTwiceCron3"/> @@ -291,7 +291,7 @@ <see userInput="$$createProductC1.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeOnCategoryCProductC1"/> <see userInput="$$createProductC2.name$$" selector="{{StorefrontCategoryMainSection.productName}}" stepKey="seeOnCategoryCProductC2"/> - <!-- 18.14. Run cron to reindex (Ensure that at least one minute passed since last cron run) --> + <!-- 18.14. Run cron to reindex --> <wait time="60" stepKey="waitExtraMinute"/> <magentoCLI command="cron:run" stepKey="runCron4"/> <magentoCLI command="cron:run" stepKey="runTwiceCron4"/> From 964ed6de6ee0362d8cbcca46d0b7419673894bc0 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Tue, 11 Jun 2019 09:24:08 -0500 Subject: [PATCH 1928/2092] MAGETWO-99930: Configuarable product stock status stays 'In Stock' --- .../CatalogInventory/Observer/SaveInventoryDataObserver.php | 3 +-- .../Model/Inventory/ParentItemProcessor.php | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/CatalogInventory/Observer/SaveInventoryDataObserver.php b/app/code/Magento/CatalogInventory/Observer/SaveInventoryDataObserver.php index fe620acb90d84..67171d6432e58 100644 --- a/app/code/Magento/CatalogInventory/Observer/SaveInventoryDataObserver.php +++ b/app/code/Magento/CatalogInventory/Observer/SaveInventoryDataObserver.php @@ -13,7 +13,6 @@ use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\CatalogInventory\Model\StockItemValidator; use Magento\Framework\Event\Observer as EventObserver; -use Magento\ConfigurableProduct\Model\Inventory\ParentItemProcessor; /** * Saves stock data from a product to the Stock Item @@ -41,7 +40,7 @@ class SaveInventoryDataObserver implements ObserverInterface private $stockItemValidator; /** - * @var ParentItemProcessor[] + * @var array */ private $parentItemProcessorPool; diff --git a/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php b/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php index 53e25a3501a0f..a83405a6d8703 100644 --- a/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php +++ b/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php @@ -52,7 +52,7 @@ public function __construct( } /** - * Process pare + * Process parent products * * @param Product $product * @return void From dc73aafaf4d057d477d7bd7c216e68ef23f42a6f Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Tue, 11 Jun 2019 10:30:57 -0500 Subject: [PATCH 1929/2092] MC-8893: Checkout can properly process flow if list of shipping carriers are changed during place order --- .../OpenStoreFrontProductPageActionGroup.xml | 17 +++ .../Mftf/ActionGroup/CheckoutActionGroup.xml | 9 ++ ...ckoutFillNewShippingAddressActionGroup.xml | 25 +++++ .../Checkout/Test/Mftf/Data/ConfigData.xml | 42 ++++++++ .../Mftf/Section/CheckoutPaymentSection.xml | 1 + .../CheckoutShippingMethodsSection.xml | 1 + ...sNotAffectedStartedCheckoutProcessTest.xml | 102 ++++++++++++++++++ ...latRateShippingMethodStatusActionGroup.xml | 21 ++++ ...enShippingMethodsConfigPageActionGroup.xml | 15 +++ .../AdminShippingMethodFlatRateSection.xml | 15 +++ .../Page/AdminShippingMethodsConfigPage.xml | 14 +++ 11 files changed, 262 insertions(+) create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStoreFrontProductPageActionGroup.xml create mode 100644 app/code/Magento/Checkout/Test/Mftf/ActionGroup/GuestCheckoutFillNewShippingAddressActionGroup.xml create mode 100644 app/code/Magento/Checkout/Test/Mftf/Data/ConfigData.xml create mode 100644 app/code/Magento/Checkout/Test/Mftf/Test/AdminCheckConfigsChangesIsNotAffectedStartedCheckoutProcessTest.xml create mode 100644 app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminChangeFlatRateShippingMethodStatusActionGroup.xml create mode 100644 app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminOpenShippingMethodsConfigPageActionGroup.xml create mode 100644 app/code/Magento/Shipping/Test/Mftf/Section/AdminShippingMethodFlatRateSection.xml create mode 100644 app/code/Magento/Ups/Test/Mftf/Page/AdminShippingMethodsConfigPage.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStoreFrontProductPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStoreFrontProductPageActionGroup.xml new file mode 100644 index 0000000000000..7c40fc5796796 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStoreFrontProductPageActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="OpenStorefrontProductPageActionGroup"> + <arguments> + <argument name="productUrlKey" type="string"/> + </arguments> + <amOnPage url="{{StorefrontProductPage.url(productUrlKey)}}" stepKey="amOnProductPage"/> + <waitForPageLoad stepKey="waitForProductPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/CheckoutActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/CheckoutActionGroup.xml index 09197a90542ee..27808e9ad03a3 100644 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/CheckoutActionGroup.xml +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/CheckoutActionGroup.xml @@ -128,4 +128,13 @@ <click selector="{{CheckoutPaymentSection.placeOrderNoWait}}" stepKey="clickPlaceOrder"/> <waitForText selector="{{StorefrontMessagesSection.errorMessage}}" userInput="{{errorMessage}}" time="30" stepKey="seeShippingMethodError"/> </actionGroup> + + <!-- Check shipping method in checkout --> + <actionGroup name="CheckShippingMethodInCheckoutActionGroup"> + <arguments> + <argument name="shippingMethod"/> + </arguments> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" time="30" stepKey="waitForPaymentSectionLoaded"/> + <see userInput="{{shippingMethod}}" selector="{{CheckoutPaymentSection.shippingMethodInformation}}" stepKey="assertshippingMethodInformation"/> + </actionGroup> </actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/GuestCheckoutFillNewShippingAddressActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/GuestCheckoutFillNewShippingAddressActionGroup.xml new file mode 100644 index 0000000000000..6ea2ccb08d8d3 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/GuestCheckoutFillNewShippingAddressActionGroup.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="GuestCheckoutFillNewShippingAddressActionGroup"> + <arguments> + <argument name="customer" type="entity"/> + <argument name="address" type="entity"/> + </arguments> + <fillField selector="{{CheckoutShippingSection.email}}" userInput="{{customer.email}}" stepKey="fillEmailField"/> + <fillField selector="{{CheckoutShippingSection.firstName}}" userInput="{{customer.firstName}}" stepKey="fillFirstName"/> + <fillField selector="{{CheckoutShippingSection.lastName}}" userInput="{{customer.lastName}}" stepKey="fillLastName"/> + <fillField selector="{{CheckoutShippingSection.street}}" userInput="{{address.street}}" stepKey="fillStreet"/> + <fillField selector="{{CheckoutShippingSection.city}}" userInput="{{address.city}}" stepKey="fillCity"/> + <selectOption selector="{{CheckoutShippingSection.region}}" userInput="{{address.state}}" stepKey="selectRegion"/> + <fillField selector="{{CheckoutShippingSection.postcode}}" userInput="{{address.postcode}}" stepKey="fillZipCode"/> + <fillField selector="{{CheckoutShippingSection.telephone}}" userInput="{{address.telephone}}" stepKey="fillPhone"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/Data/ConfigData.xml b/app/code/Magento/Checkout/Test/Mftf/Data/ConfigData.xml new file mode 100644 index 0000000000000..421422dffe65c --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Data/ConfigData.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> + <!-- Free shipping --> + <entity name="EnableFreeShippingConfigData"> + <data key="path">carriers/freeshipping/active</data> + <data key="scope">carriers</data> + <data key="scope_id">1</data> + <data key="label">Yes</data> + <data key="value">1</data> + </entity> + <entity name="DisableFreeShippingConfigData"> + <data key="path">carriers/freeshipping/active</data> + <data key="scope">carriers</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">0</data> + </entity> + + <!-- Flat Rate shipping --> + <entity name="EnableFlatRateConfigData"> + <data key="path">carriers/flatrate/active</data> + <data key="scope">carriers</data> + <data key="scope_id">1</data> + <data key="label">Yes</data> + <data key="value">1</data> + </entity> + <entity name="DisableFlatRateConfigData"> + <data key="path">carriers/flatrate/active</data> + <data key="scope">carriers</data> + <data key="scope_id">1</data> + <data key="label">No</data> + <data key="value">0</data> + </entity> +</entities> diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml index 938d46367e634..91cc992e4326f 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml @@ -49,5 +49,6 @@ <element name="billingAddressSelectShared" type="select" selector=".checkout-billing-address select[name='billing_address_id']"/> <element name="billingAddressSameAsShippingShared" type="checkbox" selector="#billing-address-same-as-shipping-shared"/> <element name="addressAction" type="button" selector="//div[@class='actions-toolbar']//span[text()='{{action}}']" parameterized="true"/> + <element name="shippingMethodInformation" type="text" selector="//div[@class='ship-via']//div[@class='shipping-information-content']" /> </section> </sections> diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutShippingMethodsSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutShippingMethodsSection.xml index d101635ca6773..aa83bc565f90a 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutShippingMethodsSection.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutShippingMethodsSection.xml @@ -16,5 +16,6 @@ <element name="shippingMethodRowByName" type="text" selector="//div[@id='checkout-shipping-method-load']//td[contains(., '{{var1}}')]/.." parameterized="true"/> <element name="flatRate" type="radio" selector="#label_carrier_flatrate_flatrate"/> <element name="freeShippingShippingMethod" type="input" selector="#s_method_freeshipping_freeshipping" timeout="30"/> + <element name="shippingMethodFreeShipping" type="radio" selector="#checkout-shipping-method-load input[value='freeshipping_freeshipping']"/> </section> </sections> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/AdminCheckConfigsChangesIsNotAffectedStartedCheckoutProcessTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/AdminCheckConfigsChangesIsNotAffectedStartedCheckoutProcessTest.xml new file mode 100644 index 0000000000000..706eccadd3a0c --- /dev/null +++ b/app/code/Magento/Checkout/Test/Mftf/Test/AdminCheckConfigsChangesIsNotAffectedStartedCheckoutProcessTest.xml @@ -0,0 +1,102 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminCheckConfigsChangesAreNotAffectedStartedCheckoutProcessTest"> + <annotations> + <features value="Checkout"/> + <stories value="Changes in configs are not affecting checkout process"/> + <title value="Admin check configs changes are not affected started checkout process test"/> + <description value="Changes in admin for shipping rates are not affecting checkout process that has been started"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-8893"/> + <group value="checkout"/> + </annotations> + <before> + <!-- Create simple product --> + <createData entity="SimpleProduct3" stepKey="createProduct"/> + + <!-- Enable free shipping method --> + <magentoCLI command="config:set {{EnableFreeShippingConfigData.path}} {{EnableFreeShippingConfigData.value}}" stepKey="enableFreeShipping"/> + + <!-- Disable flat rate method --> + <magentoCLI command="config:set {{DisableFlatRateConfigData.path}} {{DisableFlatRateConfigData.value}}" stepKey="disableFlatRate"/> + </before> + <after> + <!-- Roll back configuration --> + <magentoCLI command="config:set {{EnableFlatRateConfigData.path}} {{EnableFlatRateConfigData.value}}" stepKey="enableFlatRate"/> + <magentoCLI command="config:set {{DisableFreeShippingConfigData.path}} {{DisableFreeShippingConfigData.value}}" stepKey="disableFreeShipping"/> + + <!-- Delete simple product --> + <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> + + <!-- Log out --> + <actionGroup ref="logout" stepKey="logout"/> + </after> + + <!-- Add product to cart --> + <actionGroup ref="OpenStorefrontProductPageActionGroup" stepKey="openProductPage"> + <argument name="productUrlKey" value="$$createProduct.custom_attributes[url_key]$$"/> + </actionGroup> + <actionGroup ref="StorefrontAddProductToCartActionGroup" stepKey="addProductToCart"> + <argument name="product" value="$$createProduct$$"/> + <argument name="productCount" value="1"/> + </actionGroup> + + <!-- Proceed to Checkout from mini shopping cart --> + <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckout"/> + + <!-- Fill all required fields --> + <actionGroup ref="GuestCheckoutFillNewShippingAddressActionGroup" stepKey="fillNewShippingAddress"> + <argument name="customer" value="Simple_Customer_Without_Address"/> + <argument name="address" value="US_Address_TX"/> + </actionGroup> + + <!-- Assert Free Shipping checkbox --> + <seeCheckboxIsChecked selector="{{CheckoutShippingMethodsSection.shippingMethodFreeShipping}}" stepKey="freeShippingMethodCheckboxIsChecked"/> + + <!-- Click Next button --> + <click selector="{{GuestCheckoutShippingSection.next}}" stepKey="clickNext"/> + <waitForPageLoad stepKey="waitForShipmentPageLoad"/> + + <!-- Payment step is opened --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" stepKey="waitForPaymentSectionLoaded"/> + + <!-- Order Summary block contains information about shipping --> + <actionGroup ref="CheckShippingMethodInCheckoutActionGroup" stepKey="guestCheckoutCheckShippingMethod"> + <argument name="shippingMethod" value="freeTitleDefault.value"/> + </actionGroup> + + <!-- Open new browser's window and login as Admin --> + <openNewTab stepKey="openNewTab"/> + <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> + + <!-- Go to Store > Configuration > Sales > Shipping Methods --> + <actionGroup ref="AdminOpenShippingMethodsConfigPageActionGroup" stepKey="openShippingMethodConfigPage"/> + + <!-- Enable "Flat Rate" --> + <actionGroup ref="AdminChangeFlatRateShippingMethodStatusActionGroup" stepKey="enableFlatRateShippingStatus"/> + + <!-- Flush cache --> + <magentoCLI command="cache:flush" stepKey="cacheFlush"/> + + <!-- Back to the Checkout and refresh the page --> + <switchToPreviousTab stepKey="switchToPreviousTab"/> + <reloadPage stepKey="refreshPage"/> + <waitForPageLoad stepKey="waitPageReload"/> + + <!-- Payment step is opened after refreshing --> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" stepKey="waitForPaymentSection"/> + + <!-- Order Summary block contains information about free shipping --> + <actionGroup ref="CheckShippingMethodInCheckoutActionGroup" stepKey="guestCheckoutCheckFreeShippingMethod"> + <argument name="shippingMethod" value="freeTitleDefault.value"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminChangeFlatRateShippingMethodStatusActionGroup.xml b/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminChangeFlatRateShippingMethodStatusActionGroup.xml new file mode 100644 index 0000000000000..977ee065a8fb1 --- /dev/null +++ b/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminChangeFlatRateShippingMethodStatusActionGroup.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminChangeFlatRateShippingMethodStatusActionGroup"> + <arguments> + <argument name="status" type="string" defaultValue="1"/> + </arguments> + <conditionalClick selector="{{AdminShippingMethodFlatRateSection.carriersFlatRateTab}}" dependentSelector="{{AdminShippingMethodFlatRateSection.carriersFlatRateActive}}" visible="false" stepKey="expandTab"/> + <selectOption selector="{{AdminShippingMethodFlatRateSection.carriersFlatRateActive}}" userInput="{{status}}" stepKey="changeFlatRateMethodStatus"/> + <click selector="{{AdminConfigSection.saveButton}}" stepKey="saveConfigs"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <see selector="{{AdminCategoryMessagesSection.SuccessMessage}}" userInput="You saved the configuration." stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminOpenShippingMethodsConfigPageActionGroup.xml b/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminOpenShippingMethodsConfigPageActionGroup.xml new file mode 100644 index 0000000000000..a1fefcf13afa4 --- /dev/null +++ b/app/code/Magento/Shipping/Test/Mftf/ActionGroup/AdminOpenShippingMethodsConfigPageActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminOpenShippingMethodsConfigPageActionGroup"> + <amOnPage url="{{AdminShippingMethodsConfigPage.url}}" stepKey="navigateToAdminShippingMethodsPage"/> + <waitForPageLoad stepKey="waitForAdminShippingMethodsPageToLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Shipping/Test/Mftf/Section/AdminShippingMethodFlatRateSection.xml b/app/code/Magento/Shipping/Test/Mftf/Section/AdminShippingMethodFlatRateSection.xml new file mode 100644 index 0000000000000..a7ed0ab498bea --- /dev/null +++ b/app/code/Magento/Shipping/Test/Mftf/Section/AdminShippingMethodFlatRateSection.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminShippingMethodFlatRateSection"> + <element name="carriersFlatRateTab" type="button" selector="#carriers_flatrate-head"/> + <element name="carriersFlatRateActive" type="select" selector="#carriers_flatrate_active"/> + </section> +</sections> diff --git a/app/code/Magento/Ups/Test/Mftf/Page/AdminShippingMethodsConfigPage.xml b/app/code/Magento/Ups/Test/Mftf/Page/AdminShippingMethodsConfigPage.xml new file mode 100644 index 0000000000000..d884be709d208 --- /dev/null +++ b/app/code/Magento/Ups/Test/Mftf/Page/AdminShippingMethodsConfigPage.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<pages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/PageObject.xsd"> + <page name="AdminShippingMethodsConfigPage" url="admin/system_config/edit/section/carriers/" area="admin" module="Magento_Ups"> + <section name="AdminShippingMethodsUpsSection"/> + </page> +</pages> From e691d4d4def381c7dac8b6207f67e0af9ff8fb02 Mon Sep 17 00:00:00 2001 From: Andrew Molina <amolina@adobe.com> Date: Tue, 11 Jun 2019 11:01:16 -0500 Subject: [PATCH 1930/2092] MC-17330: Review Order For Multi-Address Checkout w/ FPT --- .../templates/sales/order/creditmemo/items/renderer.phtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml b/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml index eebcf42f3bd0f..e15b281ecddd9 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml @@ -65,7 +65,7 @@ </td> <td class="col discount" data-th="<?= $block->escapeHtml(__('Discount Amount')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= $block->escapeHtml($block->getOrder()->formatPrice(-$_item->getDiscountAmount())) ?> + <?= $block->escapeHtml($block->getOrder()->formatPrice(-$_item->getDiscountAmount()), ['span']) ?> <?php else : ?>   <?php endif; ?> From b73d4d6540412aa0e10185153ee5863b4bfa1e61 Mon Sep 17 00:00:00 2001 From: Dave Macaulay <macaulay@adobe.com> Date: Tue, 11 Jun 2019 11:11:37 -0500 Subject: [PATCH 1931/2092] MC-17242: Eliminate @escapeNotVerified in Sales-related Modules - Resolve build failures --- .../view/adminhtml/templates/order/create/form/address.phtml | 2 +- .../view/adminhtml/templates/order/create/sidebar/items.phtml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml index 7ae29e64083e1..0cdaf9ecccc0c 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml @@ -31,7 +31,7 @@ if ($block->getIsShipping()) : <script> require(["Magento_Sales/order/create/form"], function(){ order.shippingAddressContainer = '<?= $block->escapeJs($_fieldsContainerId) ?>'; - order.setAddresses(<?= /* @noEscape */ $block->getAddressCollectionJson() ?>); + order.setAddresses(<?= /* @noEscape */ $block->getAddressCollectionJson() ?>); }); </script> <?php diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar/items.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar/items.phtml index 5e26e2fa23064..a323bc9aa5c2f 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar/items.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/sidebar/items.phtml @@ -105,7 +105,7 @@ type="checkbox" class="admin__control-checkbox" name="sidebar[<?= $block->escapeHtmlAttr($block->getSidebarStorageAction()) ?>][<?= (int) $block->getIdentifierId($_item) ?>]" - value="<?= $block->canDisplayItemQty() ? (int) $_item->getQty() : 1 ?>" + value="<?= /* @noEscape */ $block->canDisplayItemQty() ? (int) $_item->getQty() : 1 ?>" title="<?= $block->escapeHtml(__('Add To Order')) ?>"/> <label class="admin__field-label" for="sidebar-<?= $block->escapeHtmlAttr($block->getSidebarStorageAction()) ?>-<?= (int) $block->getIdentifierId($_item) ?>"> From 21a3030678aafc52db47fac40caf665daf616adb Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Tue, 11 Jun 2019 12:19:26 -0500 Subject: [PATCH 1932/2092] MC-8893: Checkout can properly process flow if list of shipping carriers are changed during place order --- .../Mftf/Test/AdminCreateOrderWithBundleProductTest.xml | 2 +- ...tAvailableIfMinimumOrderAmountNotMatchOrderTotalTest.xml | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithBundleProductTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithBundleProductTest.xml index 2332ea3723a42..9808782f39f9b 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithBundleProductTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminCreateOrderWithBundleProductTest.xml @@ -19,7 +19,7 @@ <before> <!--Set default flat rate shipping method settings--> - <createData entity="FlatRateShippingMethodDefault" stepKey="setDefaultFlatRateShippingMethod"/> + <magentoCLI command="config:set {{EnableFlatRateConfigData.path}} {{EnableFlatRateConfigData.value}}" stepKey="enableFlatRate"/> <!--Create simple customer--> <createData entity="Simple_US_CA_Customer" stepKey="simpleCustomer"/> diff --git a/app/code/Magento/Sales/Test/Mftf/Test/AdminFreeShippingNotAvailableIfMinimumOrderAmountNotMatchOrderTotalTest.xml b/app/code/Magento/Sales/Test/Mftf/Test/AdminFreeShippingNotAvailableIfMinimumOrderAmountNotMatchOrderTotalTest.xml index 0bba86ae0ed87..e4e2c44887840 100644 --- a/app/code/Magento/Sales/Test/Mftf/Test/AdminFreeShippingNotAvailableIfMinimumOrderAmountNotMatchOrderTotalTest.xml +++ b/app/code/Magento/Sales/Test/Mftf/Test/AdminFreeShippingNotAvailableIfMinimumOrderAmountNotMatchOrderTotalTest.xml @@ -24,7 +24,7 @@ <field key="price">100</field> </createData> <createData entity="Simple_US_Customer" stepKey="createCustomer"/> - <createData entity="DisableFlatRateShippingMethodConfig" stepKey="disableFlatRate"/> + <magentoCLI command="config:set {{DisableFlatRateConfigData.path}} {{DisableFlatRateConfigData.value}}" stepKey="disableFlatRate"/> <createData entity="FreeShippinMethodConfig" stepKey="enableFreeShippingMethod"/> <createData entity="setFreeShippingSubtotal" stepKey="setFreeShippingSubtotal"/> <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> @@ -34,7 +34,7 @@ <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> - <createData entity="FlatRateShippingMethodConfig" stepKey="enableFlatRate"/> + <magentoCLI command="config:set {{EnableFlatRateConfigData.path}} {{EnableFlatRateConfigData.value}}" stepKey="enableFlatRate"/> <createData entity="FreeShippinMethodDefault" stepKey="disableFreeShippingMethod"/> <createData entity="setFreeShippingSubtotalToDefault" stepKey="setFreeShippingSubtotalToDefault"/> <actionGroup ref="logout" stepKey="logout"/> @@ -60,4 +60,4 @@ <dontSeeElement selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSuccessMessage"/> <seeElement selector="{{AdminMessagesSection.errorMessage}}" stepKey="seeErrorMessage"/> </test> -</tests> \ No newline at end of file +</tests> From 0fa9fe2d27ce96b6b20cd75d09349379533e087d Mon Sep 17 00:00:00 2001 From: Roman Lytvynenko <lytvynen@adobe.com> Date: Tue, 11 Jun 2019 15:55:32 -0500 Subject: [PATCH 1933/2092] MAGETWO-99491: Configurable options attribute position is not saved correctly via API --- .../Api/LinkManagementTest.php | 198 +++++++++++++++--- ...figurable_attributes_for_position_test.php | 101 +++++++++ ..._attributes_for_position_test_rollback.php | 41 ++++ 3 files changed, 312 insertions(+), 28 deletions(-) create mode 100644 dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test.php create mode 100644 dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test_rollback.php diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php index df4138db30ce0..eeb4118e1e87a 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php @@ -6,9 +6,13 @@ */ namespace Magento\ConfigurableProduct\Api; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\Eav\Model\AttributeRepository; +use Magento\Eav\Model\Entity\Attribute\Option; +use Magento\Framework\Webapi\Rest\Request; +use Magento\TestFramework\TestCase\WebapiAbstract; -class LinkManagementTest extends \Magento\TestFramework\TestCase\WebapiAbstract +class LinkManagementTest extends WebapiAbstract { const SERVICE_NAME = 'configurableProductLinkManagementV1'; const SERVICE_VERSION = 'V1'; @@ -88,9 +92,24 @@ public function testAddChildFullRestCreation() $this->createConfigurableProduct($productSku); $attribute = $this->attributeRepository->get('catalog_product', 'test_configurable'); - $attributeValue = $attribute->getOptions()[1]->getValue(); - $this->addOptionToConfigurableProduct($productSku, $attribute->getAttributeId(), $attributeValue); - $this->createSimpleProduct($childSku, $attributeValue); + + $this->addOptionToConfigurableProduct($productSku, $attribute->getAttributeId(), + [ + [ + 'value_index' => $attribute->getOptions()[1]->getValue() + ] + ] + ); + + $this->createSimpleProduct($childSku, + [ + [ + 'attribute_code' => 'test_configurable', + 'value' => $attribute->getOptions()[1]->getValue() + ] + ] + ); + $res = $this->addChild($productSku, $childSku); $this->assertTrue($res); @@ -106,10 +125,127 @@ public function testAddChildFullRestCreation() $this->assertTrue($added); // clean up products + + $this->deleteProduct($productSku); + $this->deleteProduct($childSku); + } + + /** + * Test if configurable option attribute positions are being preserved after simple products were assigned to a + * configurable product. + * + * @magentoApiDataFixture Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test.php + */ + public function testConfigurableOptionPositionPreservation() + { + $productSku = 'configurable-product-sku'; + + $childProductSkus = [ + 'simple-product-sku-1', + 'simple-product-sku-2' + ]; + + $attributesToAdd = [ + 'custom_attr_1', + 'custom_attr_2', + ]; + + $this->createConfigurableProduct($productSku); + + $position = 0; + $attributeOptions = []; + foreach ($attributesToAdd as $attributeToAdd) { + /** @var Attribute $attribute */ + $attribute = $this->attributeRepository->get('catalog_product', $attributeToAdd); + + /** @var Option $options[] */ + $options = $attribute->getOptions(); + array_shift($options); + + $attributeOptions[$attributeToAdd] = $options; + + $valueIndexesData = []; + foreach ($options as $option) { + $valueIndexesData []['value_index']= $option->getValue(); + } + $this->addOptionToConfigurableProduct($productSku, $attribute->getAttributeId(), $valueIndexesData, $position); + $position++; + } + + // Validating initial attribute and option numbers + $this->assertArrayHasKey($attributesToAdd[0], $attributeOptions); + $this->assertArrayHasKey($attributesToAdd[1], $attributeOptions); + $this->assertCount(4, $attributeOptions[$attributesToAdd[0]]); + $this->assertCount(4, $attributeOptions[$attributesToAdd[1]]); + + $attributesBeforeAssign = $this->getConfigurableAttribute($productSku); + + $simpleProdsAttributeData = []; + foreach ($attributeOptions as $attributeCode => $options) { + $simpleProdsAttributeData [0][] = [ + 'attribute_code' => $attributeCode, + 'value' => $options[0]->getValue(), + ]; + $simpleProdsAttributeData [0][] = [ + 'attribute_code' => $attributeCode, + 'value' => $options[1]->getValue(), + ]; + $simpleProdsAttributeData [1][] = [ + 'attribute_code' => $attributeCode, + 'value' => $options[2]->getValue(), + ]; + $simpleProdsAttributeData [1][] = [ + 'attribute_code' => $attributeCode, + 'value' => $options[3]->getValue(), + ]; + } + + foreach ($childProductSkus as $childNum => $childSku) { + $this->createSimpleProduct($childSku, $simpleProdsAttributeData[$childNum]); + $res = $this->addChild($productSku, $childSku); + $this->assertTrue($res); + } + + // confirm that the simple product was added + $childProductsDiff = array_diff( + $childProductSkus, + array_column( + $this->getChildren($productSku), 'sku') + ); + $this->assertCount(0, $childProductsDiff, 'Added child product count mismatch expected result'); + + $attributesAfterAssign = $this->getConfigurableAttribute($productSku); + + $this->assertEquals( + $attributesBeforeAssign[0]['position'], + $attributesAfterAssign[0]['position'], + 'Product 1 attribute option position mismatch' + ); + + $this->assertEquals( + $attributesBeforeAssign[1]['position'], + $attributesAfterAssign[1]['position'], + 'Product 2 attribute option position mismatch' + ); + + // remove products used during the test + foreach ($childProductSkus as $childSku) { + $this->deleteProduct($childSku); + } + $this->deleteProduct($productSku); + } + + /** + * Delete product by SKU + * + * @param string $sku + * @return bool + */ + private function deleteProduct(string $sku): bool { $serviceInfo = [ 'rest' => [ - 'resourcePath' => '/V1/products/' . $productSku, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE + 'resourcePath' => '/V1/products/' . $sku, + 'httpMethod' => Request::HTTP_METHOD_DELETE ], 'soap' => [ 'service' => 'catalogProductRepositoryV1', @@ -117,19 +253,29 @@ public function testAddChildFullRestCreation() 'operation' => 'catalogProductRepositoryV1DeleteById', ], ]; - $this->_webApiCall($serviceInfo, ['sku' => $productSku]); + return $this->_webApiCall($serviceInfo, ['sku' => $sku]); + } + + /** + * Get configurable product attributes + * + * @param string $productSku + * @return array + */ + protected function getConfigurableAttribute($productSku): array + { $serviceInfo = [ 'rest' => [ - 'resourcePath' => '/V1/products/' . $childSku, - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE + 'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/options/all', + 'httpMethod' => Request::HTTP_METHOD_GET ], 'soap' => [ - 'service' => 'catalogProductRepositoryV1', + 'service' => self::SERVICE_NAME, 'serviceVersion' => self::SERVICE_VERSION, - 'operation' => 'catalogProductRepositoryV1DeleteById', - ], + 'operation' => self::SERVICE_NAME . 'GetList' + ] ]; - $this->_webApiCall($serviceInfo, ['sku' => $childSku]); + return $this->_webApiCall($serviceInfo, ['sku' => $productSku]); } private function addChild($productSku, $childSku) @@ -137,7 +283,7 @@ private function addChild($productSku, $childSku) $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/child', - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST + 'httpMethod' => Request::HTTP_METHOD_POST ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -162,7 +308,7 @@ protected function createConfigurableProduct($productSku) $serviceInfo = [ 'rest' => [ 'resourcePath' => '/V1/products', - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST + 'httpMethod' => Request::HTTP_METHOD_POST ], 'soap' => [ 'service' => 'catalogProductRepositoryV1', @@ -173,24 +319,22 @@ protected function createConfigurableProduct($productSku) return $this->_webApiCall($serviceInfo, $requestData); } - protected function addOptionToConfigurableProduct($productSku, $attributeId, $attributeValue) + protected function addOptionToConfigurableProduct($productSku, $attributeId, $attributeValues, $position = 0) { $requestData = [ 'sku' => $productSku, 'option' => [ 'attribute_id' => $attributeId, 'label' => 'test_configurable', - 'position' => 0, + 'position' => $position, 'is_use_default' => true, - 'values' => [ - ['value_index' => $attributeValue], - ] + 'values' => $attributeValues ] ]; $serviceInfo = [ 'rest' => [ 'resourcePath' => '/V1/configurable-products/'. $productSku .'/options', - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + 'httpMethod' => Request::HTTP_METHOD_POST, ], 'soap' => [ 'service' => 'configurableProductOptionRepositoryV1', @@ -201,7 +345,7 @@ protected function addOptionToConfigurableProduct($productSku, $attributeId, $at return $this->_webApiCall($serviceInfo, $requestData); } - protected function createSimpleProduct($sku, $attributeValue) + protected function createSimpleProduct($sku, $customAttributes) { $requestData = [ 'product' => [ @@ -212,15 +356,13 @@ protected function createSimpleProduct($sku, $attributeValue) 'price' => 3.62, 'status' => 1, 'visibility' => 4, - 'custom_attributes' => [ - ['attribute_code' => 'test_configurable', 'value' => $attributeValue], - ] + 'custom_attributes' => $customAttributes ] ]; $serviceInfo = [ 'rest' => [ 'resourcePath' => '/V1/products', - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + 'httpMethod' => Request::HTTP_METHOD_POST, ], 'soap' => [ 'service' => 'catalogProductRepositoryV1', @@ -247,7 +389,7 @@ protected function removeChild($productSku, $childSku) $serviceInfo = [ 'rest' => [ 'resourcePath' => sprintf($resourcePath, $productSku, $childSku), - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE + 'httpMethod' => Request::HTTP_METHOD_DELETE ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -268,7 +410,7 @@ protected function getChildren($productSku) $serviceInfo = [ 'rest' => [ 'resourcePath' => self::RESOURCE_PATH . '/' . $productSku . '/children', - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET + 'httpMethod' => Request::HTTP_METHOD_GET ], 'soap' => [ 'service' => self::SERVICE_NAME, diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test.php new file mode 100644 index 0000000000000..3f907c0ad0cb6 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test.php @@ -0,0 +1,101 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Catalog\Setup\CategorySetup; +use Magento\Eav\Model\Config; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\Eav\Api\AttributeRepositoryInterface; + +Bootstrap::getInstance()->reinitialize(); + +/** @var $eavConfig Config */ +$eavConfig = Bootstrap::getObjectManager()->get(Config::class); + +/** @var $installer CategorySetup */ +$installer = Bootstrap::getObjectManager()->create(CategorySetup::class); + +$attributesData = [ + [ + 'code' => 'custom_attr_1', + 'label' => 'custom_attr_1', + ], + [ + 'code' => 'custom_attr_2', + 'label' => 'custom_attr_2', + ], +]; + +foreach ($attributesData as $attributeData) { + $attribute = $eavConfig->getAttribute('catalog_product', $attributeData['code']); + + $eavConfig->clear(); + + + if (!$attribute->getId()) { + + /** @var $attribute Attribute */ + $attribute = Bootstrap::getObjectManager()->create( + Attribute::class + ); + + /** @var AttributeRepositoryInterface $attributeRepository */ + $attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class); + + $attribute->setData( + [ + 'attribute_code' => $attributeData['code'], + 'entity_type_id' => $installer->getEntityTypeId('catalog_product'), + 'is_global' => 1, + 'is_user_defined' => 1, + 'frontend_input' => 'select', + 'is_unique' => 0, + 'is_required' => 0, + 'is_searchable' => 0, + 'is_visible_in_advanced_search' => 0, + 'is_comparable' => 0, + 'is_filterable' => 0, + 'is_filterable_in_search' => 0, + 'is_used_for_promo_rules' => 0, + 'is_html_allowed_on_front' => 1, + 'is_visible_on_front' => 0, + 'used_in_product_listing' => 0, + 'used_for_sort_by' => 0, + 'frontend_label' => $attributeData['label'], + 'backend_type' => 'int', + 'option' => [ + 'value' => [ + 'option_0' => [ + $attributeData['label'] . ' Option 1' + ], + 'option_1' => [ + $attributeData['label'] . ' Option 2' + ], + 'option_2' => [ + $attributeData['label'] . ' Option 3' + ], + 'option_3' => [ + $attributeData['label'] . ' Option 4' + ] + ], + 'order' => [ + 'option_0' => 1, + 'option_1' => 2, + 'option_2' => 3, + 'option_3' => 4 + ], + ], + ] + ); + + $attributeRepository->save($attribute); + + /* Assign attribute to attribute set */ + $installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId()); + } +} + +$eavConfig->clear(); diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test_rollback.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test_rollback.php new file mode 100644 index 0000000000000..c947eaafda393 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/configurable_attributes_for_position_test_rollback.php @@ -0,0 +1,41 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +use Magento\Catalog\Model\ResourceModel\Product\Collection; +use Magento\Eav\Model\Config; +use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; +use Magento\Framework\Registry; +use Magento\TestFramework\Helper\Bootstrap; + +/** @var Registry $registry */ +$registry = Bootstrap::getObjectManager()->get(Registry::class); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); +$productCollection = Bootstrap::getObjectManager() + ->get(Collection::class); +foreach ($productCollection as $product) { + $product->delete(); +} + +$attributesToDelete = [ + 'custom_attr_1', + 'custom_attr_2', +]; + +foreach ($attributesToDelete as $attributeToDelete) { + $eavConfig = Bootstrap::getObjectManager()->get(Config::class); + $attribute = $eavConfig->getAttribute('catalog_product', $attributeToDelete); + if ($attribute instanceof AbstractAttribute + && $attribute->getId() + ) { + $attribute->delete(); + } + $eavConfig->clear(); +} + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); From 2b5dc003a6bf0e24ba447be889a81328f01ec274 Mon Sep 17 00:00:00 2001 From: Dmytro Yushkin <dyushkin@adobe.com> Date: Tue, 11 Jun 2019 16:30:25 -0500 Subject: [PATCH 1934/2092] MAGETWO-97004: Cannot create Shipping Label for RMA: "No authorized items or allowed shipping methods" --- app/code/Magento/Shipping/Model/Shipping.php | 3 +- .../Shipping/Test/Unit/Model/ShippingTest.php | 144 ++++++++++++------ 2 files changed, 99 insertions(+), 48 deletions(-) diff --git a/app/code/Magento/Shipping/Model/Shipping.php b/app/code/Magento/Shipping/Model/Shipping.php index dc98a9d5a78d1..b0a5282080520 100644 --- a/app/code/Magento/Shipping/Model/Shipping.php +++ b/app/code/Magento/Shipping/Model/Shipping.php @@ -251,8 +251,7 @@ public function collectRates(\Magento\Quote\Model\Quote\Address\RateRequest $req */ public function collectCarrierRates($carrierCode, $request) { - /* @var $carrier \Magento\Shipping\Model\Carrier\AbstractCarrier */ - $carrier = $this->_carrierFactory->createIfActive($carrierCode, $request->getQuoteStoreId()); + $carrier = $this->_carrierFactory->create($carrierCode, $request->getQuoteStoreId()); if (!$carrier) { return $this; } diff --git a/app/code/Magento/Shipping/Test/Unit/Model/ShippingTest.php b/app/code/Magento/Shipping/Test/Unit/Model/ShippingTest.php index 727675407b8a0..812751a4f3c5f 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/ShippingTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/ShippingTest.php @@ -5,10 +5,20 @@ */ namespace Magento\Shipping\Test\Unit\Model; -use \Magento\Shipping\Model\Shipping; - +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\Product\Type as ProductType; +use Magento\CatalogInventory\Model\Stock\Item as StockItem; +use Magento\CatalogInventory\Model\StockRegistry; +use Magento\Quote\Model\Quote\Item as QuoteItem; +use Magento\Shipping\Model\Carrier\AbstractCarrier; +use Magento\Shipping\Model\Carrier\AbstractCarrierInterface; +use Magento\Shipping\Model\Carrier\CarrierInterface; +use Magento\Shipping\Model\CarrierFactory; +use Magento\Shipping\Model\Shipping; use Magento\Quote\Model\Quote\Address\RateRequest; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Store\Model\Store; +use PHPUnit_Framework_MockObject_MockObject as MockObject; class ShippingTest extends \PHPUnit\Framework\TestCase { @@ -25,71 +35,69 @@ class ShippingTest extends \PHPUnit\Framework\TestCase protected $shipping; /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Shipping\Model\Carrier\AbstractCarrier + * @var MockObject|StockRegistry */ - protected $carrier; + protected $stockRegistry; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject|StockItem */ - protected $stockRegistry; + protected $stockItemData; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject|AbstractCarrierInterface */ - protected $stockItemData; + private $carrier; protected function setUp() { - $this->carrier = $this->createMock(\Magento\Shipping\Model\Carrier\AbstractCarrier::class); - $this->carrier->expects($this->any())->method('getConfigData')->will($this->returnCallback(function ($key) { - $configData = [ - 'max_package_weight' => 10, - ]; - return isset($configData[$key]) ? $configData[$key] : 0; - })); - $this->stockRegistry = $this->createMock(\Magento\CatalogInventory\Model\StockRegistry::class); - $this->stockItemData = $this->createMock(\Magento\CatalogInventory\Model\Stock\Item::class); - - $objectManagerHelper = new ObjectManagerHelper($this); - $this->shipping = $objectManagerHelper->getObject( - \Magento\Shipping\Model\Shipping::class, - ['stockRegistry' => $this->stockRegistry] + $this->stockRegistry = $this->createMock(StockRegistry::class); + $this->stockItemData = $this->createMock(StockItem::class); + + $this->shipping = (new ObjectManagerHelper($this))->getObject( + Shipping::class, + [ + 'stockRegistry' => $this->stockRegistry, + 'carrierFactory' => $this->getCarrierFactory(), + ] ); } /** - * @covers \Magento\Shipping\Model\Shipping::composePackagesForCarrier + * */ public function testComposePackages() { $request = new RateRequest(); - /** \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface */ - $item = $this->getMockBuilder(\Magento\Quote\Model\Quote\Item::class) + $item = $this->getMockBuilder(QuoteItem::class) ->disableOriginalConstructor() - ->setMethods([ - 'getQty', 'getIsQtyDecimal', 'getProductType', 'getProduct', 'getWeight', '__wakeup', 'getStore', - ]) - ->getMock(); - $product = $this->createMock(\Magento\Catalog\Model\Product::class); - - $item->expects($this->any())->method('getQty')->will($this->returnValue(1)); - $item->expects($this->any())->method('getWeight')->will($this->returnValue(10)); - $item->expects($this->any())->method('getIsQtyDecimal')->will($this->returnValue(true)); - $item->expects($this->any())->method('getProductType') - ->will($this->returnValue(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)); - $item->expects($this->any())->method('getProduct')->will($this->returnValue($product)); - - $store = $this->createPartialMock(\Magento\Store\Model\Store::class, ['getWebsiteId']); - $store->expects($this->any()) - ->method('getWebsiteId') - ->will($this->returnValue(10)); - $item->expects($this->any())->method('getStore')->will($this->returnValue($store)); - - $product->expects($this->any())->method('getId')->will($this->returnValue($this->productId)); + ->setMethods( + [ + 'getQty', + 'getIsQtyDecimal', + 'getProductType', + 'getProduct', + 'getWeight', + '__wakeup', + 'getStore', + ] + )->getMock(); + $product = $this->createMock(Product::class); + + $item->method('getQty')->will($this->returnValue(1)); + $item->method('getWeight')->will($this->returnValue(10)); + $item->method('getIsQtyDecimal')->will($this->returnValue(true)); + $item->method('getProductType')->will($this->returnValue(ProductType::TYPE_SIMPLE)); + $item->method('getProduct')->will($this->returnValue($product)); + + $store = $this->createPartialMock(Store::class, ['getWebsiteId']); + $store->method('getWebsiteId')->will($this->returnValue(10)); + $item->method('getStore')->will($this->returnValue($store)); + + $product->method('getId')->will($this->returnValue($this->productId)); $request->setData('all_items', [$item]); - $this->stockItemData->expects($this->any())->method('getIsDecimalDivided')->will($this->returnValue(true)); + $this->stockItemData->method('getIsDecimalDivided')->will($this->returnValue(true)); /** Testable service calls to CatalogInventory module */ $this->stockRegistry->expects($this->atLeastOnce())->method('getStockItem') @@ -101,7 +109,51 @@ public function testComposePackages() ->will($this->returnValue(true)); $this->stockItemData->expects($this->atLeastOnce())->method('getQtyIncrements') ->will($this->returnValue(0.5)); + $this->carrier->method('getConfigData') + ->willReturnCallback(function ($key) { + $configData = [ + 'max_package_weight' => 10, + ]; + return isset($configData[$key]) ? $configData[$key] : 0; + }); $this->shipping->composePackagesForCarrier($this->carrier, $request); } + + /** + * Active flag should be set before collecting carrier rates. + */ + public function testCollectCarrierRatesSetActiveFlag() + { + $this->carrier->expects($this->atLeastOnce()) + ->method('setActiveFlag') + ->with('active'); + + $this->shipping->collectCarrierRates('carrier', new RateRequest()); + } + + /** + * @return CarrierFactory|MockObject + */ + private function getCarrierFactory() + { + $carrierFactory = $this->getMockBuilder(CarrierFactory::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->carrier = $this->getMockBuilder(AbstractCarrierInterface::class) + ->setMethods( + [ + 'setActiveFlag', + 'checkAvailableShipCountries', + 'processAdditionalValidation', + 'getConfigData', + 'collectRates', + ] + ) + ->getMockForAbstractClass(); + $carrierFactory->method('create')->willReturn($this->carrier); + + return $carrierFactory; + } } From 45214996f7f9d61feb08d12ceacc9d10ea8b97f8 Mon Sep 17 00:00:00 2001 From: Roman Lytvynenko <lytvynen@adobe.com> Date: Tue, 11 Jun 2019 16:41:12 -0500 Subject: [PATCH 1935/2092] MAGETWO-99491: Configurable options attribute position is not saved correctly via API --- .../Api/LinkManagementTest.php | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php index eeb4118e1e87a..80ad46a4dbf8b 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php @@ -93,7 +93,9 @@ public function testAddChildFullRestCreation() $this->createConfigurableProduct($productSku); $attribute = $this->attributeRepository->get('catalog_product', 'test_configurable'); - $this->addOptionToConfigurableProduct($productSku, $attribute->getAttributeId(), + $this->addOptionToConfigurableProduct( + $productSku, + $attribute->getAttributeId(), [ [ 'value_index' => $attribute->getOptions()[1]->getValue() @@ -101,7 +103,8 @@ public function testAddChildFullRestCreation() ] ); - $this->createSimpleProduct($childSku, + $this->createSimpleProduct( + $childSku, [ [ 'attribute_code' => 'test_configurable', @@ -168,7 +171,12 @@ public function testConfigurableOptionPositionPreservation() foreach ($options as $option) { $valueIndexesData []['value_index']= $option->getValue(); } - $this->addOptionToConfigurableProduct($productSku, $attribute->getAttributeId(), $valueIndexesData, $position); + $this->addOptionToConfigurableProduct( + $productSku, + $attribute->getAttributeId(), + $valueIndexesData, + $position + ); $position++; } @@ -210,7 +218,9 @@ public function testConfigurableOptionPositionPreservation() $childProductsDiff = array_diff( $childProductSkus, array_column( - $this->getChildren($productSku), 'sku') + $this->getChildren($productSku), + 'sku' + ) ); $this->assertCount(0, $childProductsDiff, 'Added child product count mismatch expected result'); @@ -241,7 +251,8 @@ public function testConfigurableOptionPositionPreservation() * @param string $sku * @return bool */ - private function deleteProduct(string $sku): bool { + private function deleteProduct(string $sku): bool + { $serviceInfo = [ 'rest' => [ 'resourcePath' => '/V1/products/' . $sku, From cd58124705eb2bd6c4bb87a53a9f15566ed9e438 Mon Sep 17 00:00:00 2001 From: Roman Lytvynenko <lytvynen@adobe.com> Date: Tue, 11 Jun 2019 18:05:32 -0500 Subject: [PATCH 1936/2092] MAGETWO-99491: Configurable options attribute position is not saved correctly via API --- .../Magento/ConfigurableProduct/Api/LinkManagementTest.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php index 80ad46a4dbf8b..695a084389a5c 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php @@ -142,12 +142,10 @@ public function testAddChildFullRestCreation() public function testConfigurableOptionPositionPreservation() { $productSku = 'configurable-product-sku'; - $childProductSkus = [ 'simple-product-sku-1', 'simple-product-sku-2' ]; - $attributesToAdd = [ 'custom_attr_1', 'custom_attr_2', @@ -214,7 +212,6 @@ public function testConfigurableOptionPositionPreservation() $this->assertTrue($res); } - // confirm that the simple product was added $childProductsDiff = array_diff( $childProductSkus, array_column( @@ -231,14 +228,12 @@ public function testConfigurableOptionPositionPreservation() $attributesAfterAssign[0]['position'], 'Product 1 attribute option position mismatch' ); - $this->assertEquals( $attributesBeforeAssign[1]['position'], $attributesAfterAssign[1]['position'], 'Product 2 attribute option position mismatch' ); - // remove products used during the test foreach ($childProductSkus as $childSku) { $this->deleteProduct($childSku); } From b25b512110c3ac6e9801b7625065b1e745b5a3ef Mon Sep 17 00:00:00 2001 From: Roman Lytvynenko <lytvynen@adobe.com> Date: Tue, 11 Jun 2019 18:29:01 -0500 Subject: [PATCH 1937/2092] MAGETWO-99491: Configurable options attribute position is not saved correctly via API --- .../Magento/ConfigurableProduct/Api/LinkManagementTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php index 695a084389a5c..19f172d69f808 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php @@ -178,7 +178,6 @@ public function testConfigurableOptionPositionPreservation() $position++; } - // Validating initial attribute and option numbers $this->assertArrayHasKey($attributesToAdd[0], $attributeOptions); $this->assertArrayHasKey($attributesToAdd[1], $attributeOptions); $this->assertCount(4, $attributeOptions[$attributesToAdd[0]]); From 624dedf3a21abf52bec995f4ccd9942f6826d5a4 Mon Sep 17 00:00:00 2001 From: DianaRusin <rusind95@gmail.com> Date: Wed, 12 Jun 2019 09:07:44 +0300 Subject: [PATCH 1938/2092] MAGETWO-86624: [2.2] Allowed countries restriction for a default website is applied to backend customer grid --- .../Test/Mftf/Section/AdminCustomerFiltersSection.xml | 1 + .../Test/AllowedCountriesRestrictionApplyOnBackendTest.xml | 5 ++--- .../AdminConfigurationGeneralCountryOptionsSection.xml | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml index dccf879280876..7a29d418565a1 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml @@ -16,5 +16,6 @@ <element name="clearFilters" type="button" selector=".admin__data-grid-header button[data-action='grid-filter-reset']" timeout="30"/> <element name="viewDropdown" type="button" selector=".admin__data-grid-action-bookmarks button.admin__action-dropdown"/> <element name="countryOptions" type="button" selector=".admin__data-grid-filters select[name=billing_country_id] option"/> + <element name="countryOptionsWithoutEmptyOption" type="button" selector=".admin__data-grid-filters select[name=billing_country_id] option:not([value=''])"/> </section> </sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml index 53bdf7c537520..3b45dc286f410 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/AllowedCountriesRestrictionApplyOnBackendTest.xml @@ -55,7 +55,7 @@ <!--Check that all countries are allowed initially and get amount--> <amOnPage url="{{AdminConfigurationGeneralSectionPage.url('#general_country-link')}}" stepKey="goToCountryConfigurationSectionPage"/> - <executeJS function="return document.querySelectorAll('{{AdminConfigurationGeneralCountryOptionsSection.allowedCountries}} option').length" stepKey="countriesAmount"/> + <executeJS function="return document.querySelectorAll('{{AdminConfigurationGeneralCountryOptionsSection.allowedCountriesOptions}}').length" stepKey="countriesAmount"/> <!-- Switch to first website, allow only Canada and set Canada as default country --> <actionGroup ref="AdminSwitchWebsiteActionGroup" stepKey="adminSwitchWebsite"> @@ -82,7 +82,6 @@ <!--Go to Customers grid and check that filter countries amount is the same as initial allowed countries amount--> <amOnPage url="{{AdminCustomerPage.url}}" stepKey="goToCustomersGrid"/> <click selector="{{AdminDataGridHeaderSection.filters}}" stepKey="openFiltersSectionOnCustomersGrid"/> - <executeJS function="var len = document.querySelectorAll('{{AdminCustomerFiltersSection.countryOptions}}').length; return len-1;" stepKey="actualCountriesAmount"/> - <assertEquals expected='($countriesAmount)' actual="($actualCountriesAmount)" stepKey="assertCountryAmounts"/> + <seeNumberOfElements userInput="$countriesAmount" selector="{{AdminCustomerFiltersSection.countryOptionsWithoutEmptyOption}}" stepKey="assertCountryAmounts"/> </test> </tests> diff --git a/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml b/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml index 1e2408ec2fd42..124ffbf102beb 100644 --- a/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml +++ b/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml @@ -17,5 +17,6 @@ <element name="countryOptions" type="button" selector="#general_country-head"/> <element name="countryOptionsOpen" type="button" selector="#general_country-head.open"/> <element name="topDestinations" type="select" selector="#general_country_destinations"/> + <element name="allowedCountriesOptions" selector="#general_country_allow option"/> </section> </sections> From d3fb9b5c0e520e88005804a51e47f39b7af7c072 Mon Sep 17 00:00:00 2001 From: Viktor Sevch <svitja@ukr.net> Date: Wed, 12 Jun 2019 11:21:43 +0300 Subject: [PATCH 1939/2092] MAGETWO-86335: [2.2] Product belongs to categories with and without event does not shown --- .../StorefrontCategoryActionGroup.xml | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml index 8b55737fc373d..6694a0fcf99ae 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml @@ -34,24 +34,15 @@ <seeElement selector="{{StorefrontCategoryProductSection.productTitleByName(product.name)}}" stepKey="assertProductName"/> <see userInput="${{product.price}}.00" selector="{{StorefrontCategoryProductSection.ProductPriceByName(product.name)}}" stepKey="AssertProductPrice"/> <moveMouseOver selector="{{StorefrontCategoryProductSection.ProductInfoByName(product.name)}}" stepKey="moveMouseOverProduct" /> - <executeInSelenium function="function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) use($I) { - $selProdName = '//main//li[.//a[contains(text(), \'' . {{product.name}} . '\' )]]//div[@data-container=\'product-grid\']'; - $I->assertEquals('2', $webdriver->findElement(\Facebook\WebDriver\WebDriverBy::xpath($selProdName))->getCSSValue('z-index')); + <executeInSelenium function="function($webdriver) use ($I) { + $productName = '//main//li[.//a[contains(text(), \'' . {{product.name}} . '\' )]]//div[@data-container=\'product-grid\']'; + $I->assertEquals('2', $webdriver->findElement(\Facebook\WebDriver\WebDriverBy::xpath($productName))->getCSSValue('z-index')); }" stepKey="assertProductContainerIsOpened"/> <seeElement selector="{{StorefrontCategoryProductSection.productAddToCartByName(product.name)}}" stepKey="AssertAddToCart" /> </actionGroup> - <actionGroup name="StorefrontCheckAddToCartButtonAbsence"> - <arguments> - <argument name="product" defaultValue="_defaultProduct"/> - </arguments> - <seeElement selector="{{StorefrontCategoryProductSection.productTitleByName(product.name)}}" stepKey="assertProductName"/> - <moveMouseOver selector="{{StorefrontCategoryProductSection.ProductInfoByName(product.name)}}" stepKey="moveMouseOverProduct" /> - <executeInSelenium function="function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) use($I) { - $selProdName = '//main//li[.//a[contains(text(), \'' . {{product.name}} . '\' )]]//div[@data-container=\'product-grid\']'; - $I->assertEquals('2', $webdriver->findElement(\Facebook\WebDriver\WebDriverBy::xpath($selProdName))->getCSSValue('z-index')); - }" stepKey="assertProductContainerIsOpened"/> - <dontSeeElement selector="{{StorefrontCategoryProductSection.productAddToCartByName(product.name)}}" stepKey="checkAddToCartButtonAbsence"/> + <actionGroup name="StorefrontCheckAddToCartButtonAbsence" extends="StorefrontCheckCategorySimpleProduct"> + <dontSeeElement selector="{{StorefrontCategoryProductSection.productAddToCartByName(product.name)}}" stepKey="AssertAddToCart"/> </actionGroup> <actionGroup name="StorefrontSwitchCategoryViewToListMode"> From ff56c5449d6192040df5fac09acbbe93b18dd4ba Mon Sep 17 00:00:00 2001 From: Viktor Sevch <svitja@ukr.net> Date: Wed, 12 Jun 2019 12:49:37 +0300 Subject: [PATCH 1940/2092] MC-17384: Eliminate @escapeNotVerified in Google-related Modules --- .../Magento/GoogleAdwords/view/frontend/templates/code.phtml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/app/code/Magento/GoogleAdwords/view/frontend/templates/code.phtml b/app/code/Magento/GoogleAdwords/view/frontend/templates/code.phtml index 0ae26e92d487e..31d21117590d9 100644 --- a/app/code/Magento/GoogleAdwords/view/frontend/templates/code.phtml +++ b/app/code/Magento/GoogleAdwords/view/frontend/templates/code.phtml @@ -16,10 +16,6 @@ var google_conversion_color = "<?= $block->escapeJs($block->getHelper()->getConversionColor()) ?>"; var google_conversion_label = "<?= $block->escapeJs($block->getHelper()->getConversionLabel()) ?>"; var google_conversion_value = <?= $block->escapeJs($block->getHelper()->getConversionValue()) ?>; - <?php if ($block->getHelper()->hasSendConversionValueCurrency() - && $block->getHelper()->getConversionValueCurrency()) : ?> - var google_conversion_currency = "<?= $block->escapeJs($block->getHelper()->getConversionValueCurrency()) ?>"; - <?php endif; ?> /* ]]> */ </script> <script src="<?= $block->escapeHtmlAttr($block->getHelper()->getConversionJsSrc()) ?>"></script> From 4b07df4677170644f3a0c54b9b1a5f62f8b9f723 Mon Sep 17 00:00:00 2001 From: Viktor Sevch <svitja@ukr.net> Date: Wed, 12 Jun 2019 14:41:38 +0300 Subject: [PATCH 1941/2092] MAGETWO-86335: [2.2] Product belongs to categories with and without event does not shown --- .../Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml index 6694a0fcf99ae..00b2788af2d70 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/StorefrontCategoryActionGroup.xml @@ -38,11 +38,11 @@ $productName = '//main//li[.//a[contains(text(), \'' . {{product.name}} . '\' )]]//div[@data-container=\'product-grid\']'; $I->assertEquals('2', $webdriver->findElement(\Facebook\WebDriver\WebDriverBy::xpath($productName))->getCSSValue('z-index')); }" stepKey="assertProductContainerIsOpened"/> - <seeElement selector="{{StorefrontCategoryProductSection.productAddToCartByName(product.name)}}" stepKey="AssertAddToCart" /> + <seeElement selector="{{StorefrontCategoryProductSection.productAddToCartByName(product.name)}}" stepKey="assertAddToCart" /> </actionGroup> <actionGroup name="StorefrontCheckAddToCartButtonAbsence" extends="StorefrontCheckCategorySimpleProduct"> - <dontSeeElement selector="{{StorefrontCategoryProductSection.productAddToCartByName(product.name)}}" stepKey="AssertAddToCart"/> + <dontSeeElement selector="{{StorefrontCategoryProductSection.productAddToCartByName(product.name)}}" stepKey="assertAddToCart"/> </actionGroup> <actionGroup name="StorefrontSwitchCategoryViewToListMode"> From f9276c3e5bcd349b99475371aa33498b7999b66d Mon Sep 17 00:00:00 2001 From: Roman Lytvynenko <lytvynen@adobe.com> Date: Wed, 12 Jun 2019 09:12:21 -0500 Subject: [PATCH 1942/2092] MAGETWO-99491: Configurable options attribute position is not saved correctly via API --- .../Magento/ConfigurableProduct/Api/LinkManagementTest.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php index 19f172d69f808..9053a88e84acd 100644 --- a/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/ConfigurableProduct/Api/LinkManagementTest.php @@ -15,6 +15,7 @@ class LinkManagementTest extends WebapiAbstract { const SERVICE_NAME = 'configurableProductLinkManagementV1'; + const OPTION_SERVICE_NAME = 'configurableProductOptionRepositoryV1'; const SERVICE_VERSION = 'V1'; const RESOURCE_PATH = '/V1/configurable-products'; @@ -267,7 +268,7 @@ private function deleteProduct(string $sku): bool * @param string $productSku * @return array */ - protected function getConfigurableAttribute($productSku): array + protected function getConfigurableAttribute(string $productSku): array { $serviceInfo = [ 'rest' => [ @@ -275,9 +276,9 @@ protected function getConfigurableAttribute($productSku): array 'httpMethod' => Request::HTTP_METHOD_GET ], 'soap' => [ - 'service' => self::SERVICE_NAME, + 'service' => self::OPTION_SERVICE_NAME, 'serviceVersion' => self::SERVICE_VERSION, - 'operation' => self::SERVICE_NAME . 'GetList' + 'operation' => self::OPTION_SERVICE_NAME . 'GetList' ] ]; return $this->_webApiCall($serviceInfo, ['sku' => $productSku]); From 3f5b25c6bf5c9903fbc6704dfd3c3ca515c39ac6 Mon Sep 17 00:00:00 2001 From: Joan He <johe@magento.com> Date: Wed, 12 Jun 2019 13:39:27 -0500 Subject: [PATCH 1943/2092] MC-17451: Incorrectly escaped tab header on catalog product page --- .../Catalog/view/frontend/templates/product/view/details.phtml | 2 +- .../Magento/Theme/view/frontend/templates/html/sections.phtml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Catalog/view/frontend/templates/product/view/details.phtml b/app/code/Magento/Catalog/view/frontend/templates/product/view/details.phtml index b5adcd0fcf13d..8887d0074d52f 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/product/view/details.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/product/view/details.phtml @@ -26,7 +26,7 @@ data-toggle="trigger" href="#<?= $block->escapeUrl($alias) ?>" id="tab-label-<?= $block->escapeHtmlAttr($alias) ?>-title"> - <?= $block->escapeHtml($label) ?> + <?= /* @noEscape */ $label ?> </a> </div> <div class="data item content" diff --git a/app/code/Magento/Theme/view/frontend/templates/html/sections.phtml b/app/code/Magento/Theme/view/frontend/templates/html/sections.phtml index 6529b360efc3c..96d0ba6c94715 100644 --- a/app/code/Magento/Theme/view/frontend/templates/html/sections.phtml +++ b/app/code/Magento/Theme/view/frontend/templates/html/sections.phtml @@ -30,7 +30,7 @@ $groupBehavior = $block->getGroupBehaviour() ? $block->getGroupBehaviour() : '{" data-role="collapsible"> <a class="<?= $block->escapeHtmlAttr($groupCss) ?>-item-switch" data-toggle="switch" href="#<?= $block->escapeHtmlAttr($alias) ?>"> - <?= $block->escapeHtml($label) ?> + <?= /* @noEscape */ $label ?> </a> </div> <div class="section-item-content <?= $block->escapeHtmlAttr($groupCss) ?>-item-content" From 891a727806853b47a472668be47ebcab4a34a746 Mon Sep 17 00:00:00 2001 From: Dmytro Poperechnyy <dpoperechnyy@magento.com> Date: Wed, 12 Jun 2019 14:10:51 -0500 Subject: [PATCH 1944/2092] MC-17449: Deliver CSS critical path and font display swap to 2.2.x --- .../Theme/Block/Html/Header/CriticalCss.php | 58 ++++++++++++++ .../Controller/Result/AsyncCssPlugin.php | 79 +++++++++++++++++++ .../Magento/Theme/etc/adminhtml/system.xml | 20 +++++ app/code/Magento/Theme/etc/config.xml | 3 + app/code/Magento/Theme/etc/frontend/di.xml | 8 ++ .../Theme/view/frontend/layout/default.xml | 4 +- .../frontend/layout/default_head_blocks.xml | 8 ++ .../Theme/view/frontend/requirejs-config.js | 3 +- .../templates/html/header/criticalCss.phtml | 15 ++++ .../templates/html/main_css_preloader.phtml | 13 +++ .../templates/js/css_rel_preload.phtml | 10 +++ .../layout/default_head_blocks.xml | 5 ++ .../blank/web/css/source/_loaders.less | 4 + .../blank/web/css/source/_typography.less | 12 ++- .../Magento/luma/web/css/critical.css | 1 + .../Framework/View/Asset/MergeService.php | 17 +++- .../Framework/View/Layout/etc/head.xsd | 1 + .../View/Page/Config/Reader/Head.php | 5 ++ .../Framework/View/Page/Config/Renderer.php | 39 ++++++++- lib/web/css/source/lib/_typography.less | 24 +++++- 20 files changed, 319 insertions(+), 10 deletions(-) create mode 100644 app/code/Magento/Theme/Block/Html/Header/CriticalCss.php create mode 100644 app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php create mode 100644 app/code/Magento/Theme/etc/adminhtml/system.xml create mode 100644 app/code/Magento/Theme/view/frontend/templates/html/header/criticalCss.phtml create mode 100644 app/code/Magento/Theme/view/frontend/templates/html/main_css_preloader.phtml create mode 100644 app/code/Magento/Theme/view/frontend/templates/js/css_rel_preload.phtml create mode 100644 app/design/frontend/Magento/luma/web/css/critical.css diff --git a/app/code/Magento/Theme/Block/Html/Header/CriticalCss.php b/app/code/Magento/Theme/Block/Html/Header/CriticalCss.php new file mode 100644 index 0000000000000..6ac1ba344469c --- /dev/null +++ b/app/code/Magento/Theme/Block/Html/Header/CriticalCss.php @@ -0,0 +1,58 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +declare(strict_types=1); + +namespace Magento\Theme\Block\Html\Header; + +use Magento\Framework\View\Element\Block\ArgumentInterface; +use Magento\Framework\View\Asset\Repository; +use Magento\Framework\View\Asset\File\NotFoundException; + +/** + * This ViewModel will add inline critical css in case dev/css/use_css_critical_path is enabled. + */ +class CriticalCss implements ArgumentInterface +{ + /** + * @var Repository + */ + private $assetRepo; + + /** + * @var string + */ + private $filePath; + + /** + * @param Repository $assetRepo + * @param string $filePath + */ + public function __construct( + Repository $assetRepo, + string $filePath = '' + ) { + $this->assetRepo = $assetRepo; + $this->filePath = $filePath; + } + + /** + * Returns critical css data as string. + * + * @return bool|string + */ + public function getCriticalCssData() + { + try { + $asset = $this->assetRepo->createAsset($this->filePath, ['_secure' => 'false']); + $content = $asset->getContent(); + } catch (NotFoundException $e) { + $content = ''; + } + + return $content; + } +} diff --git a/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php b/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php new file mode 100644 index 0000000000000..3ad9408306892 --- /dev/null +++ b/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php @@ -0,0 +1,79 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Theme\Controller\Result; + +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Framework\App\Response\Http; + +/** + * Plugin for asynchronous CSS loading. + */ +class AsyncCssPlugin +{ + const XML_PATH_USE_CSS_CRITICAL_PATH = 'dev/css/use_css_critical_path'; + + /** + * @var ScopeConfigInterface + */ + private $scopeConfig; + + /** + * @param ScopeConfigInterface $scopeConfig + */ + public function __construct(ScopeConfigInterface $scopeConfig) + { + $this->scopeConfig = $scopeConfig; + } + + /** + * Load CSS asynchronously if it is enabled in configuration. + * + * @param Http $subject + * @return void + */ + public function beforeSendResponse(Http $subject): void + { + $content = $subject->getContent(); + + if (strpos($content, '</body') !== false && $this->scopeConfig->isSetFlag( + self::XML_PATH_USE_CSS_CRITICAL_PATH, + ScopeInterface::SCOPE_STORE + )) { + $cssMatches = []; + // add link rel preload to style sheets + $content = preg_replace_callback( + '@<link\b.*?rel=("|\')stylesheet\1.*?/>@', + function ($matches) use (&$cssMatches) { + $cssMatches[] = $matches[0]; + preg_match('@href=("|\')(.*?)\1@', $matches[0], $hrefAttribute); + $href = $hrefAttribute[2]; + if (preg_match('@media=("|\')(.*?)\1@', $matches[0], $mediaAttribute)) { + $media = $mediaAttribute[2]; + } + $media = $media ?? 'all'; + $loadCssAsync = sprintf( + '<link rel="preload" as="style" media="%s" . + onload="this.onload=null;this.rel=\'stylesheet\'"' . + 'href="%s">', + $media, + $href + ); + + return $loadCssAsync; + }, + $content + ); + + if (!empty($cssMatches)) { + $content = str_replace('</body', implode("\n", $cssMatches) . "\n</body", $content); + $subject->setContent($content); + } + } + } +} diff --git a/app/code/Magento/Theme/etc/adminhtml/system.xml b/app/code/Magento/Theme/etc/adminhtml/system.xml new file mode 100644 index 0000000000000..c581e09fe1e25 --- /dev/null +++ b/app/code/Magento/Theme/etc/adminhtml/system.xml @@ -0,0 +1,20 @@ +<?xml version="1.0"?> +<!-- +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> + <system> + <section id="dev"> + <group id="css"> + <field id="use_css_critical_path" translate="label comment" type="select" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> + <label>Use CSS critical path</label> + <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> + <comment>CSS files are loading synchronously by default.</comment> + </field> + </group> + </section> + </system> +</config> diff --git a/app/code/Magento/Theme/etc/config.xml b/app/code/Magento/Theme/etc/config.xml index b44691c0df963..40064acdf1f43 100644 --- a/app/code/Magento/Theme/etc/config.xml +++ b/app/code/Magento/Theme/etc/config.xml @@ -66,6 +66,9 @@ Disallow: /*SID= <static> <sign>1</sign> </static> + <css> + <use_css_critical_path>0</use_css_critical_path> + </css> </dev> </default> </config> diff --git a/app/code/Magento/Theme/etc/frontend/di.xml b/app/code/Magento/Theme/etc/frontend/di.xml index 7db2783cd8dfa..41b0032e1fffc 100644 --- a/app/code/Magento/Theme/etc/frontend/di.xml +++ b/app/code/Magento/Theme/etc/frontend/di.xml @@ -26,4 +26,12 @@ <type name="Magento\Framework\Controller\ResultInterface"> <plugin name="result-messages" type="Magento\Theme\Controller\Result\MessagePlugin"/> </type> + <type name="Magento\Framework\App\Response\Http"> + <plugin name="asyncCssLoad" type="Magento\Theme\Controller\Result\AsyncCssPlugin"/> + </type> + <type name="Magento\Theme\Block\Html\Header\CriticalCss"> + <arguments> + <argument name="filePath" xsi:type="string">css/critical.css</argument> + </arguments> + </type> </config> diff --git a/app/code/Magento/Theme/view/frontend/layout/default.xml b/app/code/Magento/Theme/view/frontend/layout/default.xml index c84222be19c3c..4da46ec41da54 100644 --- a/app/code/Magento/Theme/view/frontend/layout/default.xml +++ b/app/code/Magento/Theme/view/frontend/layout/default.xml @@ -102,7 +102,9 @@ </container> </referenceContainer> <referenceContainer name="main"> - <container name="content.top" label="Main Content Top"/> + <container name="content.top" label="Main Content Top"> + <block name="main_css_preloader" as="main_css_preloader" template="Magento_Theme::html/main_css_preloader.phtml" ifconfig="dev/css/use_css_critical_path"/> + </container> <container name="content" label="Main Content Area"/> <container name="content.aside" label="Main Content Aside"/> <container name="content.bottom" label="Main Content Bottom"/> diff --git a/app/code/Magento/Theme/view/frontend/layout/default_head_blocks.xml b/app/code/Magento/Theme/view/frontend/layout/default_head_blocks.xml index 38ab9c29402e9..6a1e655786098 100644 --- a/app/code/Magento/Theme/view/frontend/layout/default_head_blocks.xml +++ b/app/code/Magento/Theme/view/frontend/layout/default_head_blocks.xml @@ -12,6 +12,14 @@ <script src="requirejs/require.js"/> </head> <body> + <referenceBlock name="head.additional"> + <block name="critical_css_block" as="critical_css" template="Magento_Theme::html/header/criticalCss.phtml" ifconfig="dev/css/use_css_critical_path"> + <arguments> + <argument name="criticalCssViewModel" xsi:type="object">Magento\Theme\Block\Html\Header\CriticalCss</argument> + </arguments> + </block> + <block name="css_rel_preload_script" ifconfig="dev/css/use_css_critical_path" template="Magento_Theme::js/css_rel_preload.phtml"/> + </referenceBlock> <referenceContainer name="after.body.start"> <block class="Magento\Framework\View\Element\Template" name="head.polyfill" as="polyfill" template="Magento_Theme::js/polyfill.phtml" before="-"/> <block class="Magento\Framework\View\Element\Js\Components" name="head.components" as="components" template="Magento_Theme::js/components.phtml" before="-"/> diff --git a/app/code/Magento/Theme/view/frontend/requirejs-config.js b/app/code/Magento/Theme/view/frontend/requirejs-config.js index ef46f4bfed825..aacec30edf188 100644 --- a/app/code/Magento/Theme/view/frontend/requirejs-config.js +++ b/app/code/Magento/Theme/view/frontend/requirejs-config.js @@ -28,7 +28,8 @@ var config = { 'popupWindow': 'mage/popup-window', 'validation': 'mage/validation/validation', 'welcome': 'Magento_Theme/js/view/welcome', - 'breadcrumbs': 'Magento_Theme/js/view/breadcrumbs' + 'breadcrumbs': 'Magento_Theme/js/view/breadcrumbs', + 'criticalCssLoader': 'Magento_Theme/js/view/critical-css-loader' } }, paths: { diff --git a/app/code/Magento/Theme/view/frontend/templates/html/header/criticalCss.phtml b/app/code/Magento/Theme/view/frontend/templates/html/header/criticalCss.phtml new file mode 100644 index 0000000000000..7d59438fdbf46 --- /dev/null +++ b/app/code/Magento/Theme/view/frontend/templates/html/header/criticalCss.phtml @@ -0,0 +1,15 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/** + * @var \Magento\Theme\Block\Html\Header\CriticalCss $criticalCssViewModel + */ +?> +<?php $criticalCssViewModel = $block->getData('criticalCssViewModel'); ?> + +<style type="text/css" data-type="criticalCss"> + <?= /* @noEscape */ $criticalCssViewModel->getCriticalCssData() ?> +</style> diff --git a/app/code/Magento/Theme/view/frontend/templates/html/main_css_preloader.phtml b/app/code/Magento/Theme/view/frontend/templates/html/main_css_preloader.phtml new file mode 100644 index 0000000000000..2c1c7db75b111 --- /dev/null +++ b/app/code/Magento/Theme/view/frontend/templates/html/main_css_preloader.phtml @@ -0,0 +1,13 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +?> +<div data-role="main-css-loader" class="loading-mask"> + <div class="loader"> + <img src="<?= $block->escapeUrl($block->getViewFileUrl('images/loader-1.gif')); ?>" + alt="<?= $block->escapeHtml(__('Loading...')); ?>" + style="position: absolute;"> + </div> +</div> diff --git a/app/code/Magento/Theme/view/frontend/templates/js/css_rel_preload.phtml b/app/code/Magento/Theme/view/frontend/templates/js/css_rel_preload.phtml new file mode 100644 index 0000000000000..d90d528ffc6f8 --- /dev/null +++ b/app/code/Magento/Theme/view/frontend/templates/js/css_rel_preload.phtml @@ -0,0 +1,10 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +?> +<script> + /*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */ + !function(t){"use strict";t.loadCSS||(t.loadCSS=function(){});var e=loadCSS.relpreload={};if(e.support=function(){var e;try{e=t.document.createElement("link").relList.supports("preload")}catch(t){e=!1}return function(){return e}}(),e.bindMediaToggle=function(t){var e=t.media||"all";function a(){t.media=e}t.addEventListener?t.addEventListener("load",a):t.attachEvent&&t.attachEvent("onload",a),setTimeout(function(){t.rel="stylesheet",t.media="only x"}),setTimeout(a,3e3)},e.poly=function(){if(!e.support())for(var a=t.document.getElementsByTagName("link"),n=0;n<a.length;n++){var o=a[n];"preload"!==o.rel||"style"!==o.getAttribute("as")||o.getAttribute("data-loadcss")||(o.setAttribute("data-loadcss",!0),e.bindMediaToggle(o))}},!e.support()){e.poly();var a=t.setInterval(e.poly,500);t.addEventListener?t.addEventListener("load",function(){e.poly(),t.clearInterval(a)}):t.attachEvent&&t.attachEvent("onload",function(){e.poly(),t.clearInterval(a)})}"undefined"!=typeof exports?exports.loadCSS=loadCSS:t.loadCSS=loadCSS}("undefined"!=typeof global?global:this); +</script> diff --git a/app/design/frontend/Magento/blank/Magento_Theme/layout/default_head_blocks.xml b/app/design/frontend/Magento/blank/Magento_Theme/layout/default_head_blocks.xml index eb1c8befb3a48..3c9f6036d0dbe 100644 --- a/app/design/frontend/Magento/blank/Magento_Theme/layout/default_head_blocks.xml +++ b/app/design/frontend/Magento/blank/Magento_Theme/layout/default_head_blocks.xml @@ -10,6 +10,11 @@ <css src="css/styles-m.css"/> <css src="css/styles-l.css" media="screen and (min-width: 768px)"/> <css src="css/print.css" media="print"/> + <font src="fonts/opensans/light/opensans-300.woff2"/> + <font src="fonts/opensans/regular/opensans-400.woff2"/> + <font src="fonts/opensans/semibold/opensans-600.woff2"/> + <font src="fonts/opensans/bold/opensans-700.woff2"/> + <font src="fonts/Luma-Icons.woff2"/> <meta name="format-detection" content="telephone=no"/> </head> </page> diff --git a/app/design/frontend/Magento/blank/web/css/source/_loaders.less b/app/design/frontend/Magento/blank/web/css/source/_loaders.less index 5fcba9653ef01..ed062c382442a 100644 --- a/app/design/frontend/Magento/blank/web/css/source/_loaders.less +++ b/app/design/frontend/Magento/blank/web/css/source/_loaders.less @@ -42,4 +42,8 @@ ._block-content-loading { position: relative; } + + [data-role='main-css-loader'] { + display: none; + } } diff --git a/app/design/frontend/Magento/blank/web/css/source/_typography.less b/app/design/frontend/Magento/blank/web/css/source/_typography.less index 8ce76fad97902..6807c0f692af8 100644 --- a/app/design/frontend/Magento/blank/web/css/source/_typography.less +++ b/app/design/frontend/Magento/blank/web/css/source/_typography.less @@ -12,28 +12,32 @@ @family-name: @font-family-name__base, @font-path: '@{baseDir}fonts/opensans/light/opensans-300', @font-weight: 300, - @font-style: normal + @font-style: normal, + @font-display: swap ); .lib-font-face( @family-name: @font-family-name__base, @font-path: '@{baseDir}fonts/opensans/regular/opensans-400', @font-weight: 400, - @font-style: normal + @font-style: normal, + @font-display: swap ); .lib-font-face( @family-name: @font-family-name__base, @font-path: '@{baseDir}fonts/opensans/semibold/opensans-600', @font-weight: 600, - @font-style: normal + @font-style: normal, + @font-display: swap ); .lib-font-face( @family-name: @font-family-name__base, @font-path: '@{baseDir}fonts/opensans/bold/opensans-700', @font-weight: 700, - @font-style: normal + @font-style: normal, + @font-display: swap ); } diff --git a/app/design/frontend/Magento/luma/web/css/critical.css b/app/design/frontend/Magento/luma/web/css/critical.css new file mode 100644 index 0000000000000..922a1eefa89e8 --- /dev/null +++ b/app/design/frontend/Magento/luma/web/css/critical.css @@ -0,0 +1 @@ +body{margin:0}.page-main{flex-grow:1}.product-image-wrapper{display:block;height:0;overflow:hidden;position:relative;z-index:1}.product-image-wrapper .product-image-photo{bottom:0;display:block;height:auto;left:0;margin:auto;max-width:100%;position:absolute;right:0;top:0}.product-image-container{display:inline-block}.modal-popup{position:fixed}.page-wrapper{display:flex;flex-direction:column;min-height:100vh}.action.skip:not(:focus),.block.newsletter .label,.minicart-wrapper .action.showcart .counter-label,.minicart-wrapper .action.showcart .text,.page-header .switcher .label,.product-item-actions .actions-secondary>.action span{border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.alink,a{color:#006bb4;text-decoration:none}.page-header .panel.wrapper{background-color:#6e716e;color:#fff}.header.panel>.header.links{list-style:none none;float:right;font-size:0;margin-right:20px}.header.panel>.header.links>li{font-size:14px;margin:0 0 0 15px}.block-search .action.search,.block-search .block-title,.block-search .nested,.block.newsletter .title,.breadcrumbs .item,.nav-toggle,.no-display,.page-footer .switcher .options ul.dropdown,.page-header .switcher .options ul.dropdown{display:none}.block-search .label>span{height:1px;overflow:hidden;position:absolute}.logo{float:left;margin:0 0 10px 40px}.minicart-wrapper{float:right}.page-footer{margin-top:25px}.footer.content{border-top:1px solid #cecece;padding-top:20px}.block.newsletter .actions{display:table-cell;vertical-align:top;width:1%}.block-banners .banner-items,.block-banners-inline .banner-items,.block-event .slider-panel .slider,.footer.content ul,.product-items{margin:0;padding:0;list-style:none none}.copyright{background-color:#6e716e;color:#fff;box-sizing:border-box;display:block;padding:10px;text-align:center}.modal-popup,.modal-slide{visibility:hidden;opacity:0}input[type=email],input[type=number],input[type=password],input[type=search],input[type=text],input[type=url]{background:#fff;background-clip:padding-box;border:1px solid #c2c2c2;border-radius:1px;font-size:14px;height:32px;line-height:1.42857143;padding:0 9px;vertical-align:baseline;width:100%;box-sizing:border-box}.action.primary{background:#1979c3;border:1px solid #1979c3;color:#fff;font-weight:600;padding:7px 15px}.block.newsletter .form.subscribe{display:table}.footer.content .links a{color:#575757}.load.indicator{background-color:rgba(255,255,255,.7);z-index:9999;bottom:0;left:0;position:fixed;right:0;top:0;position:absolute}.load.indicator:before{background:transparent url(../images/loader-2.gif) no-repeat 50% 50%;border-radius:5px;height:160px;width:160px;bottom:0;box-sizing:border-box;content:'';left:0;margin:auto;position:absolute;right:0;top:0}.load.indicator>span{display:none}.loading-mask{bottom:0;left:0;margin:auto;position:fixed;right:0;top:0;z-index:100;background:rgba(255,255,255,.5)}.loading-mask .loader>img{bottom:0;left:0;margin:auto;position:fixed;right:0;top:0;z-index:100}.loading-mask .loader>p{display:none}body>.loading-mask{z-index:9999}._block-content-loading{position:relative}@media (min-width:768px),print{body,html{height:100%}.page-header{border:0;margin-bottom:0}.nav-sections-item-title,.section-item-content .switcher-currency,ul.header.links li.customer-welcome,ul.level0.submenu{display:none}.abs-add-clearfix-desktop:after,.abs-add-clearfix-desktop:before,.account .column.main .block.block-order-details-view:after,.account .column.main .block.block-order-details-view:before,.account .column.main .block:not(.widget) .block-content:after,.account .column.main .block:not(.widget) .block-content:before,.account .page-title-wrapper:after,.account .page-title-wrapper:before,.block-addresses-list .items.addresses:after,.block-addresses-list .items.addresses:before,.block-cart-failed .block-content:after,.block-cart-failed .block-content:before,.block-giftregistry-shared .item-options:after,.block-giftregistry-shared .item-options:before,.block-wishlist-management:after,.block-wishlist-management:before,.cart-container:after,.cart-container:before,.data.table .gift-wrapping .content:after,.data.table .gift-wrapping .content:before,.data.table .gift-wrapping .nested:after,.data.table .gift-wrapping .nested:before,.header.content:after,.header.content:before,.login-container:after,.login-container:before,.magento-rma-guest-returns .column.main .block.block-order-details-view:after,.magento-rma-guest-returns .column.main .block.block-order-details-view:before,.order-links:after,.order-links:before,.order-review-form:after,.order-review-form:before,.page-header .header.panel:after,.page-header .header.panel:before,.paypal-review .block-content:after,.paypal-review .block-content:before,.paypal-review-discount:after,.paypal-review-discount:before,.sales-guest-view .column.main .block.block-order-details-view:after,.sales-guest-view .column.main .block.block-order-details-view:before,[class^=sales-guest-] .column.main .block.block-order-details-view:after,[class^=sales-guest-] .column.main .block.block-order-details-view:before{content:'';display:table}.abs-add-clearfix-desktop:after,.account .column.main .block.block-order-details-view:after,.account .column.main .block:not(.widget) .block-content:after,.account .page-title-wrapper:after,.block-addresses-list .items.addresses:after,.block-cart-failed .block-content:after,.block-giftregistry-shared .item-options:after,.block-wishlist-management:after,.cart-container:after,.data.table .gift-wrapping .content:after,.data.table .gift-wrapping .nested:after,.header.content:after,.login-container:after,.magento-rma-guest-returns .column.main .block.block-order-details-view:after,.order-links:after,.order-review-form:after,.page-header .header.panel:after,.paypal-review .block-content:after,.paypal-review-discount:after,.sales-guest-view .column.main .block.block-order-details-view:after,[class^=sales-guest-] .column.main .block.block-order-details-view:after{clear:both}.block.category.event,.breadcrumbs,.footer.content,.header.content,.navigation,.page-header .header.panel,.page-main,.page-wrapper>.page-bottom,.page-wrapper>.widget,.top-container{box-sizing:border-box;margin-left:auto;margin-right:auto;max-width:1280px;padding-left:20px;padding-right:20px;width:auto}.panel.header{padding:10px 20px}.page-header .switcher{float:right;margin-left:15px;margin-right:-6px}.header.panel>.header.links>li>a{color:#fff}.header.content{padding:30px 20px 0}.logo{margin:-8px auto 25px 0}.minicart-wrapper{margin-left:13px}.compare.wrapper{list-style:none none}.nav-sections{margin-bottom:25px}.nav-sections-item-content>.navigation{display:block}.navigation{background:#f0f0f0;font-weight:700;height:inherit;left:auto;overflow:inherit;padding:0;position:relative;top:0;width:100%;z-index:3}.navigation ul{margin-top:0;margin-bottom:0;padding:0 8px;position:relative}.navigation .level0{margin:0 10px 0 0;display:inline-block}.navigation .level0>.level-top{color:#575757;line-height:47px;padding:0 12px}.page-main{width:100%}.page-footer{background:#f4f4f4;padding-bottom:25px}.footer.content .links{display:inline-block;padding-right:50px;vertical-align:top}.footer.content ul{padding-right:50px}.footer.content .links li{border:none;font-size:14px;margin:0 0 8px;padding:0}.footer.content .block{float:right}.block.newsletter{width:34%}}@media only screen and (max-width:767px){.compare.wrapper,.panel.wrapper,[class*=block-compare]{display:none}.footer.content .links>li{background:#f4f4f4;font-size:1.6rem;border-top:1px solid #cecece;margin:0 -15px;padding:0 15px}.page-header .header.panel,.page-main{padding-left:15px;padding-right:15px}.header.content{padding-top:10px}.nav-sections-items:after,.nav-sections-items:before{content:'';display:table}.nav-sections-items:after{clear:both}.nav-sections{width:100vw;position:fixed;left:-100vw}} diff --git a/lib/internal/Magento/Framework/View/Asset/MergeService.php b/lib/internal/Magento/Framework/View/Asset/MergeService.php index a5820a6d7651b..9cb1026df5c74 100644 --- a/lib/internal/Magento/Framework/View/Asset/MergeService.php +++ b/lib/internal/Magento/Framework/View/Asset/MergeService.php @@ -40,6 +40,21 @@ class MergeService */ protected $state; + /** + * List of supported types that can be processed by merge service + * + * @var array + */ + private $supportedMergeType = [ + 'css', + 'js', + 'eot', + 'svg', + 'ttf', + 'woff', + 'woff2', + ]; + /** * Constructor * @@ -72,7 +87,7 @@ public function getMergedAssets(array $assets, $contentType) { $isCss = $contentType == 'css'; $isJs = $contentType == 'js'; - if (!$isCss && !$isJs) { + if (!\in_array($contentType, $this->supportedMergeType, true)) { throw new \InvalidArgumentException("Merge for content type '{$contentType}' is not supported."); } diff --git a/lib/internal/Magento/Framework/View/Layout/etc/head.xsd b/lib/internal/Magento/Framework/View/Layout/etc/head.xsd index 15762dc2f0ae6..51acc5789a4f8 100644 --- a/lib/internal/Magento/Framework/View/Layout/etc/head.xsd +++ b/lib/internal/Magento/Framework/View/Layout/etc/head.xsd @@ -67,6 +67,7 @@ <xs:element name="script" type="scriptType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="remove" type="srcRemoveType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="attribute" type="headAttributeType" minOccurs="0" maxOccurs="unbounded"/> + <xs:element name="font" type="linkType" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:schema> diff --git a/lib/internal/Magento/Framework/View/Page/Config/Reader/Head.php b/lib/internal/Magento/Framework/View/Page/Config/Reader/Head.php index 510da2b1b1ca9..3b8de974b2a26 100644 --- a/lib/internal/Magento/Framework/View/Page/Config/Reader/Head.php +++ b/lib/internal/Magento/Framework/View/Page/Config/Reader/Head.php @@ -17,6 +17,7 @@ class Head implements Layout\ReaderInterface * Supported types */ const TYPE_HEAD = 'head'; + const HEAD_FONT = 'font'; /**#@-*/ /**#@+ @@ -56,6 +57,9 @@ protected function addContentTypeByNodeName(Layout\Element $node) case self::HEAD_SCRIPT: $node->addAttribute('content_type', 'js'); break; + case self::HEAD_FONT: + $node->addAttribute('content_type', 'font'); + break; } } @@ -85,6 +89,7 @@ function (Layout\Element $current, Layout\Element $next) { case self::HEAD_CSS: case self::HEAD_SCRIPT: case self::HEAD_LINK: + case self::HEAD_FONT: $this->addContentTypeByNodeName($node); $pageConfigStructure->addAssets($node->getAttribute('src'), $this->getAttributes($node)); break; diff --git a/lib/internal/Magento/Framework/View/Page/Config/Renderer.php b/lib/internal/Magento/Framework/View/Page/Config/Renderer.php index 183f8d34ee41f..77808b732219c 100644 --- a/lib/internal/Magento/Framework/View/Page/Config/Renderer.php +++ b/lib/internal/Magento/Framework/View/Page/Config/Renderer.php @@ -20,7 +20,29 @@ class Renderer implements RendererInterface /** * @var array */ - protected $assetTypeOrder = ['css', 'ico', 'js']; + protected $assetTypeOrder = [ + 'css', + 'ico', + 'js', + 'eot', + 'svg', + 'ttf', + 'woff', + 'woff2', + ]; + + /** + * Possible fonts type + * + * @var array + */ + const FONTS_TYPE = [ + 'eot', + 'svg', + 'ttf', + 'woff', + 'woff2', + ]; /** * @var Config @@ -315,10 +337,25 @@ protected function addDefaultAttributes($contentType, $attributes) case 'css': $attributes = ' rel="stylesheet" type="text/css" ' . ($attributes ?: ' media="all"'); break; + + case $this->canTypeBeFont($contentType): + $attributes = 'rel="preload" as="font" crossorigin="anonymous"'; + break; } return $attributes; } + /** + * Check if file type can be font + * + * @param string $type + * @return bool + */ + private function canTypeBeFont(string $type): bool + { + return \in_array($type, self::FONTS_TYPE, true); + } + /** * @param string $contentType * @param string|null $attributes diff --git a/lib/web/css/source/lib/_typography.less b/lib/web/css/source/lib/_typography.less index 62529fe08d1c8..db4eaaf584f4a 100644 --- a/lib/web/css/source/lib/_typography.less +++ b/lib/web/css/source/lib/_typography.less @@ -10,15 +10,35 @@ .lib-font-face( @family-name, @font-path, + @font-format: false, @font-weight: normal, - @font-style: normal -) { + @font-style: normal, + @font-display: auto +) when (@font-format = false) { @font-face { font-family: @family-name; src: url('@{font-path}.woff2') format('woff2'), url('@{font-path}.woff') format('woff'); font-weight: @font-weight; font-style: @font-style; + font-display: @font-display; + } +} + +.lib-font-face( + @family-name, + @font-path, + @font-format: false, + @font-weight: normal, + @font-style: normal, + @font-display: auto +) when not (@font-format = false) { + @font-face { + font-family: @family-name; + src: url('@{font-path}.@{font-format}') format(@font-format); + font-weight: @font-weight; + font-style: @font-style; + font-display: @font-display; } } From 714c5d2e60c4d6b6332207737c095bc3530061b6 Mon Sep 17 00:00:00 2001 From: Soumya Unnikrishnan <sunnikri@adobe.com> Date: Wed, 12 Jun 2019 14:28:12 -0500 Subject: [PATCH 1945/2092] MQE-1573: Bump MFTF version in Magento and deliver all related changes to new version --- composer.json | 2 +- composer.lock | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index 5aee77e9b7f0d..d80a4220fdb71 100644 --- a/composer.json +++ b/composer.json @@ -75,7 +75,7 @@ }, "require-dev": { "allure-framework/allure-phpunit": "~1.2.0", - "magento/magento2-functional-testing-framework": "2.4.0", + "magento/magento2-functional-testing-framework": "2.4.1", "phpunit/phpunit": "~6.2.0", "squizlabs/php_codesniffer": "3.2.2", "phpmd/phpmd": "@stable", diff --git a/composer.lock b/composer.lock index cfb522e93182c..ab53fb9dc460c 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "dd391f1f6e3f43c8dfca7382fdff369c", + "content-hash": "46fe53fa96d6bee5d732fa702c3b7f0b", "packages": [ { "name": "braintree/braintree_php", @@ -6285,16 +6285,16 @@ }, { "name": "magento/magento2-functional-testing-framework", - "version": "2.4.0", + "version": "2.4.1", "source": { "type": "git", "url": "https://github.com/magento/magento2-functional-testing-framework.git", - "reference": "ef534dbcb3aeea68f9254dfd018165c546ad2edb" + "reference": "9b5de03fe069d4a36c911112c30b824ff4e80c3a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/magento/magento2-functional-testing-framework/zipball/ef534dbcb3aeea68f9254dfd018165c546ad2edb", - "reference": "ef534dbcb3aeea68f9254dfd018165c546ad2edb", + "url": "https://api.github.com/repos/magento/magento2-functional-testing-framework/zipball/9b5de03fe069d4a36c911112c30b824ff4e80c3a", + "reference": "9b5de03fe069d4a36c911112c30b824ff4e80c3a", "shasum": "" }, "require": { @@ -6354,10 +6354,10 @@ "magento", "testing" ], - "time": "2019-04-29T20:56:26+00:00" + "time": "2019-06-10T17:57:40+00:00" }, { - "name": "mikey179/vfsStream", + "name": "mikey179/vfsstream", "version": "v1.6.6", "source": { "type": "git", From 4bd076d5d4c4a17f005ebece7160e676fb0b16a7 Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Wed, 12 Jun 2019 15:42:14 -0500 Subject: [PATCH 1946/2092] MC-9220: Scrub secure data from User Creation logs --- .../AdminClickSearchInGridActionGroup.xml | 15 +++++++++ .../AdminFillInputFilterFieldActionGroup.xml | 18 +++++++++++ .../Section/AdminDataGridFilterSection.xml | 14 +++++++++ ...inClickSaveButtonOnUserFormActionGroup.xml | 14 +++++++++ ...llNewUserFormRequiredFieldsActionGroup.xml | 31 +++++++++++++++++++ .../AdminOpenNewUserPageActionGroup.xml | 14 +++++++++ .../AssertAdminUserSaveMessageActionGroup.xml | 18 +++++++++++ .../Mftf/Section/AdminNewUserFormSection.xml | 27 ++++++++++++++++ .../Section/AdminUserFormMessagesSection.xml | 14 +++++++++ 9 files changed, 165 insertions(+) create mode 100644 app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminClickSearchInGridActionGroup.xml create mode 100644 app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminFillInputFilterFieldActionGroup.xml create mode 100644 app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridFilterSection.xml create mode 100644 app/code/Magento/User/Test/Mftf/ActionGroup/AdminClickSaveButtonOnUserFormActionGroup.xml create mode 100644 app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillNewUserFormRequiredFieldsActionGroup.xml create mode 100644 app/code/Magento/User/Test/Mftf/ActionGroup/AdminOpenNewUserPageActionGroup.xml create mode 100644 app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserSaveMessageActionGroup.xml create mode 100644 app/code/Magento/User/Test/Mftf/Section/AdminNewUserFormSection.xml create mode 100644 app/code/Magento/User/Test/Mftf/Section/AdminUserFormMessagesSection.xml diff --git a/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminClickSearchInGridActionGroup.xml b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminClickSearchInGridActionGroup.xml new file mode 100644 index 0000000000000..b7fce8efcb0f6 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminClickSearchInGridActionGroup.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminClickSearchInGridActionGroup"> + <click selector="{{AdminDataGridHeaderSection.applyFilters}}" stepKey="clickSearch"/> + <waitForPageLoad stepKey="waitForSearchResult"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminFillInputFilterFieldActionGroup.xml b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminFillInputFilterFieldActionGroup.xml new file mode 100644 index 0000000000000..cc63e5ac73069 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/ActionGroup/AdminFillInputFilterFieldActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminFillInputFilterFieldActionGroup"> + <arguments> + <argument name="filterInputName" type="string"/> + <argument name="filterValue" type="string"/> + </arguments> + <fillField selector="{{AdminDataGridFilterSection.inputFieldByNameAttrInGrid(filterInputName)}}" userInput="{{filterValue}}" stepKey="fillFilterInputField" /> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridFilterSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridFilterSection.xml new file mode 100644 index 0000000000000..97ec1859e1ef7 --- /dev/null +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridFilterSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminDataGridFilterSection"> + <element name="inputFieldByNameAttrInGrid" type="input" selector="//*[@data-role='filter-form']//input[@name='{{inputNameAttr}}']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminClickSaveButtonOnUserFormActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminClickSaveButtonOnUserFormActionGroup.xml new file mode 100644 index 0000000000000..e1edb16aba6ea --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminClickSaveButtonOnUserFormActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminClickSaveButtonOnUserFormActionGroup"> + <click selector="{{AdminNewUserFormSection.save}}" stepKey="saveNewUser"/> + <waitForPageLoad stepKey="waitForSaveResultLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillNewUserFormRequiredFieldsActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillNewUserFormRequiredFieldsActionGroup.xml new file mode 100644 index 0000000000000..6554c8cc172bd --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminFillNewUserFormRequiredFieldsActionGroup.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminFillNewUserFormRequiredFieldsActionGroup"> + <arguments> + <argument name="user" type="entity"/> + </arguments> + <fillField selector="{{AdminNewUserFormSection.username}}" userInput="{{user.username}}" stepKey="fillUser"/> + <fillField selector="{{AdminNewUserFormSection.firstname}}" userInput="{{user.firstname}}" stepKey="fillFirstName"/> + <fillField selector="{{AdminNewUserFormSection.lastname}}" userInput="{{user.lastname}}" stepKey="fillLastName"/> + <fillField selector="{{AdminNewUserFormSection.email}}" userInput="{{user.email}}" stepKey="fillEmail"/> + <fillField selector="{{AdminNewUserFormSection.password}}" userInput="{{user.password}}" stepKey="fillPassword"/> + <fillField selector="{{AdminNewUserFormSection.passwordConfirmation}}" userInput="{{user.password_confirmation}}" stepKey="fillPasswordConfirmation"/> + <fillField selector="{{AdminNewUserFormSection.currentPassword}}" userInput="{{user.current_password}}" stepKey="fillCurrentUserPassword"/> + <scrollToTopOfPage stepKey="scrollToTopOfPage"/> + <click selector="{{AdminNewUserFormSection.userRoleTab}}" stepKey="openUserRoleTab"/> + <waitForPageLoad stepKey="waitForUserRoleTabOpened" /> + <click selector="{{AdminNewUserFormSection.resetFilter}}" stepKey="resetGridFilter" /> + <waitForPageLoad stepKey="waitForFiltersReset" /> + <fillField userInput="{{user.role}}" selector="{{AdminNewUserFormSection.roleFilterField}}" stepKey="fillRoleFilterField" /> + <click selector="{{AdminNewUserFormSection.search}}" stepKey="clickSearchButton" /> + <waitForPageLoad stepKey="waitForFiltersApplied" /> + <checkOption selector="{{AdminNewUserFormSection.roleRadiobutton(user.role)}}" stepKey="assignRole"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AdminOpenNewUserPageActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminOpenNewUserPageActionGroup.xml new file mode 100644 index 0000000000000..67aef9379faa8 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminOpenNewUserPageActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminOpenNewUserPageActionGroup"> + <amOnPage url="{{AdminNewUserPage.url}}" stepKey="amOnNewAdminUserPage"/> + <waitForPageLoad stepKey="waitForNewAdminUserPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserSaveMessageActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserSaveMessageActionGroup.xml new file mode 100644 index 0000000000000..db4f0a89348a9 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AssertAdminUserSaveMessageActionGroup.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AssertAdminUserSaveMessageActionGroup"> + <arguments> + <argument name="message" type="string" defaultValue="You saved the user." /> + <argument name="messageType" type="string" defaultValue="success" /> + </arguments> + <waitForElementVisible selector="{{AdminUserFormMessagesSection.messageByType(messageType)}}" stepKey="waitForMessage" /> + <see userInput="{{message}}" selector="{{AdminUserFormMessagesSection.messageByType(messageType)}}" stepKey="verifyMessage" /> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/User/Test/Mftf/Section/AdminNewUserFormSection.xml b/app/code/Magento/User/Test/Mftf/Section/AdminNewUserFormSection.xml new file mode 100644 index 0000000000000..c8c510c4019d2 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/Section/AdminNewUserFormSection.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminNewUserFormSection"> + <element name="save" type="button" selector=".page-main-actions #save"/> + <element name="username" type="input" selector="#page_tabs_main_section_content input[name='username']"/> + <element name="firstname" type="input" selector="#page_tabs_main_section_content input[name='firstname']"/> + <element name="lastname" type="input" selector="#page_tabs_main_section_content input[name='lastname']"/> + <element name="email" type="input" selector="#page_tabs_main_section_content input[name='email']"/> + <element name="password" type="input" selector="#page_tabs_main_section_content input[name='password']"/> + <element name="passwordConfirmation" type="input" selector="#page_tabs_main_section_content input[name='password_confirmation']"/> + <element name="interfaceLocale" type="select" selector="#page_tabs_main_section_content select[name='interface_locale']"/> + <element name="currentPassword" type="input" selector="#page_tabs_main_section_content input[name='current_password']"/> + <element name="userRoleTab" type="button" selector="#page_tabs_roles_section"/> + <element name="search" type="button" selector="#page_tabs_roles_section_content #permissionsUserRolesGrid [data-action='grid-filter-apply']" /> + <element name="resetFilter" type="button" selector="#page_tabs_roles_section_content #permissionsUserRolesGrid [data-action='grid-filter-reset']" /> + <element name="roleFilterField" type="input" selector="#page_tabs_roles_section_content #permissionsUserRolesGrid input[name='role_name']" /> + <element name="roleRadiobutton" type="radio" selector="//table[@id='permissionsUserRolesGrid_table']//tr[./td[contains(@class, 'col-role_name') and contains(., '{{roleName}}')]]//input[@name='roles[]']" parameterized="true"/> + </section> +</sections> diff --git a/app/code/Magento/User/Test/Mftf/Section/AdminUserFormMessagesSection.xml b/app/code/Magento/User/Test/Mftf/Section/AdminUserFormMessagesSection.xml new file mode 100644 index 0000000000000..ec4f4d8bf3ad7 --- /dev/null +++ b/app/code/Magento/User/Test/Mftf/Section/AdminUserFormMessagesSection.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> + <section name="AdminUserFormMessagesSection"> + <element name="messageByType" type="block" selector="#messages .message-{{messageType}}" parameterized="true" /> + </section> +</sections> From 052a1a34b4320aaab5dd245355ee3eb7c7771528 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Wed, 12 Jun 2019 15:58:54 -0500 Subject: [PATCH 1947/2092] MC-9220: Scrub secure data from User Creation logs --- .../Magento/User/Test/Mftf/Data/UserData.xml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/app/code/Magento/User/Test/Mftf/Data/UserData.xml b/app/code/Magento/User/Test/Mftf/Data/UserData.xml index baea1b497fc58..96e2f92dfece0 100644 --- a/app/code/Magento/User/Test/Mftf/Data/UserData.xml +++ b/app/code/Magento/User/Test/Mftf/Data/UserData.xml @@ -41,4 +41,21 @@ <item>1</item> </array> </entity> + <entity name="NewAdminUser" type="user"> + <data key="username" unique="suffix">admin</data> + <data key="firstname">John</data> + <data key="lastname">Doe</data> + <data key="email" unique="prefix">admin@example.com</data> + <data key="password">123123q</data> + <data key="password_confirmation">123123q</data> + <data key="interface_local">en_US</data> + <data key="interface_local_label">English (United States)</data> + <data key="is_active">true</data> + <data key="is_active_label">Active</data> + <data key="current_password">{{_ENV.MAGENTO_ADMIN_PASSWORD}}</data> + <data key="role">Administrators</data> + <array key="roles"> + <item>1</item> + </array> + </entity> </entities> From e01567c7f8f76189ad498882d5baf6b369a9fc67 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Wed, 12 Jun 2019 17:00:44 -0500 Subject: [PATCH 1948/2092] MC-10023: Product Categories Indexer in Update on Schedule mode --- .../AdminAssignCategoryToProductAndSaveActionGroup.xml | 2 +- .../AdminUnassignCategoryOnProductAndSaveActionGroup.xml | 2 +- .../Test/Mftf/Section/AdminProductFormActionSection.xml | 1 - .../Catalog/Test/Mftf/Section/AdminProductFormSection.xml | 6 +++--- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignCategoryToProductAndSaveActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignCategoryToProductAndSaveActionGroup.xml index 3ac7aa6d37cba..2594a963767f1 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignCategoryToProductAndSaveActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminAssignCategoryToProductAndSaveActionGroup.xml @@ -19,6 +19,6 @@ <waitForPageLoad stepKey="waitForApplyCategory"/> <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> <waitForPageLoad stepKey="waitForSavingProduct"/> - <see userInput="You saved the product." selector="{{AdminProductFormActionSection.messageSuccessSavedProduct}}" stepKey="seeSuccessMessage"/> + <see userInput="You saved the product." selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSuccessMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminUnassignCategoryOnProductAndSaveActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminUnassignCategoryOnProductAndSaveActionGroup.xml index 503302b7f1e1a..8da2b2226735a 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminUnassignCategoryOnProductAndSaveActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminUnassignCategoryOnProductAndSaveActionGroup.xml @@ -17,6 +17,6 @@ <waitForPageLoad stepKey="waitForDelete"/> <click selector="{{AdminProductFormActionSection.saveButton}}" stepKey="clickSave"/> <waitForPageLoad stepKey="waitForSavingProduct"/> - <see userInput="You saved the product." selector="{{AdminProductFormActionSection.messageSuccessSavedProduct}}" stepKey="seeSuccessMessage"/> + <see userInput="You saved the product." selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSuccessMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormActionSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormActionSection.xml index 95a55c5bf17cd..3eab31e32cc24 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormActionSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormActionSection.xml @@ -15,6 +15,5 @@ <element name="changeStoreButton" type="button" selector="#store-change-button"/> <element name="selectStoreView" type="button" selector="//ul[@data-role='stores-list']/li/a[normalize-space(.)='{{var1}}']" timeout="10" parameterized="true"/> <element name="saveAndNew" type="button" selector="#save_and_new" timeout="30"/> - <element name="messageSuccessSavedProduct" type="button" selector="//div[@data-ui-id='messages-message-success']"/> </section> </sections> diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml index 5da8d8fdef12c..d2e27b8aa78d2 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml @@ -44,9 +44,9 @@ <element name="customAttributeInputField" type="select" selector="input[name='product[{{attributeCode}}]']" parameterized="true"/> <element name="customAttributeSelectOptions" type="select" selector="select[name='product[{{attributeCode}}]'] option" parameterized="true"/> <element name="enableProductLabel" type="checkbox" selector=".admin__actions-switch > input[name='product[status]']+label"/> - <element name="selectCategory" type="input" selector="//*[@data-index='category_ids']//label[contains(., '{{categoryName}}')]" parameterized="true"/> - <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button[@data-action='remove-selected-item']" parameterized="true" timeout="30"/> - <element name="done" type="button" selector="//*[@data-index='category_ids']//button[@data-action='close-advanced-select']" timeout="30"/> + <element name="selectCategory" type="input" selector="//label[contains(., '{{categoryName}}')]" parameterized="true"/> + <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button" parameterized="true" timeout="30"/> + <element name="done" type="button" selector=".admin__action-multiselect-actions-wrap button" timeout="30"/> </section> <section name="ProductInWebsitesSection"> <element name="sectionHeader" type="button" selector="div[data-index='websites']" timeout="30"/> From 0818825615a8be59e78e2575684582f4ff7f70ec Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Wed, 12 Jun 2019 17:42:49 -0500 Subject: [PATCH 1949/2092] MC-10141: Move Product between Categories (Cron is ON, Update by Schedule Mode) --- .../Catalog/Test/Mftf/Section/AdminProductFormSection.xml | 8 ++++---- .../Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml | 6 +++--- .../AdminSwitchIndexerToActionModeActionGroup.xml | 2 +- .../Test/Mftf/Section/AdminIndexManagementSection.xml | 1 - 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml index ee9f39125b037..bbddfee9978dd 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml @@ -44,11 +44,11 @@ <element name="customAttributeInputField" type="select" selector="input[name='product[{{attributeCode}}]']" parameterized="true"/> <element name="customAttributeSelectOptions" type="select" selector="select[name='product[{{attributeCode}}]'] option" parameterized="true"/> <element name="currentCategory" type="text" selector=".admin__action-multiselect-crumb > span"/> - <element name="searchCategory" type="input" selector="//*[@data-index='category_ids']//input[contains(@class, 'multiselect-search')]"/> - <element name="selectCategory" type="input" selector="//*[@data-index='category_ids']//label[contains(., '{{categoryName}}')]" parameterized="true"/> - <element name="done" type="button" selector="//*[@data-index='category_ids']//button[@data-action='close-advanced-select']" timeout="30"/> + <element name="searchCategory" type="input" selector=".action-menu._active input.admin__action-multiselect-search"/> + <element name="selectCategory" type="input" selector="//label[contains(., '{{categoryName}}')]" parameterized="true"/> + <element name="done" type="button" selector=".admin__action-multiselect-actions-wrap button" timeout="30"/> <element name="save" type="button" selector="#save-button"/> - <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button[@data-action='remove-selected-item']" parameterized="true" timeout="30"/> + <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button" parameterized="true" timeout="30"/> </section> <section name="ProductInWebsitesSection"> <element name="sectionHeader" type="button" selector="div[data-index='websites']" timeout="30"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml index 01d658ed5880f..0f0e6c8351d16 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml @@ -87,7 +87,7 @@ <selectOption userInput="Yes" selector="{{AdminCatalogSearchEngineConfigurationSection.selectUseCategoriesPatForProductUrls}}" stepKey="selectYes"/> <click selector="{{AdminConfigSection.saveButton}}" stepKey="saveConfig"/> <waitForPageLoad stepKey="waitForSaving"/> - <see selector="{{AdminIndexManagementSection.successMessage}}" userInput="You saved the configuration." stepKey="seeMessage"/> + <see selector="{{AdminMessagesSection.successMessage}}" userInput="You saved the configuration." stepKey="seeMessage"/> <!-- Navigate to the Catalog > Products --> <amOnPage url="{{AdminCatalogProductPage.url}}" stepKey="onCatalogProductPage"/> @@ -111,7 +111,7 @@ <waitForPageLoad stepKey="waitForSavingProduct"/> <!--Product is saved --> - <see userInput="You saved the product." selector="{{AdminIndexManagementSection.successMessage}}" stepKey="seeSuccessMessage"/> + <see userInput="You saved the product." selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSuccessMessage"/> <!-- Run cron --> <magentoCLI command="cron:run" stepKey="runCron"/> @@ -184,7 +184,7 @@ <waitForPageLoad stepKey="waitForSaveChanges"/> <!-- Product is saved successfully --> - <see userInput="You saved the product." selector="{{AdminIndexManagementSection.successMessage}}" stepKey="seeSaveMessage"/> + <see userInput="You saved the product." selector="{{AdminMessagesSection.successMessage}}" stepKey="seeSaveMessage"/> <!-- Run cron --> <magentoCLI command="cron:run" stepKey="runCron2"/> diff --git a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml index 8137b292e7d71..6622d911eec8f 100644 --- a/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml +++ b/app/code/Magento/Indexer/Test/Mftf/ActionGroup/AdminSwitchIndexerToActionModeActionGroup.xml @@ -17,6 +17,6 @@ <selectOption userInput="{{action}}" selector="{{AdminIndexManagementSection.massActionSelect}}" stepKey="selectAction"/> <click selector="{{AdminIndexManagementSection.massActionSubmit}}" stepKey="clickSubmit"/> <waitForPageLoad stepKey="waitForSubmit"/> - <see selector="{{AdminIndexManagementSection.successMessage}}" userInput="1 indexer(s) are in "{{action}}" mode." stepKey="seeMessage"/> + <see selector="{{AdminMessagesSection.successMessage}}" userInput="1 indexer(s) are in "{{action}}" mode." stepKey="seeMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml b/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml index ff7ea677fbdc6..07d93ff850221 100644 --- a/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml +++ b/app/code/Magento/Indexer/Test/Mftf/Section/AdminIndexManagementSection.xml @@ -12,6 +12,5 @@ <element name="indexerCheckbox" type="checkbox" selector="#gridIndexer_table input[value='{{indexerId}}']" parameterized="true"/> <element name="massActionSelect" type="select" selector="#gridIndexer_massaction-select"/> <element name="massActionSubmit" type="button" selector="#gridIndexer_massaction-form button" timeout="30"/> - <element name="successMessage" type="text" selector="//*[@data-ui-id='messages-message-success']"/> </section> </sections> From 80beb1efb9e66d208b1eac25a8000e3aac8cf6e3 Mon Sep 17 00:00:00 2001 From: Cari Spruiell <spruiell@adobe.com> Date: Wed, 12 Jun 2019 22:09:51 -0500 Subject: [PATCH 1950/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - apply commits from 2.3 --- .../Magento/AdminNotification/Model/Feed.php | 15 +++- .../Catalog/Block/Adminhtml/Product/Edit.php | 44 ++++++++- .../Tab/Newsletter/Grid/Renderer/Action.php | 21 ++++- .../Wishlist/Grid/Renderer/Description.php | 2 +- .../Directory/Model/ResourceModel/Country.php | 23 ++++- .../Template/Grid/Renderer/Action.php | 3 +- .../Template/Grid/Renderer/Sender.php | 2 +- .../Block/Adminhtml/Template/Preview.php | 4 +- .../Magento/Email/Model/Template/Filter.php | 14 ++- .../Template/Grid/Renderer/SenderTest.php | 10 ++- .../Test/Unit/Model/Template/FilterTest.php | 40 ++++----- .../Template/Grid/Renderer/Sender.php | 7 +- .../Block/Adminhtml/Template/Preview.php | 4 +- .../Block/Adminhtml/Queue/PreviewTest.php | 20 +++-- .../Template/Grid/Renderer/SenderTest.php | 12 ++- .../Block/Adminhtml/Template/PreviewTest.php | 16 +++- .../Magento/Reports/Block/Adminhtml/Grid.php | 52 +++++++++-- app/code/Magento/Rule/Block/Editable.php | 2 +- .../Adminhtml/Reorder/Renderer/Action.php | 5 +- app/code/Magento/Sales/Helper/Admin.php | 3 +- .../Magento/SendFriend/Model/SendFriend.php | 2 +- app/code/Magento/Sitemap/Model/Sitemap.php | 68 +++++++------- .../Sitemap/Test/Unit/Model/SitemapTest.php | 8 +- .../Controller/Adminhtml/Rate/AjaxSave.php | 36 +++++++- .../Translation/Model/Inline/Parser.php | 68 +++++++++----- .../Model/ResourceModel/StringUtils.php | 17 +++- .../Unit/Component/Control/ButtonTest.php | 5 +- app/code/Magento/Webapi/Model/Soap/Fault.php | 24 ++++- .../Widget/Setup/LayoutUpdateConverter.php | 14 ++- .../Wishlist/Controller/Index/Send.php | 15 +++- .../CatalogSearch/Controller/ResultTest.php | 4 +- .../Column/Renderer/Button/DeleteTest.php | 8 +- .../Grid/Column/Renderer/Button/EditTest.php | 2 +- .../Tax/Controller/Adminhtml/RateTest.php | 4 +- .../Magento/Framework/Convert/Excel.php | 22 ++++- .../Data/Form/Element/AbstractElement.php | 3 +- .../Framework/Data/Form/Filter/Escapehtml.php | 21 ++++- .../Magento/Framework/Data/Form/FormKey.php | 15 +++- .../Unit/Form/Element/AbstractElementTest.php | 11 ++- .../Data/Test/Unit/Form/Element/LabelTest.php | 16 ++-- .../Test/Unit/Form/Element/MultilineTest.php | 14 ++- .../Test/Unit/Form/Element/ObscureTest.php | 16 ++-- .../Data/Test/Unit/Form/FormKeyTest.php | 5 +- lib/internal/Magento/Framework/Escaper.php | 15 +++- .../Filter/NormalizedToLocalized.php | 13 +++ .../Magento/Framework/Stdlib/Parameters.php | 15 ++++ .../Unit/Data/Form/Element/HiddenTest.php | 10 ++- .../Framework/View/Element/Html/Date.php | 2 +- .../Magento/Framework/View/Page/Config.php | 14 ++- .../View/Test/Unit/Page/ConfigTest.php | 10 ++- .../Setup/Model/DependencyReadinessCheck.php | 14 ++- .../Setup/Model/UninstallDependencyCheck.php | 89 ++++++++++++------- 52 files changed, 665 insertions(+), 214 deletions(-) create mode 100644 lib/internal/Magento/Framework/Filter/NormalizedToLocalized.php create mode 100644 lib/internal/Magento/Framework/Stdlib/Parameters.php diff --git a/app/code/Magento/AdminNotification/Model/Feed.php b/app/code/Magento/AdminNotification/Model/Feed.php index 1766425fb19b1..5a4f7d5ddd390 100644 --- a/app/code/Magento/AdminNotification/Model/Feed.php +++ b/app/code/Magento/AdminNotification/Model/Feed.php @@ -25,6 +25,11 @@ class Feed extends \Magento\Framework\Model\AbstractModel const XML_LAST_UPDATE_PATH = 'system/adminnotification/last_update'; + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * Feed url * @@ -77,6 +82,7 @@ class Feed extends \Magento\Framework\Model\AbstractModel * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection * @param array $data + * @param \Magento\Framework\Escaper|null $escaper * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -90,7 +96,8 @@ public function __construct( \Magento\Framework\UrlInterface $urlBuilder, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + array $data = [], + \Magento\Framework\Escaper $escaper = null ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_backendConfig = $backendConfig; @@ -99,12 +106,16 @@ public function __construct( $this->_deploymentConfig = $deploymentConfig; $this->productMetadata = $productMetadata; $this->urlBuilder = $urlBuilder; + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); } /** * Init model * * @return void + * phpcs:disable Magento2.CodeAnalysis.EmptyBlock */ protected function _construct() { @@ -255,6 +266,6 @@ public function getFeedXml() */ private function escapeString(\SimpleXMLElement $data) { - return htmlspecialchars((string)$data); + return $this->escaper->escapeHtml((string)$data); } } diff --git a/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit.php b/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit.php index 285caa974fd17..bef8ff9cf9112 100644 --- a/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit.php +++ b/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit.php @@ -12,8 +12,16 @@ */ namespace Magento\Catalog\Block\Adminhtml\Product; +/** + * Class Edit + */ class Edit extends \Magento\Backend\Block\Widget { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * @var string */ @@ -47,6 +55,7 @@ class Edit extends \Magento\Backend\Block\Widget * @param \Magento\Eav\Model\Entity\Attribute\SetFactory $attributeSetFactory * @param \Magento\Framework\Registry $registry * @param \Magento\Catalog\Helper\Product $productHelper + * @param \Magento\Framework\Escaper $escaper * @param array $data */ public function __construct( @@ -55,16 +64,20 @@ public function __construct( \Magento\Eav\Model\Entity\Attribute\SetFactory $attributeSetFactory, \Magento\Framework\Registry $registry, \Magento\Catalog\Helper\Product $productHelper, + \Magento\Framework\Escaper $escaper, array $data = [] ) { $this->_productHelper = $productHelper; $this->_attributeSetFactory = $attributeSetFactory; $this->_coreRegistry = $registry; $this->jsonEncoder = $jsonEncoder; + $this->escaper = $escaper; parent::__construct($context, $data); } /** + * Edit Product constructor + * * @return void */ protected function _construct() @@ -144,6 +157,8 @@ protected function _prepareLayout() } /** + * Retrieve back button html + * * @return string */ public function getBackButtonHtml() @@ -152,6 +167,8 @@ public function getBackButtonHtml() } /** + * Retrieve cancel button html + * * @return string */ public function getCancelButtonHtml() @@ -160,6 +177,8 @@ public function getCancelButtonHtml() } /** + * Retrieve save button html + * * @return string */ public function getSaveButtonHtml() @@ -168,6 +187,8 @@ public function getSaveButtonHtml() } /** + * Retrieve save and edit button html + * * @return string */ public function getSaveAndEditButtonHtml() @@ -176,6 +197,8 @@ public function getSaveAndEditButtonHtml() } /** + * Retrieve delete button html + * * @return string */ public function getDeleteButtonHtml() @@ -194,6 +217,8 @@ public function getSaveSplitButtonHtml() } /** + * Retrieve validation url + * * @return string */ public function getValidationUrl() @@ -202,6 +227,8 @@ public function getValidationUrl() } /** + * Retrieve save url + * * @return string */ public function getSaveUrl() @@ -210,6 +237,8 @@ public function getSaveUrl() } /** + * Retrieve save and continue url + * * @return string */ public function getSaveAndContinueUrl() @@ -221,6 +250,8 @@ public function getSaveAndContinueUrl() } /** + * Retrieve product id + * * @return mixed */ public function getProductId() @@ -229,6 +260,8 @@ public function getProductId() } /** + * Retrieve product set id + * * @return mixed */ public function getProductSetId() @@ -241,6 +274,8 @@ public function getProductSetId() } /** + * Retrieve duplicate url + * * @return string */ public function getDuplicateUrl() @@ -249,6 +284,8 @@ public function getDuplicateUrl() } /** + * Retrieve product header + * * @deprecated 101.1.0 * @return string */ @@ -263,6 +300,8 @@ public function getHeader() } /** + * Get product attribute set name + * * @return string */ public function getAttributeSetName() @@ -275,11 +314,14 @@ public function getAttributeSetName() } /** + * Retrieve id of selected tab + * * @return string */ public function getSelectedTabId() { - return addslashes(htmlspecialchars($this->getRequest()->getParam('tab'))); + // phpcs:ignore Magento2.Functions.DiscouragedFunction + return addslashes($this->escaper->escapeHtml($this->getRequest()->getParam('tab'))); } /** diff --git a/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Newsletter/Grid/Renderer/Action.php b/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Newsletter/Grid/Renderer/Action.php index 43d9af36a5652..500646c8e05a7 100644 --- a/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Newsletter/Grid/Renderer/Action.php +++ b/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Newsletter/Grid/Renderer/Action.php @@ -10,6 +10,11 @@ */ class Action extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * Core registry * @@ -21,17 +26,24 @@ class Action extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\Abstract * @param \Magento\Backend\Block\Context $context * @param \Magento\Framework\Registry $registry * @param array $data + * @param \Magento\Framework\Escaper|null $escaper */ public function __construct( \Magento\Backend\Block\Context $context, \Magento\Framework\Registry $registry, - array $data = [] + array $data = [], + \Magento\Framework\Escaper $escaper = null ) { $this->_coreRegistry = $registry; + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); parent::__construct($context, $data); } /** + * Render actions + * * @param \Magento\Framework\DataObject $row * @return string */ @@ -57,15 +69,20 @@ public function render(\Magento\Framework\DataObject $row) } /** + * Retrieve escaped value + * * @param string $value * @return string */ protected function _getEscapedValue($value) { - return addcslashes(htmlspecialchars($value), '\\\''); + // phpcs:ignore Magento2.Functions.DiscouragedFunction + return addcslashes($this->escaper->escapeHtml($value), '\\\''); } /** + * Actions to html + * * @param array $actions * @return string */ diff --git a/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Wishlist/Grid/Renderer/Description.php b/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Wishlist/Grid/Renderer/Description.php index d0b47886dca7e..aef91184fc782 100644 --- a/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Wishlist/Grid/Renderer/Description.php +++ b/app/code/Magento/Customer/Block/Adminhtml/Edit/Tab/Wishlist/Grid/Renderer/Description.php @@ -18,6 +18,6 @@ class Description extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\Abs */ public function render(\Magento\Framework\DataObject $row) { - return nl2br(htmlspecialchars($row->getData($this->getColumn()->getIndex()))); + return nl2br($this->escapeHtml($row->getData($this->getColumn()->getIndex()))); } } diff --git a/app/code/Magento/Directory/Model/ResourceModel/Country.php b/app/code/Magento/Directory/Model/ResourceModel/Country.php index 59fb2de85c8a3..00f0c1cefb75a 100644 --- a/app/code/Magento/Directory/Model/ResourceModel/Country.php +++ b/app/code/Magento/Directory/Model/ResourceModel/Country.php @@ -13,6 +13,27 @@ */ class Country extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + + /** + * @param \Magento\Framework\Model\ResourceModel\Db\Context $context + * @param null|string $connectionName + * @param \Magento\Framework\Escaper|null $escaper + */ + public function __construct( + \Magento\Framework\Model\ResourceModel\Db\Context $context, + string $connectionName = null, + \Magento\Framework\Escaper $escaper = null + ) { + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); + parent::__construct($context, $connectionName); + } + /** * Resource initialization * @@ -44,7 +65,7 @@ public function loadByCode(\Magento\Directory\Model\Country $country, $code) default: throw new \Magento\Framework\Exception\LocalizedException( - __('Please correct the country code: %1.', htmlspecialchars($code)) + __('Please correct the country code: %1.', $this->escaper->escapeHtml($code)) ); } diff --git a/app/code/Magento/Email/Block/Adminhtml/Template/Grid/Renderer/Action.php b/app/code/Magento/Email/Block/Adminhtml/Template/Grid/Renderer/Action.php index a2ba63d78d144..65f9e41b074a3 100644 --- a/app/code/Magento/Email/Block/Adminhtml/Template/Grid/Renderer/Action.php +++ b/app/code/Magento/Email/Block/Adminhtml/Template/Grid/Renderer/Action.php @@ -41,7 +41,8 @@ public function render(\Magento\Framework\DataObject $row) */ protected function _getEscapedValue($value) { - return addcslashes(htmlspecialchars($value), '\\\''); + // phpcs:ignore Magento2.Functions.DiscouragedFunction + return addcslashes($this->escapeHtml($value), '\\\''); } /** diff --git a/app/code/Magento/Email/Block/Adminhtml/Template/Grid/Renderer/Sender.php b/app/code/Magento/Email/Block/Adminhtml/Template/Grid/Renderer/Sender.php index 24c39884661ca..005d211a8962e 100644 --- a/app/code/Magento/Email/Block/Adminhtml/Template/Grid/Renderer/Sender.php +++ b/app/code/Magento/Email/Block/Adminhtml/Template/Grid/Renderer/Sender.php @@ -23,7 +23,7 @@ public function render(\Magento\Framework\DataObject $row) $str = ''; if ($row->getTemplateSenderName()) { - $str .= htmlspecialchars($row->getTemplateSenderName()) . ' '; + $str .= $this->escapeHtml($row->getTemplateSenderName()) . ' '; } if ($row->getTemplateSenderEmail()) { diff --git a/app/code/Magento/Email/Block/Adminhtml/Template/Preview.php b/app/code/Magento/Email/Block/Adminhtml/Template/Preview.php index 5f22a36510c4e..1ea6e3f921bc6 100644 --- a/app/code/Magento/Email/Block/Adminhtml/Template/Preview.php +++ b/app/code/Magento/Email/Block/Adminhtml/Template/Preview.php @@ -12,6 +12,8 @@ namespace Magento\Email\Block\Adminhtml\Template; /** + * Template Preview Block + * * @api * @since 100.0.2 */ @@ -80,7 +82,7 @@ protected function _toHtml() $template->revertDesign(); if ($template->isPlain()) { - $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>"; + $templateProcessed = "<pre>" . $this->escapeHtml($templateProcessed) . "</pre>"; } \Magento\Framework\Profiler::stop($this->profilerName); diff --git a/app/code/Magento/Email/Model/Template/Filter.php b/app/code/Magento/Email/Model/Template/Filter.php index 7ac9b944d03ed..27aa5adaee8eb 100644 --- a/app/code/Magento/Email/Model/Template/Filter.php +++ b/app/code/Magento/Email/Model/Template/Filter.php @@ -321,6 +321,8 @@ public function setDesignParams(array $designParams) } /** + * Retrieve CSS processor + * * @deprecated 100.1.2 * @return Css\Processor */ @@ -333,6 +335,8 @@ private function getCssProcessor() } /** + * Retrieve pub directory + * * @deprecated 100.1.2 * @param string $dirType * @return ReadInterface @@ -523,6 +527,7 @@ public function mediaDirective($construction) /** * Retrieve store URL directive + * * Support url and direct_url properties * * @param string[] $construction @@ -607,7 +612,7 @@ protected function getTransParameters($value) if (preg_match(self::TRANS_DIRECTIVE_REGEX, $value, $matches) !== 1) { return ['', []]; // malformed directive body; return without breaking list } - + // phpcs:disable Magento2.Functions.DiscouragedFunction $text = stripslashes($matches[2]); $params = []; @@ -683,7 +688,7 @@ protected function applyModifiers($value, $modifiers) $callback = $modifier; } array_unshift($params, $value); - $value = call_user_func_array($callback, $params); + $value = $callback(...$params); } } return $value; @@ -700,7 +705,7 @@ public function modifierEscape($value, $type = 'html') { switch ($type) { case 'html': - return htmlspecialchars($value, ENT_QUOTES); + return $this->_escaper->escapeHtml($value); case 'htmlentities': return htmlentities($value, ENT_QUOTES); @@ -950,6 +955,7 @@ public function getCssFilesContent(array $files) } } catch (ContentProcessorException $exception) { $css = $exception->getMessage(); + // phpcs:disable Magento2.Exceptions.ThrowCatch } catch (\Magento\Framework\View\Asset\File\NotFoundException $exception) { $css = ''; } @@ -958,6 +964,8 @@ public function getCssFilesContent(array $files) } /** + * Apply Inline CSS + * * Merge HTML and CSS and return HTML that has CSS styles applied "inline" to the HTML tags. This is necessary * in order to support all email clients. * diff --git a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php index b9a555c3207fc..1a493e23adb53 100644 --- a/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php +++ b/app/code/Magento/Email/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php @@ -18,7 +18,15 @@ class SenderTest extends \PHPUnit\Framework\TestCase protected function setUp() { $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->sender = $objectManager->getObject(\Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Sender::class); + $escaper = $objectManager->getObject( + \Magento\Framework\Escaper::class + ); + $this->sender = $objectManager->getObject( + \Magento\Email\Block\Adminhtml\Template\Grid\Renderer\Sender::class, + [ + 'escaper' => $escaper + ] + ); } /** diff --git a/app/code/Magento/Email/Test/Unit/Model/Template/FilterTest.php b/app/code/Magento/Email/Test/Unit/Model/Template/FilterTest.php index 2eb8f582c54fa..b3f144f507cae 100644 --- a/app/code/Magento/Email/Test/Unit/Model/Template/FilterTest.php +++ b/app/code/Magento/Email/Test/Unit/Model/Template/FilterTest.php @@ -104,9 +104,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) - ->disableOriginalConstructor() - ->getMock(); + $this->escaper = $this->objectManager->getObject(\Magento\Framework\Escaper::class); $this->assetRepo = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class) ->disableOriginalConstructor() @@ -158,23 +156,25 @@ protected function setUp() protected function getModel($mockedMethods = null) { return $this->getMockBuilder(\Magento\Email\Model\Template\Filter::class) - ->setConstructorArgs([ - $this->string, - $this->logger, - $this->escaper, - $this->assetRepo, - $this->scopeConfig, - $this->coreVariableFactory, - $this->storeManager, - $this->layout, - $this->layoutFactory, - $this->appState, - $this->backendUrlBuilder, - $this->emogrifier, - $this->configVariables, - [], - $this->cssInliner, - ]) + ->setConstructorArgs( + [ + $this->string, + $this->logger, + $this->escaper, + $this->assetRepo, + $this->scopeConfig, + $this->coreVariableFactory, + $this->storeManager, + $this->layout, + $this->layoutFactory, + $this->appState, + $this->backendUrlBuilder, + $this->emogrifier, + $this->configVariables, + [], + $this->cssInliner, + ] + ) ->setMethods($mockedMethods) ->getMock(); } diff --git a/app/code/Magento/Newsletter/Block/Adminhtml/Template/Grid/Renderer/Sender.php b/app/code/Magento/Newsletter/Block/Adminhtml/Template/Grid/Renderer/Sender.php index 9905ce25e1664..c9e9e969c7c82 100644 --- a/app/code/Magento/Newsletter/Block/Adminhtml/Template/Grid/Renderer/Sender.php +++ b/app/code/Magento/Newsletter/Block/Adminhtml/Template/Grid/Renderer/Sender.php @@ -11,6 +11,9 @@ */ namespace Magento\Newsletter\Block\Adminhtml\Template\Grid\Renderer; +/** + * Class Sender + */ class Sender extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer { /** @@ -23,10 +26,10 @@ public function render(\Magento\Framework\DataObject $row) { $str = ''; if ($row->getTemplateSenderName()) { - $str .= htmlspecialchars($row->getTemplateSenderName()) . ' '; + $str .= $this->escapeHtml($row->getTemplateSenderName()) . ' '; } if ($row->getTemplateSenderEmail()) { - $str .= '[' . htmlspecialchars($row->getTemplateSenderEmail()) . ']'; + $str .= '[' . $this->escapeHtml($row->getTemplateSenderEmail()) . ']'; } if ($str == '') { $str .= '---'; diff --git a/app/code/Magento/Newsletter/Block/Adminhtml/Template/Preview.php b/app/code/Magento/Newsletter/Block/Adminhtml/Template/Preview.php index f9474da452cac..58a904248e978 100644 --- a/app/code/Magento/Newsletter/Block/Adminhtml/Template/Preview.php +++ b/app/code/Magento/Newsletter/Block/Adminhtml/Template/Preview.php @@ -84,7 +84,7 @@ protected function _toHtml() $template->revertDesign(); if ($template->isPlain()) { - $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>"; + $templateProcessed = "<pre>" . $this->escapeHtml($templateProcessed) . "</pre>"; } \Magento\Framework\Profiler::stop($this->profilerName); @@ -142,6 +142,8 @@ protected function getStoreId() } /** + * Return template + * * @param \Magento\Newsletter\Model\Template $template * @param string $id * @return $this diff --git a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php index 219f9127d4ad8..b64453594df41 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php @@ -81,13 +81,17 @@ protected function setUp() $queueFactory->expects($this->any())->method('create')->will($this->returnValue($this->queue)); $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $escaper = $this->objectManager->getObject(\Magento\Framework\Escaper::class); + $context->expects($this->once())->method('getEscaper')->willReturn($escaper); + $this->preview = $this->objectManager->getObject( \Magento\Newsletter\Block\Adminhtml\Queue\Preview::class, [ 'context' => $context, 'templateFactory' => $templateFactory, 'subscriberFactory' => $subscriberFactory, - 'queueFactory' => $queueFactory, + 'queueFactory' => $queueFactory ] ); } @@ -103,12 +107,14 @@ public function testToHtmlEmpty() public function testToHtmlWithId() { - $this->request->expects($this->any())->method('getParam')->will($this->returnValueMap( - [ - ['id', null, 1], - ['store_id', null, 0] - ] - )); + $this->request->expects($this->any())->method('getParam')->will( + $this->returnValueMap( + [ + ['id', null, 1], + ['store_id', null, 0] + ] + ) + ); $this->queue->expects($this->once())->method('load')->will($this->returnSelf()); $this->template->expects($this->any())->method('isPlain')->will($this->returnValue(true)); /** @var \Magento\Store\Model\Store $store */ diff --git a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php index baa80759314cb..4de2d5d17c550 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/Grid/Renderer/SenderTest.php @@ -26,8 +26,14 @@ class SenderTest extends \PHPUnit\Framework\TestCase protected function setUp() { $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $escaper = $this->objectManagerHelper->getObject( + \Magento\Framework\Escaper::class + ); $this->sender = $this->objectManagerHelper->getObject( - \Magento\Newsletter\Block\Adminhtml\Template\Grid\Renderer\Sender::class + \Magento\Newsletter\Block\Adminhtml\Template\Grid\Renderer\Sender::class, + [ + 'escaper' => $escaper + ] ); } @@ -73,8 +79,8 @@ public function rendererDataProvider() 'sender_email' => "<br>'email@example.com'</br>", ], [ - 'sender' => "<br>'Sender'</br>", - 'sender_email' => "<br>'email@example.com'</br>", + 'sender' => "<br>'Sender'</br>", + 'sender_email' => "<br>'email@example.com'</br>", ], ], [ diff --git a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php index 70407b50cacc0..87fbca55e154e 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php @@ -8,6 +8,9 @@ use Magento\Framework\App\TemplateTypesInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +/** + * Test for \Magento\Newsletter\Block\Adminhtml\Template\Preview + */ class PreviewTest extends \PHPUnit\Framework\TestCase { /** @var \Magento\Newsletter\Block\Adminhtml\Template\Preview */ @@ -36,7 +39,9 @@ protected function setUp() $this->request = $this->createMock(\Magento\Framework\App\RequestInterface::class); $this->appState = $this->createMock(\Magento\Framework\App\State::class); $this->storeManager = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); - $this->template = $this->createPartialMock(\Magento\Newsletter\Model\Template::class, [ + $this->template = $this->createPartialMock( + \Magento\Newsletter\Model\Template::class, + [ 'setTemplateType', 'setTemplateText', 'setTemplateStyles', @@ -45,7 +50,8 @@ protected function setUp() 'revertDesign', 'getProcessedTemplate', 'load' - ]); + ] + ); $templateFactory = $this->createPartialMock(\Magento\Newsletter\Model\TemplateFactory::class, ['create']); $templateFactory->expects($this->once())->method('create')->willReturn($this->template); $this->subscriberFactory = $this->createPartialMock( @@ -54,6 +60,9 @@ protected function setUp() ); $this->objectManagerHelper = new ObjectManagerHelper($this); + $escaper = $this->objectManagerHelper->getObject( + \Magento\Framework\Escaper::class + ); $this->preview = $this->objectManagerHelper->getObject( \Magento\Newsletter\Block\Adminhtml\Template\Preview::class, [ @@ -61,7 +70,8 @@ protected function setUp() 'storeManager' => $this->storeManager, 'request' => $this->request, 'templateFactory' => $templateFactory, - 'subscriberFactory' => $this->subscriberFactory + 'subscriberFactory' => $this->subscriberFactory, + 'escaper' => $escaper ] ); } diff --git a/app/code/Magento/Reports/Block/Adminhtml/Grid.php b/app/code/Magento/Reports/Block/Adminhtml/Grid.php index a895ef2d75906..674f2c081d0d5 100644 --- a/app/code/Magento/Reports/Block/Adminhtml/Grid.php +++ b/app/code/Magento/Reports/Block/Adminhtml/Grid.php @@ -6,6 +6,12 @@ namespace Magento\Reports\Block\Adminhtml; +use Magento\Backend\Block\Template\Context; +use Magento\Backend\Helper\Data; +use Magento\Framework\Url\DecoderInterface; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Stdlib\Parameters; + /** * Backend report grid block * @@ -15,6 +21,16 @@ */ class Grid extends \Magento\Backend\Block\Widget\Grid { + /** + * @var DecoderInterface + */ + private $urlDecoder; + + /** + * @var Parameters + */ + private $parameters; + /** * Should Store Switcher block be visible * @@ -71,6 +87,29 @@ class Grid extends \Magento\Backend\Block\Widget\Grid */ protected $_filterValues; + /** + * @param Context $context + * @param Data $backendHelper + * @param array $data + * @param DecoderInterface|null $urlDecoder + * @param Parameters $parameters + */ + public function __construct( + Context $context, + Data $backendHelper, + array $data = [], + DecoderInterface $urlDecoder = null, + Parameters $parameters = null + ) { + $this->urlDecoder = $urlDecoder ?? ObjectManager::getInstance()->get( + DecoderInterface::class + ); + + $this->parameters = $parameters ?? new Parameters(); + + parent::__construct($context, $backendHelper, $data); + } + /** * Apply sorting and filtering to collection * @@ -86,9 +125,12 @@ protected function _prepareCollection() } if (is_string($filter)) { - $data = []; - $filter = base64_decode($filter); - parse_str(urldecode($filter), $data); + // this is a replacement for base64_decode() + $filter = $this->urlDecoder->decode($filter); + + // this is a replacement for parse_str() + $this->parameters->fromString(urldecode($filter)); + $data = $this->parameters->toArray(); if (!isset($data['report_from'])) { // getting all reports from 2001 year @@ -113,7 +155,7 @@ protected function _prepareCollection() $this->_setFilterValues($data); } elseif ($filter && is_array($filter)) { $this->_setFilterValues($filter); - } elseif (0 !== sizeof($this->_defaultFilter)) { + } elseif (0 !== count($this->_defaultFilter)) { $this->_setFilterValues($this->_defaultFilter); } @@ -328,7 +370,7 @@ public function getFilter($name) if (isset($this->_filters[$name])) { return $this->_filters[$name]; } else { - return $this->getRequest()->getParam($name) ? htmlspecialchars($this->getRequest()->getParam($name)) : ''; + return $this->getRequest()->getParam($name) ? $this->escapeHtml($this->getRequest()->getParam($name)) : ''; } } diff --git a/app/code/Magento/Rule/Block/Editable.php b/app/code/Magento/Rule/Block/Editable.php index 32bcc015e2121..a2b9d869f364e 100644 --- a/app/code/Magento/Rule/Block/Editable.php +++ b/app/code/Magento/Rule/Block/Editable.php @@ -62,7 +62,7 @@ public function render(\Magento\Framework\Data\Form\Element\AbstractElement $ele '" data-form-part="' . $element->getData('data-form-part') . '"/> ' . - htmlspecialchars( + $this->escapeHtml( $valueName ) . ' '; } else { diff --git a/app/code/Magento/Sales/Block/Adminhtml/Reorder/Renderer/Action.php b/app/code/Magento/Sales/Block/Adminhtml/Reorder/Renderer/Action.php index e6e5d6ec3df3f..566ea1214d91f 100644 --- a/app/code/Magento/Sales/Block/Adminhtml/Reorder/Renderer/Action.php +++ b/app/code/Magento/Sales/Block/Adminhtml/Reorder/Renderer/Action.php @@ -41,6 +41,8 @@ public function __construct( } /** + * Render actions + * * @param \Magento\Framework\DataObject $row * @return string */ @@ -71,7 +73,8 @@ public function render(\Magento\Framework\DataObject $row) */ protected function _getEscapedValue($value) { - return addcslashes(htmlspecialchars($value), '\\\''); + // phpcs:ignore Magento2.Functions.DiscouragedFunction + return addcslashes($this->escapeHtml($value), '\\\''); } /** diff --git a/app/code/Magento/Sales/Helper/Admin.php b/app/code/Magento/Sales/Helper/Admin.php index 3cdc8f4bca210..818acb2e5953f 100644 --- a/app/code/Magento/Sales/Helper/Admin.php +++ b/app/code/Magento/Sales/Helper/Admin.php @@ -164,7 +164,7 @@ public function escapeHtmlWithLinks($data, $allowedTags = null) //Recreate a minimalistic secure a tag $links[] = sprintf( '<a href="%s">%s</a>', - htmlspecialchars($url, ENT_QUOTES, 'UTF-8', false), + $this->escaper->escapeHtml($url), $this->escaper->escapeHtml($text) ); $data = str_replace($matches[0], '%' . $i . '$s', $data); @@ -187,6 +187,7 @@ private function filterUrl(string $url): string if ($url) { //Revert the sprintf escaping $url = str_replace('%%', '%', $url); + // phpcs:ignore Magento2.Functions.DiscouragedFunction $urlScheme = parse_url($url, PHP_URL_SCHEME); $urlScheme = $urlScheme ? strtolower($urlScheme) : ''; if ($urlScheme !== 'http' && $urlScheme !== 'https') { diff --git a/app/code/Magento/SendFriend/Model/SendFriend.php b/app/code/Magento/SendFriend/Model/SendFriend.php index 38525a9f83a12..2502db9891241 100644 --- a/app/code/Magento/SendFriend/Model/SendFriend.php +++ b/app/code/Magento/SendFriend/Model/SendFriend.php @@ -178,7 +178,7 @@ public function send() $this->inlineTranslation->suspend(); - $message = nl2br(htmlspecialchars($this->getSender()->getMessage())); + $message = nl2br($this->_escaper->escapeHtml($this->getSender()->getMessage())); $sender = [ 'name' => $this->_escaper->escapeHtml($this->getSender()->getName()), 'email' => $this->_escaper->escapeHtml($this->getSender()->getEmail()), diff --git a/app/code/Magento/Sitemap/Model/Sitemap.php b/app/code/Magento/Sitemap/Model/Sitemap.php index 7279f6eda85d7..de2ba3963c61f 100644 --- a/app/code/Magento/Sitemap/Model/Sitemap.php +++ b/app/code/Magento/Sitemap/Model/Sitemap.php @@ -275,29 +275,35 @@ public function collectSitemapItems() $storeId = $this->getStoreId(); $this->_storeManager->setCurrentStore($storeId); - $this->addSitemapItem(new DataObject( - [ - 'changefreq' => $helper->getCategoryChangefreq($storeId), - 'priority' => $helper->getCategoryPriority($storeId), - 'collection' => $this->_categoryFactory->create()->getCollection($storeId), - ] - )); - - $this->addSitemapItem(new DataObject( - [ - 'changefreq' => $helper->getProductChangefreq($storeId), - 'priority' => $helper->getProductPriority($storeId), - 'collection' => $this->_productFactory->create()->getCollection($storeId), - ] - )); - - $this->addSitemapItem(new DataObject( - [ - 'changefreq' => $helper->getPageChangefreq($storeId), - 'priority' => $helper->getPagePriority($storeId), - 'collection' => $this->_cmsFactory->create()->getCollection($storeId), - ] - )); + $this->addSitemapItem( + new DataObject( + [ + 'changefreq' => $helper->getCategoryChangefreq($storeId), + 'priority' => $helper->getCategoryPriority($storeId), + 'collection' => $this->_categoryFactory->create()->getCollection($storeId), + ] + ) + ); + + $this->addSitemapItem( + new DataObject( + [ + 'changefreq' => $helper->getProductChangefreq($storeId), + 'priority' => $helper->getProductPriority($storeId), + 'collection' => $this->_productFactory->create()->getCollection($storeId), + ] + ) + ); + + $this->addSitemapItem( + new DataObject( + [ + 'changefreq' => $helper->getPageChangefreq($storeId), + 'priority' => $helper->getPagePriority($storeId), + 'collection' => $this->_cmsFactory->create()->getCollection($storeId), + ] + ) + ); } /** @@ -505,7 +511,7 @@ protected function _isSplitRequired($row) protected function _getSitemapRow($url, $lastmod = null, $changefreq = null, $priority = null, $images = null) { $url = $this->_getUrl($url); - $row = '<loc>' . htmlspecialchars($url) . '</loc>'; + $row = '<loc>' . $this->_escaper->escapeUrl($url) . '</loc>'; if ($lastmod) { $row .= '<lastmod>' . $this->_getFormattedLastmodDate($lastmod) . '</lastmod>'; } @@ -519,17 +525,17 @@ protected function _getSitemapRow($url, $lastmod = null, $changefreq = null, $pr // Add Images to sitemap foreach ($images->getCollection() as $image) { $row .= '<image:image>'; - $row .= '<image:loc>' . htmlspecialchars($image->getUrl()) . '</image:loc>'; - $row .= '<image:title>' . htmlspecialchars($images->getTitle()) . '</image:title>'; + $row .= '<image:loc>' . $this->_escaper->escapeUrl($image->getUrl()) . '</image:loc>'; + $row .= '<image:title>' . $this->_escaper->escapeHtml($images->getTitle()) . '</image:title>'; if ($image->getCaption()) { - $row .= '<image:caption>' . htmlspecialchars($image->getCaption()) . '</image:caption>'; + $row .= '<image:caption>' . $this->_escaper->escapeHtml($image->getCaption()) . '</image:caption>'; } $row .= '</image:image>'; } // Add PageMap image for Google web search $row .= '<PageMap xmlns="http://www.google.com/schemas/sitemap-pagemap/1.0"><DataObject type="thumbnail">'; - $row .= '<Attribute name="name" value="' . htmlspecialchars($images->getTitle()) . '"/>'; - $row .= '<Attribute name="src" value="' . htmlspecialchars($images->getThumbnail()) . '"/>'; + $row .= '<Attribute name="name" value="' . $this->_escaper->escapeHtml($images->getTitle()) . '"/>'; + $row .= '<Attribute name="src" value="' . $this->_escaper->escapeUrl($images->getThumbnail()) . '"/>'; $row .= '</DataObject></PageMap>'; } @@ -546,7 +552,7 @@ protected function _getSitemapRow($url, $lastmod = null, $changefreq = null, $pr protected function _getSitemapIndexRow($sitemapFilename, $lastmod = null) { $url = $this->getSitemapUrl($this->getSitemapPath(), $sitemapFilename); - $row = '<loc>' . htmlspecialchars($url) . '</loc>'; + $row = '<loc>' . $this->_escaper->escapeUrl($url) . '</loc>'; if ($lastmod) { $row .= '<lastmod>' . $this->_getFormattedLastmodDate($lastmod) . '</lastmod>'; } @@ -688,6 +694,7 @@ protected function _getFormattedLastmodDate($date) */ protected function _getDocumentRoot() { + // phpcs:ignore Magento2.Functions.DiscouragedFunction return realpath($this->_request->getServer('DOCUMENT_ROOT')); } @@ -698,6 +705,7 @@ protected function _getDocumentRoot() */ protected function _getStoreBaseDomain() { + // phpcs:ignore Magento2.Functions.DiscouragedFunction $storeParsedUrl = parse_url($this->_getStoreBaseUrl()); $url = $storeParsedUrl['scheme'] . '://' . $storeParsedUrl['host']; diff --git a/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php b/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php index 5036c63fd87fe..e6676511b8882 100644 --- a/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php +++ b/app/code/Magento/Sitemap/Test/Unit/Model/SitemapTest.php @@ -160,7 +160,7 @@ public function testNotAllowedPath() * Check not exists sitemap path validation * * @expectedException \Magento\Framework\Exception\LocalizedException - * @expectedExceptionMessage Please create the specified folder "" before saving the sitemap. + * @expectedExceptionMessage Please create the specified folder "/" before saving the sitemap. */ public function testPathNotExists() { @@ -637,6 +637,9 @@ protected function _getModelConstructorArgs() ->getMockForAbstractClass(); $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $escaper = $objectManager->getObject( + \Magento\Framework\Escaper::class + ); $constructArguments = $objectManager->getConstructArguments( \Magento\Sitemap\Model\Sitemap::class, [ @@ -645,7 +648,8 @@ protected function _getModelConstructorArgs() 'cmsFactory' => $cmsFactory, 'storeManager' => $this->storeManagerMock, 'sitemapData' => $this->_helperMockSitemap, - 'filesystem' => $this->_filesystemMock + 'filesystem' => $this->_filesystemMock, + 'escaper' => $escaper ] ); $constructArguments['resource'] = null; diff --git a/app/code/Magento/Tax/Controller/Adminhtml/Rate/AjaxSave.php b/app/code/Magento/Tax/Controller/Adminhtml/Rate/AjaxSave.php index f6cd0fff9c9b0..572eaa55abbb5 100644 --- a/app/code/Magento/Tax/Controller/Adminhtml/Rate/AjaxSave.php +++ b/app/code/Magento/Tax/Controller/Adminhtml/Rate/AjaxSave.php @@ -6,10 +6,42 @@ */ namespace Magento\Tax\Controller\Adminhtml\Rate; +use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Backend\App\Action\Context; +use Magento\Framework\Registry; +use Magento\Tax\Model\Calculation\Rate\Converter; +use Magento\Tax\Api\TaxRateRepositoryInterface; +use Magento\Framework\Escaper; use Magento\Framework\Controller\ResultFactory; -class AjaxSave extends \Magento\Tax\Controller\Adminhtml\Rate +/** + * Tax Rate AjaxSave Controller + */ +class AjaxSave extends \Magento\Tax\Controller\Adminhtml\Rate implements HttpPostActionInterface { + /** + * @var Escaper + */ + private $escaper; + + /** + * @param Context $context + * @param Registry $coreRegistry + * @param Converter $taxRateConverter + * @param TaxRateRepositoryInterface $taxRateRepository + * @param Escaper $escaper + */ + public function __construct( + Context $context, + Registry $coreRegistry, + Converter $taxRateConverter, + TaxRateRepositoryInterface $taxRateRepository, + Escaper $escaper + ) { + $this->escaper = $escaper; + parent::__construct($context, $coreRegistry, $taxRateConverter, $taxRateRepository); + } + /** * Save Tax Rate via AJAX * @@ -27,7 +59,7 @@ public function execute() 'success' => true, 'error_message' => '', 'tax_calculation_rate_id' => $taxRate->getId(), - 'code' => htmlspecialchars($taxRate->getCode()), + 'code' => $this->escaper->escapeHtml($taxRate->getCode()), ]; } catch (\Magento\Framework\Exception\LocalizedException $e) { $responseContent = [ diff --git a/app/code/Magento/Translation/Model/Inline/Parser.php b/app/code/Magento/Translation/Model/Inline/Parser.php index e0b2ce40405d1..e984fc9ee1a1a 100644 --- a/app/code/Magento/Translation/Model/Inline/Parser.php +++ b/app/code/Magento/Translation/Model/Inline/Parser.php @@ -7,8 +7,7 @@ namespace Magento\Translation\Model\Inline; /** - * This class is responsible for parsing content and applying necessary html element - * wrapping and client scripts for inline translation. + * Parse content, applying necessary html element wrapping and client scripts for inline translation. * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ @@ -19,6 +18,11 @@ class Parser implements \Magento\Framework\Translate\Inline\ParserInterface */ const DATA_TRANSLATE = 'data-translate'; + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * Response body or JSON content string * @@ -132,6 +136,8 @@ class Parser implements \Magento\Framework\Translate\Inline\ParserInterface private $relatedCacheTypes; /** + * Return cache manager + * * @return \Magento\Translation\Model\Inline\CacheManager * * @deprecated 100.1.0 @@ -149,13 +155,14 @@ private function getCacheManger() /** * Initialize base inline translation model * - * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Translation\Model\ResourceModel\StringUtilsFactory $resource + * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Zend_Filter_Interface $inputFilter * @param \Magento\Framework\App\State $appState * @param \Magento\Framework\App\Cache\TypeListInterface $appCache * @param \Magento\Framework\Translate\InlineInterface $translateInline * @param array $relatedCacheTypes + * @param \Magento\Framework\Escaper|null $escaper */ public function __construct( \Magento\Translation\Model\ResourceModel\StringUtilsFactory $resource, @@ -164,7 +171,8 @@ public function __construct( \Magento\Framework\App\State $appState, \Magento\Framework\App\Cache\TypeListInterface $appCache, \Magento\Framework\Translate\InlineInterface $translateInline, - array $relatedCacheTypes = [] + array $relatedCacheTypes = [], + \Magento\Framework\Escaper $escaper = null ) { $this->_resourceFactory = $resource; $this->_storeManager = $storeManager; @@ -173,6 +181,9 @@ public function __construct( $this->_appCache = $appCache; $this->_translateInline = $translateInline; $this->relatedCacheTypes = $relatedCacheTypes; + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); } /** @@ -236,8 +247,8 @@ protected function _validateTranslationParams(array $translateParams) /** * Apply input filter to values of translation parameters * - * @param array &$translateParams - * @param array $fieldNames Names of fields values of which are to be filtered + * @param array $translateParams + * @param array $fieldNames * @return void */ protected function _filterTranslationParams(array &$translateParams, array $fieldNames) @@ -344,7 +355,7 @@ protected function _applySpecialTagsFormat($tagHtml, $tagName, $trArr) { $specialTags = $tagHtml . '<span class="translate-inline-' . $tagName . '" ' . $this->_getHtmlAttribute( self::DATA_TRANSLATE, - '[' . htmlspecialchars(join(',', $trArr)) . ']' + '[' . $this->escaper->escapeHtml(join(',', $trArr)) . ']' ); $additionalAttr = $this->_getAdditionalHtmlAttribute($tagName); if ($additionalAttr !== null) { @@ -360,7 +371,7 @@ protected function _applySpecialTagsFormat($tagHtml, $tagName, $trArr) * Format translation for simple tags. Added translate mode attribute for vde requests. * * @param string $tagHtml - * @param string $tagName + * @param string $tagName * @param array $trArr * @return string */ @@ -372,7 +383,7 @@ protected function _applySimpleTagsFormat($tagHtml, $tagName, $trArr) strlen($tagName) + 1 ) . ' ' . $this->_getHtmlAttribute( self::DATA_TRANSLATE, - htmlspecialchars('[' . join(',', $trArr) . ']') + $this->escaper->escapeHtml('[' . join(',', $trArr) . ']') ); $additionalAttr = $this->_getAdditionalHtmlAttribute($tagName); if ($additionalAttr !== null) { @@ -386,12 +397,12 @@ protected function _applySimpleTagsFormat($tagHtml, $tagName, $trArr) * Get translate data by regexp * * @param string $regexp - * @param string &$text - * @param string|array $locationCallback + * @param string $text + * @param callable $locationCallback * @param array $options * @return array */ - private function _getTranslateData($regexp, &$text, $locationCallback, $options = []) + private function _getTranslateData(string $regexp, string &$text, callable $locationCallback, array $options = []) { $trArr = []; $next = 0; @@ -401,7 +412,7 @@ private function _getTranslateData($regexp, &$text, $locationCallback, $options 'shown' => htmlspecialchars_decode($matches[1][0]), 'translated' => htmlspecialchars_decode($matches[2][0]), 'original' => htmlspecialchars_decode($matches[3][0]), - 'location' => htmlspecialchars_decode(call_user_func($locationCallback, $matches, $options)), + 'location' => htmlspecialchars_decode($locationCallback($matches, $options)), ] ); $text = substr_replace($text, $matches[1][0], $matches[0][1], strlen($matches[0][0])); @@ -446,7 +457,8 @@ private function _prepareTagAttributesForContent(&$content) $tagHtml = str_replace($matches[0], '', $tagHtml); $trAttr = ' ' . $this->_getHtmlAttribute( self::DATA_TRANSLATE, - '[' . htmlspecialchars($matches[1]) . ',' . str_replace("\"", "'", join(',', $trArr)) . ']' + '[' . $this->escaper->escapeHtml($matches[1]) . ',' . + str_replace("\"", "'", join(',', $trArr)) . ']' ); } else { $trAttr = ' ' . $this->_getHtmlAttribute( @@ -512,19 +524,31 @@ private function _getHtmlQuote() */ private function _specialTags() { - $this->_translateTags($this->_content, $this->_allowedTagsGlobal, '_applySpecialTagsFormat'); - $this->_translateTags($this->_content, $this->_allowedTagsSimple, '_applySimpleTagsFormat'); + $this->_translateTags( + $this->_content, + $this->_allowedTagsGlobal, + function ($tagHtml, $tagName, $trArr) { + return $this->_applySpecialTagsFormat($tagHtml, $tagName, $trArr); + } + ); + $this->_translateTags( + $this->_content, + $this->_allowedTagsSimple, + function ($tagHtml, $tagName, $trArr) { + return $this->_applySimpleTagsFormat($tagHtml, $tagName, $trArr); + } + ); } /** * Prepare simple tags * - * @param string &$content + * @param string $content * @param array $tagsList - * @param string|array $formatCallback + * @param callable $formatCallback * @return void */ - private function _translateTags(&$content, $tagsList, $formatCallback) + private function _translateTags(string &$content, array $tagsList, callable $formatCallback) { $nextTag = 0; $tagRegExpBody = '#<(body)(/?>| \s*[^>]*+/?>)#iSU'; @@ -575,10 +599,10 @@ private function _translateTags(&$content, $tagsList, $formatCallback) if (array_key_exists($tagName, $this->_allowedTagsGlobal) && $tagBodyOpenStartPosition > $tagMatch[0][1] ) { - $tagHtmlHead = call_user_func([$this, $formatCallback], $tagHtml, $tagName, $trArr); + $tagHtmlHead = $formatCallback($tagHtml, $tagName, $trArr); $headTranslateTags .= substr($tagHtmlHead, strlen($tagHtml)); } else { - $tagHtml = call_user_func([$this, $formatCallback], $tagHtml, $tagName, $trArr); + $tagHtml = $formatCallback($tagHtml, $tagName, $trArr); } } @@ -649,7 +673,7 @@ private function _otherText() ); $spanHtml = $this->_getDataTranslateSpan( - '[' . htmlspecialchars($translateProperties) . ']', + '[' . $this->escaper->escapeHtmlAttr($translateProperties) . ']', $matches[1][0] ); $this->_content = substr_replace($this->_content, $spanHtml, $matches[0][1], strlen($matches[0][0])); diff --git a/app/code/Magento/Translation/Model/ResourceModel/StringUtils.php b/app/code/Magento/Translation/Model/ResourceModel/StringUtils.php index 4be4e055a7d83..769336419d89b 100644 --- a/app/code/Magento/Translation/Model/ResourceModel/StringUtils.php +++ b/app/code/Magento/Translation/Model/ResourceModel/StringUtils.php @@ -5,8 +5,16 @@ */ namespace Magento\Translation\Model\ResourceModel; +/** + * String translation utilities + */ class StringUtils extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * @var \Magento\Framework\Locale\ResolverInterface */ @@ -28,17 +36,22 @@ class StringUtils extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb * @param \Magento\Framework\App\ScopeResolverInterface $scopeResolver * @param string $connectionName * @param string|null $scope + * @param \Magento\Framework\Escaper|null $escaper */ public function __construct( \Magento\Framework\Model\ResourceModel\Db\Context $context, \Magento\Framework\Locale\ResolverInterface $localeResolver, \Magento\Framework\App\ScopeResolverInterface $scopeResolver, $connectionName = null, - $scope = null + $scope = null, + \Magento\Framework\Escaper $escaper = null ) { $this->_localeResolver = $localeResolver; $this->scopeResolver = $scopeResolver; $this->scope = $scope; + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); parent::__construct($context, $connectionName); } @@ -211,7 +224,7 @@ public function saveTranslate($string, $translate, $locale = null, $storeId = nu $string = htmlspecialchars_decode($string); $connection = $this->getConnection(); $table = $this->getMainTable(); - $translate = htmlspecialchars($translate, ENT_QUOTES); + $translate = $this->escaper->escapeHtml($translate); if ($locale === null) { $locale = $this->_localeResolver->getLocale(); diff --git a/app/code/Magento/Ui/Test/Unit/Component/Control/ButtonTest.php b/app/code/Magento/Ui/Test/Unit/Component/Control/ButtonTest.php index bc7c3ac677e10..97c77c158c147 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Control/ButtonTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Control/ButtonTest.php @@ -10,6 +10,9 @@ use Magento\Framework\View\Element\Template\Context; use Magento\Ui\Component\Control\Button; +/** + * Class ButtonTest + */ class ButtonTest extends \PHPUnit\Framework\TestCase { /** @@ -55,7 +58,7 @@ public function testGetType() public function testGetAttributesHtml() { $expected = 'type="button" class="action- scalable classValue disabled" ' - . 'onclick="location.href = \'url2\';" disabled="disabled" data-attributeKey="attributeValue" '; + . 'onclick="location.href = 'url2';" disabled="disabled" data-attributeKey="attributeValue" '; $this->button->setDisabled(true); $this->button->setData('url', 'url2'); $this->button->setData('class', 'classValue'); diff --git a/app/code/Magento/Webapi/Model/Soap/Fault.php b/app/code/Magento/Webapi/Model/Soap/Fault.php index 74b1b41ee1bf5..7214f37d04468 100644 --- a/app/code/Magento/Webapi/Model/Soap/Fault.php +++ b/app/code/Magento/Webapi/Model/Soap/Fault.php @@ -9,6 +9,9 @@ use Magento\Framework\App\State; +/** + * Webapi Fault Model for Soap. + */ class Fault { const FAULT_REASON_INTERNAL = 'Internal Error.'; @@ -39,6 +42,11 @@ class Fault const NODE_DETAIL_WRAPPER = 'GenericFault'; /**#@-*/ + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * @var string */ @@ -108,13 +116,15 @@ class Fault * @param \Magento\Framework\Webapi\Exception $exception * @param \Magento\Framework\Locale\ResolverInterface $localeResolver * @param State $appState + * @param \Magento\Framework\Escaper|null $escaper */ public function __construct( \Magento\Framework\App\RequestInterface $request, Server $soapServer, \Magento\Framework\Webapi\Exception $exception, \Magento\Framework\Locale\ResolverInterface $localeResolver, - State $appState + State $appState, + \Magento\Framework\Escaper $escaper = null ) { $this->_soapFaultCode = $exception->getOriginator(); $this->_parameters = $exception->getDetails(); @@ -125,6 +135,9 @@ public function __construct( $this->_soapServer = $soapServer; $this->_localeResolver = $localeResolver; $this->appState = $appState; + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); } /** @@ -210,6 +223,8 @@ public function getLanguage() } /** + * Retrieve message + * * @return string */ public function getMessage() @@ -286,14 +301,15 @@ protected function _convertDetailsToXml($details) { $detailsXml = ''; foreach ($details as $detailNode => $detailValue) { - $detailNode = htmlspecialchars($detailNode); + $detailNode = $this->escaper->escapeHtml($detailNode); if (is_numeric($detailNode)) { continue; } switch ($detailNode) { case self::NODE_DETAIL_TRACE: if (is_string($detailValue) || is_numeric($detailValue)) { - $detailsXml .= "<m:{$detailNode}>" . htmlspecialchars($detailValue) . "</m:{$detailNode}>"; + $detailsXml .= "<m:{$detailNode}>" . $this->escaper->escapeHtml($detailValue) . + "</m:{$detailNode}>"; } break; case self::NODE_DETAIL_PARAMETERS: @@ -331,7 +347,7 @@ protected function _getParametersXml($parameters) $parameterName++; } $paramsXml .= "<m:$parameterNode><m:$keyNode>$parameterName</m:$keyNode><m:$valueNode>" - . htmlspecialchars($parameterValue) . "</m:$valueNode></m:$parameterNode>"; + . $this->escaper->escapeHtml($parameterValue) . "</m:$valueNode></m:$parameterNode>"; } } if (!empty($paramsXml)) { diff --git a/app/code/Magento/Widget/Setup/LayoutUpdateConverter.php b/app/code/Magento/Widget/Setup/LayoutUpdateConverter.php index 54c364dcc49a4..39b3d3c4b5a6e 100644 --- a/app/code/Magento/Widget/Setup/LayoutUpdateConverter.php +++ b/app/code/Magento/Widget/Setup/LayoutUpdateConverter.php @@ -16,6 +16,11 @@ */ class LayoutUpdateConverter extends SerializedToJson { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * @var Normalizer */ @@ -27,13 +32,18 @@ class LayoutUpdateConverter extends SerializedToJson * @param Serialize $serialize * @param Json $json * @param Normalizer $normalizer + * @param \Magento\Framework\Escaper|null $escaper */ public function __construct( Serialize $serialize, Json $json, - Normalizer $normalizer + Normalizer $normalizer, + \Magento\Framework\Escaper $escaper = null ) { $this->normalizer = $normalizer; + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); parent::__construct($serialize, $json); } @@ -85,7 +95,7 @@ protected function unserializeValue($value) */ protected function encodeJson($value) { - return htmlspecialchars( + return $this->escaper->escapeHtml( $this->normalizer->replaceReservedCharacters(parent::encodeJson($value)) ); } diff --git a/app/code/Magento/Wishlist/Controller/Index/Send.php b/app/code/Magento/Wishlist/Controller/Index/Send.php index 7ca94b1f284f5..044a5e2907e8b 100644 --- a/app/code/Magento/Wishlist/Controller/Index/Send.php +++ b/app/code/Magento/Wishlist/Controller/Index/Send.php @@ -28,6 +28,11 @@ */ class Send extends \Magento\Wishlist\Controller\AbstractIndex { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * @var \Magento\Customer\Helper\View */ @@ -102,6 +107,7 @@ class Send extends \Magento\Wishlist\Controller\AbstractIndex * @param StoreManagerInterface $storeManager * @param CaptchaHelper|null $captchaHelper * @param CaptchaStringResolver|null $captchaStringResolver + * @param \Magento\Framework\Escaper|null $escaper * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -117,7 +123,8 @@ public function __construct( ScopeConfigInterface $scopeConfig, StoreManagerInterface $storeManager, CaptchaHelper $captchaHelper = null, - CaptchaStringResolver $captchaStringResolver = null + CaptchaStringResolver $captchaStringResolver = null, + \Magento\Framework\Escaper $escaper = null ) { $this->_formKeyValidator = $formKeyValidator; $this->_customerSession = $customerSession; @@ -132,7 +139,9 @@ public function __construct( $this->captchaHelper = $captchaHelper ?: ObjectManager::getInstance()->get(CaptchaHelper::class); $this->captchaStringResolver = $captchaStringResolver ? : ObjectManager::getInstance()->get(CaptchaStringResolver::class); - + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); parent::__construct($context); } @@ -185,7 +194,7 @@ public function execute() if (strlen($message) > $textLimit) { $error = __('Message length must not exceed %1 symbols', $textLimit); } else { - $message = nl2br(htmlspecialchars($message)); + $message = nl2br($this->escaper->escapeHtml($message)); if (empty($emails)) { $error = __('Please enter an email address.'); } else { diff --git a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/ResultTest.php b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/ResultTest.php index 4cd0f124b6e46..4f8a279a59165 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/ResultTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogSearch/Controller/ResultTest.php @@ -33,13 +33,15 @@ public function testIndexActionTranslation() public function testIndexActionXSSQueryVerification() { + $escaper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->get(\Magento\Framework\Escaper::class); $this->getRequest()->setParam('q', '<script>alert(1)</script>'); $this->dispatch('catalogsearch/result'); $responseBody = $this->getResponse()->getBody(); $data = '<script>alert(1)</script>'; $this->assertNotContains($data, $responseBody); - $this->assertContains(htmlspecialchars($data, ENT_COMPAT, 'UTF-8', false), $responseBody); + $this->assertContains($escaper->escapeHtml($data), $responseBody); } /** diff --git a/dev/tests/integration/testsuite/Magento/Integration/Block/Adminhtml/Widget/Grid/Column/Renderer/Button/DeleteTest.php b/dev/tests/integration/testsuite/Magento/Integration/Block/Adminhtml/Widget/Grid/Column/Renderer/Button/DeleteTest.php index 92ae76b0d9a4d..c6cc68582ae6b 100644 --- a/dev/tests/integration/testsuite/Magento/Integration/Block/Adminhtml/Widget/Grid/Column/Renderer/Button/DeleteTest.php +++ b/dev/tests/integration/testsuite/Magento/Integration/Block/Adminhtml/Widget/Grid/Column/Renderer/Button/DeleteTest.php @@ -39,8 +39,8 @@ public function testRender() $buttonHtml = $this->deleteButtonBlock->render($integration); $this->assertContains('title="Remove"', $buttonHtml); $this->assertContains( - 'onclick="this.setAttribute(\'data-url\', ' - . '\'http://localhost/index.php/backend/admin/integration/delete/id/' + 'onclick="this.setAttribute('data-url', ' + . ''http://localhost/index.php/backend/admin/integration/delete/id/' . $integration->getId(), $buttonHtml ); @@ -54,8 +54,8 @@ public function testRenderDisabled() $buttonHtml = $this->deleteButtonBlock->render($integration); $this->assertContains('title="Uninstall the extension to remove this integration"', $buttonHtml); $this->assertContains( - 'onclick="this.setAttribute(\'data-url\', ' - . '\'http://localhost/index.php/backend/admin/integration/delete/id/' + 'onclick="this.setAttribute('data-url', ' + . ''http://localhost/index.php/backend/admin/integration/delete/id/' . $integration->getId(), $buttonHtml ); diff --git a/dev/tests/integration/testsuite/Magento/Integration/Block/Adminhtml/Widget/Grid/Column/Renderer/Button/EditTest.php b/dev/tests/integration/testsuite/Magento/Integration/Block/Adminhtml/Widget/Grid/Column/Renderer/Button/EditTest.php index df180d020888a..0463053e6b5f1 100644 --- a/dev/tests/integration/testsuite/Magento/Integration/Block/Adminhtml/Widget/Grid/Column/Renderer/Button/EditTest.php +++ b/dev/tests/integration/testsuite/Magento/Integration/Block/Adminhtml/Widget/Grid/Column/Renderer/Button/EditTest.php @@ -40,7 +40,7 @@ public function testRenderEdit() $this->assertContains('title="Edit"', $buttonHtml); $this->assertContains('class="action edit"', $buttonHtml); $this->assertContains( - 'onclick="window.location.href=\'http://localhost/index.php/backend/admin/integration/edit/id/' + 'onclick="window.location.href='http://localhost/index.php/backend/admin/integration/edit/id/' . $integration->getId(), $buttonHtml ); diff --git a/dev/tests/integration/testsuite/Magento/Tax/Controller/Adminhtml/RateTest.php b/dev/tests/integration/testsuite/Magento/Tax/Controller/Adminhtml/RateTest.php index 91a845f151eaf..afc2fbdce5e1b 100644 --- a/dev/tests/integration/testsuite/Magento/Tax/Controller/Adminhtml/RateTest.php +++ b/dev/tests/integration/testsuite/Magento/Tax/Controller/Adminhtml/RateTest.php @@ -16,7 +16,7 @@ class RateTest extends \Magento\TestFramework\TestCase\AbstractBackendController */ public function testAjaxSaveAction($postData, $expectedData) { - $this->getRequest()->setPostValue($postData); + $this->getRequest()->setPostValue($postData)->setMethod('POST'); $this->dispatch('backend/tax/rate/ajaxSave'); @@ -84,7 +84,7 @@ public function ajaxSaveActionDataProvider() */ public function testAjaxSaveActionInvalidData($postData, $expectedData) { - $this->getRequest()->setPostValue($postData); + $this->getRequest()->setPostValue($postData)->setMethod('POST'); $this->dispatch('backend/tax/rate/ajaxSave'); diff --git a/lib/internal/Magento/Framework/Convert/Excel.php b/lib/internal/Magento/Framework/Convert/Excel.php index 09acd88b38a7f..13d8c0fa9d56b 100644 --- a/lib/internal/Magento/Framework/Convert/Excel.php +++ b/lib/internal/Magento/Framework/Convert/Excel.php @@ -12,6 +12,11 @@ */ class Excel { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * \ArrayIterator Object * @@ -45,15 +50,23 @@ class Excel * * @param \Iterator $iterator * @param array $rowCallback + * @param \Magento\Framework\Escaper|null $escaper */ - public function __construct(\Iterator $iterator, $rowCallback = []) - { + public function __construct( + \Iterator $iterator, + $rowCallback = [], + \Magento\Framework\Escaper $escaper = null + ) { $this->_iterator = $iterator; $this->_rowCallback = $rowCallback; + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); } /** * Retrieve Excel XML Document Header XML Fragment + * * Append data header if it is available * * @param string $sheetName @@ -65,7 +78,7 @@ protected function _getXmlHeader($sheetName = '') $sheetName = 'Sheet 1'; } - $sheetName = htmlspecialchars($sheetName); + $sheetName = $this->escaper->escapeHtml($sheetName); $xmlHeader = '<' . '?xml version="1.0"?' . @@ -98,6 +111,7 @@ protected function _getXmlHeader($sheetName = '') /** * Retrieve Excel XML Document Footer XML Fragment + * * Append data footer if it is available * * @return string @@ -133,7 +147,7 @@ protected function _getXmlRow($row, $useCallback) $xmlData[] = '<Row>'; foreach ($row as $value) { - $value = htmlspecialchars($value); + $value = $this->escaper->escapeHtml($value); $dataType = is_numeric($value) && $value[0] !== '+' && $value[0] !== '0' ? 'Number' : 'String'; /** diff --git a/lib/internal/Magento/Framework/Data/Form/Element/AbstractElement.php b/lib/internal/Magento/Framework/Data/Form/Element/AbstractElement.php index 1b7e9ad990ce4..fe9981be0d255 100644 --- a/lib/internal/Magento/Framework/Data/Form/Element/AbstractElement.php +++ b/lib/internal/Magento/Framework/Data/Form/Element/AbstractElement.php @@ -13,6 +13,7 @@ /** * Data form abstract class * + * phpcs:disable Magento2.Classes.AbstractApi * @api * @author Magento Core Team <core@magentocommerce.com> * @SuppressWarnings(PHPMD.NumberOfChildren) @@ -289,7 +290,7 @@ public function removeClass($class) */ protected function _escape($string) { - return htmlspecialchars($string, ENT_COMPAT); + return $this->_escaper->escapeHtml($string); } /** diff --git a/lib/internal/Magento/Framework/Data/Form/Filter/Escapehtml.php b/lib/internal/Magento/Framework/Data/Form/Filter/Escapehtml.php index 6feca703f15fe..54821217ca124 100644 --- a/lib/internal/Magento/Framework/Data/Form/Filter/Escapehtml.php +++ b/lib/internal/Magento/Framework/Data/Form/Filter/Escapehtml.php @@ -11,8 +11,27 @@ */ namespace Magento\Framework\Data\Form\Filter; +/** + * EscapeHtml Form Filter Data + */ class Escapehtml implements \Magento\Framework\Data\Form\Filter\FilterInterface { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + + /** + * @param \Magento\Framework\Escaper|null $escaper + */ + public function __construct( + \Magento\Framework\Escaper $escaper = null + ) { + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); + } + /** * Returns the result of filtering $value * @@ -32,6 +51,6 @@ public function inputFilter($value) */ public function outputFilter($value) { - return htmlspecialchars($value); + return $this->escaper->escapeHtml($value); } } diff --git a/lib/internal/Magento/Framework/Data/Form/FormKey.php b/lib/internal/Magento/Framework/Data/Form/FormKey.php index 75b3311b4ffe9..355460902eee6 100644 --- a/lib/internal/Magento/Framework/Data/Form/FormKey.php +++ b/lib/internal/Magento/Framework/Data/Form/FormKey.php @@ -3,10 +3,16 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Framework\Data\Form; /** + * Class FormKey + * * @api + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ class FormKey { @@ -50,24 +56,29 @@ public function __construct( * Retrieve Session Form Key * * @return string A 16 bit unique key for forms + * @throws \Magento\Framework\Exception\LocalizedException */ public function getFormKey() { if (!$this->isPresent()) { $this->set($this->mathRandom->getRandomString(16)); } - return $this->escaper->escapeHtmlAttr($this->session->getData(self::FORM_KEY)); + return $this->escaper->escapeJs($this->session->getData(self::FORM_KEY)); } /** + * Determine if the form key is present in the session + * * @return bool */ public function isPresent() { - return (bool)$this->session->getData(self::FORM_KEY); + return (bool) $this->session->getData(self::FORM_KEY); } /** + * Set the value of the form key + * * @param string $value * @return void */ diff --git a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/AbstractElementTest.php b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/AbstractElementTest.php index a207f45cb805a..ede56713bd02d 100644 --- a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/AbstractElementTest.php +++ b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/AbstractElementTest.php @@ -3,12 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +namespace Magento\Framework\Data\Test\Unit\Form\Element; /** * Tests for \Magento\Framework\Data\Form\Element\AbstractElement */ -namespace Magento\Framework\Data\Test\Unit\Form\Element; - class AbstractElementTest extends \PHPUnit\Framework\TestCase { /** @@ -242,9 +241,9 @@ public function testRemoveClass() */ public function testGetEscapedValueWithoutFilter() { - $this->_model->setValue('<a href="#hash_tag">my \'quoted\' string</a>'); + $this->_model->setValue('<a href="#hash_tag">my 'quoted' string</a>'); $this->assertEquals( - '<a href="#hash_tag">my \'quoted\' string</a>', + '<a href="#hash_tag">my 'quoted' string</a>', $this->_model->getEscapedValue() ); } @@ -254,8 +253,8 @@ public function testGetEscapedValueWithoutFilter() */ public function testGetEscapedValueWithFilter() { - $value = '<a href="#hash_tag">my \'quoted\' string</a>'; - $expectedValue = '<a href="#hash_tag">my \'quoted\' string</a>'; + $value = '<a href="#hash_tag">my 'quoted' string</a>'; + $expectedValue = '<a href="#hash_tag">my 'quoted' string</a>'; $filterMock = $this->createPartialMock(\Magento\Framework\DataObject::class, ['filter']); $filterMock->expects($this->once()) diff --git a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/LabelTest.php b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/LabelTest.php index 8420f8e421f7b..ec625a1cdd4a5 100644 --- a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/LabelTest.php +++ b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/LabelTest.php @@ -3,18 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +namespace Magento\Framework\Data\Test\Unit\Form\Element; /** * Tests for \Magento\Framework\Data\Form\Element\Label */ -namespace Magento\Framework\Data\Test\Unit\Form\Element; - class LabelTest extends \PHPUnit\Framework\TestCase { - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_objectManagerMock; + /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + private $objectManager; /** * @var \Magento\Framework\Data\Form\Element\Label @@ -25,11 +22,14 @@ protected function setUp() { $factoryMock = $this->createMock(\Magento\Framework\Data\Form\Element\Factory::class); $collectionFactoryMock = $this->createMock(\Magento\Framework\Data\Form\Element\CollectionFactory::class); - $escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $escaper = $this->objectManager->getObject( + \Magento\Framework\Escaper::class + ); $this->_label = new \Magento\Framework\Data\Form\Element\Label( $factoryMock, $collectionFactoryMock, - $escaperMock + $escaper ); } diff --git a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/MultilineTest.php b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/MultilineTest.php index 9a391da4d65dd..85482e05188ab 100644 --- a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/MultilineTest.php +++ b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/MultilineTest.php @@ -5,8 +5,14 @@ */ namespace Magento\Framework\Data\Test\Unit\Form\Element; +/** + * Test for \Magento\Framework\Data\Form\Element\Multiline + */ class MultilineTest extends \PHPUnit\Framework\TestCase { + /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + private $objectManager; + /** * @var \Magento\Framework\Data\Form\Element\Multiline */ @@ -37,9 +43,11 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->escaper = $this->getMockBuilder(\Magento\Framework\Escaper::class) - ->disableOriginalConstructor() - ->getMock(); + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->escaper = $this->objectManager->getObject( + \Magento\Framework\Escaper::class + ); $this->element = new \Magento\Framework\Data\Form\Element\Multiline( $this->elementFactory, diff --git a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/ObscureTest.php b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/ObscureTest.php index bb0b67a40abea..cec024fd4073b 100644 --- a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/ObscureTest.php +++ b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/ObscureTest.php @@ -3,18 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +namespace Magento\Framework\Data\Test\Unit\Form\Element; /** * Tests for \Magento\Framework\Data\Form\Element\Obscure */ -namespace Magento\Framework\Data\Test\Unit\Form\Element; - class ObscureTest extends \PHPUnit\Framework\TestCase { - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_objectManagerMock; + /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + private $objectManager; /** * @var \Magento\Framework\Data\Form\Element\Obscure @@ -25,11 +22,14 @@ protected function setUp() { $factoryMock = $this->createMock(\Magento\Framework\Data\Form\Element\Factory::class); $collectionFactoryMock = $this->createMock(\Magento\Framework\Data\Form\Element\CollectionFactory::class); - $escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $escaper = $this->objectManager->getObject( + \Magento\Framework\Escaper::class + ); $this->_model = new \Magento\Framework\Data\Form\Element\Obscure( $factoryMock, $collectionFactoryMock, - $escaperMock + $escaper ); $formMock = new \Magento\Framework\DataObject(); $formMock->getHtmlIdPrefix('id_prefix'); diff --git a/lib/internal/Magento/Framework/Data/Test/Unit/Form/FormKeyTest.php b/lib/internal/Magento/Framework/Data/Test/Unit/Form/FormKeyTest.php index 5d765955f3673..eb642278694c0 100644 --- a/lib/internal/Magento/Framework/Data/Test/Unit/Form/FormKeyTest.php +++ b/lib/internal/Magento/Framework/Data/Test/Unit/Form/FormKeyTest.php @@ -10,6 +10,9 @@ use Magento\Framework\Math\Random; use Magento\Framework\Session\SessionManager; +/** + * Class FormKeyTest + */ class FormKeyTest extends \PHPUnit\Framework\TestCase { /** @@ -38,7 +41,7 @@ protected function setUp() $methods = ['setData', 'getData']; $this->sessionMock = $this->createPartialMock(\Magento\Framework\Session\SessionManager::class, $methods); $this->escaperMock = $this->createMock(\Magento\Framework\Escaper::class); - $this->escaperMock->expects($this->any())->method('escapeHtmlAttr')->willReturnArgument(0); + $this->escaperMock->expects($this->any())->method('escapeJs')->willReturnArgument(0); $this->formKey = new FormKey( $this->mathRandomMock, $this->sessionMock, diff --git a/lib/internal/Magento/Framework/Escaper.php b/lib/internal/Magento/Framework/Escaper.php index f3eefaed50d18..7eb7a8f11ba99 100644 --- a/lib/internal/Magento/Framework/Escaper.php +++ b/lib/internal/Magento/Framework/Escaper.php @@ -13,6 +13,11 @@ */ class Escaper { + /** + * HTML special characters flag + */ + private $htmlSpecialCharsFlag = ENT_QUOTES | ENT_SUBSTITUTE; + /** * @var \Magento\Framework\ZendEscaper */ @@ -74,6 +79,7 @@ public function escapeHtml($data, $allowedTags = null) $domDocument = new \DOMDocument('1.0', 'UTF-8'); set_error_handler( function ($errorNumber, $errorString) { + // phpcs:ignore Magento2.Exceptions.DirectThrow throw new \Exception($errorString, $errorNumber); } ); @@ -83,6 +89,7 @@ function ($errorNumber, $errorString) { $domDocument->loadHTML( '<html><body id="' . $wrapperElementId . '">' . $string . '</body></html>' ); + // phpcs:disable Magento2.Exceptions.ThrowCatch } catch (\Exception $e) { restore_error_handler(); $this->getLogger()->critical($e); @@ -98,7 +105,7 @@ function ($errorNumber, $errorString) { preg_match('/<body id="' . $wrapperElementId . '">(.+)<\/body><\/html>$/si', $result, $matches); return !empty($matches) ? $matches[1] : ''; } else { - $result = htmlspecialchars($data, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', false); + $result = htmlspecialchars($data, $this->htmlSpecialCharsFlag, 'UTF-8', false); } } else { $result = $data; @@ -217,7 +224,7 @@ public function escapeHtmlAttr($string, $escapeSingleQuote = true) if ($escapeSingleQuote) { return $this->getEscaper()->escapeHtmlAttr((string) $string); } - return htmlspecialchars((string)$string, ENT_COMPAT, 'UTF-8', false); + return htmlspecialchars((string)$string, $this->htmlSpecialCharsFlag, 'UTF-8', false); } /** @@ -314,7 +321,7 @@ public function escapeXssInUrl($data) { return htmlspecialchars( $this->escapeScriptIdentifiers((string)$data), - ENT_COMPAT | ENT_HTML5 | ENT_HTML401, + $this->htmlSpecialCharsFlag | ENT_HTML5 | ENT_HTML401, 'UTF-8', false ); @@ -351,7 +358,7 @@ public function escapeQuote($data, $addSlashes = false) if ($addSlashes === true) { $data = addslashes($data); } - return htmlspecialchars($data, ENT_QUOTES, null, false); + return htmlspecialchars($data, $this->htmlSpecialCharsFlag, null, false); } /** diff --git a/lib/internal/Magento/Framework/Filter/NormalizedToLocalized.php b/lib/internal/Magento/Framework/Filter/NormalizedToLocalized.php new file mode 100644 index 0000000000000..bd42c79486ee8 --- /dev/null +++ b/lib/internal/Magento/Framework/Filter/NormalizedToLocalized.php @@ -0,0 +1,13 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +namespace Magento\Framework\Filter; + +/** + * Class NormalizedToLocalized + */ +class NormalizedToLocalized extends \Zend_Filter_NormalizedToLocalized +{ +} diff --git a/lib/internal/Magento/Framework/Stdlib/Parameters.php b/lib/internal/Magento/Framework/Stdlib/Parameters.php new file mode 100644 index 0000000000000..9c9aac26a26d2 --- /dev/null +++ b/lib/internal/Magento/Framework/Stdlib/Parameters.php @@ -0,0 +1,15 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Framework\Stdlib; + +/** + * Class Parameters + */ +class Parameters extends \Zend\Stdlib\Parameters +{ +} diff --git a/lib/internal/Magento/Framework/Test/Unit/Data/Form/Element/HiddenTest.php b/lib/internal/Magento/Framework/Test/Unit/Data/Form/Element/HiddenTest.php index b57cb7ac8f0b2..953664455aaf9 100644 --- a/lib/internal/Magento/Framework/Test/Unit/Data/Form/Element/HiddenTest.php +++ b/lib/internal/Magento/Framework/Test/Unit/Data/Form/Element/HiddenTest.php @@ -21,7 +21,15 @@ class HiddenTest extends \PHPUnit\Framework\TestCase protected function setUp() { $objectManager = new ObjectManager($this); - $this->element = $objectManager->getObject(\Magento\Framework\Data\Form\Element\Hidden::class); + $escaper = $objectManager->getObject( + \Magento\Framework\Escaper::class + ); + $this->element = $objectManager->getObject( + \Magento\Framework\Data\Form\Element\Hidden::class, + [ + 'escaper' => $escaper + ] + ); } /** diff --git a/lib/internal/Magento/Framework/View/Element/Html/Date.php b/lib/internal/Magento/Framework/View/Element/Html/Date.php index 558e39427cb44..909938256b133 100644 --- a/lib/internal/Magento/Framework/View/Element/Html/Date.php +++ b/lib/internal/Magento/Framework/View/Element/Html/Date.php @@ -78,7 +78,7 @@ public function getEscapedValue() if ($this->getFormat() && $this->getValue()) { return strftime($this->getFormat(), strtotime($this->getValue())); } - return htmlspecialchars($this->getValue()); + return $this->escapeHtml($this->getValue()); } /** diff --git a/lib/internal/Magento/Framework/View/Page/Config.php b/lib/internal/Magento/Framework/View/Page/Config.php index da7bcb128f4b8..fdb7c673d3dda 100644 --- a/lib/internal/Magento/Framework/View/Page/Config.php +++ b/lib/internal/Magento/Framework/View/Page/Config.php @@ -54,6 +54,11 @@ class Config */ const HTML_ATTRIBUTE_LANG = 'lang'; + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * Allowed group of types * @@ -164,6 +169,7 @@ private function getAreaResolver() * @param Title $title * @param \Magento\Framework\Locale\ResolverInterface $localeResolver * @param bool $isIncludesAvailable + * @param \Magento\Framework\Escaper|null $escaper */ public function __construct( View\Asset\Repository $assetRepo, @@ -172,7 +178,8 @@ public function __construct( View\Page\FaviconInterface $favicon, Title $title, \Magento\Framework\Locale\ResolverInterface $localeResolver, - $isIncludesAvailable = true + $isIncludesAvailable = true, + \Magento\Framework\Escaper $escaper = null ) { $this->assetRepo = $assetRepo; $this->pageAssets = $pageAssets; @@ -186,6 +193,9 @@ public function __construct( self::HTML_ATTRIBUTE_LANG, strstr($this->localeResolver->getLocale(), '_', true) ); + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); } /** @@ -237,7 +247,7 @@ public function getTitle() public function setMetadata($name, $content) { $this->build(); - $this->metadata[$name] = htmlspecialchars($content); + $this->metadata[$name] = $this->escaper->escapeHtml($content); } /** diff --git a/lib/internal/Magento/Framework/View/Test/Unit/Page/ConfigTest.php b/lib/internal/Magento/Framework/View/Test/Unit/Page/ConfigTest.php index 5bada08bbd00f..49b3c38bdd8bd 100644 --- a/lib/internal/Magento/Framework/View/Test/Unit/Page/ConfigTest.php +++ b/lib/internal/Magento/Framework/View/Test/Unit/Page/ConfigTest.php @@ -19,6 +19,9 @@ */ class ConfigTest extends \PHPUnit\Framework\TestCase { + /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + private $objectManager; + /** * @var Config */ @@ -90,6 +93,10 @@ protected function setUp() $this->localeMock->expects($this->any()) ->method('getLocale') ->willReturn(Resolver::DEFAULT_LOCALE); + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $escaper = $this->objectManager->getObject( + \Magento\Framework\Escaper::class + ); $this->model = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) ->getObject( \Magento\Framework\View\Page\Config::class, @@ -98,7 +105,8 @@ protected function setUp() 'pageAssets' => $this->pageAssets, 'scopeConfig' => $this->scopeConfig, 'favicon' => $this->favicon, - 'localeResolver' => $this->localeMock + 'localeResolver' => $this->localeMock, + 'escaper' => $escaper ] ); diff --git a/setup/src/Magento/Setup/Model/DependencyReadinessCheck.php b/setup/src/Magento/Setup/Model/DependencyReadinessCheck.php index 4adb3a6a49b0d..95912272dfa4c 100644 --- a/setup/src/Magento/Setup/Model/DependencyReadinessCheck.php +++ b/setup/src/Magento/Setup/Model/DependencyReadinessCheck.php @@ -17,6 +17,11 @@ */ class DependencyReadinessCheck { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * @var ComposerJsonFinder */ @@ -49,18 +54,23 @@ class DependencyReadinessCheck * @param DirectoryList $directoryList * @param File $file * @param MagentoComposerApplicationFactory $composerAppFactory + * @param \Magento\Framework\Escaper|null $escaper */ public function __construct( ComposerJsonFinder $composerJsonFinder, DirectoryList $directoryList, File $file, - MagentoComposerApplicationFactory $composerAppFactory + MagentoComposerApplicationFactory $composerAppFactory, + \Magento\Framework\Escaper $escaper = null ) { $this->composerJsonFinder = $composerJsonFinder; $this->directoryList = $directoryList; $this->file = $file; $this->requireUpdateDryRunCommand = $composerAppFactory->createRequireUpdateDryRunCommand(); $this->magentoComposerApplication = $composerAppFactory->create(); + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); } /** @@ -91,7 +101,7 @@ public function runReadinessCheck(array $packages) $this->requireUpdateDryRunCommand->run($packages, $workingDir); return ['success' => true]; } catch (\RuntimeException $e) { - $message = str_replace(PHP_EOL, '<br/>', htmlspecialchars($e->getMessage())); + $message = str_replace(PHP_EOL, '<br/>', $this->escaper->escapeHtml($e->getMessage())); return ['success' => false, 'error' => $message]; } } diff --git a/setup/src/Magento/Setup/Model/UninstallDependencyCheck.php b/setup/src/Magento/Setup/Model/UninstallDependencyCheck.php index 757ee99f7f1ba..aa5821f0fc74e 100644 --- a/setup/src/Magento/Setup/Model/UninstallDependencyCheck.php +++ b/setup/src/Magento/Setup/Model/UninstallDependencyCheck.php @@ -15,6 +15,11 @@ */ class UninstallDependencyCheck { + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * @var ComposerInformation */ @@ -38,15 +43,20 @@ class UninstallDependencyCheck * @param ComposerInformation $composerInfo * @param DependencyChecker $dependencyChecker * @param ThemeDependencyCheckerFactory $themeDependencyCheckerFactory + * @param \Magento\Framework\Escaper|null $escaper */ public function __construct( ComposerInformation $composerInfo, DependencyChecker $dependencyChecker, - ThemeDependencyCheckerFactory $themeDependencyCheckerFactory + ThemeDependencyCheckerFactory $themeDependencyCheckerFactory, + \Magento\Framework\Escaper $escaper = null ) { $this->composerInfo = $composerInfo; $this->packageDependencyChecker = $dependencyChecker; $this->themeDependencyChecker = $themeDependencyCheckerFactory->create(); + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); } /** @@ -54,51 +64,62 @@ public function __construct( * * @param array $packages * @return array - * @throws \RuntimeException */ public function runUninstallReadinessCheck(array $packages) { try { - $packagesAndTypes = $this->composerInfo->getRootRequiredPackageTypesByName(); - $dependencies = $this->packageDependencyChecker->checkDependencies($packages, true); - $messages = []; - $themes = []; - - foreach ($packages as $package) { - if (!isset($packagesAndTypes[$package])) { - throw new \RuntimeException('Package ' . $package . ' not found in the system.'); - } + return $this->checkForMissingDependencies($packages); + } catch (\RuntimeException $e) { + $message = str_replace(PHP_EOL, '<br/>', $this->escaper->escapeHtml($e->getMessage())); + return ['success' => false, 'error' => $message]; + } + } - switch ($packagesAndTypes[$package]) { - case ComposerInformation::METAPACKAGE_PACKAGE_TYPE: - unset($dependencies[$package]); - break; - case ComposerInformation::THEME_PACKAGE_TYPE: - $themes[] = $package; - break; - } + /** + * Check for missing dependencies + * + * @param array $packages + * @return array + * @throws \RuntimeException + */ + private function checkForMissingDependencies(array $packages) + { + $packagesAndTypes = $this->composerInfo->getRootRequiredPackageTypesByName(); + $dependencies = $this->packageDependencyChecker->checkDependencies($packages, true); + $messages = []; + $themes = []; - if (!empty($dependencies[$package])) { - $messages[] = $package . " has the following dependent package(s): " - . implode(', ', $dependencies[$package]); - } + foreach ($packages as $package) { + if (!isset($packagesAndTypes[$package])) { + throw new \RuntimeException('Package ' . $package . ' not found in the system.'); } - if (!empty($themes)) { - $messages = array_merge( - $messages, - $this->themeDependencyChecker->checkChildThemeByPackagesName($themes) - ); + switch ($packagesAndTypes[$package]) { + case ComposerInformation::METAPACKAGE_PACKAGE_TYPE: + unset($dependencies[$package]); + break; + case ComposerInformation::THEME_PACKAGE_TYPE: + $themes[] = $package; + break; } - if (!empty($messages)) { - throw new \RuntimeException(implode(PHP_EOL, $messages)); + if (!empty($dependencies[$package])) { + $messages[] = $package . " has the following dependent package(s): " + . implode(', ', $dependencies[$package]); } + } - return ['success' => true]; - } catch (\RuntimeException $e) { - $message = str_replace(PHP_EOL, '<br/>', htmlspecialchars($e->getMessage())); - return ['success' => false, 'error' => $message]; + if (!empty($themes)) { + $messages = array_merge( + $messages, + $this->themeDependencyChecker->checkChildThemeByPackagesName($themes) + ); } + + if (!empty($messages)) { + throw new \RuntimeException(implode(PHP_EOL, $messages)); + } + + return ['success' => true]; } } From 168ffe90f1285956329caadd53ef1a63f9f9bd19 Mon Sep 17 00:00:00 2001 From: Cari Spruiell <spruiell@adobe.com> Date: Wed, 12 Jun 2019 22:22:55 -0500 Subject: [PATCH 1951/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - apply commits from 2.3 --- .../Magento/Reports/Block/Adminhtml/Grid.php | 4 +- .../Magento/Framework/Stdlib/Parameters.php | 96 ++++++++++++++++++- 2 files changed, 98 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Reports/Block/Adminhtml/Grid.php b/app/code/Magento/Reports/Block/Adminhtml/Grid.php index 674f2c081d0d5..08460bae20314 100644 --- a/app/code/Magento/Reports/Block/Adminhtml/Grid.php +++ b/app/code/Magento/Reports/Block/Adminhtml/Grid.php @@ -105,7 +105,9 @@ public function __construct( DecoderInterface::class ); - $this->parameters = $parameters ?? new Parameters(); + $this->parameters = $parameters ?? ObjectManager::getInstance()->get( + Parameters::class + ); parent::__construct($context, $backendHelper, $data); } diff --git a/lib/internal/Magento/Framework/Stdlib/Parameters.php b/lib/internal/Magento/Framework/Stdlib/Parameters.php index 9c9aac26a26d2..dcefaf85d390e 100644 --- a/lib/internal/Magento/Framework/Stdlib/Parameters.php +++ b/lib/internal/Magento/Framework/Stdlib/Parameters.php @@ -7,9 +7,103 @@ namespace Magento\Framework\Stdlib; +use Zend\Stdlib\Parameters as ZendParameters; + /** * Class Parameters */ -class Parameters extends \Zend\Stdlib\Parameters +class Parameters { + /** + * @var ZendParameters + */ + private $parameters; + + /** + * @param ZendParameters $parameters + */ + public function __construct( + ZendParameters $parameters + ) { + $this->parameters = $parameters; + } + + /** + * Populate from native PHP array + * + * @param array $values + * @return void + */ + public function fromArray(array $values) + { + $this->parameters->fromArray($values); + } + + /** + * Populate from query string + * + * @param string $string + * @return void + */ + public function fromString($string) + { + $this->parameters->fromString($string); + } + + /** + * Serialize to native PHP array + * + * @return array + */ + public function toArray() + { + return $this->parameters->toArray(); + } + + /** + * Serialize to query string + * + * @return string + */ + public function toString() + { + return $this->parameters->toString(); + } + + /** + * Retrieve by key + * + * Returns null if the key does not exist. + * + * @param string $name + * @return mixed + */ + public function offsetGet($name) + { + return $this->parameters->offsetGet($name); + } + + /** + * Get name + * + * @param string $name + * @param mixed $default optional default value + * @return mixed + */ + public function get($name, $default = null) + { + return $this->parameters->get($name, $default); + } + + /** + * Set name + * + * @param string $name + * @param mixed $value + * @return \Zend\Stdlib\Parameters + */ + public function set($name, $value) + { + return $this->parameters->set($name, $value); + } } From e38213a1e982d107a830ac7c0a567ba678d721cb Mon Sep 17 00:00:00 2001 From: Viktor Petryk <victor.petryk@transoftgroup.com> Date: Thu, 13 Jun 2019 14:08:17 +0300 Subject: [PATCH 1952/2092] MC-17385: Eliminate @escapeNotVerified in Product and Catalog Rules Modules --- .../view/adminhtml/templates/promo/fieldset.phtml | 2 +- .../view/adminhtml/templates/promo/form.phtml | 3 +-- .../Msrp/view/base/templates/product/price/msrp.phtml | 2 -- .../templates/render/item/price_msrp_item.phtml | 10 ++++------ 4 files changed, 6 insertions(+), 11 deletions(-) diff --git a/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/fieldset.phtml b/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/fieldset.phtml index 69199af271477..db5492d3c47c5 100644 --- a/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/fieldset.phtml +++ b/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/fieldset.phtml @@ -11,7 +11,7 @@ <div class="rule-tree"> <fieldset id="<?= $block->escapeHtmlAttr($_jsObjectName) ?>" <?= /* @noEscape */ $_element->serialize(['class']) ?> class="fieldset"> - <legend class="legend"><span><?= $block->escapeHtmlAttr($_element->getLegend()) ?></span></legend> + <legend class="legend"><span><?= $block->escapeHtml($_element->getLegend()) ?></span></legend> <br> <?php if ($_element->getComment()) : ?> <div class="messages"> diff --git a/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/form.phtml b/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/form.phtml index 562e27c61b4c0..4ed782edd4eec 100644 --- a/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/form.phtml +++ b/app/code/Magento/CatalogRule/view/adminhtml/templates/promo/form.phtml @@ -5,6 +5,5 @@ */ ?> <div class="entry-edit rule-tree"> - <?= $block->getFormHtml() ?> +<?= $block->getFormHtml() ?> </div> - diff --git a/app/code/Magento/Msrp/view/base/templates/product/price/msrp.phtml b/app/code/Magento/Msrp/view/base/templates/product/price/msrp.phtml index 62e79be353230..80d7cdb4fcaac 100644 --- a/app/code/Magento/Msrp/view/base/templates/product/price/msrp.phtml +++ b/app/code/Magento/Msrp/view/base/templates/product/price/msrp.phtml @@ -98,9 +98,7 @@ $priceElementIdPrefix = $block->getPriceElementIdPrefix() ? $block->getPriceElem <a href="javascript:void(0);" id="<?= /* @noEscape */ ($popupId) ?>" class="action map-show-info" - <?php // phpcs:disable ?> data-mage-init='<?= /* @noEscape */ $this->helper(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($data) ?>'> - <?php //phpcs:enable ?> <?= $block->escapeHtml(__('Click for price')) ?> </a> <?php else : ?> diff --git a/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_item.phtml b/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_item.phtml index 8a08be0a6caf1..145df32a49c38 100644 --- a/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_item.phtml +++ b/app/code/Magento/Msrp/view/frontend/templates/render/item/price_msrp_item.phtml @@ -13,14 +13,12 @@ */ ?> <?php - // phpcs:disable - /** @var $pricingHelper \Magento\Framework\Pricing\Helper\Data */ + /** @var \Magento\Framework\Pricing\Helper\Data $pricingHelper */ $pricingHelper = $this->helper(\Magento\Framework\Pricing\Helper\Data::class); - /** @var $_catalogHelper \Magento\Catalog\Helper\Data */ + /** @var \Magento\Catalog\Helper\Data $_catalogHelper */ $_catalogHelper = $this->helper(\Magento\Catalog\Helper\Data::class); - // phpcs:enable - /** @var $_product \Magento\Catalog\Model\Product */ + /** @var \Magento\Catalog\Model\Product $_product */ $_product = $block->getProduct(); $_id = $_product->getId(); $_msrpPrice = ''; @@ -53,7 +51,7 @@ <?php $helpLinkId = 'msrp-help-' . $_id . $block->getRandomString(20); ?> <a href="javascript:void(0);" id="<?= /* @noEscape */ ($helpLinkId) ?>" data-mage-init='{"addToCart":{"helpLinkId": "#<?= /* @noEscape */ ($helpLinkId) ?>", - "productName": "<?= /* @noEscape */ $block->escapeJs($block->escapeHtml($_product->getName())) ?>"}}' + "productName": "<?= $block->escapeJs($block->escapeHtml($_product->getName())) ?>"}}' class="link tip"> <?= $block->escapeHtml(__("What's this?")) ?> </a> From 22dfd0604cecee6d68a833527399a9342e94e5d9 Mon Sep 17 00:00:00 2001 From: Dave Macaulay <macaulay@adobe.com> Date: Thu, 13 Jun 2019 09:55:19 -0500 Subject: [PATCH 1953/2092] MC-17242: Eliminate @escapeNotVerified in Sales-related Modules - Resolve CR comments --- .../view/adminhtml/templates/order/create/form/address.phtml | 2 +- .../Magento/Sales/view/frontend/templates/order/items.phtml | 2 +- .../Magento/Sales/view/frontend/templates/order/recent.phtml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml index 0cdaf9ecccc0c..606c2d00fef79 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/form/address.phtml @@ -86,7 +86,7 @@ endif; ?> <?= $block->getForm()->toHtml() ?> <div class="admin__field admin__field-option order-save-in-address-book"> - <input name="<?= $block->escapeHtmlAttr($block->getForm()->getHtmlNamePrefix()) ?>[save_in_address_book]" type="checkbox" id="<?= $block->escapeHtmlAttr($block->getForm()->getHtmlIdPrefix()) ?>save_in_address_book" value="1"<?php if (!$block->getDontSaveInAddressBook()) : ?> checked="checked"<?php endif; ?> class="admin__control-checkbox"/> + <input name="<?= $block->escapeHtmlAttr($block->getForm()->getHtmlNamePrefix()) ?>[save_in_address_book]" type="checkbox" id="<?= $block->escapeHtmlAttr($block->getForm()->getHtmlIdPrefix()) ?>save_in_address_book" value="1"<?php if (!$block->getDontSaveInAddressBook() && $block->getAddress()->getSaveInAddressBook()) : ?> checked="checked"<?php endif; ?> class="admin__control-checkbox"/> <label for="<?= $block->escapeHtmlAttr($block->getForm()->getHtmlIdPrefix()) ?>save_in_address_book" class="admin__field-label"><?= $block->escapeHtml(__('Save in address book')) ?></label> </div> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/items.phtml b/app/code/Magento/Sales/view/frontend/templates/order/items.phtml index 98a1f1ebb7545..a99d90c8c310d 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/items.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/items.phtml @@ -9,7 +9,7 @@ /** @var \Magento\Sales\Block\Order\Items $block */ ?> <div class="table-wrapper order-items"> - <table class="data table table-order-items" id="my-orders-table" summary="<?= $block->escapeHtml(__('Items Ordered')) ?>"> + <table class="data table table-order-items" id="my-orders-table" summary="<?= $block->escapeHtmlAttr(__('Items Ordered')) ?>"> <caption class="table-caption"><?= $block->escapeHtml(__('Items Ordered')) ?></caption> <thead> <?php if ($block->isPagerDisplayed()) : ?> diff --git a/app/code/Magento/Sales/view/frontend/templates/order/recent.phtml b/app/code/Magento/Sales/view/frontend/templates/order/recent.phtml index 0702724e79e38..e87b33b39da2f 100644 --- a/app/code/Magento/Sales/view/frontend/templates/order/recent.phtml +++ b/app/code/Magento/Sales/view/frontend/templates/order/recent.phtml @@ -41,7 +41,7 @@ <?php foreach ($_orders as $_order) : ?> <tr> <td data-th="<?= $block->escapeHtml(__('Order #')) ?>" class="col id"><?= $block->escapeHtml($_order->getRealOrderId()) ?></td> - <td data-th="<?= $block->escapeHtml(__('Date')) ?>" class="col date"><?= $block->escapeHtml($block->formatDate($_order->getCreatedAt())) ?></td> + <td data-th="<?= $block->escapeHtml(__('Date')) ?>" class="col date"><?= /* @noEscape */ $block->formatDate($_order->getCreatedAt()) ?></td> <td data-th="<?= $block->escapeHtml(__('Ship To')) ?>" class="col shipping"><?= $_order->getShippingAddress() ? $block->escapeHtml($_order->getShippingAddress()->getName()) : " " ?></td> <td data-th="<?= $block->escapeHtml(__('Order Total')) ?>" class="col total"><?= /* @noEscape */ $_order->formatPrice($_order->getGrandTotal()) ?></td> <td data-th="<?= $block->escapeHtml(__('Status')) ?>" class="col status"><?= $block->escapeHtml($_order->getStatusLabel()) ?></td> From b722fca9aa4c91d72a35bee579b9aae917d18763 Mon Sep 17 00:00:00 2001 From: Dmytro Poperechnyy <dpoperechnyy@magento.com> Date: Thu, 13 Jun 2019 10:06:07 -0500 Subject: [PATCH 1954/2092] MC-17449: Deliver CSS critical path to 2.2.x - Remove void return type; - Fix cyclomatic complexity; --- .../Controller/Result/AsyncCssPlugin.php | 2 +- .../View/Page/Config/Reader/Head.php | 77 +++++++++++-------- 2 files changed, 46 insertions(+), 33 deletions(-) diff --git a/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php b/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php index 3ad9408306892..ddddb2002ec4f 100644 --- a/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php +++ b/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php @@ -37,7 +37,7 @@ public function __construct(ScopeConfigInterface $scopeConfig) * @param Http $subject * @return void */ - public function beforeSendResponse(Http $subject): void + public function beforeSendResponse(Http $subject) { $content = $subject->getContent(); diff --git a/lib/internal/Magento/Framework/View/Page/Config/Reader/Head.php b/lib/internal/Magento/Framework/View/Page/Config/Reader/Head.php index 3b8de974b2a26..e8c4f345625de 100644 --- a/lib/internal/Magento/Framework/View/Page/Config/Reader/Head.php +++ b/lib/internal/Magento/Framework/View/Page/Config/Reader/Head.php @@ -7,6 +7,7 @@ use Magento\Framework\View\Layout; use Magento\Framework\View\Page\Config as PageConfig; +use Magento\Framework\View\Page\Config\Structure; /** * Head structure reader is intended for collecting assets, title and metadata @@ -85,43 +86,55 @@ function (Layout\Element $current, Layout\Element $next) { ); foreach ($nodes as $node) { - switch ($node->getName()) { - case self::HEAD_CSS: - case self::HEAD_SCRIPT: - case self::HEAD_LINK: - case self::HEAD_FONT: - $this->addContentTypeByNodeName($node); - $pageConfigStructure->addAssets($node->getAttribute('src'), $this->getAttributes($node)); - break; - - case self::HEAD_REMOVE: - $pageConfigStructure->removeAssets($node->getAttribute('src')); - break; - - case self::HEAD_TITLE: - $pageConfigStructure->setTitle(new \Magento\Framework\Phrase($node)); - break; - - case self::HEAD_META: - $this->setMetadata($pageConfigStructure, $node); - break; - - case self::HEAD_ATTRIBUTE: - $pageConfigStructure->setElementAttribute( - PageConfig::ELEMENT_TYPE_HEAD, - $node->getAttribute('name'), - $node->getAttribute('value') - ); - break; - - default: - break; - } + $this->processNode($node, $pageConfigStructure); } return $this; } + /** + * Process given node based on it's name. + * + * @param Layout\Element $node + * @param Structure $pageConfigStructure + * @return void + */ + private function processNode(Layout\Element $node, Structure $pageConfigStructure) + { + switch ($node->getName()) { + case self::HEAD_CSS: + case self::HEAD_SCRIPT: + case self::HEAD_LINK: + case self::HEAD_FONT: + $this->addContentTypeByNodeName($node); + $pageConfigStructure->addAssets($node->getAttribute('src'), $this->getAttributes($node)); + break; + + case self::HEAD_REMOVE: + $pageConfigStructure->removeAssets($node->getAttribute('src')); + break; + + case self::HEAD_TITLE: + $pageConfigStructure->setTitle(new \Magento\Framework\Phrase($node)); + break; + + case self::HEAD_META: + $this->setMetadata($pageConfigStructure, $node); + break; + + case self::HEAD_ATTRIBUTE: + $pageConfigStructure->setElementAttribute( + PageConfig::ELEMENT_TYPE_HEAD, + $node->getAttribute('name'), + $node->getAttribute('value') + ); + break; + + default: + break; + } + } + /** * Get all attributes for current dom element * From 6ef8772eef9a6b8e9c58683de912c769f57bdc6c Mon Sep 17 00:00:00 2001 From: Cari Spruiell <spruiell@adobe.com> Date: Thu, 13 Jun 2019 10:54:16 -0500 Subject: [PATCH 1955/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - add static test to prohibit use of htmlspecialchars - refactor remaining usages of htmlspecialchars --- .../Customer/Model/Address/AbstractAddress.php | 14 ++++++++++++-- .../Magento/Paypal/Controller/ExpressTest.php | 7 ++++--- .../_files/security/unsecure_php_functions.php | 4 ++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/app/code/Magento/Customer/Model/Address/AbstractAddress.php b/app/code/Magento/Customer/Model/Address/AbstractAddress.php index db3436c441ec2..5d0e1e7463819 100644 --- a/app/code/Magento/Customer/Model/Address/AbstractAddress.php +++ b/app/code/Magento/Customer/Model/Address/AbstractAddress.php @@ -119,6 +119,11 @@ class AbstractAddress extends AbstractExtensibleModel implements AddressModelInt */ protected $dataObjectHelper; + /** + * @var \Magento\Framework\Escaper + */ + private $escaper; + /** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry @@ -135,6 +140,7 @@ class AbstractAddress extends AbstractExtensibleModel implements AddressModelInt * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * @param \Magento\Framework\Escaper|null $escaper * @param array $data * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -154,6 +160,7 @@ public function __construct( \Magento\Framework\Api\DataObjectHelper $dataObjectHelper, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, + \Magento\Framework\Escaper $escaper = null, array $data = [] ) { $this->_directoryData = $directoryData; @@ -166,6 +173,9 @@ public function __construct( $this->addressDataFactory = $addressDataFactory; $this->regionDataFactory = $regionDataFactory; $this->dataObjectHelper = $dataObjectHelper; + $this->escaper = $escaper ?? \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\Escaper::class + ); parent::__construct( $context, $registry, @@ -629,7 +639,7 @@ public function validate() 'Invalid value of "%value" provided for the %fieldName field.', [ 'fieldName' => 'countryId', - 'value' => htmlspecialchars($countryId) + 'value' => $this->escaper->escapeHtml($countryId) ] ); } else { @@ -654,7 +664,7 @@ public function validate() 'Invalid value of "%value" provided for the %fieldName field.', [ 'fieldName' => 'regionId', - 'value' => htmlspecialchars($regionId) + 'value' => $this->escaper->escapeHtml($regionId) ] ); } diff --git a/dev/tests/integration/testsuite/Magento/Paypal/Controller/ExpressTest.php b/dev/tests/integration/testsuite/Magento/Paypal/Controller/ExpressTest.php index d10befc3a811c..7cae512207b36 100644 --- a/dev/tests/integration/testsuite/Magento/Paypal/Controller/ExpressTest.php +++ b/dev/tests/integration/testsuite/Magento/Paypal/Controller/ExpressTest.php @@ -235,6 +235,8 @@ public function testReturnAction() */ public function testPlaceOrderZeroGrandTotal() { + /** @var \Magento\Framework\Escaper $escaper */ + $escaper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Escaper::class); /** @var Quote $quote */ $quote = $this->_objectManager->create(Quote::class); $quote->load('test01', 'reserved_order_id'); @@ -254,10 +256,9 @@ public function testPlaceOrderZeroGrandTotal() $this->assertSessionMessages( $this->equalTo( [ - htmlspecialchars( + $escaper->escapeHtml( (string)__('PayPal can\'t process orders with a zero balance due. ' - . 'To finish your purchase, please go through the standard checkout process.'), - ENT_QUOTES + . 'To finish your purchase, please go through the standard checkout process.') ) ] ), diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php index 51cc820d0fc3a..4b80c13a4e75d 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php @@ -68,4 +68,8 @@ 'replacement' => '', 'exclude' => [] ], + 'htmlspecialchars' => [ + 'replacement' => '\Magento\Framework\Escaper::escapeHtml', + 'exclude' => [] + ], ]; From eb6dd10aef16114dd7075ac94ee4a30520091dea Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Thu, 13 Jun 2019 11:30:47 -0500 Subject: [PATCH 1956/2092] Merge branch '2.2-tests-pr' into MC-10141 fix merge conflict --- .../Catalog/Test/Mftf/Section/AdminProductFormSection.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml index bbddfee9978dd..52ed81285bd09 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml @@ -49,6 +49,8 @@ <element name="done" type="button" selector=".admin__action-multiselect-actions-wrap button" timeout="30"/> <element name="save" type="button" selector="#save-button"/> <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button" parameterized="true" timeout="30"/> + <element name="enableProductLabel" type="checkbox" selector=".admin__actions-switch > input[name='product[status]']+label"/> + <element name="selectCategory" type="input" selector="//label[contains(., '{{categoryName}}')]" parameterized="true"/> </section> <section name="ProductInWebsitesSection"> <element name="sectionHeader" type="button" selector="div[data-index='websites']" timeout="30"/> From 2c2725acd3e42ae1a0c69befcdf56a1ad6e86fe1 Mon Sep 17 00:00:00 2001 From: Cari Spruiell <spruiell@adobe.com> Date: Thu, 13 Jun 2019 11:41:49 -0500 Subject: [PATCH 1957/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - clean up code --- app/code/Magento/Customer/Model/Address/AbstractAddress.php | 6 +++--- app/code/Magento/Reports/Block/Adminhtml/Grid.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/code/Magento/Customer/Model/Address/AbstractAddress.php b/app/code/Magento/Customer/Model/Address/AbstractAddress.php index 5d0e1e7463819..09b3540f2b689 100644 --- a/app/code/Magento/Customer/Model/Address/AbstractAddress.php +++ b/app/code/Magento/Customer/Model/Address/AbstractAddress.php @@ -140,8 +140,8 @@ class AbstractAddress extends AbstractExtensibleModel implements AddressModelInt * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection - * @param \Magento\Framework\Escaper|null $escaper * @param array $data + * @param \Magento\Framework\Escaper|null $escaper * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -160,8 +160,8 @@ public function __construct( \Magento\Framework\Api\DataObjectHelper $dataObjectHelper, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - \Magento\Framework\Escaper $escaper = null, - array $data = [] + array $data = [], + \Magento\Framework\Escaper $escaper = null ) { $this->_directoryData = $directoryData; $data = $this->_implodeArrayField($data); diff --git a/app/code/Magento/Reports/Block/Adminhtml/Grid.php b/app/code/Magento/Reports/Block/Adminhtml/Grid.php index 08460bae20314..ff1dc4efa2060 100644 --- a/app/code/Magento/Reports/Block/Adminhtml/Grid.php +++ b/app/code/Magento/Reports/Block/Adminhtml/Grid.php @@ -92,7 +92,7 @@ class Grid extends \Magento\Backend\Block\Widget\Grid * @param Data $backendHelper * @param array $data * @param DecoderInterface|null $urlDecoder - * @param Parameters $parameters + * @param Parameters|null $parameters */ public function __construct( Context $context, From fda01facbd6c82c3faf98c965f8df56ea6bcaee7 Mon Sep 17 00:00:00 2001 From: Hwashiang Yu <hwyu@adobe.com> Date: Thu, 13 Jun 2019 12:57:18 -0500 Subject: [PATCH 1958/2092] MC-17487: Calendar template update - Updated calendar template --- .../view/frontend/templates/js/calendar.phtml | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml b/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml index 6df2b10ac34b3..f637ae1208594 100644 --- a/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml +++ b/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml @@ -21,20 +21,20 @@ require([ //<![CDATA[ $.extend(true, $, { calendarConfig: { - dayNames: <?= $block->escapeJs($days['wide']) ?>, - dayNamesMin: <?= $block->escapeJs($days['abbreviated']) ?>, - monthNames: <?= $block->escapeJs($months['wide']) ?>, - monthNamesShort: <?= $block->escapeJs($months['abbreviated']) ?>, - infoTitle: "<?= $block->escapeJs(__('About the calendar')) ?>", - firstDay: <?= $block->escapeJs($firstDay) ?>, - closeText: "<?= $block->escapeJs(__('Close')) ?>", - currentText: "<?= $block->escapeJs(__('Go Today')) ?>", - prevText: "<?= $block->escapeJs(__('Previous')) ?>", - nextText: "<?= $block->escapeJs(__('Next')) ?>", - weekHeader: "<?= $block->escapeJs(__('WK')) ?>", - timeText: "<?= $block->escapeJs(__('Time')) ?>", - hourText: "<?= $block->escapeJs(__('Hour')) ?>", - minuteText: "<?= $block->escapeJs(__('Minute')) ?>", + dayNames: <?= /* @noEscape */ $days['wide'] ?>, + dayNamesMin: <?= /* @noEscape */ $days['abbreviated'] ?>, + monthNames: <?= /* @noEscape */ $months['wide'] ?>, + monthNamesShort: <?= /* @noEscape */ $months['abbreviated'] ?>, + infoTitle: "<?= /* @noEscape */ __('About the calendar') ?>", + firstDay: <?= /* @noEscape */ $firstDay ?>, + closeText: "<?= /* @noEscape */ __('Close') ?>", + currentText: "<?= /* @noEscape */ __('Go Today') ?>", + prevText: "<?= /* @noEscape */ __('Previous') ?>", + nextText: "<?= /* @noEscape */ __('Next') ?>", + weekHeader: "<?= /* @noEscape */ __('WK') ?>", + timeText: "<?= /* @noEscape */ __('Time') ?>", + hourText: "<?= /* @noEscape */ __('Hour') ?>", + minuteText: "<?= /* @noEscape */ __('Minute') ?>", dateFormat: $.datepicker.RFC_2822, showOn: "button", showAnim: "", From 7be090acdd2c76594b0b7734c95b2919dcae6389 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Thu, 13 Jun 2019 13:16:21 -0500 Subject: [PATCH 1959/2092] MC-7438: Checkout with 'Table Rates' for different states of the USA --- .../LoginToStorefrontActionGroup.xml | 2 +- ...esShippingMethodForDifferentStatesTest.xml | 20 +++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/LoginToStorefrontActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/LoginToStorefrontActionGroup.xml index 703b9f542f81a..a77f17ed4382c 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/LoginToStorefrontActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/LoginToStorefrontActionGroup.xml @@ -12,7 +12,7 @@ <argument name="Customer"/> </arguments> <amOnPage url="{{StorefrontCustomerSignInPage.url}}" stepKey="amOnSignInPage"/> - <waitForPageLoad time="30" stepKey="waitPageFullyLoaded"/> + <waitForPageLoad stepKey="waitPageFullyLoaded"/> <waitForElementVisible selector="{{StorefrontCustomerSignInFormSection.emailField}}" stepKey="waitFormAppears"/> <fillField userInput="{{Customer.email}}" selector="{{StorefrontCustomerSignInFormSection.emailField}}" stepKey="fillEmail"/> <fillField userInput="{{Customer.password}}" selector="{{StorefrontCustomerSignInFormSection.passwordField}}" stepKey="fillPassword"/> diff --git a/app/code/Magento/Shipping/Test/Mftf/Test/TableRatesShippingMethodForDifferentStatesTest.xml b/app/code/Magento/Shipping/Test/Mftf/Test/TableRatesShippingMethodForDifferentStatesTest.xml index fa0d4ca5ebe10..22b10a16da3cc 100644 --- a/app/code/Magento/Shipping/Test/Mftf/Test/TableRatesShippingMethodForDifferentStatesTest.xml +++ b/app/code/Magento/Shipping/Test/Mftf/Test/TableRatesShippingMethodForDifferentStatesTest.xml @@ -35,6 +35,16 @@ <!-- Delete customer --> <deleteData createDataKey="createCustomer" stepKey="deleteCustomer"/> + <!-- Rollback config --> + <actionGroup ref="AdminOpenShippingMethodsConfigPageActionGroup" stepKey="openShippingMethodSystemConfigPage"/> + <actionGroup ref="AdminSwitchWebsiteByNameActionGroup" stepKey="AdminSwitchStoreViewToMainWebsite"> + <argument name="website" value="_defaultWebsite"/> + </actionGroup> + <actionGroup ref="AdminChangeTableRatesShippingMethodStatusActionGroup" stepKey="disableTableRatesShippingMethod"> + <argument name="status" value="0"/> + </actionGroup> + <actionGroup ref="AdminSaveConfigActionGroup" stepKey="saveSystemConfig"/> + <!-- Log out --> <actionGroup ref="logout" stepKey="logout"/> </after> @@ -100,15 +110,5 @@ <argument name="methodName" value="{{TableRatesWeightVSDestination.methodName}}"/> <argument name="price" value="{{TableRatesWeightVSDestination.price}}"/> </actionGroup> - - <!-- Rollback config --> - <actionGroup ref="AdminOpenShippingMethodsConfigPageActionGroup" stepKey="openShippingMethodSystemConfigPage"/> - <actionGroup ref="AdminSwitchWebsiteByNameActionGroup" stepKey="AdminSwitchStoreViewToMainWebsite"> - <argument name="website" value="_defaultWebsite"/> - </actionGroup> - <actionGroup ref="AdminChangeTableRatesShippingMethodStatusActionGroup" stepKey="disableTableRatesShippingMethod"> - <argument name="status" value="0"/> - </actionGroup> - <actionGroup ref="AdminSaveConfigActionGroup" stepKey="saveSystemConfig"/> </test> </tests> From cfabc8a1fd6f077dd981709571ad72fb48d4aacb Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Thu, 13 Jun 2019 13:17:21 -0500 Subject: [PATCH 1960/2092] MC-7710: There is no XSS vulnerability if Create Order with sample email --- .../Section/StorefrontCheckoutCheckoutCustomerLoginSection.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutCheckoutCustomerLoginSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutCheckoutCustomerLoginSection.xml index afb660ecb057b..174b91434931e 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutCheckoutCustomerLoginSection.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Section/StorefrontCheckoutCheckoutCustomerLoginSection.xml @@ -11,6 +11,6 @@ <section name="StorefrontCheckoutCheckoutCustomerLoginSection"> <element name="email" type="input" selector="form[data-role='email-with-possible-login'] input[name='username']"/> <element name="emailErrorMessage" type="text" selector="#customer-email-error"/> - <element name="emailTooltipButton" type="button" selector="//form[@data-role='email-with-possible-login']//div[input[@name='username']]//*[contains(@class, 'action-help')]"/> + <element name="emailTooltipButton" type="button" selector="#customer-email-fieldset .field-tooltip-action"/> </section> </sections> From 86109e38ddce960b7170f58bb54541c3bf6aa86c Mon Sep 17 00:00:00 2001 From: Cari Spruiell <spruiell@adobe.com> Date: Thu, 13 Jun 2019 13:19:43 -0500 Subject: [PATCH 1961/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - clean up code --- app/code/Magento/Catalog/Block/Adminhtml/Product/Edit.php | 7 ++----- .../Magento/Email/Block/Adminhtml/Template/Preview.php | 1 + .../Newsletter/Block/Adminhtml/Template/Preview.php | 1 + app/code/Magento/Reports/Block/Adminhtml/Grid.php | 1 + .../Magento/Tax/Controller/Adminhtml/Rate/AjaxSave.php | 3 +-- .../Test/Legacy/_files/security/unsecure_php_functions.php | 4 +++- 6 files changed, 9 insertions(+), 8 deletions(-) diff --git a/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit.php b/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit.php index bef8ff9cf9112..95ccd2ed3e726 100644 --- a/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit.php +++ b/app/code/Magento/Catalog/Block/Adminhtml/Product/Edit.php @@ -3,17 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +namespace Magento\Catalog\Block\Adminhtml\Product; /** * Customer edit block * * @author Magento Core Team <core@magentocommerce.com> * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -namespace Magento\Catalog\Block\Adminhtml\Product; - -/** - * Class Edit + * @SuppressWarnings(PHPMD.RequestAwareBlockMethod) */ class Edit extends \Magento\Backend\Block\Widget { diff --git a/app/code/Magento/Email/Block/Adminhtml/Template/Preview.php b/app/code/Magento/Email/Block/Adminhtml/Template/Preview.php index 1ea6e3f921bc6..9096e6c5d9048 100644 --- a/app/code/Magento/Email/Block/Adminhtml/Template/Preview.php +++ b/app/code/Magento/Email/Block/Adminhtml/Template/Preview.php @@ -16,6 +16,7 @@ * * @api * @since 100.0.2 + * @SuppressWarnings(PHPMD.RequestAwareBlockMethod) */ class Preview extends \Magento\Backend\Block\Widget { diff --git a/app/code/Magento/Newsletter/Block/Adminhtml/Template/Preview.php b/app/code/Magento/Newsletter/Block/Adminhtml/Template/Preview.php index 58a904248e978..437d5f522cd2e 100644 --- a/app/code/Magento/Newsletter/Block/Adminhtml/Template/Preview.php +++ b/app/code/Magento/Newsletter/Block/Adminhtml/Template/Preview.php @@ -10,6 +10,7 @@ * * @api * @since 100.0.2 + * @SuppressWarnings(PHPMD.RequestAwareBlockMethod) */ class Preview extends \Magento\Backend\Block\Widget { diff --git a/app/code/Magento/Reports/Block/Adminhtml/Grid.php b/app/code/Magento/Reports/Block/Adminhtml/Grid.php index ff1dc4efa2060..5538ad6f53d4e 100644 --- a/app/code/Magento/Reports/Block/Adminhtml/Grid.php +++ b/app/code/Magento/Reports/Block/Adminhtml/Grid.php @@ -18,6 +18,7 @@ * @api * @author Magento Core Team <core@magentocommerce.com> * @since 100.0.2 + * @SuppressWarnings(PHPMD.RequestAwareBlockMethod) */ class Grid extends \Magento\Backend\Block\Widget\Grid { diff --git a/app/code/Magento/Tax/Controller/Adminhtml/Rate/AjaxSave.php b/app/code/Magento/Tax/Controller/Adminhtml/Rate/AjaxSave.php index 572eaa55abbb5..465f66357802b 100644 --- a/app/code/Magento/Tax/Controller/Adminhtml/Rate/AjaxSave.php +++ b/app/code/Magento/Tax/Controller/Adminhtml/Rate/AjaxSave.php @@ -6,7 +6,6 @@ */ namespace Magento\Tax\Controller\Adminhtml\Rate; -use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Backend\App\Action\Context; use Magento\Framework\Registry; use Magento\Tax\Model\Calculation\Rate\Converter; @@ -17,7 +16,7 @@ /** * Tax Rate AjaxSave Controller */ -class AjaxSave extends \Magento\Tax\Controller\Adminhtml\Rate implements HttpPostActionInterface +class AjaxSave extends \Magento\Tax\Controller\Adminhtml\Rate { /** * @var Escaper diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php index 4b80c13a4e75d..ec75381c7098b 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php @@ -70,6 +70,8 @@ ], 'htmlspecialchars' => [ 'replacement' => '\Magento\Framework\Escaper::escapeHtml', - 'exclude' => [] + 'exclude' => [ + ['type' => 'library', 'name' => 'magento/framework', 'path' => 'Escaper.php'], + ] ], ]; From dff87785ce0eb6ba16247b49c27d7cffe6a7cf14 Mon Sep 17 00:00:00 2001 From: Dave Macaulay <macaulay@adobe.com> Date: Thu, 13 Jun 2019 13:21:19 -0500 Subject: [PATCH 1962/2092] MC-17242: Eliminate @escapeNotVerified in Sales-related Modules - Resolve usage of single underscore translations --- .../adminhtml/templates/catalog/product/helper/gallery.phtml | 2 +- .../Checkout/view/frontend/templates/onepage/failure.phtml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/helper/gallery.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/helper/gallery.phtml index 611262ac94f8e..60dad8f7bc67c 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/helper/gallery.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/helper/gallery.phtml @@ -173,7 +173,7 @@ $formName = $block->getFormName(); <label class="admin__field-label"> <span><?= $block->escapeHtml(__('Image Size')) ?></span> </label> - <div class="admin__field-value" data-message="<?= $block->escapeHtmlAttr(_('{size}')) ?>"></div> + <div class="admin__field-value" data-message="<?= $block->escapeHtmlAttr(__('{size}')) ?>"></div> </div> <div class="admin__field admin__field-inline field-image-resolution" data-role="resolution"> diff --git a/app/code/Magento/Checkout/view/frontend/templates/onepage/failure.phtml b/app/code/Magento/Checkout/view/frontend/templates/onepage/failure.phtml index 3888ec6504982..ace2b0464171c 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/onepage/failure.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/onepage/failure.phtml @@ -13,7 +13,7 @@ <p><?= $block->escapeHtml($error) ?></p> <?php endif ?> <p><?= $block->escapeHtml( - _('Click <a href="%1">here</a> to continue shopping.', $block->escapeUrl($block->getContinueShoppingUrl())), + __('Click <a href="%1">here</a> to continue shopping.', $block->escapeUrl($block->getContinueShoppingUrl())), ['a'] ) ?> </p> From 350a44cb2ef9db4e467284fd67e40bdf486efef1 Mon Sep 17 00:00:00 2001 From: Hwashiang Yu <hwyu@adobe.com> Date: Thu, 13 Jun 2019 13:23:49 -0500 Subject: [PATCH 1963/2092] MC-17487: Calendar template update - Updated calendar template --- .../view/frontend/templates/js/calendar.phtml | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml b/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml index f637ae1208594..7044c1e2d6f66 100644 --- a/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml +++ b/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml @@ -25,16 +25,16 @@ require([ dayNamesMin: <?= /* @noEscape */ $days['abbreviated'] ?>, monthNames: <?= /* @noEscape */ $months['wide'] ?>, monthNamesShort: <?= /* @noEscape */ $months['abbreviated'] ?>, - infoTitle: "<?= /* @noEscape */ __('About the calendar') ?>", - firstDay: <?= /* @noEscape */ $firstDay ?>, - closeText: "<?= /* @noEscape */ __('Close') ?>", - currentText: "<?= /* @noEscape */ __('Go Today') ?>", - prevText: "<?= /* @noEscape */ __('Previous') ?>", - nextText: "<?= /* @noEscape */ __('Next') ?>", - weekHeader: "<?= /* @noEscape */ __('WK') ?>", - timeText: "<?= /* @noEscape */ __('Time') ?>", - hourText: "<?= /* @noEscape */ __('Hour') ?>", - minuteText: "<?= /* @noEscape */ __('Minute') ?>", + infoTitle: "<?= $block->escapeJs(__('About the calendar')) ?>", + firstDay: <?= (int)$firstDay ?>, + closeText: "<?= $block->escapeJs(__('Close')) ?>", + currentText: "<?= $block->escapeJs(__('Go Today')) ?>", + prevText: "<?= $block->escapeJs(__('Previous')) ?>", + nextText: "<?= $block->escapeJs(__('Next')) ?>", + weekHeader: "<?= $block->escapeJs(__('WK')) ?>", + timeText: "<?= $block->escapeJs(__('Time')) ?>", + hourText: "<?= $block->escapeJs(__('Hour')) ?>", + minuteText: "<?= $block->escapeJs(__('Minute')) ?>", dateFormat: $.datepicker.RFC_2822, showOn: "button", showAnim: "", From d75c5519d516469b5a6e7ac370a3665bde517233 Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Thu, 13 Jun 2019 14:04:21 -0500 Subject: [PATCH 1964/2092] MC-8893: Checkout can properly process flow if list of shipping carriers are changed during place order --- .../Checkout/Test/Mftf/ActionGroup/CheckoutActionGroup.xml | 3 ++- .../Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/CheckoutActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/CheckoutActionGroup.xml index 27808e9ad03a3..0122303510a5f 100644 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/CheckoutActionGroup.xml +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/CheckoutActionGroup.xml @@ -134,7 +134,8 @@ <arguments> <argument name="shippingMethod"/> </arguments> - <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" time="30" stepKey="waitForPaymentSectionLoaded"/> + <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" stepKey="waitForPaymentSectionLoaded"/> + <seeElement selector="{{CheckoutPaymentSection.isPaymentSection}}" stepKey="assertPaymentSection"/> <see userInput="{{shippingMethod}}" selector="{{CheckoutPaymentSection.shippingMethodInformation}}" stepKey="assertshippingMethodInformation"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml index 91cc992e4326f..b2dd49cded7c1 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml @@ -49,6 +49,6 @@ <element name="billingAddressSelectShared" type="select" selector=".checkout-billing-address select[name='billing_address_id']"/> <element name="billingAddressSameAsShippingShared" type="checkbox" selector="#billing-address-same-as-shipping-shared"/> <element name="addressAction" type="button" selector="//div[@class='actions-toolbar']//span[text()='{{action}}']" parameterized="true"/> - <element name="shippingMethodInformation" type="text" selector="//div[@class='ship-via']//div[@class='shipping-information-content']" /> + <element name="shippingMethodInformation" type="text" selector=".ship-via .shipping-information-content"/> </section> </sections> From 3c9a52df177f55832d0bccf36113eebd97d04a10 Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Thu, 13 Jun 2019 14:14:05 -0500 Subject: [PATCH 1965/2092] Merge branch '2.2-tests-pr' of github.com:magento-pangolin/magento2ce into MC-8893 # Conflicts: # app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStoreFrontProductPageActionGroup.xml --- .../Mftf/ActionGroup/OpenStorefrontProductPageActionGroup.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStorefrontProductPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStorefrontProductPageActionGroup.xml index 7c40fc5796796..4bfd5673e4a8b 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStorefrontProductPageActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/OpenStorefrontProductPageActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="OpenStorefrontProductPageActionGroup"> + <actionGroup name="OpenStoreFrontProductPageActionGroup"> <arguments> <argument name="productUrlKey" type="string"/> </arguments> From 4a899d810a9328b460c85ea55aa740828ec56af1 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Thu, 13 Jun 2019 14:17:38 -0500 Subject: [PATCH 1966/2092] MC-8120: Logging during checkout for Customer without addresses in address book --- .../ActionGroup/LoginAsCustomerOnCheckoutPageActionGroup.xml | 2 +- .../Checkout/Test/Mftf/Section/CheckoutShippingSection.xml | 2 +- .../Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/LoginAsCustomerOnCheckoutPageActionGroup.xml b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/LoginAsCustomerOnCheckoutPageActionGroup.xml index 06a49b856b5e2..0c89d4ea78648 100644 --- a/app/code/Magento/Checkout/Test/Mftf/ActionGroup/LoginAsCustomerOnCheckoutPageActionGroup.xml +++ b/app/code/Magento/Checkout/Test/Mftf/ActionGroup/LoginAsCustomerOnCheckoutPageActionGroup.xml @@ -22,6 +22,6 @@ <doubleClick selector="{{CheckoutShippingSection.loginButton}}" stepKey="clickLoginBtn"/> <waitForLoadingMaskToDisappear stepKey="waitForLoadingMaskToDisappear3"/> <waitForPageLoad stepKey="waitToBeLoggedIn"/> - <waitForElementNotVisible selector="{{CheckoutShippingSection.email}}" stepKey="waitForEmailInvisible" time ="60"/> + <waitForElementNotVisible selector="{{CheckoutShippingSection.email}}" stepKey="waitForEmailInvisible"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutShippingSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutShippingSection.xml index 2ae138a76d42a..42c92cbe20c3a 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutShippingSection.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutShippingSection.xml @@ -38,6 +38,6 @@ <element name="nameSuffix" type="select" selector="[name='suffix']"/> <element name="nameSuffixOption" type="text" selector="select[name='suffix'] option[value='{{optionValue}}']" parameterized="true" timeout="30"/> <element name="password" type="input" selector="#customer-password"/> - <element name="loginButton" type="button" selector=".action.login" timeout="30"/> + <element name="loginButton" type="button" selector=".action.login"/> </section> </sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml index 134970fc1c8f8..47f167d12f3e5 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml @@ -14,7 +14,7 @@ <element name="emailInput" type="input" selector="input[name=email]"/> <element name="apply" type="button" selector="button[data-action=grid-filter-apply]" timeout="30"/> <element name="clearFilters" type="button" selector=".admin__data-grid-header button[data-action='grid-filter-reset']" timeout="30"/> - <element name="clearAll" type="button" selector=".admin__data-grid-header .action-tertiary.action-clear" timeout="30"/> + <element name="clearAll" type="button" selector=".admin__data-grid-header .action-tertiary.action-clear"/> <element name="viewDropdown" type="button" selector=".admin__data-grid-action-bookmarks button.admin__action-dropdown"/> </section> </sections> From 1c1d3d46ee50c9f7caa3a57e4d2574df760b3bfe Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Thu, 13 Jun 2019 14:21:05 -0500 Subject: [PATCH 1967/2092] MAGETWO-99930: Configuarable product stock status stays 'In Stock' --- .../Model/Inventory/ParentItemProcessor.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php b/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php index a83405a6d8703..2089e6c5dddab 100644 --- a/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php +++ b/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php @@ -39,6 +39,13 @@ class ParentItemProcessor */ private $stockConfiguration; + /** + * ParentItemProcessor constructor. + * @param Configurable $configurableType + * @param StockItemCriteriaInterfaceFactory $criteriaInterfaceFactory + * @param StockItemRepositoryInterface $stockItemRepository + * @param StockConfigurationInterface $stockConfiguration + */ public function __construct( Configurable $configurableType, StockItemCriteriaInterfaceFactory $criteriaInterfaceFactory, From b547c55ee8a416393cd46c31cac8b6522b25a069 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Thu, 13 Jun 2019 14:23:32 -0500 Subject: [PATCH 1968/2092] MAGETWO-99930: Configuarable product stock status stays 'In Stock' --- .../ConfigurableProduct/Model/Inventory/ParentItemProcessor.php | 1 - 1 file changed, 1 deletion(-) diff --git a/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php b/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php index 2089e6c5dddab..38204790a910f 100644 --- a/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php +++ b/app/code/Magento/ConfigurableProduct/Model/Inventory/ParentItemProcessor.php @@ -40,7 +40,6 @@ class ParentItemProcessor private $stockConfiguration; /** - * ParentItemProcessor constructor. * @param Configurable $configurableType * @param StockItemCriteriaInterfaceFactory $criteriaInterfaceFactory * @param StockItemRepositoryInterface $stockItemRepository From 65e8db2f6f34120dae0cd9ed039945a88a61b4fa Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Thu, 13 Jun 2019 14:51:47 -0500 Subject: [PATCH 1969/2092] MC-8120: Logging during checkout for Customer without addresses in address book --- .../Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml | 1 + .../Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml index d08f10b22419d..6a3b80bf4ab69 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml @@ -19,6 +19,7 @@ <click stepKey="delete" selector="{{AdminCustomerGridMainActionsSection.delete}}"/> <waitForPageLoad stepKey="waitForConfirmationAlert"/> <click stepKey="accept" selector="{{AdminCustomerGridMainActionsSection.ok}}"/> + <waitForPageLoad stepKey="waitForDelete"/> <see stepKey="seeSuccessMessage" userInput="were deleted."/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml index d7d230debb671..95bc62cff8351 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml @@ -10,9 +10,9 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminCustomerGridMainActionsSection"> <element name="addNewCustomer" type="button" selector="#add" timeout="30"/> - <element name="customerCheckbox" type="button" selector="//*[contains(text(),'{{arg}}')]/parent::td/preceding-sibling::td/label[@class='data-grid-checkbox-cell-inner']//input" parameterized="true"/> + <element name="customerCheckbox" type="button" selector="//*[contains(text(),'{{arg}}')]/../preceding-sibling::td[contains(@class, 'data-grid-checkbox-cell')]//input" parameterized="true"/> <element name="delete" type="button" selector="//*[contains(@class, 'admin__data-grid-header')]//span[contains(@class,'action-menu-item') and text()='Delete']"/> <element name="actions" type="text" selector=".action-select"/> - <element name="ok" type="button" selector="//button[@data-role='action']//span[text()='OK']"/> + <element name="ok" type="button" selector=".modal-footer button.action-accept"/> </section> </sections> From 2feac92200e0c1ed1606b76d1ead58cb5dfd0ca9 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Thu, 13 Jun 2019 15:18:16 -0500 Subject: [PATCH 1970/2092] MC-8316: Apply Promo Code during Checkout for physical product --- .../Mftf/Section/CheckoutPaymentSection.xml | 2 ++ ...efrontApplyPromoCodeDuringCheckoutTest.xml | 22 ++++++++++++++----- .../AdminCartPriceRuleDiscountSection.xml | 2 +- .../Section/StorefrontDiscountSection.xml | 3 ++- 4 files changed, 21 insertions(+), 8 deletions(-) diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml index 938d46367e634..5ae199a1ce339 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml @@ -49,5 +49,7 @@ <element name="billingAddressSelectShared" type="select" selector=".checkout-billing-address select[name='billing_address_id']"/> <element name="billingAddressSameAsShippingShared" type="checkbox" selector="#billing-address-same-as-shipping-shared"/> <element name="addressAction" type="button" selector="//div[@class='actions-toolbar']//span[text()='{{action}}']" parameterized="true"/> + <element name="discount" type="block" selector="tr.totals.discount"/> + <element name="discountPrice" type="text" selector=".discount .price"/> </section> </sections> diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontApplyPromoCodeDuringCheckoutTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontApplyPromoCodeDuringCheckoutTest.xml index 058f098a4e659..7563df33b471e 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontApplyPromoCodeDuringCheckoutTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontApplyPromoCodeDuringCheckoutTest.xml @@ -41,35 +41,45 @@ <actionGroup ref="logout" stepKey="logout"/> </after> - <!-- Add simple product to cart --> + <!-- Go to Storefront as Guest and add simple product to cart --> <actionGroup ref="AddSimpleProductToCart" stepKey="addProductToCart"> <argument name="product" value="$$createProduct$$"/> </actionGroup> - <!-- Navigate to checkout --> + <!-- Go to Checkout --> <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="goToCheckoutFromMinicart"/> - <!-- Fill shipping address --> + <!-- Fill all required fields with valid data and select Flat Rate, price = 5, shipping --> <actionGroup ref="GuestCheckoutFillingShippingSectionActionGroup" stepKey="guestCheckoutFillingShipping"> <argument name="shippingMethod" value="Flat Rate"/> </actionGroup> - <!-- Apply discount to order --> + <!-- Click Apply Discount Code: section is expanded. Input promo code, apply and see success message --> <actionGroup ref="StorefrontApplyDiscountCodeActionGroup" stepKey="applyCoupon"> <argument name="discountCode" value="$$createCouponForCartPriceRule.code$$"/> </actionGroup> + <!-- Apply button is disappeared --> + <dontSeeElement selector="{{StorefrontDiscountSection.applyCodeBtn}}" stepKey="dontSeeApplyButton"/> + + <!-- Cancel coupon button is appeared --> + <seeElement selector="{{StorefrontDiscountSection.CancelCouponBtn}}" stepKey="seeCancelCouponButton"/> + + <!-- Order summary contains information about applied code --> + <seeElement selector="{{CheckoutPaymentSection.discount}}" stepKey="seeDiscountCouponInSummaryBlock"/> + <see selector="{{CheckoutPaymentSection.discountPrice}}" userInput="-$5.00" stepKey="seeDiscountPrice"/> + <!-- Select payment solution --> <actionGroup ref="CheckoutSelectCheckMoneyOrderPaymentActionGroup" stepKey="clickCheckMoneyOrderPayment"/> - <!-- Place Order --> + <!-- Place Order: order is successfully placed --> <actionGroup ref="ClickPlaceOrderActionGroup" stepKey="clickPlaceOrder"/> <grabTextFrom selector="{{CheckoutSuccessMainSection.orderNumber}}" stepKey="grabOrderNumber"/> <!-- Login as admin --> <actionGroup ref="LoginAsAdmin" stepKey="loginAsAdmin"/> - <!-- Check total in created order --> + <!-- Verify total on order page --> <actionGroup ref="filterOrderGridById" stepKey="filterOrderById"> <argument name="orderId" value="$grabOrderNumber"/> </actionGroup> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Section/AdminCartPriceRuleDiscountSection.xml b/app/code/Magento/SalesRule/Test/Mftf/Section/AdminCartPriceRuleDiscountSection.xml index 257452d6cd27a..d388cc4b61628 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Section/AdminCartPriceRuleDiscountSection.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Section/AdminCartPriceRuleDiscountSection.xml @@ -12,6 +12,6 @@ <element name="couponInput" type="input" selector="#coupon_code"/> <element name="applyCodeBtn" type="button" selector="#discount-coupon-form button[class*='apply']" timeout="30"/> <element name="discountBlockActive" type="text" selector=".block.discount.active"/> - <element name="cancelButton" type="text" selector="#discount-coupon-form button[class*='cancel']" timeout="30"/> + <element name="cancelButton" type="text" selector="#discount-form .action-cancel" timeout="30"/> </section> </sections> diff --git a/app/code/Magento/SalesRule/Test/Mftf/Section/StorefrontDiscountSection.xml b/app/code/Magento/SalesRule/Test/Mftf/Section/StorefrontDiscountSection.xml index 7801fa29adc22..108b845008d1a 100644 --- a/app/code/Magento/SalesRule/Test/Mftf/Section/StorefrontDiscountSection.xml +++ b/app/code/Magento/SalesRule/Test/Mftf/Section/StorefrontDiscountSection.xml @@ -14,6 +14,7 @@ <element name="cancelCoupon" type="button" selector="button[value='Cancel Coupon']"/> <element name="discountInput" type="input" selector="#discount-code"/> <element name="discountBlockActive" type="text" selector=".block.discount.active"/> - <element name="discountVerificationMsg" type="button" selector="//div[contains(@class, 'discount-code _active')]//div[@data-role='checkout-messages']/div/div"/> + <element name="discountVerificationMsg" type="button" selector=".message-success div"/> + <element name="CancelCouponBtn" type="button" selector="#discount-form .action-cancel"/> </section> </sections> From 6a9700cfab4051cdfcc06557a02cd3282a57ad0a Mon Sep 17 00:00:00 2001 From: Hwashiang Yu <hwyu@adobe.com> Date: Thu, 13 Jun 2019 16:16:35 -0500 Subject: [PATCH 1971/2092] MC-17487: Calendar template update - Updated calendar template --- .../Magento/Theme/view/frontend/templates/js/calendar.phtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml b/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml index 7044c1e2d6f66..5393475627bbe 100644 --- a/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml +++ b/app/code/Magento/Theme/view/frontend/templates/js/calendar.phtml @@ -51,7 +51,7 @@ require([ } }); - enUS = <?= $block->escapeJs($enUS) ?>; // en_US locale reference + enUS = <?= /* @noEscape */ $enUS ?>; // en_US locale reference //]]> }); From 335af4447023875f226a5a122a77b5f6f8993fd5 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Thu, 13 Jun 2019 16:30:50 -0500 Subject: [PATCH 1972/2092] Merge branch '2.2-tests-pr' into MC-10141 fix merge conflict --- .../Catalog/Test/Mftf/Section/AdminProductFormSection.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml index 52ed81285bd09..b458b05da43c6 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Section/AdminProductFormSection.xml @@ -50,7 +50,6 @@ <element name="save" type="button" selector="#save-button"/> <element name="unselectCategories" type="button" selector="//span[@class='admin__action-multiselect-crumb']/span[contains(.,'{{category}}')]/../button" parameterized="true" timeout="30"/> <element name="enableProductLabel" type="checkbox" selector=".admin__actions-switch > input[name='product[status]']+label"/> - <element name="selectCategory" type="input" selector="//label[contains(., '{{categoryName}}')]" parameterized="true"/> </section> <section name="ProductInWebsitesSection"> <element name="sectionHeader" type="button" selector="div[data-index='websites']" timeout="30"/> From b34d7c0bc8782e444a8ffa5b3b906e6e081433a8 Mon Sep 17 00:00:00 2001 From: Cari Spruiell <spruiell@adobe.com> Date: Thu, 13 Jun 2019 16:35:02 -0500 Subject: [PATCH 1973/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - clean up code --- .../Adminhtml/System/Config/CollectionTimeLabelTest.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php index 4adbb236ab952..48909208fb2ad 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php @@ -40,6 +40,14 @@ protected function setUp() ->setMethods(['getComment', 'getHtmlId', 'getName']) ->disableOriginalConstructor() ->getMock(); + + $objectManager = new ObjectManager($this); + $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $reflection = new \ReflectionClass($this->abstractElementMock); + $reflection_property = $reflection->getProperty('_escaper'); + $reflection_property->setAccessible(true); + $reflection_property->setValue($this->abstractElementMock, $escaper); + $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods(['getLocaleDate']) ->disableOriginalConstructor() From 764c5775afc2256668d4bba5ffdad011c6b23f6e Mon Sep 17 00:00:00 2001 From: Dmytro Poperechnyy <dpoperechnyy@magento.com> Date: Thu, 13 Jun 2019 17:24:08 -0500 Subject: [PATCH 1974/2092] MC-17449: Deliver CSS critical path to 2.2.x - Update async css plugin; --- app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php b/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php index ddddb2002ec4f..d15e5e69b1759 100644 --- a/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php +++ b/app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php @@ -41,7 +41,7 @@ public function beforeSendResponse(Http $subject) { $content = $subject->getContent(); - if (strpos($content, '</body') !== false && $this->scopeConfig->isSetFlag( + if (\is_string($content) && strpos($content, '</body') !== false && $this->scopeConfig->isSetFlag( self::XML_PATH_USE_CSS_CRITICAL_PATH, ScopeInterface::SCOPE_STORE )) { From c1f783bbbb04a994b00da2d1950df5cb128231c2 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Thu, 13 Jun 2019 17:35:36 -0500 Subject: [PATCH 1975/2092] MC-8190: Checkout flow if shipping rates are not available --- .../Test/StorefrontGuestCheckoutForSpecificCountriesTest.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutForSpecificCountriesTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutForSpecificCountriesTest.xml index 88e0740b77ee2..f6a428ab08bfb 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutForSpecificCountriesTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/StorefrontGuestCheckoutForSpecificCountriesTest.xml @@ -42,6 +42,11 @@ <deleteData createDataKey="createProduct" stepKey="deleteProduct"/> </after> + <!-- Go to Storefront as Guest. Check that "Log out" button absent on page --> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnHomePage"/> + <waitForPageLoad stepKey="waitForPage"/> + <dontSeeElement selector="{{StorefrontPanelHeaderSection.customerLogoutLink}}" stepKey="dontSeeLogOutButton"/> + <!-- Add product to cart --> <actionGroup ref="OpenStoreFrontProductPageActionGroup" stepKey="openProductPage"> <argument name="productUrlKey" value="$$createProduct.custom_attributes[url_key]$$"/> From 56ca6b22781ace586cc5fd7ff075c290874bbb93 Mon Sep 17 00:00:00 2001 From: Mila Lesechko <llesechk@adobe.com> Date: Thu, 13 Jun 2019 17:46:09 -0500 Subject: [PATCH 1976/2092] Merge branch '2.2-develop' into MC-8316 fix merge conflict --- .../Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml index 5ae199a1ce339..614855be46061 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml @@ -51,5 +51,6 @@ <element name="addressAction" type="button" selector="//div[@class='actions-toolbar']//span[text()='{{action}}']" parameterized="true"/> <element name="discount" type="block" selector="tr.totals.discount"/> <element name="discountPrice" type="text" selector=".discount .price"/> + <element name="shippingMethodInformation" type="text" selector=".ship-via .shipping-information-content"/> </section> </sections> From 446f0c0e6a7183328a8065e00aa843871c749e03 Mon Sep 17 00:00:00 2001 From: Surabhi Srivastava <surabhisrivastava@cedcoss.com> Date: Sat, 4 May 2019 06:04:57 +0000 Subject: [PATCH 1977/2092] Fixed Issue #22087 Fixed Issue #22087 --- .../Reports/Model/ResourceModel/Product/Sold/Collection.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php b/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php index 61dc77d188438..cd628c7a19c2b 100644 --- a/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php +++ b/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php @@ -79,6 +79,10 @@ public function addOrderedQty($from = '', $to = '') )->having( 'order_items.qty_ordered > ?', 0 + )->columns( + 'SUM(order_items.qty_ordered) as ordered_qty' + )->group( + 'order_items.product_id' ); return $this; } From c60aab5bad451da8b79e1c77f20cb24043a1b93e Mon Sep 17 00:00:00 2001 From: Nazarn96 <nazarn96@gmail.com> Date: Mon, 6 May 2019 13:13:59 +0300 Subject: [PATCH 1978/2092] magento/magento2#22646 static-test-fix --- .../Reports/Model/ResourceModel/Product/Sold/Collection.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php b/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php index cd628c7a19c2b..35a14e09e314f 100644 --- a/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php +++ b/app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php @@ -14,6 +14,8 @@ use Magento\Framework\DB\Select; /** + * Data collection. + * * @SuppressWarnings(PHPMD.DepthOfInheritance) * @api * @since 100.0.2 @@ -21,7 +23,7 @@ class Collection extends \Magento\Reports\Model\ResourceModel\Order\Collection { /** - * Set Date range to collection + * Set Date range to collection. * * @param int $from * @param int $to @@ -120,6 +122,8 @@ public function setOrder($attribute, $dir = self::SORT_ORDER_DESC) } /** + * @inheritdoc + * * @return Select * @since 100.2.0 */ From a5e61f9cee76640a1e3994f48b1abd924d1389f2 Mon Sep 17 00:00:00 2001 From: Stas Kozar <stas.kozar@transoftgroup.com> Date: Fri, 14 Jun 2019 09:18:56 +0300 Subject: [PATCH 1979/2092] MAGETWO-73529: [Optimize] Performance for grouped products with large # of options --- .../Model/Product/Type/Grouped.php | 2 +- .../Product/Form/Modifier/GroupedTest.php | 87 +++++++++++++++++-- .../Product/Form/Modifier/Grouped.php | 48 +++++++--- .../web/js/dynamic-rows/dynamic-rows-grid.js | 9 ++ 4 files changed, 125 insertions(+), 21 deletions(-) diff --git a/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php b/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php index 7bdf7c0112795..ec0157bdfcfe5 100644 --- a/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php +++ b/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php @@ -208,7 +208,7 @@ public function getAssociatedProducts($product) $collection = $this->getAssociatedProductCollection( $product )->addAttributeToSelect( - ['name', 'price', 'special_price', 'special_from_date', 'special_to_date', 'tax_class_id'] + ['name', 'price', 'special_price', 'special_from_date', 'special_to_date', 'tax_class_id', 'image'] )->addFilterByRequiredOptions()->setPositionOrder()->addStoreFilter( $this->getStoreFilter($product) )->addAttributeToFilter( diff --git a/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GroupedTest.php b/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GroupedTest.php index 327b47d4a75d8..ad4b86351a66c 100644 --- a/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GroupedTest.php +++ b/app/code/Magento/GroupedProduct/Test/Unit/Ui/DataProvider/Product/Form/Modifier/GroupedTest.php @@ -21,6 +21,9 @@ use Magento\GroupedProduct\Model\Product\Type\Grouped as GroupedProductType; use Magento\GroupedProduct\Ui\DataProvider\Product\Form\Modifier\Grouped; use Magento\Store\Api\Data\StoreInterface; +use Magento\Catalog\Model\Product; +use Magento\GroupedProduct\Model\Product\Link\CollectionProvider\Grouped as GroupedProducts; +use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; /** * Class GroupedTest @@ -82,23 +85,38 @@ class GroupedTest extends AbstractModifierTest */ protected $storeMock; + /** + * @var GroupedProducts|\PHPUnit_Framework_MockObject_MockObject + */ + private $groupedProductsMock; + + /** + * @var ProductLinkInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + */ + private $productLinkFactoryMock; + + /** + * @inheritdoc + */ protected function setUp() { $this->objectManager = new ObjectManager($this); $this->locatorMock = $this->getMockBuilder(LocatorInterface::class) ->getMockForAbstractClass(); - $this->productMock = $this->getMockBuilder(ProductInterface::class) + $this->productMock = $this->getMockBuilder(Product::class) ->setMethods(['getId', 'getTypeId']) - ->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMock(); $this->productMock->expects($this->any()) ->method('getId') ->willReturn(self::PRODUCT_ID); $this->productMock->expects($this->any()) ->method('getTypeId') ->willReturn(GroupedProductType::TYPE_CODE); - $this->linkedProductMock = $this->getMockBuilder(ProductInterface::class) + $this->linkedProductMock = $this->getMockBuilder(Product::class) ->setMethods(['getId', 'getName', 'getPrice']) - ->getMockForAbstractClass(); + ->disableOriginalConstructor() + ->getMock(); $this->linkedProductMock->expects($this->any()) ->method('getId') ->willReturn(self::LINKED_PRODUCT_ID); @@ -135,7 +153,7 @@ protected function setUp() $this->linkRepositoryMock->expects($this->any()) ->method('getList') ->with($this->productMock) - ->willReturn([$this->linkMock]); + ->willReturn([$this->linkedProductMock]); $this->productRepositoryMock = $this->getMockBuilder(ProductRepositoryInterface::class) ->setMethods(['get']) ->getMockForAbstractClass(); @@ -155,7 +173,7 @@ protected function setUp() } /** - * {@inheritdoc} + * @inheritdoc */ protected function createModel() { @@ -169,6 +187,16 @@ protected function createModel() ->setMethods(['init', 'getUrl']) ->disableOriginalConstructor() ->getMock(); + + $this->groupedProductsMock = $this->getMockBuilder(GroupedProducts::class) + ->setMethods(['getLinkedProducts']) + ->disableOriginalConstructor() + ->getMock(); + $this->productLinkFactoryMock = $this->getMockBuilder(ProductLinkInterfaceFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $this->imageHelperMock->expects($this->any()) ->method('init') ->willReturn($this->imageHelperMock); @@ -189,16 +217,23 @@ protected function createModel() 'localeCurrency' => $this->currencyMock, 'imageHelper' => $this->imageHelperMock, 'attributeSetRepository' => $this->attributeSetRepositoryMock, + 'groupedProducts' => $this->groupedProductsMock, + 'productLinkFactory' => $this->productLinkFactoryMock, ]); } + /** + * Assert array has key + * + * @return void + */ public function testModifyMeta() { $this->assertArrayHasKey(Grouped::GROUP_GROUPED, $this->getModel()->modifyMeta([])); } /** - * {@inheritdoc} + * @inheritdoc */ public function testModifyData() { @@ -226,6 +261,42 @@ public function testModifyData() ], ], ]; - $this->assertSame($expectedData, $this->getModel()->modifyData([])); + $model = $this->getModel(); + $linkedProductMock = $this->getMockBuilder(Product::class) + ->setMethods(['getId', 'getName', 'getPrice', 'getSku', 'getImage', 'getPosition', 'getQty']) + ->disableOriginalConstructor() + ->getMock(); + $linkedProductMock->expects($this->once()) + ->method('getId') + ->willReturn(self::LINKED_PRODUCT_ID); + $linkedProductMock->expects($this->once()) + ->method('getName') + ->willReturn(self::LINKED_PRODUCT_NAME); + $linkedProductMock->expects($this->once()) + ->method('getPrice') + ->willReturn(self::LINKED_PRODUCT_PRICE); + $linkedProductMock->expects($this->once()) + ->method('getSku') + ->willReturn(self::LINKED_PRODUCT_SKU); + $linkedProductMock->expects($this->once()) + ->method('getImage') + ->willReturn(''); + $linkedProductMock->expects($this->exactly(2)) + ->method('getPosition') + ->willReturn(self::LINKED_PRODUCT_POSITION); + $linkedProductMock->expects($this->once()) + ->method('getQty') + ->willReturn(self::LINKED_PRODUCT_QTY); + $this->groupedProductsMock->expects($this->once()) + ->method('getLinkedProducts') + ->willReturn([$linkedProductMock]); + $linkMock = $this->getMockBuilder(ProductLinkInterface::class) + ->getMockForAbstractClass(); + + $this->productLinkFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($linkMock); + + $this->assertSame($expectedData, $model->modifyData([])); } } diff --git a/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php b/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php index 57d9bc78aaf28..19f11df406ff8 100644 --- a/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php +++ b/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php @@ -21,6 +21,9 @@ use Magento\Eav\Api\AttributeSetRepositoryInterface; use Magento\Catalog\Model\Product\Attribute\Source\Status; use Magento\Framework\Locale\CurrencyInterface; +use Magento\GroupedProduct\Model\Product\Link\CollectionProvider\Grouped as GroupedProducts; +use Magento\Framework\App\ObjectManager; +use Magento\Catalog\Api\Data\ProductLinkInterfaceFactory; /** * Data provider for Grouped products @@ -99,6 +102,16 @@ class Grouped extends AbstractModifier */ private static $codeQty = 'qty'; + /** + * @var GroupedProducts + */ + private $groupedProducts; + + /** + * @var ProductLinkInterfaceFactory + */ + private $productLinkFactory; + /** * @param LocatorInterface $locator * @param UrlInterface $urlBuilder @@ -109,6 +122,9 @@ class Grouped extends AbstractModifier * @param AttributeSetRepositoryInterface $attributeSetRepository * @param CurrencyInterface $localeCurrency * @param array $uiComponentsConfig + * @param GroupedProducts $groupedProducts + * @param \Magento\Catalog\Api\Data\ProductLinkInterfaceFactory|null $productLinkFactory + * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( LocatorInterface $locator, @@ -119,7 +135,9 @@ public function __construct( Status $status, AttributeSetRepositoryInterface $attributeSetRepository, CurrencyInterface $localeCurrency, - array $uiComponentsConfig = [] + array $uiComponentsConfig = [], + GroupedProducts $groupedProducts = null, + \Magento\Catalog\Api\Data\ProductLinkInterfaceFactory $productLinkFactory = null ) { $this->locator = $locator; $this->urlBuilder = $urlBuilder; @@ -130,6 +148,11 @@ public function __construct( $this->status = $status; $this->localeCurrency = $localeCurrency; $this->uiComponentsConfig = array_replace_recursive($this->uiComponentsConfig, $uiComponentsConfig); + $this->groupedProducts = $groupedProducts ?: ObjectManager::getInstance()->get( + \Magento\GroupedProduct\Model\Product\Link\CollectionProvider\Grouped::class + ); + $this->productLinkFactory = $productLinkFactory ?: ObjectManager::getInstance() + ->get(\Magento\Catalog\Api\Data\ProductLinkInterfaceFactory::class); } /** @@ -143,18 +166,15 @@ public function modifyData(array $data) if ($modelId) { $storeId = $this->locator->getStore()->getId(); $data[$product->getId()]['links'][self::LINK_TYPE] = []; - $linkedItems = $this->productLinkRepository->getList($product); + $linkedItems = $this->groupedProducts->getLinkedProducts($product); usort($linkedItems, function ($a, $b) { return $a->getPosition() <=> $b->getPosition(); }); + $productLink = $this->productLinkFactory->create(); foreach ($linkedItems as $index => $linkItem) { - if ($linkItem->getLinkType() !== self::LINK_TYPE) { - continue; - } /** @var \Magento\Catalog\Api\Data\ProductInterface $linkedProduct */ - $linkedProduct = $this->productRepository->get($linkItem->getLinkedProductSku(), false, $storeId); $linkItem->setPosition($index); - $data[$modelId]['links'][self::LINK_TYPE][] = $this->fillData($linkedProduct, $linkItem); + $data[$modelId]['links'][self::LINK_TYPE][] = $this->fillData($linkItem, $productLink); } $data[$modelId][self::DATA_SOURCE_DEFAULT]['current_store_id'] = $storeId; } @@ -167,6 +187,7 @@ public function modifyData(array $data) * @param ProductInterface $linkedProduct * @param ProductLinkInterface $linkItem * @return array + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ protected function fillData(ProductInterface $linkedProduct, ProductLinkInterface $linkItem) { @@ -176,12 +197,15 @@ protected function fillData(ProductInterface $linkedProduct, ProductLinkInterfac return [ 'id' => $linkedProduct->getId(), 'name' => $linkedProduct->getName(), - 'sku' => $linkItem->getLinkedProductSku(), + 'sku' => $linkedProduct->getSku(), 'price' => $currency->toCurrency(sprintf("%f", $linkedProduct->getPrice())), - 'qty' => $linkItem->getExtensionAttributes()->getQty(), - 'position' => $linkItem->getPosition(), - 'positionCalculated' => $linkItem->getPosition(), - 'thumbnail' => $this->imageHelper->init($linkedProduct, 'product_listing_thumbnail')->getUrl(), + 'qty' => $linkedProduct->getQty(), + 'position' => $linkedProduct->getPosition(), + 'positionCalculated' => $linkedProduct->getPosition(), + 'thumbnail' => $this->imageHelper + ->init($linkedProduct, 'product_listing_thumbnail') + ->setImageFile($linkedProduct->getImage()) + ->getUrl(), 'type_id' => $linkedProduct->getTypeId(), 'status' => $this->status->getOptionText($linkedProduct->getStatus()), 'attribute_set' => $this->attributeSetRepository diff --git a/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows-grid.js b/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows-grid.js index 27a32b04a7e1c..7e53bdd04cda7 100644 --- a/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows-grid.js +++ b/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows-grid.js @@ -33,6 +33,15 @@ define([ } }, + /** + * @inheritdoc + */ + initialize: function () { + this.setToInsertData = _.debounce(this.setToInsertData, 200); + + return this._super(); + }, + /** * Calls 'initObservable' of parent * From a9154427844d6e790be7d8df37a284f302fc73aa Mon Sep 17 00:00:00 2001 From: Serhii Balko <serhii.balko@transoftgroup.com> Date: Fri, 14 Jun 2019 10:35:41 +0300 Subject: [PATCH 1980/2092] MAGETWO-99537: Missing categories in URL rewrites category tree --- .../view/adminhtml/web/js/category-tree.js | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Catalog/view/adminhtml/web/js/category-tree.js b/app/code/Magento/Catalog/view/adminhtml/web/js/category-tree.js index 561e23b974462..157879041cd66 100644 --- a/app/code/Magento/Catalog/view/adminhtml/web/js/category-tree.js +++ b/app/code/Magento/Catalog/view/adminhtml/web/js/category-tree.js @@ -37,8 +37,8 @@ define([ ajax: { url: options.url, type: 'POST', - success: $.proxy(function (node) { - return this._convertData(node[0]); + success: $.proxy(function (nodes) { + return this._convertDataNodes(nodes); }, this), /** @@ -77,6 +77,21 @@ define([ } }, + /** + * @param {Array} nodes + * @returns {Array} + * @private + */ + _convertDataNodes: function (nodes) { + var nodesData = []; + + nodes.forEach(function (node) { + nodesData.push(this._convertData(node)); + }, this); + + return nodesData; + }, + /** * @param {Object} node * @return {*} From 70c47cfa05cfa385b4ed5031b87a69eae6431630 Mon Sep 17 00:00:00 2001 From: Dmytro Horytskyi <horytsky@adobe.com> Date: Fri, 14 Jun 2019 10:44:17 -0500 Subject: [PATCH 1981/2092] MAGETWO-99655: [Magento Cloud] Error on searching for < symbol --- .../Model/ResourceModel/SynonymReader.php | 14 +++++++++- .../Search/Model/SynonymReaderTest.php | 26 ++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Search/Model/ResourceModel/SynonymReader.php b/app/code/Magento/Search/Model/ResourceModel/SynonymReader.php index 46e794a1954cf..1ac1547eb8d0a 100644 --- a/app/code/Magento/Search/Model/ResourceModel/SynonymReader.php +++ b/app/code/Magento/Search/Model/ResourceModel/SynonymReader.php @@ -87,7 +87,7 @@ private function queryByPhrase($phrase) { $matchQuery = $this->fullTextSelect->getMatchQuery( ['synonyms' => 'synonyms'], - $phrase, + $this->escapePhrase($phrase), Fulltext::FULLTEXT_MODE_BOOLEAN ); $query = $this->getConnection()->select()->from( @@ -97,6 +97,18 @@ private function queryByPhrase($phrase) return $this->getConnection()->fetchAll($query); } + /** + * Cut trailing plus or minus sign, and @ symbol, using of which causes InnoDB to report a syntax error. + * + * @see https://dev.mysql.com/doc/refman/5.7/en/fulltext-boolean.html + * @param string $phrase + * @return string + */ + private function escapePhrase(string $phrase): string + { + return preg_replace('/@+|[@+-]+$|[<>]/', '', $phrase); + } + /** * A private helper function to retrieve matching synonym groups per scope * diff --git a/dev/tests/integration/testsuite/Magento/Search/Model/SynonymReaderTest.php b/dev/tests/integration/testsuite/Magento/Search/Model/SynonymReaderTest.php index b9ba89ba53144..9a6df9b9966d2 100644 --- a/dev/tests/integration/testsuite/Magento/Search/Model/SynonymReaderTest.php +++ b/dev/tests/integration/testsuite/Magento/Search/Model/SynonymReaderTest.php @@ -48,7 +48,31 @@ public static function loadByPhraseDataProvider() ['synonyms' => 'queen,monarch', 'store_id' => 1, 'website_id' => 0], ['synonyms' => 'british,english', 'store_id' => 1, 'website_id' => 0] ] - ] + ], + [ + 'query_value', [] + ], + [ + 'query_value+', [] + ], + [ + 'query_value-', [] + ], + [ + 'query_@value', [] + ], + [ + 'query_value+@', [] + ], + [ + '<', [] + ], + [ + '>', [] + ], + [ + '<english>', [['synonyms' => 'british,english', 'store_id' => 1, 'website_id' => 0]] + ], ]; } From 77a7650cf49e1fd9e38dd56c6ea77b3cc53a7776 Mon Sep 17 00:00:00 2001 From: Vitalii Zabaznov <vzabaznov@magento.com> Date: Fri, 14 Jun 2019 12:52:06 -0500 Subject: [PATCH 1982/2092] MC-17512: Move fonts preload from blank to luma 2.2.x --- .../blank/Magento_Theme/layout/default_head_blocks.xml | 5 ----- .../luma/Magento_Theme/layout/default_head_blocks.xml | 5 +++++ 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/design/frontend/Magento/blank/Magento_Theme/layout/default_head_blocks.xml b/app/design/frontend/Magento/blank/Magento_Theme/layout/default_head_blocks.xml index 3c9f6036d0dbe..eb1c8befb3a48 100644 --- a/app/design/frontend/Magento/blank/Magento_Theme/layout/default_head_blocks.xml +++ b/app/design/frontend/Magento/blank/Magento_Theme/layout/default_head_blocks.xml @@ -10,11 +10,6 @@ <css src="css/styles-m.css"/> <css src="css/styles-l.css" media="screen and (min-width: 768px)"/> <css src="css/print.css" media="print"/> - <font src="fonts/opensans/light/opensans-300.woff2"/> - <font src="fonts/opensans/regular/opensans-400.woff2"/> - <font src="fonts/opensans/semibold/opensans-600.woff2"/> - <font src="fonts/opensans/bold/opensans-700.woff2"/> - <font src="fonts/Luma-Icons.woff2"/> <meta name="format-detection" content="telephone=no"/> </head> </page> diff --git a/app/design/frontend/Magento/luma/Magento_Theme/layout/default_head_blocks.xml b/app/design/frontend/Magento/luma/Magento_Theme/layout/default_head_blocks.xml index 2dfb1d3ee6bf0..e516978fd6e57 100644 --- a/app/design/frontend/Magento/luma/Magento_Theme/layout/default_head_blocks.xml +++ b/app/design/frontend/Magento/luma/Magento_Theme/layout/default_head_blocks.xml @@ -7,6 +7,11 @@ --> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> + <font src="fonts/opensans/light/opensans-300.woff2"/> + <font src="fonts/opensans/regular/opensans-400.woff2"/> + <font src="fonts/opensans/semibold/opensans-600.woff2"/> + <font src="fonts/opensans/bold/opensans-700.woff2"/> + <font src="fonts/Luma-Icons.woff2"/> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/> </head> </page> From 61e3e9f3f04c3d7aca7af107a2210bf897d8898b Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Tue, 11 Jun 2019 15:41:29 -0500 Subject: [PATCH 1983/2092] MC-8972: Register customer with image upload --- .../AdminDeleteCustomerActionGroup.xml | 12 +++++----- .../StorefrontCustomerLogoutActionGroup.xml | 10 ++------ ...refrontFillRegistrationFormActionGroup.xml | 23 +++++++++++++++++++ ...refrontSaveRegistrationFormActionGroup.xml | 14 +++++++++++ ...AdminCustomerAccountInformationSection.xml | 2 ++ .../Section/AdminCustomerFiltersSection.xml | 1 + .../AdminCustomerGridMainActionsSection.xml | 6 ++--- 7 files changed, 51 insertions(+), 17 deletions(-) create mode 100644 app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontFillRegistrationFormActionGroup.xml create mode 100644 app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontSaveRegistrationFormActionGroup.xml diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml index 6a3b80bf4ab69..67589677f0530 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml @@ -12,14 +12,14 @@ <argument name="customerEmail"/> </arguments> <amOnPage url="{{AdminCustomerPage.url}}" stepKey="navigateToCustomersPage"/> + <waitForPageLoad stepKey="waitForCustomerPageLoad"/> <conditionalClick selector="{{AdminCustomerFiltersSection.clearAll}}" dependentSelector="{{AdminCustomerFiltersSection.clearAll}}" visible="true" stepKey="clickClearFilters"/> - <click stepKey="chooseCustomer" selector="{{AdminCustomerGridMainActionsSection.customerCheckbox(customerEmail)}}"/> - <click stepKey="openActions" selector="{{AdminCustomerGridMainActionsSection.actions}}"/> + <click selector="{{AdminCustomerGridMainActionsSection.customerCheckbox(customerEmail)}}" stepKey="chooseCustomer"/> + <click selector="{{AdminCustomerGridMainActionsSection.actions}}" stepKey="openActions"/> <waitForPageLoad stepKey="waitActions"/> - <click stepKey="delete" selector="{{AdminCustomerGridMainActionsSection.delete}}"/> + <click selector="{{AdminCustomerGridMainActionsSection.delete}}" stepKey="deleteCustomer"/> <waitForPageLoad stepKey="waitForConfirmationAlert"/> - <click stepKey="accept" selector="{{AdminCustomerGridMainActionsSection.ok}}"/> - <waitForPageLoad stepKey="waitForDelete"/> - <see stepKey="seeSuccessMessage" userInput="were deleted."/> + <click selector="{{AdminCustomerGridMainActionsSection.ok}}" stepKey="acceptDeletion"/> + <see userInput="were deleted." stepKey="seeSuccessMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerLogoutActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerLogoutActionGroup.xml index de97bb47de796..10cc27f0d7f7e 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerLogoutActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerLogoutActionGroup.xml @@ -9,13 +9,7 @@ <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="StorefrontCustomerLogoutActionGroup"> - <amOnPage url="{{StorefrontCustomerLogoutPage.url}}" stepKey="storefrontSignOut"/> - </actionGroup> - - <actionGroup name="StorefrontSignOutActionGroup"> - <click selector="{{StoreFrontSignOutSection.customerAccount}}" stepKey="clickCustomerButton"/> - <click selector="{{StoreFrontSignOutSection.signOut}}" stepKey="clickToSignOut"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <see userInput="You are signed out" stepKey="signOut"/> + <amOnPage url="{{StorefrontCustomerSignOutPage.url}}" stepKey="storefrontSignOut"/> + <waitForPageLoad stepKey="waitForSignOutPageLoad"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontFillRegistrationFormActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontFillRegistrationFormActionGroup.xml new file mode 100644 index 0000000000000..c1a1920b3c734 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontFillRegistrationFormActionGroup.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="../../../../../../../dev/tests/acceptance/vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontFillRegistrationFormActionGroup"> + <arguments> + <argument name="customer" defaultValue="CustomerEntityOne"/> + </arguments> + <amOnPage url="{{StorefrontHomePage.url}}" stepKey="amOnStorefrontPage"/> + <waitForPageLoad stepKey="waitForNavigateToCustomersPageLoad"/> + <click stepKey="clickOnCreateAccountLink" selector="{{StorefrontPanelHeaderSection.createAnAccountLink}}"/> + <fillField stepKey="fillFirstName" userInput="{{customer.firstname}}" selector="{{StorefrontCustomerCreateFormSection.firstnameField}}"/> + <fillField stepKey="fillLastName" userInput="{{customer.lastname}}" selector="{{StorefrontCustomerCreateFormSection.lastnameField}}"/> + <fillField stepKey="fillEmail" userInput="{{customer.email}}" selector="{{StorefrontCustomerCreateFormSection.emailField}}"/> + <fillField stepKey="fillPassword" userInput="{{customer.password}}" selector="{{StorefrontCustomerCreateFormSection.passwordField}}"/> + <fillField stepKey="fillConfirmPassword" userInput="{{customer.password}}" selector="{{StorefrontCustomerCreateFormSection.confirmPasswordField}}"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontSaveRegistrationFormActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontSaveRegistrationFormActionGroup.xml new file mode 100644 index 0000000000000..e5af973e78851 --- /dev/null +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontSaveRegistrationFormActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="../../../../../../../dev/tests/acceptance/vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Test/etc/actionGroupSchema.xsd"> + <actionGroup name="StorefrontSaveRegistrationFormActionGroup"> + <click selector="{{StorefrontCustomerCreateFormSection.createAccountButton}}" stepKey="clickCreateAccountButton"/> + <waitForPageLoad stepKey="waitForCreateAccountButtonToLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml index d651d56504c76..583f72d1b6db8 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml @@ -17,5 +17,7 @@ <element name="groupValue" type="button" selector="//span[text()='{{groupValue}}']" parameterized="true"/> <element name="associateToWebsite" type="select" selector="select[name='customer[website_id]']"/> <element name="storeView" type="select" selector="select[name='customer[sendemail_store_id]']"/> + <element name="accountInformationTab" type="button" selector="#tab_customer" timeout="30"/> + <element name="attributeImage" type="image" selector="//div[contains(concat(' ',normalize-space(@class),' '),' file-uploader-preview ')]//img"/> </section> </sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml index 47f167d12f3e5..49caf8f152354 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml @@ -16,5 +16,6 @@ <element name="clearFilters" type="button" selector=".admin__data-grid-header button[data-action='grid-filter-reset']" timeout="30"/> <element name="clearAll" type="button" selector=".admin__data-grid-header .action-tertiary.action-clear"/> <element name="viewDropdown" type="button" selector=".admin__data-grid-action-bookmarks button.admin__action-dropdown"/> + <element name="clearAll" type="button" selector=".admin__data-grid-header .action-tertiary.action-clear" timeout="30"/> </section> </sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml index 95bc62cff8351..53eed7dc1d89a 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml @@ -10,9 +10,9 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="AdminCustomerGridMainActionsSection"> <element name="addNewCustomer" type="button" selector="#add" timeout="30"/> - <element name="customerCheckbox" type="button" selector="//*[contains(text(),'{{arg}}')]/../preceding-sibling::td[contains(@class, 'data-grid-checkbox-cell')]//input" parameterized="true"/> - <element name="delete" type="button" selector="//*[contains(@class, 'admin__data-grid-header')]//span[contains(@class,'action-menu-item') and text()='Delete']"/> <element name="actions" type="text" selector=".action-select"/> - <element name="ok" type="button" selector=".modal-footer button.action-accept"/> + <element name="customerCheckbox" type="button" selector="//*[contains(text(),'{{arg}}')]/parent::td/preceding-sibling::td/label[@class='data-grid-checkbox-cell-inner']//input" parameterized="true"/> + <element name="delete" type="button" selector="//*[contains(@class, 'admin__data-grid-header')]//span[contains(@class,'action-menu-item') and text()='Delete']"/> + <element name="ok" type="button" selector="//button[@data-role='action']//span[text()='OK']"/> </section> </sections> From c07be1aa257ea5a34d997374753e1e38c4a359ac Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Fri, 14 Jun 2019 08:36:25 -0500 Subject: [PATCH 1984/2092] MC-8972: Register customer with image upload --- .../Mftf/Section/AdminCustomerAccountInformationSection.xml | 4 ++-- .../Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml index 583f72d1b6db8..6b988b067043a 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerAccountInformationSection.xml @@ -17,7 +17,7 @@ <element name="groupValue" type="button" selector="//span[text()='{{groupValue}}']" parameterized="true"/> <element name="associateToWebsite" type="select" selector="select[name='customer[website_id]']"/> <element name="storeView" type="select" selector="select[name='customer[sendemail_store_id]']"/> - <element name="accountInformationTab" type="button" selector="#tab_customer" timeout="30"/> - <element name="attributeImage" type="image" selector="//div[contains(concat(' ',normalize-space(@class),' '),' file-uploader-preview ')]//img"/> + <element name="accountInformationTab" type="button" selector="#tab_customer"/> + <element name="attributeImage" type="block" selector=".file-uploader-preview img"/> </section> </sections> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml index 53eed7dc1d89a..c1553de65111e 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerGridMainActionsSection.xml @@ -11,8 +11,8 @@ <section name="AdminCustomerGridMainActionsSection"> <element name="addNewCustomer" type="button" selector="#add" timeout="30"/> <element name="actions" type="text" selector=".action-select"/> - <element name="customerCheckbox" type="button" selector="//*[contains(text(),'{{arg}}')]/parent::td/preceding-sibling::td/label[@class='data-grid-checkbox-cell-inner']//input" parameterized="true"/> + <element name="customerCheckbox" type="button" selector="//*[contains(text(),'{{arg}}')]/../preceding-sibling::td[contains(@class, 'data-grid-checkbox-cell')]//input" parameterized="true"/> <element name="delete" type="button" selector="//*[contains(@class, 'admin__data-grid-header')]//span[contains(@class,'action-menu-item') and text()='Delete']"/> - <element name="ok" type="button" selector="//button[@data-role='action']//span[text()='OK']"/> + <element name="ok" type="button" selector=".modal-footer button.action-accept"/> </section> </sections> From a22f2d2f2196b55eb09da4c1e93415517bf936b2 Mon Sep 17 00:00:00 2001 From: Soumya Unnikrishnan <sunnikri@adobe.com> Date: Fri, 14 Jun 2019 13:27:15 -0500 Subject: [PATCH 1985/2092] MC-8972: Register customer with image upload fixed merge issues --- .../StorefrontCustomerLogoutActionGroup.xml | 10 ++++++++-- .../Test/Mftf/Section/AdminCustomerFiltersSection.xml | 1 - 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerLogoutActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerLogoutActionGroup.xml index 10cc27f0d7f7e..de97bb47de796 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerLogoutActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/StorefrontCustomerLogoutActionGroup.xml @@ -9,7 +9,13 @@ <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="StorefrontCustomerLogoutActionGroup"> - <amOnPage url="{{StorefrontCustomerSignOutPage.url}}" stepKey="storefrontSignOut"/> - <waitForPageLoad stepKey="waitForSignOutPageLoad"/> + <amOnPage url="{{StorefrontCustomerLogoutPage.url}}" stepKey="storefrontSignOut"/> + </actionGroup> + + <actionGroup name="StorefrontSignOutActionGroup"> + <click selector="{{StoreFrontSignOutSection.customerAccount}}" stepKey="clickCustomerButton"/> + <click selector="{{StoreFrontSignOutSection.signOut}}" stepKey="clickToSignOut"/> + <waitForPageLoad stepKey="waitForPageLoad"/> + <see userInput="You are signed out" stepKey="signOut"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml index 49caf8f152354..879558c6636ba 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml @@ -14,7 +14,6 @@ <element name="emailInput" type="input" selector="input[name=email]"/> <element name="apply" type="button" selector="button[data-action=grid-filter-apply]" timeout="30"/> <element name="clearFilters" type="button" selector=".admin__data-grid-header button[data-action='grid-filter-reset']" timeout="30"/> - <element name="clearAll" type="button" selector=".admin__data-grid-header .action-tertiary.action-clear"/> <element name="viewDropdown" type="button" selector=".admin__data-grid-action-bookmarks button.admin__action-dropdown"/> <element name="clearAll" type="button" selector=".admin__data-grid-header .action-tertiary.action-clear" timeout="30"/> </section> From 64d0c39e21478e3248cb8f7740d181f02a2a7e98 Mon Sep 17 00:00:00 2001 From: Soumya Unnikrishnan <sunnikri@adobe.com> Date: Fri, 14 Jun 2019 13:39:54 -0500 Subject: [PATCH 1986/2092] MC-8972: Register customer with image upload fixed merge issues --- .../Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml | 1 + .../Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml index 67589677f0530..d0d7f839fd957 100644 --- a/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml +++ b/app/code/Magento/Customer/Test/Mftf/ActionGroup/AdminDeleteCustomerActionGroup.xml @@ -20,6 +20,7 @@ <click selector="{{AdminCustomerGridMainActionsSection.delete}}" stepKey="deleteCustomer"/> <waitForPageLoad stepKey="waitForConfirmationAlert"/> <click selector="{{AdminCustomerGridMainActionsSection.ok}}" stepKey="acceptDeletion"/> + <waitForPageLoad stepKey="waitForDelete"/> <see userInput="were deleted." stepKey="seeSuccessMessage"/> </actionGroup> </actionGroups> diff --git a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml index 879558c6636ba..134970fc1c8f8 100644 --- a/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml +++ b/app/code/Magento/Customer/Test/Mftf/Section/AdminCustomerFiltersSection.xml @@ -14,7 +14,7 @@ <element name="emailInput" type="input" selector="input[name=email]"/> <element name="apply" type="button" selector="button[data-action=grid-filter-apply]" timeout="30"/> <element name="clearFilters" type="button" selector=".admin__data-grid-header button[data-action='grid-filter-reset']" timeout="30"/> - <element name="viewDropdown" type="button" selector=".admin__data-grid-action-bookmarks button.admin__action-dropdown"/> <element name="clearAll" type="button" selector=".admin__data-grid-header .action-tertiary.action-clear" timeout="30"/> + <element name="viewDropdown" type="button" selector=".admin__data-grid-action-bookmarks button.admin__action-dropdown"/> </section> </sections> From cf5d202371aebda3625d11c7adc9421a79a7dfe1 Mon Sep 17 00:00:00 2001 From: Cari Spruiell <spruiell@adobe.com> Date: Fri, 14 Jun 2019 15:31:03 -0500 Subject: [PATCH 1987/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - clean up code --- .../Config/SubscriptionStatusLabelTest.php | 8 ++++++++ .../Adminhtml/System/Config/VerticalTest.php | 8 ++++++++ .../Unit/Model/Address/AbstractAddressTest.php | 3 ++- .../Test/Unit/Model/Renderer/RegionTest.php | 10 ++++++++++ .../Config/Field/Enable/AbstractEnableTest.php | 14 +++++++++++++- .../Unit/Form/Element/AbstractElementTest.php | 16 +++++++++------- 6 files changed, 50 insertions(+), 9 deletions(-) diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php index 3e0307c9d86e1..9162554ae6843 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php @@ -54,6 +54,14 @@ protected function setUp() ->setMethods(['getComment', 'getHtmlId', 'getName']) ->disableOriginalConstructor() ->getMock(); + + $objectManager = new ObjectManager($this); + $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $reflection = new \ReflectionClass($this->abstractElementMock); + $reflection_property = $reflection->getProperty('_escaper'); + $reflection_property->setAccessible(true); + $reflection_property->setValue($this->abstractElementMock, $escaper); + $this->formMock = $this->getMockBuilder(Form::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php index 8ca562385236a..1adbef416f067 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php @@ -39,6 +39,14 @@ protected function setUp() ->setMethods(['getComment', 'getLabel', 'getHint', 'getHtmlId', 'getName']) ->disableOriginalConstructor() ->getMock(); + + $objectManager = new ObjectManager($this); + $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $reflection = new \ReflectionClass($this->abstractElementMock); + $reflection_property = $reflection->getProperty('_escaper'); + $reflection_property->setAccessible(true); + $reflection_property->setValue($this->abstractElementMock, $escaper); + $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/AbstractAddressTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/AbstractAddressTest.php index a3b0dc257515b..0a94c94b95b88 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/AbstractAddressTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/AbstractAddressTest.php @@ -95,7 +95,8 @@ protected function setUp() 'regionFactory' => $this->regionFactoryMock, 'countryFactory' => $this->countryFactoryMock, 'resource' => $this->resourceMock, - 'resourceCollection' => $this->resourceCollectionMock + 'resourceCollection' => $this->resourceCollectionMock, + 'escaper' => $this->objectManager->getObject(\Magento\Framework\Escaper::class) ] ); } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php b/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php index 8421320dc7322..306fce8a15c02 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php @@ -5,6 +5,8 @@ */ namespace Magento\Customer\Test\Unit\Model\Renderer; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; + class RegionTest extends \PHPUnit\Framework\TestCase { /** @@ -58,6 +60,14 @@ public function testRender($regionCollection) ] ) ); + + $objectManager = new ObjectManager($this); + $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $reflection = new \ReflectionClass($elementMock); + $reflection_property = $reflection->getProperty('_escaper'); + $reflection_property->setAccessible(true); + $reflection_property->setValue($elementMock, $escaper); + $formMock->expects( $this->any() )->method( diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php index dd113562783aa..37acb12cc5e24 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php @@ -5,6 +5,8 @@ */ namespace Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field\Enable; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; + /** * Class AbstractEnableTest * @@ -44,8 +46,18 @@ protected function setUp() )->disableOriginalConstructor() ->getMockForAbstractClass(); + $objectManager = new ObjectManager($this); + $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); + $reflection = new \ReflectionClass($this->elementMock); + $reflection_property = $reflection->getProperty('_escaper'); + $reflection_property->setAccessible(true); + $reflection_property->setValue($this->elementMock, $escaper); + $this->abstractEnable = $objectManager->getObject( - \Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field\Enable\AbstractEnable\Stub::class + \Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field\Enable\AbstractEnable\Stub::class, + [ + '_escaper' => $objectManager->getObject(\Magento\Framework\Escaper::class) + ] ); } diff --git a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/AbstractElementTest.php b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/AbstractElementTest.php index ede56713bd02d..f7585b8d62e19 100644 --- a/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/AbstractElementTest.php +++ b/lib/internal/Magento/Framework/Data/Test/Unit/Form/Element/AbstractElementTest.php @@ -5,6 +5,8 @@ */ namespace Magento\Framework\Data\Test\Unit\Form\Element; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; + /** * Tests for \Magento\Framework\Data\Form\Element\AbstractElement */ @@ -26,9 +28,9 @@ class AbstractElementTest extends \PHPUnit\Framework\TestCase protected $_collectionFactoryMock; /** - * @var \Magento\Framework\Escaper|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Escaper */ - protected $_escaperMock; + protected $_escaper; protected function setUp() { @@ -36,15 +38,15 @@ protected function setUp() $this->createMock(\Magento\Framework\Data\Form\Element\Factory::class); $this->_collectionFactoryMock = $this->createMock(\Magento\Framework\Data\Form\Element\CollectionFactory::class); - $this->_escaperMock = $this->createMock(\Magento\Framework\Escaper::class); - $this->_escaperMock->method('escapeHtml')->willReturnArgument(0); + $objectManager = new ObjectManager($this); + $this->_escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); $this->_model = $this->getMockForAbstractClass( \Magento\Framework\Data\Form\Element\AbstractElement::class, [ $this->_factoryMock, $this->_collectionFactoryMock, - $this->_escaperMock + $this->_escaper ] ); } @@ -302,7 +304,7 @@ public function testGetLabelHtml(array $initialData, $expectedValue) /** * @param array $initialData * @param string $expectedValue - * @dataProvider testGetDefaultHtmlDataProvider + * @dataProvider defaultHtmlDataProvider * @covers \Magento\Framework\Data\Form\Element\AbstractElement::getDefaultHtml() */ public function testGetDefaultHtml(array $initialData, $expectedValue) @@ -519,7 +521,7 @@ public function serializeDataProvider() /** * @return array */ - public function testGetDefaultHtmlDataProvider() + public function defaultHtmlDataProvider() { return [ [ From 6c46ed078f3896071c69704f1b206436924fa2e7 Mon Sep 17 00:00:00 2001 From: Shikha Mishra <shikhamishra@cedcoss.com> Date: Fri, 26 Apr 2019 21:43:58 +0530 Subject: [PATCH 1988/2092] Fixed #22396 config:set fails with JSON values --- app/code/Magento/CatalogInventory/Helper/Minsaleqty.php | 2 +- .../CatalogInventory/Test/Unit/Helper/MinsaleqtyTest.php | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/CatalogInventory/Helper/Minsaleqty.php b/app/code/Magento/CatalogInventory/Helper/Minsaleqty.php index b4f5d8b670fb2..96bf5bd965355 100644 --- a/app/code/Magento/CatalogInventory/Helper/Minsaleqty.php +++ b/app/code/Magento/CatalogInventory/Helper/Minsaleqty.php @@ -95,7 +95,7 @@ protected function serializeValue($value) } return $this->serializer->serialize($data); } else { - return ''; + return $value; } } diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Helper/MinsaleqtyTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Helper/MinsaleqtyTest.php index f008ed7d9d694..051e002b80c3e 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Helper/MinsaleqtyTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Helper/MinsaleqtyTest.php @@ -216,7 +216,7 @@ public function testMakeStorableArrayFieldValue($value, $result, $serializeCallC public function makeStorableArrayFieldValueDataProvider() { return [ - 'invalid bool' => [false, ''], + 'invalid bool' => [false, false], 'invalid empty string' => ['', ''], 'valid numeric' => ['22', '22'], 'valid empty array' => [[], '[]', 1], @@ -240,7 +240,8 @@ public function makeStorableArrayFieldValueDataProvider() '[1]', 1, [0 => 1.0] - ] + ], + 'json value' => ['{"32000":2,"0":1}', '{"32000":2,"0":1}'], ]; } } From 6033a391a1bb19eb99327bac074ae61264015041 Mon Sep 17 00:00:00 2001 From: Dmytro Yushkin <dyushkin@adobe.com> Date: Mon, 17 Jun 2019 14:21:07 -0500 Subject: [PATCH 1989/2092] MC-17459: Coupon's expiration date and time do not match staging update end_date after creating a staging update --- .../SalesRule/Model/Coupon/Massgenerator.php | 6 ------ .../Magento/SalesRule/Model/CouponRepository.php | 1 - .../SalesRule/Model/ResourceModel/Coupon.php | 15 --------------- .../Model/ResourceModel/Rule/Collection.php | 7 +------ app/code/Magento/SalesRule/Model/Rule.php | 4 ---- .../Test/Unit/Model/Coupon/MassgeneratorTest.php | 2 -- 6 files changed, 1 insertion(+), 34 deletions(-) diff --git a/app/code/Magento/SalesRule/Model/Coupon/Massgenerator.php b/app/code/Magento/SalesRule/Model/Coupon/Massgenerator.php index 453a022d31397..b9cac227be127 100644 --- a/app/code/Magento/SalesRule/Model/Coupon/Massgenerator.php +++ b/app/code/Magento/SalesRule/Model/Coupon/Massgenerator.php @@ -168,16 +168,10 @@ public function generatePool() ++$attempt; } while ($this->getResource()->exists($code)); - $expirationDate = $this->getToDate(); - if ($expirationDate instanceof \DateTimeInterface) { - $expirationDate = $expirationDate->format('Y-m-d H:i:s'); - } - $coupon->setId(null) ->setRuleId($this->getRuleId()) ->setUsageLimit($this->getUsesPerCoupon()) ->setUsagePerCustomer($this->getUsagePerCustomer()) - ->setExpirationDate($expirationDate) ->setCreatedAt($nowTimestamp) ->setType(\Magento\SalesRule\Helper\Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED) ->setCode($code) diff --git a/app/code/Magento/SalesRule/Model/CouponRepository.php b/app/code/Magento/SalesRule/Model/CouponRepository.php index 99d6727a8be29..5aa66dd1e8ac5 100644 --- a/app/code/Magento/SalesRule/Model/CouponRepository.php +++ b/app/code/Magento/SalesRule/Model/CouponRepository.php @@ -119,7 +119,6 @@ public function save(\Magento\SalesRule\Api\Data\CouponInterface $coupon) __('Specified rule does not allow auto generated coupons') ); } - $coupon->setExpirationDate($rule->getToDate()); $coupon->setUsageLimit($rule->getUsesPerCoupon()); $coupon->setUsagePerCustomer($rule->getUsesPerCustomer()); } catch (\Exception $e) { diff --git a/app/code/Magento/SalesRule/Model/ResourceModel/Coupon.php b/app/code/Magento/SalesRule/Model/ResourceModel/Coupon.php index 3907261cad1b9..a544355536d6f 100644 --- a/app/code/Magento/SalesRule/Model/ResourceModel/Coupon.php +++ b/app/code/Magento/SalesRule/Model/ResourceModel/Coupon.php @@ -34,14 +34,6 @@ protected function _construct() */ public function _beforeSave(AbstractModel $object) { - if (!$object->getExpirationDate()) { - $object->setExpirationDate(null); - } elseif ($object->getExpirationDate() instanceof \DateTimeInterface) { - $object->setExpirationDate( - $object->getExpirationDate()->format('Y-m-d H:i:s') - ); - } - // maintain single primary coupon per rule $object->setIsPrimary($object->getIsPrimary() ? 1 : null); @@ -126,13 +118,6 @@ public function updateSpecificCoupons(\Magento\SalesRule\Model\Rule $rule) $updateArray['usage_per_customer'] = $rule->getUsesPerCustomer(); } - $ruleNewDate = new \DateTime($rule->getToDate()); - $ruleOldDate = new \DateTime($rule->getOrigData('to_date')); - - if ($ruleNewDate != $ruleOldDate) { - $updateArray['expiration_date'] = $rule->getToDate(); - } - if (!empty($updateArray)) { $this->getConnection()->update( $this->getTable('salesrule_coupon'), diff --git a/app/code/Magento/SalesRule/Model/ResourceModel/Rule/Collection.php b/app/code/Magento/SalesRule/Model/ResourceModel/Rule/Collection.php index 423cd1543117b..637828c993fa0 100644 --- a/app/code/Magento/SalesRule/Model/ResourceModel/Rule/Collection.php +++ b/app/code/Magento/SalesRule/Model/ResourceModel/Rule/Collection.php @@ -231,11 +231,6 @@ private function getCouponCodeSelect($couponCode) $this->joinCouponTable($couponCode, $couponSelect); - $notExpired = $this->getConnection()->quoteInto( - '(rule_coupons.expiration_date IS NULL OR rule_coupons.expiration_date >= ?)', - $this->_date->date()->format('Y-m-d') - ); - $isAutogenerated = $this->getConnection()->quoteInto('main_table.coupon_type = ?', Rule::COUPON_TYPE_AUTO) . ' AND ' . @@ -250,7 +245,7 @@ private function getCouponCodeSelect($couponCode) . ')'; $couponSelect->where( - "$notExpired AND ($isAutogenerated OR $isValidSpecific)", + "$isAutogenerated OR $isValidSpecific", null, Select::TYPE_CONDITION ); diff --git a/app/code/Magento/SalesRule/Model/Rule.php b/app/code/Magento/SalesRule/Model/Rule.php index 640398342bb5a..b9342fe7b35b7 100644 --- a/app/code/Magento/SalesRule/Model/Rule.php +++ b/app/code/Magento/SalesRule/Model/Rule.php @@ -296,8 +296,6 @@ public function afterSave() $this->getUsesPerCoupon() ? $this->getUsesPerCoupon() : null )->setUsagePerCustomer( $this->getUsesPerCustomer() ? $this->getUsesPerCustomer() : null - )->setExpirationDate( - $this->getToDate() )->save(); } else { $this->getPrimaryCoupon()->delete(); @@ -499,8 +497,6 @@ public function acquireCoupon($saveNewlyCreated = true, $saveAttemptCount = 10) $this->getUsesPerCoupon() ? $this->getUsesPerCoupon() : null )->setUsagePerCustomer( $this->getUsesPerCustomer() ? $this->getUsesPerCustomer() : null - )->setExpirationDate( - $this->getToDate() )->setType( \Magento\SalesRule\Api\Data\CouponInterface::TYPE_GENERATED ); diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/MassgeneratorTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/MassgeneratorTest.php index 8408636ae2669..1a6ebff3e61bc 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/MassgeneratorTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/Coupon/MassgeneratorTest.php @@ -109,7 +109,6 @@ public function testGeneratePool() 'setRuleId', 'setUsageLimit', 'setUsagePerCustomer', - 'setExpirationDate', 'setCreatedAt', 'setType', 'setCode', @@ -120,7 +119,6 @@ public function testGeneratePool() $couponMock->expects($this->any())->method('setRuleId')->will($this->returnSelf()); $couponMock->expects($this->any())->method('setUsageLimit')->will($this->returnSelf()); $couponMock->expects($this->any())->method('setUsagePerCustomer')->will($this->returnSelf()); - $couponMock->expects($this->any())->method('setExpirationDate')->will($this->returnSelf()); $couponMock->expects($this->any())->method('setCreatedAt')->will($this->returnSelf()); $couponMock->expects($this->any())->method('setType')->will($this->returnSelf()); $couponMock->expects($this->any())->method('setCode')->will($this->returnSelf()); From ad83e608906ae73b3473286a7352c597039ce70d Mon Sep 17 00:00:00 2001 From: Hwashiang Yu <hwyu@adobe.com> Date: Mon, 17 Jun 2019 15:25:57 -0500 Subject: [PATCH 1990/2092] MC-17547: Incorrect bundle and downloadable email template update - Resolved incorrect email template updates --- .../creditmemo/create/items/renderer.phtml | 20 +++++++++---------- .../creditmemo/view/items/renderer.phtml | 2 +- .../sales/invoice/create/items/renderer.phtml | 18 ++++++++--------- .../sales/invoice/view/items/renderer.phtml | 2 +- .../sales/order/view/items/renderer.phtml | 14 ++++++------- .../shipment/create/items/renderer.phtml | 2 +- .../sales/shipment/view/items/renderer.phtml | 2 +- .../order/items/creditmemo/default.phtml | 4 ++-- .../email/order/items/invoice/default.phtml | 4 ++-- .../email/order/items/order/default.phtml | 4 ++-- .../email/order/items/shipment/default.phtml | 2 +- .../order/creditmemo/items/renderer.phtml | 2 +- .../sales/order/invoice/items/renderer.phtml | 2 +- .../sales/order/shipment/items/renderer.phtml | 2 +- .../order/items/creditmemo/downloadable.phtml | 4 ++-- .../order/items/invoice/downloadable.phtml | 4 ++-- .../order/items/order/downloadable.phtml | 4 ++-- .../items/renderer/downloadable.phtml | 2 +- .../invoice/items/renderer/downloadable.phtml | 2 +- .../order/items/renderer/downloadable.phtml | 16 +++++++-------- 20 files changed, 56 insertions(+), 56 deletions(-) diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/create/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/create/items/renderer.phtml index e65269559a3a9..4bd3ee6fef225 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/create/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/create/items/renderer.phtml @@ -68,30 +68,30 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyOrdered()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyOrdered()*1 ?></td> </tr> <?php if ((float) $_item->getOrderItem()->getQtyInvoiced()) : ?> <tr> <th><?= $block->escapeHtml(__('Invoiced')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyInvoiced()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyInvoiced()*1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyShipped() && $block->isShipmentSeparately($_item)) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyShipped()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyShipped()*1 ?></td> </tr> <?php endif; ?> - <?php if ((float) $_item->getOrderItem()->getQtyRefunded()) : ?> + <?php if ((float) $_item->getOrderItem()->getQtyRefunded() : ?> <tr> <th><?= $block->escapeHtml(__('Refunded')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyRefunded()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyRefunded()*1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyCanceled()) : ?> <tr> <th><?= $block->escapeHtml(__('Canceled')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyCanceled()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyCanceled()*1 ?></td> </tr> <?php endif; ?> </table> @@ -99,12 +99,12 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyOrdered()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyOrdered()*1 ?></td> </tr> <?php if ((float) $_item->getOrderItem()->getQtyShipped()) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyShipped()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyShipped()*1 ?></td> </tr> <?php endif; ?> </table> @@ -133,9 +133,9 @@ <input type="text" class="input-text admin__control-text qty-input" name="creditmemo[items][<?= $block->escapeHtmlAttr($_item->getOrderItemId()) ?>][qty]" - value="<?= $block->escapeHtmlAttr($_item->getQty()*1) ?>" /> + value="<?= (int)$_item->getQty()*1 ?>" /> <?php else : ?> - <?= $block->escapeHtml($_item->getQty()*1) ?> + <?= (int)$_item->getQty()*1 ?> <?php endif; ?> <?php else : ?>   diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/view/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/view/items/renderer.phtml index 18dc5db23d562..d52f41e27262f 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/view/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/view/items/renderer.phtml @@ -63,7 +63,7 @@ </td> <td class="col-qty"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= $block->escapeHtml($_item->getQty()*1) ?> + <?= (int)$_item->getQty()*1 ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/create/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/create/items/renderer.phtml index de2dde87403af..2259a25b1e6c5 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/create/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/create/items/renderer.phtml @@ -69,30 +69,30 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><span><?= $block->escapeHtml($_item->getOrderItem()->getQtyOrdered()*1) ?></span></td> + <td><span><?= (float)$_item->getOrderItem()->getQtyOrdered()*1 ?></span></td> </tr> <?php if ((float) $_item->getOrderItem()->getQtyInvoiced()) : ?> <tr> <th><?= $block->escapeHtml(__('Invoiced')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyInvoiced()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyInvoiced()*1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyShipped() && $block->isShipmentSeparately($_item)) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyShipped()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyShipped()*1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyRefunded()) : ?> <tr> <th><?= $block->escapeHtml(__('Refunded')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyRefunded()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyRefunded()*1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyCanceled()) : ?> <tr> <th><?= $block->escapeHtml(__('Canceled')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyCanceled()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyCanceled()*1 ?></td> </tr> <?php endif; ?> </table> @@ -100,12 +100,12 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyOrdered()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyOrdered()*1 ?></td> </tr> <?php if ((float) $_item->getOrderItem()->getQtyShipped()) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= $block->escapeHtml($_item->getOrderItem()->getQtyShipped()*1) ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyShipped()*1 ?></td> </tr> <?php endif; ?> </table> @@ -119,9 +119,9 @@ <input type="text" class="input-text admin__control-text qty-input" name="invoice[items][<?= $block->escapeHtmlAttr($_item->getOrderItemId()) ?>]" - value="<?= $block->escapeHtmlAttr($_item->getQty()*1) ?>" /> + value="<?= (int)$_item->getQty()*1 ?>" /> <?php else : ?> - <?= $block->escapeHtml($_item->getQty()*1) ?> + <?= (int)$_item->getQty()*1 ?> <?php endif; ?> <?php else : ?>   diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/view/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/view/items/renderer.phtml index b8a2c0db82d4b..2126030219670 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/view/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/view/items/renderer.phtml @@ -64,7 +64,7 @@ </td> <td class="col-qty"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= $block->escapeHtml($_item->getQty()*1) ?> + <?= (int)$_item->getQty()*1 ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/order/view/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/order/view/items/renderer.phtml index 332230fb188fb..330d9e37f00c6 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/order/view/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/order/view/items/renderer.phtml @@ -87,30 +87,30 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= $block->escapeHtml($_item->getQtyOrdered()*1) ?></td> + <td><?= (float)$_item->getQtyOrdered()*1 ?></td> </tr> <?php if ((float) $_item->getQtyInvoiced()) : ?> <tr> <th><?= $block->escapeHtml(__('Invoiced')) ?></th> - <td><?= $block->escapeHtml($_item->getQtyInvoiced()*1) ?></td> + <td><?= (float)$_item->getQtyInvoiced()*1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getQtyShipped() && $block->isShipmentSeparately($_item)) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= $block->escapeHtml($_item->getQtyShipped()*1) ?></td> + <td><?= (float)$_item->getQtyShipped()*1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getQtyRefunded()) : ?> <tr> <th><?= $block->escapeHtml(__('Refunded')) ?></th> - <td><?= $block->escapeHtml($_item->getQtyRefunded()*1) ?></td> + <td><?= (float)$_item->getQtyRefunded()*1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getQtyCanceled()) : ?> <tr> <th><?= $block->escapeHtml(__('Canceled')) ?></th> - <td><?= $block->escapeHtml($_item->getQtyCanceled()*1) ?></td> + <td><?= (float)$_item->getQtyCanceled()*1 ?></td> </tr> <?php endif; ?> </table> @@ -118,12 +118,12 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= $block->escapeHtml($_item->getQtyOrdered()*1) ?></td> + <td><?= (float)$_item->getQtyOrdered()*1 ?></td> </tr> <?php if ((float) $_item->getQtyShipped()) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= $block->escapeHtml($_item->getQtyShipped()*1) ?></td> + <td><?= (float)$_item->getQtyShipped()*1 ?></td> </tr> <?php endif; ?> </table> diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/create/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/create/items/renderer.phtml index fe446ec095719..3cb8473905fe9 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/create/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/create/items/renderer.phtml @@ -58,7 +58,7 @@ <input type="text" class="input-text admin__control-text" name="shipment[items][<?= $block->escapeHtmlAttr($_item->getOrderItemId()) ?>]" - value="<?= $block->escapeHtmlAttr($_item->getQty()*1) ?>" /> + value="<?= (int)$_item->getQty()*1 ?>" /> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/view/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/view/items/renderer.phtml index d99cabe41420b..bd9587024bcc0 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/view/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/view/items/renderer.phtml @@ -48,7 +48,7 @@ <td class="col-qty last"> <?php if (($block->isShipmentSeparately() && $_item->getParentItem()) || (!$block->isShipmentSeparately() && !$_item->getParentItem())) : ?> <?php if (isset($shipItems[$_item->getId()])) : ?> - <?= $block->escapeHtml($shipItems[$_item->getId()]->getQty()*1) ?> + <?= (int)$shipItems[$_item->getId()]->getQty()*1 ?> <?php elseif ($_item->getIsVirtual()) : ?> <?= $block->escapeHtml(__('N/A')) ?> <?php else : ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/creditmemo/default.phtml b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/creditmemo/default.phtml index c935cc62e7ca7..58a234d728cbd 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/creditmemo/default.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/creditmemo/default.phtml @@ -52,14 +52,14 @@ <?php endif; ?> <td class="item-qty"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= $block->escapeHtml($_item->getQty() * 1) ?> + <?= (int)$_item->getQty() * 1 ?> <?php else : ?>   <?php endif; ?> </td> <td class="item-price"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= $block->escapeHtml($block->getItemPrice($_item)) ?> + <?= /* @noEscape */ $block->getItemPrice($_item) ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/invoice/default.phtml b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/invoice/default.phtml index f3084c5f19287..406888bcd902f 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/invoice/default.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/invoice/default.phtml @@ -53,14 +53,14 @@ <?php endif; ?> <td class="item-qty"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= $block->escapeHtml($_item->getQty() * 1) ?> + <?= (int)$_item->getQty() * 1 ?> <?php else : ?>   <?php endif; ?> </td> <td class="item-price"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= $block->escapeHtml($block->getItemPrice($_item)) ?> + <?= /* @noEscape */ $block->getItemPrice($_item) ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/order/default.phtml b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/order/default.phtml index 01f6586603863..5274ae9ab1447 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/order/default.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/order/default.phtml @@ -39,10 +39,10 @@ <p class="sku"><?= $block->escapeHtml(__('SKU')) ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> </td> <td class="item-qty"> - <?= $block->escapeHtml($_item->getQtyOrdered() * 1) ?> + <?= (int)$_item->getQtyOrdered() * 1 ?> </td> <td class="item-price"> - <?= $block->escapeHtml($block->getItemPrice($_item)) ?> + <?= /* @noEscape */ $block->getItemPrice($_item) ?> </td> </tr> <?php else : ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/shipment/default.phtml b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/shipment/default.phtml index 3128b895888f1..16b0c58cb5609 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/shipment/default.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/shipment/default.phtml @@ -47,7 +47,7 @@ <td class="item-qty"> <?php if (($block->isShipmentSeparately() && $_item->getParentItem()) || (!$block->isShipmentSeparately() && !$_item->getParentItem())) : ?> <?php if (isset($shipItems[$_item->getId()])) : ?> - <?= $block->escapeHtml($shipItems[$_item->getId()]->getQty() * 1) ?> + <?= (int)$shipItems[$_item->getId()]->getQty() * 1 ?> <?php elseif ($_item->getIsVirtual()) : ?> <?= $block->escapeHtml(__('N/A')) ?> <?php else : ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml b/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml index e15b281ecddd9..39080a1a14d07 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml @@ -51,7 +51,7 @@ </td> <td class="col qty" data-th="<?= $block->escapeHtml(__('Quantity')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= $block->escapeHtml($_item->getQty()*1) ?> + <?= (int)$_item->getQty()*1 ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/sales/order/invoice/items/renderer.phtml b/app/code/Magento/Bundle/view/frontend/templates/sales/order/invoice/items/renderer.phtml index 65845bead142d..4677889f314bd 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/sales/order/invoice/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/sales/order/invoice/items/renderer.phtml @@ -50,7 +50,7 @@ </td> <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= $block->escapeHtml($_item->getQty()*1) ?> + <?= (int)$_item->getQty()*1 ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/sales/order/shipment/items/renderer.phtml b/app/code/Magento/Bundle/view/frontend/templates/sales/order/shipment/items/renderer.phtml index befd4bbe462f3..3f54ec938a2c4 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/sales/order/shipment/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/sales/order/shipment/items/renderer.phtml @@ -45,7 +45,7 @@ <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Shipped')) ?>"> <?php if (($block->isShipmentSeparately() && $_item->getParentItem()) || (!$block->isShipmentSeparately() && !$_item->getParentItem())) : ?> <?php if (isset($shipItems[$_item->getId()])) : ?> - <?= $block->escapeHtml($shipItems[$_item->getId()]->getQty()*1) ?> + <?= (int)$shipItems[$_item->getId()]->getQty()*1 ?> <?php elseif ($_item->getIsVirtual()) : ?> <?= $block->escapeHtml(__('N/A')) ?> <?php else : ?> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/creditmemo/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/creditmemo/downloadable.phtml index 78c9f712dfaab..bf4083e8a8b4e 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/creditmemo/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/creditmemo/downloadable.phtml @@ -31,8 +31,8 @@ <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="item-qty"><?= $block->escapeHtml($_item->getQty() * 1) ?></td> + <td class="item-qty"><?= (int)$_item->getQty()*1 ?></td> <td class="item-price"> - <?= $block->escapeHtml($block->getItemPrice($_item)) ?> + <?= /* @noEscape */ $block->getItemPrice($_item) ?> </td> </tr> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/invoice/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/invoice/downloadable.phtml index 727bf156f368a..e1e0b99e114cd 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/invoice/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/invoice/downloadable.phtml @@ -32,8 +32,8 @@ <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="item-qty"><?= $block->escapeHtml($_item->getQty() * 1) ?></td> + <td class="item-qty"><?= (int)$_item->getQty()*1 ?></td> <td class="item-price"> - <?= $block->escapeHtml($block->getItemPrice($_item)) ?> + <?= /* @noEscape */ $block->getItemPrice($_item) ?> </td> </tr> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/order/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/order/downloadable.phtml index 9f9de6bf7d051..da6ae3ca1248f 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/order/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/order/downloadable.phtml @@ -46,8 +46,8 @@ </table> <?php endif; ?> </td> - <td class="item-qty"><?= $block->escapeHtml($_item->getQtyOrdered() * 1) ?></td> + <td class="item-qty"><?= (int)$_item->getQtyOrdered() * 1 ?></td> <td class="item-price"> - <?= $block->escapeHtml($block->getItemPrice($_item)) ?> + <?= /* @noEscape */ $block->getItemPrice($_item) ?> </td> </tr> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/creditmemo/items/renderer/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/creditmemo/items/renderer/downloadable.phtml index 2d263635718da..df5ddf6e10336 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/creditmemo/items/renderer/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/creditmemo/items/renderer/downloadable.phtml @@ -55,7 +55,7 @@ <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> <?= $block->getItemPriceHtml() ?> </td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"><?= $block->escapeHtml($_item->getQty()*1) ?></td> + <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"><?= (int)$_item->getQty()*1 ?></td> <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> <?= $block->getItemRowTotalHtml() ?> </td> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml index 6e86dc5bf8785..e56b7aded3dbe 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml @@ -55,7 +55,7 @@ <?= $block->getItemPriceHtml() ?> </td> <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"> - <span class="qty summary" data-label="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"><?= $block->escapeHtml($_item->getQty()*1) ?></span> + <span class="qty summary" data-label="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"><?= (int)$_item->getQty()*1 ?></span> </td> <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> <?= $block->getItemRowTotalHtml() ?> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/items/renderer/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/items/renderer/downloadable.phtml index 4caedd3e2d231..5dcf6857d422f 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/items/renderer/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/items/renderer/downloadable.phtml @@ -8,7 +8,7 @@ ?> <?php $_item = $block->getItem() ?> <tr id="order-item-row-<?= $block->escapeHtmlAttr($_item->getId()) ?>"> - <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> + <td class="col name" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> <?php if ($_options = $block->getItemOptions()) : ?> <dl class="item-options links"> @@ -51,8 +51,8 @@ <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> - <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> + <td class="col sku" data-th="<?= $block->escapeHtmlAttr(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> + <td class="col price" data-th="<?= $block->escapeHtmlAttr(__('Price')) ?>"> <?= $block->getItemPriceHtml() ?> </td> <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"> @@ -60,30 +60,30 @@ <?php if ($block->getItem()->getQtyOrdered() > 0) : ?> <li class="item"> <span class="title"><?= $block->escapeHtml(__('Ordered')) ?></span> - <span class="content"><?= $block->escapeHtml($block->getItem()->getQtyOrdered()*1) ?></span> + <span class="content"><?= (int)$block->getItem()->getQtyOrdered()*1 ?></span> </li> <?php endif; ?> <?php if ($block->getItem()->getQtyShipped() > 0) : ?> <li class="item"> <span class="title"><?= $block->escapeHtml(__('Shipped')) ?></span> - <span class="content"><?= $block->escapeHtml($block->getItem()->getQtyShipped() * 1) ?></span> + <span class="content"><?= (int)$block->getItem()->getQtyShipped()*1 ?></span> </li> <?php endif; ?> <?php if ($block->getItem()->getQtyCanceled() > 0) : ?> <li class="item"> <span class="title"><?= $block->escapeHtml(__('Canceled')) ?></span> - <span class="content"><?= $block->escapeHtml($block->getItem()->getQtyCanceled()*1) ?></span> + <span class="content"><?= (int)$block->getItem()->getQtyCanceled()*1 ?></span> </li> <?php endif; ?> <?php if ($block->getItem()->getQtyRefunded() > 0) : ?> <li class="item"> <span class="title"><?= $block->escapeHtml(__('Refunded')) ?></span> - <span class="content"><?= $block->escapeHtml($block->getItem()->getQtyRefunded()*1) ?></span> + <span class="content"><?= (int)$block->getItem()->getQtyRefunded()*1 ?></span> </li> <?php endif; ?> </ul> </td> - <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> + <td class="col subtotal" data-th="<?= $block->escapeHtmlAttr(__('Subtotal')) ?>"> <?= $block->getItemRowTotalHtml() ?> </td> </tr> From ae188386939fdb991d007ac471823af7ad460bea Mon Sep 17 00:00:00 2001 From: Dmytro Yushkin <dyushkin@adobe.com> Date: Mon, 17 Jun 2019 16:28:27 -0500 Subject: [PATCH 1991/2092] MC-17459: Coupon's expiration date and time do not match staging update end_date after creating a staging update - Deprecation of coupon expiration date usage --- app/code/Magento/SalesRule/Api/Data/CouponInterface.php | 2 ++ app/code/Magento/SalesRule/Model/Coupon.php | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/app/code/Magento/SalesRule/Api/Data/CouponInterface.php b/app/code/Magento/SalesRule/Api/Data/CouponInterface.php index 327b3ffa7b725..8ca4b00bf4ba8 100644 --- a/app/code/Magento/SalesRule/Api/Data/CouponInterface.php +++ b/app/code/Magento/SalesRule/Api/Data/CouponInterface.php @@ -108,6 +108,7 @@ public function setTimesUsed($timesUsed); * Get expiration date * * @return string|null + * @deprecated Coupon expiration must follow sales rule expiration date. */ public function getExpirationDate(); @@ -116,6 +117,7 @@ public function getExpirationDate(); * * @param string $expirationDate * @return $this + * @deprecated Coupon expiration must follow sales rule expiration date. */ public function setExpirationDate($expirationDate); diff --git a/app/code/Magento/SalesRule/Model/Coupon.php b/app/code/Magento/SalesRule/Model/Coupon.php index ee1eaff08303c..600e18cf2c184 100644 --- a/app/code/Magento/SalesRule/Model/Coupon.php +++ b/app/code/Magento/SalesRule/Model/Coupon.php @@ -20,6 +20,9 @@ class Coupon extends \Magento\Framework\Model\AbstractExtensibleModel implements const KEY_USAGE_LIMIT = 'usage_limit'; const KEY_USAGE_PER_CUSTOMER = 'usage_per_customer'; const KEY_TIMES_USED = 'times_used'; + /** + * @deprecated Coupon expiration must follow sales rule expiration date. + */ const KEY_EXPIRATION_DATE = 'expiration_date'; const KEY_IS_PRIMARY = 'is_primary'; const KEY_CREATED_AT = 'created_at'; @@ -202,6 +205,7 @@ public function setTimesUsed($timesUsed) * Get expiration date * * @return string|null + * @deprecated Coupon expiration must follow sales rule expiration date. */ public function getExpirationDate() { @@ -213,6 +217,7 @@ public function getExpirationDate() * * @param string $expirationDate * @return $this + * @deprecated Coupon expiration must follow sales rule expiration date. */ public function setExpirationDate($expirationDate) { From b03108a4c0b001b7f8b1b53499a61d1b8b0f7108 Mon Sep 17 00:00:00 2001 From: Myroslav Dobra <dmaraptor@gmail.com> Date: Tue, 18 Jun 2019 12:19:59 +0300 Subject: [PATCH 1992/2092] MAGETWO-86624: [2.2] Allowed countries restriction for a default website is applied to backend customer grid --- .../Section/AdminConfigurationGeneralCountryOptionsSection.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml b/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml index 124ffbf102beb..9f61c9876d8fa 100644 --- a/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml +++ b/app/code/Magento/Directory/Test/Mftf/Section/AdminConfigurationGeneralCountryOptionsSection.xml @@ -17,6 +17,6 @@ <element name="countryOptions" type="button" selector="#general_country-head"/> <element name="countryOptionsOpen" type="button" selector="#general_country-head.open"/> <element name="topDestinations" type="select" selector="#general_country_destinations"/> - <element name="allowedCountriesOptions" selector="#general_country_allow option"/> + <element name="allowedCountriesOptions" type="select" selector="#general_country_allow option"/> </section> </sections> From 817fa94cbd3bbb74689cef65d8da4199aa2478b4 Mon Sep 17 00:00:00 2001 From: Myroslav Dobra <dmaraptor@gmail.com> Date: Tue, 18 Jun 2019 12:22:08 +0300 Subject: [PATCH 1993/2092] MAGETWO-73989: [GitHub] Minimal Query Length For Catalog Search #6681 --- .../Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml index 0f0e6c8351d16..39fa355eea6ed 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminMoveProductBetweenCategoriesTest.xml @@ -80,9 +80,7 @@ <waitForPageLoad stepKey="waitForSavingChanges"/> <!-- Enable `Use Categories Path for Product URLs` on Stores -> Configuration -> Catalog -> Catalog -> Search Engine Optimization --> - <amOnPage url="{{AdminCatalogSearchConfigurationPage.url}}" stepKey="onConfigPage"/> - <waitForPageLoad stepKey="waitForLoading"/> - <conditionalClick selector="{{AdminCatalogSearchEngineConfigurationSection.searchEngineOptimization}}" dependentSelector="{{AdminCatalogSearchEngineConfigurationSection.openedEngineOptimization}}" visible="false" stepKey="clickEngineOptimization"/> + <amOnPage url="{{AdminCatalogSearchConfigurationPage.url('#catalog_seo-link')}}" stepKey="onConfigPage"/> <uncheckOption selector="{{AdminCatalogSearchEngineConfigurationSection.systemValueUseCategoriesPath}}" stepKey="uncheckDefault"/> <selectOption userInput="Yes" selector="{{AdminCatalogSearchEngineConfigurationSection.selectUseCategoriesPatForProductUrls}}" stepKey="selectYes"/> <click selector="{{AdminConfigSection.saveButton}}" stepKey="saveConfig"/> From 491db76942701ad53b428b12ad9fa027ac297c72 Mon Sep 17 00:00:00 2001 From: Stas Kozar <stas.kozar@transoftgroup.com> Date: Tue, 18 Jun 2019 12:37:58 +0300 Subject: [PATCH 1994/2092] MAGETWO-73529: [Optimize] Performance for grouped products with large # of options --- .../Ui/DataProvider/Product/Form/Modifier/Grouped.php | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php b/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php index 19f11df406ff8..136e68cc7955a 100644 --- a/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php +++ b/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php @@ -122,8 +122,8 @@ class Grouped extends AbstractModifier * @param AttributeSetRepositoryInterface $attributeSetRepository * @param CurrencyInterface $localeCurrency * @param array $uiComponentsConfig - * @param GroupedProducts $groupedProducts - * @param \Magento\Catalog\Api\Data\ProductLinkInterfaceFactory|null $productLinkFactory + * @param GroupedProducts|null $groupedProducts + * @param ProductLinkInterfaceFactory|null $productLinkFactory * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -148,11 +148,9 @@ public function __construct( $this->status = $status; $this->localeCurrency = $localeCurrency; $this->uiComponentsConfig = array_replace_recursive($this->uiComponentsConfig, $uiComponentsConfig); - $this->groupedProducts = $groupedProducts ?: ObjectManager::getInstance()->get( - \Magento\GroupedProduct\Model\Product\Link\CollectionProvider\Grouped::class - ); + $this->groupedProducts = $groupedProducts ?: ObjectManager::getInstance()->get(GroupedProducts::class); $this->productLinkFactory = $productLinkFactory ?: ObjectManager::getInstance() - ->get(\Magento\Catalog\Api\Data\ProductLinkInterfaceFactory::class); + ->get(ProductLinkInterfaceFactory::class); } /** From 46f7e5240fd2f3816b509eb16ae02c8bae0bdd5e Mon Sep 17 00:00:00 2001 From: Stas Kozar <stas.kozar@transoftgroup.com> Date: Tue, 18 Jun 2019 13:24:25 +0300 Subject: [PATCH 1995/2092] MAGETWO-73529: [Optimize] Performance for grouped products with large # of options --- .../Ui/DataProvider/Product/Form/Modifier/Grouped.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php b/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php index 136e68cc7955a..ce221935c62bd 100644 --- a/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php +++ b/app/code/Magento/GroupedProduct/Ui/DataProvider/Product/Form/Modifier/Grouped.php @@ -137,7 +137,7 @@ public function __construct( CurrencyInterface $localeCurrency, array $uiComponentsConfig = [], GroupedProducts $groupedProducts = null, - \Magento\Catalog\Api\Data\ProductLinkInterfaceFactory $productLinkFactory = null + ProductLinkInterfaceFactory $productLinkFactory = null ) { $this->locator = $locator; $this->urlBuilder = $urlBuilder; From 9151ddb9cca70fc337f0aff2db3272e14ff969e1 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Tue, 18 Jun 2019 11:42:05 -0500 Subject: [PATCH 1996/2092] MAGETWO-99925: Product URL rewrites are always regenerated if products are updated via CSV import in default scope --- .../CatalogImportExport/Model/Import/Product.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product.php b/app/code/Magento/CatalogImportExport/Model/Import/Product.php index d37b755e8c57a..07e116897b1c2 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product.php @@ -2525,6 +2525,12 @@ public function validateRow(array $rowData, $rowNum) */ private function isNeedToValidateUrlKey($rowData) { + if (!empty($rowData[self::COL_SKU]) && empty($rowData[self::URL_KEY]) + && $this->getBehavior() === Import::BEHAVIOR_APPEND + && $this->isSkuExist($rowData[self::COL_SKU])) { + return false; + } + return (!empty($rowData[self::URL_KEY]) || !empty($rowData[self::COL_NAME])) && (empty($rowData[self::COL_VISIBILITY]) || $rowData[self::COL_VISIBILITY] @@ -2869,15 +2875,12 @@ protected function getResource() */ private function isNeedToChangeUrlKey(array $rowData): bool { - $urlKey = $this->getUrlKey($rowData); $productExists = $this->isSkuExist($rowData[self::COL_SKU]); - $markedToEraseUrlKey = isset($rowData[self::URL_KEY]); // The product isn't new and the url key index wasn't marked for change. - if (!$urlKey && $productExists && !$markedToEraseUrlKey) { + if ($productExists && empty($rowData[self::URL_KEY]) && $this->getBehavior() === Import::BEHAVIOR_APPEND) { // Seems there is no need to change the url key return false; } - return true; } From 7c4990f082b143eb378b5f066500305fc71e898b Mon Sep 17 00:00:00 2001 From: Dmytro Horytskyi <horytsky@adobe.com> Date: Tue, 18 Jun 2019 15:32:02 -0500 Subject: [PATCH 1997/2092] MAGETWO-99813: Redundant URL rewrites regeneration when products are added to or removed from a category --- .../Observer/UrlRewriteHandler.php | 2 +- .../Observer/UrlRewriteHandlerTest.php | 52 +++++++++----- .../_files/category_with_products.php | 71 +++++++++++++++++++ .../category_with_products_rollback.php | 30 ++++++++ 4 files changed, 136 insertions(+), 19 deletions(-) create mode 100644 dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/category_with_products.php create mode 100644 dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/category_with_products_rollback.php diff --git a/app/code/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandler.php b/app/code/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandler.php index b4a35f323e1bc..3bbbcd4052c4a 100644 --- a/app/code/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandler.php +++ b/app/code/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandler.php @@ -280,7 +280,7 @@ private function generateChangedProductUrls( /* @var Collection $collection */ $collection = $this->productCollectionFactory->create() ->setStoreId($categoryStoreId) - ->addIdFilter($category->getAffectedProductIds()) + ->addIdFilter($category->getChangedProductIds()) ->addAttributeToSelect('visibility') ->addAttributeToSelect('name') ->addAttributeToSelect('url_key') diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandlerTest.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandlerTest.php index 402db06a0bbc9..c6ed8611b3813 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandlerTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/Observer/UrlRewriteHandlerTest.php @@ -9,7 +9,6 @@ use Magento\Catalog\Api\CategoryListInterface; use Magento\Catalog\Api\Data\CategoryInterface; -use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\TestFramework\Helper\Bootstrap; @@ -19,6 +18,7 @@ /** * @magentoAppArea adminhtml + * @magentoDbIsolation disabled */ class UrlRewriteHandlerTest extends TestCase { @@ -27,6 +27,11 @@ class UrlRewriteHandlerTest extends TestCase */ private $handler; + /** + * @var ProductRepositoryInterface + */ + private $productRepository; + /** * @var ObjectManager */ @@ -38,20 +43,20 @@ class UrlRewriteHandlerTest extends TestCase protected function setUp() { $this->objectManager = Bootstrap::getObjectManager(); - $this->handler = $this->objectManager->get(UrlRewriteHandler::class); + $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); + $this->handler = $this->objectManager->create(UrlRewriteHandler::class); } /** * Checks category URLs rewrites generation with enabled `Use Categories Path for Product URLs` option and * store's specific product URL key. * - * @magentoDbIsolation disabled * @magentoDataFixture Magento/CatalogUrlRewrite/Fixtures/product_custom_url_key.php * @magentoConfigFixture admin_store catalog/seo/product_use_categories 1 */ public function testGenerateProductUrlRewrites() { - $product = $this->getProduct('p002'); + $product = $this->productRepository->get('p002'); $category = $this->getCategory('category 1'); // change the category scope to the global $category->setStoreId(0) @@ -75,6 +80,31 @@ public function testGenerateProductUrlRewrites() self::assertEquals($expected, $actual, 'Generated URLs rewrites do not match.'); } + /** + * @magentoDataFixture Magento/CatalogUrlRewrite/_files/category_with_products.php + */ + public function testGenerateProductUrlRewrites2() + { + $product1 = $this->productRepository->get('simple'); + $product2 = $this->productRepository->get('12345'); + $category = $this->getCategory('Category 1'); + + $category->setChangedProductIds([$product1->getId()]); + $category->setAffectedProductIds([$product1->getId(), $product2->getId()]); + $category->setAnchorsAbove(false); + $generatedUrls = $this->handler->generateProductUrlRewrites($category); + $actual = array_values(array_map(function (UrlRewrite $urlRewrite) { + return $urlRewrite->getRequestPath(); + }, $generatedUrls)); + + $expected = [ + 'simple-product.html', + 'category-1/simple-product.html', + '/simple-product.html', + ]; + $this->assertEquals($expected, $actual, 'Generated URLs rewrites do not match.'); + } + /** * Gets category by name. * @@ -94,18 +124,4 @@ private function getCategory(string $name): CategoryInterface return array_pop($items); } - - /** - * Gets product by SKU. - * - * @param string $sku - * @return ProductInterface - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - private function getProduct(string $sku): ProductInterface - { - /** @var ProductRepositoryInterface $productRepository */ - $productRepository = $this->objectManager->get(ProductRepositoryInterface::class); - return $productRepository->get($sku); - } } diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/category_with_products.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/category_with_products.php new file mode 100644 index 0000000000000..8d0a7ea6096a5 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/category_with_products.php @@ -0,0 +1,71 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + +$installer = $objectManager->create(\Magento\Catalog\Setup\CategorySetup::class); + +\Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea( + \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE +); + +$category = $objectManager->create(\Magento\Catalog\Model\Category::class); +$category->isObjectNew(true); +$category->setId(3) + ->setName('Category 1') + ->setParentId(2) + ->setPath('1/2/3') + ->setLevel(2) + ->setAvailableSortBy('name') + ->setDefaultSortBy('name') + ->setIsActive(true) + ->setPosition(1) + ->save(); + +$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); +$categoryLinkRepository = $objectManager->create( + \Magento\Catalog\Api\CategoryLinkRepositoryInterface::class, + [ + 'productRepository' => $productRepository + ] +); +$categoryLinkManagement = $objectManager->create( + \Magento\Catalog\Api\CategoryLinkManagementInterface::class, + [ + 'productRepository' => $productRepository, + 'categoryLinkRepository' => $categoryLinkRepository + ] +); + +$product = $objectManager->create(\Magento\Catalog\Model\Product::class); +$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE) + ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default')) + ->setStoreId(1) + ->setWebsiteIds([1]) + ->setName('Simple Product') + ->setSku('simple') + ->setPrice(10) + ->setWeight(18) + ->setStockData(['use_config_manage_stock' => 0]) + ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH) + ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) + ->save(); +$categoryLinkManagement->assignProductToCategories($product->getSku(), [3]); + +$product =$objectManager->create(\Magento\Catalog\Model\Product::class); +$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE) + ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default')) + ->setStoreId(1) + ->setWebsiteIds([1]) + ->setName('Simple Product Two') + ->setSku('12345') // SKU intentionally contains digits only + ->setPrice(45.67) + ->setWeight(56) + ->setStockData(['use_config_manage_stock' => 0]) + ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH) + ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) + ->save(); +$categoryLinkManagement->assignProductToCategories($product->getSku(), [3]); diff --git a/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/category_with_products_rollback.php b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/category_with_products_rollback.php new file mode 100644 index 0000000000000..62130ad2c7628 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogUrlRewrite/_files/category_with_products_rollback.php @@ -0,0 +1,30 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + +$registry = $objectManager->get(\Magento\Framework\Registry::class); +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', true); + +$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class); +$productSkuList = ['simple', '12345']; +foreach ($productSkuList as $sku) { + try { + $product = $productRepository->get($sku, true, null, true); + $productRepository->delete($product); + } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { + //Product already removed + } +} + +$collection = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Category\Collection::class); +$collection->addAttributeToFilter('level', 2) + ->load() + ->delete(); + +$registry->unregister('isSecureArea'); +$registry->register('isSecureArea', false); From eeac8dfb3b73bd8b19df33f1ef9d3febb9ebeb1f Mon Sep 17 00:00:00 2001 From: Serhiy Yelahin <serhiy.yelahin@transoftgroup.com> Date: Wed, 19 Jun 2019 10:22:21 +0300 Subject: [PATCH 1998/2092] MAGETWO-99659: Enabling a product doesn't clear FPC for PDP if product is not assigned to a category --- app/code/Magento/Cms/Model/Plugin/Product.php | 50 ++++++++++ .../Test/Unit/Model/Plugin/ProductTest.php | 93 +++++++++++++++++++ app/code/Magento/Cms/etc/di.xml | 3 + 3 files changed, 146 insertions(+) create mode 100644 app/code/Magento/Cms/Model/Plugin/Product.php create mode 100644 app/code/Magento/Cms/Test/Unit/Model/Plugin/ProductTest.php diff --git a/app/code/Magento/Cms/Model/Plugin/Product.php b/app/code/Magento/Cms/Model/Plugin/Product.php new file mode 100644 index 0000000000000..c8456d5cd6bfe --- /dev/null +++ b/app/code/Magento/Cms/Model/Plugin/Product.php @@ -0,0 +1,50 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Cms\Model\Plugin; + +use Magento\Catalog\Model\Product as CatalogProduct; +use Magento\Cms\Model\Page; + +/** + * Cleaning no-route page cache for the product details page after enabling product that is not assigned to a category + */ +class Product +{ + /** + * @var Page + */ + private $page; + + /** + * @param Page $page + */ + public function __construct(Page $page) + { + $this->page = $page; + } + + /** + * After get identities + * + * @param CatalogProduct $product + * @param array $identities + * @return array + */ + public function afterGetIdentities(CatalogProduct $product, array $identities) + { + if ($product->getOrigData('status') > $product->getData('status')) { + if (empty($product->getCategoryIds())) { + $noRoutePage = $this->page->load(Page::NOROUTE_PAGE_ID); + $noRoutePageId = $noRoutePage->getId(); + $identities[] = Page::CACHE_TAG . '_' . $noRoutePageId; + } + } + + return array_unique($identities); + } +} diff --git a/app/code/Magento/Cms/Test/Unit/Model/Plugin/ProductTest.php b/app/code/Magento/Cms/Test/Unit/Model/Plugin/ProductTest.php new file mode 100644 index 0000000000000..3e8d811623616 --- /dev/null +++ b/app/code/Magento/Cms/Test/Unit/Model/Plugin/ProductTest.php @@ -0,0 +1,93 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Cms\Test\Unit\Model\Plugin; + +use Magento\Catalog\Model\Product as CatalogProduct; +use Magento\Cms\Model\Page; +use Magento\Cms\Model\Plugin\Product; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit_Framework_MockObject_MockObject as MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Product plugin test + */ +class ProductTest extends TestCase +{ + /** + * @var Product + */ + private $plugin; + + /** + * @var MockObject|CatalogProduct + */ + private $product; + + /** + * @var MockObject|Page + */ + private $page; + + /** + * @inheritdoc + */ + protected function setUp() + { + $objectManager = new ObjectManager($this); + + $this->product = $this->getMockBuilder(CatalogProduct::class) + ->disableOriginalConstructor() + ->setMethods(['getEntityId', 'getOrigData', 'getData', 'getCategoryIds']) + ->getMock(); + + $this->page = $this->getMockBuilder(Page::class) + ->disableOriginalConstructor() + ->setMethods(['getId', 'load']) + ->getMock(); + + $this->plugin = $objectManager->getObject( + Product::class, + [ + 'page' => $this->page + ] + ); + } + + public function testAfterGetIdentities() + { + $baseIdentities = [ + 'SomeCacheId', + 'AnotherCacheId', + ]; + $id = 12345; + $pageId = 1; + $expectedIdentities = [ + 'SomeCacheId', + 'AnotherCacheId', + Page::CACHE_TAG . '_' . $pageId, + ]; + + $this->product->method('getEntityId') + ->willReturn($id); + $this->product->method('getOrigData') + ->with('status') + ->willReturn(2); + $this->product->method('getData') + ->with('status') + ->willReturn(1); + $this->page->method('getId') + ->willReturn(1); + $this->page->method('load') + ->willReturnSelf(); + + $identities = $this->plugin->afterGetIdentities($this->product, $baseIdentities); + + $this->assertEquals($expectedIdentities, $identities); + } +} diff --git a/app/code/Magento/Cms/etc/di.xml b/app/code/Magento/Cms/etc/di.xml index e11f7bf5933e6..622745434483c 100644 --- a/app/code/Magento/Cms/etc/di.xml +++ b/app/code/Magento/Cms/etc/di.xml @@ -197,4 +197,7 @@ </argument> </arguments> </type> + <type name="Magento\Catalog\Model\Product"> + <plugin name="cms" type="Magento\Cms\Model\Plugin\Product" sortOrder="100"/> + </type> </config> From a9f2edea30677524d4241ff34399f45e7d0ce1fd Mon Sep 17 00:00:00 2001 From: Serhiy Yelahin <serhiy.yelahin@transoftgroup.com> Date: Wed, 19 Jun 2019 12:56:53 +0300 Subject: [PATCH 1999/2092] MC-17492: Customer address attribute Phone validation issue --- app/code/Magento/Eav/Model/Attribute/Data/Text.php | 2 +- .../Magento/Eav/Test/Unit/Model/Attribute/Data/TextTest.php | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Eav/Model/Attribute/Data/Text.php b/app/code/Magento/Eav/Model/Attribute/Data/Text.php index 8235b409a39ec..1371b0f645775 100644 --- a/app/code/Magento/Eav/Model/Attribute/Data/Text.php +++ b/app/code/Magento/Eav/Model/Attribute/Data/Text.php @@ -82,7 +82,7 @@ public function validateValue($value) $errors = array_merge($errors, $result); } - $result = $this->_validateInputRule($value); + $result = $this->_validateInputRule(trim($value)); if ($result !== true) { $errors = array_merge($errors, $result); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/TextTest.php b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/TextTest.php index 8b16d286471b4..b1e2c1e37d67c 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/TextTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Attribute/Data/TextTest.php @@ -8,6 +8,9 @@ use Magento\Framework\Stdlib\StringUtils; +/** + * Eav text attribute model test + */ class TextTest extends \PHPUnit\Framework\TestCase { /** @@ -136,6 +139,7 @@ public function alphanumDataProvider(): array 'QazWsx12345', [__('"%1" length must be equal or less than %2 characters.', 'Test', 10)], ], + [' 12345 ', true], ]; } From e602b9ffb9adcd3d24febf9f4436063a3e743adf Mon Sep 17 00:00:00 2001 From: Ihor Sviziev <svizev.igor@gmail.com> Date: Wed, 19 Jun 2019 17:38:56 +0300 Subject: [PATCH 2000/2092] Remove fotorama.min.js --- lib/web/fotorama/fotorama.min.js | 1 - 1 file changed, 1 deletion(-) delete mode 100644 lib/web/fotorama/fotorama.min.js diff --git a/lib/web/fotorama/fotorama.min.js b/lib/web/fotorama/fotorama.min.js deleted file mode 100644 index f416d57488925..0000000000000 --- a/lib/web/fotorama/fotorama.min.js +++ /dev/null @@ -1 +0,0 @@ -fotoramaVersion="4.6.4",function(t,e,n,o,a){"use strict";var i="fotorama",r="fotorama__fullscreen",s=i+"__wrap",u=s+"--css2",l=s+"--css3",c=s+"--video",d=s+"--fade",h=s+"--slide",f=s+"--no-controls",m=s+"--no-shadows",v=s+"--pan-y",p=s+"--rtl",g=s+"--no-captions",w=s+"--toggle-arrows",b=i+"__stage",y=b+"__frame",x=y+"--video",_=b+"__shaft",C=i+"__grab",k=i+"__pointer",P=i+"__arr",S=P+"--disabled",T=P+"--prev",F=P+"--next",E=i+"__nav",M=E+"-wrap",j=E+"__shaft",$=M+"--vertical",z=M+"--list",q=M+"--horizontal",N=E+"--dots",A=E+"--thumbs",L=E+"__frame",O=i+"__fade",D=O+"-front",I=O+"-rear",W=i+"__shadow"+"s",R=W+"--left",H=W+"--right",K=W+"--top",Q=W+"--bottom",V=i+"__active",X=i+"__select",B=i+"--hidden",Y=i+"--fullscreen",U=i+"__fullscreen-icon",G=i+"__error",J=i+"__loading",Z=i+"__loaded",tt=Z+"--full",et=Z+"--img",nt=i+"__grabbing",ot=i+"__img",at=ot+"--full",it=i+"__thumb",rt=it+"__arr--left",st=it+"__arr--right",ut=it+"-border",lt=i+"__html",ct=i+"-video-container",dt=i+"__video",ht=dt+"-play",ft=dt+"-close",mt=i+"_horizontal_ratio",vt=i+"_vertical_ratio",pt=i+"__spinner",gt=pt+"--show",wt=o&&o.fn.jquery.split(".");if(!wt||wt[0]<1||1==wt[0]&&wt[1]<8)throw"Fotorama requires jQuery 1.8 or later and will not run without it.";var bt=function(t,e,n){var o,a,i={},r=e.documentElement,s="modernizr",u=e.createElement(s),l=u.style,c=" -webkit- -moz- -o- -ms- ".split(" "),d="Webkit Moz O ms",h=d.split(" "),f=d.toLowerCase().split(" "),m={},v=[],p=v.slice,g=function(t,n,o,a){var i,u,l,c,d=e.createElement("div"),h=e.body,f=h||e.createElement("body");if(parseInt(o,10))for(;o--;)(l=e.createElement("div")).id=a?a[o]:s+(o+1),d.appendChild(l);return i=["­",'<style id="s',s,'">',t,"</style>"].join(""),d.id=s,(h?d:f).innerHTML+=i,f.appendChild(d),h||(f.style.background="",f.style.overflow="hidden",c=r.style.overflow,r.style.overflow="hidden",r.appendChild(f)),u=n(d,t),h?d.parentNode.removeChild(d):(f.parentNode.removeChild(f),r.style.overflow=c),!!u},w={}.hasOwnProperty;function b(t){l.cssText=t}function y(t,e){return typeof t===e}function x(t,e){for(var o in t){var a=t[o];if(!~(""+a).indexOf("-")&&l[a]!==n)return"pfx"!=e||a}return!1}function _(t,e,o){var a=t.charAt(0).toUpperCase()+t.slice(1),i=(t+" "+h.join(a+" ")+a).split(" ");return y(e,"string")||y(e,"undefined")?x(i,e):function(t,e,o){for(var a in t){var i=e[t[a]];if(i!==n)return!1===o?t[a]:y(i,"function")?i.bind(o||e):i}return!1}(i=(t+" "+f.join(a+" ")+a).split(" "),e,o)}for(var C in a=y(w,"undefined")||y(w.call,"undefined")?function(t,e){return e in t&&y(t.constructor.prototype[e],"undefined")}:function(t,e){return w.call(t,e)},Function.prototype.bind||(Function.prototype.bind=function(t){var e=this;if("function"!=typeof e)throw new TypeError;var n=p.call(arguments,1),o=function(){if(this instanceof o){var a=function(){};a.prototype=e.prototype;var i=new a,r=e.apply(i,n.concat(p.call(arguments)));return Object(r)===r?r:i}return e.apply(t,n.concat(p.call(arguments)))};return o}),m.touch=function(){var n;return"ontouchstart"in t||t.DocumentTouch&&e instanceof DocumentTouch?n=!0:g(["@media (",c.join("touch-enabled),("),s,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(t){n=9===t.offsetTop}),n},m.csstransforms3d=function(){var t=!!_("perspective");return t&&"webkitPerspective"in r.style&&g("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(e,n){t=9===e.offsetLeft&&3===e.offsetHeight}),t},m.csstransitions=function(){return _("transition")},m)a(m,C)&&(o=C.toLowerCase(),i[o]=m[C](),v.push((i[o]?"":"no-")+o));return i.addTest=function(t,e){if("object"==typeof t)for(var o in t)a(t,o)&&i.addTest(o,t[o]);else{if(t=t.toLowerCase(),i[t]!==n)return i;e="function"==typeof e?e():e,"undefined"!=typeof enableClasses&&enableClasses&&(r.className+=" "+(e?"":"no-")+t),i[t]=e}return i},b(""),u=null,i._version="2.8.3",i._prefixes=c,i._domPrefixes=f,i._cssomPrefixes=h,i.testProp=function(t){return x([t])},i.testAllProps=_,i.testStyles=g,i.prefixed=function(t,e,n){return e?_(t,e,n):_(t,"pfx")},i}(t,e),yt={ok:!1,is:function(){return!1},request:function(){},cancel:function(){},event:"",prefix:""},xt="webkit moz o ms khtml".split(" ");if(void 0!==e.cancelFullScreen)yt.ok=!0;else for(var _t=0,Ct=xt.length;_t<Ct;_t++)if(yt.prefix=xt[_t],void 0!==e[yt.prefix+"CancelFullScreen"]){yt.ok=!0;break}yt.ok&&(yt.event=yt.prefix+"fullscreenchange",yt.is=function(){switch(this.prefix){case"":return e.fullScreen;case"webkit":return e.webkitIsFullScreen;default:return e[this.prefix+"FullScreen"]}},yt.request=function(t){return""===this.prefix?t.requestFullScreen():t[this.prefix+"RequestFullScreen"]()},yt.cancel=function(t){return""===this.prefix?e.cancelFullScreen():e[this.prefix+"CancelFullScreen"]()});var kt,Pt,St=o(t),Tt=o(e),Ft="quirks"===n.hash.replace("#",""),Et=bt.csstransforms3d,Mt=Et&&!Ft,jt=Et||"CSS1Compat"===e.compatMode,$t=yt.ok,zt=navigator.userAgent.match(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i),qt=!Mt||zt,Nt=navigator.msPointerEnabled,At="onwheel"in e.createElement("div")?"wheel":e.onmousewheel!==a?"mousewheel":"DOMMouseScroll",Lt=250,Ot=300,Dt=1400,It=5e3,Wt=64,Rt=500,Ht=333,Kt="$stageFrame",Qt="$navDotFrame",Vt="$navThumbFrame",Xt="auto",Bt=function(t){var e="bez_"+o.makeArray(arguments).join("_").replace(".","p");if("function"!=typeof o.easing[e]){var n=function(t,e){var n=[null,null],o=[null,null],a=[null,null],i=function(i,r){return a[r]=3*t[r],o[r]=3*(e[r]-t[r])-a[r],n[r]=1-a[r]-o[r],i*(a[r]+i*(o[r]+i*n[r]))};return function(t){return i(function(t){for(var e,r,s=t,u=0;++u<14&&(e=i(s,0)-t,!(Math.abs(e)<.001));)s-=e/(r=s,a[0]+r*(2*o[0]+3*n[0]*r));return s}(t),1)}};o.easing[e]=function(e,o,a,i,r){return i*n([t[0],t[1]],[t[2],t[3]])(o/r)+a}}return e}([.1,0,.25,1]),Yt=1,Ut={width:null,minwidth:null,maxwidth:"100%",height:null,minheight:null,maxheight:null,ratio:null,margin:2,nav:"dots",navposition:"bottom",navwidth:null,thumbwidth:Wt,thumbheight:Wt,thumbmargin:2,thumbborderwidth:2,allowfullscreen:!1,transition:"slide",clicktransition:null,transitionduration:Ot,captions:!0,startindex:0,loop:!1,autoplay:!1,stopautoplayontouch:!0,keyboard:!1,arrows:!0,click:!0,swipe:!1,trackpad:!1,shuffle:!1,direction:"ltr",shadows:!0,showcaption:!0,navdir:"horizontal",navarrows:!0,navtype:"thumbs"},Gt={left:!0,right:!0,down:!0,up:!0,space:!1,home:!1,end:!1};function Jt(){}function Zt(t,e,n){return Math.max(isNaN(e)?-1/0:e,Math.min(isNaN(n)?1/0:n,t))}function te(t,e){return Mt?(n=t.css("transform"),o=e,+(n.match(/ma/)&&n.match(/-?\d+(?!d)/g)[n.match(/3d/)?"vertical"===o?13:12:"vertical"===o?5:4])):+t.css("vertical"===e?"top":"left").replace("px","");var n,o}function ee(t,e){var n={};if(Mt)switch(e){case"vertical":n.transform="translate3d(0, "+t+"px,0)";break;case"list":break;default:n.transform="translate3d("+t+"px,0,0)"}else"vertical"===e?n.top=t:n.left=t;return n}function ne(t){return{"transition-duration":t+"ms"}}function oe(t,e){return isNaN(t)?e:t}function ae(t,e){return oe(+String(t).replace(e||"px",""))}function ie(t,e){return oe((/%$/.test(n=t)?ae(n,"%"):a)/100*e,ae(t));var n}function re(t){return(!isNaN(ae(t))||!isNaN(ae(t,"%")))&&t}function se(t,e,n,o){return(t-(o||0))*(e+(n||0))}function ue(t,e,n,o){var a,i,r,s=t.data();s&&(s.onEndFn=function(){a||(a=!0,clearTimeout(s.tT),n())},s.tProp=e,clearTimeout(s.tT),s.tT=setTimeout(function(){s.onEndFn()},1.5*o),(r=(i=t).data()).tEnd||(Te(i[0],{WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",msTransition:"MSTransitionEnd",transition:"transitionend"}[bt.prefixed("transition")],function(t){r.tProp&&t.propertyName.match(r.tProp)&&r.onEndFn()}),r.tEnd=!0))}function le(t,e){var n=t.navdir||"horizontal";if(t.length){var o=t.data();Mt?(t.css(ne(0)),o.onEndFn=Jt,clearTimeout(o.tT)):t.stop();var a=ce(e,function(){return te(t,n)});return t.css(ee(a,n)),a}}function ce(){for(var t,e=0,n=arguments.length;e<n&&"number"!=typeof(t=e?arguments[e]():arguments[e]);e++);return t}function de(t,e){return Math.round(t+(e-t)/1.5)}function he(){return he.p=he.p||("https:"===n.protocol?"https://":"http://"),he.p}function fe(t,n){if("string"!=typeof t)return t;var o,a,i,r;if(o=t,(a=e.createElement("a")).href=o,(t=a).host.match(/youtube\.com/)&&t.search){if(i=t.search.split("v=")[1]){var s=i.indexOf("&");-1!==s&&(i=i.substring(0,s)),r="youtube"}}else t.host.match(/youtube\.com|youtu\.be/)?(i=t.pathname.replace(/^\/(embed\/|v\/)?/,"").replace(/\/.*/,""),r="youtube"):t.host.match(/vimeo\.com/)&&(r="vimeo",i=t.pathname.replace(/^\/(video\/)?/,"").replace(/\/.*/,""));return i&&r||!n||(i=t.href,r="custom"),!!i&&{id:i,type:r,s:t.search.replace(/^\?/,""),p:he()}}function me(t,e,n,a){for(var i=0,r=t.length;i<r;i++){var s=t[i];if(s.i===n&&s.thumbsReady){var u={videoReady:!0};u[Kt]=u[Vt]=u[Qt]=!1,a.splice(i,1,o.extend({},s,u,e));break}}}function ve(t){var e=[];function n(t,e,n){var a=n.thumb&&n.img!==n.thumb,i=ae(n.width||t.attr("width")),r=ae(n.height||t.attr("height"));o.extend(n,{width:i,height:r,thumbratio:Se(n.thumbratio||ae(n.thumbwidth||e&&e.attr("width")||a||i)/ae(n.thumbheight||e&&e.attr("height")||a||r))})}return t.children().each(function(){var t,a,i,r,s,u,l,c,d,h=o(this),f=Pe(o.extend(h.data(),{id:h.attr("id")}));if(h.is("a, img"))a=f,i=!0,r=(t=h).children("img").eq(0),s=t.attr("href"),u=t.attr("src"),l=r.attr("src"),c=a.video,(d=!!i&&fe(s,!0===c))?s=!1:d=c,n(t,r,o.extend(a,{video:d,img:a.img||s||u||l,thumb:a.thumb||l||u||s}));else{if(h.is(":empty"))return;n(h,null,o.extend(f,{html:this,_html:h.html()}))}e.push(f)}),e}function pe(t,e,n,o){return pe.i||(pe.i=1,pe.ii=[!0]),o=o||pe.i,void 0===pe.ii[o]&&(pe.ii[o]=!0),t()?e():pe.ii[o]&&setTimeout(function(){pe.ii[o]&&pe(t,e,n,o)},n||100),pe.i++}function ge(t,e){var n=t.data(),o=n.measures;if(o&&(!n.l||n.l.W!==o.width||n.l.H!==o.height||n.l.r!==o.ratio||n.l.w!==e.w||n.l.h!==e.h)){var a=Zt(e.h,0,o.height),i=a*o.ratio;De.setRatio(t,i,a),n.l={W:o.width,H:o.height,r:o.ratio,w:e.w,h:e.h}}return!0}function we(t,e,n,o){return e!==n&&("vertical"===o?t<=e?"top":t>=n?"bottom":"top bottom":t<=e?"left":t>=n?"right":"left right")}function be(t,e,n){n=n||{},t.each(function(){var t,a=o(this),i=a.data();i.clickOn||(i.clickOn=!0,o.extend(Re(a,{onStart:function(e){t=e,(n.onStart||Jt).call(this,e)},onMove:n.onMove||Jt,onTouchEnd:n.onTouchEnd||Jt,onEnd:function(n){n.moved||e.call(this,t)}}),{noMove:!0}))})}function ye(t,e){return'<div class="'+t+'">'+(e||"")+"</div>"}function xe(t){return"."+t}function _e(t){for(var e=t.length;e;){var n=Math.floor(Math.random()*e--),o=t[e];t[e]=t[n],t[n]=o}return t}function Ce(t){return"[object Array]"==Object.prototype.toString.call(t)&&o.map(t,function(t){return o.extend({},t)})}function ke(t,e,n){t.scrollLeft(e||0).scrollTop(n||0)}function Pe(t){if(t){var e={};return o.each(t,function(t,n){e[t.toLowerCase()]=n}),e}}function Se(t){if(t){var e=+t;return isNaN(e)?+(e=t.split("/"))[0]/+e[1]||a:e}}function Te(t,e,n,o){e&&(t.addEventListener?t.addEventListener(e,n,!!o):t.attachEvent("on"+e,n))}function Fe(t,e){return t>e.max?t=e.max:t<e.min&&(t=e.min),t}function Ee(t,e){return e?{disabled:t}:{tabindex:-1*t+"",disabled:t}}function Me(t,e){Te(t,"keyup",function(n){t.getAttribute("disabled")||13==n.keyCode&&e.call(t,n)})}function je(t,e){Te(t,"focus",t.onfocusin=function(n){e.call(t,n)},!0)}function $e(t,e){t.preventDefault?t.preventDefault():t.returnValue=!1,e&&t.stopPropagation&&t.stopPropagation()}function ze(t){return t?">":"<"}pe.stop=function(t){pe.ii[t]=!1};var qe,Ne,Ae,Le,Oe,De=function(){return{setRatio:function(t,e,n){e/n<=1?(t.parent().removeClass(mt),t.parent().addClass(vt)):(t.parent().removeClass(vt),t.parent().addClass(mt))},setThumbAttr:function(t,e,n){var i=n;t.attr(i)||t.attr(i)===a||t.attr(i,e),t.find("["+i+"]").length&&t.find("["+i+"]").each(function(){o(this).attr(i,e)})},isExpectedCaption:function(t,e,n){var o,a=!1;return o=t.showCaption===n||!0===t.showCaption,!!e&&(t.caption&&o&&(a=!0),a)}}}(jQuery);function Ie(t,e){var n=t.data(),a=Math.round(e.pos),i=function(){n&&n.sliding&&(n.sliding=!1),(e.onEnd||Jt)()};void 0!==e.overPos&&e.overPos!==e.pos&&(a=e.overPos);var r=o.extend(ee(a,e.direction),e.width&&{width:e.width},e.height&&{height:e.height});n&&n.sliding&&(n.sliding=!0),Mt?(t.css(o.extend(ne(e.time),r)),e.time>10?ue(t,"transform",i,e.time):i()):t.stop().animate(r,e.time,Bt,i)}function We(t){var e=(t.touches||[])[0]||t;t._x=e.pageX||e.originalEvent.pageX,t._y=e.clientY||e.originalEvent.clientY,t._now=o.now()}function Re(t,n){var a,i,r,s,u,l,c,d,h,f=t[0],m={};function v(t){if(r=o(t.target),m.checked=l=c=h=!1,a||m.flow||t.touches&&t.touches.length>1||t.which>1||qe&&qe.type!==t.type&&Ae||(l=n.select&&r.is(n.select,f)))return l;u="touchstart"===t.type,c=r.is("a, a *",f),s=m.control,d=m.noMove||m.noSwipe||s?16:m.snap?0:4,We(t),i=qe=t,Ne=t.type.replace(/down|start/,"move").replace(/Down/,"Move"),(n.onStart||Jt).call(f,t,{control:s,$target:r}),a=m.flow=!0,u&&!m.go||$e(t)}function p(t){if(t.touches&&t.touches.length>1||Nt&&!t.isPrimary||Ne!==t.type||!a)return a&&w(),void(n.onTouchEnd||Jt)();We(t);var e=Math.abs(t._x-i._x),o=Math.abs(t._y-i._y),r=e-o,s=(m.go||m.x||r>=0)&&!m.noSwipe,l=r<0;u&&!m.checked?(a=s)&&$e(t):($e(t),g(e,o)&&(n.onMove||Jt).call(f,t,{touch:u})),!h&&g(e,o)&&Math.sqrt(Math.pow(e,2)+Math.pow(o,2))>d&&(h=!0),m.checked=m.checked||s||l}function g(t,e){return t>e&&t>1.5}function w(t){(n.onTouchEnd||Jt)();var e=a;m.control=a=!1,e&&(m.flow=!1),!e||c&&!m.checked||(t&&$e(t),Ae=!0,clearTimeout(Le),Le=setTimeout(function(){Ae=!1},1e3),(n.onEnd||Jt).call(f,{moved:h,$target:r,control:s,touch:u,startEvent:i,aborted:!t||"MSPointerCancel"===t.type}))}function b(){m.flow&&(m.flow=!1)}return Nt?(Te(f,"MSPointerDown",v),Te(e,"MSPointerMove",p),Te(e,"MSPointerCancel",w),Te(e,"MSPointerUp",w)):(Te(f,"touchstart",v),Te(f,"touchmove",p),Te(f,"touchend",w),Te(e,"touchstart",function(){m.flow||(m.flow=!0)}),Te(e,"touchend",b),Te(e,"touchcancel",b),St.on("scroll",b),t.on("mousedown pointerdown",v),Tt.on("mousemove pointermove",p).on("mouseup pointerup",w)),Oe=bt.touch?"a":"div",t.on("click",Oe,function(t){m.checked&&$e(t)}),m}function He(t,e){var n,a,i,r,s,u,l,c,d,h,f,m,v,p,g,w=t[0],b=t.data(),y={};function x(o,s){g=!0,n=a="vertical"===m?o._y:o._x,l=o._now,u=[[l,n]],i=r=y.noMove||s?0:le(t,(e.getPos||Jt)()),(e.onStart||Jt).call(w,o)}return y=o.extend(Re(e.$wrap,o.extend({},e,{onStart:function(e,n){d=y.min,h=y.max,f=y.snap,m=y.direction||"horizontal",t.navdir=m,v=e.altKey,g=p=!1,n.control||b.sliding||x(e)},onMove:function(o,l){y.noSwipe||(g||x(o),a="vertical"===m?o._y:o._x,u.push([o._now,a]),s=we(r=i-(n-a),d,h,m),r<=d?r=de(r,d):r>=h&&(r=de(r,h)),y.noMove||(t.css(ee(r,m)),p||(p=!0,l.touch||Nt||t.addClass(nt)),(e.onMove||Jt).call(w,o,{pos:r,edge:s})))},onEnd:function(n){if(!y.noSwipe||!n.moved){g||x(n.startEvent,!0),n.touch||Nt||t.removeClass(nt);for(var s,l,p,b,_,C,k,P,S,T=(c=o.now())-Lt,F=null,E=Ot,M=e.friction,j=u.length-1;j>=0;j--){if(s=u[j][0],l=Math.abs(s-T),null===F||l<p)F=s,b=u[j][1];else if(F===T||l>p)break;p=l}k=Zt(r,d,h);var $=b-a,z=$>=0,q=c-F,N=q>Lt,A=!N&&r!==i&&k===r;f&&(k=Zt(Math[A?z?"floor":"ceil":"round"](r/f)*f,d,h),d=h=k),A&&(f||k===r)&&(S=-$/q,E*=Zt(Math.abs(S),e.timeLow,e.timeHigh),_=Math.round(r+S*E/M),f||(k=_),(!z&&_>h||z&&_<d)&&(C=z?d:h,f||(k=C),P=Zt(k+.03*(P=_-C),C-50,C+50),E=Math.abs((r-P)/(S/M)))),E*=v?10:1,(e.onEnd||Jt).call(w,o.extend(n,{moved:n.moved||N&&f,pos:r,newPos:k,overPos:P,time:E,dir:m}))}}})),y)}function Ke(t,e){var n,a,i,r=t[0],s={prevent:{}};return Te(r,At,function(t){var r=t.wheelDeltaY||-1*t.deltaY||0,u=t.wheelDeltaX||-1*t.deltaX||0,l=Math.abs(u)&&!Math.abs(r),c=ze(u<0),d=a===c,h=o.now(),f=h-i<Lt;a=c,i=h,l&&s.ok&&(!s.prevent[c]||n)&&($e(t,!0),n&&d&&f||(e.shift&&(n=!0,clearTimeout(s.t),s.t=setTimeout(function(){n=!1},Dt)),(e.onEnd||Jt)(t,e.shift?c:u)))}),s}function Qe(){o.each(o.Fotorama.instances,function(t,e){e.index=t})}jQuery.Fotorama=function(n,O){kt=o("html"),Pt=o("body");var nt,it,mt,vt,wt,bt,xt,_t,Ct,Ft,Et,zt,At,Dt,Bt,Ut,oe,ue,de,Te,qe,Ne,Ae,Le,Oe,We,Re,Ve,Xe,Be,Ye,Ue,Ge,Je,Ze,tn,en=this,nn=o.now(),on=i+nn,an=n[0],rn=1,sn=n.data(),un=o("<style></style>"),ln=o(ye(B)),cn=n.find(xe(s)),dn=cn.find(xe(b)),hn=(dn[0],n.find(xe(_))),fn=o(),mn=n.find(xe(T)),vn=n.find(xe(F)),pn=n.find(xe(P)),gn=n.find(xe(M)),wn=gn.find(xe(E)),bn=wn.find(xe(j)),yn=o(),xn=o(),_n=(hn.data(),bn.data(),n.find(xe(ut))),Cn=n.find(xe(rt)),kn=n.find(xe(st)),Pn=n.find(xe(U)),Sn=Pn[0],Tn=o(ye(ht)),Fn=n.find(xe(ft))[0],En=n.find(xe(pt)),Mn=!1,jn={},$n={},zn={},qn={},Nn={},An={},Ln={},On=0,Dn=[];function In(){o.each(nt,function(t,e){if(!e.i){e.i=rn++;var n=fe(e.video,!0);if(n){var a={};e.video=n,e.img||e.thumb?e.thumbsReady=!0:(r=nt,s=en,"youtube"===(c=(i=e).video).type?(u=(l=he()+"img.youtube.com/vi/"+c.id+"/default.jpg").replace(/\/default.jpg$/,"/hqdefault.jpg"),i.thumbsReady=!0):"vimeo"===c.type?o.ajax({url:he()+"vimeo.com/api/v2/video/"+c.id+".json",dataType:"jsonp",success:function(t){i.thumbsReady=!0,me(r,{img:t[0].thumbnail_large,thumb:t[0].thumbnail_small},i.i,s)}}):i.thumbsReady=!0,a={img:u,thumb:l}),me(nt,{img:a.img,thumb:a.thumb},e.i,en)}}var i,r,s,u,l,c})}function Wn(t){return Re[t]}function Rn(){if(dn!==a)if("vertical"==O.navdir){var t=O.thumbwidth+O.thumbmargin;dn.css("left",t),vn.css("right",t),Pn.css("right",t),cn.css("width",cn.css("width")+t),hn.css("max-width",cn.width()-t)}else dn.css("left",""),vn.css("right",""),Pn.css("right",""),cn.css("width",cn.css("width")+t),hn.css("max-width","")}function Hn(t){var e,a,s,u,l,c,d,h,f;t!==Hn.f&&(t?(n.addClass(i+" "+on).before(ln).before(un),a=en,o.Fotorama.instances.push(a),Qe()):(ln.detach(),un.detach(),n.html(sn.urtext).removeClass(on),e=en,o.Fotorama.instances.splice(e.index,1),Qe()),l="keydown."+i,d="keydown."+(c=i+nn),h="keyup."+c,f="resize."+c+" orientationchange."+c,(s=t)?(Tt.on(d,function(t){var e,n;vt&&27===t.keyCode?(e=!0,Mo(vt,!0,!0)):(en.fullScreen||O.keyboard&&!en.index)&&(27===t.keyCode?(e=!0,en.cancelFullScreen()):t.shiftKey&&32===t.keyCode&&Wn("space")||37===t.keyCode&&Wn("left")||38===t.keyCode&&Wn("up")&&o(":focus").attr("data-gallery-role")?(en.longPress.progress(),n="<"):32===t.keyCode&&Wn("space")||39===t.keyCode&&Wn("right")||40===t.keyCode&&Wn("down")&&o(":focus").attr("data-gallery-role")?(en.longPress.progress(),n=">"):36===t.keyCode&&Wn("home")?(en.longPress.progress(),n="<<"):35===t.keyCode&&Wn("end")&&(en.longPress.progress(),n=">>")),(e||n)&&$e(t),u={index:n,slow:t.altKey,user:!0},n&&(en.longPress.inProgress?en.showWhileLongPress(u):en.show(u))}),s&&Tt.on(h,function(t){en.longPress.inProgress&&en.showEndLongPress({user:!0}),en.longPress.reset()}),en.index||Tt.off(l).on(l,"textarea, input, select",function(t){!Pt.hasClass(r)&&t.stopPropagation()}),St.on(f,en.resize)):(Tt.off(d),St.off(f)),Hn.f=t)}function Kn(){var t=it<2||vt;$n.noMove=t||Te,$n.noSwipe=t||!O.swipe,!Le&&hn.toggleClass(C,!O.click&&!$n.noMove&&!$n.noSwipe),Nt&&cn.toggleClass(v,!$n.noSwipe)}function Qn(t){!0===t&&(t=""),O.autoplay=Math.max(+t||It,1.5*Ae)}function Vn(t,e){return Math.floor(cn.width()/(e.thumbwidth+e.thumbmargin))}function Xn(){var t;O.nav&&"dots"!==O.nav||(O.navdir="horizontal"),en.options=O=Pe(O),Yt=Vn(0,O),Te="crossfade"===O.transition||"dissolve"===O.transition,Dt=O.loop&&(it>2||Te&&(!Le||"slide"!==Le)),Ae=+O.transitionduration||Ot,We="rtl"===O.direction,Re=o.extend({},O.keyboard&&Gt,O.keyboard),(t=O).navarrows&&"thumbs"===t.nav?(Cn.show(),kn.show()):(Cn.hide(),kn.hide());var e,n,a,i,r={add:[],remove:[]};function s(t,e){r[t?"add":"remove"].push(e)}it>1?(Bt=O.nav,oe="top"===O.navposition,r.remove.push(X),pn.toggle(O.arrows)):(Bt=!1,pn.hide()),co(),fo(),ho(),O.autoplay&&Qn(O.autoplay),qe=ae(O.thumbwidth)||Wt,Ne=ae(O.thumbheight)||Wt,zn.ok=Nn.ok=O.trackpad&&!qt,Kn(),yo(O,[jn]),Ut="thumbs"===Bt,gn.filter(":hidden")&&Bt&&gn.show(),Ut?(ao(it,"navThumb"),mt=xn,tn=Vt,e=un,n=o.Fotorama.jst.style({w:qe,h:Ne,b:O.thumbborderwidth,m:O.thumbmargin,s:nn,q:!jt}),(a=e[0]).styleSheet?a.styleSheet.cssText=n:e.html(n),wn.addClass(A).removeClass(N)):"dots"===Bt?(ao(it,"navDot"),mt=yn,tn=Qt,wn.addClass(N).removeClass(A)):(gn.hide(),Bt=!1,wn.removeClass(A+" "+N)),Bt&&(oe?gn.insertBefore(dn):gn.insertAfter(dn),uo.nav=!1,uo(mt,bn,"nav")),(ue=O.allowfullscreen)?(Pn.prependTo(dn),de=$t&&"native"===ue,i="touchend",Pn.on(i,function(t){return $e(t,!0),!1})):(Pn.detach(),de=!1),s(Te,d),s(!Te,h),s(!O.captions,g),s(We,p),s(O.arrows,w),s(!(Oe=O.shadows&&!qt),m),cn.addClass(r.add.join(" ")).removeClass(r.remove.join(" ")),o.extend({},O),Rn()}function Bn(t){return t<0?(it+t%it)%it:t>=it?t%it:t}function Yn(t){return Zt(t,0,it-1)}function Un(t){return Dt?Bn(t):Yn(t)}function Gn(t){return!!(t>0||Dt)&&t-1}function Jn(t){return!!(t<it-1||Dt)&&t+1}function Zn(t,e,n){if("number"==typeof t){t=new Array(t);var a=!0}return o.each(t,function(t,o){if(a&&(o=t),"number"==typeof o){var i=nt[Bn(o)];if(i){var r="$"+e+"Frame",s=i[r];n.call(this,t,o,i,s,r,s&&s.data())}}})}function to(t,e,n,o){(!Ve||"*"===Ve&&o===At)&&(t=re(O.width)||re(t)||Rt,e=re(O.height)||re(e)||Ht,en.resize({width:t,ratio:O.ratio||n||t/e},0,o!==At&&"*"))}function eo(t,e,n,a){Zn(t,e,function(t,i,r,s,u,l){if(s){var c=en.fullScreen&&!l.$full&&"stage"===e;if(!l.$img||a||c){var d=new Image,h=o(d),f=h.data();l[c?"$full":"$img"]=h;var m="stage"===e?c?"full":"img":"thumb",v=r[m],p=c?r.img:r["stage"===e?"thumb":"img"];"navThumb"===e&&(s=l.$wrap),v?(o.Fotorama.cache[v]?function t(){"error"===o.Fotorama.cache[v]?w():"loaded"===o.Fotorama.cache[v]?setTimeout(b,0):setTimeout(t,100)}():(o.Fotorama.cache[v]="*",h.on("load",b).on("error",w)),l.state="",d.src=v,l.data.caption&&(d.alt=l.data.caption||""),l.data.full&&o(d).data("original",l.data.full),De.isExpectedCaption(r,O.showcaption)&&o(d).attr("aria-labelledby",r.labelledby)):w()}}function g(t){var e=Bn(i);xo(t,{index:e,src:v,frame:nt[e]})}function w(){h.remove(),o.Fotorama.cache[v]="error",r.html&&"stage"===e||!p||p===v?(!v||r.html||c?"stage"===e&&(s.trigger("f:load").removeClass(J+" "+G).addClass(Z),g("load"),to()):(s.trigger("f:error").removeClass(J).addClass(G),g("error")),l.state="error",!(it>1&&nt[i]===r)||r.html||r.deleted||r.video||c||(r.deleted=!0,en.splice(i,1))):(r[m]=v=p,l.$full=null,eo([i],e,n,!0))}function b(){var t=10;pe(function(){return!Je||!t--&&!qt},function(){o.Fotorama.measures[v]=f.measures=o.Fotorama.measures[v]||{width:d.width,height:d.height,ratio:d.width/d.height},to(f.measures.width,f.measures.height,f.measures.ratio,i),h.off("load error").addClass(""+(c?at:ot)).attr("aria-hidden","false").prependTo(s),s.hasClass(y)&&!s.hasClass(ct)&&s.attr("href",h.attr("src")),ge(h,(o.isFunction(n)?n():n)||jn),o.Fotorama.cache[v]=l.state="loaded",setTimeout(function(){s.trigger("f:load").removeClass(J+" "+G).addClass(Z+" "+(c?tt:et)),"stage"===e?g("load"):(r.thumbratio===Xt||!r.thumbratio&&O.thumbratio===Xt)&&(r.thumbratio=f.measures.ratio,Oo())},0)})}})}function no(){var t=wt[Kt];t&&!t.data().state&&(En.addClass(gt),t.on("f:load f:error",function(){t.off("f:load f:error"),En.removeClass(gt)}))}function oo(t){Me(t,No),je(t,function(){setTimeout(function(){ke(wn)},0),po({time:Ae,guessIndex:o(this).data().eq,minMax:qn})})}function ao(t,e){Zn(t,e,function(t,n,a,i,r,s){if(!i){i=a[r]=cn[r].clone(),(s=i.data()).data=a;var u=i[0],l="labelledby"+o.now();"stage"===e?(a.html&&o('<div class="'+lt+'"></div>').append(a._html?o(a.html).removeAttr("id").html(a._html):a.html).appendTo(i),a.id&&(l=a.id||l),a.labelledby=l,De.isExpectedCaption(a,O.showcaption)&&o(o.Fotorama.jst.frameCaption({caption:a.caption,labelledby:l})).appendTo(i),a.video&&i.addClass(x).append(Tn.clone()),je(u,function(){setTimeout(function(){ke(dn)},0),zo({index:s.eq,user:!0})}),fn=fn.add(i)):"navDot"===e?(oo(u),yn=yn.add(i)):"navThumb"===e&&(oo(u),s.$wrap=i.children(":first"),xn=xn.add(i),a.video&&s.$wrap.append(Tn.clone()))}})}function io(t,e){return t&&t.length&&ge(t,e)}function ro(t){Zn(t,"stage",function(t,n,a,i,r,s){if(i){var u,l=Bn(n);s.eq=l,Ln[Kt][l]=i.css(o.extend({left:Te?0:se(n,jn.w,O.margin,xt)},Te&&ne(0))),u=i[0],o.contains(e.documentElement,u)||(i.appendTo(hn),Mo(a.$video)),io(s.$img,jn),io(s.$full,jn),!i.hasClass(y)||"false"===i.attr("aria-hidden")&&i.hasClass(V)||i.attr("aria-hidden","true")}})}function so(t,e){var n,a;"thumbs"!==Bt||isNaN(t)||(n=-t,a=-t+jn.nw,"vertical"===O.navdir&&(t-=O.thumbheight,a=-t+jn.h),xn.each(function(){var t=o(this).data(),i=t.eq,r=function(){return{h:Ne,w:t.w}},s=r(),u="vertical"===O.navdir?t.t>a:t.l>a;s.w=t.w,t.l+t.w<n||u||io(t.$img,s)||e&&eo([i],"navThumb",r)}))}function uo(t,e,n){if(!uo[n]){var a="nav"===n&&Ut,i=0,r=0;e.append(t.filter(function(){for(var t,e=o(this),n=e.data(),a=0,i=nt.length;a<i;a++)if(n.data===nt[a]){t=!0,n.eq=a;break}return t||e.remove()&&!1}).sort(function(t,e){return o(t).data().eq-o(e).data().eq}).each(function(){var t=o(this),e=t.data();De.setThumbAttr(t,e.data.caption,"aria-label")}).each(function(){if(a){var t=o(this),e=t.data(),n=Math.round(Ne*e.data.thumbratio)||qe,s=Math.round(qe/e.data.thumbratio)||Ne;e.t=r,e.h=s,e.l=i,e.w=n,t.css({width:n}),r+=s+O.thumbmargin,i+=n+O.thumbmargin}})),uo[n]=!0}}function lo(t){return!(Dt||Mn+t&&Mn-it+t||vt)}function co(){var t=lo(0),e=lo(1);mn.toggleClass(S,t).attr(Ee(t,!1)),vn.toggleClass(S,e).attr(Ee(e,!1))}function ho(){var t=!1,e=!1;if("thumbs"!==O.navtype||O.loop||(t=0==Mn,e=Mn==O.data.length-1),"slides"===O.navtype){var n=te(bn,O.navdir);t=n>=qn.max,e=n<=qn.min}Cn.toggleClass(S,t).attr(Ee(t,!0)),kn.toggleClass(S,e).attr(Ee(e,!0))}function fo(){zn.ok&&(zn.prevent={"<":lo(0),">":lo(1)})}function mo(t){var e,n,o,a,i=t.data();Ut?(e=i.l,n=i.t,o=i.w,a=i.h):(e=t.position().left,o=t.width());var r={c:e+o/2,min:-e+10*O.thumbmargin,max:-e+jn.w-o-10*O.thumbmargin},s={c:n+a/2,min:-n+10*O.thumbmargin,max:-n+jn.h-a-10*O.thumbmargin};return"vertical"===O.navdir?s:r}function vo(t){var e=wt[tn].data();Ie(_n,{time:1.2*t,pos:"vertical"===O.navdir?e.t:e.l,width:e.w,height:e.h,direction:O.navdir})}function po(t){var e,n,o,a,i,r,s,u,l,c,d,h,f,m,v,p,g,w=nt[t.guessIndex][tn],b=O.navtype;w&&("thumbs"===b?(e=qn.min!==qn.max,o=t.minMax||e&&mo(wt[tn]),a=e&&(t.keep&&po.t?po.l:Zt((t.coo||jn.nw/2)-mo(w).c,o.min,o.max)),i=e&&(t.keep&&po.l?po.l:Zt((t.coo||jn.nw/2)-mo(w).c,o.min,o.max)),r="vertical"===O.navdir?a:i,s=e&&Zt(r,qn.min,qn.max)||0,n=1.1*t.time,Ie(bn,{time:n,pos:s,direction:O.navdir,onEnd:function(){so(s,!0),ho()}}),Eo(wn,we(s,qn.min,qn.max,O.navdir)),po.l=r):(u=te(bn,O.navdir),n=1.11*t.time,l=O,c=qn,d=t.guessIndex,h=u,f=w,m=gn,"horizontal"===(v=O.navdir)?(p=l.thumbwidth,g=m.width()):(p=l.thumbheight,g=m.height()),s=Fe((p+l.margin)*(d+1)>=g-h?"horizontal"===v?-f.position().left:-f.position().top:(p+l.margin)*d<=Math.abs(h)?"horizontal"===v?-f.position().left+g-(p+l.margin):-f.position().top+g-(p+l.margin):h,c)||0,Ie(bn,{time:n,pos:s,direction:O.navdir,onEnd:function(){so(s,!0),ho()}}),Eo(wn,we(s,qn.min,qn.max,O.navdir))))}function go(t){for(var e=An[t];e.length;)e.shift().removeClass(V).attr("data-active",!1)}function wo(t){var e=Ln[t];o.each(bt,function(t,n){delete e[Bn(n)]}),o.each(e,function(t,n){delete e[t],n.detach()})}function bo(t){xt=_t=Mn;var e,o,a,i=wt[Kt];i&&(go(Kt),An[Kt].push(i.addClass(V).attr("data-active",!0)),i.hasClass(y)&&i.attr("aria-hidden","false"),t||en.showStage.onEnd(!0),le(hn,0),wo(Kt),ro(bt),$n.min=Dt?-1/0:-se(it-1,jn.w,O.margin,xt),$n.max=Dt?1/0:-se(0,jn.w,O.margin,xt),$n.snap=jn.w+O.margin,e="vertical"===O.navdir,o=e?bn.height():bn.width(),a=e?jn.h:jn.nw,qn.min=Math.min(0,a-o),qn.max=0,qn.direction=O.navdir,bn.toggleClass(C,!(qn.noMove=qn.min===qn.max)),Me(hn[0],function(){n.hasClass(Y)||(en.requestFullScreen(),Pn.focus())}))}function yo(t,e){t&&o.each(e,function(e,n){n&&o.extend(n,{width:t.width||n.width,height:t.height,minwidth:t.minwidth,maxwidth:t.maxwidth,minheight:t.minheight,maxheight:t.maxheight,ratio:Se(t.ratio)})})}function xo(t,e){n.trigger(i+":"+t,[en,e])}function _o(){clearTimeout(Co.t),Je=1,O.stopautoplayontouch?en.stopAutoplay():Ye=!0}function Co(){Je&&(O.stopautoplayontouch||(ko(),Po()),Co.t=setTimeout(function(){Je=0},Ot+Lt))}function ko(){Ye=!(!vt&&!Ue)}function Po(){if(clearTimeout(Po.t),pe.stop(Po.w),O.autoplay&&!Ye){en.autoplay||(en.autoplay=!0,xo("startautoplay"));var t=Mn,e=wt[Kt].data();Po.w=pe(function(){return e.state||t!==Mn},function(){Po.t=setTimeout(function(){if(!Ye&&t===Mn){var e=zt,n=nt[e][Kt].data();Po.w=pe(function(){return n.state||e!==zt},function(){Ye||e!==zt||en.show(Dt?ze(!We):zt)})}},O.autoplay)})}else en.autoplay&&(en.autoplay=!1,xo("stopautoplay"))}function So(t){var e;return"object"!=typeof t?(e=t,t={}):e=t.index,e=">"===e?_t+1:"<"===e?_t-1:"<<"===e?0:">>"===e?it-1:e,e=void 0===(e=isNaN(e)?a:e)?Mn||0:e}function To(t){en.activeIndex=Mn=Un(t),Ft=Gn(Mn),Et=Jn(Mn),zt=Bn(Mn+(We?-1:1)),bt=[Mn,Ft,Et],_t=Dt?t:Mn}function Fo(t){var e=Math.abs(Ct-_t),n=ce(t.time,function(){return Math.min(Ae*(1+(e-1)/12),2*Ae)});return t.slow&&(n*=10),n}function Eo(t,e){Oe&&(t.removeClass(R+" "+H),t.removeClass(K+" "+Q),e&&!vt&&t.addClass(e.replace(/^|\s/g," "+W+"--")))}function Mo(t,e,n){e&&(cn.removeClass(c),vt=!1,Kn()),t&&t!==vt&&(t.remove(),xo("unloadvideo")),n&&(ko(),Po())}function jo(t){cn.toggleClass(f,t)}function $o(t){if(!$n.flow){var e,n=t?t.pageX:$o.x,o=n&&!lo((e=n,e-On>jn.w/3))&&O.click;$o.p!==o&&dn.toggleClass(k,o)&&($o.p=o,$o.x=n)}}function zo(t){clearTimeout(zo.t),O.clicktransition&&O.clicktransition!==O.transition?setTimeout(function(){var e=O.transition;en.setOptions({transition:O.clicktransition}),Le=e,zo.t=setTimeout(function(){en.show(t)},10)},0):en.show(t)}function qo(t,e){$n[t]=qn[t]=e}function No(t){var e=o(this).data().eq;"thumbs"===O.navtype?zo({index:e,slow:t.altKey,user:!0,coo:t._x-wn.offset().left}):zo({index:e,slow:t.altKey,user:!0})}function Ao(t){zo({index:pn.index(this)?">":"<",slow:t.altKey,user:!0})}function Lo(t){je(t,function(){setTimeout(function(){ke(dn)},0),jo(!1)})}function Oo(){if(nt=en.data=nt||Ce(O.data)||ve(n),it=en.size=nt.length,Do.ok&&O.shuffle&&_e(nt),In(),Mn=Yn(Mn),it&&Hn(!0),Xn(),!Oo.i){Oo.i=!0;var t=O.startindex;Mn=xt=_t=Ct=At=Un(t)||0}if(it){if(function t(){if(!t.f===We)return t.f=We,Mn=it-1-Mn,en.reverse(),!0}())return;vt&&Mo(vt,!0),bt=[],wo(Kt),Oo.ok=!0,en.show({index:Mn,time:0}),en.resize()}else en.destroy()}function Do(){Do.ok&&(Do.ok=!1,xo("ready"))}cn[Kt]=o('<div class="'+y+'"></div>'),cn[Vt]=o(o.Fotorama.jst.thumb()),cn[Qt]=o(o.Fotorama.jst.dots()),An[Kt]=[],An[Vt]=[],An[Qt]=[],Ln[Kt]={},cn.addClass(Mt?l:u),sn.fotorama=this,en.startAutoplay=function(t){return en.autoplay?this:(Ye=Ue=!1,Qn(t||O.autoplay),Po(),this)},en.stopAutoplay=function(){return en.autoplay&&(Ye=Ue=!0,Po()),this},en.showSlide=function(t){var e,n=te(bn,O.navdir),o="horizontal"===O.navdir?O.thumbwidth:O.thumbheight;"next"===t&&(e=n-(o+O.margin)*Yt),"prev"===t&&(e=n+(o+O.margin)*Yt),so(e=Fe(e,qn),!0),Ie(bn,{time:550,pos:e,direction:O.navdir,onEnd:function(){ho()}})},en.showWhileLongPress=function(t){if(!en.longPress.singlePressInProgress){To(So(t));var e=Fo(t)/50,n=wt;en.activeFrame=wt=nt[Mn];var o=n===wt&&!t.user;return en.showNav(o,t,e),this}},en.showEndLongPress=function(t){if(!en.longPress.singlePressInProgress){To(So(t));var e=Fo(t)/50,n=wt;en.activeFrame=wt=nt[Mn];var o=n===wt&&!t.user;return en.showStage(o,t,e),void 0!==Ct&&Ct!==Mn,Ct=Mn,this}},en.showStage=function(t,e,n){Mo(vt,wt.i!==nt[Bn(xt)].i),ao(bt,"stage"),ro(qt?[_t]:[_t,Gn(_t),Jn(_t)]),qo("go",!0),t||xo("show",{user:e.user,time:n}),Ye=!0;var a=e.overPos,i=en.showStage.onEnd=function(n){if(!i.ok){if(i.ok=!0,n||bo(!0),t||xo("showend",{user:e.user}),!n&&Le&&Le!==O.transition)return en.setOptions({transition:Le}),void(Le=!1);no(),eo(bt,"stage"),qo("go",!1),fo(),$o(),ko(),Po(),en.fullScreen?(wt[Kt].find("."+at).attr("aria-hidden",!1),wt[Kt].find("."+ot).attr("aria-hidden",!0)):(wt[Kt].find("."+at).attr("aria-hidden",!0),wt[Kt].find("."+ot).attr("aria-hidden",!1))}};Te?function t(e,n,a,i,r,s){var u=void 0!==s;if(u||(r.push(arguments),Array.prototype.push.call(arguments,r.length),!(r.length>1))){e=e||o(e),n=n||o(n);var l=e[0],c=n[0],d="crossfade"===i.method,h=function(){if(!h.done){h.done=!0;var e=(u||r.shift())&&r.shift();e&&t.apply(this,e),(i.onEnd||Jt)(!!e)}},f=i.time/(s||1);a.removeClass(I+" "+D),e.stop().addClass(I),n.stop().addClass(D),d&&c&&e.fadeTo(0,0),e.fadeTo(d?f:0,1,d&&h),n.fadeTo(f,0,h),l&&d||c||h()}}(wt[Kt],nt[Ct]&&Mn!==Ct?nt[Ct][Kt]:null,fn,{time:n,method:O.transition,onEnd:i},Dn):Ie(hn,{pos:-se(_t,jn.w,O.margin,xt),overPos:a,time:n,onEnd:i});co()},en.showNav=function(t,e,n){if(ho(),Bt){go(tn),An[tn].push(wt[tn].addClass(V).attr("data-active",!0));var o=Yn(Mn+Zt(_t-Ct,-1,1));po({time:n,coo:o!==Mn&&e.coo,guessIndex:void 0!==e.coo?o:Mn,keep:t}),Ut&&vo(n)}},en.show=function(t){en.longPress.singlePressInProgress=!0,To(So(t));var e=Fo(t),n=wt;en.activeFrame=wt=nt[Mn];var o=n===wt&&!t.user;return en.showStage(o,t,e),en.showNav(o,t,e),void 0!==Ct&&Ct!==Mn,Ct=Mn,en.longPress.singlePressInProgress=!1,this},en.requestFullScreen=function(){if(ue&&!en.fullScreen){if(o((en.activeFrame||{}).$stageFrame||{}).hasClass("fotorama-video-container"))return;Xe=St.scrollTop(),Be=St.scrollLeft(),ke(St),qo("x",!0),Ge=o.extend({},jn),n.addClass(Y).appendTo(Pt.addClass(r)),kt.addClass(r),Mo(vt,!0,!0),en.fullScreen=!0,de&&yt.request(an),en.resize(),eo(bt,"stage"),no(),xo("fullscreenenter"),"ontouchstart"in t||Pn.focus()}return this},en.cancelFullScreen=function(){return de&&yt.is()?yt.cancel(e):en.fullScreen&&(en.fullScreen=!1,$t&&yt.cancel(an),Pt.removeClass(r),kt.removeClass(r),n.removeClass(Y).insertAfter(ln),jn=o.extend({},Ge),Mo(vt,!0,!0),qo("x",!1),en.resize(),eo(bt,"stage"),ke(St,Be,Xe),xo("fullscreenexit")),this},en.toggleFullScreen=function(){return en[(en.fullScreen?"cancel":"request")+"FullScreen"]()},en.resize=function(e){if(!nt)return this;var n=arguments[1]||0,a=arguments[2];Yt=Vn(0,O),yo(en.fullScreen?{width:o(t).width(),maxwidth:null,minwidth:null,height:o(t).height(),maxheight:null,minheight:null}:Pe(e),[jn,a||en.fullScreen||O]);var i=jn.width,r=jn.height,s=jn.ratio,u=St.height()-(Bt?wn.height():0);if(re(i)&&(cn.css({width:""}),cn.css({height:""}),dn.css({width:""}),dn.css({height:""}),hn.css({width:""}),hn.css({height:""}),wn.css({width:""}),wn.css({height:""}),cn.css({minWidth:jn.minwidth||0,maxWidth:jn.maxwidth||1200}),"dots"===Bt&&gn.hide(),i=jn.W=jn.w=cn.width(),jn.nw=Bt&&ie(O.navwidth,i)||i,hn.css({width:jn.w,marginLeft:(jn.W-jn.w)/2}),r=(r=ie(r,u))||s&&i/s)){if(i=Math.round(i),r=jn.h=Math.round(Zt(r,ie(jn.minheight,u),ie(jn.maxheight,u))),dn.css({width:i,height:r}),"vertical"!==O.navdir||en.fullscreen||wn.width(O.thumbwidth+2*O.thumbmargin),"horizontal"!==O.navdir||en.fullscreen||wn.height(O.thumbheight+2*O.thumbmargin),"dots"===Bt&&(wn.width(i).height("auto"),gn.show()),"vertical"===O.navdir&&en.fullScreen&&dn.css("height",St.height()),"horizontal"===O.navdir&&en.fullScreen&&dn.css("height",St.height()-wn.height()),Bt){switch(O.navdir){case"vertical":gn.removeClass(q),gn.removeClass(z),gn.addClass($),wn.stop().animate({height:jn.h,width:O.thumbwidth},n);break;case"list":gn.removeClass($),gn.removeClass(q),gn.addClass(z);break;default:gn.removeClass($),gn.removeClass(z),gn.addClass(q),wn.stop().animate({width:jn.nw},n)}bo(),po({guessIndex:Mn,time:n,keep:!0}),Ut&&uo.nav&&vo(n)}Ve=a||!0,Do.ok=!0,Do()}return On=dn.offset().left,Rn(),this},en.setOptions=function(t){return o.extend(O,t),Oo(),this},en.shuffle=function(){return nt&&_e(nt)&&Oo(),this},en.longPress={threshold:1,count:0,thumbSlideTime:20,progress:function(){this.inProgress||(this.count++,this.inProgress=this.count>this.threshold)},end:function(){this.inProgress&&(this.isEnded=!0)},reset:function(){this.count=0,this.inProgress=!1,this.isEnded=!1}},en.destroy=function(){return en.cancelFullScreen(),en.stopAutoplay(),nt=en.data=null,Hn(),bt=[],wo(Kt),Oo.ok=!1,this},en.playVideo=function(){var t=wt,e=t.video,n=Mn;return"object"==typeof e&&t.videoReady&&(de&&en.fullScreen&&en.cancelFullScreen(),pe(function(){return!yt.is()||n!==Mn},function(){var a;n===Mn&&(t.$video=t.$video||o(ye(dt)).append('<iframe src="'+(a=e).p+a.type+".com/embed/"+a.id+'" frameborder="0" allowfullscreen></iframe>'),t.$video.appendTo(t[Kt]),cn.addClass(c),vt=t.$video,Kn(),pn.blur(),Pn.blur(),xo("loadvideo"))})),this},en.stopVideo=function(){return Mo(vt,!0,!0),this},en.spliceByIndex=function(t,e){e.i=t+1,e.img&&o.ajax({url:e.img,type:"HEAD",success:function(){nt.splice(t,1,e),Oo()}})},dn.on("mousemove",$o),$n=He(hn,{onStart:_o,onMove:function(t,e){Eo(dn,e.edge)},onTouchEnd:Co,onEnd:function(t){var e,a,i,r,s,u,l;if(Eo(dn),e=(Nt&&!Ze||t.touch)&&O.arrows,(t.moved||e&&t.pos!==t.newPos&&!t.control)&&t.$target[0]!==Pn[0]){var c=(r=t.newPos,s=jn.w,u=O.margin,l=xt,-Math.round(r/(s+(u||0))-(l||0)));en.show({index:c,time:Te?Ae:t.time,overPos:t.overPos,user:!0})}else t.aborted||t.control||(a=t.startEvent,i=a.target,o(i).hasClass(ht)?en.playVideo():i===Sn?en.toggleFullScreen():vt?i===Fn&&Mo(vt,!0,!0):n.hasClass(Y)||en.requestFullScreen())},timeLow:1,timeHigh:1,friction:2,select:"."+X+", ."+X+" *",$wrap:dn,direction:"horizontal"}),qn=He(bn,{onStart:_o,onMove:function(t,e){Eo(wn,e.edge)},onTouchEnd:Co,onEnd:function(t){function e(){po.l=t.newPos,ko(),Po(),so(t.newPos,!0),ho()}if(t.moved)t.pos!==t.newPos?(Ye=!0,Ie(bn,{time:t.time,pos:t.newPos,overPos:t.overPos,direction:O.navdir,onEnd:e}),so(t.newPos),Oe&&Eo(wn,we(t.newPos,qn.min,qn.max,t.dir))):e();else{var n=t.$target.closest("."+L,bn)[0];n&&No.call(n,t.startEvent)}},timeLow:.5,timeHigh:2,friction:5,$wrap:wn,direction:O.navdir}),zn=Ke(dn,{shift:!0,onEnd:function(t,e){_o(),Co(),en.show({index:e,slow:t.altKey})}}),Nn=Ke(wn,{onEnd:function(t,e){_o(),Co();var n=le(bn)+.25*e;bn.css(ee(Zt(n,qn.min,qn.max),O.navdir)),Oe&&Eo(wn,we(n,qn.min,qn.max,O.navdir)),Nn.prevent={"<":n>=qn.max,">":n<=qn.min},clearTimeout(Nn.t),Nn.t=setTimeout(function(){po.l=n,so(n,!0)},Lt),so(n)}}),cn.hover(function(){setTimeout(function(){Je||jo(!(Ze=!0))},0)},function(){Ze&&jo(!(Ze=!1))}),be(pn,function(t){$e(t),Ao.call(this,t)},{onStart:function(){_o(),$n.control=!0},onTouchEnd:Co}),be(Cn,function(t){$e(t),"thumbs"===O.navtype?en.show("<"):en.showSlide("prev")}),be(kn,function(t){$e(t),"thumbs"===O.navtype?en.show(">"):en.showSlide("next")}),pn.each(function(){Me(this,function(t){Ao.call(this,t)}),Lo(this)}),Me(Sn,function(){n.hasClass(Y)?(en.cancelFullScreen(),hn.focus()):(en.requestFullScreen(),Pn.focus())}),Lo(Sn),o.each("load push pop shift unshift reverse sort splice".split(" "),function(t,e){en[e]=function(){return nt=nt||[],"load"!==e?Array.prototype[e].apply(nt,arguments):arguments[0]&&"object"==typeof arguments[0]&&arguments[0].length&&(nt=Ce(arguments[0])),Oo(),en}}),Oo()},o.fn.fotorama=function(e){return this.each(function(){var n=this,a=o(this),i=a.data(),r=i.fotorama;r?r.setOptions(e,!0):pe(function(){return!(0===(t=n).offsetWidth&&0===t.offsetHeight);var t},function(){i.urtext=a.html(),new o.Fotorama(a,o.extend({},Ut,t.fotoramaDefaults,e,i))})})},o.Fotorama.instances=[],o.Fotorama.cache={},o.Fotorama.measures={},(o=o||{}).Fotorama=o.Fotorama||{},o.Fotorama.jst=o.Fotorama.jst||{},o.Fotorama.jst.dots=function(t){return'<div class="fotorama__nav__frame fotorama__nav__frame--dot" tabindex="0" role="button" data-gallery-role="nav-frame" data-nav-type="thumb" aria-label>\r\n <div class="fotorama__dot"></div>\r\n</div>','<div class="fotorama__nav__frame fotorama__nav__frame--dot" tabindex="0" role="button" data-gallery-role="nav-frame" data-nav-type="thumb" aria-label>\r\n <div class="fotorama__dot"></div>\r\n</div>'},o.Fotorama.jst.frameCaption=function(t){var e,n="";return n+='<div class="fotorama__caption" aria-hidden="true">\r\n <div class="fotorama__caption__wrap" id="'+(null==(e=t.labelledby)?"":e)+'">'+(null==(e=t.caption)?"":e)+"</div>\r\n</div>\r\n"},o.Fotorama.jst.style=function(t){var e,n="";return n+=".fotorama"+(null==(e=t.s)?"":e)+" .fotorama__nav--thumbs .fotorama__nav__frame{\r\npadding:"+(null==(e=t.m)?"":e)+"px;\r\nheight:"+(null==(e=t.h)?"":e)+"px}\r\n.fotorama"+(null==(e=t.s)?"":e)+" .fotorama__thumb-border{\r\nheight:"+(null==(e=t.h)?"":e)+"px;\r\nborder-width:"+(null==(e=t.b)?"":e)+"px;\r\nmargin-top:"+(null==(e=t.m)?"":e)+"px}"},o.Fotorama.jst.thumb=function(t){return'<div class="fotorama__nav__frame fotorama__nav__frame--thumb" tabindex="0" role="button" data-gallery-role="nav-frame" data-nav-type="thumb" aria-label>\r\n <div class="fotorama__thumb">\r\n </div>\r\n</div>','<div class="fotorama__nav__frame fotorama__nav__frame--thumb" tabindex="0" role="button" data-gallery-role="nav-frame" data-nav-type="thumb" aria-label>\r\n <div class="fotorama__thumb">\r\n </div>\r\n</div>'}}(window,document,location,"undefined"!=typeof jQuery&&jQuery); \ No newline at end of file From e69474452eff0defe6cfd1782e1ef835e534a16a Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Wed, 19 Jun 2019 11:04:17 -0500 Subject: [PATCH 2001/2092] MAGETWO-99925: Product URL rewrites are always regenerated if products are updated via CSV import in default scope --- .../Magento/CatalogImportExport/Model/Import/Product.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product.php b/app/code/Magento/CatalogImportExport/Model/Import/Product.php index 07e116897b1c2..224f22f3325f0 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product.php @@ -2848,7 +2848,7 @@ protected function getUrlKey($rowData) return trim(strtolower($urlKey)); } - if (!empty($rowData[self::COL_NAME])) { + if (!empty($rowData[self::COL_NAME]) && array_key_exists(self::URL_KEY, $rowData)) { return $this->productUrl->formatUrlKey($rowData[self::COL_NAME]); } @@ -2875,12 +2875,15 @@ protected function getResource() */ private function isNeedToChangeUrlKey(array $rowData): bool { + $urlKey = $this->getUrlKey($rowData); $productExists = $this->isSkuExist($rowData[self::COL_SKU]); + $markedToEraseUrlKey = isset($rowData[self::URL_KEY]); // The product isn't new and the url key index wasn't marked for change. - if ($productExists && empty($rowData[self::URL_KEY]) && $this->getBehavior() === Import::BEHAVIOR_APPEND) { + if (!$urlKey && $productExists && !$markedToEraseUrlKey) { // Seems there is no need to change the url key return false; } + return true; } From 44a35f992bb2d56c617264be8c67722b353c1c95 Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh <kovdrysh@adobe.com> Date: Wed, 19 Jun 2019 11:11:13 -0500 Subject: [PATCH 2002/2092] MC-17552: Saving configurable product with custom product attribute (images as swatches) --- .../AdminDeleteProductBySkuActionGroup.xml | 30 +++++ ...nfigurationsByAttributeCodeActionGroup.xml | 28 +++++ ...AdminOpenAttributeSetByNameActionGroup.xml | 17 +++ ...minOpenAttributeSetGridPageActionGroup.xml | 14 +++ .../AdminOpenProductIndexPageActionGroup.xml | 14 +++ .../AdminProductAttributeActionGroup.xml | 4 + .../Test/Mftf/Data/ProductAttributeData.xml | 21 ++++ ...uctWithAttributesImagesAndSwatchesTest.xml | 116 ++++++++++++++++++ .../AdminProductFormConfigurationsSection.xml | 1 + 9 files changed, 245 insertions(+) create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminDeleteProductBySkuActionGroup.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminGenerateProductConfigurationsByAttributeCodeActionGroup.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenAttributeSetByNameActionGroup.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenAttributeSetGridPageActionGroup.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenProductIndexPageActionGroup.xml create mode 100644 app/code/Magento/Catalog/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminDeleteProductBySkuActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminDeleteProductBySkuActionGroup.xml new file mode 100644 index 0000000000000..9b9b269c2601e --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminDeleteProductBySkuActionGroup.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <!-- Delete a product by filtering grid and using delete action--> + <actionGroup name="AdminDeleteProductBySkuActionGroup"> + <arguments> + <argument name="sku" type="string"/> + </arguments> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="visitAdminProductPage"/> + <conditionalClick selector="{{AdminDataGridHeaderSection.clearFilters}}" dependentSelector="{{AdminDataGridHeaderSection.clearFilters}}" visible="true" stepKey="clickClearFilters"/> + <click selector="{{AdminProductGridFilterSection.filters}}" stepKey="openProductFilters"/> + <fillField selector="{{AdminProductGridFilterSection.skuFilter}}" userInput="{{sku}}" stepKey="fillProductSkuFilter"/> + <click selector="{{AdminProductGridFilterSection.applyFilters}}" stepKey="clickApplyFilters"/> + <see selector="{{AdminProductGridSection.productGridCell('1', 'SKU')}}" userInput="{{sku}}" stepKey="seeProductSkuInGrid"/> + <click selector="{{AdminProductGridSection.multicheckDropdown}}" stepKey="openMulticheckDropdown"/> + <click selector="{{AdminProductGridSection.multicheckOption('Select All')}}" stepKey="selectAllProductInFilteredGrid"/> + <click selector="{{AdminProductGridSection.bulkActionDropdown}}" stepKey="clickActionDropdown"/> + <click selector="{{AdminProductGridSection.bulkActionOption('Delete')}}" stepKey="clickDeleteAction"/> + <waitForElementVisible selector="{{AdminConfirmationModalSection.ok}}" stepKey="waitForConfirmModal"/> + <click selector="{{AdminConfirmationModalSection.ok}}" stepKey="confirmProductDelete"/> + <see selector="{{AdminMessagesSection.success}}" userInput="record(s) have been deleted." stepKey="seeSuccessMessage"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminGenerateProductConfigurationsByAttributeCodeActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminGenerateProductConfigurationsByAttributeCodeActionGroup.xml new file mode 100644 index 0000000000000..73b55ce3dd8eb --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminGenerateProductConfigurationsByAttributeCodeActionGroup.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminGenerateProductConfigurationsByAttributeCodeActionGroup"> + <arguments> + <argument name="attributeCode" type="string" defaultValue="SomeString"/> + </arguments> + <click selector="{{AdminProductFormConfigurationsSection.createConfigurations}}" stepKey="clickCreateConfigurations"/> + <click selector="{{AdminCreateProductConfigurationsPanel.filters}}" stepKey="clickFilters"/> + <fillField selector="{{AdminCreateProductConfigurationsPanel.attributeCode}}" userInput="{{attributeCode}}" stepKey="fillFilterAttributeCodeField"/> + <click selector="{{AdminCreateProductConfigurationsPanel.applyFilters}}" stepKey="clickApplyFiltersButton"/> + <click selector="{{AdminCreateProductConfigurationsPanel.firstCheckbox}}" stepKey="clickOnFirstCheckbox"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton1"/> + <click selector="{{AdminCreateProductConfigurationsPanel.selectAll}}" stepKey="clickOnSelectAll"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton2"/> + <click selector="{{AdminCreateProductConfigurationsPanel.applySingleQuantityToEachSkus}}" stepKey="clickOnApplySingleQuantityToEachSku"/> + <fillField selector="{{AdminCreateProductConfigurationsPanel.quantity}}" userInput="99" stepKey="enterAttributeQuantity"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton3"/> + <click selector="{{AdminCreateProductConfigurationsPanel.next}}" stepKey="clickOnNextButton4"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenAttributeSetByNameActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenAttributeSetByNameActionGroup.xml new file mode 100644 index 0000000000000..e9b244d4cf223 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenAttributeSetByNameActionGroup.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminOpenAttributeSetByNameActionGroup"> + <arguments> + <argument name="attributeSetName" type="string" defaultValue="Default"/> + </arguments> + <click selector="{{AdminProductAttributeSetGridSection.attributeSetName(attributeSetName)}}" stepKey="chooseAttributeSet"/> + <waitForPageLoad stepKey="waitForAttributeSetPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenAttributeSetGridPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenAttributeSetGridPageActionGroup.xml new file mode 100644 index 0000000000000..c6f0c3332b1d5 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenAttributeSetGridPageActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminOpenAttributeSetGridPageActionGroup"> + <amOnPage url="{{AdminProductAttributeSetGridPage.url}}" stepKey="goToAttributeSetPage"/> + <waitForPageLoad stepKey="waitForAttributeSetPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenProductIndexPageActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenProductIndexPageActionGroup.xml new file mode 100644 index 0000000000000..ca1303f180ca4 --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminOpenProductIndexPageActionGroup.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> +<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + <actionGroup name="AdminOpenProductIndexPageActionGroup"> + <amOnPage url="{{AdminProductIndexPage.url}}" stepKey="goToProductIndexPage"/> + <waitForPageLoad stepKey="waitForProductIndexPageLoad"/> + </actionGroup> +</actionGroups> diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributeActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributeActionGroup.xml index f043b82f2d44f..ef6970b9d8368 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributeActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributeActionGroup.xml @@ -80,10 +80,14 @@ <argument name="attributeType" type="string" defaultValue="select"/> </arguments> <amOnPage url="{{AdminProductAttributeNewPage.url}}" stepKey="goToNewProductAttributePage"/> + <waitForPageLoad stepKey="waitForProductAttributeNewPageLoad"/> <fillField selector="{{AttributePropertiesSection.defaultLabel}}" userInput="{{attributeCode}}" stepKey="fillDefaultLabel"/> <selectOption selector="{{AttributePropertiesSection.inputType}}" userInput="{{attributeType}}" stepKey="selectInputType"/> <waitForElementVisible selector="{{AdminNewAttributePanelSection.addOption}}" stepKey="waitForElementVisible"/> </actionGroup> + <actionGroup name="AdminFillProductAttributePropertiesActionGroup" extends="StartCreateProductAttribute"> + <remove keyForRemoval="waitForElementVisible"/> + </actionGroup> <actionGroup name="AddOptionToProductAttribute"> <arguments> <argument name="optionName" type="string"/> diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeData.xml index b2483c3d2d080..dfe6bfdf681e1 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeData.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Data/ProductAttributeData.xml @@ -77,4 +77,25 @@ <entity name="ProductAttributeText" extends="productAttributeWithTwoOptions"> <data key="frontend_input">text</data> </entity> + <entity name="productVisualSwatchAttribute" type="ProductAttribute"> + <data key="attribute_code" unique="suffix">attribute</data> + <data key="frontend_input">swatch_visual</data> + <data key="scope">global</data> + <data key="is_required">false</data> + <data key="is_unique">false</data> + <data key="is_searchable">true</data> + <data key="is_visible">true</data> + <data key="is_visible_in_advanced_search">true</data> + <data key="is_visible_on_front">true</data> + <data key="is_filterable">true</data> + <data key="is_filterable_in_search">true</data> + <data key="used_in_product_listing">true</data> + <data key="is_used_for_promo_rules">true</data> + <data key="is_comparable">true</data> + <data key="is_used_in_grid">true</data> + <data key="is_visible_in_grid">true</data> + <data key="is_filterable_in_grid">true</data> + <data key="used_for_sort_by">true</data> + <requiredEntity type="FrontendLabel">ProductAttributeFrontendLabel</requiredEntity> + </entity> </entities> diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml new file mode 100644 index 0000000000000..c23f162a95fbb --- /dev/null +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml @@ -0,0 +1,116 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + /** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +--> + +<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> + <test name="AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest"> + <annotations> + <features value="Catalog"/> + <stories value="Product attributes"/> + <title value="Saving configurable product with custom product attribute (images as swatches)"/> + <description value="Saving configurable product with custom product attribute (images as swatches)"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-17552"/> + <group value="catalog"/> + </annotations> + <before> + <!-- Login as admin --> + <actionGroup ref="LoginAsAdmin" stepKey="LoginAsAdmin"/> + </before> + <after> + <!-- Admin logout --> + <actionGroup ref="logout" stepKey="adminLogout"/> + </after> + + <!-- Create a new product attribute: set Catalog Input Type for Store Owner: Visual Swatch --> + <actionGroup ref="AdminFillProductAttributePropertiesActionGroup" stepKey="fillAttributeProperties"> + <argument name="attributeCode" value="{{productVisualSwatchAttribute.attribute_code}}"/> + <argument name="attributeType" value="{{productVisualSwatchAttribute.frontend_input}}"/> + </actionGroup> + + <!-- Add a few Swatches and add images to Manage Swatch (Values of Your Attribute) + 1. Set swatch #1 using the color picker --> + <click selector="{{AdminManageSwatchSection.addSwatch}}" stepKey="clickAddFirstSwatch"/> + <actionGroup ref="openSwatchMenuByIndex" stepKey="clickFirstSwatch"> + <argument name="index" value="0"/> + </actionGroup> + <click selector="{{AdminManageSwatchSection.chooseColorRow('1')}}" stepKey="clickChooseFirstColor"/> + <actionGroup ref="setColorPickerValueByHex" stepKey="fillFirstHex"> + <argument name="nthColorPicker" value="1"/> + <argument name="hexColor" value="e74c3c"/> + </actionGroup> + <fillField selector="{{AdminManageSwatchSection.adminInputByIndex('0')}}" userInput="red" stepKey="fillFirstAdminField"/> + + <!-- 2. Set swatch #2 using the color picker --> + <click selector="{{AdminManageSwatchSection.addSwatch}}" stepKey="clickAddSecondSwatch"/> + <actionGroup ref="openSwatchMenuByIndex" stepKey="clickSecondSwatch"> + <argument name="index" value="1"/> + </actionGroup> + <click selector="{{AdminManageSwatchSection.chooseColorRow('2')}}" stepKey="clickChooseSecondColor"/> + <actionGroup ref="setColorPickerValueByHex" stepKey="fillSecondHex"> + <argument name="nthColorPicker" value="2"/> + <argument name="hexColor" value="3498db"/> + </actionGroup> + <fillField selector="{{AdminManageSwatchSection.adminInputByIndex('1')}}" userInput="blue" stepKey="fillSecondAdminField"/> + + <!-- Set Scope: Global in Advanced Attribute Properties --> + <click selector="{{AttributePropertiesSection.AdvancedProperties}}" stepKey="expandAdvancedProperties"/> + <selectOption selector="{{AttributePropertiesSection.scope}}" userInput="1" stepKey="selectGlobalScope"/> + + <!-- Click "Save Attribute" button --> + <click selector="{{AttributePropertiesSection.saveAndEdit}}" stepKey="clickSaveAndEdit"/> + <waitForElementVisible selector="{{AdminProductMessagesSection.successMessage}}" stepKey="waitForSuccessMessage"/> + + <!-- Add created product attribute to the Default set --> + <actionGroup ref="AdminOpenAttributeSetGridPageActionGroup" stepKey="openAttributeSetPage"/> + <actionGroup ref="AdminOpenAttributeSetByNameActionGroup" stepKey="openDefaultAttributeSet"/> + <actionGroup ref="AssignAttributeToGroup" stepKey="assignAttributeToGroup"> + <argument name="group" value="Product Details"/> + <argument name="attribute" value="productVisualSwatchAttribute.attribute_code"/> + </actionGroup> + <actionGroup ref="SaveAttributeSet" stepKey="saveAttributeSet"/> + + <!-- Create configurable product --> + <actionGroup ref="AdminOpenProductIndexPageActionGroup" stepKey="openOpenProductIndexPage"/> + <actionGroup ref="goToCreateProductPage" stepKey="goToCreateConfigurableProduct"> + <argument name="product" value="BaseConfigurableProduct"/> + </actionGroup> + + <!-- Select Attribute Set --> + <actionGroup ref="AssignProductToAttributeSet" stepKey="selectAttributeSet"> + <argument name="attributeSetName" value="Default"/> + </actionGroup> + + <!-- Fill all the necessary information such as weight, name, SKU etc --> + <actionGroup ref="fillMainProductForm" stepKey="fillProductForm"> + <argument name="product" value="BaseConfigurableProduct"/> + </actionGroup> + + <!-- Click "Create Configurations" button, select created product attribute using the same Quantity for all products. Click "Generate products" button --> + <actionGroup ref="AdminGenerateProductConfigurationsByAttributeCodeActionGroup" stepKey="addAttributeToProduct"> + <argument name="attributeCode" value="{{productVisualSwatchAttribute.attribute_code}}"/> + </actionGroup> + + <!-- Add images for the products --> + <attachFile selector="{{AdminProductFormConfigurationsSection.addImageByAttributeOption('red')}}" userInput="{{MagentoLogo.file}}" stepKey="uploadImageForFirstProduct"/> + <attachFile selector="{{AdminProductFormConfigurationsSection.addImageByAttributeOption('blue')}}" userInput="{{ProductImage.file}}" stepKey="uploadImageForSecondProduct"/> + + <!-- Click "Save" button --> + <actionGroup ref="saveProductForm" stepKey="clickSaveButton"/> + + <!-- Delete all created product --> + <actionGroup ref="AdminDeleteProductBySkuActionGroup" stepKey="deleteCreatedProducts"> + <argument name="sku" value="{{BaseConfigurableProduct.sku}}"/> + </actionGroup> + + <!-- Delete product attribute --> + <actionGroup ref="deleteProductAttribute" stepKey="deleteProductAttribute"> + <argument name="ProductAttribute" value="productVisualSwatchAttribute"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml index cdaade4271cec..f188f62dab200 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml @@ -26,5 +26,6 @@ <element name="skuValidationMessage" type="text" selector="input[name='configurable-matrix[{{index}}][sku]'] + label" parameterized="true"/> <element name="stepsWizardTitle" type="text" selector="div.content:not([style='display: none;']) .steps-wizard-title"/> <element name="attributeEntityByName" type="text" selector="//div[@class='attribute-entity']//div[normalize-space(.)='{{attributeLabel}}']" parameterized="true"/> + <element name="addImageByAttributeOption" type="file" selector="//*[.='Attributes']/ancestor::tr//span[contains(text(), '{{option}}')]/ancestor::tr//input[@class='file-uploader-input']" parameterized="true"/> </section> </sections> From cc0cbad74885299b134a425c8a785efcee5c9d72 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Wed, 19 Jun 2019 11:13:52 -0500 Subject: [PATCH 2003/2092] MAGETWO-99925: Product URL rewrites are always regenerated if products are updated via CSV import in default scope --- .../Model/Import/ProductTest.php | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php index cb96910ec86e1..f0b5d2fe6401c 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php @@ -29,6 +29,7 @@ use Magento\Store\Model\Store; use Psr\Log\LoggerInterface; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\ImportExport\Model\Import\Source\Csv; /** * Class ProductTest @@ -1584,6 +1585,35 @@ public function testExistingProductWithUrlKeys() } } + /** + * @magentoDataFixture Magento/Catalog/_files/product_simple_with_url_key.php + * @magentoDbIsolation enabled + * @magentoAppIsolation enabled + */ + public function testImportWithoutChangingUrlKeys() + { + $filesystem = $this->objectManager->create(Filesystem::class); + $directory = $filesystem->getDirectoryWrite(DirectoryList::ROOT); + $source = $this->objectManager->create( + Csv::class, + [ + 'file' => __DIR__ . '/_files/products_to_import_without_url_keys_column.csv', + 'directory' => $directory + ] + ); + + $errors = $this->_model->setParameters( + ['behavior' => Import::BEHAVIOR_APPEND, 'entity' => 'catalog_product'] + ) + ->setSource($source) + ->validateData(); + + $this->assertTrue($errors->getErrorsCount() == 0); + $this->_model->importData(); + $productRepository = $this->objectManager->create(ProductRepositoryInterface::class); + $this->assertEquals('url-key', $productRepository->get('simple1')->getUrlKey()); + } + /** * @magentoDataFixture Magento/Catalog/_files/product_simple_with_url_key.php * @magentoDbIsolation enabled From 4880dc7e453e35bdbca7137dfbabd06b4a563d9f Mon Sep 17 00:00:00 2001 From: Kevin Kozan <kkozan@magento.com> Date: Wed, 19 Jun 2019 11:23:31 -0500 Subject: [PATCH 2004/2092] MQE-1604: Move specific utils in MTF into Infrastructure 2.2 - Move MTF utils out from Magento codebase --- dev/tests/functional/.htaccess.sample | 11 ------ dev/tests/functional/utils/authenticate.php | 29 --------------- dev/tests/functional/utils/command.php | 27 -------------- .../utils/deleteMagentoGeneratedCode.php | 16 -------- dev/tests/functional/utils/export.php | 32 ---------------- dev/tests/functional/utils/locales.php | 25 ------------- dev/tests/functional/utils/log.php | 21 ----------- dev/tests/functional/utils/pathChecker.php | 22 ----------- dev/tests/functional/utils/website.php | 37 ------------------- 9 files changed, 220 deletions(-) delete mode 100644 dev/tests/functional/.htaccess.sample delete mode 100644 dev/tests/functional/utils/authenticate.php delete mode 100644 dev/tests/functional/utils/command.php delete mode 100644 dev/tests/functional/utils/deleteMagentoGeneratedCode.php delete mode 100644 dev/tests/functional/utils/export.php delete mode 100644 dev/tests/functional/utils/locales.php delete mode 100644 dev/tests/functional/utils/log.php delete mode 100644 dev/tests/functional/utils/pathChecker.php delete mode 100644 dev/tests/functional/utils/website.php diff --git a/dev/tests/functional/.htaccess.sample b/dev/tests/functional/.htaccess.sample deleted file mode 100644 index 67c2f3fe2d027..0000000000000 --- a/dev/tests/functional/.htaccess.sample +++ /dev/null @@ -1,11 +0,0 @@ -############################################## -## Allow access to command.php, website.php, export.php, pathChecker.php, locales.php, deleteMagentoGeneratedCode.php and log.php - <FilesMatch "command.php|website.php|export.php|pathChecker.php|deleteMagentoGeneratedCode.php|log.php|locales.php"> - <IfVersion < 2.4> - order allow,deny - allow from all - </IfVersion> - <IfVersion >= 2.4> - Require all granted - </IfVersion> - </FilesMatch> diff --git a/dev/tests/functional/utils/authenticate.php b/dev/tests/functional/utils/authenticate.php deleted file mode 100644 index 15851f6e8000a..0000000000000 --- a/dev/tests/functional/utils/authenticate.php +++ /dev/null @@ -1,29 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -/** - * Check if token passed in is a valid auth token. - * - * @param string $token - * @return bool - */ -function authenticate($token) -{ - require_once __DIR__ . '/../../../../app/bootstrap.php'; - - $magentoObjectManagerFactory = \Magento\Framework\App\Bootstrap::createObjectManagerFactory(BP, $_SERVER); - $magentoObjectManager = $magentoObjectManagerFactory->create($_SERVER); - $tokenModel = $magentoObjectManager->get(\Magento\Integration\Model\Oauth\Token::class); - - $tokenPassedIn = $token; - // Token returned will be null if the token we passed in is invalid - $tokenFromMagento = $tokenModel->loadByToken($tokenPassedIn)->getToken(); - if (!empty($tokenFromMagento) && ($tokenFromMagento == $tokenPassedIn)) { - return true; - } else { - return false; - } -} diff --git a/dev/tests/functional/utils/command.php b/dev/tests/functional/utils/command.php deleted file mode 100644 index e7b336464682d..0000000000000 --- a/dev/tests/functional/utils/command.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -include __DIR__ . '/authenticate.php'; -require_once __DIR__ . '/../../../../app/bootstrap.php'; - -use Symfony\Component\Console\Input\StringInput; -use Symfony\Component\Console\Output\NullOutput; - -if (!empty($_POST['token']) && !empty($_POST['command'])) { - if (authenticate(urldecode($_POST['token']))) { - $command = urldecode($_POST['command']); - $magentoObjectManagerFactory = \Magento\Framework\App\Bootstrap::createObjectManagerFactory(BP, $_SERVER); - $magentoObjectManager = $magentoObjectManagerFactory->create($_SERVER); - $cli = $magentoObjectManager->create(\Magento\Framework\Console\Cli::class); - $input = new StringInput($command); - $input->setInteractive(false); - $output = new NullOutput(); - $cli->doRun($input, $output); - } else { - echo "Command not unauthorized."; - } -} else { - echo "'token' or 'command' parameter is not set."; -} diff --git a/dev/tests/functional/utils/deleteMagentoGeneratedCode.php b/dev/tests/functional/utils/deleteMagentoGeneratedCode.php deleted file mode 100644 index 17e3575c87686..0000000000000 --- a/dev/tests/functional/utils/deleteMagentoGeneratedCode.php +++ /dev/null @@ -1,16 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -include __DIR__ . '/authenticate.php'; - -if (!empty($_POST['token']) && !empty($_POST['path'])) { - if (authenticate(urldecode($_POST['token']))) { - exec('rm -rf ../../../../generated/*'); - } else { - echo "Command not unauthorized."; - } -} else { - echo "'token' parameter is not set."; -} diff --git a/dev/tests/functional/utils/export.php b/dev/tests/functional/utils/export.php deleted file mode 100644 index 9357bfa459be0..0000000000000 --- a/dev/tests/functional/utils/export.php +++ /dev/null @@ -1,32 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -include __DIR__ . '/authenticate.php'; - -if (!empty($_POST['token']) && !empty($_POST['template'])) { - if (authenticate(urldecode($_POST['token']))) { - $varDir = '../../../../var/'; - $template = urldecode($_POST['template']); - $fileList = scandir($varDir, SCANDIR_SORT_NONE); - $files = []; - - foreach ($fileList as $fileName) { - if (preg_match("`$template`", $fileName) === 1) { - $filePath = $varDir . $fileName; - $files[] = [ - 'content' => file_get_contents($filePath), - 'name' => $fileName, - 'date' => filectime($filePath), - ]; - } - } - - echo serialize($files); - } else { - echo "Command not unauthorized."; - } -} else { - echo "'token' or 'template' parameter is not set."; -} diff --git a/dev/tests/functional/utils/locales.php b/dev/tests/functional/utils/locales.php deleted file mode 100644 index a3b4ec05eed65..0000000000000 --- a/dev/tests/functional/utils/locales.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -include __DIR__ . '/authenticate.php'; - -if (!empty($_POST['token'])) { - if (authenticate(urldecode($_POST['token']))) { - if ($_POST['type'] == 'deployed') { - $themePath = isset($_POST['theme_path']) ? $_POST['theme_path'] : 'adminhtml/Magento/backend'; - $directory = __DIR__ . '/../../../../pub/static/' . $themePath; - $locales = array_diff(scandir($directory), ['..', '.']); - } else { - require_once __DIR__ . DIRECTORY_SEPARATOR . 'bootstrap.php'; - $localeConfig = $magentoObjectManager->create(\Magento\Framework\Locale\Config::class); - $locales = $localeConfig->getAllowedLocales(); - } - echo implode('|', $locales); - } else { - echo "Command not unauthorized."; - } -} else { - echo "'token' parameter is not set."; -} diff --git a/dev/tests/functional/utils/log.php b/dev/tests/functional/utils/log.php deleted file mode 100644 index 0d6f1fa2ac5cf..0000000000000 --- a/dev/tests/functional/utils/log.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -include __DIR__ . '/authenticate.php'; - -if (!empty($_POST['token']) && !empty($_POST['name'])) { - if (authenticate(urldecode($_POST['token']))) { - $name = urldecode($_POST['name']); - if (preg_match('/\.\.(\\\|\/)/', $name)) { - throw new \InvalidArgumentException('Invalid log file name'); - } - - echo serialize(file_get_contents('../../../../var/log' . '/' . $name)); - } else { - echo "Command not unauthorized."; - } -} else { - echo "'token' or 'name' parameter is not set."; -} diff --git a/dev/tests/functional/utils/pathChecker.php b/dev/tests/functional/utils/pathChecker.php deleted file mode 100644 index b5a2ddb405bde..0000000000000 --- a/dev/tests/functional/utils/pathChecker.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -include __DIR__ . '/authenticate.php'; - -if (!empty($_POST['token']) && !empty($_POST['path'])) { - if (authenticate(urldecode($_POST['token']))) { - $path = urldecode($_POST['path']); - - if (file_exists('../../../../' . $path)) { - echo 'path exists: true'; - } else { - echo 'path exists: false'; - } - } else { - echo "Command not unauthorized."; - } -} else { - echo "'token' or 'path' parameter is not set."; -} diff --git a/dev/tests/functional/utils/website.php b/dev/tests/functional/utils/website.php deleted file mode 100644 index ab8e3742f55ae..0000000000000 --- a/dev/tests/functional/utils/website.php +++ /dev/null @@ -1,37 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -include __DIR__ . '/authenticate.php'; - -if (!empty($_POST['token']) && !empty($_POST['website_code'])) { - if (authenticate(urldecode($_POST['token']))) { - $websiteCode = urldecode($_POST['website_code']); - $rootDir = '../../../../'; - $websiteDir = $rootDir . 'websites/' . $websiteCode . '/'; - $contents = file_get_contents($rootDir . 'index.php'); - - $websiteParam = <<<EOD -\$params = \$_SERVER; -\$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = '$websiteCode'; -\$params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'website'; -EOD; - - $pattern = '`(try {.*?)(\/app\/bootstrap.*?}\n)(.*?)\$_SERVER`mis'; - $replacement = "$1/../..$2\n$websiteParam$3\$params"; - - $contents = preg_replace($pattern, $replacement, $contents); - - $old = umask(0); - mkdir($websiteDir, 0760, true); - umask($old); - - copy($rootDir . '.htaccess', $websiteDir . '.htaccess'); - file_put_contents($websiteDir . 'index.php', $contents); - } else { - echo "Command not unauthorized."; - } -} else { - echo "'token' or 'website_code' parameter is not set."; -} From 5c2e115e698a32d61278055ac84d6554146274dc Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Wed, 19 Jun 2019 11:23:32 -0500 Subject: [PATCH 2005/2092] MAGETWO-99925: Product URL rewrites are always regenerated if products are updated via CSV import in default scope --- .../Magento/CatalogImportExport/Model/Import/ProductTest.php | 2 +- .../Import/_files/products_to_import_without_url_key_column.csv | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/products_to_import_without_url_key_column.csv diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php index f0b5d2fe6401c..3afe503dc1b6b 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php @@ -1597,7 +1597,7 @@ public function testImportWithoutChangingUrlKeys() $source = $this->objectManager->create( Csv::class, [ - 'file' => __DIR__ . '/_files/products_to_import_without_url_keys_column.csv', + 'file' => __DIR__ . '/_files/products_to_import_without_url_key_column.csv', 'directory' => $directory ] ); diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/products_to_import_without_url_key_column.csv b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/products_to_import_without_url_key_column.csv new file mode 100644 index 0000000000000..437ed182f9f5e --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/_files/products_to_import_without_url_key_column.csv @@ -0,0 +1,2 @@ +sku,product_type,store_view_code,name,price,attribute_set_code +simple1,simple,,"simple 1",25,Default \ No newline at end of file From 265d5fd988a1e6e8ea99b161c7228cd7fb4c8d9a Mon Sep 17 00:00:00 2001 From: Mastiuhin Olexandr <mastiuhin.olexandr@transoftgroup.com> Date: Wed, 19 Jun 2019 19:24:33 +0300 Subject: [PATCH 2006/2092] MAGETWO-99315: Restricted admin cannot edit reviews from pending reviews grid --- .../Magento/Review/Block/Adminhtml/Edit.php | 28 +++++- .../Review/Controller/Adminhtml/Product.php | 22 ++--- .../Controller/Adminhtml/Product/Delete.php | 55 ++++++++++- .../Controller/Adminhtml/Product/Edit.php | 53 +++++++++- .../Adminhtml/Product/MassDelete.php | 96 ++++++++++++++++++- .../Adminhtml/Product/MassUpdateStatus.php | 96 ++++++++++++++++++- .../Controller/Adminhtml/Product/Pending.php | 18 +++- .../Adminhtml/Product/ReviewGrid.php | 19 +++- .../Controller/Adminhtml/Product/Save.php | 56 ++++++++++- app/code/Magento/Review/i18n/en_US.csv | 2 + .../Controller/Adminhtml/Product/EditTest.php | 91 ++++++++++++++++++ .../Adminhtml/Product/MassUpdateTest.php | 93 ++++++++++++++++++ 12 files changed, 595 insertions(+), 34 deletions(-) create mode 100644 dev/tests/integration/testsuite/Magento/Review/Controller/Adminhtml/Product/EditTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Review/Controller/Adminhtml/Product/MassUpdateTest.php diff --git a/app/code/Magento/Review/Block/Adminhtml/Edit.php b/app/code/Magento/Review/Block/Adminhtml/Edit.php index d4079bbed3e3c..5efead952280e 100644 --- a/app/code/Magento/Review/Block/Adminhtml/Edit.php +++ b/app/code/Magento/Review/Block/Adminhtml/Edit.php @@ -7,7 +7,7 @@ namespace Magento\Review\Block\Adminhtml; /** - * Review edit form + * Review edit form. */ class Edit extends \Magento\Backend\Block\Widget\Form\Container { @@ -79,7 +79,13 @@ protected function _construct() 'previous', [ 'label' => __('Previous'), - 'onclick' => 'setLocation(\'' . $this->getUrl('review/*/*', ['id' => $prevId]) . '\')' + 'onclick' => 'setLocation(\'' . $this->getUrl( + 'review/*/*', + [ + 'id' => $prevId, + 'ret' => $this->getRequest()->getParam('ret'), + ] + ) . '\')' ], 3, 10 @@ -95,7 +101,10 @@ protected function _construct() 'button' => [ 'event' => 'save', 'target' => '#edit_form', - 'eventData' => ['action' => ['args' => ['next_item' => $prevId]]], + 'eventData' => ['action' => ['args' => [ + 'next_item' => $prevId, + 'ret' => $this->getRequest()->getParam('ret'), + ]]], ], ], ] @@ -115,7 +124,10 @@ protected function _construct() 'button' => [ 'event' => 'save', 'target' => '#edit_form', - 'eventData' => ['action' => ['args' => ['next_item' => $nextId]]], + 'eventData' => ['action' => ['args' => [ + 'next_item' => $nextId, + 'ret' => $this->getRequest()->getParam('ret'), + ]]], ], ], ] @@ -128,7 +140,13 @@ protected function _construct() 'next', [ 'label' => __('Next'), - 'onclick' => 'setLocation(\'' . $this->getUrl('review/*/*', ['id' => $nextId]) . '\')' + 'onclick' => 'setLocation(\'' . $this->getUrl( + 'review/*/*', + [ + 'id' => $nextId, + 'ret' => $this->getRequest()->getParam('ret'), + ] + ) . '\')' ], 3, 105 diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product.php b/app/code/Magento/Review/Controller/Adminhtml/Product.php index 8c4503d8f023e..32e30b0906dd8 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product.php @@ -12,10 +12,15 @@ use Magento\Review\Model\RatingFactory; /** - * Reviews admin controller + * Reviews admin controller. */ abstract class Product extends Action { + /** + * Authorization resource + */ + public const ADMIN_RESOURCE = 'Magento_Review::reviews_all'; + /** * Array of actions which can be processed without secret key validation * @@ -61,19 +66,4 @@ public function __construct( $this->ratingFactory = $ratingFactory; parent::__construct($context); } - - /** - * @return bool - */ - protected function _isAllowed() - { - switch ($this->getRequest()->getActionName()) { - case 'pending': - return $this->_authorization->isAllowed('Magento_Review::pending'); - break; - default: - return $this->_authorization->isAllowed('Magento_Review::reviews_all'); - break; - } - } } diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php index 68f178911dc7c..2af7d26202c3d 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php @@ -5,12 +5,24 @@ */ namespace Magento\Review\Controller\Adminhtml\Product; +use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Controller\ResultFactory; +use Magento\Review\Model\Review; -class Delete extends ProductController +/** + * Delete action. + */ +class Delete extends ProductController implements HttpPostActionInterface { /** + * @var Review + */ + private $model; + + /** + * Execute action. + * * @return \Magento\Backend\Model\View\Result\Redirect */ public function execute() @@ -20,7 +32,7 @@ public function execute() $reviewId = $this->getRequest()->getParam('id', false); if ($this->getRequest()->isPost()) { try { - $this->reviewFactory->create()->setId($reviewId)->aggregate()->delete(); + $this->getModel()->aggregate()->delete(); $this->messageManager->addSuccess(__('The review has been deleted.')); if ($this->getRequest()->getParam('ret') == 'pending') { @@ -39,4 +51,43 @@ public function execute() return $resultRedirect->setPath('review/*/edit/', ['id' => $reviewId]); } + + /** + * @inheritdoc + */ + protected function _isAllowed() + { + if (parent::_isAllowed()) { + return true; + } + + if (!$this->_authorization->isAllowed('Magento_Review::pending')) { + return false; + } + + if ($this->getModel()->getStatusId() != Review::STATUS_PENDING) { + $this->messageManager->addErrorMessage( + __('Sorry, You have not permission to do this. The Review is not in Pending status.') + ); + + return false; + } + + return true; + } + + /** + * Returns requested model. + * + * @return Review + */ + private function getModel(): Review + { + if ($this->model === null) { + $this->model = $this->reviewFactory->create() + ->load($this->getRequest()->getParam('id', false)); + } + + return $this->model; + } } diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php index a39b22ec080c6..bcf307944e0f9 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php @@ -5,12 +5,24 @@ */ namespace Magento\Review\Controller\Adminhtml\Product; +use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface; use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Controller\ResultFactory; +use Magento\Review\Model\Review; -class Edit extends ProductController +/** + * Edit action. + */ +class Edit extends ProductController implements HttpGetActionInterface { /** + * @var Review + */ + private $review; + + /** + * Execute action. + * * @return \Magento\Backend\Model\View\Result\Page */ public function execute() @@ -23,4 +35,43 @@ public function execute() $resultPage->addContent($resultPage->getLayout()->createBlock(\Magento\Review\Block\Adminhtml\Edit::class)); return $resultPage; } + + /** + * @inheritdoc + */ + protected function _isAllowed() + { + if (parent::_isAllowed()) { + return true; + } + + if (!$this->_authorization->isAllowed('Magento_Review::pending')) { + return false; + } + + if ($this->getModel()->getStatusId() != Review::STATUS_PENDING) { + $this->messageManager->addErrorMessage( + __('Sorry, You have not permission to do this. The Review is not in Pending status.') + ); + + return false; + } + + return true; + } + + /** + * Returns requested model. + * + * @return Review + */ + private function getModel(): Review + { + if ($this->review === null) { + $this->review = $this->reviewFactory->create() + ->load($this->getRequest()->getParam('id', false)); + } + + return $this->review; + } } diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php b/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php index 954c393276c14..c28c2e7b68f80 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php @@ -5,13 +5,54 @@ */ namespace Magento\Review\Controller\Adminhtml\Product; +use Magento\Backend\App\Action\Context; +use Magento\Framework\Registry; use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Controller\ResultFactory; +use Magento\Review\Model\RatingFactory; +use Magento\Review\Model\Review; +use Magento\Review\Model\ResourceModel\Review\Collection; +use Magento\Review\Model\ResourceModel\Review\CollectionFactory; +use Magento\Review\Model\ReviewFactory; +use Magento\Framework\App\Action\HttpPostActionInterface; -class MassDelete extends ProductController +/** + * Mass Delete action. + */ +class MassDelete extends ProductController implements HttpPostActionInterface { /** + * @var Collection + */ + private $collection; + + /** + * @var CollectionFactory + */ + private $collectionFactory; + + /** + * @param Context $context + * @param Registry $coreRegistry + * @param ReviewFactory $reviewFactory + * @param RatingFactory $ratingFactory + * @param CollectionFactory $collectionFactory + */ + public function __construct( + Context $context, + Registry $coreRegistry, + ReviewFactory $reviewFactory, + RatingFactory $ratingFactory, + CollectionFactory $collectionFactory + ) { + parent::__construct($context, $coreRegistry, $reviewFactory, $ratingFactory); + $this->collectionFactory = $collectionFactory; + } + + /** + * Execute action. + * * @return \Magento\Backend\Model\View\Result\Redirect * @throws \Magento\Framework\Exception\NotFoundException */ @@ -26,8 +67,7 @@ public function execute() $this->messageManager->addError(__('Please select review(s).')); } else { try { - foreach ($reviewsIds as $reviewId) { - $model = $this->reviewFactory->create()->load($reviewId); + foreach ($this->getCollection() as $model) { $model->delete(); } $this->messageManager->addSuccess( @@ -44,4 +84,54 @@ public function execute() $resultRedirect->setPath('review/*/' . $this->getRequest()->getParam('ret', 'index')); return $resultRedirect; } + + /** + * @inheritdoc + */ + protected function _isAllowed() + { + if (parent::_isAllowed()) { + return true; + } + + if (!$this->_authorization->isAllowed('Magento_Review::pending')) { + return false; + } + + foreach ($this->getCollection() as $model) { + if ($model->getStatusId() != Review::STATUS_PENDING) { + $this->messageManager->addErrorMessage( + __( + 'Sorry, You have not permission to do this.' + . ' One or more of the reviews are not in Pending Status.' + ) + ); + + return false; + } + } + + return true; + } + + /** + * Returns requested collection. + * + * @return Collection + */ + private function getCollection(): Collection + { + if ($this->collection === null) { + $collection = $this->collectionFactory->create(); + $collection->addFieldToFilter( + 'main_table.' . $collection->getResource() + ->getIdFieldName(), + $this->getRequest()->getParam('reviews') + ); + + $this->collection = $collection; + } + + return $this->collection; + } } diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php b/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php index a5850a6896321..eb45eab695591 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php @@ -5,13 +5,54 @@ */ namespace Magento\Review\Controller\Adminhtml\Product; +use Magento\Backend\App\Action\Context; +use Magento\Framework\Registry; use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Controller\ResultFactory; +use Magento\Review\Model\RatingFactory; +use Magento\Review\Model\Review; +use Magento\Review\Model\ResourceModel\Review\Collection; +use Magento\Review\Model\ResourceModel\Review\CollectionFactory; +use Magento\Review\Model\ReviewFactory; +use Magento\Framework\App\Action\HttpPostActionInterface; -class MassUpdateStatus extends ProductController +/** + * Mass Update Status action. + */ +class MassUpdateStatus extends ProductController implements HttpPostActionInterface { /** + * @var Collection + */ + private $collection; + + /** + * @var CollectionFactory + */ + private $collectionFactory; + + /** + * @param Context $context + * @param Registry $coreRegistry + * @param ReviewFactory $reviewFactory + * @param RatingFactory $ratingFactory + * @param CollectionFactory $collectionFactory + */ + public function __construct( + Context $context, + Registry $coreRegistry, + ReviewFactory $reviewFactory, + RatingFactory $ratingFactory, + CollectionFactory $collectionFactory + ) { + parent::__construct($context, $coreRegistry, $reviewFactory, $ratingFactory); + $this->collectionFactory = $collectionFactory; + } + + /** + * Execute action. + * * @return \Magento\Backend\Model\View\Result\Redirect * @throws \Magento\Framework\Exception\NotFoundException */ @@ -27,8 +68,7 @@ public function execute() } else { try { $status = $this->getRequest()->getParam('status'); - foreach ($reviewsIds as $reviewId) { - $model = $this->reviewFactory->create()->load($reviewId); + foreach ($this->getCollection() as $model) { $model->setStatusId($status)->save()->aggregate(); } $this->messageManager->addSuccess( @@ -48,4 +88,54 @@ public function execute() $resultRedirect->setPath('review/*/' . $this->getRequest()->getParam('ret', 'index')); return $resultRedirect; } + + /** + * @inheritdoc + */ + protected function _isAllowed() + { + if (parent::_isAllowed()) { + return true; + } + + if (!$this->_authorization->isAllowed('Magento_Review::pending')) { + return false; + } + + foreach ($this->getCollection() as $model) { + if ($model->getStatusId() != Review::STATUS_PENDING) { + $this->messageManager->addErrorMessage( + __( + 'Sorry, You have not permission to do this. ' + . 'One or more of the reviews are not in Pending Status.' + ) + ); + + return false; + } + } + + return true; + } + + /** + * Returns requested collection. + * + * @return Collection + */ + private function getCollection(): Collection + { + if ($this->collection === null) { + $collection = $this->collectionFactory->create(); + $collection->addFieldToFilter( + 'main_table.' . $collection->getResource() + ->getIdFieldName(), + $this->getRequest()->getParam('reviews') + ); + + $this->collection = $collection; + } + + return $this->collection; + } } diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Pending.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Pending.php index 75eaaaeeef24e..385b7e12bf32a 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Pending.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Pending.php @@ -7,10 +7,17 @@ use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\Action\HttpPostActionInterface; -class Pending extends ProductController +/** + * Pending reviews grid. + */ +class Pending extends ProductController implements HttpGetActionInterface, HttpPostActionInterface { /** + * Execute action. + * * @return \Magento\Framework\Controller\ResultInterface */ public function execute() @@ -30,4 +37,13 @@ public function execute() $resultPage->addContent($resultPage->getLayout()->createBlock(\Magento\Review\Block\Adminhtml\Main::class)); return $resultPage; } + + /** + * @inheritdoc + */ + protected function _isAllowed() + { + return $this->_authorization->isAllowed('Magento_Review::reviews_all') + || $this->_authorization->isAllowed('Magento_Review::pending'); + } } diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php b/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php index 017fbc95a8b9a..8925851e33420 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php @@ -12,8 +12,14 @@ use Magento\Review\Model\RatingFactory; use Magento\Framework\View\LayoutFactory; use Magento\Framework\Controller\ResultFactory; +use Magento\Framework\App\Request\Http; +use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\Action\HttpPostActionInterface; -class ReviewGrid extends ProductController +/** + * Review grid. + */ +class ReviewGrid extends ProductController implements HttpGetActionInterface, HttpPostActionInterface { /** * @var \Magento\Framework\View\LayoutFactory @@ -39,6 +45,8 @@ public function __construct( } /** + * Execute action. + * * @return \Magento\Framework\Controller\Result\Raw */ public function execute() @@ -49,4 +57,13 @@ public function execute() $resultRaw->setContents($layout->createBlock(\Magento\Review\Block\Adminhtml\Grid::class)->toHtml()); return $resultRaw; } + + /** + * @inheritdoc + */ + protected function _isAllowed() + { + return $this->_authorization->isAllowed('Magento_Review::reviews_all') + || $this->_authorization->isAllowed('Magento_Review::pending'); + } } diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Save.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Save.php index 7caf6de1583d5..ca870edb97c95 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Save.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Save.php @@ -8,12 +8,18 @@ use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Exception\LocalizedException; +use Magento\Review\Model\Review; /** * Save Review action. */ class Save extends ProductController { + /** + * @var Review + */ + private $review; + /** * Save Review action. * @@ -25,7 +31,7 @@ public function execute() /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (($data = $this->getRequest()->getPostValue()) && ($reviewId = $this->getRequest()->getParam('id'))) { - $review = $this->reviewFactory->create()->load($reviewId); + $review = $this->getModel(); if (!$review->getId()) { $this->messageManager->addError(__('The review was removed by another user or does not exist.')); } else { @@ -66,7 +72,14 @@ public function execute() $nextId = (int)$this->getRequest()->getParam('next_item'); if ($nextId) { - $resultRedirect->setPath('review/*/edit', ['id' => $nextId]); + $resultRedirect->setPath( + 'review/*/edit', + [ + 'id' => $nextId, + 'ret' => $this->getRequest() + ->getParam('ret'), + ] + ); } elseif ($this->getRequest()->getParam('ret') == 'pending') { $resultRedirect->setPath('review/*/pending'); } else { @@ -85,4 +98,43 @@ public function execute() $resultRedirect->setPath('review/*/'); return $resultRedirect; } + + /** + * @inheritdoc + */ + protected function _isAllowed() + { + if (parent::_isAllowed()) { + return true; + } + + if (!$this->_authorization->isAllowed('Magento_Review::pending')) { + return false; + } + + if ($this->getModel()->getStatusId() != Review::STATUS_PENDING) { + $this->messageManager->addErrorMessage( + __('Sorry, You have not permission to do this. The Review is not in Pending status.') + ); + + return false; + } + + return true; + } + + /** + * Returns requested model. + * + * @return Review + */ + private function getModel(): Review + { + if (!$this->review) { + $this->review = $this->reviewFactory->create() + ->load($this->getRequest()->getParam('id', false)); + } + + return $this->review; + } } diff --git a/app/code/Magento/Review/i18n/en_US.csv b/app/code/Magento/Review/i18n/en_US.csv index b3ea21dfcae90..c597f0ae70f04 100644 --- a/app/code/Magento/Review/i18n/en_US.csv +++ b/app/code/Magento/Review/i18n/en_US.csv @@ -135,3 +135,5 @@ Inactive,Inactive "Please select one of each of the ratings above.","Please select one of each of the ratings above." star,star stars,stars +"Sorry, You have not permission to do this. One or more of the reviews are not in Pending Status.","Sorry, You have not permission to do this. One or more of the reviews are not in Pending Status." +"Sorry, You have not permission to do this. The Review is not in Pending status.","Sorry, You have not permission to do this. The Review is not in Pending status." diff --git a/dev/tests/integration/testsuite/Magento/Review/Controller/Adminhtml/Product/EditTest.php b/dev/tests/integration/testsuite/Magento/Review/Controller/Adminhtml/Product/EditTest.php new file mode 100644 index 0000000000000..2af9b093cb815 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Review/Controller/Adminhtml/Product/EditTest.php @@ -0,0 +1,91 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Review\Controller\Adminhtml\Product; + +use Magento\Review\Model\Review; +use Magento\TestFramework\TestCase\AbstractBackendController; +use Magento\Framework\Acl\Builder; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\Framework\UrlInterface; +use Magento\Review\Model\ResourceModel\Review\CollectionFactory; + +/** + * Test Edit action. + * + * @magentoAppArea adminhtml + */ +class EditTest extends AbstractBackendController +{ + /** + * @var \Magento\Framework\ObjectManagerInterface + */ + private $objectManager; + + /** + * @var Builder + */ + private $aclBuilder; + + /** + * @var UrlInterface + */ + private $urlBuilder; + + /** + * @var CollectionFactory + */ + private $collectionFactory; + + /** + * @inheritdoc + */ + protected function setUp() + { + parent::setUp(); + + $this->objectManager = Bootstrap::getObjectManager(); + $this->aclBuilder = $this->objectManager->get(Builder::class); + $this->urlBuilder = $this->objectManager->get(UrlInterface::class); + $this->collectionFactory = $this->objectManager->get(CollectionFactory::class); + $this->aclBuilder->resetRuntimeAcl(); + } + + /** + * Tests Edit action without reviews_all resource when manipulating Pending review. + * + * @return void + * @magentoDataFixture Magento/Review/_files/reviews.php + */ + public function testAclHasAccess() + { + $collection = $this->collectionFactory->create(); + $collection->addFilter('detail.nickname', 'Nickname'); + /** @var Review $review */ + $review = $collection->getItemByColumnValue('status_id', Review::STATUS_PENDING); + + // Exclude resource from ACL. + $this->aclBuilder->getAcl()->deny(null, 'Magento_Review::reviews_all'); + $this->uri = 'backend/review/product/edit/id/' . $review->getId(); + + parent::testAclHasAccess(); + } + + /** + * Tests Edit action without pending and reviews_all resources. + * + * @return void + */ + public function testAclNoAccess() + { + // Exclude resource from ACL. + $this->resource = ['Magento_Review::reviews_all', 'Magento_Review::pending']; + $this->uri = 'backend/review/product/edit/id/' . 'doesn\'t matter'; + + parent::testAclNoAccess(); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Review/Controller/Adminhtml/Product/MassUpdateTest.php b/dev/tests/integration/testsuite/Magento/Review/Controller/Adminhtml/Product/MassUpdateTest.php new file mode 100644 index 0000000000000..8e8973af6f597 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Review/Controller/Adminhtml/Product/MassUpdateTest.php @@ -0,0 +1,93 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Review\Controller\Adminhtml\Product; + +use Magento\Review\Model\Review; +use Magento\TestFramework\TestCase\AbstractBackendController; +use Magento\Framework\Acl\Builder; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\Framework\UrlInterface; +use Magento\Review\Model\ResourceModel\Review\CollectionFactory; +use Zend\Http\Request; + +/** + * Test Mass Update action. + * + * @magentoAppArea adminhtml + */ +class MassUpdateTest extends AbstractBackendController +{ + /** + * @var \Magento\Framework\ObjectManagerInterface + */ + private $objectManager; + + /** + * @var Builder + */ + private $aclBuilder; + + /** + * @var UrlInterface + */ + private $urlBuilder; + + /** + * @var CollectionFactory + */ + private $collectionFactory; + + /** + * @inheritdoc + */ + protected function setUp() + { + parent::setUp(); + + $this->objectManager = Bootstrap::getObjectManager(); + $this->aclBuilder = $this->objectManager->get(Builder::class); + $this->urlBuilder = $this->objectManager->get(UrlInterface::class); + $this->collectionFactory = $this->objectManager->get(CollectionFactory::class); + $this->aclBuilder->resetRuntimeAcl(); + $this->httpMethod = Request::METHOD_POST; + $this->uri = 'backend/review/product/massUpdateStatus'; + } + + /** + * Tests Mass Update action without reviews_all resource when manipulating Pending reviews. + * + * @return void + * @magentoDataFixture Magento/Review/_files/reviews.php + */ + public function testAclHasAccess() + { + $collection = $this->collectionFactory->create(); + $collection->addFilter('detail.nickname', 'Nickname'); + /** @var Review $review */ + $review = $collection->getItemByColumnValue('status_id', Review::STATUS_PENDING); + + // Exclude resource from ACL. + $this->aclBuilder->getAcl()->deny(null, 'Magento_Review::reviews_all'); + $this->getRequest()->setPostValue(['reviews' => $review->getId()]); + + parent::testAclHasAccess(); + } + + /** + * Tests Mass Update action without pending and reviews_all resources. + * + * @return void + */ + public function testAclNoAccess() + { + // Exclude resource from ACL. + $this->resource = ['Magento_Review::reviews_all', 'Magento_Review::pending']; + + parent::testAclNoAccess(); + } +} From ec4fff2bfa0e48dc9d2e7b9c284c3c11e0e59b04 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Wed, 19 Jun 2019 13:07:51 -0500 Subject: [PATCH 2007/2092] MAGETWO-99925: Product URL rewrites are always regenerated if products are updated via CSV import in default scope --- app/code/Magento/CatalogImportExport/Model/Import/Product.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product.php b/app/code/Magento/CatalogImportExport/Model/Import/Product.php index 224f22f3325f0..9f3f3d6ce5fb8 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product.php @@ -2848,7 +2848,8 @@ protected function getUrlKey($rowData) return trim(strtolower($urlKey)); } - if (!empty($rowData[self::COL_NAME]) && array_key_exists(self::URL_KEY, $rowData)) { + if (!empty($rowData[self::COL_NAME]) + && (array_key_exists(self::URL_KEY, $rowData) || !$this->isSkuExist($rowData[self::COL_SKU]))) { return $this->productUrl->formatUrlKey($rowData[self::COL_NAME]); } From f389c3648e4aa8776a37139c79e05c94d51f30d9 Mon Sep 17 00:00:00 2001 From: Hwashiang Yu <hwyu@adobe.com> Date: Wed, 19 Jun 2019 13:56:42 -0500 Subject: [PATCH 2008/2092] MC-17547: Incorrect bundle and downloadable email template update - Updated correct typecasting - Updated template attributes --- .../creditmemo/create/items/renderer.phtml | 20 +++++++++---------- .../creditmemo/view/items/renderer.phtml | 2 +- .../sales/invoice/create/items/renderer.phtml | 18 ++++++++--------- .../sales/invoice/view/items/renderer.phtml | 2 +- .../sales/order/view/items/renderer.phtml | 14 ++++++------- .../shipment/create/items/renderer.phtml | 2 +- .../sales/shipment/view/items/renderer.phtml | 2 +- .../order/items/creditmemo/default.phtml | 2 +- .../email/order/items/invoice/default.phtml | 2 +- .../email/order/items/order/default.phtml | 2 +- .../email/order/items/shipment/default.phtml | 2 +- .../order/creditmemo/items/renderer.phtml | 18 ++++++++--------- .../sales/order/invoice/items/renderer.phtml | 14 ++++++------- .../sales/order/items/renderer.phtml | 14 ++++++------- .../sales/order/shipment/items/renderer.phtml | 10 +++++----- .../templates/customer/products/list.phtml | 10 +++++----- .../order/items/creditmemo/downloadable.phtml | 2 +- .../order/items/invoice/downloadable.phtml | 2 +- .../order/items/order/downloadable.phtml | 2 +- .../items/renderer/downloadable.phtml | 14 ++++++------- .../invoice/items/renderer/downloadable.phtml | 12 +++++------ .../order/items/renderer/downloadable.phtml | 10 +++++----- 22 files changed, 88 insertions(+), 88 deletions(-) diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/create/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/create/items/renderer.phtml index 4bd3ee6fef225..c480d9b126da6 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/create/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/create/items/renderer.phtml @@ -68,30 +68,30 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyOrdered()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyOrdered() * 1 ?></td> </tr> <?php if ((float) $_item->getOrderItem()->getQtyInvoiced()) : ?> <tr> <th><?= $block->escapeHtml(__('Invoiced')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyInvoiced()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyInvoiced() * 1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyShipped() && $block->isShipmentSeparately($_item)) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyShipped()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyShipped() * 1 ?></td> </tr> <?php endif; ?> - <?php if ((float) $_item->getOrderItem()->getQtyRefunded() : ?> + <?php if ((float) $_item->getOrderItem()->getQtyRefunded()) : ?> <tr> <th><?= $block->escapeHtml(__('Refunded')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyRefunded()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyRefunded() * 1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyCanceled()) : ?> <tr> <th><?= $block->escapeHtml(__('Canceled')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyCanceled()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyCanceled() * 1 ?></td> </tr> <?php endif; ?> </table> @@ -99,12 +99,12 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyOrdered()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyOrdered() * 1 ?></td> </tr> <?php if ((float) $_item->getOrderItem()->getQtyShipped()) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyShipped()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyShipped() * 1 ?></td> </tr> <?php endif; ?> </table> @@ -133,9 +133,9 @@ <input type="text" class="input-text admin__control-text qty-input" name="creditmemo[items][<?= $block->escapeHtmlAttr($_item->getOrderItemId()) ?>][qty]" - value="<?= (int)$_item->getQty()*1 ?>" /> + value="<?= (float)$_item->getQty() * 1 ?>" /> <?php else : ?> - <?= (int)$_item->getQty()*1 ?> + <?= (float)$_item->getQty() * 1 ?> <?php endif; ?> <?php else : ?>   diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/view/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/view/items/renderer.phtml index d52f41e27262f..0d54e1528dfe9 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/view/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/creditmemo/view/items/renderer.phtml @@ -63,7 +63,7 @@ </td> <td class="col-qty"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= (int)$_item->getQty()*1 ?> + <?= (float)$_item->getQty() * 1 ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/create/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/create/items/renderer.phtml index 2259a25b1e6c5..b3c4b0b1d999c 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/create/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/create/items/renderer.phtml @@ -69,30 +69,30 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><span><?= (float)$_item->getOrderItem()->getQtyOrdered()*1 ?></span></td> + <td><span><?= (float)$_item->getOrderItem()->getQtyOrdered() * 1 ?></span></td> </tr> <?php if ((float) $_item->getOrderItem()->getQtyInvoiced()) : ?> <tr> <th><?= $block->escapeHtml(__('Invoiced')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyInvoiced()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyInvoiced() * 1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyShipped() && $block->isShipmentSeparately($_item)) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyShipped()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyShipped() * 1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyRefunded()) : ?> <tr> <th><?= $block->escapeHtml(__('Refunded')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyRefunded()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyRefunded() * 1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getOrderItem()->getQtyCanceled()) : ?> <tr> <th><?= $block->escapeHtml(__('Canceled')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyCanceled()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyCanceled() * 1 ?></td> </tr> <?php endif; ?> </table> @@ -100,12 +100,12 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyOrdered()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyOrdered() * 1 ?></td> </tr> <?php if ((float) $_item->getOrderItem()->getQtyShipped()) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= (float)$_item->getOrderItem()->getQtyShipped()*1 ?></td> + <td><?= (float)$_item->getOrderItem()->getQtyShipped() * 1 ?></td> </tr> <?php endif; ?> </table> @@ -119,9 +119,9 @@ <input type="text" class="input-text admin__control-text qty-input" name="invoice[items][<?= $block->escapeHtmlAttr($_item->getOrderItemId()) ?>]" - value="<?= (int)$_item->getQty()*1 ?>" /> + value="<?= (float)$_item->getQty() * 1 ?>" /> <?php else : ?> - <?= (int)$_item->getQty()*1 ?> + <?= (float)$_item->getQty() * 1 ?> <?php endif; ?> <?php else : ?>   diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/view/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/view/items/renderer.phtml index 2126030219670..e29bb5dbc9479 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/view/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/invoice/view/items/renderer.phtml @@ -64,7 +64,7 @@ </td> <td class="col-qty"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= (int)$_item->getQty()*1 ?> + <?= (float)$_item->getQty() * 1 ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/order/view/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/order/view/items/renderer.phtml index 330d9e37f00c6..356a510888d8e 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/order/view/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/order/view/items/renderer.phtml @@ -87,30 +87,30 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= (float)$_item->getQtyOrdered()*1 ?></td> + <td><?= (float)$_item->getQtyOrdered() * 1 ?></td> </tr> <?php if ((float) $_item->getQtyInvoiced()) : ?> <tr> <th><?= $block->escapeHtml(__('Invoiced')) ?></th> - <td><?= (float)$_item->getQtyInvoiced()*1 ?></td> + <td><?= (float)$_item->getQtyInvoiced() * 1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getQtyShipped() && $block->isShipmentSeparately($_item)) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= (float)$_item->getQtyShipped()*1 ?></td> + <td><?= (float)$_item->getQtyShipped() * 1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getQtyRefunded()) : ?> <tr> <th><?= $block->escapeHtml(__('Refunded')) ?></th> - <td><?= (float)$_item->getQtyRefunded()*1 ?></td> + <td><?= (float)$_item->getQtyRefunded() * 1 ?></td> </tr> <?php endif; ?> <?php if ((float) $_item->getQtyCanceled()) : ?> <tr> <th><?= $block->escapeHtml(__('Canceled')) ?></th> - <td><?= (float)$_item->getQtyCanceled()*1 ?></td> + <td><?= (float)$_item->getQtyCanceled() * 1 ?></td> </tr> <?php endif; ?> </table> @@ -118,12 +118,12 @@ <table class="qty-table"> <tr> <th><?= $block->escapeHtml(__('Ordered')) ?></th> - <td><?= (float)$_item->getQtyOrdered()*1 ?></td> + <td><?= (float)$_item->getQtyOrdered() * 1 ?></td> </tr> <?php if ((float) $_item->getQtyShipped()) : ?> <tr> <th><?= $block->escapeHtml(__('Shipped')) ?></th> - <td><?= (float)$_item->getQtyShipped()*1 ?></td> + <td><?= (float)$_item->getQtyShipped() * 1 ?></td> </tr> <?php endif; ?> </table> diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/create/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/create/items/renderer.phtml index 3cb8473905fe9..2e52ed906626b 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/create/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/create/items/renderer.phtml @@ -58,7 +58,7 @@ <input type="text" class="input-text admin__control-text" name="shipment[items][<?= $block->escapeHtmlAttr($_item->getOrderItemId()) ?>]" - value="<?= (int)$_item->getQty()*1 ?>" /> + value="<?= (float)$_item->getQty() * 1 ?>" /> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/view/items/renderer.phtml b/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/view/items/renderer.phtml index bd9587024bcc0..521669700e10a 100644 --- a/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/view/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/adminhtml/templates/sales/shipment/view/items/renderer.phtml @@ -48,7 +48,7 @@ <td class="col-qty last"> <?php if (($block->isShipmentSeparately() && $_item->getParentItem()) || (!$block->isShipmentSeparately() && !$_item->getParentItem())) : ?> <?php if (isset($shipItems[$_item->getId()])) : ?> - <?= (int)$shipItems[$_item->getId()]->getQty()*1 ?> + <?= (float)$shipItems[$_item->getId()]->getQty() * 1 ?> <?php elseif ($_item->getIsVirtual()) : ?> <?= $block->escapeHtml(__('N/A')) ?> <?php else : ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/creditmemo/default.phtml b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/creditmemo/default.phtml index 58a234d728cbd..6230b7e8580fa 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/creditmemo/default.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/creditmemo/default.phtml @@ -52,7 +52,7 @@ <?php endif; ?> <td class="item-qty"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= (int)$_item->getQty() * 1 ?> + <?= (float)$_item->getQty() * 1 ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/invoice/default.phtml b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/invoice/default.phtml index 406888bcd902f..25702ef480cbb 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/invoice/default.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/invoice/default.phtml @@ -53,7 +53,7 @@ <?php endif; ?> <td class="item-qty"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= (int)$_item->getQty() * 1 ?> + <?= (float)$_item->getQty() * 1 ?> <?php else : ?>   <?php endif; ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/order/default.phtml b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/order/default.phtml index 5274ae9ab1447..b50b455b59a08 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/order/default.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/order/default.phtml @@ -39,7 +39,7 @@ <p class="sku"><?= $block->escapeHtml(__('SKU')) ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p> </td> <td class="item-qty"> - <?= (int)$_item->getQtyOrdered() * 1 ?> + <?= (float)$_item->getQtyOrdered() * 1 ?> </td> <td class="item-price"> <?= /* @noEscape */ $block->getItemPrice($_item) ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/shipment/default.phtml b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/shipment/default.phtml index 16b0c58cb5609..e63660802929e 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/email/order/items/shipment/default.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/email/order/items/shipment/default.phtml @@ -47,7 +47,7 @@ <td class="item-qty"> <?php if (($block->isShipmentSeparately() && $_item->getParentItem()) || (!$block->isShipmentSeparately() && !$_item->getParentItem())) : ?> <?php if (isset($shipItems[$_item->getId()])) : ?> - <?= (int)$shipItems[$_item->getId()]->getQty() * 1 ?> + <?= (float)$shipItems[$_item->getId()]->getQty() * 1 ?> <?php elseif ($_item->getIsVirtual()) : ?> <?= $block->escapeHtml(__('N/A')) ?> <?php else : ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml b/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml index 39080a1a14d07..87efa31a06a91 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/sales/order/creditmemo/items/renderer.phtml @@ -35,42 +35,42 @@ <?php if ($_item->getParentItem()) : ?> data-th="<?= $block->escapeHtmlAttr($attributes['option_label']) ?>"<?php endif; ?>> <?php if (!$_item->getOrderItem()->getParentItem()) : ?> - <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> + <td class="col name" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> </td> <?php else : ?> - <td class="col value" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"><?= $block->getValueHtml($_item) ?></td> + <td class="col value" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"><?= $block->getValueHtml($_item) ?></td> <?php endif; ?> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= $block->escapeHtml($_item->getSku()) ?></td> - <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> + <td class="col sku" data-th="<?= $block->escapeHtmlAttr(__('SKU')) ?>"><?= $block->escapeHtml($_item->getSku()) ?></td> + <td class="col price" data-th="<?= $block->escapeHtmlAttr(__('Price')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> <?= $block->getItemPriceHtml($_item) ?> <?php else : ?>   <?php endif; ?> </td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Quantity')) ?>"> + <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Quantity')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= (int)$_item->getQty()*1 ?> + <?= (float)$_item->getQty() * 1 ?> <?php else : ?>   <?php endif; ?> </td> - <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> + <td class="col subtotal" data-th="<?= $block->escapeHtmlAttr(__('Subtotal')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> <?= $block->getItemRowTotalHtml($_item) ?> <?php else : ?>   <?php endif; ?> </td> - <td class="col discount" data-th="<?= $block->escapeHtml(__('Discount Amount')) ?>"> + <td class="col discount" data-th="<?= $block->escapeHtmlAttr(__('Discount Amount')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> <?= $block->escapeHtml($block->getOrder()->formatPrice(-$_item->getDiscountAmount()), ['span']) ?> <?php else : ?>   <?php endif; ?> </td> - <td class="col rowtotal" data-th="<?= $block->escapeHtml(__('Row Total')) ?>"> + <td class="col rowtotal" data-th="<?= $block->escapeHtmlAttr(__('Row Total')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> <?= $block->getItemRowTotalAfterDiscountHtml($_item) ?> <?php else : ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/sales/order/invoice/items/renderer.phtml b/app/code/Magento/Bundle/view/frontend/templates/sales/order/invoice/items/renderer.phtml index 4677889f314bd..590ca301c29ff 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/sales/order/invoice/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/sales/order/invoice/items/renderer.phtml @@ -34,28 +34,28 @@ <?php if ($_item->getOrderItem()->getParentItem()) : ?> data-th="<?= $block->escapeHtmlAttr($attributes['option_label']) ?>"<?php endif; ?>> <?php if (!$_item->getOrderItem()->getParentItem()) : ?> - <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> + <td class="col name" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> </td> <?php else : ?> - <td class="col value" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"><?= $block->getValueHtml($_item) ?></td> + <td class="col value" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"><?= $block->getValueHtml($_item) ?></td> <?php endif; ?> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= $block->escapeHtml($_item->getSku()) ?></td> - <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> + <td class="col sku" data-th="<?= $block->escapeHtmlAttr(__('SKU')) ?>"><?= $block->escapeHtml($_item->getSku()) ?></td> + <td class="col price" data-th="<?= $block->escapeHtmlAttr(__('Price')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> <?= $block->getItemPriceHtml($_item) ?> <?php else : ?>   <?php endif; ?> </td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"> + <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Qty Invoiced')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> - <?= (int)$_item->getQty()*1 ?> + <?= (float)$_item->getQty() * 1 ?> <?php else : ?>   <?php endif; ?> </td> - <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> + <td class="col subtotal" data-th="<?= $block->escapeHtmlAttr(__('Subtotal')) ?>"> <?php if ($block->canShowPriceInfo($_item)) : ?> <?= $block->getItemRowTotalHtml($_item) ?> <?php else : ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/sales/order/items/renderer.phtml b/app/code/Magento/Bundle/view/frontend/templates/sales/order/items/renderer.phtml index 3c42334992a9f..0a946a2522ed9 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/sales/order/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/sales/order/items/renderer.phtml @@ -37,28 +37,28 @@ $prevOptionId = ''; item-parent <?php endif; ?>" <?php if ($item->getParentItem()) : ?> - data-th="<?= $block->escapeHtml($attributes['option_label']); ?>" + data-th="<?= $block->escapeHtmlAttr($attributes['option_label']); ?>" <?php endif; ?>> <?php if (!$item->getParentItem()) : ?> - <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')); ?>"> + <td class="col name" data-th="<?= $block->escapeHtmlAttr(__('Product Name')); ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($item->getName()); ?></strong> </td> <?php else : ?> - <td class="col value" data-th="<?= $block->escapeHtml(__('Product Name')); ?>"> + <td class="col value" data-th="<?= $block->escapeHtmlAttr(__('Product Name')); ?>"> <?= $block->getValueHtml($item); ?> </td> <?php endif; ?> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')); ?>"> + <td class="col sku" data-th="<?= $block->escapeHtmlAttr(__('SKU')); ?>"> <?= /* @noEscape */ $block->prepareSku($item->getSku()); ?> </td> - <td class="col price" data-th="<?= $block->escapeHtml(__('Price')); ?>"> + <td class="col price" data-th="<?= $block->escapeHtmlAttr(__('Price')); ?>"> <?php if (!$item->getParentItem()) : ?> <?= /* @noEscape */ $block->getItemPriceHtml(); ?> <?php else : ?>   <?php endif; ?> </td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Quantity')); ?>"> + <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Quantity')); ?>"> <?php if (($item->getParentItem() && $block->isChildCalculated()) || (!$item->getParentItem() && !$block->isChildCalculated()) || ($item->getQtyShipped() > 0 && $item->getParentItem() && $block->isShipmentSeparately())) : ?> @@ -104,7 +104,7 @@ $prevOptionId = ''; </ul> <?php endif; ?> </td> - <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> + <td class="col subtotal" data-th="<?= $block->escapeHtmlAttr(__('Subtotal')) ?>"> <?php if (!$item->getParentItem()) : ?> <?= /* @noEscape */ $block->getItemRowTotalHtml(); ?> <?php else : ?> diff --git a/app/code/Magento/Bundle/view/frontend/templates/sales/order/shipment/items/renderer.phtml b/app/code/Magento/Bundle/view/frontend/templates/sales/order/shipment/items/renderer.phtml index 3f54ec938a2c4..ae6e12b80d54e 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/sales/order/shipment/items/renderer.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/sales/order/shipment/items/renderer.phtml @@ -35,17 +35,17 @@ <?php if ($_item->getParentItem()) : ?> data-th="<?= $block->escapeHtmlAttr($attributes['option_label']) ?>"<?php endif; ?>> <?php if (!$_item->getParentItem()) : ?> - <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> + <td class="col name" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> </td> <?php else : ?> - <td class="col value" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"><?= $block->getValueHtml($_item) ?></td> + <td class="col value" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"><?= $block->getValueHtml($_item) ?></td> <?php endif; ?> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= $block->escapeHtml($_item->getSku()) ?></td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Shipped')) ?>"> + <td class="col sku" data-th="<?= $block->escapeHtmlAttr(__('SKU')) ?>"><?= $block->escapeHtml($_item->getSku()) ?></td> + <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Qty Shipped')) ?>"> <?php if (($block->isShipmentSeparately() && $_item->getParentItem()) || (!$block->isShipmentSeparately() && !$_item->getParentItem())) : ?> <?php if (isset($shipItems[$_item->getId()])) : ?> - <?= (int)$shipItems[$_item->getId()]->getQty()*1 ?> + <?= (float)$shipItems[$_item->getId()]->getQty() * 1 ?> <?php elseif ($_item->getIsVirtual()) : ?> <?= $block->escapeHtml(__('N/A')) ?> <?php else : ?> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/customer/products/list.phtml b/app/code/Magento/Downloadable/view/frontend/templates/customer/products/list.phtml index d040714aa9aef..eca72b3500924 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/customer/products/list.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/customer/products/list.phtml @@ -26,21 +26,21 @@ <tbody> <?php foreach ($_items as $_item) : ?> <tr> - <td data-th="<?= $block->escapeHtml(__('Order #')) ?>" class="col id"> + <td data-th="<?= $block->escapeHtmlAttr(__('Order #')) ?>" class="col id"> <a href="<?= $block->escapeUrl($block->getOrderViewUrl($_item->getPurchased()->getOrderId())) ?>" title="<?= $block->escapeHtml(__('View Order')) ?>"> <?= $block->escapeHtml($_item->getPurchased()->getOrderIncrementId()) ?> </a> </td> - <td data-th="<?= $block->escapeHtml(__('Date')) ?>" class="col date"><?= $block->escapeHtml($block->formatDate($_item->getPurchased()->getCreatedAt())) ?></td> - <td data-th="<?= $block->escapeHtml(__('Title')) ?>" class="col title"> + <td data-th="<?= $block->escapeHtmlAttr(__('Date')) ?>" class="col date"><?= $block->escapeHtml($block->formatDate($_item->getPurchased()->getCreatedAt())) ?></td> + <td data-th="<?= $block->escapeHtmlAttr(__('Title')) ?>" class="col title"> <strong class="product-name"><?= $block->escapeHtml($_item->getPurchased()->getProductName()) ?></strong> <?php if ($_item->getStatus() == \Magento\Downloadable\Model\Link\Purchased\Item::LINK_STATUS_AVAILABLE) : ?> <a href="<?= $block->escapeUrl($block->getDownloadUrl($_item)) ?>" title="<?= $block->escapeHtmlAttr(__('Start Download')) ?>" class="action download" <?= /* @noEscape */ $block->getIsOpenInNewWindow() ? 'onclick="this.target=\'_blank\'"' : '' ?>><?= $block->escapeHtml($_item->getLinkTitle()) ?></a> <?php endif; ?> </td> - <td data-th="<?= $block->escapeHtml(__('Status')) ?>" class="col status"><?= $block->escapeHtml(__(ucfirst($_item->getStatus()))) ?></td> - <td data-th="<?= $block->escapeHtml(__('Remaining Downloads')) ?>" class="col remaining"><?= $block->escapeHtml($block->getRemainingDownloads($_item)) ?></td> + <td data-th="<?= $block->escapeHtmlAttr(__('Status')) ?>" class="col status"><?= $block->escapeHtml(__(ucfirst($_item->getStatus()))) ?></td> + <td data-th="<?= $block->escapeHtmlAttr(__('Remaining Downloads')) ?>" class="col remaining"><?= $block->escapeHtml($block->getRemainingDownloads($_item)) ?></td> </tr> <?php endforeach; ?> </tbody> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/creditmemo/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/creditmemo/downloadable.phtml index bf4083e8a8b4e..25d2302e94b1c 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/creditmemo/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/creditmemo/downloadable.phtml @@ -31,7 +31,7 @@ <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="item-qty"><?= (int)$_item->getQty()*1 ?></td> + <td class="item-qty"><?= (float)$_item->getQty() * 1 ?></td> <td class="item-price"> <?= /* @noEscape */ $block->getItemPrice($_item) ?> </td> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/invoice/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/invoice/downloadable.phtml index e1e0b99e114cd..88f3b2cc6f9c7 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/invoice/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/invoice/downloadable.phtml @@ -32,7 +32,7 @@ <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="item-qty"><?= (int)$_item->getQty()*1 ?></td> + <td class="item-qty"><?= (float)$_item->getQty() * 1 ?></td> <td class="item-price"> <?= /* @noEscape */ $block->getItemPrice($_item) ?> </td> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/order/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/order/downloadable.phtml index da6ae3ca1248f..8dc552933fd3f 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/order/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/email/order/items/order/downloadable.phtml @@ -46,7 +46,7 @@ </table> <?php endif; ?> </td> - <td class="item-qty"><?= (int)$_item->getQtyOrdered() * 1 ?></td> + <td class="item-qty"><?= (float)$_item->getQtyOrdered() * 1 ?></td> <td class="item-price"> <?= /* @noEscape */ $block->getItemPrice($_item) ?> </td> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/creditmemo/items/renderer/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/creditmemo/items/renderer/downloadable.phtml index df5ddf6e10336..491d83ac0d5f9 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/creditmemo/items/renderer/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/creditmemo/items/renderer/downloadable.phtml @@ -9,7 +9,7 @@ <?php $_item = $block->getItem() ?> <?php $_order = $block->getItem()->getOrderItem()->getOrder() ?> <tr class="border" id="order-item-row-<?= $block->escapeHtmlAttr($_item->getId()) ?>"> - <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> + <td class="col name" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> <?php if ($_options = $block->getItemOptions()) : ?> <dl class="item-options links"> @@ -51,16 +51,16 @@ <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> - <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> + <td class="col sku" data-th="<?= $block->escapeHtmlAttr(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> + <td class="col price" data-th="<?= $block->escapeHtmlAttr(__('Price')) ?>"> <?= $block->getItemPriceHtml() ?> </td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"><?= (int)$_item->getQty()*1 ?></td> - <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> + <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Qty')) ?>"><?= (float)$_item->getQty() * 1 ?></td> + <td class="col subtotal" data-th="<?= $block->escapeHtmlAttr(__('Subtotal')) ?>"> <?= $block->getItemRowTotalHtml() ?> </td> - <td class="col discount" data-th="<?= $block->escapeHtml(__('Discount Amount')) ?>"><?= /* @noEscape */ $_order->formatPrice(-$_item->getDiscountAmount()) ?></td> - <td class="col total" data-th="<?= $block->escapeHtml(__('Row Total')) ?>"> + <td class="col discount" data-th="<?= $block->escapeHtmlAttr(__('Discount Amount')) ?>"><?= /* @noEscape */ $_order->formatPrice(-$_item->getDiscountAmount()) ?></td> + <td class="col total" data-th="<?= $block->escapeHtmlAttr(__('Row Total')) ?>"> <?= $block->getItemRowTotalAfterDiscountHtml() ?> </td> </tr> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml index e56b7aded3dbe..7d0d51775fc9b 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml @@ -9,7 +9,7 @@ <?php $_item = $block->getItem() ?> <?php $_order = $block->getItem()->getOrderItem()->getOrder() ?> <tr id="order-item-row-<?= $block->escapeHtmlAttr($_item->getId()) ?>"> - <td class="col name" data-th="<?= $block->escapeHtml(__('Product Name')) ?>"> + <td class="col name" data-th="<?= $block->escapeHtmlAttr(__('Product Name')) ?>"> <strong class="product name product-item-name"><?= $block->escapeHtml($_item->getName()) ?></strong> <?php if ($_options = $block->getItemOptions()) : ?> <dl class="item-options links"> @@ -50,14 +50,14 @@ <?php endif; ?> <?= $block->escapeHtml($_item->getDescription()) ?> </td> - <td class="col sku" data-th="<?= $block->escapeHtml(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> - <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> + <td class="col sku" data-th="<?= $block->escapeHtmlAttr(__('SKU')) ?>"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></td> + <td class="col price" data-th="<?= $block->escapeHtmlAttr(__('Price')) ?>"> <?= $block->getItemPriceHtml() ?> </td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"> - <span class="qty summary" data-label="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"><?= (int)$_item->getQty()*1 ?></span> + <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Qty Invoiced')) ?>"> + <span class="qty summary" data-label="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"><?= (float)$_item->getQty() * 1 ?></span> </td> - <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> + <td class="col subtotal" data-th="<?= $block->escapeHtmlAttr(__('Subtotal')) ?>"> <?= $block->getItemRowTotalHtml() ?> </td> </tr> diff --git a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/items/renderer/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/items/renderer/downloadable.phtml index 5dcf6857d422f..368f17449bb71 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/items/renderer/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/items/renderer/downloadable.phtml @@ -55,30 +55,30 @@ <td class="col price" data-th="<?= $block->escapeHtmlAttr(__('Price')) ?>"> <?= $block->getItemPriceHtml() ?> </td> - <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"> + <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Qty')) ?>"> <ul class="items-qty"> <?php if ($block->getItem()->getQtyOrdered() > 0) : ?> <li class="item"> <span class="title"><?= $block->escapeHtml(__('Ordered')) ?></span> - <span class="content"><?= (int)$block->getItem()->getQtyOrdered()*1 ?></span> + <span class="content"><?= (float)$block->getItem()->getQtyOrdered() * 1 ?></span> </li> <?php endif; ?> <?php if ($block->getItem()->getQtyShipped() > 0) : ?> <li class="item"> <span class="title"><?= $block->escapeHtml(__('Shipped')) ?></span> - <span class="content"><?= (int)$block->getItem()->getQtyShipped()*1 ?></span> + <span class="content"><?= (float)$block->getItem()->getQtyShipped() * 1 ?></span> </li> <?php endif; ?> <?php if ($block->getItem()->getQtyCanceled() > 0) : ?> <li class="item"> <span class="title"><?= $block->escapeHtml(__('Canceled')) ?></span> - <span class="content"><?= (int)$block->getItem()->getQtyCanceled()*1 ?></span> + <span class="content"><?= (float)$block->getItem()->getQtyCanceled() * 1 ?></span> </li> <?php endif; ?> <?php if ($block->getItem()->getQtyRefunded() > 0) : ?> <li class="item"> <span class="title"><?= $block->escapeHtml(__('Refunded')) ?></span> - <span class="content"><?= (int)$block->getItem()->getQtyRefunded()*1 ?></span> + <span class="content"><?= (float)$block->getItem()->getQtyRefunded() * 1 ?></span> </li> <?php endif; ?> </ul> From 85a865625c57e8a0380091202861392a641d3ff1 Mon Sep 17 00:00:00 2001 From: Hwashiang Yu <hwyu@adobe.com> Date: Wed, 19 Jun 2019 14:08:11 -0500 Subject: [PATCH 2009/2092] MC-17547: Incorrect bundle and downloadable email template update - Updated template attributes --- .../sales/order/invoice/items/renderer/downloadable.phtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml index 7d0d51775fc9b..7ea2de6e46ba1 100644 --- a/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml +++ b/app/code/Magento/Downloadable/view/frontend/templates/sales/order/invoice/items/renderer/downloadable.phtml @@ -55,7 +55,7 @@ <?= $block->getItemPriceHtml() ?> </td> <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Qty Invoiced')) ?>"> - <span class="qty summary" data-label="<?= $block->escapeHtml(__('Qty Invoiced')) ?>"><?= (float)$_item->getQty() * 1 ?></span> + <span class="qty summary" data-label="<?= $block->escapeHtmlAttr(__('Qty Invoiced')) ?>"><?= (float)$_item->getQty() * 1 ?></span> </td> <td class="col subtotal" data-th="<?= $block->escapeHtmlAttr(__('Subtotal')) ?>"> <?= $block->getItemRowTotalHtml() ?> From e0241c8eea4aa79a0a47964441f375f0e729c0ab Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov <oiegorov@magento.com> Date: Wed, 19 Jun 2019 16:15:12 -0500 Subject: [PATCH 2010/2092] MAGETWO-99925: Product URL rewrites are always regenerated if products are updated via CSV import in default scope --- .../Magento/CatalogImportExport/Model/Import/ProductTest.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php index 3afe503dc1b6b..829576ce8c193 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogImportExport/Model/Import/ProductTest.php @@ -2167,7 +2167,6 @@ public function testImportWithFilesystemImages() * @magentoDataFixture Magento/Catalog/_files/attribute_set_with_renamed_group.php * @magentoDataFixture Magento/Catalog/_files/product_without_options.php * @magentoDataFixture Magento/Catalog/_files/second_product_simple.php - * */ public function testImportDataChangeAttributeSet() { @@ -2184,7 +2183,7 @@ public function testImportDataChangeAttributeSet() ); $errors = $this->_model->setParameters( [ - 'behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_ADD_UPDATE, + 'behavior' => \Magento\ImportExport\Model\Import::BEHAVIOR_APPEND, 'entity' => \Magento\Catalog\Model\Product::ENTITY ] )->setSource( From 83a9c9b16a9d00590491a64684de65702e7d7956 Mon Sep 17 00:00:00 2001 From: Geeta <geeta@ranosys.com> Date: Sun, 19 May 2019 18:00:21 +0530 Subject: [PATCH 2011/2092] Fixed issue #18337 --- app/code/Magento/Search/view/frontend/web/js/form-mini.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/code/Magento/Search/view/frontend/web/js/form-mini.js b/app/code/Magento/Search/view/frontend/web/js/form-mini.js index 15bcf2e73393e..177ec5b50228f 100644 --- a/app/code/Magento/Search/view/frontend/web/js/form-mini.js +++ b/app/code/Magento/Search/view/frontend/web/js/form-mini.js @@ -71,8 +71,7 @@ define([ this.isExpandable = true; }.bind(this), exit: function () { - this.isExpandable = false; - this.element.removeAttr('aria-expanded'); + this.isExpandable = true; }.bind(this) }); From 39e7c2cbda322b7aac524fca6fa7566436bf143d Mon Sep 17 00:00:00 2001 From: Geeta <geeta@ranosys.com> Date: Fri, 31 May 2019 12:10:51 +0530 Subject: [PATCH 2012/2092] Resolve issue given by the QA --- app/code/Magento/Search/view/frontend/web/js/form-mini.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/code/Magento/Search/view/frontend/web/js/form-mini.js b/app/code/Magento/Search/view/frontend/web/js/form-mini.js index 177ec5b50228f..948fd1f27d964 100644 --- a/app/code/Magento/Search/view/frontend/web/js/form-mini.js +++ b/app/code/Magento/Search/view/frontend/web/js/form-mini.js @@ -69,9 +69,11 @@ define([ media: '(max-width: 768px)', entry: function () { this.isExpandable = true; + this.element.attr('aria-expanded', false); }.bind(this), exit: function () { this.isExpandable = true; + this.element.attr('aria-expanded', false); }.bind(this) }); From 3d989c6d0bf16b6b38d66bd1fdc9e80b77af5a68 Mon Sep 17 00:00:00 2001 From: Geeta <geeta@ranosys.com> Date: Thu, 6 Jun 2019 12:09:07 +0530 Subject: [PATCH 2013/2092] Removed attribute added code from form-mini js and added attribute in form --- .../Magento/Search/view/frontend/templates/form.mini.phtml | 3 ++- app/code/Magento/Search/view/frontend/web/js/form-mini.js | 2 -- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Search/view/frontend/templates/form.mini.phtml b/app/code/Magento/Search/view/frontend/templates/form.mini.phtml index a7635b7dc3fbe..888d5b678569f 100644 --- a/app/code/Magento/Search/view/frontend/templates/form.mini.phtml +++ b/app/code/Magento/Search/view/frontend/templates/form.mini.phtml @@ -35,7 +35,8 @@ $helper = $this->helper(\Magento\Search\Helper\Data::class); role="combobox" aria-haspopup="false" aria-autocomplete="both" - autocomplete="off"/> + autocomplete="off" + aria-expanded="false"/> <div id="search_autocomplete" class="search-autocomplete"></div> <?= $block->getChildHtml() ?> </div> diff --git a/app/code/Magento/Search/view/frontend/web/js/form-mini.js b/app/code/Magento/Search/view/frontend/web/js/form-mini.js index 948fd1f27d964..177ec5b50228f 100644 --- a/app/code/Magento/Search/view/frontend/web/js/form-mini.js +++ b/app/code/Magento/Search/view/frontend/web/js/form-mini.js @@ -69,11 +69,9 @@ define([ media: '(max-width: 768px)', entry: function () { this.isExpandable = true; - this.element.attr('aria-expanded', false); }.bind(this), exit: function () { this.isExpandable = true; - this.element.attr('aria-expanded', false); }.bind(this) }); From a9406b5da9f0e9315b161be358205075a42a12bd Mon Sep 17 00:00:00 2001 From: Gaurav Agarwal <37572719+gauravagarwal1001@users.noreply.github.com> Date: Fri, 14 Jun 2019 01:19:52 +0530 Subject: [PATCH 2014/2092] Fixed #23238 Apply coupon button act like remove coupon --- .../view/adminhtml/templates/order/create/coupons/form.phtml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml index d499df585e565..fe7b8ae28a199 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml @@ -17,8 +17,10 @@ <div class="admin__field field-apply-coupon-code"> <label class="admin__field-label"><span><?= /* @escapeNotVerified */ __('Apply Coupon Code') ?></span></label> <div class="admin__field-control"> + <?php if (!$block->getCouponCode()): ?> <input type="text" class="admin__control-text" id="coupons:code" value="" name="coupon_code" /> <?= $block->getButtonHtml(__('Apply'), 'order.applyCoupon($F(\'coupons:code\'))') ?> + <?php endif; ?> <?php if ($block->getCouponCode()): ?> <p class="added-coupon-code"> <span><?= $block->escapeHtml($block->getCouponCode()) ?></span> From 5b3b88b8c3ff852ca174253f2ab1e89181e8db17 Mon Sep 17 00:00:00 2001 From: Mastiuhin Olexandr <mastiuhin.olexandr@transoftgroup.com> Date: Thu, 20 Jun 2019 13:34:53 +0300 Subject: [PATCH 2015/2092] MAGETWO-99315: Restricted admin cannot edit reviews from pending reviews grid --- app/code/Magento/Review/Controller/Adminhtml/Product.php | 2 +- .../Magento/Review/Controller/Adminhtml/Product/Delete.php | 3 +-- .../Review/Controller/Adminhtml/Product/MassDelete.php | 3 +-- .../Review/Controller/Adminhtml/Product/MassUpdateStatus.php | 3 +-- .../Magento/Review/Controller/Adminhtml/Product/Pending.php | 4 +--- .../Review/Controller/Adminhtml/Product/ReviewGrid.php | 4 +--- 6 files changed, 6 insertions(+), 13 deletions(-) diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product.php b/app/code/Magento/Review/Controller/Adminhtml/Product.php index 32e30b0906dd8..e694fe0edec6c 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product.php @@ -19,7 +19,7 @@ abstract class Product extends Action /** * Authorization resource */ - public const ADMIN_RESOURCE = 'Magento_Review::reviews_all'; + const ADMIN_RESOURCE = 'Magento_Review::reviews_all'; /** * Array of actions which can be processed without secret key validation diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php index 2af7d26202c3d..fcbae259ef53b 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php @@ -5,7 +5,6 @@ */ namespace Magento\Review\Controller\Adminhtml\Product; -use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Controller\ResultFactory; use Magento\Review\Model\Review; @@ -13,7 +12,7 @@ /** * Delete action. */ -class Delete extends ProductController implements HttpPostActionInterface +class Delete extends ProductController { /** * @var Review diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php b/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php index c28c2e7b68f80..321064a2031c3 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php @@ -15,12 +15,11 @@ use Magento\Review\Model\ResourceModel\Review\Collection; use Magento\Review\Model\ResourceModel\Review\CollectionFactory; use Magento\Review\Model\ReviewFactory; -use Magento\Framework\App\Action\HttpPostActionInterface; /** * Mass Delete action. */ -class MassDelete extends ProductController implements HttpPostActionInterface +class MassDelete extends ProductController { /** * @var Collection diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php b/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php index eb45eab695591..45f76acf01164 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php @@ -15,12 +15,11 @@ use Magento\Review\Model\ResourceModel\Review\Collection; use Magento\Review\Model\ResourceModel\Review\CollectionFactory; use Magento\Review\Model\ReviewFactory; -use Magento\Framework\App\Action\HttpPostActionInterface; /** * Mass Update Status action. */ -class MassUpdateStatus extends ProductController implements HttpPostActionInterface +class MassUpdateStatus extends ProductController { /** * @var Collection diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Pending.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Pending.php index 385b7e12bf32a..9c54f22814c15 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Pending.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Pending.php @@ -7,13 +7,11 @@ use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; /** * Pending reviews grid. */ -class Pending extends ProductController implements HttpGetActionInterface, HttpPostActionInterface +class Pending extends ProductController { /** * Execute action. diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php b/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php index 8925851e33420..6afdffd77ea55 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php @@ -13,13 +13,11 @@ use Magento\Framework\View\LayoutFactory; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\App\Request\Http; -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; /** * Review grid. */ -class ReviewGrid extends ProductController implements HttpGetActionInterface, HttpPostActionInterface +class ReviewGrid extends ProductController { /** * @var \Magento\Framework\View\LayoutFactory From 65fa0da3ee50d8c9df08819d0ec199093b3092c7 Mon Sep 17 00:00:00 2001 From: Mastiuhin Olexandr <mastiuhin.olexandr@transoftgroup.com> Date: Thu, 20 Jun 2019 15:30:42 +0300 Subject: [PATCH 2016/2092] MAGETWO-99315: Restricted admin cannot edit reviews from pending reviews grid --- app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php | 3 +-- .../Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php index bcf307944e0f9..dacac2a1ad17d 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php @@ -5,7 +5,6 @@ */ namespace Magento\Review\Controller\Adminhtml\Product; -use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface; use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Controller\ResultFactory; use Magento\Review\Model\Review; @@ -13,7 +12,7 @@ /** * Edit action. */ -class Edit extends ProductController implements HttpGetActionInterface +class Edit extends ProductController { /** * @var Review diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php b/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php index 6afdffd77ea55..8c2324f35b09c 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/ReviewGrid.php @@ -12,7 +12,6 @@ use Magento\Review\Model\RatingFactory; use Magento\Framework\View\LayoutFactory; use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\App\Request\Http; /** * Review grid. From 1d9c0cec3f9a206e3a9eebe5fa9731279f5128dc Mon Sep 17 00:00:00 2001 From: "rostyslav.hymon" <rostyslav.hymon@transoftgroup.com> Date: Thu, 20 Jun 2019 16:19:13 +0300 Subject: [PATCH 2017/2092] MAGETWO-99719: Dasboard displays incorrect currency codes if default base currency differs from default website currency --- app/code/Magento/Backend/Block/Dashboard/Bar.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Backend/Block/Dashboard/Bar.php b/app/code/Magento/Backend/Block/Dashboard/Bar.php index 7ccb2d51ccd1b..819539940baa8 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Bar.php +++ b/app/code/Magento/Backend/Block/Dashboard/Bar.php @@ -5,6 +5,8 @@ */ namespace Magento\Backend\Block\Dashboard; +use Magento\Store\Model\Store; + /** * Adminhtml dashboard bar block * @@ -90,7 +92,7 @@ public function getCurrency() $this->getRequest()->getParam('group') )->getWebsite()->getBaseCurrency(); } else { - $this->_currentCurrencyCode = $this->_storeManager->getStore()->getBaseCurrency(); + $this->_currentCurrencyCode = $this->_storeManager->getStore(Store::DEFAULT_STORE_ID)->getBaseCurrency(); } } From 43770ea4c2c30ef79bb3e274f30d86782ed8c0b3 Mon Sep 17 00:00:00 2001 From: Mastiuhin Olexandr <mastiuhin.olexandr@transoftgroup.com> Date: Thu, 20 Jun 2019 20:19:50 +0300 Subject: [PATCH 2018/2092] MAGETWO-99315: Restricted admin cannot edit reviews from pending reviews grid --- .../Magento/Review/Controller/Adminhtml/Product/Delete.php | 5 ++++- .../Magento/Review/Controller/Adminhtml/Product/Edit.php | 5 ++++- .../Review/Controller/Adminhtml/Product/MassDelete.php | 4 ++-- .../Review/Controller/Adminhtml/Product/MassUpdateStatus.php | 4 ++-- .../Magento/Review/Controller/Adminhtml/Product/Save.php | 5 ++++- app/code/Magento/Review/i18n/en_US.csv | 4 ++-- 6 files changed, 18 insertions(+), 9 deletions(-) diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php index fcbae259ef53b..1289299b51eb5 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php @@ -66,7 +66,10 @@ protected function _isAllowed() if ($this->getModel()->getStatusId() != Review::STATUS_PENDING) { $this->messageManager->addErrorMessage( - __('Sorry, You have not permission to do this. The Review is not in Pending status.') + __( + 'You don’t have permission to perform this operation.' + . ' The selected review must be in Pending Status.' + ) ); return false; diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php index dacac2a1ad17d..86964fe38e952 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Edit.php @@ -50,7 +50,10 @@ protected function _isAllowed() if ($this->getModel()->getStatusId() != Review::STATUS_PENDING) { $this->messageManager->addErrorMessage( - __('Sorry, You have not permission to do this. The Review is not in Pending status.') + __( + 'You don’t have permission to perform this operation.' + . ' The selected review must be in Pending Status.' + ) ); return false; diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php b/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php index 321064a2031c3..c9d0f5f0259b1 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/MassDelete.php @@ -101,8 +101,8 @@ protected function _isAllowed() if ($model->getStatusId() != Review::STATUS_PENDING) { $this->messageManager->addErrorMessage( __( - 'Sorry, You have not permission to do this.' - . ' One or more of the reviews are not in Pending Status.' + 'You don’t have permission to perform this operation.' + . ' Selected reviews must be in Pending Status only.' ) ); diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php b/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php index 45f76acf01164..edcef8c8d6653 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/MassUpdateStatus.php @@ -105,8 +105,8 @@ protected function _isAllowed() if ($model->getStatusId() != Review::STATUS_PENDING) { $this->messageManager->addErrorMessage( __( - 'Sorry, You have not permission to do this. ' - . 'One or more of the reviews are not in Pending Status.' + 'You don’t have permission to perform this operation. ' + . 'Selected reviews must be in Pending Status only.' ) ); diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Save.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Save.php index ca870edb97c95..44a6aba172b15 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Save.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Save.php @@ -114,7 +114,10 @@ protected function _isAllowed() if ($this->getModel()->getStatusId() != Review::STATUS_PENDING) { $this->messageManager->addErrorMessage( - __('Sorry, You have not permission to do this. The Review is not in Pending status.') + __( + 'You don’t have permission to perform this operation.' + . ' The selected review must be in Pending Status.' + ) ); return false; diff --git a/app/code/Magento/Review/i18n/en_US.csv b/app/code/Magento/Review/i18n/en_US.csv index c597f0ae70f04..07b7e8c13bd1f 100644 --- a/app/code/Magento/Review/i18n/en_US.csv +++ b/app/code/Magento/Review/i18n/en_US.csv @@ -135,5 +135,5 @@ Inactive,Inactive "Please select one of each of the ratings above.","Please select one of each of the ratings above." star,star stars,stars -"Sorry, You have not permission to do this. One or more of the reviews are not in Pending Status.","Sorry, You have not permission to do this. One or more of the reviews are not in Pending Status." -"Sorry, You have not permission to do this. The Review is not in Pending status.","Sorry, You have not permission to do this. The Review is not in Pending status." +"You don’t have permission to perform this operation. Selected reviews must be in Pending Status only.","You don’t have permission to perform this operation. Selected reviews must be in Pending Status only." +"You don’t have permission to perform this operation. The selected review must be in Pending Status.","You don’t have permission to perform this operation. The selected review must be in Pending Status." From a491fdd50491917361cb555f4f169087120913c8 Mon Sep 17 00:00:00 2001 From: Dmytro Horytskyi <horytsky@adobe.com> Date: Thu, 20 Jun 2019 13:03:23 -0500 Subject: [PATCH 2019/2092] MAGETWO-73840: Videos in product description are displayed incorrectly --- lib/web/css/source/lib/_resets.less | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/web/css/source/lib/_resets.less b/lib/web/css/source/lib/_resets.less index 8228a07ef92ab..5ad50b3bb39ab 100644 --- a/lib/web/css/source/lib/_resets.less +++ b/lib/web/css/source/lib/_resets.less @@ -55,7 +55,7 @@ object, video, embed { - height: auto; + max-height: 100%; max-width: 100%; } From 4ae7c0ca8146071fb6fdc464bb96a7712fd671d2 Mon Sep 17 00:00:00 2001 From: Viktor Tymchynskyi <vtymchynskyi@magento.com> Date: Fri, 14 Jun 2019 09:01:23 -0500 Subject: [PATCH 2020/2092] MC-17551: Empty Order creation with Braintree and multiple address checkout --- .../method-renderer/multishipping/cc-form.js | 9 +-- .../method-renderer/multishipping/paypal.js | 9 +-- .../set-payment-information-extended.js | 60 +++++++++++++++++++ .../web/js/action/set-payment-information.js | 49 ++------------- .../frontend/web/js/view/payment/iframe.js | 19 ++++-- 5 files changed, 87 insertions(+), 59 deletions(-) create mode 100644 app/code/Magento/Checkout/view/frontend/web/js/action/set-payment-information-extended.js diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/cc-form.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/cc-form.js index dc816c035a23d..868fe174ae482 100644 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/cc-form.js +++ b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/cc-form.js @@ -12,7 +12,7 @@ define([ 'Magento_Ui/js/model/messageList', 'mage/translate', 'Magento_Checkout/js/model/full-screen-loader', - 'Magento_Checkout/js/action/set-payment-information', + 'Magento_Checkout/js/action/set-payment-information-extended', 'Magento_Checkout/js/model/payment/additional-validators', 'Magento_Braintree/js/view/payment/validator-handler' ], function ( @@ -22,7 +22,7 @@ define([ messageList, $t, fullScreenLoader, - setPaymentInformationAction, + setPaymentInformationExtended, additionalValidators, validatorManager ) { @@ -51,9 +51,10 @@ define([ if (additionalValidators.validate()) { fullScreenLoader.startLoader(); $.when( - setPaymentInformationAction( + setPaymentInformationExtended( this.messageContainer, - this.getData() + this.getData(), + true ) ).done(this.done.bind(this)) .fail(this.fail.bind(this)); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/paypal.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/paypal.js index 0a9ec4fb6c6ee..b3837103148cc 100644 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/paypal.js +++ b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/paypal.js @@ -8,14 +8,14 @@ define([ 'jquery', 'underscore', 'Magento_Braintree/js/view/payment/method-renderer/paypal', - 'Magento_Checkout/js/action/set-payment-information', + 'Magento_Checkout/js/action/set-payment-information-extended', 'Magento_Checkout/js/model/payment/additional-validators', 'Magento_Checkout/js/model/full-screen-loader' ], function ( $, _, Component, - setPaymentInformationAction, + setPaymentInformationExtended, additionalValidators, fullScreenLoader ) { @@ -131,9 +131,10 @@ define([ placeOrder: function () { fullScreenLoader.startLoader(); $.when( - setPaymentInformationAction( + setPaymentInformationExtended( this.messageContainer, - this.getData() + this.getData(), + true ) ).done(this.done.bind(this)) .fail(this.fail.bind(this)); diff --git a/app/code/Magento/Checkout/view/frontend/web/js/action/set-payment-information-extended.js b/app/code/Magento/Checkout/view/frontend/web/js/action/set-payment-information-extended.js new file mode 100644 index 0000000000000..4085da82f4151 --- /dev/null +++ b/app/code/Magento/Checkout/view/frontend/web/js/action/set-payment-information-extended.js @@ -0,0 +1,60 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/** + * @api + */ +define([ + 'Magento_Checkout/js/model/quote', + 'Magento_Checkout/js/model/url-builder', + 'mage/storage', + 'Magento_Checkout/js/model/error-processor', + 'Magento_Customer/js/model/customer', + 'Magento_Checkout/js/action/get-totals', + 'Magento_Checkout/js/model/full-screen-loader' +], function (quote, urlBuilder, storage, errorProcessor, customer, getTotalsAction, fullScreenLoader) { + 'use strict'; + + return function (messageContainer, paymentData, skipBilling) { + var serviceUrl, + payload; + + skipBilling = skipBilling || false; + payload = { + cartId: quote.getQuoteId(), + paymentMethod: paymentData + }; + + /** + * Checkout for guest and registered customer. + */ + if (!customer.isLoggedIn()) { + serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/set-payment-information', { + cartId: quote.getQuoteId() + }); + payload.email = quote.guestEmail; + } else { + serviceUrl = urlBuilder.createUrl('/carts/mine/set-payment-information', {}); + } + + if (skipBilling === false) { + payload.billingAddress = quote.billingAddress(); + } + + fullScreenLoader.startLoader(); + + return storage.post( + serviceUrl, JSON.stringify(payload) + ).fail( + function (response) { + errorProcessor.process(response, messageContainer); + } + ).always( + function () { + fullScreenLoader.stopLoader(); + } + ); + }; +}); diff --git a/app/code/Magento/Checkout/view/frontend/web/js/action/set-payment-information.js b/app/code/Magento/Checkout/view/frontend/web/js/action/set-payment-information.js index 997b60503a2b3..d5261c976a725 100644 --- a/app/code/Magento/Checkout/view/frontend/web/js/action/set-payment-information.js +++ b/app/code/Magento/Checkout/view/frontend/web/js/action/set-payment-information.js @@ -7,54 +7,13 @@ * @api */ define([ - 'Magento_Checkout/js/model/quote', - 'Magento_Checkout/js/model/url-builder', - 'mage/storage', - 'Magento_Checkout/js/model/error-processor', - 'Magento_Customer/js/model/customer', - 'Magento_Checkout/js/action/get-totals', - 'Magento_Checkout/js/model/full-screen-loader' -], function (quote, urlBuilder, storage, errorProcessor, customer, getTotalsAction, fullScreenLoader) { + 'Magento_Checkout/js/action/set-payment-information-extended' + +], function (setPaymentInformationExtended) { 'use strict'; return function (messageContainer, paymentData) { - var serviceUrl, - payload; - - /** - * Checkout for guest and registered customer. - */ - if (!customer.isLoggedIn()) { - serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/set-payment-information', { - cartId: quote.getQuoteId() - }); - payload = { - cartId: quote.getQuoteId(), - email: quote.guestEmail, - paymentMethod: paymentData, - billingAddress: quote.billingAddress() - }; - } else { - serviceUrl = urlBuilder.createUrl('/carts/mine/set-payment-information', {}); - payload = { - cartId: quote.getQuoteId(), - paymentMethod: paymentData, - billingAddress: quote.billingAddress() - }; - } - - fullScreenLoader.startLoader(); - return storage.post( - serviceUrl, JSON.stringify(payload) - ).fail( - function (response) { - errorProcessor.process(response, messageContainer); - } - ).always( - function () { - fullScreenLoader.stopLoader(); - } - ); + return setPaymentInformationExtended(messageContainer, paymentData, false); }; }); diff --git a/app/code/Magento/Payment/view/frontend/web/js/view/payment/iframe.js b/app/code/Magento/Payment/view/frontend/web/js/view/payment/iframe.js index 1e352e4297131..089dabac00b0f 100644 --- a/app/code/Magento/Payment/view/frontend/web/js/view/payment/iframe.js +++ b/app/code/Magento/Payment/view/frontend/web/js/view/payment/iframe.js @@ -125,12 +125,7 @@ define([ this.isPlaceOrderActionAllowed(false); $.when( - setPaymentInformationAction( - this.messageContainer, - { - method: this.getCode() - } - ) + this.setPaymentInformation() ).done( this.done.bind(this) ).fail( @@ -145,6 +140,18 @@ define([ } }, + /** + * {Function} + */ + setPaymentInformation: function () { + setPaymentInformationAction( + this.messageContainer, + { + method: this.getCode() + } + ); + }, + /** * {Function} */ From fff2c0d72a6e19ad873bb7b86758416e9b9860c3 Mon Sep 17 00:00:00 2001 From: "rostyslav.hymon" <rostyslav.hymon@transoftgroup.com> Date: Fri, 21 Jun 2019 09:12:19 +0300 Subject: [PATCH 2021/2092] MAGETWO-99719: Dasboard displays incorrect currency codes if default base currency differs from default website currency --- app/code/Magento/Backend/Block/Dashboard/Bar.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Backend/Block/Dashboard/Bar.php b/app/code/Magento/Backend/Block/Dashboard/Bar.php index 819539940baa8..e6bbdc116e3bc 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Bar.php +++ b/app/code/Magento/Backend/Block/Dashboard/Bar.php @@ -75,6 +75,7 @@ public function setCurrency($currency) * Retrieve currency model if not set then return currency model for current store * * @return \Magento\Directory\Model\Currency + * @SuppressWarnings(PHPMD.RequestAwareBlockMethod) */ public function getCurrency() { @@ -92,7 +93,8 @@ public function getCurrency() $this->getRequest()->getParam('group') )->getWebsite()->getBaseCurrency(); } else { - $this->_currentCurrencyCode = $this->_storeManager->getStore(Store::DEFAULT_STORE_ID)->getBaseCurrency(); + $this->_currentCurrencyCode = $this->_storeManager->getStore(Store::DEFAULT_STORE_ID) + ->getBaseCurrency(); } } From c068886d876c2fc76f6600ba515bc2e125f58697 Mon Sep 17 00:00:00 2001 From: sanjay <sanjay.chouhan180@webkul.com> Date: Wed, 8 May 2019 22:52:36 +0530 Subject: [PATCH 2022/2092] fixed issue #22736 - Cursor position not in right side of search keyword in mobile --- app/code/Magento/Search/view/frontend/web/js/form-mini.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/code/Magento/Search/view/frontend/web/js/form-mini.js b/app/code/Magento/Search/view/frontend/web/js/form-mini.js index 15bcf2e73393e..8654933190eed 100644 --- a/app/code/Magento/Search/view/frontend/web/js/form-mini.js +++ b/app/code/Magento/Search/view/frontend/web/js/form-mini.js @@ -134,6 +134,9 @@ define([ if (this.isExpandable) { this.element.attr('aria-expanded', isActive); + let searchValue = this.element.val(); + this.element.val(""); + this.element.val(searchValue); } }, From 525396ac328f058dcfd9ad740976ce1d8d8e2aa7 Mon Sep 17 00:00:00 2001 From: sanjay <sanjay.chouhan180@webkul.com> Date: Sat, 18 May 2019 09:00:35 +0530 Subject: [PATCH 2023/2092] changed according to guidelines --- app/code/Magento/Search/view/frontend/web/js/form-mini.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Search/view/frontend/web/js/form-mini.js b/app/code/Magento/Search/view/frontend/web/js/form-mini.js index 8654933190eed..c3019bcf5f822 100644 --- a/app/code/Magento/Search/view/frontend/web/js/form-mini.js +++ b/app/code/Magento/Search/view/frontend/web/js/form-mini.js @@ -129,12 +129,13 @@ define([ * @param {Boolean} isActive */ setActiveState: function (isActive) { + var searchValue; this.searchForm.toggleClass('active', isActive); this.searchLabel.toggleClass('active', isActive); if (this.isExpandable) { this.element.attr('aria-expanded', isActive); - let searchValue = this.element.val(); + searchValue = this.element.val(); this.element.val(""); this.element.val(searchValue); } From e7c33f33eaf6033a715828bdb64acc2aba935963 Mon Sep 17 00:00:00 2001 From: Volodymyr Zaets <vzaets@magento.com> Date: Mon, 20 May 2019 03:33:04 -0500 Subject: [PATCH 2024/2092] Update form-mini.js --- app/code/Magento/Search/view/frontend/web/js/form-mini.js | 1 + 1 file changed, 1 insertion(+) diff --git a/app/code/Magento/Search/view/frontend/web/js/form-mini.js b/app/code/Magento/Search/view/frontend/web/js/form-mini.js index c3019bcf5f822..e6428d7c65a0c 100644 --- a/app/code/Magento/Search/view/frontend/web/js/form-mini.js +++ b/app/code/Magento/Search/view/frontend/web/js/form-mini.js @@ -130,6 +130,7 @@ define([ */ setActiveState: function (isActive) { var searchValue; + this.searchForm.toggleClass('active', isActive); this.searchLabel.toggleClass('active', isActive); From 2464b3169e4a8d1294d69bdc1a9b0009adb3d8e5 Mon Sep 17 00:00:00 2001 From: Pavel Bystritsky <p.bystritsky@yandex.ru> Date: Tue, 21 May 2019 10:29:24 +0300 Subject: [PATCH 2025/2092] magento/magento2#22795: Static test fix. --- app/code/Magento/Search/view/frontend/web/js/form-mini.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Search/view/frontend/web/js/form-mini.js b/app/code/Magento/Search/view/frontend/web/js/form-mini.js index e6428d7c65a0c..8d62994a4dc75 100644 --- a/app/code/Magento/Search/view/frontend/web/js/form-mini.js +++ b/app/code/Magento/Search/view/frontend/web/js/form-mini.js @@ -130,14 +130,14 @@ define([ */ setActiveState: function (isActive) { var searchValue; - + this.searchForm.toggleClass('active', isActive); this.searchLabel.toggleClass('active', isActive); if (this.isExpandable) { this.element.attr('aria-expanded', isActive); searchValue = this.element.val(); - this.element.val(""); + this.element.val(''); this.element.val(searchValue); } }, From 98b9ece0a841af41062be60aa407626df0e012d4 Mon Sep 17 00:00:00 2001 From: Harald Deiser <h.deiser@techdivision.com> Date: Wed, 29 May 2019 16:52:04 +0200 Subject: [PATCH 2026/2092] MC-16700: Added further composer updates to submodule --- app/code/Magento/AdminNotification/composer.json | 2 +- app/code/Magento/AdvancedPricingImportExport/composer.json | 2 +- app/code/Magento/Analytics/composer.json | 2 +- app/code/Magento/Authorization/composer.json | 2 +- app/code/Magento/Authorizenet/composer.json | 2 +- app/code/Magento/Backend/composer.json | 2 +- app/code/Magento/Backup/composer.json | 2 +- app/code/Magento/Braintree/composer.json | 2 +- app/code/Magento/Bundle/composer.json | 2 +- app/code/Magento/BundleImportExport/composer.json | 2 +- app/code/Magento/CacheInvalidate/composer.json | 2 +- app/code/Magento/Captcha/composer.json | 2 +- app/code/Magento/Catalog/composer.json | 2 +- app/code/Magento/CatalogAnalytics/composer.json | 2 +- app/code/Magento/CatalogImportExport/composer.json | 2 +- app/code/Magento/CatalogInventory/composer.json | 2 +- app/code/Magento/CatalogRule/composer.json | 2 +- app/code/Magento/CatalogRuleConfigurable/composer.json | 2 +- app/code/Magento/CatalogSearch/composer.json | 2 +- app/code/Magento/CatalogUrlRewrite/composer.json | 2 +- app/code/Magento/CatalogWidget/composer.json | 2 +- app/code/Magento/Checkout/composer.json | 2 +- app/code/Magento/CheckoutAgreements/composer.json | 2 +- app/code/Magento/Cms/composer.json | 2 +- app/code/Magento/CmsUrlRewrite/composer.json | 2 +- app/code/Magento/Config/composer.json | 2 +- app/code/Magento/ConfigurableImportExport/composer.json | 2 +- app/code/Magento/ConfigurableProduct/composer.json | 2 +- app/code/Magento/ConfigurableProductSales/composer.json | 2 +- app/code/Magento/Contact/composer.json | 2 +- app/code/Magento/Cookie/composer.json | 2 +- app/code/Magento/Cron/composer.json | 2 +- app/code/Magento/CurrencySymbol/composer.json | 2 +- app/code/Magento/Customer/composer.json | 2 +- app/code/Magento/CustomerAnalytics/composer.json | 2 +- app/code/Magento/CustomerImportExport/composer.json | 2 +- app/code/Magento/Deploy/composer.json | 2 +- app/code/Magento/Developer/composer.json | 2 +- app/code/Magento/Dhl/composer.json | 2 +- app/code/Magento/Directory/composer.json | 2 +- app/code/Magento/Downloadable/composer.json | 2 +- app/code/Magento/DownloadableImportExport/composer.json | 2 +- app/code/Magento/Eav/composer.json | 2 +- app/code/Magento/Email/composer.json | 2 +- app/code/Magento/EncryptionKey/composer.json | 2 +- app/code/Magento/Fedex/composer.json | 2 +- app/code/Magento/GiftMessage/composer.json | 2 +- app/code/Magento/GoogleAdwords/composer.json | 2 +- app/code/Magento/GoogleAnalytics/composer.json | 2 +- app/code/Magento/GoogleOptimizer/composer.json | 2 +- app/code/Magento/GroupedImportExport/composer.json | 2 +- app/code/Magento/GroupedProduct/composer.json | 2 +- app/code/Magento/ImportExport/composer.json | 2 +- app/code/Magento/Indexer/composer.json | 2 +- app/code/Magento/InstantPurchase/composer.json | 2 +- app/code/Magento/Integration/composer.json | 2 +- app/code/Magento/LayeredNavigation/composer.json | 2 +- app/code/Magento/Marketplace/composer.json | 2 +- app/code/Magento/MediaStorage/composer.json | 2 +- app/code/Magento/Msrp/composer.json | 2 +- app/code/Magento/Multishipping/composer.json | 2 +- app/code/Magento/NewRelicReporting/composer.json | 2 +- app/code/Magento/Newsletter/composer.json | 2 +- app/code/Magento/OfflinePayments/composer.json | 2 +- app/code/Magento/OfflineShipping/composer.json | 2 +- app/code/Magento/PageCache/composer.json | 2 +- app/code/Magento/Payment/composer.json | 2 +- app/code/Magento/Paypal/composer.json | 2 +- app/code/Magento/PaypalCaptcha/composer.json | 2 +- app/code/Magento/Persistent/composer.json | 2 +- app/code/Magento/ProductAlert/composer.json | 2 +- app/code/Magento/ProductVideo/composer.json | 2 +- app/code/Magento/Quote/composer.json | 2 +- app/code/Magento/QuoteAnalytics/composer.json | 2 +- app/code/Magento/ReleaseNotification/composer.json | 2 +- app/code/Magento/Reports/composer.json | 2 +- app/code/Magento/RequireJs/composer.json | 2 +- app/code/Magento/Review/composer.json | 2 +- app/code/Magento/ReviewAnalytics/composer.json | 2 +- app/code/Magento/Robots/composer.json | 2 +- app/code/Magento/Rss/composer.json | 2 +- app/code/Magento/Rule/composer.json | 2 +- app/code/Magento/Sales/composer.json | 2 +- app/code/Magento/SalesAnalytics/composer.json | 2 +- app/code/Magento/SalesInventory/composer.json | 2 +- app/code/Magento/SalesRule/composer.json | 2 +- app/code/Magento/SalesSequence/composer.json | 2 +- app/code/Magento/SampleData/composer.json | 2 +- app/code/Magento/Search/composer.json | 2 +- app/code/Magento/Security/composer.json | 2 +- app/code/Magento/SendFriend/composer.json | 2 +- app/code/Magento/Shipping/composer.json | 2 +- app/code/Magento/Signifyd/composer.json | 2 +- app/code/Magento/Sitemap/composer.json | 2 +- app/code/Magento/Store/composer.json | 2 +- app/code/Magento/Swagger/composer.json | 2 +- app/code/Magento/SwaggerWebapi/composer.json | 2 +- app/code/Magento/Swatches/composer.json | 2 +- app/code/Magento/SwatchesLayeredNavigation/composer.json | 2 +- app/code/Magento/Tax/composer.json | 2 +- app/code/Magento/TaxImportExport/composer.json | 2 +- app/code/Magento/Theme/composer.json | 2 +- app/code/Magento/Translation/composer.json | 2 +- app/code/Magento/Ui/composer.json | 2 +- app/code/Magento/Ups/composer.json | 2 +- app/code/Magento/UrlRewrite/composer.json | 2 +- app/code/Magento/User/composer.json | 2 +- app/code/Magento/Usps/composer.json | 2 +- app/code/Magento/Variable/composer.json | 2 +- app/code/Magento/Vault/composer.json | 2 +- app/code/Magento/Version/composer.json | 2 +- app/code/Magento/Webapi/composer.json | 2 +- app/code/Magento/WebapiSecurity/composer.json | 2 +- app/code/Magento/Weee/composer.json | 2 +- app/code/Magento/Widget/composer.json | 2 +- app/code/Magento/Wishlist/composer.json | 2 +- app/code/Magento/WishlistAnalytics/composer.json | 2 +- lib/internal/Magento/Framework/composer.json | 2 +- 118 files changed, 118 insertions(+), 118 deletions(-) diff --git a/app/code/Magento/AdminNotification/composer.json b/app/code/Magento/AdminNotification/composer.json index 14afd21079f34..618191a84d6b8 100644 --- a/app/code/Magento/AdminNotification/composer.json +++ b/app/code/Magento/AdminNotification/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-admin-notification", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-media-storage": "100.2.*", diff --git a/app/code/Magento/AdvancedPricingImportExport/composer.json b/app/code/Magento/AdvancedPricingImportExport/composer.json index 4fa012f4acee8..c1424efe6033a 100644 --- a/app/code/Magento/AdvancedPricingImportExport/composer.json +++ b/app/code/Magento/AdvancedPricingImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-advanced-pricing-import-export", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-catalog-inventory": "100.2.*", "magento/module-eav": "101.0.*", diff --git a/app/code/Magento/Analytics/composer.json b/app/code/Magento/Analytics/composer.json index 11acfec76ca24..a268c3de09d7f 100644 --- a/app/code/Magento/Analytics/composer.json +++ b/app/code/Magento/Analytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-analytics", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-backend": "100.2.*", "magento/module-config": "101.0.*", "magento/module-integration": "100.2.*", diff --git a/app/code/Magento/Authorization/composer.json b/app/code/Magento/Authorization/composer.json index 1af2a1f672762..f982088934010 100644 --- a/app/code/Magento/Authorization/composer.json +++ b/app/code/Magento/Authorization/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-authorization", "description": "Authorization module provides access to Magento ACL functionality.", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-backend": "100.2.*", "magento/framework": "101.0.*" }, diff --git a/app/code/Magento/Authorizenet/composer.json b/app/code/Magento/Authorizenet/composer.json index d397f5cfae81e..ca9dfdb9a6e1f 100644 --- a/app/code/Magento/Authorizenet/composer.json +++ b/app/code/Magento/Authorizenet/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-authorizenet", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-sales": "101.0.*", "magento/module-store": "100.2.*", "magento/module-quote": "101.0.*", diff --git a/app/code/Magento/Backend/composer.json b/app/code/Magento/Backend/composer.json index d3b766da0006f..e0b9e02edf099 100644 --- a/app/code/Magento/Backend/composer.json +++ b/app/code/Magento/Backend/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-backend", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-directory": "100.2.*", "magento/module-developer": "100.2.*", diff --git a/app/code/Magento/Backup/composer.json b/app/code/Magento/Backup/composer.json index 6e741ae29cab5..d9a950ab13eb7 100644 --- a/app/code/Magento/Backup/composer.json +++ b/app/code/Magento/Backup/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-backup", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-cron": "100.2.*", diff --git a/app/code/Magento/Braintree/composer.json b/app/code/Magento/Braintree/composer.json index 0b9d76bc2ee9e..630ecc0544983 100644 --- a/app/code/Magento/Braintree/composer.json +++ b/app/code/Magento/Braintree/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-braintree", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/magento-composer-installer": "*", "magento/module-config": "101.0.*", diff --git a/app/code/Magento/Bundle/composer.json b/app/code/Magento/Bundle/composer.json index d82e4201bbda4..62c5ce5fea3a8 100644 --- a/app/code/Magento/Bundle/composer.json +++ b/app/code/Magento/Bundle/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-bundle", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-tax": "100.2.*", diff --git a/app/code/Magento/BundleImportExport/composer.json b/app/code/Magento/BundleImportExport/composer.json index 985b83a197369..ac28ca62e3563 100644 --- a/app/code/Magento/BundleImportExport/composer.json +++ b/app/code/Magento/BundleImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-bundle-import-export", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-import-export": "100.2.*", "magento/module-catalog-import-export": "100.2.*", diff --git a/app/code/Magento/CacheInvalidate/composer.json b/app/code/Magento/CacheInvalidate/composer.json index 4b9ef4e140f35..c03443310d594 100644 --- a/app/code/Magento/CacheInvalidate/composer.json +++ b/app/code/Magento/CacheInvalidate/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-cache-invalidate", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-page-cache": "100.2.*", "magento/framework": "101.0.*" }, diff --git a/app/code/Magento/Captcha/composer.json b/app/code/Magento/Captcha/composer.json index 471c4f976a300..398088624cfaa 100644 --- a/app/code/Magento/Captcha/composer.json +++ b/app/code/Magento/Captcha/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-captcha", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-customer": "101.0.*", "magento/module-checkout": "100.2.*", diff --git a/app/code/Magento/Catalog/composer.json b/app/code/Magento/Catalog/composer.json index 893f8d7190700..f78860dfd3ca7 100644 --- a/app/code/Magento/Catalog/composer.json +++ b/app/code/Magento/Catalog/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-eav": "101.0.*", "magento/module-cms": "102.0.*", diff --git a/app/code/Magento/CatalogAnalytics/composer.json b/app/code/Magento/CatalogAnalytics/composer.json index c2f5a050d0a9b..09df8e3329403 100644 --- a/app/code/Magento/CatalogAnalytics/composer.json +++ b/app/code/Magento/CatalogAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog-analytics", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-catalog": "102.0.*" }, diff --git a/app/code/Magento/CatalogImportExport/composer.json b/app/code/Magento/CatalogImportExport/composer.json index 180fdb95a4d9b..4e050dec829ef 100644 --- a/app/code/Magento/CatalogImportExport/composer.json +++ b/app/code/Magento/CatalogImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog-import-export", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-catalog-url-rewrite": "100.2.*", "magento/module-eav": "101.0.*", diff --git a/app/code/Magento/CatalogInventory/composer.json b/app/code/Magento/CatalogInventory/composer.json index 3086b50168aed..e79e19480448a 100644 --- a/app/code/Magento/CatalogInventory/composer.json +++ b/app/code/Magento/CatalogInventory/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog-inventory", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", diff --git a/app/code/Magento/CatalogRule/composer.json b/app/code/Magento/CatalogRule/composer.json index ef4dece889f6b..4c0fe257202a2 100644 --- a/app/code/Magento/CatalogRule/composer.json +++ b/app/code/Magento/CatalogRule/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog-rule", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-rule": "100.2.*", "magento/module-catalog": "102.0.*", diff --git a/app/code/Magento/CatalogRuleConfigurable/composer.json b/app/code/Magento/CatalogRuleConfigurable/composer.json index 16d5f2955d5d2..0a4524a769f26 100644 --- a/app/code/Magento/CatalogRuleConfigurable/composer.json +++ b/app/code/Magento/CatalogRuleConfigurable/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog-rule-configurable", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-configurable-product": "100.2.*", "magento/framework": "101.0.*", "magento/module-catalog": "102.0.*", diff --git a/app/code/Magento/CatalogSearch/composer.json b/app/code/Magento/CatalogSearch/composer.json index a5f1e5f6fc4f2..9945c2140dc7c 100644 --- a/app/code/Magento/CatalogSearch/composer.json +++ b/app/code/Magento/CatalogSearch/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog-search", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-indexer": "100.2.*", diff --git a/app/code/Magento/CatalogUrlRewrite/composer.json b/app/code/Magento/CatalogUrlRewrite/composer.json index a486b7bb3f6b8..1687d4b925df1 100644 --- a/app/code/Magento/CatalogUrlRewrite/composer.json +++ b/app/code/Magento/CatalogUrlRewrite/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog-url-rewrite", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-backend": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-catalog-import-export": "100.2.*", diff --git a/app/code/Magento/CatalogWidget/composer.json b/app/code/Magento/CatalogWidget/composer.json index 510026b008f4e..0e315d1efbde3 100644 --- a/app/code/Magento/CatalogWidget/composer.json +++ b/app/code/Magento/CatalogWidget/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-catalog-widget", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-widget": "101.0.*", "magento/module-backend": "100.2.*", diff --git a/app/code/Magento/Checkout/composer.json b/app/code/Magento/Checkout/composer.json index c46aaa9cb612c..2593155cb5155 100644 --- a/app/code/Magento/Checkout/composer.json +++ b/app/code/Magento/Checkout/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-checkout", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-sales": "101.0.*", "magento/module-catalog-inventory": "100.2.*", diff --git a/app/code/Magento/CheckoutAgreements/composer.json b/app/code/Magento/CheckoutAgreements/composer.json index 93ecb3bf836ae..4897676b4bd59 100644 --- a/app/code/Magento/CheckoutAgreements/composer.json +++ b/app/code/Magento/CheckoutAgreements/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-checkout-agreements", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-checkout": "100.2.*", "magento/module-quote": "101.0.*", "magento/module-store": "100.2.*", diff --git a/app/code/Magento/Cms/composer.json b/app/code/Magento/Cms/composer.json index d463cedd8dcd2..547814a8680ea 100644 --- a/app/code/Magento/Cms/composer.json +++ b/app/code/Magento/Cms/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-cms", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-theme": "100.2.*", "magento/module-widget": "101.0.*", diff --git a/app/code/Magento/CmsUrlRewrite/composer.json b/app/code/Magento/CmsUrlRewrite/composer.json index abd8ad9fe2916..572e95c0f0c03 100644 --- a/app/code/Magento/CmsUrlRewrite/composer.json +++ b/app/code/Magento/CmsUrlRewrite/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-cms-url-rewrite", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-cms": "102.0.*", "magento/module-url-rewrite": "101.0.*", diff --git a/app/code/Magento/Config/composer.json b/app/code/Magento/Config/composer.json index f36c29d387c9b..5b737b4c213d5 100644 --- a/app/code/Magento/Config/composer.json +++ b/app/code/Magento/Config/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-config", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-store": "100.2.*", "magento/module-cron": "100.2.*", diff --git a/app/code/Magento/ConfigurableImportExport/composer.json b/app/code/Magento/ConfigurableImportExport/composer.json index cf0e0e819a89c..aefc558733dd6 100644 --- a/app/code/Magento/ConfigurableImportExport/composer.json +++ b/app/code/Magento/ConfigurableImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-configurable-import-export", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-catalog-import-export": "100.2.*", "magento/module-eav": "101.0.*", diff --git a/app/code/Magento/ConfigurableProduct/composer.json b/app/code/Magento/ConfigurableProduct/composer.json index 90b1ce26a920b..218d66579b13e 100644 --- a/app/code/Magento/ConfigurableProduct/composer.json +++ b/app/code/Magento/ConfigurableProduct/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-configurable-product", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-catalog-inventory": "100.2.*", diff --git a/app/code/Magento/ConfigurableProductSales/composer.json b/app/code/Magento/ConfigurableProductSales/composer.json index 5baa9bef17e11..591eefdbed54f 100644 --- a/app/code/Magento/ConfigurableProductSales/composer.json +++ b/app/code/Magento/ConfigurableProductSales/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-configurable-product-sales", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-sales": "101.0.*", "magento/module-store": "100.2.*", diff --git a/app/code/Magento/Contact/composer.json b/app/code/Magento/Contact/composer.json index bb95e20c1172a..fc5bcfe0d9782 100644 --- a/app/code/Magento/Contact/composer.json +++ b/app/code/Magento/Contact/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-contact", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/Cookie/composer.json b/app/code/Magento/Cookie/composer.json index ba4427e9681b5..ea3334b20b86b 100644 --- a/app/code/Magento/Cookie/composer.json +++ b/app/code/Magento/Cookie/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-cookie", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/framework": "101.0.*" }, diff --git a/app/code/Magento/Cron/composer.json b/app/code/Magento/Cron/composer.json index a1f1e107a3c57..20426bedadd0e 100644 --- a/app/code/Magento/Cron/composer.json +++ b/app/code/Magento/Cron/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-cron", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/framework": "101.0.*" }, diff --git a/app/code/Magento/CurrencySymbol/composer.json b/app/code/Magento/CurrencySymbol/composer.json index 378b0df398ef5..2d9dd65422a98 100644 --- a/app/code/Magento/CurrencySymbol/composer.json +++ b/app/code/Magento/CurrencySymbol/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-currency-symbol", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-page-cache": "100.2.*", diff --git a/app/code/Magento/Customer/composer.json b/app/code/Magento/Customer/composer.json index e8d5fe2aaff48..67945e6ea5b4c 100644 --- a/app/code/Magento/Customer/composer.json +++ b/app/code/Magento/Customer/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-customer", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-eav": "101.0.*", "magento/module-directory": "100.2.*", diff --git a/app/code/Magento/CustomerAnalytics/composer.json b/app/code/Magento/CustomerAnalytics/composer.json index 901989b9d2550..9f0a1953eef99 100644 --- a/app/code/Magento/CustomerAnalytics/composer.json +++ b/app/code/Magento/CustomerAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-customer-analytics", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-customer": "101.0.*" }, diff --git a/app/code/Magento/CustomerImportExport/composer.json b/app/code/Magento/CustomerImportExport/composer.json index e0571ba1247ea..a77ce7a6fb63e 100644 --- a/app/code/Magento/CustomerImportExport/composer.json +++ b/app/code/Magento/CustomerImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-customer-import-export", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/Deploy/composer.json b/app/code/Magento/Deploy/composer.json index b33313081b0f0..11d2482278a21 100644 --- a/app/code/Magento/Deploy/composer.json +++ b/app/code/Magento/Deploy/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-deploy", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-store": "100.2.*", "magento/module-require-js": "100.2.*", diff --git a/app/code/Magento/Developer/composer.json b/app/code/Magento/Developer/composer.json index 776d565bf5efa..8c5063f111f66 100644 --- a/app/code/Magento/Developer/composer.json +++ b/app/code/Magento/Developer/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-developer", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/framework": "101.0.*", "magento/module-config": "101.0.*" diff --git a/app/code/Magento/Dhl/composer.json b/app/code/Magento/Dhl/composer.json index 93926d6e1e28b..5d95a2fffa7c0 100644 --- a/app/code/Magento/Dhl/composer.json +++ b/app/code/Magento/Dhl/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-dhl", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-shipping": "100.2.*", diff --git a/app/code/Magento/Directory/composer.json b/app/code/Magento/Directory/composer.json index 9681a951d9d06..420bd11e61d69 100644 --- a/app/code/Magento/Directory/composer.json +++ b/app/code/Magento/Directory/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-directory", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", diff --git a/app/code/Magento/Downloadable/composer.json b/app/code/Magento/Downloadable/composer.json index 3ea7f69c2fad5..9f347db1ff8d8 100644 --- a/app/code/Magento/Downloadable/composer.json +++ b/app/code/Magento/Downloadable/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-downloadable", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/DownloadableImportExport/composer.json b/app/code/Magento/DownloadableImportExport/composer.json index 07336fa5c9957..302953b1dcad6 100644 --- a/app/code/Magento/DownloadableImportExport/composer.json +++ b/app/code/Magento/DownloadableImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-downloadable-import-export", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-import-export": "100.2.*", "magento/module-catalog-import-export": "100.2.*", diff --git a/app/code/Magento/Eav/composer.json b/app/code/Magento/Eav/composer.json index b5f3c86947a0f..0fbb17591a1ba 100644 --- a/app/code/Magento/Eav/composer.json +++ b/app/code/Magento/Eav/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-eav", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-catalog": "102.0.*", diff --git a/app/code/Magento/Email/composer.json b/app/code/Magento/Email/composer.json index 6fda406b73483..9e3b936734380 100644 --- a/app/code/Magento/Email/composer.json +++ b/app/code/Magento/Email/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-email", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-theme": "100.2.*", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", diff --git a/app/code/Magento/EncryptionKey/composer.json b/app/code/Magento/EncryptionKey/composer.json index 1044173d8921d..1f1594e036617 100644 --- a/app/code/Magento/EncryptionKey/composer.json +++ b/app/code/Magento/EncryptionKey/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-encryption-key", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-backend": "100.2.*", "magento/framework": "101.0.*" diff --git a/app/code/Magento/Fedex/composer.json b/app/code/Magento/Fedex/composer.json index 9211bcffb0f71..fb6795306ac54 100644 --- a/app/code/Magento/Fedex/composer.json +++ b/app/code/Magento/Fedex/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-fedex", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-shipping": "100.2.*", "magento/module-directory": "100.2.*", diff --git a/app/code/Magento/GiftMessage/composer.json b/app/code/Magento/GiftMessage/composer.json index 7ad147a15989a..1817b60285ae2 100644 --- a/app/code/Magento/GiftMessage/composer.json +++ b/app/code/Magento/GiftMessage/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-gift-message", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-checkout": "100.2.*", diff --git a/app/code/Magento/GoogleAdwords/composer.json b/app/code/Magento/GoogleAdwords/composer.json index dec1440ecf174..514c600294906 100644 --- a/app/code/Magento/GoogleAdwords/composer.json +++ b/app/code/Magento/GoogleAdwords/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-google-adwords", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-sales": "101.0.*", "magento/framework": "101.0.*" diff --git a/app/code/Magento/GoogleAnalytics/composer.json b/app/code/Magento/GoogleAnalytics/composer.json index 7c6a511f8b5e4..03b6159d592cb 100644 --- a/app/code/Magento/GoogleAnalytics/composer.json +++ b/app/code/Magento/GoogleAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-google-analytics", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-sales": "101.0.*", "magento/framework": "101.0.*", diff --git a/app/code/Magento/GoogleOptimizer/composer.json b/app/code/Magento/GoogleOptimizer/composer.json index 5d84613c0e13c..08eee723a118a 100644 --- a/app/code/Magento/GoogleOptimizer/composer.json +++ b/app/code/Magento/GoogleOptimizer/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-google-optimizer", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-google-analytics": "100.2.*", "magento/module-catalog": "102.0.*", diff --git a/app/code/Magento/GroupedImportExport/composer.json b/app/code/Magento/GroupedImportExport/composer.json index 4e7573761f3a1..103803024b626 100644 --- a/app/code/Magento/GroupedImportExport/composer.json +++ b/app/code/Magento/GroupedImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-grouped-import-export", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-import-export": "100.2.*", "magento/module-catalog-import-export": "100.2.*", diff --git a/app/code/Magento/GroupedProduct/composer.json b/app/code/Magento/GroupedProduct/composer.json index 508b424b2c022..46ff706d4fc93 100644 --- a/app/code/Magento/GroupedProduct/composer.json +++ b/app/code/Magento/GroupedProduct/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-grouped-product", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-catalog-inventory": "100.2.*", diff --git a/app/code/Magento/ImportExport/composer.json b/app/code/Magento/ImportExport/composer.json index 9e9f1babad4a3..63dcf71bd714e 100644 --- a/app/code/Magento/ImportExport/composer.json +++ b/app/code/Magento/ImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-import-export", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", diff --git a/app/code/Magento/Indexer/composer.json b/app/code/Magento/Indexer/composer.json index 6b8ee0825fc14..448a81b432a38 100644 --- a/app/code/Magento/Indexer/composer.json +++ b/app/code/Magento/Indexer/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-indexer", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-backend": "100.2.*", "magento/framework": "101.0.*" }, diff --git a/app/code/Magento/InstantPurchase/composer.json b/app/code/Magento/InstantPurchase/composer.json index 1643692addbec..e1bfd440ba96d 100644 --- a/app/code/Magento/InstantPurchase/composer.json +++ b/app/code/Magento/InstantPurchase/composer.json @@ -8,7 +8,7 @@ "AFL-3.0" ], "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/Integration/composer.json b/app/code/Magento/Integration/composer.json index 5d457d76cb94e..945dd8c784eb9 100644 --- a/app/code/Magento/Integration/composer.json +++ b/app/code/Magento/Integration/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-integration", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/LayeredNavigation/composer.json b/app/code/Magento/LayeredNavigation/composer.json index 328549074f9b8..c198c0635b164 100644 --- a/app/code/Magento/LayeredNavigation/composer.json +++ b/app/code/Magento/LayeredNavigation/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-layered-navigation", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-catalog": "102.0.*", "magento/framework": "101.0.*" diff --git a/app/code/Magento/Marketplace/composer.json b/app/code/Magento/Marketplace/composer.json index 02824a6796fc7..b8b4c8384af09 100644 --- a/app/code/Magento/Marketplace/composer.json +++ b/app/code/Magento/Marketplace/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-marketplace", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-backend": "100.2.*" }, diff --git a/app/code/Magento/MediaStorage/composer.json b/app/code/Magento/MediaStorage/composer.json index a891dce37624d..18d55c4d68231 100644 --- a/app/code/Magento/MediaStorage/composer.json +++ b/app/code/Magento/MediaStorage/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-media-storage", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-config": "101.0.*", diff --git a/app/code/Magento/Msrp/composer.json b/app/code/Magento/Msrp/composer.json index 405c11dfe8195..ef16e069e7d2f 100644 --- a/app/code/Magento/Msrp/composer.json +++ b/app/code/Magento/Msrp/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-msrp", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-downloadable": "100.2.*", diff --git a/app/code/Magento/Multishipping/composer.json b/app/code/Magento/Multishipping/composer.json index 48095da856e02..aed4aadbd8ca6 100644 --- a/app/code/Magento/Multishipping/composer.json +++ b/app/code/Magento/Multishipping/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-multishipping", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-store": "100.2.*", "magento/module-checkout": "100.2.*", diff --git a/app/code/Magento/NewRelicReporting/composer.json b/app/code/Magento/NewRelicReporting/composer.json index b256b25716c87..a9d0aa9370a6a 100644 --- a/app/code/Magento/NewRelicReporting/composer.json +++ b/app/code/Magento/NewRelicReporting/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-new-relic-reporting", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/Newsletter/composer.json b/app/code/Magento/Newsletter/composer.json index 9e02676e2488c..480ee1b09b3b6 100644 --- a/app/code/Magento/Newsletter/composer.json +++ b/app/code/Magento/Newsletter/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-newsletter", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-customer": "101.0.*", "magento/module-widget": "101.0.*", diff --git a/app/code/Magento/OfflinePayments/composer.json b/app/code/Magento/OfflinePayments/composer.json index 747db3d70602e..dcb8e7c02b218 100644 --- a/app/code/Magento/OfflinePayments/composer.json +++ b/app/code/Magento/OfflinePayments/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-offline-payments", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-checkout": "100.2.*", "magento/module-payment": "100.2.*", "magento/framework": "101.0.*" diff --git a/app/code/Magento/OfflineShipping/composer.json b/app/code/Magento/OfflineShipping/composer.json index 416181733dc07..c71a39f1716d5 100644 --- a/app/code/Magento/OfflineShipping/composer.json +++ b/app/code/Magento/OfflineShipping/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-offline-shipping", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", diff --git a/app/code/Magento/PageCache/composer.json b/app/code/Magento/PageCache/composer.json index e83801344dae7..e2c323bb9e84c 100644 --- a/app/code/Magento/PageCache/composer.json +++ b/app/code/Magento/PageCache/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-page-cache", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", diff --git a/app/code/Magento/Payment/composer.json b/app/code/Magento/Payment/composer.json index 2f00b878417bd..333c65e806cd9 100644 --- a/app/code/Magento/Payment/composer.json +++ b/app/code/Magento/Payment/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-payment", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-sales": "101.0.*", diff --git a/app/code/Magento/Paypal/composer.json b/app/code/Magento/Paypal/composer.json index 5ee1739253ced..8a69d78f5351c 100644 --- a/app/code/Magento/Paypal/composer.json +++ b/app/code/Magento/Paypal/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-paypal", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-checkout": "100.2.*", diff --git a/app/code/Magento/PaypalCaptcha/composer.json b/app/code/Magento/PaypalCaptcha/composer.json index c2c7032ae8060..9d6fd95cf8dcb 100644 --- a/app/code/Magento/PaypalCaptcha/composer.json +++ b/app/code/Magento/PaypalCaptcha/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-paypal-captcha", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-captcha": "100.2.*", "magento/module-checkout": "100.2.*", diff --git a/app/code/Magento/Persistent/composer.json b/app/code/Magento/Persistent/composer.json index 0bfbc30e28f69..883c5ed1a3349 100644 --- a/app/code/Magento/Persistent/composer.json +++ b/app/code/Magento/Persistent/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-persistent", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-checkout": "100.2.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/ProductAlert/composer.json b/app/code/Magento/ProductAlert/composer.json index d2b7a8014d9a6..232879052d202 100644 --- a/app/code/Magento/ProductAlert/composer.json +++ b/app/code/Magento/ProductAlert/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-product-alert", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-backend": "100.2.*", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", diff --git a/app/code/Magento/ProductVideo/composer.json b/app/code/Magento/ProductVideo/composer.json index d92ab26d39fe5..6995a6723fe1a 100644 --- a/app/code/Magento/ProductVideo/composer.json +++ b/app/code/Magento/ProductVideo/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-product-video", "description": "Add Video to Products", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-backend": "100.2.*", "magento/module-eav": "101.0.*", diff --git a/app/code/Magento/Quote/composer.json b/app/code/Magento/Quote/composer.json index 202a5b601ceab..39017bb64df17 100644 --- a/app/code/Magento/Quote/composer.json +++ b/app/code/Magento/Quote/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-quote", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/QuoteAnalytics/composer.json b/app/code/Magento/QuoteAnalytics/composer.json index bc43c38421650..e3bff4f35a91c 100644 --- a/app/code/Magento/QuoteAnalytics/composer.json +++ b/app/code/Magento/QuoteAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-quote-analytics", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-quote": "101.0.*" }, diff --git a/app/code/Magento/ReleaseNotification/composer.json b/app/code/Magento/ReleaseNotification/composer.json index d16734d45f048..8c61d21882a07 100644 --- a/app/code/Magento/ReleaseNotification/composer.json +++ b/app/code/Magento/ReleaseNotification/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-release-notification", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-user": "101.0.*", "magento/module-backend": "100.2.*", "magento/framework": "101.0.*" diff --git a/app/code/Magento/Reports/composer.json b/app/code/Magento/Reports/composer.json index f9c0c3568b077..fbb1ebb54ac7b 100644 --- a/app/code/Magento/Reports/composer.json +++ b/app/code/Magento/Reports/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-reports", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-eav": "101.0.*", diff --git a/app/code/Magento/RequireJs/composer.json b/app/code/Magento/RequireJs/composer.json index 5c947c8d8e85d..d04f8695e881a 100644 --- a/app/code/Magento/RequireJs/composer.json +++ b/app/code/Magento/RequireJs/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-require-js", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*" }, "type": "magento2-module", diff --git a/app/code/Magento/Review/composer.json b/app/code/Magento/Review/composer.json index 4cc5cfc8d3f03..40aed162e5d8d 100644 --- a/app/code/Magento/Review/composer.json +++ b/app/code/Magento/Review/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-review", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/ReviewAnalytics/composer.json b/app/code/Magento/ReviewAnalytics/composer.json index b95b473c0af70..2b75ef9681ee3 100644 --- a/app/code/Magento/ReviewAnalytics/composer.json +++ b/app/code/Magento/ReviewAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-review-analytics", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-review": "100.2.*" }, diff --git a/app/code/Magento/Robots/composer.json b/app/code/Magento/Robots/composer.json index 9cf847e152ae7..1b36b13a86090 100644 --- a/app/code/Magento/Robots/composer.json +++ b/app/code/Magento/Robots/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-robots", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-store": "100.2.*" }, diff --git a/app/code/Magento/Rss/composer.json b/app/code/Magento/Rss/composer.json index 0a8acfe4981e1..1f5051995ae22 100644 --- a/app/code/Magento/Rss/composer.json +++ b/app/code/Magento/Rss/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-rss", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/framework": "101.0.*", diff --git a/app/code/Magento/Rule/composer.json b/app/code/Magento/Rule/composer.json index 33341dcf1e778..9777d5f5f6809 100644 --- a/app/code/Magento/Rule/composer.json +++ b/app/code/Magento/Rule/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-rule", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-eav": "101.0.*", "magento/module-catalog": "102.0.*", diff --git a/app/code/Magento/Sales/composer.json b/app/code/Magento/Sales/composer.json index a2730b255639f..c746f5dc0b541 100644 --- a/app/code/Magento/Sales/composer.json +++ b/app/code/Magento/Sales/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-sales", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-bundle": "100.2.*", diff --git a/app/code/Magento/SalesAnalytics/composer.json b/app/code/Magento/SalesAnalytics/composer.json index f6f2eaf29a70f..6d19d885114b2 100644 --- a/app/code/Magento/SalesAnalytics/composer.json +++ b/app/code/Magento/SalesAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-sales-analytics", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-sales": "101.0.*" }, diff --git a/app/code/Magento/SalesInventory/composer.json b/app/code/Magento/SalesInventory/composer.json index 28064cf97305e..44cb440a97385 100644 --- a/app/code/Magento/SalesInventory/composer.json +++ b/app/code/Magento/SalesInventory/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-sales-inventory", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog-inventory": "100.2.*", "magento/module-sales": "101.0.*", "magento/module-store": "100.2.*", diff --git a/app/code/Magento/SalesRule/composer.json b/app/code/Magento/SalesRule/composer.json index bf19520c7b552..f77696c2a6f0e 100644 --- a/app/code/Magento/SalesRule/composer.json +++ b/app/code/Magento/SalesRule/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-sales-rule", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-rule": "100.2.*", diff --git a/app/code/Magento/SalesSequence/composer.json b/app/code/Magento/SalesSequence/composer.json index a0c93b6310910..40a04df8f0530 100644 --- a/app/code/Magento/SalesSequence/composer.json +++ b/app/code/Magento/SalesSequence/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-sales-sequence", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*" }, "type": "magento2-module", diff --git a/app/code/Magento/SampleData/composer.json b/app/code/Magento/SampleData/composer.json index 31358c933acd3..3dadf9d2183e4 100644 --- a/app/code/Magento/SampleData/composer.json +++ b/app/code/Magento/SampleData/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-sample-data", "description": "Sample Data fixtures", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*" }, "suggest": { diff --git a/app/code/Magento/Search/composer.json b/app/code/Magento/Search/composer.json index 0ade5ca67b6ee..4ffe9bf0008c6 100644 --- a/app/code/Magento/Search/composer.json +++ b/app/code/Magento/Search/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-search", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-backend": "100.2.*", "magento/module-catalog-search": "100.2.*", diff --git a/app/code/Magento/Security/composer.json b/app/code/Magento/Security/composer.json index c3e632a8216a4..7f8c809bd72cd 100644 --- a/app/code/Magento/Security/composer.json +++ b/app/code/Magento/Security/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-security", "description": "Security management module", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-backend": "100.2.*", "magento/module-store": "100.2.*", "magento/framework": "101.0.*" diff --git a/app/code/Magento/SendFriend/composer.json b/app/code/Magento/SendFriend/composer.json index de252db3f3969..d0da89fdba3fb 100644 --- a/app/code/Magento/SendFriend/composer.json +++ b/app/code/Magento/SendFriend/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-send-friend", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-customer": "101.0.*", diff --git a/app/code/Magento/Shipping/composer.json b/app/code/Magento/Shipping/composer.json index a8bb256cdd305..d2653c5514077 100644 --- a/app/code/Magento/Shipping/composer.json +++ b/app/code/Magento/Shipping/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-shipping", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-sales": "101.0.*", diff --git a/app/code/Magento/Signifyd/composer.json b/app/code/Magento/Signifyd/composer.json index 62ecc442c3138..699e51c58d697 100644 --- a/app/code/Magento/Signifyd/composer.json +++ b/app/code/Magento/Signifyd/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-signifyd", "description": "Submitting Case Entry to Signifyd on Order Creation", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/framework": "101.0.*", "magento/module-sales": "101.0.*", diff --git a/app/code/Magento/Sitemap/composer.json b/app/code/Magento/Sitemap/composer.json index acc5c9d8f33a0..e3dfbe7c12173 100644 --- a/app/code/Magento/Sitemap/composer.json +++ b/app/code/Magento/Sitemap/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-sitemap", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-eav": "101.0.*", diff --git a/app/code/Magento/Store/composer.json b/app/code/Magento/Store/composer.json index 6059432d66038..b5d61ac833cda 100644 --- a/app/code/Magento/Store/composer.json +++ b/app/code/Magento/Store/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-store", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-directory": "100.2.*", "magento/module-ui": "101.0.*", diff --git a/app/code/Magento/Swagger/composer.json b/app/code/Magento/Swagger/composer.json index 67278bfd2b4a9..c3a5d174a0d8e 100644 --- a/app/code/Magento/Swagger/composer.json +++ b/app/code/Magento/Swagger/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-swagger", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*" }, "type": "magento2-module", diff --git a/app/code/Magento/SwaggerWebapi/composer.json b/app/code/Magento/SwaggerWebapi/composer.json index f2b5cb08948a4..803233d434401 100644 --- a/app/code/Magento/SwaggerWebapi/composer.json +++ b/app/code/Magento/SwaggerWebapi/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-swagger-webapi", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-swagger": "100.2.*" }, diff --git a/app/code/Magento/Swatches/composer.json b/app/code/Magento/Swatches/composer.json index 609fe43345d19..a97fed5a8dc6b 100644 --- a/app/code/Magento/Swatches/composer.json +++ b/app/code/Magento/Swatches/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-swatches", "description": "Add Swatches to Products", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-configurable-product": "100.2.*", "magento/module-eav": "101.0.*", diff --git a/app/code/Magento/SwatchesLayeredNavigation/composer.json b/app/code/Magento/SwatchesLayeredNavigation/composer.json index 61fee9b5279a6..35b3ebe9bf61a 100644 --- a/app/code/Magento/SwatchesLayeredNavigation/composer.json +++ b/app/code/Magento/SwatchesLayeredNavigation/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-swatches-layered-navigation", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/magento-composer-installer": "*" }, diff --git a/app/code/Magento/Tax/composer.json b/app/code/Magento/Tax/composer.json index be194636c1ec4..9dc30f19f1474 100644 --- a/app/code/Magento/Tax/composer.json +++ b/app/code/Magento/Tax/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-tax", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", diff --git a/app/code/Magento/TaxImportExport/composer.json b/app/code/Magento/TaxImportExport/composer.json index 72a442e29caca..929239846c1ac 100644 --- a/app/code/Magento/TaxImportExport/composer.json +++ b/app/code/Magento/TaxImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-tax-import-export", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-tax": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-directory": "100.2.*", diff --git a/app/code/Magento/Theme/composer.json b/app/code/Magento/Theme/composer.json index e83b49bbbee03..0a7c57c94a5b4 100644 --- a/app/code/Magento/Theme/composer.json +++ b/app/code/Magento/Theme/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-theme", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-customer": "101.0.*", "magento/module-backend": "100.2.*", diff --git a/app/code/Magento/Translation/composer.json b/app/code/Magento/Translation/composer.json index dd9e78d16614d..dd87050753c6b 100644 --- a/app/code/Magento/Translation/composer.json +++ b/app/code/Magento/Translation/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-translation", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-backend": "100.2.*", "magento/module-developer": "100.2.*", "magento/module-store": "100.2.*", diff --git a/app/code/Magento/Ui/composer.json b/app/code/Magento/Ui/composer.json index 4ad83870331a4..48d97c22a4fe1 100644 --- a/app/code/Magento/Ui/composer.json +++ b/app/code/Magento/Ui/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-ui", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-backend": "100.2.*", "magento/framework": "101.0.*", "magento/module-eav": "101.0.*", diff --git a/app/code/Magento/Ups/composer.json b/app/code/Magento/Ups/composer.json index 8a124a7c10f80..1b0ff56c3853a 100644 --- a/app/code/Magento/Ups/composer.json +++ b/app/code/Magento/Ups/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-ups", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-sales": "101.0.*", diff --git a/app/code/Magento/UrlRewrite/composer.json b/app/code/Magento/UrlRewrite/composer.json index 82d0ce9cd8365..59f1d0b623850 100644 --- a/app/code/Magento/UrlRewrite/composer.json +++ b/app/code/Magento/UrlRewrite/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-url-rewrite", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-catalog": "102.0.*", "magento/module-store": "100.2.*", "magento/framework": "101.0.*", diff --git a/app/code/Magento/User/composer.json b/app/code/Magento/User/composer.json index 513a34639b0a5..60e5778c0c431 100644 --- a/app/code/Magento/User/composer.json +++ b/app/code/Magento/User/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-user", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-authorization": "100.2.*", "magento/module-backend": "100.2.*", diff --git a/app/code/Magento/Usps/composer.json b/app/code/Magento/Usps/composer.json index 93456fb9a0a94..69ef9caa67220 100644 --- a/app/code/Magento/Usps/composer.json +++ b/app/code/Magento/Usps/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-usps", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-shipping": "100.2.*", "magento/module-directory": "100.2.*", diff --git a/app/code/Magento/Variable/composer.json b/app/code/Magento/Variable/composer.json index bfa87d1d5c935..c1c577934b23f 100644 --- a/app/code/Magento/Variable/composer.json +++ b/app/code/Magento/Variable/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-variable", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-backend": "100.2.*", "magento/module-email": "100.2.*", "magento/module-store": "100.2.*", diff --git a/app/code/Magento/Vault/composer.json b/app/code/Magento/Vault/composer.json index fa6ffe8f1d884..78b524ac04ef1 100644 --- a/app/code/Magento/Vault/composer.json +++ b/app/code/Magento/Vault/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-vault", "description": "", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-sales": "101.0.*", "magento/module-store": "100.2.*", diff --git a/app/code/Magento/Version/composer.json b/app/code/Magento/Version/composer.json index d8bfd8061aad1..8af6cbc770af2 100644 --- a/app/code/Magento/Version/composer.json +++ b/app/code/Magento/Version/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-version", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*" }, "type": "magento2-module", diff --git a/app/code/Magento/Webapi/composer.json b/app/code/Magento/Webapi/composer.json index d13034eddd5ac..9f6de6d1f118a 100644 --- a/app/code/Magento/Webapi/composer.json +++ b/app/code/Magento/Webapi/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-webapi", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-authorization": "100.2.*", "magento/module-integration": "100.2.*", diff --git a/app/code/Magento/WebapiSecurity/composer.json b/app/code/Magento/WebapiSecurity/composer.json index 6a2c3469f670a..7a8005f702e5e 100644 --- a/app/code/Magento/WebapiSecurity/composer.json +++ b/app/code/Magento/WebapiSecurity/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-webapi-security", "description": "WebapiSecurity module provides option to loosen security on some webapi resources.", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-webapi": "100.2.*", "magento/framework": "101.0.*" }, diff --git a/app/code/Magento/Weee/composer.json b/app/code/Magento/Weee/composer.json index efb6bddb9289c..e5e56e2449059 100644 --- a/app/code/Magento/Weee/composer.json +++ b/app/code/Magento/Weee/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-weee", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", "magento/module-tax": "100.2.*", diff --git a/app/code/Magento/Widget/composer.json b/app/code/Magento/Widget/composer.json index fc63ae00bdb7a..0f749439d581f 100644 --- a/app/code/Magento/Widget/composer.json +++ b/app/code/Magento/Widget/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-widget", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-cms": "102.0.*", "magento/module-backend": "100.2.*", diff --git a/app/code/Magento/Wishlist/composer.json b/app/code/Magento/Wishlist/composer.json index e99e0488284b9..f45813d6eebae 100644 --- a/app/code/Magento/Wishlist/composer.json +++ b/app/code/Magento/Wishlist/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-wishlist", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/module-store": "100.2.*", "magento/module-customer": "101.0.*", "magento/module-catalog": "102.0.*", diff --git a/app/code/Magento/WishlistAnalytics/composer.json b/app/code/Magento/WishlistAnalytics/composer.json index 6acee91b65ff2..f24bba445c102 100644 --- a/app/code/Magento/WishlistAnalytics/composer.json +++ b/app/code/Magento/WishlistAnalytics/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-wishlist-analytics", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*", "magento/module-wishlist": "101.0.*" }, diff --git a/lib/internal/Magento/Framework/composer.json b/lib/internal/Magento/Framework/composer.json index c674010af1a1f..86933cf59c3a2 100644 --- a/lib/internal/Magento/Framework/composer.json +++ b/lib/internal/Magento/Framework/composer.json @@ -8,7 +8,7 @@ "AFL-3.0" ], "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "ext-spl": "*", "ext-dom": "*", "ext-simplexml": "*", From 5cfbe4454f6eddfa2697168f518fb179d2fa9887 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht <f.ulbricht@techdivision.com> Date: Tue, 28 May 2019 09:40:24 +0200 Subject: [PATCH 2027/2092] MC-16965: Fixes UnitTests for PHP 7.2 and dropped support for ofb method --- .../Unit/Crypt/_files/_crypt_fixtures.php | 88 +++++-------------- .../Encryption/Test/Unit/CryptTest.php | 78 ++++------------ 2 files changed, 39 insertions(+), 127 deletions(-) diff --git a/lib/internal/Magento/Framework/Encryption/Test/Unit/Crypt/_files/_crypt_fixtures.php b/lib/internal/Magento/Framework/Encryption/Test/Unit/Crypt/_files/_crypt_fixtures.php index 1b96b756f5ff0..0fbe6515c80b2 100644 --- a/lib/internal/Magento/Framework/Encryption/Test/Unit/Crypt/_files/_crypt_fixtures.php +++ b/lib/internal/Magento/Framework/Encryption/Test/Unit/Crypt/_files/_crypt_fixtures.php @@ -30,14 +30,6 @@ 5 => '', ], 3 => [ - 0 => '5d304b80fbe2f6d6eaa51103d7558368e15f843b005fbd6353b7d0dd', - 1 => 'blowfish', - 2 => 'ofb', - 3 => 'a8e85663', - 4 => '', - 5 => '', - ], - 4 => [ 0 => 'f33d7a68248758b77863569a9caa08271fcda17eb3903e8c8f01ea48', 1 => 'blowfish', 2 => 'nofb', @@ -45,7 +37,7 @@ 4 => '', 5 => '', ], - 5 => [ + 4 => [ 0 => '7e34794ae07b3540a683cfd47b24a039', 1 => 'rijndael-128', 2 => 'ecb', @@ -53,7 +45,7 @@ 4 => '', 5 => '', ], - 6 => [ + 5 => [ 0 => 'eed11fb167c5ba7c6666b0379d3f0efd', 1 => 'rijndael-128', 2 => 'cbc', @@ -61,7 +53,7 @@ 4 => '', 5 => '', ], - 7 => [ + 6 => [ 0 => 'b0baa1454a71e4902d2f21cca5822a43', 1 => 'rijndael-128', 2 => 'cfb', @@ -69,15 +61,7 @@ 4 => '', 5 => '', ], - 8 => [ - 0 => '097577dd9bd37a37670d4ffac6db71ca', - 1 => 'rijndael-128', - 2 => 'ofb', - 3 => '9662705b5c8a92e2', - 4 => '', - 5 => '', - ], - 9 => [ + 7 => [ 0 => '26283c5ee61006051e109fb13cbeadd4', 1 => 'rijndael-128', 2 => 'nofb', @@ -85,7 +69,7 @@ 4 => '', 5 => '', ], - 10 => [ + 8 => [ 0 => '912940718c6991dcc9927fe1357a59eb', 1 => 'rijndael-256', 2 => 'ecb', @@ -93,7 +77,7 @@ 4 => '', 5 => '', ], - 11 => [ + 9 => [ 0 => '22eaec79b2ae279beac05375f1dd301f', 1 => 'rijndael-256', 2 => 'cbc', @@ -101,7 +85,7 @@ 4 => '', 5 => '', ], - 12 => [ + 10 => [ 0 => '331ff7ee00849ef02acfcc4a4c44b002', 1 => 'rijndael-256', 2 => 'cfb', @@ -109,15 +93,7 @@ 4 => '', 5 => '', ], - 13 => [ - 0 => '52b9991fb182434f8ef64db604c1946a', - 1 => 'rijndael-256', - 2 => 'ofb', - 3 => '95118150491d3acb936fed8f8aad942a', - 4 => '', - 5 => '', - ], - 14 => [ + 11 => [ 0 => '42cba7ea2c940077df289a594170c846', 1 => 'rijndael-256', 2 => 'nofb', @@ -125,7 +101,7 @@ 4 => '', 5 => '', ], - 15 => [ + 12 => [ 0 => '72f761d4c435986911087485b8664d40b28d12f818eca42edf84fecd', 1 => 'blowfish', 2 => 'ecb', @@ -133,7 +109,7 @@ 4 => 'Hello world!!!', 5 => 'UObRTUnq3jCNZjJOxwNubA==', ], - 16 => [ + 13 => [ 0 => '63341175e4edd8ef27ea0d754f985b6bbfddd29b381ea8473a450b8c', 1 => 'blowfish', 2 => 'cbc', @@ -141,7 +117,7 @@ 4 => 'Hello world!!!', 5 => '18QUXHt++6HiTQynQ4nUkg==', ], - 17 => [ + 14 => [ 0 => '5c4beba2e7571460dd0c2a6971dec5d707b6d8681a69e927ba8fac9f', 1 => 'blowfish', 2 => 'cfb', @@ -149,15 +125,7 @@ 4 => 'Hello world!!!', 5 => '11ubM60SiGkecJRFZMQ=', ], - 18 => [ - 0 => '073f901024e51b0ab85cf5944a90aea92bf353083ff642024f61a62d', - 1 => 'blowfish', - 2 => 'ofb', - 3 => 'a9b4f0ca', - 4 => 'Hello world!!!', - 5 => 'SqliQR1lHxY4r/HCgoI=', - ], - 19 => [ + 15 => [ 0 => '56df989b718351624480eb7776f827da7caf7996a6aa38dfa3e7328a', 1 => 'blowfish', 2 => 'nofb', @@ -165,7 +133,7 @@ 4 => 'Hello world!!!', 5 => 'vkPrtkjZ9TPapsG1sEY=', ], - 20 => [ + 16 => [ 0 => '6f326ec41c0e1d17fc030018043c0862', 1 => 'rijndael-128', 2 => 'ecb', @@ -173,7 +141,7 @@ 4 => 'Hello world!!!', 5 => 'dYsG1NhOM0lvXj32RqXJuw==', ], - 21 => [ + 17 => [ 0 => '7891bd79c8bae053e795733dd6b99d4e', 1 => 'rijndael-128', 2 => 'cbc', @@ -181,7 +149,7 @@ 4 => 'Hello world!!!', 5 => '5rMjKp16UzjD1rxcTFqNfg==', ], - 22 => [ + 18 => [ 0 => '247ec5c7e7fa07628090ed1e07bc601f', 1 => 'rijndael-128', 2 => 'cfb', @@ -189,15 +157,7 @@ 4 => 'Hello world!!!', 5 => 'OOhZb1g3owMU05jD2qk=', ], - 23 => [ - 0 => '0cedc5085da7c010a4136f7cc4c8f073', - 1 => 'rijndael-128', - 2 => 'ofb', - 3 => 'f7cf137c927714de', - 4 => 'Hello world!!!', - 5 => 'iq9Kx0artzuKew+HWpU=', - ], - 24 => [ + 19 => [ 0 => 'a0374d4b62c0394e01407f4133bc61c1', 1 => 'rijndael-128', 2 => 'nofb', @@ -205,7 +165,7 @@ 4 => 'Hello world!!!', 5 => 'gO5d+xbHk8E+8EH308E=', ], - 25 => [ + 20 => [ 0 => 'afa6f9c61c9199e2e4b6a1426dead6d4', 1 => 'rijndael-256', 2 => 'ecb', @@ -213,7 +173,7 @@ 4 => 'Hello world!!!', 5 => 'qTO/oVNzMhFZCnjCY90IuMuJcb7UVa7SXygKHWExX70=', ], - 26 => [ + 21 => [ 0 => '774bb6dac74b24796469d1865df679be', 1 => 'rijndael-256', 2 => 'cbc', @@ -221,7 +181,7 @@ 4 => 'Hello world!!!', 5 => '4APJzBRpwuZSqbIfr/GPS+Zb8wV/uo9qNSOvk68cGRM=', ], - 27 => [ + 22 => [ 0 => '0a319daff472006ec9d10a70920dd592', 1 => 'rijndael-256', 2 => 'cfb', @@ -229,15 +189,7 @@ 4 => 'Hello world!!!', 5 => 'GbcnmzgYRB+4ETtw5zQ=', ], - 28 => [ - 0 => '4fbd81fce821dd6042b46051eddcc300', - 1 => 'rijndael-256', - 2 => 'ofb', - 3 => 'b78b752f32a9788347f6f70e7a5fe1f0', - 4 => 'Hello world!!!', - 5 => 'PvbnFhmV0tej2c6zVIc=', - ], - 29 => [ + 23 => [ 0 => 'c183b2078424e7c9c129ba425421c0eb', 1 => 'rijndael-256', 2 => 'nofb', diff --git a/lib/internal/Magento/Framework/Encryption/Test/Unit/CryptTest.php b/lib/internal/Magento/Framework/Encryption/Test/Unit/CryptTest.php index fc513aac6e5ff..2f6a3edb0879d 100644 --- a/lib/internal/Magento/Framework/Encryption/Test/Unit/CryptTest.php +++ b/lib/internal/Magento/Framework/Encryption/Test/Unit/CryptTest.php @@ -18,25 +18,19 @@ class CryptTest extends \PHPUnit\Framework\TestCase private static $_cipherInfo; - protected $_supportedCiphers = [MCRYPT_BLOWFISH, MCRYPT_RIJNDAEL_128, MCRYPT_RIJNDAEL_256]; - - protected $_supportedModes = [ - MCRYPT_MODE_ECB, - MCRYPT_MODE_CBC, - MCRYPT_MODE_CFB, - MCRYPT_MODE_OFB, - MCRYPT_MODE_NOFB, + protected $_supportedCiphersModeCombinations = [ + MCRYPT_BLOWFISH => [MCRYPT_MODE_ECB], + MCRYPT_RIJNDAEL_128 => [MCRYPT_MODE_ECB], + MCRYPT_RIJNDAEL_256 => [MCRYPT_MODE_CBC], ]; protected function setUp() { - $this->markTestSkipped('MC-16965: need to fix'); $this->_key = substr(__CLASS__, -32, 32); } /** * @param $length - * * @return bool|string */ protected function _getRandomString($length) @@ -51,23 +45,7 @@ protected function _getRandomString($length) protected function _requireCipherInfo() { $filename = __DIR__ . '/Crypt/_files/_cipher_info.php'; - /* Generate allowed sizes for encryption key and init vector - $data = array(); - foreach ($this->_supportedCiphers as $cipher) { - if (!array_key_exists($cipher, $data)) { - $data[$cipher] = array(); - } - foreach ($this->_supportedModes as $mode) { - $cipherHandle = mcrypt_module_open($cipher, '', $mode, ''); - $data[$cipher][$mode] = array( - 'key_size' => mcrypt_enc_get_key_size($cipherHandle), - 'iv_size' => mcrypt_enc_get_iv_size($cipherHandle), - ); - mcrypt_module_close($cipherHandle); - } - } - file_put_contents($filename, '<?php return ' . var_export($data, true) . ";\n", LOCK_EX); - */ + if (!self::$_cipherInfo) { self::$_cipherInfo = include $filename; } @@ -76,7 +54,6 @@ protected function _requireCipherInfo() /** * @param $cipherName * @param $modeName - * * @return mixed */ protected function _getKeySize($cipherName, $modeName) @@ -88,7 +65,6 @@ protected function _getKeySize($cipherName, $modeName) /** * @param $cipherName * @param $modeName - * * @return mixed */ protected function _getInitVectorSize($cipherName, $modeName) @@ -100,12 +76,13 @@ protected function _getInitVectorSize($cipherName, $modeName) /** * @return array */ - public function getCipherModeCombinations() + public function getCipherModeCombinations(): array { $result = []; - foreach ($this->_supportedCiphers as $cipher) { - foreach ($this->_supportedModes as $mode) { - $result[] = [$cipher, $mode]; + foreach ($this->_supportedCiphersModeCombinations as $cipher => $modes) { + /** @var array $modes */ + foreach ($modes as $mode) { + $result[$cipher . '-' . $mode] = [$cipher, $mode]; } } return $result; @@ -131,15 +108,18 @@ public function testConstructor($cipher, $mode) */ public function getConstructorExceptionData() { + $key = substr(__CLASS__, -32, 32); $result = []; - foreach ($this->_supportedCiphers as $cipher) { - foreach ($this->_supportedModes as $mode) { + foreach ($this->_supportedCiphersModeCombinations as $cipher => $modes) { + /** @var array $modes */ + foreach ($modes as $mode) { $tooLongKey = str_repeat('-', $this->_getKeySize($cipher, $mode) + 1); $tooShortInitVector = str_repeat('-', $this->_getInitVectorSize($cipher, $mode) - 1); $tooLongInitVector = str_repeat('-', $this->_getInitVectorSize($cipher, $mode) + 1); - $result[] = [$tooLongKey, $cipher, $mode, false]; - $result[] = [$this->_key, $cipher, $mode, $tooShortInitVector]; - $result[] = [$this->_key, $cipher, $mode, $tooLongInitVector]; + $result['tooLongKey-' . $cipher . '-' . $mode . '-false'] = [$tooLongKey, $cipher, $mode, false]; + $keyPrefix = 'key-' . $cipher . '-' . $mode; + $result[$keyPrefix . '-tooShortInitVector'] = [$key, $cipher, $mode, $tooShortInitVector]; + $result[$keyPrefix . '-tooLongInitVector'] = [$key, $cipher, $mode, $tooLongInitVector]; } } return $result; @@ -170,27 +150,7 @@ public function testConstructorDefaults() public function getCryptData() { $fixturesFilename = __DIR__ . '/Crypt/_files/_crypt_fixtures.php'; - /* Generate fixtures - $fixtures = array(); - foreach (array('', 'Hello world!!!') as $inputString) { - foreach ($this->_supportedCiphers as $cipher) { - foreach ($this->_supportedModes as $mode) { - $randomKey = $this->_getRandomString($this->_getKeySize($cipher, $mode)); - $randomInitVector = $this->_getRandomString($this->_getInitVectorSize($cipher, $mode)); - $crypt = new \Magento\Framework\Encryption\Crypt($randomKey, $cipher, $mode, $randomInitVector); - $fixtures[] = array( - $randomKey, // Encryption key - $cipher, - $mode, - $randomInitVector, // Init vector - $inputString, // String to encrypt - base64_encode($crypt->encrypt($inputString)) // Store result of encryption as base64 - ); - } - } - } - file_put_contents($fixturesFilename, '<?php return ' . var_export($fixtures, true) . ";\n", LOCK_EX); - */ + $result = include $fixturesFilename; /* Restore encoded string back to binary */ foreach ($result as &$cryptParams) { From 07ea60b7196c0174beac2a2171d5e52f1e54592a Mon Sep 17 00:00:00 2001 From: Falk Ulbricht <f.ulbricht@techdivision.com> Date: Wed, 29 May 2019 13:00:21 +0200 Subject: [PATCH 2028/2092] MC-16722: Fixes UnitTests for PHP 7.2 --- app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeTest.php | 1 + .../Unit/Controller/Adminhtml/Order/Create/ReorderTest.php | 4 +++- app/code/Magento/Sales/Test/Unit/Model/Order/ConfigTest.php | 1 + .../Tax/Test/Unit/Plugin/Checkout/CustomerData/CartTest.php | 4 ++-- .../Ui/DataProvider/Product/Listing/Collector/TaxTest.php | 2 ++ .../Ui/DataProvider/Product/Listing/Collector/WeeeTest.php | 2 ++ 6 files changed, 11 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeTest.php index 18c94381a5054..e12ccbf016ea2 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/AttributeTest.php @@ -118,6 +118,7 @@ public function testGetFrontendLabels() $attributeId = 1; $storeLabels = ['test_attribute_store1']; $frontendLabelFactory = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\FrontendLabelFactory::class) + ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $resource = $this->getMockBuilder(\Magento\Eav\Model\ResourceModel\Entity\Attribute::class) diff --git a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ReorderTest.php b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ReorderTest.php index 1fdd9759f5045..8203b4486d193 100644 --- a/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ReorderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Controller/Adminhtml/Order/Create/ReorderTest.php @@ -118,7 +118,9 @@ protected function setUp() ->getMock(); $this->requestMock = $this->getMockBuilder(RequestInterface::class)->getMockForAbstractClass(); $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class)->getMockForAbstractClass(); - $this->resultForwardFactoryMock = $this->getMockBuilder(ForwardFactory::class)->getMock(); + $this->resultForwardFactoryMock = $this->getMockBuilder(ForwardFactory::class) + ->disableOriginalConstructor() + ->getMock(); $this->resultRedirectFactoryMock = $this->getMockBuilder(RedirectFactory::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/ConfigTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/ConfigTest.php index 86419c0c905b6..decce409b3331 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/ConfigTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/ConfigTest.php @@ -47,6 +47,7 @@ protected function setUp() 'storeManager' => $this->storeManagerMock, ]); $this->statusFactoryMock = $this->getMockBuilder(\Magento\Sales\Model\Order\StatusFactory::class) + ->disableOriginalConstructor() ->setMethods(['load', 'create']) ->getMock(); $this->orderStatusCollectionFactoryMock = $this->createPartialMock( diff --git a/app/code/Magento/Tax/Test/Unit/Plugin/Checkout/CustomerData/CartTest.php b/app/code/Magento/Tax/Test/Unit/Plugin/Checkout/CustomerData/CartTest.php index effc54b84ac04..d4218e6491837 100644 --- a/app/code/Magento/Tax/Test/Unit/Plugin/Checkout/CustomerData/CartTest.php +++ b/app/code/Magento/Tax/Test/Unit/Plugin/Checkout/CustomerData/CartTest.php @@ -119,7 +119,7 @@ public function testAfterGetSectionData() $this->assertArrayHasKey('items', $result); $this->assertTrue(is_array($result['items'])); $this->assertEquals(2, count($result['items'])); - $this->assertEquals(1, count($result['items'][0]['product_price'])); - $this->assertEquals(1, count($result['items'][1]['product_price'])); + $this->assertEquals(1, $result['items'][0]['product_price']); + $this->assertEquals(1, $result['items'][1]['product_price']); } } diff --git a/app/code/Magento/Tax/Test/Unit/Ui/DataProvider/Product/Listing/Collector/TaxTest.php b/app/code/Magento/Tax/Test/Unit/Ui/DataProvider/Product/Listing/Collector/TaxTest.php index 4cf3f4d339e18..908aeb5e3f405 100644 --- a/app/code/Magento/Tax/Test/Unit/Ui/DataProvider/Product/Listing/Collector/TaxTest.php +++ b/app/code/Magento/Tax/Test/Unit/Ui/DataProvider/Product/Listing/Collector/TaxTest.php @@ -68,10 +68,12 @@ protected function setUp() ->getMockForAbstractClass(); $this->priceInfoFactory = $this->getMockBuilder(PriceInfoInterfaceFactory::class) + ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->priceInfoExtensionFactory = $this->getMockBuilder(PriceInfoExtensionInterfaceFactory::class) + ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->formattedPriceInfoBuilder = $this->getMockBuilder(FormattedPriceInfoBuilder::class) diff --git a/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Listing/Collector/WeeeTest.php b/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Listing/Collector/WeeeTest.php index 6be1713c99004..6ba83ed7ce229 100644 --- a/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Listing/Collector/WeeeTest.php +++ b/app/code/Magento/Weee/Test/Unit/Ui/DataProvider/Product/Listing/Collector/WeeeTest.php @@ -50,6 +50,7 @@ protected function setUp() ->getMockForAbstractClass(); $this->weeeAdjustmentAttributeFactory = $this->getMockBuilder(WeeeAdjustmentAttributeInterfaceFactory::class) + ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -58,6 +59,7 @@ protected function setUp() ->getMock(); $this->priceInfoExtensionFactory = $this->getMockBuilder(PriceInfoExtensionInterfaceFactory::class) + ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); From 1483d65bfe2c58179c1a78b4210a0a0a489e3c48 Mon Sep 17 00:00:00 2001 From: Harald Deiser <h.deiser@techdivision.com> Date: Fri, 31 May 2019 11:33:45 +0200 Subject: [PATCH 2029/2092] MC-17030: Backported rss feed logic from M2.3 --- app/code/Magento/Rss/Model/Rss.php | 17 +++- .../Controller/Adminhtml/Feed/IndexTest.php | 13 +++- .../Test/Unit/Controller/Feed/IndexTest.php | 14 +++- .../Rss/Test/Unit/Model/RssManagerTest.php | 4 +- .../Magento/Rss/Test/Unit/Model/RssTest.php | 55 ++++++++++--- .../Rss/Test/Unit/Model/UrlBuilderTest.php | 3 +- app/etc/di.xml | 7 ++ composer.json | 1 + lib/internal/Magento/Framework/App/Feed.php | 38 +++++++++ .../Magento/Framework/App/FeedFactory.php | 78 +++++++++++++++++++ .../Framework/App/FeedFactoryInterface.php | 30 +++++++ .../Magento/Framework/App/FeedInterface.php | 21 +++++ 12 files changed, 262 insertions(+), 19 deletions(-) create mode 100644 lib/internal/Magento/Framework/App/Feed.php create mode 100644 lib/internal/Magento/Framework/App/FeedFactory.php create mode 100644 lib/internal/Magento/Framework/App/FeedFactoryInterface.php create mode 100644 lib/internal/Magento/Framework/App/FeedInterface.php diff --git a/app/code/Magento/Rss/Model/Rss.php b/app/code/Magento/Rss/Model/Rss.php index 7461c780fb230..c46c2240173f6 100644 --- a/app/code/Magento/Rss/Model/Rss.php +++ b/app/code/Magento/Rss/Model/Rss.php @@ -8,6 +8,7 @@ use Magento\Framework\App\ObjectManager; use Magento\Framework\App\Rss\DataProviderInterface; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\App\FeedFactoryInterface; /** * Provides functionality to work with RSS feeds @@ -27,6 +28,11 @@ class Rss */ protected $cache; + /** + * @var \Magento\Framework\App\FeedFactoryInterface + */ + private $feedFactory; + /** * @var SerializerInterface */ @@ -37,13 +43,16 @@ class Rss * * @param \Magento\Framework\App\CacheInterface $cache * @param SerializerInterface|null $serializer + * @param FeedFactoryInterface|null $feedFactory */ public function __construct( \Magento\Framework\App\CacheInterface $cache, - SerializerInterface $serializer = null + SerializerInterface $serializer = null, + FeedFactoryInterface $feedFactory = null ) { $this->cache = $cache; $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); + $this->feedFactory = $feedFactory ?: ObjectManager::getInstance()->get(FeedFactoryInterface::class); } /** @@ -89,10 +98,12 @@ public function setDataProvider(DataProviderInterface $dataProvider) /** * @return string + * @throws \Magento\Framework\Exception\InputException + * @throws \Magento\Framework\Exception\RuntimeException */ public function createRssXml() { - $rssFeedFromArray = \Zend_Feed::importArray($this->getFeeds(), 'rss'); - return $rssFeedFromArray->saveXML(); + $feed = $this->feedFactory->create($this->getFeeds(), FeedFactoryInterface::FORMAT_RSS); + return $feed->getFormattedContent(); } } diff --git a/app/code/Magento/Rss/Test/Unit/Controller/Adminhtml/Feed/IndexTest.php b/app/code/Magento/Rss/Test/Unit/Controller/Adminhtml/Feed/IndexTest.php index 32aab6ffb92bc..a601f8fb2d1d7 100644 --- a/app/code/Magento/Rss/Test/Unit/Controller/Adminhtml/Feed/IndexTest.php +++ b/app/code/Magento/Rss/Test/Unit/Controller/Adminhtml/Feed/IndexTest.php @@ -6,6 +6,7 @@ namespace Magento\Rss\Test\Unit\Controller\Adminhtml\Feed; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Zend\Feed\Writer\Exception\InvalidArgumentException; /** * Class IndexTest @@ -103,14 +104,22 @@ public function testExecuteWithException() $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); $dataProvider->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); - $rssModel = $this->createPartialMock(\Magento\Rss\Model\Rss::class, ['setDataProvider']); + $rssModel = $this->createPartialMock(\Magento\Rss\Model\Rss::class, ['setDataProvider', 'createRssXml']); $rssModel->expects($this->once())->method('setDataProvider')->will($this->returnSelf()); + $exceptionMock = new \Magento\Framework\Exception\RuntimeException( + new \Magento\Framework\Phrase('Any message') + ); + + $rssModel->expects($this->once())->method('createRssXml')->will( + $this->throwException($exceptionMock) + ); + $this->response->expects($this->once())->method('setHeader')->will($this->returnSelf()); $this->rssFactory->expects($this->once())->method('create')->will($this->returnValue($rssModel)); $this->rssManager->expects($this->once())->method('getProvider')->will($this->returnValue($dataProvider)); - $this->expectException('\Zend_Feed_Builder_Exception'); + $this->expectException(\Magento\Framework\Exception\RuntimeException::class); $this->controller->execute(); } } diff --git a/app/code/Magento/Rss/Test/Unit/Controller/Feed/IndexTest.php b/app/code/Magento/Rss/Test/Unit/Controller/Feed/IndexTest.php index 71802deee0a8d..30415155d5f6e 100644 --- a/app/code/Magento/Rss/Test/Unit/Controller/Feed/IndexTest.php +++ b/app/code/Magento/Rss/Test/Unit/Controller/Feed/IndexTest.php @@ -6,6 +6,7 @@ namespace Magento\Rss\Test\Unit\Controller\Feed; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Zend\Feed\Writer\Exception\InvalidArgumentException; /** * Class IndexTest @@ -52,6 +53,7 @@ protected function setUp() ->disableOriginalConstructor()->getMock(); $objectManagerHelper = new ObjectManagerHelper($this); + $this->controller = $objectManagerHelper->getObject( \Magento\Rss\Controller\Feed\Index::class, [ @@ -90,14 +92,22 @@ public function testExecuteWithException() $dataProvider = $this->createMock(\Magento\Framework\App\Rss\DataProviderInterface::class); $dataProvider->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); - $rssModel = $this->createPartialMock(\Magento\Rss\Model\Rss::class, ['setDataProvider']); + $rssModel = $this->createPartialMock(\Magento\Rss\Model\Rss::class, ['setDataProvider', 'createRssXml']); $rssModel->expects($this->once())->method('setDataProvider')->will($this->returnSelf()); + $exceptionMock = new \Magento\Framework\Exception\RuntimeException( + new \Magento\Framework\Phrase('Any message') + ); + + $rssModel->expects($this->once())->method('createRssXml')->will( + $this->throwException($exceptionMock) + ); + $this->response->expects($this->once())->method('setHeader')->will($this->returnSelf()); $this->rssFactory->expects($this->once())->method('create')->will($this->returnValue($rssModel)); $this->rssManager->expects($this->once())->method('getProvider')->will($this->returnValue($dataProvider)); - $this->expectException('\Zend_Feed_Builder_Exception'); + $this->expectException(\Magento\Framework\Exception\RuntimeException::class); $this->controller->execute(); } } diff --git a/app/code/Magento/Rss/Test/Unit/Model/RssManagerTest.php b/app/code/Magento/Rss/Test/Unit/Model/RssManagerTest.php index 6583e772589c7..d44ccf487d0db 100644 --- a/app/code/Magento/Rss/Test/Unit/Model/RssManagerTest.php +++ b/app/code/Magento/Rss/Test/Unit/Model/RssManagerTest.php @@ -45,8 +45,8 @@ public function testGetProvider() $this->objectManager->expects($this->once())->method('get')->will($this->returnValue($dataProvider)); $this->assertInstanceOf( - \Magento\Framework\App\Rss\DataProviderInterface::class, - $this->rssManager->getProvider('rss_feed') + \Magento\Framework\App\Rss\DataProviderInterface::class, + $this->rssManager->getProvider('rss_feed') ); } diff --git a/app/code/Magento/Rss/Test/Unit/Model/RssTest.php b/app/code/Magento/Rss/Test/Unit/Model/RssTest.php index 6f98b9f202e30..f2888e4296b40 100644 --- a/app/code/Magento/Rss/Test/Unit/Model/RssTest.php +++ b/app/code/Magento/Rss/Test/Unit/Model/RssTest.php @@ -19,7 +19,7 @@ class RssTest extends \PHPUnit\Framework\TestCase /** * @var array */ - protected $feedData = [ + private $feedData = [ 'title' => 'Feed Title', 'link' => 'http://magento.com/rss/link', 'description' => 'Feed Description', @@ -33,6 +33,27 @@ class RssTest extends \PHPUnit\Framework\TestCase ], ]; + /** + * @var string + */ + private $feedXml = '<?xml version="1.0" encoding="UTF-8"?> +<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0"> + <channel> + <title><![CDATA[Feed Title]]> + http://magento.com/rss/link + + Sat, 22 Apr 2017 13:21:12 +0200 + Zend\Feed + http://blogs.law.harvard.edu/tech/rss + + <![CDATA[Feed 1 Title]]> + http://magento.com/rss/link/id/1 + + Sat, 22 Apr 2017 13:21:12 +0200 + + +'; + /** * @var ObjectManagerHelper */ @@ -43,6 +64,16 @@ class RssTest extends \PHPUnit\Framework\TestCase */ private $cacheMock; + /** + * @var \Magento\Framework\App\FeedFactoryInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $feedFactoryMock; + + /** + * @var \Magento\Framework\App\FeedInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $feedMock; + /** * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ @@ -52,11 +83,15 @@ protected function setUp() { $this->cacheMock = $this->createMock(\Magento\Framework\App\CacheInterface::class); $this->serializerMock = $this->createMock(SerializerInterface::class); + $this->feedFactoryMock = $this->createMock(\Magento\Framework\App\FeedFactoryInterface::class); + $this->feedMock = $this->createMock(\Magento\Framework\App\FeedInterface::class); + $this->objectManagerHelper = new ObjectManagerHelper($this); $this->rss = $this->objectManagerHelper->getObject( \Magento\Rss\Model\Rss::class, [ 'cache' => $this->cacheMock, + 'feedFactory' => $this->feedFactoryMock, 'serializer' => $this->serializerMock ] ); @@ -116,14 +151,16 @@ public function testCreateRssXml() $dataProvider->expects($this->any())->method('getCacheLifetime')->will($this->returnValue(100)); $dataProvider->expects($this->any())->method('getRssData')->will($this->returnValue($this->feedData)); + $this->feedMock->expects($this->once()) + ->method('getFormattedContent') + ->willReturn($this->feedXml); + + $this->feedFactoryMock->expects($this->once()) + ->method('create') + ->with($this->feedData, \Magento\Framework\App\FeedFactoryInterface::FORMAT_RSS) + ->will($this->returnValue($this->feedMock)); + $this->rss->setDataProvider($dataProvider); - $result = $this->rss->createRssXml(); - $this->assertContains('', $result); - $this->assertContains('<![CDATA[Feed Title]]>', $result); - $this->assertContains('<![CDATA[Feed 1 Title]]>', $result); - $this->assertContains('http://magento.com/rss/link', $result); - $this->assertContains('http://magento.com/rss/link/id/1', $result); - $this->assertContains('', $result); - $this->assertContains('', $result); + $this->assertNotNull($this->rss->createRssXml()); } } diff --git a/app/code/Magento/Rss/Test/Unit/Model/UrlBuilderTest.php b/app/code/Magento/Rss/Test/Unit/Model/UrlBuilderTest.php index df3ff3649d1ab..e5561e309184c 100644 --- a/app/code/Magento/Rss/Test/Unit/Model/UrlBuilderTest.php +++ b/app/code/Magento/Rss/Test/Unit/Model/UrlBuilderTest.php @@ -64,6 +64,7 @@ public function testGetUrl() ->will($this->returnValue('http://magento.com/rss/feed/index/type/rss_feed')); $this->assertEquals( 'http://magento.com/rss/feed/index/type/rss_feed', - $this->urlBuilder->getUrl(['type' => 'rss_feed'])); + $this->urlBuilder->getUrl(['type' => 'rss_feed']) + ); } } diff --git a/app/etc/di.xml b/app/etc/di.xml index 5e7d4f67b8b23..4309d84773e03 100755 --- a/app/etc/di.xml +++ b/app/etc/di.xml @@ -248,6 +248,13 @@ + + + + Magento\Framework\App\Feed + + + Cm\RedisSession\Handler\ConfigInterface diff --git a/composer.json b/composer.json index 8aaebef9a6bde..83d7e14e7d271 100644 --- a/composer.json +++ b/composer.json @@ -22,6 +22,7 @@ "zendframework/zend-text": "^2.6.0", "zendframework/zend-i18n": "^2.7.3", "zendframework/zend-eventmanager": "^2.6.3", + "zendframework/zend-feed": "^2.9.0", "zendframework/zend-view": "^2.8.1", "zendframework/zend-servicemanager": "^2.7.8", "zendframework/zend-json": "^2.6.1", diff --git a/lib/internal/Magento/Framework/App/Feed.php b/lib/internal/Magento/Framework/App/Feed.php new file mode 100644 index 0000000000000..1154749a75b94 --- /dev/null +++ b/lib/internal/Magento/Framework/App/Feed.php @@ -0,0 +1,38 @@ +feeds = $data; + } + + /** + * {@inheritdoc} + */ + public function getFormattedContent() : string + { + return FeedFactory::factory($this->feeds)->export(FeedFactoryInterface::FORMAT_RSS); + } +} diff --git a/lib/internal/Magento/Framework/App/FeedFactory.php b/lib/internal/Magento/Framework/App/FeedFactory.php new file mode 100644 index 0000000000000..c80ece29f6143 --- /dev/null +++ b/lib/internal/Magento/Framework/App/FeedFactory.php @@ -0,0 +1,78 @@ +objectManager = $objectManger; + $this->logger = $logger; + $this->formats = $formats; + } + + /** + * {@inheritdoc} + */ + public function create(array $data, string $format = FeedFactoryInterface::FORMAT_RSS) : FeedInterface + { + if (!isset($this->formats[$format])) { + throw new \Magento\Framework\Exception\InputException( + new \Magento\Framework\Phrase('The format is not supported') + ); + } + + if (!is_subclass_of($this->formats[$format], \Magento\Framework\App\FeedInterface::class)) { + throw new \Magento\Framework\Exception\InputException( + new \Magento\Framework\Phrase('Wrong format handler type') + ); + } + + try { + return $this->objectManager->create( + $this->formats[$format], + ['data' => $data] + ); + } catch (\Exception $e) { + $this->logger->error($e->getMessage()); + throw new \Magento\Framework\Exception\RuntimeException( + new \Magento\Framework\Phrase('There has been an error with import'), + $e + ); + } + } +} diff --git a/lib/internal/Magento/Framework/App/FeedFactoryInterface.php b/lib/internal/Magento/Framework/App/FeedFactoryInterface.php new file mode 100644 index 0000000000000..ac53a366bd127 --- /dev/null +++ b/lib/internal/Magento/Framework/App/FeedFactoryInterface.php @@ -0,0 +1,30 @@ + Date: Fri, 31 May 2019 09:23:16 +0200 Subject: [PATCH 2030/2092] MC-17036: Fixes Integration Tests for PHP 7.2 --- lib/internal/Magento/Framework/Data/Form/Element/Collection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/internal/Magento/Framework/Data/Form/Element/Collection.php b/lib/internal/Magento/Framework/Data/Form/Element/Collection.php index 7a544501861bd..ced1f4208223d 100644 --- a/lib/internal/Magento/Framework/Data/Form/Element/Collection.php +++ b/lib/internal/Magento/Framework/Data/Form/Element/Collection.php @@ -13,7 +13,7 @@ * * @author Magento Core Team */ -class Collection implements \ArrayAccess, \IteratorAggregate +class Collection implements \ArrayAccess, \IteratorAggregate, \Countable { /** * Elements storage From ba39728dc3f970973f3d764b9b2352dcb5c6f366 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Fri, 31 May 2019 09:27:35 +0200 Subject: [PATCH 2031/2092] MC-17036: Fixes Integration Tests for PHP 7.2 --- lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php b/lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php index fa468a6df2909..f2e3e8163d375 100644 --- a/lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php +++ b/lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php @@ -2012,7 +2012,7 @@ public function insertArray($table, array $columns, array $data, $strategy = 0) $bind = []; $columnsCount = count($columns); foreach ($data as $row) { - if ($columnsCount != count($row)) { + if (is_array($row) && $columnsCount != count($row)) { throw new \Zend_Db_Exception('Invalid data for insert'); } $values[] = $this->_prepareInsertData($row, $bind); From 84e28af038bf1b38827231e0172f49571698c4c6 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Fri, 31 May 2019 11:36:23 +0200 Subject: [PATCH 2032/2092] MC-17036: Fixes Integration Tests for PHP 7.2 --- app/code/Magento/Ui/DataProvider/AbstractDataProvider.php | 2 +- lib/internal/Magento/Framework/DB/Tree/NodeSet.php | 2 +- lib/internal/Magento/Framework/Data/Tree/Node/Collection.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Ui/DataProvider/AbstractDataProvider.php b/app/code/Magento/Ui/DataProvider/AbstractDataProvider.php index efe4a1b8f0859..578ebe4d441d9 100644 --- a/app/code/Magento/Ui/DataProvider/AbstractDataProvider.php +++ b/app/code/Magento/Ui/DataProvider/AbstractDataProvider.php @@ -12,7 +12,7 @@ * @api * @since 100.0.2 */ -abstract class AbstractDataProvider implements DataProviderInterface +abstract class AbstractDataProvider implements DataProviderInterface, \Countable { /** * Data Provider name diff --git a/lib/internal/Magento/Framework/DB/Tree/NodeSet.php b/lib/internal/Magento/Framework/DB/Tree/NodeSet.php index 525651577f289..1c9eb1db9dbfc 100644 --- a/lib/internal/Magento/Framework/DB/Tree/NodeSet.php +++ b/lib/internal/Magento/Framework/DB/Tree/NodeSet.php @@ -9,7 +9,7 @@ * TODO implements iterators * */ -class NodeSet implements \Iterator +class NodeSet implements \Iterator, \Countable { /** * @var Node[] diff --git a/lib/internal/Magento/Framework/Data/Tree/Node/Collection.php b/lib/internal/Magento/Framework/Data/Tree/Node/Collection.php index 832fd18b48606..94990c0340a83 100644 --- a/lib/internal/Magento/Framework/Data/Tree/Node/Collection.php +++ b/lib/internal/Magento/Framework/Data/Tree/Node/Collection.php @@ -17,7 +17,7 @@ /** * @api */ -class Collection implements \ArrayAccess, \IteratorAggregate +class Collection implements \ArrayAccess, \IteratorAggregate, \Countable { /** * @var array From e5e57edd6960a775b2d428c9e01ce339f76841f0 Mon Sep 17 00:00:00 2001 From: Harald Deiser Date: Mon, 3 Jun 2019 17:59:18 +0200 Subject: [PATCH 2033/2092] MC-16722: Added further composer dependencies --- app/design/adminhtml/Magento/backend/composer.json | 2 +- app/design/frontend/Magento/blank/composer.json | 2 +- app/design/frontend/Magento/luma/composer.json | 2 +- lib/internal/Magento/Framework/composer.json | 1 - 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/app/design/adminhtml/Magento/backend/composer.json b/app/design/adminhtml/Magento/backend/composer.json index fb11aa2dc159f..752f8a588e438 100644 --- a/app/design/adminhtml/Magento/backend/composer.json +++ b/app/design/adminhtml/Magento/backend/composer.json @@ -2,7 +2,7 @@ "name": "magento/theme-adminhtml-backend", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*" }, "type": "magento2-theme", diff --git a/app/design/frontend/Magento/blank/composer.json b/app/design/frontend/Magento/blank/composer.json index f691cc8e9eb5f..0660b46cfa11f 100644 --- a/app/design/frontend/Magento/blank/composer.json +++ b/app/design/frontend/Magento/blank/composer.json @@ -2,7 +2,7 @@ "name": "magento/theme-frontend-blank", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "101.0.*" }, "type": "magento2-theme", diff --git a/app/design/frontend/Magento/luma/composer.json b/app/design/frontend/Magento/luma/composer.json index f5ba64ad9ed57..e5a5ab147fb99 100644 --- a/app/design/frontend/Magento/luma/composer.json +++ b/app/design/frontend/Magento/luma/composer.json @@ -2,7 +2,7 @@ "name": "magento/theme-frontend-luma", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/theme-frontend-blank": "100.2.*", "magento/framework": "101.0.*" }, diff --git a/lib/internal/Magento/Framework/composer.json b/lib/internal/Magento/Framework/composer.json index 86933cf59c3a2..6e1da52eb1629 100644 --- a/lib/internal/Magento/Framework/composer.json +++ b/lib/internal/Magento/Framework/composer.json @@ -12,7 +12,6 @@ "ext-spl": "*", "ext-dom": "*", "ext-simplexml": "*", - "ext-mcrypt": "*", "ext-hash": "*", "ext-curl": "*", "ext-iconv": "*", From dfc3ad29dc6d661096da55ee44724853b0aee38f Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Fri, 31 May 2019 13:13:48 +0200 Subject: [PATCH 2034/2092] MC-17033: Fixes Integration Tests for PHP 7.2 Magento/Framework/Session --- .../Magento/Framework/Session/ConfigTest.php | 597 ++++++++++-------- .../Framework/Session/SessionManagerTest.php | 225 +++++-- .../Framework/Session/SidResolverTest.php | 6 +- .../Magento/Framework/Session/SaveHandler.php | 8 +- .../Magento/Framework/Session/SidResolver.php | 10 +- 5 files changed, 512 insertions(+), 334 deletions(-) diff --git a/dev/tests/integration/testsuite/Magento/Framework/Session/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Framework/Session/ConfigTest.php index 573531cff960a..3e90aa67f464a 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Session/ConfigTest.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Session/ConfigTest.php @@ -3,314 +3,377 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -namespace Magento\Framework\Session; - -use Magento\Framework\App\Filesystem\DirectoryList; - -/** - * @magentoAppIsolation enabled - */ -class ConfigTest extends \PHPUnit\Framework\TestCase -{ - /** @var \Magento\Framework\Session\Config */ - protected $_model; - - /** @var string */ - protected $_cacheLimiter = 'private_no_expire'; +// @codingStandardsIgnoreStart +namespace { + $mockPHPFunctions = false; +} - /** @var \Magento\TestFramework\ObjectManager */ - protected $_objectManager; +namespace Magento\Framework\Session { - /** @var string Default value for session.save_path setting */ - protected $defaultSavePath; + use Magento\Framework\App\Filesystem\DirectoryList; - /** @var \Magento\Framework\App\DeploymentConfig | \PHPUnit_Framework_MockObject_MockObject */ - protected $deploymentConfigMock; + // @codingStandardsIgnoreEnd - protected function setUp() + /** + * Mock ini_get global function + * + * @return string + */ + function ini_get($varName) { - $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); - /** @var $sessionManager \Magento\Framework\Session\SessionManager */ - $sessionManager = $this->_objectManager->create(\Magento\Framework\Session\SessionManager::class); - if ($sessionManager->isSessionExists()) { - $sessionManager->writeClose(); + global $mockPHPFunctions; + if ($mockPHPFunctions == 1) { + switch ($varName) { + case 'session.save_path': + return 'preset_save_path'; + case 'session.save_handler': + return 'php'; + default: + return ''; + } + } elseif ($mockPHPFunctions == 2) { + return null; } - $this->deploymentConfigMock = $this->createMock(\Magento\Framework\App\DeploymentConfig::class); - $this->deploymentConfigMock - ->method('get') - ->willReturnCallback(function ($configPath) { - switch ($configPath) { - case Config::PARAM_SESSION_SAVE_METHOD: - return 'files'; - case Config::PARAM_SESSION_CACHE_LIMITER: - return $this->_cacheLimiter; - default: - return null; - } - }); - - $this->_model = $this->_objectManager->create( - \Magento\Framework\Session\Config::class, - ['deploymentConfig' => $this->deploymentConfigMock] - ); - $this->defaultSavePath = $this->_objectManager - ->get(\Magento\Framework\Filesystem\DirectoryList::class) - ->getPath(DirectoryList::SESSION); + return call_user_func_array('\ini_get', func_get_args()); } /** * @magentoAppIsolation enabled */ - public function testDefaultConfiguration() + class ConfigTest extends \PHPUnit\Framework\TestCase { - /** @var \Magento\Framework\Filesystem $filesystem */ - $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( - \Magento\Framework\Filesystem::class - ); - $path = ini_get('session.save_path') ?: - $filesystem->getDirectoryRead(DirectoryList::SESSION)->getAbsolutePath(); - - $this->assertEquals( - $path, - $this->_model->getSavePath() - ); - $this->assertEquals( - \Magento\Framework\Session\Config::COOKIE_LIFETIME_DEFAULT, - $this->_model->getCookieLifetime() - ); - $this->assertEquals($this->_cacheLimiter, $this->_model->getCacheLimiter()); - $this->assertEquals('/', $this->_model->getCookiePath()); - $this->assertEquals('localhost', $this->_model->getCookieDomain()); - $this->assertEquals(false, $this->_model->getCookieSecure()); - $this->assertEquals(true, $this->_model->getCookieHttpOnly()); - $this->assertEquals($this->_model->getSavePath(), $this->_model->getOption('save_path')); - } + /** @var string */ + private $_cacheLimiter = 'private_no_expire'; + + /** @var \Magento\TestFramework\ObjectManager */ + private $_objectManager; + + /** @var string Default value for session.save_path setting */ + private $defaultSavePath; + + /** @var \Magento\Framework\App\DeploymentConfig | \PHPUnit_Framework_MockObject_MockObject */ + private $deploymentConfigMock; + + protected function setUp() + { + $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + + $this->deploymentConfigMock = $this->createMock(\Magento\Framework\App\DeploymentConfig::class); + $this->deploymentConfigMock + ->method('get') + ->willReturnCallback(function ($configPath) { + switch ($configPath) { + case Config::PARAM_SESSION_SAVE_METHOD: + return 'files'; + case Config::PARAM_SESSION_CACHE_LIMITER: + return $this->_cacheLimiter; + default: + return null; + } + }); + + $this->defaultSavePath = $this->_objectManager + ->get(\Magento\Framework\Filesystem\DirectoryList::class) + ->getPath(DirectoryList::SESSION); + } - public function testSetOptionsInvalidValue() - { - $preValue = $this->_model->getOptions(); - $this->_model->setOptions(''); - $this->assertEquals($preValue, $this->_model->getOptions()); - } + /** + * @magentoAppIsolation enabled + */ + public function testDefaultConfiguration() + { + $model = $this->getModel(); + /** @var \Magento\Framework\Filesystem $filesystem */ + $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( + \Magento\Framework\Filesystem::class + ); + $path = ini_get('session.save_path') ?: + $filesystem->getDirectoryRead(DirectoryList::SESSION)->getAbsolutePath(); + + $this->assertEquals( + $path, + $model->getSavePath() + ); + $this->assertEquals( + \Magento\Framework\Session\Config::COOKIE_LIFETIME_DEFAULT, + $model->getCookieLifetime() + ); + $this->assertEquals($this->_cacheLimiter, $model->getCacheLimiter()); + $this->assertEquals('/', $model->getCookiePath()); + $this->assertEquals('localhost', $model->getCookieDomain()); + $this->assertEquals(false, $model->getCookieSecure()); + $this->assertEquals(true, $model->getCookieHttpOnly()); + $this->assertEquals($model->getSavePath(), $model->getOption('save_path')); + } - /** - * @dataProvider optionsProvider - */ - public function testSetOptions($option, $getter, $value) - { - $options = [$option => $value]; - $this->_model->setOptions($options); - $this->assertSame($value, $this->_model->{$getter}()); - } + public function testSetOptionsInvalidValue() + { + $model = $this->getModel(); + $preValue = $model->getOptions(); + $model->setOptions(''); + $this->assertEquals($preValue, $model->getOptions()); + } - public function optionsProvider() - { - return [ - ['save_path', 'getSavePath', __DIR__], - ['name', 'getName', 'FOOBAR'], - ['gc_probability', 'getGcProbability', 42], - ['gc_divisor', 'getGcDivisor', 3], - ['gc_maxlifetime', 'getGcMaxlifetime', 180], - ['serialize_handler', 'getSerializeHandler', 'php_binary'], - ['cookie_lifetime', 'getCookieLifetime', 180], - ['cookie_path', 'getCookiePath', '/foo/bar'], - ['cookie_domain', 'getCookieDomain', 'framework.zend.com'], - ['cookie_secure', 'getCookieSecure', true], - ['cookie_httponly', 'getCookieHttpOnly', true], - ['use_cookies', 'getUseCookies', false], - ['use_only_cookies', 'getUseOnlyCookies', true], - ['referer_check', 'getRefererCheck', 'foobar'], - ['entropy_file', 'getEntropyFile', __FILE__], - ['entropy_length', 'getEntropyLength', 42], - ['cache_limiter', 'getCacheLimiter', 'private'], - ['cache_expire', 'getCacheExpire', 42], - ['use_trans_sid', 'getUseTransSid', true], - ['hash_function', 'getHashFunction', 'md5'], - ['hash_bits_per_character', 'getHashBitsPerCharacter', 5], - ['url_rewriter_tags', 'getUrlRewriterTags', 'a=href'] - ]; - } + /** + * @dataProvider optionsProvider + */ + public function testSetOptions($option, $getter, $value) + { + $model = $this->getModel(); + $options = [$option => $value]; + $model->setOptions($options); + $this->assertSame($value, $model->{$getter}()); + } - public function testNameIsMutable() - { - $this->_model->setName('FOOBAR'); - $this->assertEquals('FOOBAR', $this->_model->getName()); - } + public function optionsProvider() + { + return [ + ['save_path', 'getSavePath', __DIR__], + ['name', 'getName', 'FOOBAR'], + ['gc_probability', 'getGcProbability', 42], + ['gc_divisor', 'getGcDivisor', 3], + ['gc_maxlifetime', 'getGcMaxlifetime', 180], + ['serialize_handler', 'getSerializeHandler', 'php_binary'], + ['cookie_lifetime', 'getCookieLifetime', 180], + ['cookie_path', 'getCookiePath', '/foo/bar'], + ['cookie_domain', 'getCookieDomain', 'framework.zend.com'], + ['cookie_secure', 'getCookieSecure', true], + ['cookie_httponly', 'getCookieHttpOnly', true], + ['use_cookies', 'getUseCookies', false], + ['use_only_cookies', 'getUseOnlyCookies', true], + ['referer_check', 'getRefererCheck', 'foobar'], + ['entropy_file', 'getEntropyFile', __FILE__], + ['entropy_length', 'getEntropyLength', 42], + ['cache_limiter', 'getCacheLimiter', 'private'], + ['cache_expire', 'getCacheExpire', 42], + ['use_trans_sid', 'getUseTransSid', true], + ['hash_function', 'getHashFunction', 'md5'], + ['hash_bits_per_character', 'getHashBitsPerCharacter', 5], + ['url_rewriter_tags', 'getUrlRewriterTags', 'a=href'] + ]; + } - public function testCookieLifetimeIsMutable() - { - $this->_model->setCookieLifetime(20); - $this->assertEquals(20, $this->_model->getCookieLifetime()); - } + public function testNameIsMutable() + { + $model = $this->getModel(); + $model->setName('FOOBAR'); + $this->assertEquals('FOOBAR', $model->getName()); + } - public function testCookieLifetimeCanBeZero() - { - $this->_model->setCookieLifetime(0); - $this->assertEquals(0, $this->_model->getCookieLifetime()); - } + public function testCookieLifetimeIsMutable() + { + $model = $this->getModel(); + $model->setCookieLifetime(20); + $this->assertEquals(20, $model->getCookieLifetime()); + } - public function testSettingInvalidCookieLifetime() - { - $preVal = $this->_model->getCookieLifetime(); - $this->_model->setCookieLifetime('foobar_bogus'); - $this->assertEquals($preVal, $this->_model->getCookieLifetime()); - } + public function testCookieLifetimeCanBeZero() + { + $model = $this->getModel(); + $model->setCookieLifetime(0); + $this->assertEquals(0, $model->getCookieLifetime()); + } - public function testSettingInvalidCookieLifetime2() - { - $preVal = $this->_model->getCookieLifetime(); - $this->_model->setCookieLifetime(-1); - $this->assertEquals($preVal, $this->_model->getCookieLifetime()); - } + public function testSettingInvalidCookieLifetime() + { + $model = $this->getModel(); + $preVal = $model->getCookieLifetime(); + $model->setCookieLifetime('foobar_bogus'); + $this->assertEquals($preVal, $model->getCookieLifetime()); + } - public function testWrongMethodCall() - { - $this->expectException( - '\BadMethodCallException', - 'Method "methodThatNotExist" does not exist in Magento\Framework\Session\Config' - ); - $this->_model->methodThatNotExist(); - } + public function testSettingInvalidCookieLifetime2() + { + $model = $this->getModel(); + $preVal = $model->getCookieLifetime(); + $model->setCookieLifetime(-1); + $this->assertEquals($preVal, $model->getCookieLifetime()); + } - public function testCookieSecureDefaultsToIniSettings() - { - $this->assertSame((bool)ini_get('session.cookie_secure'), $this->_model->getCookieSecure()); - } + public function testWrongMethodCall() + { + $model = $this->getModel(); + $this->expectException( + '\BadMethodCallException', + 'Method "methodThatNotExist" does not exist in Magento\Framework\Session\Config' + ); + $model->methodThatNotExist(); + } - public function testSetCookieSecureInOptions() - { - $this->_model->setCookieSecure(true); - $this->assertTrue($this->_model->getCookieSecure()); - } + public function testCookieSecureDefaultsToIniSettings() + { + $model = $this->getModel(); + $this->assertSame((bool)ini_get('session.cookie_secure'), $model->getCookieSecure()); + } - public function testCookieDomainIsMutable() - { - $this->_model->setCookieDomain('example.com'); - $this->assertEquals('example.com', $this->_model->getCookieDomain()); - } + public function testSetCookieSecureInOptions() + { + $model = $this->getModel(); + $model->setCookieSecure(true); + $this->assertTrue($model->getCookieSecure()); + } - public function testCookieDomainCanBeEmpty() - { - $this->_model->setCookieDomain(''); - $this->assertEquals('', $this->_model->getCookieDomain()); - } + public function testCookieDomainIsMutable() + { + $model = $this->getModel(); + $model->setCookieDomain('example.com'); + $this->assertEquals('example.com', $model->getCookieDomain()); + } - public function testSettingInvalidCookieDomain() - { - $preVal = $this->_model->getCookieDomain(); - $this->_model->setCookieDomain(24); - $this->assertEquals($preVal, $this->_model->getCookieDomain()); - } + public function testCookieDomainCanBeEmpty() + { + $model = $this->getModel(); + $model->setCookieDomain(''); + $this->assertEquals('', $model->getCookieDomain()); + } - public function testSettingInvalidCookieDomain2() - { - $preVal = $this->_model->getCookieDomain(); - $this->_model->setCookieDomain('D:\\WINDOWS\\System32\\drivers\\etc\\hosts'); - $this->assertEquals($preVal, $this->_model->getCookieDomain()); - } + public function testSettingInvalidCookieDomain() + { + $model = $this->getModel(); + $preVal = $model->getCookieDomain(); + $model->setCookieDomain(24); + $this->assertEquals($preVal, $model->getCookieDomain()); + } - public function testSetCookieHttpOnlyInOptions() - { - $this->_model->setCookieHttpOnly(true); - $this->assertTrue($this->_model->getCookieHttpOnly()); - } + public function testSettingInvalidCookieDomain2() + { + $model = $this->getModel(); + $preVal = $model->getCookieDomain(); + $model->setCookieDomain('D:\\WINDOWS\\System32\\drivers\\etc\\hosts'); + $this->assertEquals($preVal, $model->getCookieDomain()); + } - public function testUseCookiesDefaultsToIniSettings() - { - $this->assertSame((bool)ini_get('session.use_cookies'), $this->_model->getUseCookies()); - } + public function testSetCookieHttpOnlyInOptions() + { + $model = $this->getModel(); + $model->setCookieHttpOnly(true); + $this->assertTrue($model->getCookieHttpOnly()); + } - public function testSetUseCookiesInOptions() - { - $this->_model->setUseCookies(true); - $this->assertTrue($this->_model->getUseCookies()); - } + public function testUseCookiesDefaultsToIniSettings() + { + $model = $this->getModel(); + $this->assertSame((bool)ini_get('session.use_cookies'), $model->getUseCookies()); + } - public function testUseOnlyCookiesDefaultsToIniSettings() - { - $this->assertSame((bool)ini_get('session.use_only_cookies'), $this->_model->getUseOnlyCookies()); - } + public function testSetUseCookiesInOptions() + { + $model = $this->getModel(); + $model->setUseCookies(true); + $this->assertTrue($model->getUseCookies()); + } - public function testSetUseOnlyCookiesInOptions() - { - $this->_model->setOption('use_only_cookies', true); - $this->assertTrue((bool)$this->_model->getOption('use_only_cookies')); - } + public function testUseOnlyCookiesDefaultsToIniSettings() + { + $model = $this->getModel(); + $this->assertSame((bool)ini_get('session.use_only_cookies'), $model->getUseOnlyCookies()); + } - public function testRefererCheckDefaultsToIniSettings() - { - $this->assertSame(ini_get('session.referer_check'), $this->_model->getRefererCheck()); - } + public function testSetUseOnlyCookiesInOptions() + { + $model = $this->getModel(); + $model->setOption('use_only_cookies', true); + $this->assertTrue((bool)$model->getOption('use_only_cookies')); + } - public function testRefererCheckIsMutable() - { - $this->_model->setOption('referer_check', 'FOOBAR'); - $this->assertEquals('FOOBAR', $this->_model->getOption('referer_check')); - } + public function testRefererCheckDefaultsToIniSettings() + { + $model = $this->getModel(); + $this->assertSame(ini_get('session.referer_check'), $model->getRefererCheck()); + } - public function testRefererCheckMayBeEmpty() - { - $this->_model->setOption('referer_check', ''); - $this->assertEquals('', $this->_model->getOption('referer_check')); - } + public function testRefererCheckIsMutable() + { + $model = $this->getModel(); + $model->setOption('referer_check', 'FOOBAR'); + $this->assertEquals('FOOBAR', $model->getOption('referer_check')); + } - public function testSetSavePath() - { - $this->_model->setSavePath('some_save_path'); - $this->assertEquals($this->_model->getOption('save_path'), 'some_save_path'); - } + public function testRefererCheckMayBeEmpty() + { + $model = $this->getModel(); + $model->setOption('referer_check', ''); + $this->assertEquals('', $model->getOption('referer_check')); + } - /** - * @dataProvider savePathDataProvider - */ - public function testConstructorSavePath($existing, $given, $expected) - { - $sessionSavePath = ini_get('session.save_path'); - if ($expected === 'default') { - $expected = $this->defaultSavePath . '/'; + public function testSetSavePath() + { + $model = $this->getModel(); + $model->setSavePath('some_save_path'); + $this->assertEquals($model->getOption('save_path'), 'some_save_path'); } - $setup = ini_set('session.save_path', $existing); - if ($setup === false) { - $this->markTestSkipped('Cannot set session.save_path with ini_set'); + + /** + * @param $mockPHPFunctionNum + * @param $givenSavePath + * @param $expectedSavePath + * @param $givenSaveHandler + * @param $expectedSaveHandler + * @dataProvider constructorDataProvider + */ + public function testConstructor( + $mockPHPFunctionNum, + $givenSavePath, + $expectedSavePath, + $givenSaveHandler, + $expectedSaveHandler + ) { + global $mockPHPFunctions; + $mockPHPFunctions = $mockPHPFunctionNum; + + $sessionSaveHandler = ini_get('session.save_handler'); + if ($expectedSavePath === 'default') { + $expectedSavePath = $this->defaultSavePath . '/'; + } + if ($expectedSaveHandler === 'php') { + $expectedSaveHandler = $sessionSaveHandler; + } + + $deploymentConfigMock = $this->createMock(\Magento\Framework\App\DeploymentConfig::class); + $deploymentConfigMock + ->method('get') + ->willReturnCallback(function ($configPath) use ($givenSavePath, $givenSaveHandler) { + switch ($configPath) { + case Config::PARAM_SESSION_SAVE_METHOD: + return $givenSaveHandler; + case Config::PARAM_SESSION_CACHE_LIMITER: + return $this->_cacheLimiter; + case Config::PARAM_SESSION_SAVE_PATH: + return $givenSavePath; + default: + return null; + } + }); + + $model = $this->_objectManager->create( + \Magento\Framework\Session\Config::class, + ['deploymentConfig' => $deploymentConfigMock] + ); + $this->assertEquals($expectedSavePath, $model->getOption('save_path')); + $this->assertEquals($expectedSaveHandler, $model->getOption('session.save_handler')); + global $mockPHPFunctions; + $mockPHPFunctions = false; } - $deploymentConfigMock = $this->createMock(\Magento\Framework\App\DeploymentConfig::class); - $deploymentConfigMock - ->method('get') - ->willReturnCallback(function ($configPath) use ($given) { - switch ($configPath) { - case Config::PARAM_SESSION_SAVE_METHOD: - return 'files'; - case Config::PARAM_SESSION_CACHE_LIMITER: - return $this->_cacheLimiter; - case Config::PARAM_SESSION_SAVE_PATH: - return $given; - default: - return null; - } - }); - - $model = $this->_objectManager->create( - \Magento\Framework\Session\Config::class, - ['deploymentConfig' => $deploymentConfigMock] - ); - $this->assertEquals($expected, $model->getOption('save_path')); - - if ($sessionSavePath != ini_get('session.save_path')) { - ini_set('session.save_path', $sessionSavePath); + public function constructorDataProvider() + { + // preset value (null = not set), input value (null = not set), expected value + $savePathGiven = 'explicit_save_path'; + $presetPath = 'preset_save_path'; + return [ + [2, $savePathGiven, $savePathGiven, 'db', 'db'], + [2, null, 'default', 'redis', 'redis'], + [1, $savePathGiven, $savePathGiven, null, 'php'], + [1, null, $presetPath, 'files', 'files'], + ]; } - } - public function savePathDataProvider() - { - // preset value (null = not set), input value (null = not set), expected value - $savePathGiven = 'explicit_save_path'; - $presetPath = 'preset_save_path'; - return [ - [null, $savePathGiven, $savePathGiven], - [null, null, 'default'], - [$presetPath, $savePathGiven, $savePathGiven], - [$presetPath, null, $presetPath], - ]; + private function getModel(): \Magento\Framework\Session\Config + { + return $this->_objectManager->create( + \Magento\Framework\Session\Config::class, + ['deploymentConfig' => $this->deploymentConfigMock] + ); + } } } diff --git a/dev/tests/integration/testsuite/Magento/Framework/Session/SessionManagerTest.php b/dev/tests/integration/testsuite/Magento/Framework/Session/SessionManagerTest.php index 7bb9ed9da3b15..3205c19445ee1 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Session/SessionManagerTest.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Session/SessionManagerTest.php @@ -10,7 +10,9 @@ namespace Magento\Framework\Session { + use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\State; + // @codingStandardsIgnoreEnd /** @@ -36,30 +38,72 @@ function headers_sent() return call_user_func_array('\headers_sent', func_get_args()); } + /** + * Mock ini_set global function + * + * @param string $varName + * @param string $newValue + * @return bool|string + */ + function ini_set($varName, $newValue) + { + global $mockPHPFunctions; + if ($mockPHPFunctions) { + SessionManagerTest::$isIniSetInvoked[$varName] = $newValue; + return true; + } + return call_user_func_array('\ini_set', func_get_args()); + } + + /** + * Mock session_set_save_handler global function + * + * @return bool + */ + function session_set_save_handler() + { + global $mockPHPFunctions; + if ($mockPHPFunctions) { + SessionManagerTest::$isSessionSetSaveHandlerInvoked = true; + return true; + } + return call_user_func_array('\session_set_save_handler', func_get_args()); + } + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class SessionManagerTest extends \PHPUnit\Framework\TestCase { + /** + * @var string[] + */ + public static $isIniSetInvoked = []; + + /** + * @var bool + */ + public static $isSessionSetSaveHandlerInvoked; + /** * @var \Magento\Framework\Session\SessionManagerInterface */ - protected $_model; + private $model; /** * @var \Magento\Framework\Session\SidResolverInterface */ - protected $_sidResolver; + private $sidResolver; /** * @var string */ - protected $sessionName; + private $sessionName; /** - * @var \Magento\Framework\ObjectManagerInterface + * @var \Magento\TestFramework\ObjectManager */ - protected $objectManager; + private $objectManager; /** * @var \Magento\Framework\App\RequestInterface @@ -80,50 +124,46 @@ protected function setUp() $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + /** @var \Magento\Framework\Session\SidResolverInterface $sidResolver */ $this->appState = $this->getMockBuilder(State::class) ->setMethods(['getAreaCode']) ->disableOriginalConstructor() ->getMock(); /** @var \Magento\Framework\Session\SidResolver $sidResolver */ - $this->_sidResolver = $this->objectManager->create( + $this->sidResolver = $this->objectManager->create( \Magento\Framework\Session\SidResolver::class, [ - 'appState' => $this->appState + 'appState' => $this->appState, ] ); $this->request = $this->objectManager->get(\Magento\Framework\App\RequestInterface::class); - - /** @var \Magento\Framework\Session\SessionManager _model */ - $this->_model = $this->objectManager->create( - \Magento\Framework\Session\SessionManager::class, - [ - $this->objectManager->get(\Magento\Framework\App\Request\Http::class), - $this->_sidResolver, - $this->objectManager->get(\Magento\Framework\Session\Config\ConfigInterface::class), - $this->objectManager->get(\Magento\Framework\Session\SaveHandlerInterface::class), - $this->objectManager->get(\Magento\Framework\Session\ValidatorInterface::class), - $this->objectManager->get(\Magento\Framework\Session\StorageInterface::class) - ] - ); } protected function tearDown() { global $mockPHPFunctions; $mockPHPFunctions = false; + self::$isIniSetInvoked = []; + self::$isSessionSetSaveHandlerInvoked = false; + if ($this->model !== null) { + $this->model->destroy(); + $this->model = null; + } } public function testSessionNameFromIni() { - $this->_model->start(); - $this->assertSame($this->sessionName, $this->_model->getName()); - $this->_model->destroy(); + $this->initializeModel(); + $this->model->start(); + $this->assertSame($this->sessionName, $this->model->getName()); + $this->model->destroy(); } public function testSessionUseOnlyCookies() { + $this->initializeModel(); $expectedValue = '1'; $sessionUseOnlyCookies = ini_get('session.use_only_cookies'); $this->assertSame($expectedValue, $sessionUseOnlyCookies); @@ -131,49 +171,57 @@ public function testSessionUseOnlyCookies() public function testGetData() { - $this->_model->setData(['test_key' => 'test_value']); - $this->assertEquals('test_value', $this->_model->getData('test_key', true)); - $this->assertNull($this->_model->getData('test_key')); + $this->initializeModel(); + $this->model->setData(['test_key' => 'test_value']); + $this->assertEquals('test_value', $this->model->getData('test_key', true)); + $this->assertNull($this->model->getData('test_key')); } public function testGetSessionId() { - $this->assertEquals(session_id(), $this->_model->getSessionId()); + $this->initializeModel(); + $this->assertEquals(session_id(), $this->model->getSessionId()); } public function testGetName() { - $this->assertEquals(session_name(), $this->_model->getName()); + $this->initializeModel(); + $this->assertEquals(session_name(), $this->model->getName()); } public function testSetName() { - $this->_model->setName('test'); - $this->assertEquals('test', $this->_model->getName()); + $this->initializeModel(); + $this->model->destroy(); + $this->model->setName('test'); + $this->model->start(); + $this->assertEquals('test', $this->model->getName()); } public function testDestroy() { + $this->initializeModel(); $data = ['key' => 'value']; - $this->_model->setData($data); + $this->model->setData($data); - $this->assertEquals($data, $this->_model->getData()); - $this->_model->destroy(); + $this->assertEquals($data, $this->model->getData()); + $this->model->destroy(); - $this->assertEquals([], $this->_model->getData()); + $this->assertEquals([], $this->model->getData()); } public function testSetSessionId() { - $sessionId = $this->_model->getSessionId(); + $this->initializeModel(); + $sessionId = $this->model->getSessionId(); $this->appState->expects($this->atLeastOnce()) ->method('getAreaCode') ->willReturn(\Magento\Framework\App\Area::AREA_FRONTEND); - $this->_model->setSessionId($this->_sidResolver->getSid($this->_model)); - $this->assertEquals($sessionId, $this->_model->getSessionId()); + $this->model->setSessionId($this->sidResolver->getSid($this->model)); + $this->assertEquals($sessionId, $this->model->getSessionId()); - $this->_model->setSessionId('test'); - $this->assertEquals('test', $this->_model->getSessionId()); + $this->model->setSessionId('test'); + $this->assertEquals('test', $this->model->getSessionId()); } /** @@ -181,40 +229,43 @@ public function testSetSessionId() */ public function testSetSessionIdFromParam() { + $this->initializeModel(); $this->appState->expects($this->atLeastOnce()) ->method('getAreaCode') ->willReturn(\Magento\Framework\App\Area::AREA_FRONTEND); - $this->assertNotEquals('test_id', $this->_model->getSessionId()); - $this->request->getQuery()->set($this->_sidResolver->getSessionIdQueryParam($this->_model), 'test-id'); - $this->_model->setSessionId($this->_sidResolver->getSid($this->_model)); - $this->assertEquals('test-id', $this->_model->getSessionId()); + $this->assertNotEquals('test_id', $this->model->getSessionId()); + $this->request->getQuery()->set($this->sidResolver->getSessionIdQueryParam($this->model), 'test-id'); + $this->model->setSessionId($this->sidResolver->getSid($this->model)); + $this->assertEquals('test-id', $this->model->getSessionId()); /* Use not valid identifier */ - $this->request->getQuery()->set($this->_sidResolver->getSessionIdQueryParam($this->_model), 'test_id'); - $this->_model->setSessionId($this->_sidResolver->getSid($this->_model)); - $this->assertEquals('test-id', $this->_model->getSessionId()); + $this->request->getQuery()->set($this->sidResolver->getSessionIdQueryParam($this->model), 'test_id'); + $this->model->setSessionId($this->sidResolver->getSid($this->model)); + $this->assertEquals('test-id', $this->model->getSessionId()); } public function testGetSessionIdForHost() { + $this->initializeModel(); $_SERVER['HTTP_HOST'] = 'localhost'; - $this->_model->start(); - $this->assertEmpty($this->_model->getSessionIdForHost('localhost')); - $this->assertNotEmpty($this->_model->getSessionIdForHost('test')); - $this->_model->destroy(); + $this->model->start(); + $this->assertEmpty($this->model->getSessionIdForHost('localhost')); + $this->assertNotEmpty($this->model->getSessionIdForHost('test')); + $this->model->destroy(); } public function testIsValidForHost() { + $this->initializeModel(); $_SERVER['HTTP_HOST'] = 'localhost'; - $this->_model->start(); + $this->model->start(); - $reflection = new \ReflectionMethod($this->_model, '_addHost'); + $reflection = new \ReflectionMethod($this->model, '_addHost'); $reflection->setAccessible(true); - $reflection->invoke($this->_model); + $reflection->invoke($this->model); - $this->assertFalse($this->_model->isValidForHost('test.com')); - $this->assertTrue($this->_model->isValidForHost('localhost')); - $this->_model->destroy(); + $this->assertFalse($this->model->isValidForHost('test.com')); + $this->assertTrue($this->model->isValidForHost('localhost')); + $this->model->destroy(); } /** @@ -232,9 +283,9 @@ public function testStartAreaNotSet() * * @var \Magento\Framework\Session\SessionManager _model */ - $this->_model = new \Magento\Framework\Session\SessionManager( + $this->model = new \Magento\Framework\Session\SessionManager( $this->objectManager->get(\Magento\Framework\App\Request\Http::class), - $this->_sidResolver, + $this->sidResolver, $this->objectManager->get(\Magento\Framework\Session\Config\ConfigInterface::class), $this->objectManager->get(\Magento\Framework\Session\SaveHandlerInterface::class), $this->objectManager->get(\Magento\Framework\Session\ValidatorInterface::class), @@ -246,7 +297,63 @@ public function testStartAreaNotSet() global $mockPHPFunctions; $mockPHPFunctions = true; - $this->_model->start(); + $this->model->start(); + } + + public function testConstructor() + { + global $mockPHPFunctions; + $mockPHPFunctions = true; + + $deploymentConfigMock = $this->createMock(DeploymentConfig::class); + $deploymentConfigMock->method('get') + ->willReturnCallback(function ($configPath) { + switch ($configPath) { + case Config::PARAM_SESSION_SAVE_METHOD: + return 'db'; + case Config::PARAM_SESSION_CACHE_LIMITER: + return 'private_no_expire'; + case Config::PARAM_SESSION_SAVE_PATH: + return 'explicit_save_path'; + default: + return null; + } + }); + $sessionConfig = $this->objectManager->create(Config::class, ['deploymentConfig' => $deploymentConfigMock]); + $saveHandler = $this->objectManager->create(SaveHandler::class, ['sessionConfig' => $sessionConfig]); + + $this->model = $this->objectManager->create( + \Magento\Framework\Session\SessionManager::class, + [ + 'sidResolver' => $this->sidResolver, + 'saveHandler' => $saveHandler, + 'sessionConfig' => $sessionConfig, + ] + ); + $this->assertEquals('db', $sessionConfig->getOption('session.save_handler')); + $this->assertEquals('private_no_expire', $sessionConfig->getOption('session.cache_limiter')); + $this->assertEquals('explicit_save_path', $sessionConfig->getOption('session.save_path')); + $this->assertArrayHasKey('session.use_only_cookies', self::$isIniSetInvoked); + $this->assertEquals('1', self::$isIniSetInvoked['session.use_only_cookies']); + foreach ($sessionConfig->getOptions() as $option => $value) { + if ($option=='session.save_handler') { + $this->assertArrayNotHasKey('session.save_handler', self::$isIniSetInvoked); + } else { + $this->assertArrayHasKey($option, self::$isIniSetInvoked); + $this->assertEquals($value, self::$isIniSetInvoked[$option]); + } + } + $this->assertTrue(self::$isSessionSetSaveHandlerInvoked); + } + + private function initializeModel(): void + { + $this->model = $this->objectManager->create( + \Magento\Framework\Session\SessionManager::class, + [ + 'sidResolver' => $this->sidResolver + ] + ); } } } diff --git a/dev/tests/integration/testsuite/Magento/Framework/Session/SidResolverTest.php b/dev/tests/integration/testsuite/Magento/Framework/Session/SidResolverTest.php index 6e043728b073a..5e70eb491b50c 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Session/SidResolverTest.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Session/SidResolverTest.php @@ -114,7 +114,7 @@ public function testGetSid($sid, $useFrontedSid, $isOwnOriginUrl, $testSid) $this->scopeConfig->expects( $this->any() )->method( - 'getValue' + 'isSetFlag' )->with( \Magento\Framework\Session\SidResolver::XML_PATH_USE_FRONTEND_SID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE @@ -154,10 +154,12 @@ public function testGetSessionIdQueryParam() public function testGetSessionIdQueryParamCustom() { + $this->session->destroy(); $oldSessionName = $this->session->getName(); $this->session->setName($this->customSessionName); $this->assertEquals($this->customSessionQueryParam, $this->model->getSessionIdQueryParam($this->session)); $this->session->setName($oldSessionName); + $this->session->start(); } public function testSetGetUseSessionVar() @@ -193,7 +195,7 @@ public function testSetGetUseSessionInUrl($configValue) $this->scopeConfig->expects( $this->any() )->method( - 'getValue' + 'isSetFlag' )->with( \Magento\Framework\Session\SidResolver::XML_PATH_USE_FRONTEND_SID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE diff --git a/lib/internal/Magento/Framework/Session/SaveHandler.php b/lib/internal/Magento/Framework/Session/SaveHandler.php index 4ab3d8e28f169..0a5402957de5b 100644 --- a/lib/internal/Magento/Framework/Session/SaveHandler.php +++ b/lib/internal/Magento/Framework/Session/SaveHandler.php @@ -5,7 +5,6 @@ */ namespace Magento\Framework\Session; -use Magento\Framework\App\DeploymentConfig; use Magento\Framework\App\ObjectManager; use Magento\Framework\Exception\SessionException; use Magento\Framework\Session\Config\ConfigInterface; @@ -33,12 +32,12 @@ class SaveHandler implements SaveHandlerInterface * Constructor * * @param SaveHandlerFactory $saveHandlerFactory - * @param DeploymentConfig $deploymentConfig + * @param ConfigInterface $sessionConfig * @param string $default */ public function __construct( SaveHandlerFactory $saveHandlerFactory, - DeploymentConfig $deploymentConfig, + ConfigInterface $sessionConfig, $default = self::DEFAULT_HANDLER ) { /** @@ -47,8 +46,7 @@ public function __construct( * Save handler may be set to custom value in deployment config, which will override everything else. * Otherwise, try to read PHP settings for session.save_handler value. Otherwise, use 'files' as default. */ - $defaultSaveHandler = ini_get('session.save_handler') ?: SaveHandlerInterface::DEFAULT_HANDLER; - $saveMethod = $deploymentConfig->get(Config::PARAM_SESSION_SAVE_METHOD, $defaultSaveHandler); + $saveMethod = $sessionConfig->getOption('session.save_handler') ?: $default; $this->setSaveHandler($saveMethod); try { diff --git a/lib/internal/Magento/Framework/Session/SidResolver.php b/lib/internal/Magento/Framework/Session/SidResolver.php index ab830b5991818..1208aeb31eaee 100644 --- a/lib/internal/Magento/Framework/Session/SidResolver.php +++ b/lib/internal/Magento/Framework/Session/SidResolver.php @@ -9,6 +9,9 @@ use Magento\Framework\App\State; +/** + * Class SidResolver + */ class SidResolver implements SidResolverInterface { /** @@ -86,8 +89,12 @@ public function __construct( } /** + * Get Sid + * * @param SessionManagerInterface $session + * * @return string|null + * @throws \Magento\Framework\Exception\LocalizedException */ public function getSid(SessionManagerInterface $session) { @@ -96,6 +103,7 @@ public function getSid(SessionManagerInterface $session) } $sidKey = null; + $useSidOnFrontend = $this->getUseSessionInUrl(); if ($useSidOnFrontend && $this->request->getQuery( $this->getSessionIdQueryParam($session), @@ -168,7 +176,7 @@ public function getUseSessionInUrl() if ($this->_useSessionInUrl === null) { //Using config value by default, can be overridden by using the //setter. - $this->_useSessionInUrl = (bool)$this->scopeConfig->getValue( + $this->_useSessionInUrl = $this->scopeConfig->isSetFlag( self::XML_PATH_USE_FRONTEND_SID, $this->_scopeType ); From bbaf398b6cc689ef0917a2f0a9155424eb37583f Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Tue, 4 Jun 2019 09:57:57 +0200 Subject: [PATCH 2035/2092] MC-17030: Fixes RSS Interface - adds preference --- app/code/Magento/Rss/etc/di.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/app/code/Magento/Rss/etc/di.xml b/app/code/Magento/Rss/etc/di.xml index 3b00e1893efaf..d9e930482578e 100644 --- a/app/code/Magento/Rss/etc/di.xml +++ b/app/code/Magento/Rss/etc/di.xml @@ -8,4 +8,5 @@ + From 484bdb5debdd3d97ea98391da9dc3227fce0cf6d Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Tue, 4 Jun 2019 09:58:48 +0200 Subject: [PATCH 2036/2092] MC-16722: Fixes UnitTests --- setup/src/Magento/Setup/Module/I18n/Pack/Generator.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup/src/Magento/Setup/Module/I18n/Pack/Generator.php b/setup/src/Magento/Setup/Module/I18n/Pack/Generator.php index 720fc351bea00..d1da0a16487a3 100644 --- a/setup/src/Magento/Setup/Module/I18n/Pack/Generator.php +++ b/setup/src/Magento/Setup/Module/I18n/Pack/Generator.php @@ -71,7 +71,8 @@ public function generate( $locale = $this->factory->createLocale($locale); $dictionary = $this->dictionaryLoader->load($dictionaryPath); - if (!count($dictionary->getPhrases())) { + $phrases = $dictionary->getPhrases(); + if (!is_array($phrases) || !count($phrases)) { throw new \UnexpectedValueException('No phrases have been found by the specified path.'); } From e7519972274624b3c555a19606c479460b20f37e Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Tue, 4 Jun 2019 13:53:01 +0200 Subject: [PATCH 2037/2092] MC-16174: Fixes some Integration Tests for PHP 7.2 --- .../Magento/Store/Test/Unit/Model/WebsiteRepositoryTest.php | 2 +- .../Test/Integrity/Magento/Backend/ControllerAclTest.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Store/Test/Unit/Model/WebsiteRepositoryTest.php b/app/code/Magento/Store/Test/Unit/Model/WebsiteRepositoryTest.php index 80e4973bbe7fe..6ebc7ebd4bbd9 100644 --- a/app/code/Magento/Store/Test/Unit/Model/WebsiteRepositoryTest.php +++ b/app/code/Magento/Store/Test/Unit/Model/WebsiteRepositoryTest.php @@ -34,7 +34,7 @@ protected function setUp() { $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->websiteFactoryMock = - $this->getMockBuilder('Magento\Store\Model\WebsiteFactory') + $this->getMockBuilder(\Magento\Store\Model\WebsiteFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); diff --git a/dev/tests/static/testsuite/Magento/Test/Integrity/Magento/Backend/ControllerAclTest.php b/dev/tests/static/testsuite/Magento/Test/Integrity/Magento/Backend/ControllerAclTest.php index fc53e4391007b..46bdd3dd666df 100644 --- a/dev/tests/static/testsuite/Magento/Test/Integrity/Magento/Backend/ControllerAclTest.php +++ b/dev/tests/static/testsuite/Magento/Test/Integrity/Magento/Backend/ControllerAclTest.php @@ -97,7 +97,7 @@ public function testAcl() $inheritanceMessage = "Backend controller $className have to inherit " . AbstractAction::class; $errorMessages[] = $inheritanceMessage; continue; - }; + } $isAclRedefinedInTheChildClass = $this->isConstantOverwritten($controllerClass) || $this->isMethodOverwritten($controllerClass); @@ -233,7 +233,7 @@ private function isItTest($relativeFilePath) private function getControllerPath($relativeFilePath) { if (preg_match('~(Magento\/[^\/]+\/Controller\/Adminhtml\/.*)\.php~', $relativeFilePath, $matches)) { - if (count($matches) === 2 && count($partPath = $matches[1]) >= 1) { + if (count($matches) === 2) { $partPath = $matches[1]; return $partPath; } From 1bc20baf261cfe0016c4f8a6b00bc56ccd29ba6b Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Tue, 4 Jun 2019 15:38:35 +0200 Subject: [PATCH 2038/2092] MC-16174: remove void return type to ensure compatibility with PHP7.0 --- .../testsuite/Magento/Framework/Session/SessionManagerTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/tests/integration/testsuite/Magento/Framework/Session/SessionManagerTest.php b/dev/tests/integration/testsuite/Magento/Framework/Session/SessionManagerTest.php index 3205c19445ee1..7ab5bb5f5c916 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Session/SessionManagerTest.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Session/SessionManagerTest.php @@ -346,7 +346,7 @@ public function testConstructor() $this->assertTrue(self::$isSessionSetSaveHandlerInvoked); } - private function initializeModel(): void + private function initializeModel() { $this->model = $this->objectManager->create( \Magento\Framework\Session\SessionManager::class, From 2876dcf92c670c714f383858e7b0a86d6c3facb8 Mon Sep 17 00:00:00 2001 From: Harald Deiser Date: Wed, 5 Jun 2019 10:26:29 +0200 Subject: [PATCH 2039/2092] MC-17183: fixed a bug that cause legacy tests to fail --- composer.lock | 400 ++++++++++++++++++++++++-------------------------- 1 file changed, 191 insertions(+), 209 deletions(-) diff --git a/composer.lock b/composer.lock index fbc187c22689e..98552a918df81 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "5c05752aca22723453de6d1ffae9f9a6", + "content-hash": "69bb1429f30758489828b09780072e60", "packages": [ { "name": "braintree/braintree_php", @@ -981,16 +981,16 @@ }, { "name": "phpseclib/mcrypt_compat", - "version": "1.0.9", + "version": "1.0.8", "source": { "type": "git", "url": "https://github.com/phpseclib/mcrypt_compat.git", - "reference": "0220d5916d5027b85370211e03231e1144c245c3" + "reference": "f74c7b1897b62f08f268184b8bb98d9d9ab723b0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/mcrypt_compat/zipball/0220d5916d5027b85370211e03231e1144c245c3", - "reference": "0220d5916d5027b85370211e03231e1144c245c3", + "url": "https://api.github.com/repos/phpseclib/mcrypt_compat/zipball/f74c7b1897b62f08f268184b8bb98d9d9ab723b0", + "reference": "f74c7b1897b62f08f268184b8bb98d9d9ab723b0", "shasum": "" }, "require": { @@ -1026,20 +1026,20 @@ "encryption", "mcrypt" ], - "time": "2019-02-15T13:26:06+00:00" + "time": "2018-08-22T03:11:43+00:00" }, { "name": "phpseclib/phpseclib", - "version": "2.0.15", + "version": "2.0.17", "source": { "type": "git", "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "11cf67cf78dc4acb18dc9149a57be4aee5036ce0" + "reference": "3ca5b88d582c69178c8d01fd9d02b94e15042bb8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/11cf67cf78dc4acb18dc9149a57be4aee5036ce0", - "reference": "11cf67cf78dc4acb18dc9149a57be4aee5036ce0", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/3ca5b88d582c69178c8d01fd9d02b94e15042bb8", + "reference": "3ca5b88d582c69178c8d01fd9d02b94e15042bb8", "shasum": "" }, "require": { @@ -1118,7 +1118,7 @@ "x.509", "x509" ], - "time": "2019-03-10T16:53:45+00:00" + "time": "2019-05-26T20:38:34+00:00" }, { "name": "psr/container", @@ -1550,25 +1550,25 @@ }, { "name": "symfony/css-selector", - "version": "v4.2.8", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/css-selector.git", - "reference": "48eddf66950fa57996e1be4a55916d65c10c604a" + "reference": "8ca29297c29b64fb3a1a135e71cb25f67f9fdccf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/css-selector/zipball/48eddf66950fa57996e1be4a55916d65c10c604a", - "reference": "48eddf66950fa57996e1be4a55916d65c10c604a", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/8ca29297c29b64fb3a1a135e71cb25f67f9fdccf", + "reference": "8ca29297c29b64fb3a1a135e71cb25f67f9fdccf", "shasum": "" }, "require": { - "php": "^7.1.3" + "php": "^5.5.9|>=7.0.8" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "3.4-dev" } }, "autoload": { @@ -1599,7 +1599,7 @@ ], "description": "Symfony CssSelector Component", "homepage": "https://symfony.com", - "time": "2019-01-16T20:31:39+00:00" + "time": "2019-01-16T09:39:14+00:00" }, { "name": "symfony/debug", @@ -1720,7 +1720,7 @@ }, { "name": "symfony/filesystem", - "version": "v3.4.27", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", @@ -1770,16 +1770,16 @@ }, { "name": "symfony/finder", - "version": "v3.4.27", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "61af5ce0b34b942d414fe8f1b11950d0e9a90e98" + "reference": "fa5d962a71f2169dfe1cbae217fa5a2799859f6c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/61af5ce0b34b942d414fe8f1b11950d0e9a90e98", - "reference": "61af5ce0b34b942d414fe8f1b11950d0e9a90e98", + "url": "https://api.github.com/repos/symfony/finder/zipball/fa5d962a71f2169dfe1cbae217fa5a2799859f6c", + "reference": "fa5d962a71f2169dfe1cbae217fa5a2799859f6c", "shasum": "" }, "require": { @@ -1815,7 +1815,7 @@ ], "description": "Symfony Finder Component", "homepage": "https://symfony.com", - "time": "2019-04-02T19:54:57+00:00" + "time": "2019-05-24T12:25:55+00:00" }, { "name": "symfony/polyfill-ctype", @@ -2659,6 +2659,67 @@ ], "time": "2017-12-12T17:48:56+00:00" }, + { + "name": "zendframework/zend-feed", + "version": "2.10.3", + "source": { + "type": "git", + "url": "https://github.com/zendframework/zend-feed.git", + "reference": "6641f4cf3f4586c63f83fd70b6d19966025c8888" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/zend-feed/zipball/6641f4cf3f4586c63f83fd70b6d19966025c8888", + "reference": "6641f4cf3f4586c63f83fd70b6d19966025c8888", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0", + "zendframework/zend-escaper": "^2.5.2", + "zendframework/zend-stdlib": "^2.7.7 || ^3.1" + }, + "require-dev": { + "phpunit/phpunit": "^5.7.23 || ^6.4.3", + "psr/http-message": "^1.0.1", + "zendframework/zend-cache": "^2.7.2", + "zendframework/zend-coding-standard": "~1.0.0", + "zendframework/zend-db": "^2.8.2", + "zendframework/zend-http": "^2.7", + "zendframework/zend-servicemanager": "^2.7.8 || ^3.3", + "zendframework/zend-validator": "^2.10.1" + }, + "suggest": { + "psr/http-message": "PSR-7 ^1.0.1, if you wish to use Zend\\Feed\\Reader\\Http\\Psr7ResponseDecorator", + "zendframework/zend-cache": "Zend\\Cache component, for optionally caching feeds between requests", + "zendframework/zend-db": "Zend\\Db component, for use with PubSubHubbub", + "zendframework/zend-http": "Zend\\Http for PubSubHubbub, and optionally for use with Zend\\Feed\\Reader", + "zendframework/zend-servicemanager": "Zend\\ServiceManager component, for easily extending ExtensionManager implementations", + "zendframework/zend-validator": "Zend\\Validator component, for validating email addresses used in Atom feeds and entries when using the Writer subcomponent" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.10.x-dev", + "dev-develop": "2.11.x-dev" + } + }, + "autoload": { + "psr-4": { + "Zend\\Feed\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides functionality for consuming RSS and Atom feeds", + "keywords": [ + "ZendFramework", + "feed", + "zf" + ], + "time": "2018-08-01T13:53:20+00:00" + }, { "name": "zendframework/zend-filter", "version": "2.9.1", @@ -4551,16 +4612,16 @@ }, { "name": "composer/xdebug-handler", - "version": "1.3.2", + "version": "1.3.3", "source": { "type": "git", "url": "https://github.com/composer/xdebug-handler.git", - "reference": "d17708133b6c276d6e42ef887a877866b909d892" + "reference": "46867cbf8ca9fb8d60c506895449eb799db1184f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/d17708133b6c276d6e42ef887a877866b909d892", - "reference": "d17708133b6c276d6e42ef887a877866b909d892", + "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/46867cbf8ca9fb8d60c506895449eb799db1184f", + "reference": "46867cbf8ca9fb8d60c506895449eb799db1184f", "shasum": "" }, "require": { @@ -4591,7 +4652,7 @@ "Xdebug", "performance" ], - "time": "2019-01-28T20:25:53+00:00" + "time": "2019-05-27T17:52:04+00:00" }, { "name": "consolidation/annotated-command", @@ -4862,16 +4923,16 @@ }, { "name": "consolidation/output-formatters", - "version": "3.4.1", + "version": "3.5.0", "source": { "type": "git", "url": "https://github.com/consolidation/output-formatters.git", - "reference": "0881112642ad9059071f13f397f571035b527cb9" + "reference": "99ec998ffb697e0eada5aacf81feebfb13023605" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/consolidation/output-formatters/zipball/0881112642ad9059071f13f397f571035b527cb9", - "reference": "0881112642ad9059071f13f397f571035b527cb9", + "url": "https://api.github.com/repos/consolidation/output-formatters/zipball/99ec998ffb697e0eada5aacf81feebfb13023605", + "reference": "99ec998ffb697e0eada5aacf81feebfb13023605", "shasum": "" }, "require": { @@ -4959,7 +5020,7 @@ } ], "description": "Format text by applying transformations provided by plug-in formatters.", - "time": "2019-03-14T03:45:44+00:00" + "time": "2019-05-30T23:16:01+00:00" }, { "name": "consolidation/robo", @@ -5180,30 +5241,30 @@ }, { "name": "doctrine/annotations", - "version": "v1.6.1", + "version": "v1.4.0", "source": { "type": "git", "url": "https://github.com/doctrine/annotations.git", - "reference": "53120e0eb10355388d6ccbe462f1fea34ddadb24" + "reference": "54cacc9b81758b14e3ce750f205a393d52339e97" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/annotations/zipball/53120e0eb10355388d6ccbe462f1fea34ddadb24", - "reference": "53120e0eb10355388d6ccbe462f1fea34ddadb24", + "url": "https://api.github.com/repos/doctrine/annotations/zipball/54cacc9b81758b14e3ce750f205a393d52339e97", + "reference": "54cacc9b81758b14e3ce750f205a393d52339e97", "shasum": "" }, "require": { "doctrine/lexer": "1.*", - "php": "^7.1" + "php": "^5.6 || ^7.0" }, "require-dev": { "doctrine/cache": "1.*", - "phpunit/phpunit": "^6.4" + "phpunit/phpunit": "^5.7" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.6.x-dev" + "dev-master": "1.4.x-dev" } }, "autoload": { @@ -5244,40 +5305,38 @@ "docblock", "parser" ], - "time": "2019-03-25T19:12:02+00:00" + "time": "2017-02-24T16:22:25+00:00" }, { "name": "doctrine/collections", - "version": "v1.6.1", + "version": "v1.4.0", "source": { "type": "git", "url": "https://github.com/doctrine/collections.git", - "reference": "d2ae4ef05e25197343b6a39bae1d3c427a2f6956" + "reference": "1a4fb7e902202c33cce8c55989b945612943c2ba" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/collections/zipball/d2ae4ef05e25197343b6a39bae1d3c427a2f6956", - "reference": "d2ae4ef05e25197343b6a39bae1d3c427a2f6956", + "url": "https://api.github.com/repos/doctrine/collections/zipball/1a4fb7e902202c33cce8c55989b945612943c2ba", + "reference": "1a4fb7e902202c33cce8c55989b945612943c2ba", "shasum": "" }, "require": { - "php": "^7.1.3" + "php": "^5.6 || ^7.0" }, "require-dev": { - "doctrine/coding-standard": "^6.0", - "phpstan/phpstan-shim": "^0.9.2", - "phpunit/phpunit": "^7.0", - "vimeo/psalm": "^3.2.2" + "doctrine/coding-standard": "~0.1@dev", + "phpunit/phpunit": "^5.7" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.6.x-dev" + "dev-master": "1.3.x-dev" } }, "autoload": { - "psr-4": { - "Doctrine\\Common\\Collections\\": "lib/Doctrine/Common/Collections" + "psr-0": { + "Doctrine\\Common\\Collections\\": "lib/" } }, "notification-url": "https://packagist.org/downloads/", @@ -5306,46 +5365,43 @@ "email": "schmittjoh@gmail.com" } ], - "description": "PHP Doctrine Collections library that adds additional functionality on top of PHP arrays.", - "homepage": "https://www.doctrine-project.org/projects/collections.html", + "description": "Collections Abstraction library", + "homepage": "http://www.doctrine-project.org", "keywords": [ "array", "collections", - "iterators", - "php" + "iterator" ], - "time": "2019-03-25T19:03:48+00:00" + "time": "2017-01-03T10:49:41+00:00" }, { "name": "doctrine/instantiator", - "version": "1.2.0", + "version": "1.0.5", "source": { "type": "git", "url": "https://github.com/doctrine/instantiator.git", - "reference": "a2c590166b2133a4633738648b6b064edae0814a" + "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/instantiator/zipball/a2c590166b2133a4633738648b6b064edae0814a", - "reference": "a2c590166b2133a4633738648b6b064edae0814a", + "url": "https://api.github.com/repos/doctrine/instantiator/zipball/8e884e78f9f0eb1329e445619e04456e64d8051d", + "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d", "shasum": "" }, "require": { - "php": "^7.1" + "php": ">=5.3,<8.0-DEV" }, "require-dev": { - "doctrine/coding-standard": "^6.0", + "athletic/athletic": "~0.1.8", "ext-pdo": "*", "ext-phar": "*", - "phpbench/phpbench": "^0.13", - "phpstan/phpstan-phpunit": "^0.11", - "phpstan/phpstan-shim": "^0.11", - "phpunit/phpunit": "^7.0" + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.2.x-dev" + "dev-master": "1.0.x-dev" } }, "autoload": { @@ -5365,12 +5421,12 @@ } ], "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors", - "homepage": "https://www.doctrine-project.org/projects/instantiator.html", + "homepage": "https://github.com/doctrine/instantiator", "keywords": [ "constructor", "instantiate" ], - "time": "2019-03-17T17:37:11+00:00" + "time": "2015-06-14T21:17:01+00:00" }, { "name": "doctrine/lexer", @@ -6553,28 +6609,25 @@ }, { "name": "myclabs/deep-copy", - "version": "1.9.1", + "version": "1.7.0", "source": { "type": "git", "url": "https://github.com/myclabs/DeepCopy.git", - "reference": "e6828efaba2c9b79f4499dae1d66ef8bfa7b2b72" + "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/e6828efaba2c9b79f4499dae1d66ef8bfa7b2b72", - "reference": "e6828efaba2c9b79f4499dae1d66ef8bfa7b2b72", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e", + "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e", "shasum": "" }, "require": { - "php": "^7.1" - }, - "replace": { - "myclabs/deep-copy": "self.version" + "php": "^5.6 || ^7.0" }, "require-dev": { "doctrine/collections": "^1.0", "doctrine/common": "^2.6", - "phpunit/phpunit": "^7.1" + "phpunit/phpunit": "^4.1" }, "type": "library", "autoload": { @@ -6597,7 +6650,7 @@ "object", "object graph" ], - "time": "2019-04-07T13:18:21+00:00" + "time": "2017-10-19T19:58:43+00:00" }, { "name": "pdepend/pdepend", @@ -8255,25 +8308,25 @@ }, { "name": "symfony/browser-kit", - "version": "v4.2.8", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/browser-kit.git", - "reference": "c09c18cca96d7067152f78956faf55346c338283" + "reference": "7f2b0843d5045468225f9a9b27a0cb171ae81828" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/browser-kit/zipball/c09c18cca96d7067152f78956faf55346c338283", - "reference": "c09c18cca96d7067152f78956faf55346c338283", + "url": "https://api.github.com/repos/symfony/browser-kit/zipball/7f2b0843d5045468225f9a9b27a0cb171ae81828", + "reference": "7f2b0843d5045468225f9a9b27a0cb171ae81828", "shasum": "" }, "require": { - "php": "^7.1.3", - "symfony/dom-crawler": "~3.4|~4.0" + "php": "^5.5.9|>=7.0.8", + "symfony/dom-crawler": "~2.8|~3.0|~4.0" }, "require-dev": { - "symfony/css-selector": "~3.4|~4.0", - "symfony/process": "~3.4|~4.0" + "symfony/css-selector": "~2.8|~3.0|~4.0", + "symfony/process": "~2.8|~3.0|~4.0" }, "suggest": { "symfony/process": "" @@ -8281,7 +8334,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "3.4-dev" } }, "autoload": { @@ -8308,35 +8361,36 @@ ], "description": "Symfony BrowserKit Component", "homepage": "https://symfony.com", - "time": "2019-04-07T09:56:43+00:00" + "time": "2019-04-06T19:33:58+00:00" }, { "name": "symfony/config", - "version": "v4.2.8", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/config.git", - "reference": "0e745ead307d5dcd4e163e94a47ec04b1428943f" + "reference": "177a276c01575253c95cefe0866e3d1b57637fe0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/config/zipball/0e745ead307d5dcd4e163e94a47ec04b1428943f", - "reference": "0e745ead307d5dcd4e163e94a47ec04b1428943f", + "url": "https://api.github.com/repos/symfony/config/zipball/177a276c01575253c95cefe0866e3d1b57637fe0", + "reference": "177a276c01575253c95cefe0866e3d1b57637fe0", "shasum": "" }, "require": { - "php": "^7.1.3", - "symfony/filesystem": "~3.4|~4.0", + "php": "^5.5.9|>=7.0.8", + "symfony/filesystem": "~2.8|~3.0|~4.0", "symfony/polyfill-ctype": "~1.8" }, "conflict": { - "symfony/finder": "<3.4" + "symfony/dependency-injection": "<3.3", + "symfony/finder": "<3.3" }, "require-dev": { - "symfony/dependency-injection": "~3.4|~4.0", - "symfony/event-dispatcher": "~3.4|~4.0", - "symfony/finder": "~3.4|~4.0", - "symfony/yaml": "~3.4|~4.0" + "symfony/dependency-injection": "~3.3|~4.0", + "symfony/event-dispatcher": "~3.3|~4.0", + "symfony/finder": "~3.3|~4.0", + "symfony/yaml": "~3.0|~4.0" }, "suggest": { "symfony/yaml": "To use the yaml reference dumper" @@ -8344,7 +8398,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "3.4-dev" } }, "autoload": { @@ -8371,78 +8425,7 @@ ], "description": "Symfony Config Component", "homepage": "https://symfony.com", - "time": "2019-04-01T14:03:25+00:00" - }, - { - "name": "symfony/contracts", - "version": "v1.1.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/contracts.git", - "reference": "d3636025e8253c6144358ec0a62773cae588395b" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/contracts/zipball/d3636025e8253c6144358ec0a62773cae588395b", - "reference": "d3636025e8253c6144358ec0a62773cae588395b", - "shasum": "" - }, - "require": { - "php": "^7.1.3" - }, - "require-dev": { - "psr/cache": "^1.0", - "psr/container": "^1.0", - "symfony/polyfill-intl-idn": "^1.10" - }, - "suggest": { - "psr/cache": "When using the Cache contracts", - "psr/container": "When using the Service contracts", - "symfony/cache-contracts-implementation": "", - "symfony/event-dispatcher-implementation": "", - "symfony/http-client-contracts-implementation": "", - "symfony/service-contracts-implementation": "", - "symfony/translation-contracts-implementation": "" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.1-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Contracts\\": "" - }, - "exclude-from-classmap": [ - "**/Tests/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "A set of abstractions extracted out of the Symfony components", - "homepage": "https://symfony.com", - "keywords": [ - "abstractions", - "contracts", - "decoupling", - "interfaces", - "interoperability", - "standards" - ], - "time": "2019-04-27T14:29:50+00:00" + "time": "2019-02-23T15:06:07+00:00" }, { "name": "symfony/dependency-injection", @@ -8516,25 +8499,25 @@ }, { "name": "symfony/dom-crawler", - "version": "v4.2.8", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/dom-crawler.git", - "reference": "53c97769814c80a84a8403efcf3ae7ae966d53bb" + "reference": "d40023c057393fb25f7ca80af2a56ed948c45a09" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/53c97769814c80a84a8403efcf3ae7ae966d53bb", - "reference": "53c97769814c80a84a8403efcf3ae7ae966d53bb", + "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/d40023c057393fb25f7ca80af2a56ed948c45a09", + "reference": "d40023c057393fb25f7ca80af2a56ed948c45a09", "shasum": "" }, "require": { - "php": "^7.1.3", + "php": "^5.5.9|>=7.0.8", "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-mbstring": "~1.0" }, "require-dev": { - "symfony/css-selector": "~3.4|~4.0" + "symfony/css-selector": "~2.8|~3.0|~4.0" }, "suggest": { "symfony/css-selector": "" @@ -8542,7 +8525,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "3.4-dev" } }, "autoload": { @@ -8569,34 +8552,34 @@ ], "description": "Symfony DomCrawler Component", "homepage": "https://symfony.com", - "time": "2019-02-23T15:17:42+00:00" + "time": "2019-02-23T15:06:07+00:00" }, { "name": "symfony/http-foundation", - "version": "v4.2.8", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "1ea878bd3af18f934dedb8c0de60656a9a31a718" + "reference": "677ae5e892b081e71a665bfa7dd90fe61800c00e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/1ea878bd3af18f934dedb8c0de60656a9a31a718", - "reference": "1ea878bd3af18f934dedb8c0de60656a9a31a718", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/677ae5e892b081e71a665bfa7dd90fe61800c00e", + "reference": "677ae5e892b081e71a665bfa7dd90fe61800c00e", "shasum": "" }, "require": { - "php": "^7.1.3", - "symfony/polyfill-mbstring": "~1.1" + "php": "^5.5.9|>=7.0.8", + "symfony/polyfill-mbstring": "~1.1", + "symfony/polyfill-php70": "~1.6" }, "require-dev": { - "predis/predis": "~1.0", - "symfony/expression-language": "~3.4|~4.0" + "symfony/expression-language": "~2.8|~3.0|~4.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "3.4-dev" } }, "autoload": { @@ -8623,29 +8606,29 @@ ], "description": "Symfony HttpFoundation Component", "homepage": "https://symfony.com", - "time": "2019-05-01T08:36:31+00:00" + "time": "2019-05-27T05:50:24+00:00" }, { "name": "symfony/options-resolver", - "version": "v4.2.8", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/options-resolver.git", - "reference": "fd4a5f27b7cd085b489247b9890ebca9f3e10044" + "reference": "ed3b397f9c07c8ca388b2a1ef744403b4d4ecc44" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/options-resolver/zipball/fd4a5f27b7cd085b489247b9890ebca9f3e10044", - "reference": "fd4a5f27b7cd085b489247b9890ebca9f3e10044", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/ed3b397f9c07c8ca388b2a1ef744403b4d4ecc44", + "reference": "ed3b397f9c07c8ca388b2a1ef744403b4d4ecc44", "shasum": "" }, "require": { - "php": "^7.1.3" + "php": "^5.5.9|>=7.0.8" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "3.4-dev" } }, "autoload": { @@ -8677,7 +8660,7 @@ "configuration", "options" ], - "time": "2019-04-10T16:20:36+00:00" + "time": "2019-04-10T16:00:48+00:00" }, { "name": "symfony/polyfill-php54", @@ -8909,26 +8892,25 @@ }, { "name": "symfony/stopwatch", - "version": "v4.2.8", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/stopwatch.git", - "reference": "b1a5f646d56a3290230dbc8edf2a0d62cda23f67" + "reference": "2a651c2645c10bbedd21170771f122d935e0dd58" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/stopwatch/zipball/b1a5f646d56a3290230dbc8edf2a0d62cda23f67", - "reference": "b1a5f646d56a3290230dbc8edf2a0d62cda23f67", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/2a651c2645c10bbedd21170771f122d935e0dd58", + "reference": "2a651c2645c10bbedd21170771f122d935e0dd58", "shasum": "" }, "require": { - "php": "^7.1.3", - "symfony/contracts": "^1.0" + "php": "^5.5.9|>=7.0.8" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.2-dev" + "dev-master": "3.4-dev" } }, "autoload": { @@ -8955,7 +8937,7 @@ ], "description": "Symfony Stopwatch Component", "homepage": "https://symfony.com", - "time": "2019-01-16T20:31:39+00:00" + "time": "2019-01-16T09:39:14+00:00" }, { "name": "symfony/yaml", From 85e7e4a0c3943d5b89ae0df5c3cbfb70d74aea8f Mon Sep 17 00:00:00 2001 From: Harald Deiser Date: Wed, 5 Jun 2019 12:39:46 +0200 Subject: [PATCH 2040/2092] MC-17238: changend constructor parameter from concrete to abstract implementation --- .../CatalogSearch/Model/ResourceModel/Search/Collection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/CatalogSearch/Model/ResourceModel/Search/Collection.php b/app/code/Magento/CatalogSearch/Model/ResourceModel/Search/Collection.php index ae9311b452627..d66eb906266f8 100644 --- a/app/code/Magento/CatalogSearch/Model/ResourceModel/Search/Collection.php +++ b/app/code/Magento/CatalogSearch/Model/ResourceModel/Search/Collection.php @@ -65,7 +65,7 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\Data\Collection\EntityFactory $entityFactory, + \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, \Magento\Framework\Event\ManagerInterface $eventManager, From bb5ccc1c615f98cf0f5dd38d88d997a88b6a1b91 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Wed, 5 Jun 2019 11:17:52 +0200 Subject: [PATCH 2041/2092] MC-17237: fix composer.json to pass static tests --- lib/internal/Magento/Framework/composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/internal/Magento/Framework/composer.json b/lib/internal/Magento/Framework/composer.json index 6e1da52eb1629..f1c6497b70631 100644 --- a/lib/internal/Magento/Framework/composer.json +++ b/lib/internal/Magento/Framework/composer.json @@ -21,7 +21,7 @@ "ext-xsl": "*", "ext-bcmath": "*", "symfony/process": "~2.1", - "colinmollenhour/php-redis-session-abstract": "1.3.4", + "colinmollenhour/php-redis-session-abstract": "1.3.8", "composer/composer": "^1.4", "monolog/monolog": "^1.17", "oyejorge/less.php": "~1.7.0", @@ -34,7 +34,7 @@ "zendframework/zend-validator": "^2.6.0", "zendframework/zend-stdlib": "^2.7.7", "zendframework/zend-http": "^2.6.0", - "magento/zendframework1": "~1.13.0" + "magento/zendframework1": "~1.14.0" }, "suggest": { "ext-imagick": "Use Image Magick >=3.0.0 as an optional alternative image processing library" From fb39e40b18f6719f3f2f32240c985a17160564e7 Mon Sep 17 00:00:00 2001 From: Harald Deiser Date: Wed, 5 Jun 2019 14:36:31 +0200 Subject: [PATCH 2042/2092] MC-17238: Reverted constructor change --- .../CatalogSearch/Model/ResourceModel/Search/Collection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/CatalogSearch/Model/ResourceModel/Search/Collection.php b/app/code/Magento/CatalogSearch/Model/ResourceModel/Search/Collection.php index d66eb906266f8..ae9311b452627 100644 --- a/app/code/Magento/CatalogSearch/Model/ResourceModel/Search/Collection.php +++ b/app/code/Magento/CatalogSearch/Model/ResourceModel/Search/Collection.php @@ -65,7 +65,7 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory, + \Magento\Framework\Data\Collection\EntityFactory $entityFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, \Magento\Framework\Event\ManagerInterface $eventManager, From 536f5c10cf83574d0ff6cbd781b59f41d8190c88 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Fri, 7 Jun 2019 08:27:43 +0200 Subject: [PATCH 2043/2092] MC-17240: fixes Integration tests --- .../Framework/Code/Reader/SourceArgumentsReaderTest.php | 4 ++-- .../Reader/_files/SourceArgumentsReaderTest.php.sample | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/dev/tests/integration/testsuite/Magento/Framework/Code/Reader/SourceArgumentsReaderTest.php b/dev/tests/integration/testsuite/Magento/Framework/Code/Reader/SourceArgumentsReaderTest.php index 2f7f040d82c24..d1b22e853ce1d 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Code/Reader/SourceArgumentsReaderTest.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Code/Reader/SourceArgumentsReaderTest.php @@ -41,8 +41,8 @@ public function getConstructorArgumentTypesDataProvider() '\Imported\Name\Space\One', '\Imported\Name\Space\AnotherTest\Extended', '\Imported\Name\Space\Test', - '\Imported\Name\Space\Object\Under\Test', - '\Imported\Name\Space\Object', + '\Imported\Name\Space\ClassName\Under\Test', + '\Imported\Name\Space\ClassName', '\Some\Testing\Name\Space\Test', 'array', '' diff --git a/dev/tests/integration/testsuite/Magento/Framework/Code/Reader/_files/SourceArgumentsReaderTest.php.sample b/dev/tests/integration/testsuite/Magento/Framework/Code/Reader/_files/SourceArgumentsReaderTest.php.sample index 739369ee4e16a..47c059de2034b 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Code/Reader/_files/SourceArgumentsReaderTest.php.sample +++ b/dev/tests/integration/testsuite/Magento/Framework/Code/Reader/_files/SourceArgumentsReaderTest.php.sample @@ -6,8 +6,8 @@ namespace Some\Testing\Name\Space; use Imported\Name\Space\One as FirstImport; -use Imported\Name\Space\Object; -use Imported\Name\Space\Test as Testing, \Imported\Name\Space\AnotherTest; +use Imported\Name\Space\ClassName; +use Imported\Name\Space\Test as Testing, \Imported\Name\Space\AnotherTest ; class AnotherSimpleClass { @@ -16,8 +16,8 @@ class AnotherSimpleClass FirstImport $itemTwo, AnotherTest\Extended $itemThree, Testing $itemFour, - Object\Under\Test $itemFive, - Object $itemSix, + ClassName\Under\Test $itemFive, + ClassName $itemSix, Test $itemSeven, array $itemEight = [], $itemNine = 'test' From 24aba675224677d85e69c87016be1fc7d4809340 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Thu, 6 Jun 2019 10:27:21 +0200 Subject: [PATCH 2044/2092] MC-17240: add ignore to pass static tests --- .../Address/Attribute/Source/CountryWithWebsites.php | 2 ++ .../Magento/Setup/Fixtures/ConfigurableProductsFixture.php | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/app/code/Magento/Customer/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsites.php b/app/code/Magento/Customer/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsites.php index 2b5e3b702a914..630da5f6cd582 100644 --- a/app/code/Magento/Customer/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsites.php +++ b/app/code/Magento/Customer/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsites.php @@ -71,8 +71,10 @@ public function __construct( * * @return array */ + // @codingStandardsIgnoreStart public function getAllOptions($withEmpty = true, $defaultValues = false) { + // @codingStandardsIgnoreEnd if (!$this->options) { $allowedCountries = []; $websiteIds = []; diff --git a/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php b/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php index 3cd1dfb0ee4c9..6f58f1c09b890 100644 --- a/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php +++ b/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php @@ -317,7 +317,9 @@ private function getDefaultAttributeSetsConfig(array $defaultAttributeSets, $con { $attributeSetClosure = function ($index) use ($defaultAttributeSets) { $attributeSetAmount = count(array_keys($defaultAttributeSets)); + // @codingStandardsIgnoreStart mt_srand($index); + // @codingStandardsIgnoreEnd return $attributeSetAmount > ($index - 1) % (int)$this->fixtureModel->getValue('categories', 30) ? array_keys($defaultAttributeSets)[mt_rand(0, $attributeSetAmount - 1)] @@ -851,7 +853,9 @@ private function getDescriptionClosure( $configurableProductsCount / ($simpleProductsCount + $configurableProductsCount) ) ); + // @codingStandardsIgnoreStart mt_srand($index); + // @codingStandardsIgnoreEnd return $this->dataGenerator->generate( $minAmountOfWordsDescription, $maxAmountOfWordsDescription, From db6426c57a02478c5f7e797ae015b9af9187ee00 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Thu, 6 Jun 2019 13:03:29 +0200 Subject: [PATCH 2045/2092] MC-17237: add suppress warnings to pass static tests --- .../Address/Attribute/Source/CountryWithWebsites.php | 3 +-- .../Magento/Setup/Fixtures/ConfigurableProductsFixture.php | 6 ++---- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/app/code/Magento/Customer/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsites.php b/app/code/Magento/Customer/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsites.php index 630da5f6cd582..b25d11e424660 100644 --- a/app/code/Magento/Customer/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsites.php +++ b/app/code/Magento/Customer/Model/ResourceModel/Address/Attribute/Source/CountryWithWebsites.php @@ -70,11 +70,10 @@ public function __construct( * Retrieve all options * * @return array + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - // @codingStandardsIgnoreStart public function getAllOptions($withEmpty = true, $defaultValues = false) { - // @codingStandardsIgnoreEnd if (!$this->options) { $allowedCountries = []; $websiteIds = []; diff --git a/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php b/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php index 6f58f1c09b890..d2a5932b7309d 100644 --- a/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php +++ b/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php @@ -312,14 +312,13 @@ private function getConfigurableWebsiteIdsClosure() * @param array $defaultAttributeSets * @param int $configurableProductsCount * @return array + * @SuppressWarnings */ private function getDefaultAttributeSetsConfig(array $defaultAttributeSets, $configurableProductsCount) { $attributeSetClosure = function ($index) use ($defaultAttributeSets) { $attributeSetAmount = count(array_keys($defaultAttributeSets)); - // @codingStandardsIgnoreStart mt_srand($index); - // @codingStandardsIgnoreEnd return $attributeSetAmount > ($index - 1) % (int)$this->fixtureModel->getValue('categories', 30) ? array_keys($defaultAttributeSets)[mt_rand(0, $attributeSetAmount - 1)] @@ -823,6 +822,7 @@ private function getConfigurableOptionSkuPattern($skuPattern) * @param int $minAmountOfWordsDescription * @param string $descriptionPrefix * @return \Closure + * @SuppressWarnings */ private function getDescriptionClosure( $searchTerms, @@ -853,9 +853,7 @@ private function getDescriptionClosure( $configurableProductsCount / ($simpleProductsCount + $configurableProductsCount) ) ); - // @codingStandardsIgnoreStart mt_srand($index); - // @codingStandardsIgnoreEnd return $this->dataGenerator->generate( $minAmountOfWordsDescription, $maxAmountOfWordsDescription, From 4d929b94b7f6a07f42fa9c0047aca1157cca722e Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Fri, 7 Jun 2019 08:26:16 +0200 Subject: [PATCH 2046/2092] MC-17237: add suppress warnings to pass static tests --- .../Test/Legacy/_files/security/unsecure_php_functions.php | 4 +++- .../Magento/Setup/Fixtures/ConfigurableProductsFixture.php | 2 -- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php index 38fb25dff760a..0ccf975f397b8 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php @@ -49,6 +49,8 @@ ], 'mt_srand' => [ 'replacement' => '', - 'exclude' => [] + 'exclude' => [ + ['type' => 'setup', 'name' => 'magento/setup', 'path' => 'Fixtures/ConfigurableProductsFixture.php'], + ] ], ]; diff --git a/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php b/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php index d2a5932b7309d..3cd1dfb0ee4c9 100644 --- a/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php +++ b/setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php @@ -312,7 +312,6 @@ private function getConfigurableWebsiteIdsClosure() * @param array $defaultAttributeSets * @param int $configurableProductsCount * @return array - * @SuppressWarnings */ private function getDefaultAttributeSetsConfig(array $defaultAttributeSets, $configurableProductsCount) { @@ -822,7 +821,6 @@ private function getConfigurableOptionSkuPattern($skuPattern) * @param int $minAmountOfWordsDescription * @param string $descriptionPrefix * @return \Closure - * @SuppressWarnings */ private function getDescriptionClosure( $searchTerms, From 9a0ea0c02833f25040145a0d8dfcdb8570ab0690 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Fri, 7 Jun 2019 10:43:50 +0200 Subject: [PATCH 2047/2092] MC-17237: fixes declaration of excluded files --- .../Test/Legacy/_files/security/unsecure_php_functions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php index 0ccf975f397b8..ea01337d9882d 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php @@ -50,7 +50,7 @@ 'mt_srand' => [ 'replacement' => '', 'exclude' => [ - ['type' => 'setup', 'name' => 'magento/setup', 'path' => 'Fixtures/ConfigurableProductsFixture.php'], + ['type' => 'setup', 'path' => 'setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php'], ] ], ]; From d183b4afe30a4b474052e0a9b2b0c65854a32c8e Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Fri, 7 Jun 2019 10:52:34 +0200 Subject: [PATCH 2048/2092] MC-17237: fixes waring of unused parameter with SuppressWarnings --- app/code/Magento/Eav/Model/Entity/Attribute/Source/Store.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Eav/Model/Entity/Attribute/Source/Store.php b/app/code/Magento/Eav/Model/Entity/Attribute/Source/Store.php index a8f3cb5f777e9..cef1db109c750 100644 --- a/app/code/Magento/Eav/Model/Entity/Attribute/Source/Store.php +++ b/app/code/Magento/Eav/Model/Entity/Attribute/Source/Store.php @@ -35,8 +35,8 @@ public function __construct( /** * Retrieve Full Option values array - * - * @return array + * @inheritdoc + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getAllOptions($withEmpty = true, $defaultValues = false) { From 35eed2f4145b1f8b9f0f59bfb58d098b290a83f8 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Fri, 7 Jun 2019 13:18:50 +0200 Subject: [PATCH 2049/2092] MC-17237: fixes waring of unused parameter with SuppressWarnings --- .../Test/Legacy/_files/security/unsecure_php_functions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php index ea01337d9882d..2b25999b6c2ff 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php @@ -50,7 +50,7 @@ 'mt_srand' => [ 'replacement' => '', 'exclude' => [ - ['type' => 'setup', 'path' => 'setup/src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php'], + ['type' => 'setup', 'path' => 'src/Magento/Setup/Fixtures/ConfigurableProductsFixture.php'], ] ], ]; From f13f536f9f57f20a0a512fc35cbb65be3706293d Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Fri, 7 Jun 2019 13:25:37 +0200 Subject: [PATCH 2050/2092] MC-17237: fixes waring of unused parameter with SuppressWarnings --- app/code/Magento/Theme/Block/Html/Topmenu.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/code/Magento/Theme/Block/Html/Topmenu.php b/app/code/Magento/Theme/Block/Html/Topmenu.php index 0f846440abb74..1a25550d93937 100644 --- a/app/code/Magento/Theme/Block/Html/Topmenu.php +++ b/app/code/Magento/Theme/Block/Html/Topmenu.php @@ -78,6 +78,7 @@ protected function getCacheLifetime() * @param string $childrenWrapClass * @param int $limit * @return string + * @SuppressWarnings(PHPMD.RequestAwareBlockMethod) */ public function getHtml($outermostClass = '', $childrenWrapClass = '', $limit = 0) { From ef2335102f84b6add7cfac5f3b8c59727fe4fc17 Mon Sep 17 00:00:00 2001 From: Lars Roettig Date: Wed, 12 Jun 2019 15:38:41 +0200 Subject: [PATCH 2051/2092] MC-16722: Fixes for php72 composer.json --- .../Magento/TestModuleIntegrationFromConfig/composer.json | 2 +- .../_files/Magento/TestModuleJoinDirectives/composer.json | 2 +- .../integration/_files/Magento/TestModuleSample/composer.json | 2 +- .../Command/_files/root/app/code/Magento/A/composer.json | 2 +- .../Command/_files/root/app/code/Magento/B/composer.json | 2 +- .../Widget/_files/design/adminhtml/magento_basic/composer.json | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/dev/tests/api-functional/_files/Magento/TestModuleIntegrationFromConfig/composer.json b/dev/tests/api-functional/_files/Magento/TestModuleIntegrationFromConfig/composer.json index b8c10d886fd76..9797885b942ba 100644 --- a/dev/tests/api-functional/_files/Magento/TestModuleIntegrationFromConfig/composer.json +++ b/dev/tests/api-functional/_files/Magento/TestModuleIntegrationFromConfig/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-test-module-integration-from-config", "description": "test integration create from config", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "0.42.0-beta8", "magento/module-integration": "0.42.0-beta8" }, diff --git a/dev/tests/api-functional/_files/Magento/TestModuleJoinDirectives/composer.json b/dev/tests/api-functional/_files/Magento/TestModuleJoinDirectives/composer.json index f99883f4b4c26..622413b9c0ac7 100644 --- a/dev/tests/api-functional/_files/Magento/TestModuleJoinDirectives/composer.json +++ b/dev/tests/api-functional/_files/Magento/TestModuleJoinDirectives/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-test-join-directives", "description": "test integration for join directives", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "0.42.0-beta8", "magento/module-sales": "0.42.0-beta8" }, diff --git a/dev/tests/integration/_files/Magento/TestModuleSample/composer.json b/dev/tests/integration/_files/Magento/TestModuleSample/composer.json index f72844a2968f3..bcf490e35c99b 100644 --- a/dev/tests/integration/_files/Magento/TestModuleSample/composer.json +++ b/dev/tests/integration/_files/Magento/TestModuleSample/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-sample-test", "description": "test sample module", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "100.1.*", "magento/module-integration": "100.1.*" }, diff --git a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/root/app/code/Magento/A/composer.json b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/root/app/code/Magento/A/composer.json index ddf42815e0580..a19a1e2811ee0 100644 --- a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/root/app/code/Magento/A/composer.json +++ b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/root/app/code/Magento/A/composer.json @@ -1,7 +1,7 @@ { "name": "magento/module-a", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "0.1", "magento/module-b": "0.1" }, diff --git a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/root/app/code/Magento/B/composer.json b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/root/app/code/Magento/B/composer.json index 9634021dee0fb..ec34ef169ca01 100644 --- a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/root/app/code/Magento/B/composer.json +++ b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/root/app/code/Magento/B/composer.json @@ -1,7 +1,7 @@ { "name": "magento/module-b", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "0.74.0-beta6", "magento/module-a": "0.1" }, diff --git a/dev/tests/integration/testsuite/Magento/Widget/_files/design/adminhtml/magento_basic/composer.json b/dev/tests/integration/testsuite/Magento/Widget/_files/design/adminhtml/magento_basic/composer.json index 654be88a3b58c..c49d52b3dc4c1 100644 --- a/dev/tests/integration/testsuite/Magento/Widget/_files/design/adminhtml/magento_basic/composer.json +++ b/dev/tests/integration/testsuite/Magento/Widget/_files/design/adminhtml/magento_basic/composer.json @@ -2,7 +2,7 @@ "name": "magento/admin-Magento_Catalog", "description": "N/A", "require": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "magento/framework": "0.1.0-alpha103" }, "type": "magento2-theme", From ceafcf2bee30671a276f1ec8ba58eaed56eaeb46 Mon Sep 17 00:00:00 2001 From: Lars Roettig Date: Thu, 13 Jun 2019 20:32:06 +0200 Subject: [PATCH 2052/2092] MC-16722: Fixes for session --- .../Magento/Framework/Session/SaveHandler.php | 46 ++----------------- 1 file changed, 3 insertions(+), 43 deletions(-) diff --git a/lib/internal/Magento/Framework/Session/SaveHandler.php b/lib/internal/Magento/Framework/Session/SaveHandler.php index 0a5402957de5b..7959130d1e41c 100644 --- a/lib/internal/Magento/Framework/Session/SaveHandler.php +++ b/lib/internal/Magento/Framework/Session/SaveHandler.php @@ -5,9 +5,8 @@ */ namespace Magento\Framework\Session; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Exception\SessionException; use Magento\Framework\Session\Config\ConfigInterface; +use \Magento\Framework\Exception\SessionException; /** * Magento session save handler @@ -21,13 +20,6 @@ class SaveHandler implements SaveHandlerInterface */ protected $saveHandlerAdapter; - /** - * Config - * - * @var ConfigInterface - */ - private $config; - /** * Constructor * @@ -47,15 +39,12 @@ public function __construct( * Otherwise, try to read PHP settings for session.save_handler value. Otherwise, use 'files' as default. */ $saveMethod = $sessionConfig->getOption('session.save_handler') ?: $default; - $this->setSaveHandler($saveMethod); try { - $connection = $saveHandlerFactory->create($saveMethod); + $this->saveHandlerAdapter = $saveHandlerFactory->create($saveMethod); } catch (SessionException $e) { - $connection = $saveHandlerFactory->create($default); - $this->setSaveHandler($default); + $this->saveHandlerAdapter = $saveHandlerFactory->create($default); } - $this->saveHandlerAdapter = $connection; } /** @@ -126,33 +115,4 @@ public function gc($maxLifetime) { return $this->saveHandlerAdapter->gc($maxLifetime); } - - /** - * Get config - * - * @return ConfigInterface - * @deprecated 100.0.8 - */ - private function getConfig() - { - if ($this->config === null) { - $this->config = ObjectManager::getInstance()->get(ConfigInterface::class); - } - return $this->config; - } - - /** - * Set session.save_handler option - * - * @param string $saveHandler - * @return $this - */ - private function setSaveHandler($saveHandler) - { - if ($saveHandler === 'db' || $saveHandler === 'redis') { - $saveHandler = 'user'; - } - $this->getConfig()->setOption('session.save_handler', $saveHandler); - return $this; - } } From a30ffea3833ad344c066a3db1ea4de15c7ce79a2 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Mon, 17 Jun 2019 16:24:41 +0200 Subject: [PATCH 2053/2092] MC-17316: Fix Unit Tests for EE --- .../Block/Adminhtml/Order/AbstractForm.php | 25 +------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/AbstractForm.php b/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/AbstractForm.php index bc7ee4372d61b..5572c06816a39 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/AbstractForm.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/AbstractForm.php @@ -6,9 +6,7 @@ namespace Magento\Sales\Test\Block\Adminhtml\Order; -use function GuzzleHttp\Psr7\str; use Magento\Mtf\Block\Form; -use Magento\Mtf\Client\Locator; /** * Abstract Form block. @@ -44,27 +42,6 @@ function () { ); } - /** - * Wait for element is enabled. - * - * @param string $selector - * @param string $strategy - * @return bool|null - */ - protected function waitForElementEnabled(string $selector, string $strategy = Locator::SELECTOR_CSS) - { - $browser = $this->browser; - - return $browser->waitUntil( - function () use ($browser, $selector, $strategy) { - $element = $browser->find($selector, $strategy); - $class = $element->getAttribute('class'); - - return (!$element->isDisabled() && !strpos($class, 'disabled')) ? true : null; - } - ); - } - /** * Fill form data. * @@ -136,7 +113,7 @@ abstract protected function getItemsBlock(); */ public function submit() { - $this->waitForElementEnabled($this->send); + $this->waitLoader(); $this->_rootElement->find($this->send)->click(); } From a205f7c6ab790d604960be02714bb99d0f799f7f Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Tue, 18 Jun 2019 11:43:41 +0200 Subject: [PATCH 2054/2092] MC-17316: Fix Unit Tests for EE an minor bugs --- app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php | 2 +- .../ConfigurableProduct/Test/TestCase/TaxCalculationTest.xml | 2 +- .../tests/app/Magento/Tax/Test/Handler/TaxRule/Curl.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php b/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php index 7bdf7c0112795..b2e1e093eda99 100644 --- a/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php +++ b/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php @@ -232,7 +232,7 @@ public function getAssociatedProducts($product) */ public function flushAssociatedProductsCache($product) { - return $product->unsData($this->_keyAssociatedProducts); + return $product->unsetData($this->_keyAssociatedProducts); } /** diff --git a/dev/tests/functional/tests/app/Magento/ConfigurableProduct/Test/TestCase/TaxCalculationTest.xml b/dev/tests/functional/tests/app/Magento/ConfigurableProduct/Test/TestCase/TaxCalculationTest.xml index 8b89e9f085279..89fa91d3a6264 100644 --- a/dev/tests/functional/tests/app/Magento/ConfigurableProduct/Test/TestCase/TaxCalculationTest.xml +++ b/dev/tests/functional/tests/app/Magento/ConfigurableProduct/Test/TestCase/TaxCalculationTest.xml @@ -6,7 +6,7 @@ */ --> - + configurableProduct::two_options_by_one_dollar us_full_tax_rule diff --git a/dev/tests/functional/tests/app/Magento/Tax/Test/Handler/TaxRule/Curl.php b/dev/tests/functional/tests/app/Magento/Tax/Test/Handler/TaxRule/Curl.php index 64f69d44abc80..bdc3015a81272 100644 --- a/dev/tests/functional/tests/app/Magento/Tax/Test/Handler/TaxRule/Curl.php +++ b/dev/tests/functional/tests/app/Magento/Tax/Test/Handler/TaxRule/Curl.php @@ -46,7 +46,7 @@ public function persist(FixtureInterface $fixture = null) $response = $curl->read(); $curl->close(); - if (!strpos($response, 'data-ui-id="messages-message-success"')) { + if (strpos($response, 'data-ui-id="messages-message-success"') === false) { $this->_eventManager->dispatchEvent(['curl_failed'], [$response]); throw new \Exception("Tax rate creation by curl handler was not successful!"); } From 9c63c4b87d3c4399715def1866a1b2058e88c832 Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Tue, 18 Jun 2019 14:13:13 +0200 Subject: [PATCH 2055/2092] MC-17316: undo fix typo --- app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php b/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php index b2e1e093eda99..7bdf7c0112795 100644 --- a/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php +++ b/app/code/Magento/GroupedProduct/Model/Product/Type/Grouped.php @@ -232,7 +232,7 @@ public function getAssociatedProducts($product) */ public function flushAssociatedProductsCache($product) { - return $product->unsetData($this->_keyAssociatedProducts); + return $product->unsData($this->_keyAssociatedProducts); } /** From 334eeb0da9fba59fdcf263e641a24325c3a89cca Mon Sep 17 00:00:00 2001 From: Harald Deiser Date: Wed, 19 Jun 2019 10:14:30 +0200 Subject: [PATCH 2056/2092] MC-16395: Fixed a timeing problem in DeleteProductFromMiniShoppingCartTest --- .../tests/app/Magento/Catalog/Test/Block/Product/View.php | 1 + 1 file changed, 1 insertion(+) diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/Block/Product/View.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/Block/Product/View.php index 4ba335511c82c..d65bb22402e20 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/Block/Product/View.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/Block/Product/View.php @@ -298,6 +298,7 @@ public function configure(FixtureInterface $product) $checkoutData = $product->getCheckoutData(); $this->getMiniCartBlock()->waitInit(); + sleep(10); $this->fillOptions($product); if (isset($checkoutData['qty'])) { $this->setQty($checkoutData['qty']); From 354b253a43da1b8f0b76cf939e232c85ab5093ff Mon Sep 17 00:00:00 2001 From: Harald Deiser Date: Wed, 19 Jun 2019 13:15:13 +0200 Subject: [PATCH 2057/2092] MC-16395: Added compatibility fix --- app/code/Magento/Customer/Controller/Account/CreatePost.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Customer/Controller/Account/CreatePost.php b/app/code/Magento/Customer/Controller/Account/CreatePost.php index a16434d90c2ed..1d67a6b5d5eba 100644 --- a/app/code/Magento/Customer/Controller/Account/CreatePost.php +++ b/app/code/Magento/Customer/Controller/Account/CreatePost.php @@ -177,7 +177,7 @@ public function __construct( CustomerExtractor $customerExtractor, DataObjectHelper $dataObjectHelper, AccountRedirect $accountRedirect, - CustomerRepository $customerRepository, + CustomerRepository $customerRepository = null, Validator $formKeyValidator = null ) { $this->session = $customerSession; @@ -198,7 +198,7 @@ public function __construct( $this->dataObjectHelper = $dataObjectHelper; $this->accountRedirect = $accountRedirect; $this->formKeyValidator = $formKeyValidator ?: ObjectManager::getInstance()->get(Validator::class); - $this->customerRepository = $customerRepository; + $this->customerRepository = $customerRepository ?: ObjectManager::getInstance()->get(CustomerRepository::class); parent::__construct($context); } From b2f6aa5a8605ee1c164083140eeb29b878ad5ffe Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov Date: Fri, 21 Jun 2019 09:55:49 -0500 Subject: [PATCH 2058/2092] MAGETWO-99925: Product URL rewrites are always regenerated if products are updated via CSV import in default scope --- .../CatalogUrlRewrite/Observer/AfterImportDataObserver.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php b/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php index 9aaa384776855..3d6d10f7e4a70 100644 --- a/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php +++ b/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php @@ -239,6 +239,13 @@ protected function _populateForUrlGeneration($rowData) && empty($rowData[self::URL_KEY_ATTRIBUTE_CODE])) { return null; } + $oldSku = $this->import->getOldSku(); + if (array_key_exists($rowData[ImportProduct::COL_SKU], $oldSku) + && !isset($rowData[self::URL_KEY_ATTRIBUTE_CODE]) + && $this->import->getBehavior() === ImportExport::BEHAVIOR_APPEND + ) { + return null; + } $rowData['entity_id'] = $newSku['entity_id']; $product = $this->catalogProductFactory->create(); From 8214fd92bf1c271f5d454d313423d732caabaefa Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov Date: Fri, 21 Jun 2019 10:06:26 -0500 Subject: [PATCH 2059/2092] MAGETWO-99925: Product URL rewrites are always regenerated if products are updated via CSV import in default scope --- .../CatalogUrlRewrite/Observer/AfterImportDataObserver.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php b/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php index 3d6d10f7e4a70..bb3ed2e1750ea 100644 --- a/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php +++ b/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php @@ -242,8 +242,7 @@ protected function _populateForUrlGeneration($rowData) $oldSku = $this->import->getOldSku(); if (array_key_exists($rowData[ImportProduct::COL_SKU], $oldSku) && !isset($rowData[self::URL_KEY_ATTRIBUTE_CODE]) - && $this->import->getBehavior() === ImportExport::BEHAVIOR_APPEND - ) { + && $this->import->getBehavior() === ImportExport::BEHAVIOR_APPEND) { return null; } $rowData['entity_id'] = $newSku['entity_id']; From 4998c87ee75fa4d0d9b26cd638f05e9259fb8ed4 Mon Sep 17 00:00:00 2001 From: Oleksandr Iegorov Date: Fri, 21 Jun 2019 10:47:30 -0500 Subject: [PATCH 2060/2092] MAGETWO-99925: Product URL rewrites are always regenerated if products are updated via CSV import in default scope --- .../Observer/AfterImportDataObserver.php | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php b/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php index bb3ed2e1750ea..aeb57561e67fd 100644 --- a/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php +++ b/app/code/Magento/CatalogUrlRewrite/Observer/AfterImportDataObserver.php @@ -232,17 +232,8 @@ public function execute(Observer $observer) protected function _populateForUrlGeneration($rowData) { $newSku = $this->import->getNewSku($rowData[ImportProduct::COL_SKU]); - if (empty($newSku) || !isset($newSku['entity_id'])) { - return null; - } - if ($this->import->getRowScope($rowData) == ImportProduct::SCOPE_STORE - && empty($rowData[self::URL_KEY_ATTRIBUTE_CODE])) { - return null; - } $oldSku = $this->import->getOldSku(); - if (array_key_exists($rowData[ImportProduct::COL_SKU], $oldSku) - && !isset($rowData[self::URL_KEY_ATTRIBUTE_CODE]) - && $this->import->getBehavior() === ImportExport::BEHAVIOR_APPEND) { + if (!$this->isNeedToPopulateForUrlGeneration($rowData, $newSku, $oldSku)) { return null; } $rowData['entity_id'] = $newSku['entity_id']; @@ -274,6 +265,27 @@ protected function _populateForUrlGeneration($rowData) return $this; } + /** + * Check is need to populate data for url generation + * + * @param array $rowData + * @param array $newSku + * @param array $oldSku + * @return bool + */ + private function isNeedToPopulateForUrlGeneration($rowData, $newSku, $oldSku): bool + { + if ((empty($newSku) || !isset($newSku['entity_id'])) + || ($this->import->getRowScope($rowData) == ImportProduct::SCOPE_STORE + && empty($rowData[self::URL_KEY_ATTRIBUTE_CODE])) + || (array_key_exists($rowData[ImportProduct::COL_SKU], $oldSku) + && !isset($rowData[self::URL_KEY_ATTRIBUTE_CODE]) + && $this->import->getBehavior() === ImportExport::BEHAVIOR_APPEND)) { + return false; + } + return true; + } + /** * Add store id to product data. * From e0448f0a6afbcf5384d77e2fcde251331cd9517f Mon Sep 17 00:00:00 2001 From: Maria Kovdrysh Date: Fri, 21 Jun 2019 11:10:34 -0500 Subject: [PATCH 2061/2092] MC-17552: Saving configurable product with custom product attribute (images as swatches) Fixed selector --- ...igurableProductWithAttributesImagesAndSwatchesTest.xml | 8 ++++++-- .../Section/AdminProductFormConfigurationsSection.xml | 2 +- .../Ui/Test/Mftf/Section/AdminDataGridTableSection.xml | 1 + 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml index c23f162a95fbb..6a82df0a27385 100644 --- a/app/code/Magento/Catalog/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml +++ b/app/code/Magento/Catalog/Test/Mftf/Test/AdminSaveConfigurableProductWithAttributesImagesAndSwatchesTest.xml @@ -96,9 +96,13 @@ + + + + - - + + diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml index f188f62dab200..cf50c383075f5 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Section/AdminProductFormConfigurationsSection.xml @@ -26,6 +26,6 @@ - +
    diff --git a/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridTableSection.xml b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridTableSection.xml index cbe5d9e158bb3..5dc5798c2c06b 100644 --- a/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridTableSection.xml +++ b/app/code/Magento/Ui/Test/Mftf/Section/AdminDataGridTableSection.xml @@ -22,5 +22,6 @@ +
    From 8a36f9fd01be4c374913c7b40dfaa41b86083aea Mon Sep 17 00:00:00 2001 From: Falk Ulbricht Date: Mon, 24 Jun 2019 08:58:59 +0200 Subject: [PATCH 2062/2092] MC-16395: Update composer.lock to compatible with PHP 7.2 --- composer.lock | 381 +++++++++++++++++++++++++++++++++----------------- 1 file changed, 252 insertions(+), 129 deletions(-) diff --git a/composer.lock b/composer.lock index ab53fb9dc460c..6677cd4e4a514 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "46fe53fa96d6bee5d732fa702c3b7f0b", + "content-hash": "5e8efc018c1d8d2c668a5ad1105dda0d", "packages": [ { "name": "braintree/braintree_php", @@ -55,21 +55,18 @@ }, { "name": "colinmollenhour/cache-backend-file", - "version": "1.4", + "version": "v1.4.5", "source": { "type": "git", "url": "https://github.com/colinmollenhour/Cm_Cache_Backend_File.git", - "reference": "51251b80a817790eb624fbe2afc882c14f3c4fb0" + "reference": "03c7d4c0f43b2de1b559a3527d18ff697d306544" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/colinmollenhour/Cm_Cache_Backend_File/zipball/51251b80a817790eb624fbe2afc882c14f3c4fb0", - "reference": "51251b80a817790eb624fbe2afc882c14f3c4fb0", + "url": "https://api.github.com/repos/colinmollenhour/Cm_Cache_Backend_File/zipball/03c7d4c0f43b2de1b559a3527d18ff697d306544", + "reference": "03c7d4c0f43b2de1b559a3527d18ff697d306544", "shasum": "" }, - "require": { - "magento-hackathon/magento-composer-installer": "*" - }, "type": "magento-module", "autoload": { "classmap": [ @@ -87,20 +84,20 @@ ], "description": "The stock Zend_Cache_Backend_File backend has extremely poor performance for cleaning by tags making it become unusable as the number of cached items increases. This backend makes many changes resulting in a huge performance boost, especially for tag cleaning.", "homepage": "https://github.com/colinmollenhour/Cm_Cache_Backend_File", - "time": "2016-05-02T16:24:47+00:00" + "time": "2019-04-18T21:54:31+00:00" }, { "name": "colinmollenhour/cache-backend-redis", - "version": "1.10.4", + "version": "1.10.7", "source": { "type": "git", "url": "https://github.com/colinmollenhour/Cm_Cache_Backend_Redis.git", - "reference": "6bf0a4b7a3f8dc4a6255fad5b6e42213253d9972" + "reference": "0ea3e4bf924242f8d03155761bf540c90a2db2d7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/colinmollenhour/Cm_Cache_Backend_Redis/zipball/6bf0a4b7a3f8dc4a6255fad5b6e42213253d9972", - "reference": "6bf0a4b7a3f8dc4a6255fad5b6e42213253d9972", + "url": "https://api.github.com/repos/colinmollenhour/Cm_Cache_Backend_Redis/zipball/0ea3e4bf924242f8d03155761bf540c90a2db2d7", + "reference": "0ea3e4bf924242f8d03155761bf540c90a2db2d7", "shasum": "" }, "require": { @@ -123,7 +120,7 @@ ], "description": "Zend_Cache backend using Redis with full support for tags.", "homepage": "https://github.com/colinmollenhour/Cm_Cache_Backend_Redis", - "time": "2017-10-05T20:50:44+00:00" + "time": "2019-02-18T18:59:51+00:00" }, { "name": "colinmollenhour/credis", @@ -167,21 +164,21 @@ }, { "name": "colinmollenhour/php-redis-session-abstract", - "version": "v1.3.4", + "version": "v1.3.8", "source": { "type": "git", "url": "https://github.com/colinmollenhour/php-redis-session-abstract.git", - "reference": "6f005b2c3755e4a96ddad821e2ea15d66fb314ae" + "reference": "9f69f5c1be512d5ff168e731e7fa29ab2905d847" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/colinmollenhour/php-redis-session-abstract/zipball/6f005b2c3755e4a96ddad821e2ea15d66fb314ae", - "reference": "6f005b2c3755e4a96ddad821e2ea15d66fb314ae", + "url": "https://api.github.com/repos/colinmollenhour/php-redis-session-abstract/zipball/9f69f5c1be512d5ff168e731e7fa29ab2905d847", + "reference": "9f69f5c1be512d5ff168e731e7fa29ab2905d847", "shasum": "" }, "require": { "colinmollenhour/credis": "~1.6", - "php": "~5.5.0|~5.6.0|~7.0.0|~7.1.0" + "php": "~5.5.0|~5.6.0|~7.0.0|~7.1.0|~7.2.0" }, "type": "library", "autoload": { @@ -200,7 +197,7 @@ ], "description": "A Redis-based session handler with optimistic locking", "homepage": "https://github.com/colinmollenhour/php-redis-session-abstract", - "time": "2017-03-22T16:13:03+00:00" + "time": "2018-01-08T14:53:13+00:00" }, { "name": "composer/ca-bundle", @@ -556,21 +553,21 @@ }, { "name": "magento/composer", - "version": "1.2.0", + "version": "1.2.x-dev", "source": { "type": "git", "url": "https://github.com/magento/composer.git", - "reference": "130753af2b755f1967e253deb661225942bb302c" + "reference": "6b406bc65690c1b28be9255249507e1c6572d815" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/magento/composer/zipball/130753af2b755f1967e253deb661225942bb302c", - "reference": "130753af2b755f1967e253deb661225942bb302c", + "url": "https://api.github.com/repos/magento/composer/zipball/6b406bc65690c1b28be9255249507e1c6572d815", + "reference": "6b406bc65690c1b28be9255249507e1c6572d815", "shasum": "" }, "require": { "composer/composer": "1.4.1", - "php": "~5.5.0|~5.6.0|~7.0.0|~7.1.0", + "php": "~5.5.0|~5.6.0|~7.0.0|~7.1.0|~7.2.0", "symfony/console": "~2.3, !=2.7.0" }, "require-dev": { @@ -582,13 +579,16 @@ "Magento\\Composer\\": "src" } }, - "notification-url": "https://packagist.org/downloads/", "license": [ "OSL-3.0", "AFL-3.0" ], "description": "Magento composer library helps to instantiate Composer application and run composer commands.", - "time": "2017-04-24T09:57:02+00:00" + "support": { + "source": "https://github.com/magento/composer/tree/1.2", + "issues": "https://github.com/magento/composer/issues" + }, + "time": "2019-05-21T16:03:27+00:00" }, { "name": "magento/magento-composer-installer", @@ -671,16 +671,16 @@ }, { "name": "magento/zendframework1", - "version": "1.13.1", + "version": "1.14.1", "source": { "type": "git", "url": "https://github.com/magento/zf1.git", - "reference": "e2693f047bb7ccb8affa8f72ea40269f4c9f4fbf" + "reference": "4df018254c70b5b998b00a8cb1a30760f831ff0d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/magento/zf1/zipball/e2693f047bb7ccb8affa8f72ea40269f4c9f4fbf", - "reference": "e2693f047bb7ccb8affa8f72ea40269f4c9f4fbf", + "url": "https://api.github.com/repos/magento/zf1/zipball/4df018254c70b5b998b00a8cb1a30760f831ff0d", + "reference": "4df018254c70b5b998b00a8cb1a30760f831ff0d", "shasum": "" }, "require": { @@ -714,7 +714,7 @@ "ZF1", "framework" ], - "time": "2017-06-21T14:56:23+00:00" + "time": "2018-08-09T15:03:40+00:00" }, { "name": "monolog/monolog", @@ -979,18 +979,67 @@ ], "time": "2018-12-10T10:36:30+00:00" }, + { + "name": "phpseclib/mcrypt_compat", + "version": "1.0.8", + "source": { + "type": "git", + "url": "https://github.com/phpseclib/mcrypt_compat.git", + "reference": "f74c7b1897b62f08f268184b8bb98d9d9ab723b0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpseclib/mcrypt_compat/zipball/f74c7b1897b62f08f268184b8bb98d9d9ab723b0", + "reference": "f74c7b1897b62f08f268184b8bb98d9d9ab723b0", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "phpseclib/phpseclib": ">=2.0.11 <3.0.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35|^5.7|^6.0" + }, + "suggest": { + "ext-openssl": "Will enable faster cryptographic operations" + }, + "type": "library", + "autoload": { + "files": [ + "lib/mcrypt.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jim Wigginton", + "email": "terrafrost@php.net", + "homepage": "http://phpseclib.sourceforge.net" + } + ], + "description": "PHP 7.1 polyfill for the mcrypt extension from PHP <= 7.0", + "keywords": [ + "cryptograpy", + "encryption", + "mcrypt" + ], + "time": "2018-08-22T03:11:43+00:00" + }, { "name": "phpseclib/phpseclib", - "version": "2.0.15", + "version": "2.0.20", "source": { "type": "git", "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "11cf67cf78dc4acb18dc9149a57be4aee5036ce0" + "reference": "d6819a55b05e123db1e881d8b230d57f912126be" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/11cf67cf78dc4acb18dc9149a57be4aee5036ce0", - "reference": "11cf67cf78dc4acb18dc9149a57be4aee5036ce0", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/d6819a55b05e123db1e881d8b230d57f912126be", + "reference": "d6819a55b05e123db1e881d8b230d57f912126be", "shasum": "" }, "require": { @@ -1069,7 +1118,7 @@ "x.509", "x509" ], - "time": "2019-03-10T16:53:45+00:00" + "time": "2019-06-23T16:33:11+00:00" }, { "name": "psr/container", @@ -1440,7 +1489,7 @@ }, { "name": "symfony/console", - "version": "v2.8.49", + "version": "v2.8.50", "source": { "type": "git", "url": "https://github.com/symfony/console.git", @@ -1501,7 +1550,7 @@ }, { "name": "symfony/css-selector", - "version": "v3.4.23", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/css-selector.git", @@ -1611,7 +1660,7 @@ }, { "name": "symfony/event-dispatcher", - "version": "v2.8.49", + "version": "v2.8.50", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher.git", @@ -1671,7 +1720,7 @@ }, { "name": "symfony/filesystem", - "version": "v3.4.23", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", @@ -1721,16 +1770,16 @@ }, { "name": "symfony/finder", - "version": "v3.4.23", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "fcdde4aa38f48190ce70d782c166f23930084f9b" + "reference": "fa5d962a71f2169dfe1cbae217fa5a2799859f6c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/fcdde4aa38f48190ce70d782c166f23930084f9b", - "reference": "fcdde4aa38f48190ce70d782c166f23930084f9b", + "url": "https://api.github.com/repos/symfony/finder/zipball/fa5d962a71f2169dfe1cbae217fa5a2799859f6c", + "reference": "fa5d962a71f2169dfe1cbae217fa5a2799859f6c", "shasum": "" }, "require": { @@ -1766,7 +1815,7 @@ ], "description": "Symfony Finder Component", "homepage": "https://symfony.com", - "time": "2019-02-22T14:44:53+00:00" + "time": "2019-05-24T12:25:55+00:00" }, { "name": "symfony/polyfill-ctype", @@ -1887,7 +1936,7 @@ }, { "name": "symfony/process", - "version": "v2.8.49", + "version": "v2.8.50", "source": { "type": "git", "url": "https://github.com/symfony/process.git", @@ -1936,16 +1985,16 @@ }, { "name": "tedivm/jshrink", - "version": "v1.3.1", + "version": "v1.3.2", "source": { "type": "git", "url": "https://github.com/tedious/JShrink.git", - "reference": "21254058dc3ce6aba6bef458cff4bfa25cf8b198" + "reference": "d9b51729f3c6692c2da3e3fe6c5cd7c9d1d3fa8f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/tedious/JShrink/zipball/21254058dc3ce6aba6bef458cff4bfa25cf8b198", - "reference": "21254058dc3ce6aba6bef458cff4bfa25cf8b198", + "url": "https://api.github.com/repos/tedious/JShrink/zipball/d9b51729f3c6692c2da3e3fe6c5cd7c9d1d3fa8f", + "reference": "d9b51729f3c6692c2da3e3fe6c5cd7c9d1d3fa8f", "shasum": "" }, "require": { @@ -1978,7 +2027,7 @@ "javascript", "minifier" ], - "time": "2018-09-16T00:02:51+00:00" + "time": "2019-06-15T23:11:19+00:00" }, { "name": "true/punycode", @@ -2610,6 +2659,67 @@ ], "time": "2017-12-12T17:48:56+00:00" }, + { + "name": "zendframework/zend-feed", + "version": "2.10.3", + "source": { + "type": "git", + "url": "https://github.com/zendframework/zend-feed.git", + "reference": "6641f4cf3f4586c63f83fd70b6d19966025c8888" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/zend-feed/zipball/6641f4cf3f4586c63f83fd70b6d19966025c8888", + "reference": "6641f4cf3f4586c63f83fd70b6d19966025c8888", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0", + "zendframework/zend-escaper": "^2.5.2", + "zendframework/zend-stdlib": "^2.7.7 || ^3.1" + }, + "require-dev": { + "phpunit/phpunit": "^5.7.23 || ^6.4.3", + "psr/http-message": "^1.0.1", + "zendframework/zend-cache": "^2.7.2", + "zendframework/zend-coding-standard": "~1.0.0", + "zendframework/zend-db": "^2.8.2", + "zendframework/zend-http": "^2.7", + "zendframework/zend-servicemanager": "^2.7.8 || ^3.3", + "zendframework/zend-validator": "^2.10.1" + }, + "suggest": { + "psr/http-message": "PSR-7 ^1.0.1, if you wish to use Zend\\Feed\\Reader\\Http\\Psr7ResponseDecorator", + "zendframework/zend-cache": "Zend\\Cache component, for optionally caching feeds between requests", + "zendframework/zend-db": "Zend\\Db component, for use with PubSubHubbub", + "zendframework/zend-http": "Zend\\Http for PubSubHubbub, and optionally for use with Zend\\Feed\\Reader", + "zendframework/zend-servicemanager": "Zend\\ServiceManager component, for easily extending ExtensionManager implementations", + "zendframework/zend-validator": "Zend\\Validator component, for validating email addresses used in Atom feeds and entries when using the Writer subcomponent" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.10.x-dev", + "dev-develop": "2.11.x-dev" + } + }, + "autoload": { + "psr-4": { + "Zend\\Feed\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides functionality for consuming RSS and Atom feeds", + "keywords": [ + "ZendFramework", + "feed", + "zf" + ], + "time": "2018-08-01T13:53:20+00:00" + }, { "name": "zendframework/zend-filter", "version": "2.9.1", @@ -3754,16 +3864,16 @@ }, { "name": "zendframework/zend-soap", - "version": "2.7.0", + "version": "2.8.0", "source": { "type": "git", "url": "https://github.com/zendframework/zend-soap.git", - "reference": "af03c32f0db2b899b3df8cfe29aeb2b49857d284" + "reference": "8762d79efa220d82529c43ce08d70554146be645" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/zendframework/zend-soap/zipball/af03c32f0db2b899b3df8cfe29aeb2b49857d284", - "reference": "af03c32f0db2b899b3df8cfe29aeb2b49857d284", + "url": "https://api.github.com/repos/zendframework/zend-soap/zipball/8762d79efa220d82529c43ce08d70554146be645", + "reference": "8762d79efa220d82529c43ce08d70554146be645", "shasum": "" }, "require": { @@ -3803,7 +3913,7 @@ "soap", "zf2" ], - "time": "2018-01-29T17:51:26+00:00" + "time": "2019-04-30T16:45:35+00:00" }, { "name": "zendframework/zend-stdlib", @@ -4502,16 +4612,16 @@ }, { "name": "composer/xdebug-handler", - "version": "1.3.2", + "version": "1.3.3", "source": { "type": "git", "url": "https://github.com/composer/xdebug-handler.git", - "reference": "d17708133b6c276d6e42ef887a877866b909d892" + "reference": "46867cbf8ca9fb8d60c506895449eb799db1184f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/d17708133b6c276d6e42ef887a877866b909d892", - "reference": "d17708133b6c276d6e42ef887a877866b909d892", + "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/46867cbf8ca9fb8d60c506895449eb799db1184f", + "reference": "46867cbf8ca9fb8d60c506895449eb799db1184f", "shasum": "" }, "require": { @@ -4542,7 +4652,7 @@ "Xdebug", "performance" ], - "time": "2019-01-28T20:25:53+00:00" + "time": "2019-05-27T17:52:04+00:00" }, { "name": "consolidation/annotated-command", @@ -4813,16 +4923,16 @@ }, { "name": "consolidation/output-formatters", - "version": "3.4.1", + "version": "3.5.0", "source": { "type": "git", "url": "https://github.com/consolidation/output-formatters.git", - "reference": "0881112642ad9059071f13f397f571035b527cb9" + "reference": "99ec998ffb697e0eada5aacf81feebfb13023605" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/consolidation/output-formatters/zipball/0881112642ad9059071f13f397f571035b527cb9", - "reference": "0881112642ad9059071f13f397f571035b527cb9", + "url": "https://api.github.com/repos/consolidation/output-formatters/zipball/99ec998ffb697e0eada5aacf81feebfb13023605", + "reference": "99ec998ffb697e0eada5aacf81feebfb13023605", "shasum": "" }, "require": { @@ -4910,7 +5020,7 @@ } ], "description": "Format text by applying transformations provided by plug-in formatters.", - "time": "2019-03-14T03:45:44+00:00" + "time": "2019-05-30T23:16:01+00:00" }, { "name": "consolidation/robo", @@ -5320,21 +5430,24 @@ }, { "name": "doctrine/lexer", - "version": "v1.0.1", + "version": "1.0.2", "source": { "type": "git", "url": "https://github.com/doctrine/lexer.git", - "reference": "83893c552fd2045dd78aef794c31e694c37c0b8c" + "reference": "1febd6c3ef84253d7c815bed85fc622ad207a9f8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/lexer/zipball/83893c552fd2045dd78aef794c31e694c37c0b8c", - "reference": "83893c552fd2045dd78aef794c31e694c37c0b8c", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/1febd6c3ef84253d7c815bed85fc622ad207a9f8", + "reference": "1febd6c3ef84253d7c815bed85fc622ad207a9f8", "shasum": "" }, "require": { "php": ">=5.3.2" }, + "require-dev": { + "phpunit/phpunit": "^4.5" + }, "type": "library", "extra": { "branch-alias": { @@ -5342,8 +5455,8 @@ } }, "autoload": { - "psr-0": { - "Doctrine\\Common\\Lexer\\": "lib/" + "psr-4": { + "Doctrine\\Common\\Lexer\\": "lib/Doctrine/Common/Lexer" } }, "notification-url": "https://packagist.org/downloads/", @@ -5364,13 +5477,16 @@ "email": "schmittjoh@gmail.com" } ], - "description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.", - "homepage": "http://www.doctrine-project.org", + "description": "PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "https://www.doctrine-project.org/projects/lexer.html", "keywords": [ + "annotations", + "docblock", "lexer", - "parser" + "parser", + "php" ], - "time": "2014-09-09T13:34:57+00:00" + "time": "2019-06-08T11:03:04+00:00" }, { "name": "epfremme/swagger-php", @@ -5420,16 +5536,16 @@ }, { "name": "facebook/webdriver", - "version": "1.6.0", + "version": "1.7.1", "source": { "type": "git", "url": "https://github.com/facebook/php-webdriver.git", - "reference": "bd8c740097eb9f2fc3735250fc1912bc811a954e" + "reference": "e43de70f3c7166169d0f14a374505392734160e5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/facebook/php-webdriver/zipball/bd8c740097eb9f2fc3735250fc1912bc811a954e", - "reference": "bd8c740097eb9f2fc3735250fc1912bc811a954e", + "url": "https://api.github.com/repos/facebook/php-webdriver/zipball/e43de70f3c7166169d0f14a374505392734160e5", + "reference": "e43de70f3c7166169d0f14a374505392734160e5", "shasum": "" }, "require": { @@ -5476,7 +5592,7 @@ "selenium", "webdriver" ], - "time": "2018-05-16T17:37:13+00:00" + "time": "2019-06-13T08:02:18+00:00" }, { "name": "flow/jsonpath", @@ -6069,16 +6185,16 @@ }, { "name": "jms/serializer", - "version": "1.13.0", + "version": "1.14.0", "source": { "type": "git", "url": "https://github.com/schmittjoh/serializer.git", - "reference": "00863e1d55b411cc33ad3e1de09a4c8d3aae793c" + "reference": "ee96d57024af9a7716d56fcbe3aa94b3d030f3ca" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/schmittjoh/serializer/zipball/00863e1d55b411cc33ad3e1de09a4c8d3aae793c", - "reference": "00863e1d55b411cc33ad3e1de09a4c8d3aae793c", + "url": "https://api.github.com/repos/schmittjoh/serializer/zipball/ee96d57024af9a7716d56fcbe3aa94b3d030f3ca", + "reference": "ee96d57024af9a7716d56fcbe3aa94b3d030f3ca", "shasum": "" }, "require": { @@ -6118,7 +6234,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-1.x": "1.13-dev" + "dev-1.x": "1.14-dev" } }, "autoload": { @@ -6149,7 +6265,7 @@ "serialization", "xml" ], - "time": "2018-07-25T13:58:54+00:00" + "time": "2019-04-17T08:12:16+00:00" }, { "name": "league/container", @@ -6357,7 +6473,7 @@ "time": "2019-06-10T17:57:40+00:00" }, { - "name": "mikey179/vfsstream", + "name": "mikey179/vfsStream", "version": "v1.6.6", "source": { "type": "git", @@ -6788,16 +6904,16 @@ }, { "name": "phpdocumentor/reflection-docblock", - "version": "4.3.0", + "version": "4.3.1", "source": { "type": "git", "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", - "reference": "94fd0001232e47129dd3504189fa1c7225010d08" + "reference": "bdd9f737ebc2a01c06ea7ff4308ec6697db9b53c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/94fd0001232e47129dd3504189fa1c7225010d08", - "reference": "94fd0001232e47129dd3504189fa1c7225010d08", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/bdd9f737ebc2a01c06ea7ff4308ec6697db9b53c", + "reference": "bdd9f737ebc2a01c06ea7ff4308ec6697db9b53c", "shasum": "" }, "require": { @@ -6835,7 +6951,7 @@ } ], "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", - "time": "2017-11-30T07:14:17+00:00" + "time": "2019-04-30T17:48:53+00:00" }, { "name": "phpdocumentor/type-resolver", @@ -7002,16 +7118,16 @@ }, { "name": "phpspec/prophecy", - "version": "1.8.0", + "version": "1.8.1", "source": { "type": "git", "url": "https://github.com/phpspec/prophecy.git", - "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06" + "reference": "1927e75f4ed19131ec9bcc3b002e07fb1173ee76" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpspec/prophecy/zipball/4ba436b55987b4bf311cb7c6ba82aa528aac0a06", - "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06", + "url": "https://api.github.com/repos/phpspec/prophecy/zipball/1927e75f4ed19131ec9bcc3b002e07fb1173ee76", + "reference": "1927e75f4ed19131ec9bcc3b002e07fb1173ee76", "shasum": "" }, "require": { @@ -7032,8 +7148,8 @@ } }, "autoload": { - "psr-0": { - "Prophecy\\": "src/" + "psr-4": { + "Prophecy\\": "src/Prophecy" } }, "notification-url": "https://packagist.org/downloads/", @@ -7061,7 +7177,7 @@ "spy", "stub" ], - "time": "2018-08-05T17:53:17+00:00" + "time": "2019-06-13T12:50:23+00:00" }, { "name": "phpunit/php-code-coverage", @@ -8198,16 +8314,16 @@ }, { "name": "symfony/browser-kit", - "version": "v3.4.23", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/browser-kit.git", - "reference": "c0fadd368c1031109e996316e53ffeb886d37ea1" + "reference": "7f2b0843d5045468225f9a9b27a0cb171ae81828" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/browser-kit/zipball/c0fadd368c1031109e996316e53ffeb886d37ea1", - "reference": "c0fadd368c1031109e996316e53ffeb886d37ea1", + "url": "https://api.github.com/repos/symfony/browser-kit/zipball/7f2b0843d5045468225f9a9b27a0cb171ae81828", + "reference": "7f2b0843d5045468225f9a9b27a0cb171ae81828", "shasum": "" }, "require": { @@ -8251,11 +8367,11 @@ ], "description": "Symfony BrowserKit Component", "homepage": "https://symfony.com", - "time": "2019-02-23T15:06:07+00:00" + "time": "2019-04-06T19:33:58+00:00" }, { "name": "symfony/config", - "version": "v3.4.23", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/config.git", @@ -8389,7 +8505,7 @@ }, { "name": "symfony/dom-crawler", - "version": "v3.4.23", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/dom-crawler.git", @@ -8446,16 +8562,16 @@ }, { "name": "symfony/http-foundation", - "version": "v3.4.23", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "9a96d77ceb1fd913c9d4a89e8a7e1be87604be8a" + "reference": "677ae5e892b081e71a665bfa7dd90fe61800c00e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/9a96d77ceb1fd913c9d4a89e8a7e1be87604be8a", - "reference": "9a96d77ceb1fd913c9d4a89e8a7e1be87604be8a", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/677ae5e892b081e71a665bfa7dd90fe61800c00e", + "reference": "677ae5e892b081e71a665bfa7dd90fe61800c00e", "shasum": "" }, "require": { @@ -8496,20 +8612,20 @@ ], "description": "Symfony HttpFoundation Component", "homepage": "https://symfony.com", - "time": "2019-02-23T15:06:07+00:00" + "time": "2019-05-27T05:50:24+00:00" }, { "name": "symfony/options-resolver", - "version": "v3.4.23", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/options-resolver.git", - "reference": "926e3b797e6bb66c0e4d7da7eff3a174f7378bcf" + "reference": "ed3b397f9c07c8ca388b2a1ef744403b4d4ecc44" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/options-resolver/zipball/926e3b797e6bb66c0e4d7da7eff3a174f7378bcf", - "reference": "926e3b797e6bb66c0e4d7da7eff3a174f7378bcf", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/ed3b397f9c07c8ca388b2a1ef744403b4d4ecc44", + "reference": "ed3b397f9c07c8ca388b2a1ef744403b4d4ecc44", "shasum": "" }, "require": { @@ -8550,7 +8666,7 @@ "configuration", "options" ], - "time": "2019-02-23T15:06:07+00:00" + "time": "2019-04-10T16:00:48+00:00" }, { "name": "symfony/polyfill-php54", @@ -8782,7 +8898,7 @@ }, { "name": "symfony/stopwatch", - "version": "v3.4.23", + "version": "v3.4.28", "source": { "type": "git", "url": "https://github.com/symfony/stopwatch.git", @@ -8926,16 +9042,16 @@ }, { "name": "theseer/tokenizer", - "version": "1.1.0", + "version": "1.1.3", "source": { "type": "git", "url": "https://github.com/theseer/tokenizer.git", - "reference": "cb2f008f3f05af2893a87208fe6a6c4985483f8b" + "reference": "11336f6f84e16a720dae9d8e6ed5019efa85a0f9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/theseer/tokenizer/zipball/cb2f008f3f05af2893a87208fe6a6c4985483f8b", - "reference": "cb2f008f3f05af2893a87208fe6a6c4985483f8b", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/11336f6f84e16a720dae9d8e6ed5019efa85a0f9", + "reference": "11336f6f84e16a720dae9d8e6ed5019efa85a0f9", "shasum": "" }, "require": { @@ -8962,7 +9078,7 @@ } ], "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", - "time": "2017-04-07T12:08:54+00:00" + "time": "2019-06-13T22:48:21+00:00" }, { "name": "vlucas/phpdotenv", @@ -9067,22 +9183,29 @@ "time": "2018-12-25T11:19:39+00:00" } ], - "aliases": [], - "minimum-stability": "stable", + "aliases": [ + { + "alias": "1.2.1", + "alias_normalized": "1.2.1.0", + "version": "1.2.9999999.9999999-dev", + "package": "magento/composer" + } + ], + "minimum-stability": "dev", "stability-flags": { + "magento/composer": 20, "phpmd/phpmd": 0 }, - "prefer-stable": false, + "prefer-stable": true, "prefer-lowest": false, "platform": { - "php": "~7.0.13|~7.1.0", + "php": "~7.0.13|~7.1.0|~7.2.0", "lib-libxml": "*", "ext-ctype": "*", "ext-gd": "*", "ext-spl": "*", "ext-dom": "*", "ext-simplexml": "*", - "ext-mcrypt": "*", "ext-bcmath": "*", "ext-hash": "*", "ext-curl": "*", From 54c0f4ee86ace642c23772609f52707fbd039b3d Mon Sep 17 00:00:00 2001 From: Denis Kopylov Date: Wed, 19 Jun 2019 13:35:20 +0300 Subject: [PATCH 2063/2092] Allow to define listing configuration via ui component xml --- .../web/js/variations/paging/sizes.js | 30 +++--- app/code/Magento/Ui/Component/Paging.php | 94 ++++++++++++------- .../Ui/Test/Unit/Component/PagingTest.php | 24 +---- .../Ui/view/base/web/js/grid/paging/paging.js | 13 ++- .../Ui/view/base/web/js/grid/paging/sizes.js | 23 ----- .../View/Layout/Generator/UiComponent.php | 12 +-- 6 files changed, 92 insertions(+), 104 deletions(-) diff --git a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/variations/paging/sizes.js b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/variations/paging/sizes.js index a8b8f95f6536f..155b176bd431b 100644 --- a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/variations/paging/sizes.js +++ b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/variations/paging/sizes.js @@ -9,21 +9,21 @@ define([ return Sizes.extend({ defaults: { - excludedOptions: ['100', '200'] - }, - - /** - * @override - */ - initialize: function () { - this._super(); - - this.excludedOptions.forEach(function (excludedOption) { - delete this.options[excludedOption]; - }, this); - this.updateArray(); - - return this; + options: { + '20': { + value: 20, + label: 20 + }, + '30': { + value: 30, + label: 30 + }, + '50': { + value: 50, + label: 50 + } + }, + value: 20 } }); }); diff --git a/app/code/Magento/Ui/Component/Paging.php b/app/code/Magento/Ui/Component/Paging.php index ae83bfc3916cc..57d0ec53777e2 100644 --- a/app/code/Magento/Ui/Component/Paging.php +++ b/app/code/Magento/Ui/Component/Paging.php @@ -3,9 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Ui\Component; /** + * Class Paging + * * @api * @since 100.0.2 */ @@ -13,6 +16,41 @@ class Paging extends AbstractComponent { const NAME = 'paging'; + /** + * Default paging options + * + * @var array + */ + private $defaultOptions = [ + '20' => [ + 'value' => 20, + 'label' => 20 + ], + '30' => [ + 'value' => 30, + 'label' => 30 + ], + '50' => [ + 'value' => 50, + 'label' => 50 + ], + '100' => [ + 'value' => 100, + 'label' => 100 + ], + '200' => [ + 'value' => 200, + 'label' => 200 + ], + ]; + + /** + * Default page size + * + * @var int + */ + private $defaultPageSize = 20; + /** * Default component data * @@ -20,29 +58,6 @@ class Paging extends AbstractComponent */ protected $_data = [ 'config' => [ - 'options' => [ - '20' => [ - 'value' => 20, - 'label' => 20 - ], - '30' => [ - 'value' => 30, - 'label' => 30 - ], - '50' => [ - 'value' => 50, - 'label' => 50 - ], - '100' => [ - 'value' => 100, - 'label' => 100 - ], - '200' => [ - 'value' => 200, - 'label' => 200 - ], - ], - 'pageSize' => 20, 'current' => 1 ] ]; @@ -65,13 +80,13 @@ public function getComponentName() public function prepare() { $this->prepareOptions(); + $this->preparePageSize(); $paging = $this->getContext()->getRequestParam('paging'); if (!isset($paging['notLimits'])) { $this->getContext() ->getDataProvider() ->setLimit($this->getOffset($paging), $this->getSize($paging)); } - parent::prepare(); } @@ -83,12 +98,26 @@ public function prepare() protected function prepareOptions() { $config = $this->getData('config'); - if (isset($config['options'])) { - $config['options'] = array_values($config['options']); - foreach ($config['options'] as &$item) { - $item['value'] = (int) $item['value']; - } - unset($item); + if (!isset($config['options'])) { + $config['options'] = $this->defaultOptions; + } + foreach ($config['options'] as &$item) { + $item['value'] = (int)$item['value']; + } + unset($item); + $this->setData('config', $config); + } + + /** + * Prepare page size + * + * @return void + */ + private function preparePageSize() + { + $config = $this->getData('config'); + if (!isset($config['pageSize'])) { + $config['pageSize'] = $this->defaultPageSize; $this->setData('config', $config); } } @@ -102,7 +131,7 @@ protected function prepareOptions() protected function getOffset($paging) { $defaultPage = $this->getData('config/current') ?: 1; - return (int) (isset($paging['current']) ? $paging['current'] : $defaultPage); + return (int)(isset($paging['current']) ? $paging['current'] : $defaultPage); } /** @@ -113,7 +142,6 @@ protected function getOffset($paging) */ protected function getSize($paging) { - $defaultLimit = $this->getData('config/pageSize') ?: 20; - return (int) (isset($paging['pageSize']) ? $paging['pageSize'] : $defaultLimit); + return (int)(isset($paging['pageSize']) ? $paging['pageSize'] : $this->getData('config/pageSize')); } } diff --git a/app/code/Magento/Ui/Test/Unit/Component/PagingTest.php b/app/code/Magento/Ui/Test/Unit/Component/PagingTest.php index 44dca689eef99..97df719ef14cb 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/PagingTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/PagingTest.php @@ -81,31 +81,11 @@ public function testPrepare() ], 'config' => [ 'options' => [ - [ - 'value' => 20, - 'label' => 20 - ], - [ - 'value' => 30, - 'label' => 30 - ], - [ - 'value' => 50, - 'label' => 50 - ], - [ - 'value' => 100, - 'label' => 100 - ], - [ - 'value' => 200, - 'label' => 200 - ], - [ + 'options1' => [ 'value' => 20, 'label' => 'options1' ], - [ + 'options2' => [ 'value' => 40, 'label' => 'options2' ], diff --git a/app/code/Magento/Ui/view/base/web/js/grid/paging/paging.js b/app/code/Magento/Ui/view/base/web/js/grid/paging/paging.js index 8e6f1496495c7..534d292809ed1 100644 --- a/app/code/Magento/Ui/view/base/web/js/grid/paging/paging.js +++ b/app/code/Magento/Ui/view/base/web/js/grid/paging/paging.js @@ -20,7 +20,6 @@ define([ template: 'ui/grid/paging/paging', totalTmpl: 'ui/grid/paging-total', totalRecords: 0, - pageSize: 20, pages: 1, current: 1, selectProvider: 'ns = ${ $.ns }, index = ids', @@ -35,7 +34,6 @@ define([ }, imports: { - pageSize: '${ $.sizesConfig.name }:value', totalSelected: '${ $.selectProvider }:totalSelected', totalRecords: '${ $.provider }:data.totalRecords', filters: '${ $.provider }:params.filters' @@ -46,6 +44,11 @@ define([ current: '${ $.provider }:params.paging.current' }, + links: { + options: '${ $.sizesConfig.name }:options', + pageSize: '${ $.sizesConfig.name }:value' + }, + statefull: { pageSize: true, current: true @@ -231,10 +234,10 @@ define([ * previous and current page size values. */ updateCursor: function () { - var cursor = this.current - 1, - size = this.pageSize, + var cursor = this.current - 1, + size = this.pageSize, oldSize = _.isUndefined(this.previousSize) ? this.pageSize : this.previousSize, - delta = cursor * (oldSize - size) / size; + delta = cursor * (oldSize - size) / size; delta = size > oldSize ? Math.ceil(delta) : diff --git a/app/code/Magento/Ui/view/base/web/js/grid/paging/sizes.js b/app/code/Magento/Ui/view/base/web/js/grid/paging/sizes.js index 4941eabbc4ee6..3af5c196173b8 100644 --- a/app/code/Magento/Ui/view/base/web/js/grid/paging/sizes.js +++ b/app/code/Magento/Ui/view/base/web/js/grid/paging/sizes.js @@ -17,31 +17,8 @@ define([ return Element.extend({ defaults: { template: 'ui/grid/paging/sizes', - value: 20, minSize: 1, maxSize: 999, - options: { - '20': { - value: 20, - label: 20 - }, - '30': { - value: 30, - label: 30 - }, - '50': { - value: 50, - label: 50 - }, - '100': { - value: 100, - label: 100 - }, - '200': { - value: 200, - label: 200 - } - }, statefull: { options: true, value: true diff --git a/lib/internal/Magento/Framework/View/Layout/Generator/UiComponent.php b/lib/internal/Magento/Framework/View/Layout/Generator/UiComponent.php index b82e79806acf9..233b97baeef0c 100644 --- a/lib/internal/Magento/Framework/View/Layout/Generator/UiComponent.php +++ b/lib/internal/Magento/Framework/View/Layout/Generator/UiComponent.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Framework\View\Layout\Generator; use Magento\Framework\View\Element\BlockFactory; @@ -60,7 +61,7 @@ public function __construct( } /** - * {@inheritdoc} + * @inheritdoc */ public function getType() { @@ -85,8 +86,6 @@ public function process(ReaderContext $readerContext, GeneratorContext $generato $layout = $generatorContext->getLayout(); // Instantiate blocks and collect all actions data - /** @var $blocks \Magento\Framework\View\Element\AbstractBlock[] */ - $blocks = []; foreach ($scheduledElements as $elementName => $element) { list($elementType, $data) = $element; @@ -94,9 +93,10 @@ public function process(ReaderContext $readerContext, GeneratorContext $generato continue; } - $block = $this->generateComponent($structure, $elementName, $data, $layout); - $blocks[$elementName] = $block; - $layout->setBlock($elementName, $block); + $layout->setBlock( + $elementName, + $this->generateComponent($structure, $elementName, $data, $layout) + ); $scheduledStructure->unsetElement($elementName); } From 53c472a32d6c21bafac344999361008f7a7ae43f Mon Sep 17 00:00:00 2001 From: Dmytro Yushkin Date: Mon, 24 Jun 2019 11:10:06 -0500 Subject: [PATCH 2064/2092] MC-17459: Coupon's expiration date and time do not match staging update end_date after creating a staging update - Removed deprecation of coupon expiration date usage in Magento 2.2 due to backward compatibility rules --- app/code/Magento/SalesRule/Api/Data/CouponInterface.php | 2 -- app/code/Magento/SalesRule/Model/Coupon.php | 5 ----- 2 files changed, 7 deletions(-) diff --git a/app/code/Magento/SalesRule/Api/Data/CouponInterface.php b/app/code/Magento/SalesRule/Api/Data/CouponInterface.php index 8ca4b00bf4ba8..327b3ffa7b725 100644 --- a/app/code/Magento/SalesRule/Api/Data/CouponInterface.php +++ b/app/code/Magento/SalesRule/Api/Data/CouponInterface.php @@ -108,7 +108,6 @@ public function setTimesUsed($timesUsed); * Get expiration date * * @return string|null - * @deprecated Coupon expiration must follow sales rule expiration date. */ public function getExpirationDate(); @@ -117,7 +116,6 @@ public function getExpirationDate(); * * @param string $expirationDate * @return $this - * @deprecated Coupon expiration must follow sales rule expiration date. */ public function setExpirationDate($expirationDate); diff --git a/app/code/Magento/SalesRule/Model/Coupon.php b/app/code/Magento/SalesRule/Model/Coupon.php index 600e18cf2c184..ee1eaff08303c 100644 --- a/app/code/Magento/SalesRule/Model/Coupon.php +++ b/app/code/Magento/SalesRule/Model/Coupon.php @@ -20,9 +20,6 @@ class Coupon extends \Magento\Framework\Model\AbstractExtensibleModel implements const KEY_USAGE_LIMIT = 'usage_limit'; const KEY_USAGE_PER_CUSTOMER = 'usage_per_customer'; const KEY_TIMES_USED = 'times_used'; - /** - * @deprecated Coupon expiration must follow sales rule expiration date. - */ const KEY_EXPIRATION_DATE = 'expiration_date'; const KEY_IS_PRIMARY = 'is_primary'; const KEY_CREATED_AT = 'created_at'; @@ -205,7 +202,6 @@ public function setTimesUsed($timesUsed) * Get expiration date * * @return string|null - * @deprecated Coupon expiration must follow sales rule expiration date. */ public function getExpirationDate() { @@ -217,7 +213,6 @@ public function getExpirationDate() * * @param string $expirationDate * @return $this - * @deprecated Coupon expiration must follow sales rule expiration date. */ public function setExpirationDate($expirationDate) { From 2ca4dbe918edcb55020847086e29432b48f506b3 Mon Sep 17 00:00:00 2001 From: Pavel Bystritsky Date: Wed, 26 Jun 2019 11:03:11 +0300 Subject: [PATCH 2065/2092] magento/magento2#23332: Static test fixed. --- .../view/adminhtml/templates/order/create/coupons/form.phtml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml index bfa775f41d988..188587588897e 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/create/coupons/form.phtml @@ -10,11 +10,11 @@
    - getCouponCode()): ?> + getCouponCode()) : ?> getButtonHtml(__('Apply'), 'order.applyCoupon($F(\'coupons:code\'))') ?> - getCouponCode()): ?> + getCouponCode()) : ?>

    escapeHtml($block->getCouponCode()) ?> Date: Tue, 18 Jun 2019 15:55:02 +0100 Subject: [PATCH 2066/2092] Added function to check against running/pending/successful cron tasks Added type missing for static call Updated static code tests again --- .../Observer/ProcessCronQueueObserver.php | 62 ++++++++++++++----- 1 file changed, 46 insertions(+), 16 deletions(-) diff --git a/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php b/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php index c8dcd8049fbe8..84be5f73a9272 100644 --- a/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php +++ b/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php @@ -332,16 +332,21 @@ protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule, $this->stopProfiling(); } - $schedule->setStatus(Schedule::STATUS_SUCCESS)->setFinishedAt(strftime( - '%Y-%m-%d %H:%M:%S', - $this->dateTime->gmtTimestamp() - )); - - $this->logger->info(sprintf( - 'Cron Job %s is successfully finished. Statistics: %s', - $jobCode, - $this->getProfilingStat() - )); + $schedule->setStatus( + Schedule::STATUS_SUCCESS)->setFinishedAt( + strftime( + '%Y-%m-%d %H:%M:%S', + $this->dateTime->gmtTimestamp() + ) + ); + + $this->logger->info( + sprintf( + 'Cron Job %s is successfully finished. Statistics: %s', + $jobCode, + $this->getProfilingStat() + ) + ); } /** @@ -391,6 +396,28 @@ private function getPendingSchedules($groupId) return $pendingJobs; } + /** + * Return job collection from database with status 'pending', 'running' or 'success' + * + * @param string $groupId + * @return \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection + */ + private function getNonExitedSchedules($groupId) + { + $jobs = $this->_config->getJobs(); + $pendingJobs = $this->_scheduleFactory->create()->getCollection(); + $pendingJobs->addFieldToFilter( + 'status', + [ + 'in' => [ + Schedule::STATUS_PENDING, Schedule::STATUS_RUNNING, Schedule::STATUS_SUCCESS + ] + ] + ); + $pendingJobs->addFieldToFilter('job_code', ['in' => array_keys($jobs[$groupId])]); + return $pendingJobs; + } + /** * Generate cron schedule * @@ -422,7 +449,7 @@ private function generateSchedules($groupId) null ); - $schedules = $this->getPendingSchedules($groupId); + $schedules = $this->getNonExitedSchedules($groupId); $exists = []; /** @var Schedule $schedule */ foreach ($schedules as $schedule) { @@ -653,11 +680,14 @@ private function cleanupScheduleMismatches() /** @var \Magento\Cron\Model\ResourceModel\Schedule $scheduleResource */ $scheduleResource = $this->_scheduleFactory->create()->getResource(); foreach ($this->invalid as $jobCode => $scheduledAtList) { - $scheduleResource->getConnection()->delete($scheduleResource->getMainTable(), [ - 'status = ?' => Schedule::STATUS_PENDING, - 'job_code = ?' => $jobCode, - 'scheduled_at in (?)' => $scheduledAtList, - ]); + $scheduleResource->getConnection()->delete( + $scheduleResource->getMainTable(), + [ + 'status = ?' => Schedule::STATUS_PENDING, + 'job_code = ?' => $jobCode, + 'scheduled_at in (?)' => $scheduledAtList, + ] + ); } return $this; } From ff568ac7ceb868cf71a444066be20c9be106b2ba Mon Sep 17 00:00:00 2001 From: Pavel Bystritsky Date: Fri, 21 Jun 2019 12:54:39 +0300 Subject: [PATCH 2067/2092] magento/magento2#23312: Static test fix. --- .../Observer/ProcessCronQueueObserver.php | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php b/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php index 84be5f73a9272..6008d4ebce218 100644 --- a/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php +++ b/app/code/Magento/Cron/Observer/ProcessCronQueueObserver.php @@ -3,16 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - /** * Handling cron jobs */ namespace Magento\Cron\Observer; +use Magento\Cron\Model\Schedule; use Magento\Framework\App\State; use Magento\Framework\Console\Cli; use Magento\Framework\Event\ObserverInterface; -use \Magento\Cron\Model\Schedule; use Magento\Framework\Profiler\Driver\Standard\Stat; use Magento\Framework\Profiler\Driver\Standard\StatFactory; @@ -201,7 +200,6 @@ public function __construct( */ public function execute(\Magento\Framework\Event\Observer $observer) { - $currentTime = $this->dateTime->gmtTimestamp(); $jobGroupsRoot = $this->_config->getJobs(); // sort jobs groups to start from used in separated process @@ -255,7 +253,6 @@ function ($groupId) use ($currentTime, $jobsRoot) { */ private function lockGroup($groupId, callable $callback) { - if (!$this->lockManager->lock(self::LOCK_PREFIX . $groupId, self::LOCK_TIMEOUT)) { $this->logger->warning( sprintf( @@ -290,17 +287,20 @@ protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule, $scheduleLifetime = $scheduleLifetime * self::SECONDS_IN_MINUTE; if ($scheduledTime < $currentTime - $scheduleLifetime) { $schedule->setStatus(Schedule::STATUS_MISSED); + // phpcs:ignore Magento2.Exceptions.DirectThrow throw new \Exception(sprintf('Cron Job %s is missed at %s', $jobCode, $schedule->getScheduledAt())); } if (!isset($jobConfig['instance'], $jobConfig['method'])) { $schedule->setStatus(Schedule::STATUS_ERROR); - throw new \Exception('No callbacks found'); + // phpcs:ignore Magento2.Exceptions.DirectThrow + throw new \Exception(sprintf('No callbacks found for cron job %s', $jobCode)); } $model = $this->_objectManager->create($jobConfig['instance']); $callback = [$model, $jobConfig['method']]; if (!is_callable($callback)) { $schedule->setStatus(Schedule::STATUS_ERROR); + // phpcs:ignore Magento2.Exceptions.DirectThrow throw new \Exception( sprintf('Invalid callback: %s::%s can\'t be called', $jobConfig['instance'], $jobConfig['method']) ); @@ -311,15 +311,18 @@ protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule, $this->startProfiling(); try { $this->logger->info(sprintf('Cron Job %s is run', $jobCode)); + //phpcs:ignore Magento2.Functions.DiscouragedFunction call_user_func_array($callback, [$schedule]); } catch (\Throwable $e) { $schedule->setStatus(Schedule::STATUS_ERROR); - $this->logger->error(sprintf( - 'Cron Job %s has an error: %s. Statistics: %s', - $jobCode, - $e->getMessage(), - $this->getProfilingStat() - )); + $this->logger->error( + sprintf( + 'Cron Job %s has an error: %s. Statistics: %s', + $jobCode, + $e->getMessage(), + $this->getProfilingStat() + ) + ); if (!$e instanceof \Exception) { $e = new \RuntimeException( 'Error when running a cron job', @@ -333,7 +336,8 @@ protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule, } $schedule->setStatus( - Schedule::STATUS_SUCCESS)->setFinishedAt( + Schedule::STATUS_SUCCESS + )->setFinishedAt( strftime( '%Y-%m-%d %H:%M:%S', $this->dateTime->gmtTimestamp() @@ -407,7 +411,7 @@ private function getNonExitedSchedules($groupId) $jobs = $this->_config->getJobs(); $pendingJobs = $this->_scheduleFactory->create()->getCollection(); $pendingJobs->addFieldToFilter( - 'status', + 'status', [ 'in' => [ Schedule::STATUS_PENDING, Schedule::STATUS_RUNNING, Schedule::STATUS_SUCCESS From 024d243c5f1d3a935187389cb58b609c3e79f775 Mon Sep 17 00:00:00 2001 From: Anthoula Wojczak Date: Thu, 27 Jun 2019 10:53:45 -0500 Subject: [PATCH 2068/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - clean up code --- .../System/Config/CollectionTimeLabelTest.php | 9 +++++---- .../Test/Unit/Block/Adminhtml/Queue/PreviewTest.php | 12 +++++------- .../Unit/Block/Adminhtml/Template/PreviewTest.php | 4 +--- 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php index 48909208fb2ad..1a06b309beb5e 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php @@ -43,10 +43,11 @@ protected function setUp() $objectManager = new ObjectManager($this); $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); - $reflection = new \ReflectionClass($this->abstractElementMock); - $reflection_property = $reflection->getProperty('_escaper'); - $reflection_property->setAccessible(true); - $reflection_property->setValue($this->abstractElementMock, $escaper); + $objectManager->setBackwardCompatibleProperty( + $this->abstractElementMock, + '_escaper', + $escaper + ); $this->contextMock = $this->getMockBuilder(Context::class) ->setMethods(['getLocaleDate']) diff --git a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php index b64453594df41..b0989569d9d4a 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Queue/PreviewTest.php @@ -107,13 +107,11 @@ public function testToHtmlEmpty() public function testToHtmlWithId() { - $this->request->expects($this->any())->method('getParam')->will( - $this->returnValueMap( - [ - ['id', null, 1], - ['store_id', null, 0] - ] - ) + $this->request->expects($this->any())->method('getParam')->willReturnMap( + [ + ['id', null, 1], + ['store_id', null, 0] + ] ); $this->queue->expects($this->once())->method('load')->will($this->returnSelf()); $this->template->expects($this->any())->method('isPlain')->will($this->returnValue(true)); diff --git a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php index 87fbca55e154e..26cf59d99a18e 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php @@ -60,9 +60,7 @@ protected function setUp() ); $this->objectManagerHelper = new ObjectManagerHelper($this); - $escaper = $this->objectManagerHelper->getObject( - \Magento\Framework\Escaper::class - ); + $escaper = $this->createMock(\Magento\Framework\Escaper::class); $this->preview = $this->objectManagerHelper->getObject( \Magento\Newsletter\Block\Adminhtml\Template\Preview::class, [ From 77b04c62bfe03ad9aba9b99d88e6378c51945661 Mon Sep 17 00:00:00 2001 From: Anthoula Wojczak Date: Thu, 27 Jun 2019 11:02:45 -0500 Subject: [PATCH 2069/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - clean up code --- .../Test/Unit/Block/Adminhtml/Template/PreviewTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php index 26cf59d99a18e..f4e120b6f0e4d 100644 --- a/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php +++ b/app/code/Magento/Newsletter/Test/Unit/Block/Adminhtml/Template/PreviewTest.php @@ -7,6 +7,7 @@ use Magento\Framework\App\TemplateTypesInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\Escaper; /** * Test for \Magento\Newsletter\Block\Adminhtml\Template\Preview @@ -60,7 +61,7 @@ protected function setUp() ); $this->objectManagerHelper = new ObjectManagerHelper($this); - $escaper = $this->createMock(\Magento\Framework\Escaper::class); + $escaper = new Escaper(); $this->preview = $this->objectManagerHelper->getObject( \Magento\Newsletter\Block\Adminhtml\Template\Preview::class, [ From 39b3f3a8f267dba70a7ed039794ff73f1a610d1d Mon Sep 17 00:00:00 2001 From: Anthoula Wojczak Date: Thu, 27 Jun 2019 11:41:34 -0500 Subject: [PATCH 2070/2092] MC-16926: [Backport for 2.2.x] Use Escaper methods - clean up code --- .../System/Config/SubscriptionStatusLabelTest.php | 9 +++++---- .../Block/Adminhtml/System/Config/VerticalTest.php | 9 +++++---- .../Customer/Test/Unit/Model/Renderer/RegionTest.php | 9 +++++---- .../System/Config/Field/Enable/AbstractEnableTest.php | 11 +++++------ 4 files changed, 20 insertions(+), 18 deletions(-) diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php index 9162554ae6843..48b2d4ee33e7f 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php @@ -57,10 +57,11 @@ protected function setUp() $objectManager = new ObjectManager($this); $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); - $reflection = new \ReflectionClass($this->abstractElementMock); - $reflection_property = $reflection->getProperty('_escaper'); - $reflection_property->setAccessible(true); - $reflection_property->setValue($this->abstractElementMock, $escaper); + $objectManager->setBackwardCompatibleProperty( + $this->abstractElementMock, + '_escaper', + $escaper + ); $this->formMock = $this->getMockBuilder(Form::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php index 1adbef416f067..06a12414a8126 100644 --- a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php @@ -42,10 +42,11 @@ protected function setUp() $objectManager = new ObjectManager($this); $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); - $reflection = new \ReflectionClass($this->abstractElementMock); - $reflection_property = $reflection->getProperty('_escaper'); - $reflection_property->setAccessible(true); - $reflection_property->setValue($this->abstractElementMock, $escaper); + $objectManager->setBackwardCompatibleProperty( + $this->abstractElementMock, + '_escaper', + $escaper + ); $this->contextMock = $this->getMockBuilder(Context::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php b/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php index 306fce8a15c02..0f0fb9f29eb2c 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Renderer/RegionTest.php @@ -63,10 +63,11 @@ public function testRender($regionCollection) $objectManager = new ObjectManager($this); $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); - $reflection = new \ReflectionClass($elementMock); - $reflection_property = $reflection->getProperty('_escaper'); - $reflection_property->setAccessible(true); - $reflection_property->setValue($elementMock, $escaper); + $objectManager->setBackwardCompatibleProperty( + $elementMock, + '_escaper', + $escaper + ); $formMock->expects( $this->any() diff --git a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php index 37acb12cc5e24..1aba699aefaad 100644 --- a/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Block/Adminhtml/System/Config/Field/Enable/AbstractEnableTest.php @@ -33,8 +33,6 @@ class AbstractEnableTest extends \PHPUnit\Framework\TestCase */ protected function setUp() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class) ->setMethods( [ @@ -48,10 +46,11 @@ protected function setUp() $objectManager = new ObjectManager($this); $escaper = $objectManager->getObject(\Magento\Framework\Escaper::class); - $reflection = new \ReflectionClass($this->elementMock); - $reflection_property = $reflection->getProperty('_escaper'); - $reflection_property->setAccessible(true); - $reflection_property->setValue($this->elementMock, $escaper); + $objectManager->setBackwardCompatibleProperty( + $this->elementMock, + '_escaper', + $escaper + ); $this->abstractEnable = $objectManager->getObject( \Magento\Paypal\Test\Unit\Block\Adminhtml\System\Config\Field\Enable\AbstractEnable\Stub::class, From 4277e3eac3fb85bacfde346848524f93bba7a300 Mon Sep 17 00:00:00 2001 From: Harald Deiser Date: Thu, 27 Jun 2019 19:23:49 +0200 Subject: [PATCH 2071/2092] MC-16395: Updated Composer file --- composer.lock | 66 +++++++++++++++++++++++++-------------------------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/composer.lock b/composer.lock index 6677cd4e4a514..b3e859ea015bf 100644 --- a/composer.lock +++ b/composer.lock @@ -1550,7 +1550,7 @@ }, { "name": "symfony/css-selector", - "version": "v3.4.28", + "version": "v3.4.29", "source": { "type": "git", "url": "https://github.com/symfony/css-selector.git", @@ -1720,16 +1720,16 @@ }, { "name": "symfony/filesystem", - "version": "v3.4.28", + "version": "v3.4.29", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "acf99758b1df8e9295e6b85aa69f294565c9fedb" + "reference": "70adda061ef83bb7def63a17953dc41f203308a7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/acf99758b1df8e9295e6b85aa69f294565c9fedb", - "reference": "acf99758b1df8e9295e6b85aa69f294565c9fedb", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/70adda061ef83bb7def63a17953dc41f203308a7", + "reference": "70adda061ef83bb7def63a17953dc41f203308a7", "shasum": "" }, "require": { @@ -1766,20 +1766,20 @@ ], "description": "Symfony Filesystem Component", "homepage": "https://symfony.com", - "time": "2019-02-04T21:34:32+00:00" + "time": "2019-06-23T09:29:17+00:00" }, { "name": "symfony/finder", - "version": "v3.4.28", + "version": "v3.4.29", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "fa5d962a71f2169dfe1cbae217fa5a2799859f6c" + "reference": "5f80266a729e30bbcc37f8bf0e62c3d5a38c8208" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/fa5d962a71f2169dfe1cbae217fa5a2799859f6c", - "reference": "fa5d962a71f2169dfe1cbae217fa5a2799859f6c", + "url": "https://api.github.com/repos/symfony/finder/zipball/5f80266a729e30bbcc37f8bf0e62c3d5a38c8208", + "reference": "5f80266a729e30bbcc37f8bf0e62c3d5a38c8208", "shasum": "" }, "require": { @@ -1815,7 +1815,7 @@ ], "description": "Symfony Finder Component", "homepage": "https://symfony.com", - "time": "2019-05-24T12:25:55+00:00" + "time": "2019-05-30T15:47:52+00:00" }, { "name": "symfony/polyfill-ctype", @@ -8314,16 +8314,16 @@ }, { "name": "symfony/browser-kit", - "version": "v3.4.28", + "version": "v3.4.29", "source": { "type": "git", "url": "https://github.com/symfony/browser-kit.git", - "reference": "7f2b0843d5045468225f9a9b27a0cb171ae81828" + "reference": "53266c9a1536e2dc673eb1efb6a6142ef84c6282" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/browser-kit/zipball/7f2b0843d5045468225f9a9b27a0cb171ae81828", - "reference": "7f2b0843d5045468225f9a9b27a0cb171ae81828", + "url": "https://api.github.com/repos/symfony/browser-kit/zipball/53266c9a1536e2dc673eb1efb6a6142ef84c6282", + "reference": "53266c9a1536e2dc673eb1efb6a6142ef84c6282", "shasum": "" }, "require": { @@ -8367,20 +8367,20 @@ ], "description": "Symfony BrowserKit Component", "homepage": "https://symfony.com", - "time": "2019-04-06T19:33:58+00:00" + "time": "2019-06-09T14:27:26+00:00" }, { "name": "symfony/config", - "version": "v3.4.28", + "version": "v3.4.29", "source": { "type": "git", "url": "https://github.com/symfony/config.git", - "reference": "177a276c01575253c95cefe0866e3d1b57637fe0" + "reference": "29a33f66194fbe2ed4555981810f15fd8440e4a8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/config/zipball/177a276c01575253c95cefe0866e3d1b57637fe0", - "reference": "177a276c01575253c95cefe0866e3d1b57637fe0", + "url": "https://api.github.com/repos/symfony/config/zipball/29a33f66194fbe2ed4555981810f15fd8440e4a8", + "reference": "29a33f66194fbe2ed4555981810f15fd8440e4a8", "shasum": "" }, "require": { @@ -8431,7 +8431,7 @@ ], "description": "Symfony Config Component", "homepage": "https://symfony.com", - "time": "2019-02-23T15:06:07+00:00" + "time": "2019-05-30T15:47:52+00:00" }, { "name": "symfony/dependency-injection", @@ -8505,16 +8505,16 @@ }, { "name": "symfony/dom-crawler", - "version": "v3.4.28", + "version": "v3.4.29", "source": { "type": "git", "url": "https://github.com/symfony/dom-crawler.git", - "reference": "d40023c057393fb25f7ca80af2a56ed948c45a09" + "reference": "adb96e63af6fb0cc721cc69861001d60d0133d0c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/d40023c057393fb25f7ca80af2a56ed948c45a09", - "reference": "d40023c057393fb25f7ca80af2a56ed948c45a09", + "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/adb96e63af6fb0cc721cc69861001d60d0133d0c", + "reference": "adb96e63af6fb0cc721cc69861001d60d0133d0c", "shasum": "" }, "require": { @@ -8558,20 +8558,20 @@ ], "description": "Symfony DomCrawler Component", "homepage": "https://symfony.com", - "time": "2019-02-23T15:06:07+00:00" + "time": "2019-05-30T15:47:52+00:00" }, { "name": "symfony/http-foundation", - "version": "v3.4.28", + "version": "v3.4.29", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "677ae5e892b081e71a665bfa7dd90fe61800c00e" + "reference": "8cfbf75bb3a72963b12c513a73e9247891df24f8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/677ae5e892b081e71a665bfa7dd90fe61800c00e", - "reference": "677ae5e892b081e71a665bfa7dd90fe61800c00e", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/8cfbf75bb3a72963b12c513a73e9247891df24f8", + "reference": "8cfbf75bb3a72963b12c513a73e9247891df24f8", "shasum": "" }, "require": { @@ -8612,11 +8612,11 @@ ], "description": "Symfony HttpFoundation Component", "homepage": "https://symfony.com", - "time": "2019-05-27T05:50:24+00:00" + "time": "2019-06-22T20:10:25+00:00" }, { "name": "symfony/options-resolver", - "version": "v3.4.28", + "version": "v3.4.29", "source": { "type": "git", "url": "https://github.com/symfony/options-resolver.git", @@ -8898,7 +8898,7 @@ }, { "name": "symfony/stopwatch", - "version": "v3.4.28", + "version": "v3.4.29", "source": { "type": "git", "url": "https://github.com/symfony/stopwatch.git", From 82d3b7161b68ae50459e4439388022c29dd66037 Mon Sep 17 00:00:00 2001 From: Yurii Sapiha Date: Mon, 1 Jul 2019 18:04:34 +0300 Subject: [PATCH 2072/2092] magento/magento2 #23439 Fix-Unit-tests --- .../Test/Unit/Observer/ProcessCronQueueObserverTest.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/Cron/Test/Unit/Observer/ProcessCronQueueObserverTest.php b/app/code/Magento/Cron/Test/Unit/Observer/ProcessCronQueueObserverTest.php index d14249e6b0e57..f69cb13c17e47 100644 --- a/app/code/Magento/Cron/Test/Unit/Observer/ProcessCronQueueObserverTest.php +++ b/app/code/Magento/Cron/Test/Unit/Observer/ProcessCronQueueObserverTest.php @@ -354,7 +354,8 @@ public function testDispatchExceptionTooLate() */ public function testDispatchExceptionNoCallback() { - $exceptionMessage = 'No callbacks found'; + $jobCode = 'test_job1'; + $exceptionMessage = sprintf('No callbacks found for cron job %s', $jobCode); $exception = new \Exception(__($exceptionMessage)); $dateScheduledAt = date('Y-m-d H:i:s', $this->time - 86400); @@ -363,7 +364,7 @@ public function testDispatchExceptionNoCallback() )->setMethods( ['getJobCode', 'tryLockJob', 'getScheduledAt', 'save', 'setStatus', 'setMessages', '__wakeup', 'getStatus'] )->disableOriginalConstructor()->getMock(); - $schedule->expects($this->any())->method('getJobCode')->will($this->returnValue('test_job1')); + $schedule->expects($this->any())->method('getJobCode')->will($this->returnValue($jobCode)); $schedule->expects($this->once())->method('getScheduledAt')->will($this->returnValue($dateScheduledAt)); $schedule->expects($this->once())->method('tryLockJob')->will($this->returnValue(true)); $schedule->expects( @@ -383,7 +384,7 @@ public function testDispatchExceptionNoCallback() $this->loggerMock->expects($this->once())->method('critical')->with($exception); - $jobConfig = ['test_group' => ['test_job1' => ['instance' => 'Some_Class']]]; + $jobConfig = ['test_group' => [$jobCode => ['instance' => 'Some_Class']]]; $this->_config->expects($this->exactly(2))->method('getJobs')->will($this->returnValue($jobConfig)); From dfdbe7cc4b94c103ab66383577e13b91de395dff Mon Sep 17 00:00:00 2001 From: Graham Wharton Date: Tue, 2 Jul 2019 11:26:24 +0100 Subject: [PATCH 2073/2092] Update Framework/Mail::Message to send all emails as MIME, not just HTML emails. --- .../Magento/Framework/Mail/Message.php | 31 ++++++++++++++++--- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/lib/internal/Magento/Framework/Mail/Message.php b/lib/internal/Magento/Framework/Mail/Message.php index 96566ad82b8eb..d42f74943ee89 100644 --- a/lib/internal/Magento/Framework/Mail/Message.php +++ b/lib/internal/Magento/Framework/Mail/Message.php @@ -20,7 +20,7 @@ class Message implements MailMessageInterface * * @var string */ - private $messageType = self::TYPE_TEXT; + private $messageType = Mime::TYPE_TEXT; /** * Initialize dependencies. @@ -55,8 +55,8 @@ public function setMessageType($type) */ public function setBody($body) { - if (is_string($body) && $this->messageType === MailMessageInterface::TYPE_HTML) { - $body = $this->createHtmlMimeFromString($body); + if (is_string($body)) { + $body = $this->createMimeFromString($body, $this->messageType); } $this->zendMessage->setBody($body); return $this; @@ -158,7 +158,7 @@ public function getRawMessage() */ public function setBodyHtml($html) { - $this->setMessageType(self::TYPE_HTML); + $this->setMessageType(Mime::TYPE_HTML); return $this->setBody($html); } @@ -167,7 +167,7 @@ public function setBodyHtml($html) */ public function setBodyText($text) { - $this->setMessageType(self::TYPE_TEXT); + $this->setMessageType(Mime::TYPE_TEXT); return $this->setBody($text); } @@ -176,6 +176,10 @@ public function setBodyText($text) * * @param string $htmlBody * @return \Zend\Mime\Message + * + * @deprecated All emails that Magento sends should be mime encoded. Therefore + * use generic function createMimeFromString + * @see createMimeFromString() */ private function createHtmlMimeFromString($htmlBody) { @@ -186,4 +190,21 @@ private function createHtmlMimeFromString($htmlBody) $mimeMessage->addPart($htmlPart); return $mimeMessage; } + + /** + * Create mime message from the string. + * + * @param string $body + * @param string $messageType + * @return \Zend\Mime\Message + */ + private function createMimeFromString($body, $messageType) + { + $part = new Part($body); + $part->setCharset($this->zendMessage->getEncoding()); + $part->setType($messageType); + $mimeMessage = new \Zend\Mime\Message(); + $mimeMessage->addPart($part); + return $mimeMessage; + } } From e6fbf99d409eb77e86266e008ff23db9276f3fb2 Mon Sep 17 00:00:00 2001 From: Graham Wharton Date: Tue, 2 Jul 2019 12:27:09 +0100 Subject: [PATCH 2074/2092] Updated unit test --- .../Framework/Mail/Test/Unit/MessageTest.php | 37 ++++++++----------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/lib/internal/Magento/Framework/Mail/Test/Unit/MessageTest.php b/lib/internal/Magento/Framework/Mail/Test/Unit/MessageTest.php index 0c33e25e0d9d0..478998230a276 100644 --- a/lib/internal/Magento/Framework/Mail/Test/Unit/MessageTest.php +++ b/lib/internal/Magento/Framework/Mail/Test/Unit/MessageTest.php @@ -8,41 +8,34 @@ class MessageTest extends \PHPUnit\Framework\TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Mail\Message + * @var \Magento\Framework\Mail\Message */ - protected $_messageMock; + protected $message; protected function setUp() { - $this->_messageMock = $this->createPartialMock( - \Magento\Framework\Mail\Message::class, - ['setBody', 'setMessageType'] - ); + $this->message = new \Magento\Framework\Mail\Message(); } public function testSetBodyHtml() { - $this->_messageMock->expects($this->once()) - ->method('setMessageType') - ->with('text/html'); + $this->message->setBodyHtml('body'); - $this->_messageMock->expects($this->once()) - ->method('setBody') - ->with('body'); - - $this->_messageMock->setBodyHtml('body'); + $part = $this->message->getBody()->getParts()[0]; + $this->assertEquals('text/html', $part->getType()); + $this->assertEquals('8bit', $part->getEncoding()); + $this->assertEquals('utf-8', $part->getCharset()); + $this->assertEquals('body', $part->getContent()); } public function testSetBodyText() { - $this->_messageMock->expects($this->once()) - ->method('setMessageType') - ->with('text/plain'); - - $this->_messageMock->expects($this->once()) - ->method('setBody') - ->with('body'); + $this->message->setBodyText('body'); - $this->_messageMock->setBodyText('body'); + $part = $this->message->getBody()->getParts()[0]; + $this->assertEquals('text/plain', $part->getType()); + $this->assertEquals('8bit', $part->getEncoding()); + $this->assertEquals('utf-8', $part->getCharset()); + $this->assertEquals('body', $part->getContent()); } } From 6874f6158e17902809b91659783c597864d2ec16 Mon Sep 17 00:00:00 2001 From: Geeta Date: Tue, 25 Jun 2019 16:07:26 +0530 Subject: [PATCH 2075/2092] Fixed issue #23377 --- .../Checkout/view/frontend/templates/cart/minicart.phtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Checkout/view/frontend/templates/cart/minicart.phtml b/app/code/Magento/Checkout/view/frontend/templates/cart/minicart.phtml index 8928bbabcb718..28275e0223936 100644 --- a/app/code/Magento/Checkout/view/frontend/templates/cart/minicart.phtml +++ b/app/code/Magento/Checkout/view/frontend/templates/cart/minicart.phtml @@ -12,7 +12,7 @@ data-bind="scope: 'minicart_content'"> escapeHtml(__('My Cart')) ?> + data-bind="css: { empty: !!getCartParam('summary_count') == false && !isLoading() }, blockLoader: isLoading"> From 235cabaa912aba3ba3b5f0b96ef6ab0105859c27 Mon Sep 17 00:00:00 2001 From: Graham Wharton Date: Tue, 2 Jul 2019 13:14:37 +0100 Subject: [PATCH 2076/2092] Fixed coding standards violations --- .../Magento/Framework/Mail/Message.php | 20 ------------------- .../Framework/Mail/Test/Unit/MessageTest.php | 3 +++ 2 files changed, 3 insertions(+), 20 deletions(-) diff --git a/lib/internal/Magento/Framework/Mail/Message.php b/lib/internal/Magento/Framework/Mail/Message.php index d42f74943ee89..1156a047ba370 100644 --- a/lib/internal/Magento/Framework/Mail/Message.php +++ b/lib/internal/Magento/Framework/Mail/Message.php @@ -171,26 +171,6 @@ public function setBodyText($text) return $this->setBody($text); } - /** - * Create HTML mime message from the string. - * - * @param string $htmlBody - * @return \Zend\Mime\Message - * - * @deprecated All emails that Magento sends should be mime encoded. Therefore - * use generic function createMimeFromString - * @see createMimeFromString() - */ - private function createHtmlMimeFromString($htmlBody) - { - $htmlPart = new Part($htmlBody); - $htmlPart->setCharset($this->zendMessage->getEncoding()); - $htmlPart->setType(Mime::TYPE_HTML); - $mimeMessage = new \Zend\Mime\Message(); - $mimeMessage->addPart($htmlPart); - return $mimeMessage; - } - /** * Create mime message from the string. * diff --git a/lib/internal/Magento/Framework/Mail/Test/Unit/MessageTest.php b/lib/internal/Magento/Framework/Mail/Test/Unit/MessageTest.php index 478998230a276..bea2a9ea91d38 100644 --- a/lib/internal/Magento/Framework/Mail/Test/Unit/MessageTest.php +++ b/lib/internal/Magento/Framework/Mail/Test/Unit/MessageTest.php @@ -5,6 +5,9 @@ */ namespace Magento\Framework\Mail\Test\Unit; +/** + * test Magento\Framework\Mail\Message + */ class MessageTest extends \PHPUnit\Framework\TestCase { /** From 0a9418f704c1f8597fd2c2c943b817149848e79b Mon Sep 17 00:00:00 2001 From: bobemoe Date: Tue, 2 Jul 2019 19:02:08 +0100 Subject: [PATCH 2077/2092] fix nav breakpoint issue (backports #23528) --- lib/web/mage/menu.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/web/mage/menu.js b/lib/web/mage/menu.js index 6446fef4c56f3..839730c9ea600 100644 --- a/lib/web/mage/menu.js +++ b/lib/web/mage/menu.js @@ -22,7 +22,7 @@ define([ showDelay: 42, hideDelay: 300, delay: 0, - mediaBreakpoint: '(max-width: 768px)' + mediaBreakpoint: '(max-width: 767px)' }, /** From d1cf785af8f5d508d2cb0d068b0944c1ccf6007f Mon Sep 17 00:00:00 2001 From: Surbhi Date: Sat, 4 May 2019 15:37:57 +0530 Subject: [PATCH 2078/2092] Fixed Issue #20234 --- .../luma/Magento_Catalog/web/css/source/module/_listings.less | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/design/frontend/Magento/luma/Magento_Catalog/web/css/source/module/_listings.less b/app/design/frontend/Magento/luma/Magento_Catalog/web/css/source/module/_listings.less index 6bf766b7400a7..b84c3f391121e 100644 --- a/app/design/frontend/Magento/luma/Magento_Catalog/web/css/source/module/_listings.less +++ b/app/design/frontend/Magento/luma/Magento_Catalog/web/css/source/module/_listings.less @@ -99,7 +99,7 @@ .reviews-actions { font-size: @font-size__s; margin-top: 5px; - text-transform: lowercase; + text-transform: none; } } From cf4be31ba12b07e96b48b21c7421f5987bc0de2b Mon Sep 17 00:00:00 2001 From: Surbhi Date: Tue, 14 May 2019 10:34:09 +0530 Subject: [PATCH 2079/2092] removing text transform --- .../luma/Magento_Catalog/web/css/source/module/_listings.less | 1 - 1 file changed, 1 deletion(-) diff --git a/app/design/frontend/Magento/luma/Magento_Catalog/web/css/source/module/_listings.less b/app/design/frontend/Magento/luma/Magento_Catalog/web/css/source/module/_listings.less index b84c3f391121e..6c0d4da83b8c5 100644 --- a/app/design/frontend/Magento/luma/Magento_Catalog/web/css/source/module/_listings.less +++ b/app/design/frontend/Magento/luma/Magento_Catalog/web/css/source/module/_listings.less @@ -99,7 +99,6 @@ .reviews-actions { font-size: @font-size__s; margin-top: 5px; - text-transform: none; } } From e90af0c5fd16b3b1c731433bb4008a9204014164 Mon Sep 17 00:00:00 2001 From: Surbhi Date: Thu, 16 May 2019 14:30:39 +0530 Subject: [PATCH 2080/2092] Removing text transform for blank theme --- .../blank/Magento_Catalog/web/css/source/module/_listings.less | 1 - 1 file changed, 1 deletion(-) diff --git a/app/design/frontend/Magento/blank/Magento_Catalog/web/css/source/module/_listings.less b/app/design/frontend/Magento/blank/Magento_Catalog/web/css/source/module/_listings.less index 951ca89a07988..f38b98c14b0b3 100644 --- a/app/design/frontend/Magento/blank/Magento_Catalog/web/css/source/module/_listings.less +++ b/app/design/frontend/Magento/blank/Magento_Catalog/web/css/source/module/_listings.less @@ -94,7 +94,6 @@ .reviews-actions { font-size: @font-size__s; margin-top: 5px; - text-transform: lowercase; } } From e1d04914dd26b22040b7ee53ff5f16d950e0c7fe Mon Sep 17 00:00:00 2001 From: Nishant Jariwala Date: Mon, 17 Jun 2019 17:08:22 +0530 Subject: [PATCH 2081/2092] Fixed button disabled although value is correct. --- .../templates/order/creditmemo/create/totals/adjustments.phtml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml index 187cb96f32aa0..fd2d737251c79 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/totals/adjustments.phtml @@ -68,6 +68,9 @@ enableElements('submit-button'); } }); + $(id).observe('change', function (event) { + enableElements('submit-button'); + }); } //]]> From 5a1ca956d52a0103d9df965b51a2d90803692ca5 Mon Sep 17 00:00:00 2001 From: sanjay Date: Mon, 6 May 2019 10:21:12 +0530 Subject: [PATCH 2082/2092] issue #22676 fixed - Compare Products counter, and My Wish List counter vertical not aligned --- app/design/frontend/Magento/luma/web/css/source/_extends.less | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/design/frontend/Magento/luma/web/css/source/_extends.less b/app/design/frontend/Magento/luma/web/css/source/_extends.less index d923bee0b7f8a..8a128b3967e25 100644 --- a/app/design/frontend/Magento/luma/web/css/source/_extends.less +++ b/app/design/frontend/Magento/luma/web/css/source/_extends.less @@ -1533,6 +1533,7 @@ .lib-css(color, @block-items__counter__color); .lib-font-size(12px); white-space: nowrap; + vertical-align: middle; &:before { content: '('; @@ -1555,6 +1556,7 @@ strong { font-size: @font-size__l; font-weight: @font-weight__light; + vertical-align: middle; } } } From 2a052552d2c86d15742f776836283f09e511df61 Mon Sep 17 00:00:00 2001 From: Nazarn96 Date: Wed, 8 May 2019 10:36:58 +0300 Subject: [PATCH 2083/2092] magento/magento2#22742 static-test-fix --- app/design/frontend/Magento/luma/web/css/source/_extends.less | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/design/frontend/Magento/luma/web/css/source/_extends.less b/app/design/frontend/Magento/luma/web/css/source/_extends.less index 8a128b3967e25..8621b7be2a931 100644 --- a/app/design/frontend/Magento/luma/web/css/source/_extends.less +++ b/app/design/frontend/Magento/luma/web/css/source/_extends.less @@ -1532,8 +1532,8 @@ .abs-block-items-counter { .lib-css(color, @block-items__counter__color); .lib-font-size(12px); - white-space: nowrap; vertical-align: middle; + white-space: nowrap; &:before { content: '('; From 0b5ee99cf568d29829b2e1b638283f7807c2966d Mon Sep 17 00:00:00 2001 From: Fanis Date: Tue, 18 Jun 2019 14:04:52 +0100 Subject: [PATCH 2084/2092] Fix modulo with less than a 1 value --- lib/web/mage/validation.js | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/web/mage/validation.js b/lib/web/mage/validation.js index d391760d4cc5c..a40a5f01e63bd 100644 --- a/lib/web/mage/validation.js +++ b/lib/web/mage/validation.js @@ -204,6 +204,21 @@ return empty === 0; } + /** + * + * @param {float} qty + * @param {float} qtyIncrements + * @returns {float} + */ + function resolveModulo(qty, qtyIncrements) { + while (qtyIncrements < 1) { + qty *= 10; + qtyIncrements *= 10; + } + + return qty % qtyIncrements; + } + /** * Collection of validation rules including rules from additional-methods.js * @type {Object} @@ -1608,7 +1623,7 @@ isMaxAllowedValid = typeof params.maxAllowed === 'undefined' || qty <= $.mage.parseNumber(params.maxAllowed), isQtyIncrementsValid = typeof params.qtyIncrements === 'undefined' || - qty % $.mage.parseNumber(params.qtyIncrements) === 0; + resolveModulo(qty, $.mage.parseNumber(params.qtyIncrements)) === 0.0; result = qty > 0; @@ -1637,7 +1652,7 @@ result = isQtyIncrementsValid; if (result === false) { - validator.itemQtyErrorMessage = $.mage.__('You can buy this product only in quantities of %1 at a time.').replace('%1', params.qtyIncrements);//eslint-disable-line max-len + validator.itemQtyErrorMessage = $.mage.__('You can buy this product only in quantities of fanis %1 at a time.').replace('%1', params.qtyIncrements);//eslint-disable-line max-len return result; } From 138b4cf31c6d499d2817c53c663710ce894c058a Mon Sep 17 00:00:00 2001 From: sertlab Date: Tue, 18 Jun 2019 14:21:58 +0100 Subject: [PATCH 2085/2092] revert texes to normall --- lib/web/mage/validation.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/web/mage/validation.js b/lib/web/mage/validation.js index a40a5f01e63bd..68b0c0f9f02fd 100644 --- a/lib/web/mage/validation.js +++ b/lib/web/mage/validation.js @@ -1652,7 +1652,7 @@ result = isQtyIncrementsValid; if (result === false) { - validator.itemQtyErrorMessage = $.mage.__('You can buy this product only in quantities of fanis %1 at a time.').replace('%1', params.qtyIncrements);//eslint-disable-line max-len + validator.itemQtyErrorMessage = $.mage.__('You can buy this product only in quantities of %1 at a time.').replace('%1', params.qtyIncrements);//eslint-disable-line max-len return result; } From ecfaea17beafdfbd77f831cee29a819cad6c98ef Mon Sep 17 00:00:00 2001 From: eduard13 Date: Wed, 12 Jun 2019 19:27:31 +0300 Subject: [PATCH 2086/2092] Calling the always action on opening and closing the modal. --- app/code/Magento/Ui/view/base/web/js/modal/alert.js | 1 - app/code/Magento/Ui/view/base/web/js/modal/confirm.js | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Ui/view/base/web/js/modal/alert.js b/app/code/Magento/Ui/view/base/web/js/modal/alert.js index 911d0e02578d2..4741f26ba2574 100644 --- a/app/code/Magento/Ui/view/base/web/js/modal/alert.js +++ b/app/code/Magento/Ui/view/base/web/js/modal/alert.js @@ -43,7 +43,6 @@ define([ * Close modal window. */ closeModal: function () { - this.options.actions.always(); this.element.bind('alertclosed', _.bind(this._remove, this)); return this._super(); diff --git a/app/code/Magento/Ui/view/base/web/js/modal/confirm.js b/app/code/Magento/Ui/view/base/web/js/modal/confirm.js index eceab940d1141..08a6fe2dc07c3 100644 --- a/app/code/Magento/Ui/view/base/web/js/modal/confirm.js +++ b/app/code/Magento/Ui/view/base/web/js/modal/confirm.js @@ -80,6 +80,8 @@ define([ * Open modal window. */ openModal: function () { + this.options.actions.always(); + return this._super(); }, From 371755171cde37b2ef96f3b24758e427c0b93893 Mon Sep 17 00:00:00 2001 From: eduard13 Date: Thu, 13 Jun 2019 15:10:36 +0300 Subject: [PATCH 2087/2092] Revert "Calling the always action on opening and closing the modal." This reverts commit 0c402aedc254ca85864008f54d5d4b2545b605d0. --- app/code/Magento/Ui/view/base/web/js/modal/alert.js | 1 + app/code/Magento/Ui/view/base/web/js/modal/confirm.js | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/app/code/Magento/Ui/view/base/web/js/modal/alert.js b/app/code/Magento/Ui/view/base/web/js/modal/alert.js index 4741f26ba2574..911d0e02578d2 100644 --- a/app/code/Magento/Ui/view/base/web/js/modal/alert.js +++ b/app/code/Magento/Ui/view/base/web/js/modal/alert.js @@ -43,6 +43,7 @@ define([ * Close modal window. */ closeModal: function () { + this.options.actions.always(); this.element.bind('alertclosed', _.bind(this._remove, this)); return this._super(); diff --git a/app/code/Magento/Ui/view/base/web/js/modal/confirm.js b/app/code/Magento/Ui/view/base/web/js/modal/confirm.js index 08a6fe2dc07c3..eceab940d1141 100644 --- a/app/code/Magento/Ui/view/base/web/js/modal/confirm.js +++ b/app/code/Magento/Ui/view/base/web/js/modal/confirm.js @@ -80,8 +80,6 @@ define([ * Open modal window. */ openModal: function () { - this.options.actions.always(); - return this._super(); }, From 18a3f7021c2a35cc353c5d2e142420fa6d57cc79 Mon Sep 17 00:00:00 2001 From: eduard13 Date: Thu, 13 Jun 2019 16:16:54 +0300 Subject: [PATCH 2088/2092] Calling the always action on creating the widget. --- app/code/Magento/Ui/view/base/web/js/modal/alert.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/code/Magento/Ui/view/base/web/js/modal/alert.js b/app/code/Magento/Ui/view/base/web/js/modal/alert.js index 911d0e02578d2..07b7230bd126f 100644 --- a/app/code/Magento/Ui/view/base/web/js/modal/alert.js +++ b/app/code/Magento/Ui/view/base/web/js/modal/alert.js @@ -39,6 +39,14 @@ define([ }] }, + /** + * Create widget. + */ + _create: function () { + this.options.actions.always(); + this._super(); + }, + /** * Close modal window. */ From fc35128073722d72670262ba7aeffb1e63d09704 Mon Sep 17 00:00:00 2001 From: eduard13 Date: Tue, 18 Jun 2019 11:54:52 +0300 Subject: [PATCH 2089/2092] Removing the always calling on closeModal --- app/code/Magento/Ui/view/base/web/js/modal/alert.js | 1 - 1 file changed, 1 deletion(-) diff --git a/app/code/Magento/Ui/view/base/web/js/modal/alert.js b/app/code/Magento/Ui/view/base/web/js/modal/alert.js index 07b7230bd126f..b63294e3d8750 100644 --- a/app/code/Magento/Ui/view/base/web/js/modal/alert.js +++ b/app/code/Magento/Ui/view/base/web/js/modal/alert.js @@ -51,7 +51,6 @@ define([ * Close modal window. */ closeModal: function () { - this.options.actions.always(); this.element.bind('alertclosed', _.bind(this._remove, this)); return this._super(); From 4499e604c50ac555e0cd8aa37c2926948697a813 Mon Sep 17 00:00:00 2001 From: Kajal Solanki Date: Wed, 20 Feb 2019 17:45:32 +0530 Subject: [PATCH 2090/2092] Resolved import design break issue resolved --- .../backend/web/css/source/forms/_fields.less | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less b/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less index 0218744b80a4d..7b299946817fb 100644 --- a/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less +++ b/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less @@ -32,6 +32,20 @@ width: @field-size__l; } +.admin__field { + &.field { + &.field-basic_behavior.with-addon { + .admin__field-control { + position: relative; + .mage-error { + position: absolute; + width: 100%; + } + } + } + } +} + .abs-field-sizes { &.admin__field-x-small { > .admin__field-control { From 34bc068276b6564c2d094bf11ead8972770446ba Mon Sep 17 00:00:00 2001 From: Kajal Solanki Date: Sat, 29 Jun 2019 11:35:33 +0530 Subject: [PATCH 2091/2092] fix tooltip designing issue --- .../backend/web/css/source/forms/_fields.less | 14 -------------- lib/web/mage/validation.js | 4 ++++ 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less b/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less index 7b299946817fb..0218744b80a4d 100644 --- a/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less +++ b/app/design/adminhtml/Magento/backend/web/css/source/forms/_fields.less @@ -32,20 +32,6 @@ width: @field-size__l; } -.admin__field { - &.field { - &.field-basic_behavior.with-addon { - .admin__field-control { - position: relative; - .mage-error { - position: absolute; - width: 100%; - } - } - } - } -} - .abs-field-sizes { &.admin__field-x-small { > .admin__field-control { diff --git a/lib/web/mage/validation.js b/lib/web/mage/validation.js index 68b0c0f9f02fd..3cb4b452aac3d 100644 --- a/lib/web/mage/validation.js +++ b/lib/web/mage/validation.js @@ -1877,6 +1877,10 @@ //logic for control with tooltip if (element.siblings('.tooltip').length) { errorPlacement = element.siblings('.tooltip'); + } + //logic for select with tooltip in after element + if (element.next().find('.tooltip').length) { + errorPlacement = element.next(); } errorPlacement.after(error); } From b8b8ad0880d11f82dc5e146c320225946caa2a3d Mon Sep 17 00:00:00 2001 From: Kajal Solanki Date: Sat, 29 Jun 2019 12:30:30 +0530 Subject: [PATCH 2092/2092] update validation.js --- lib/web/mage/validation.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/web/mage/validation.js b/lib/web/mage/validation.js index 3cb4b452aac3d..ea41ee38d9d3c 100644 --- a/lib/web/mage/validation.js +++ b/lib/web/mage/validation.js @@ -1878,7 +1878,7 @@ if (element.siblings('.tooltip').length) { errorPlacement = element.siblings('.tooltip'); } - //logic for select with tooltip in after element + //logic for select with tooltip in after element if (element.next().find('.tooltip').length) { errorPlacement = element.next(); }