_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q243900
Api.createRequest
validation
public function createRequest($version, $request) { $checkIfExists = $this->getRequest($version, $request['name']); $url = $this->_getApiServiceUri(). 'version/' .$version. '/request_settings'; if (!$checkIfExists) { $verb = \Zend_Http_Client::POST; } else { $verb = \Zend_Http_Client::PUT; $url .= '/'.$request['name']; } $result = $this->_fetch($url, $verb, $request); if (!$result) { throw new LocalizedException(__('Failed to create the REQUEST object.')); } }
php
{ "resource": "" }
q243901
Api.getRequest
validation
public function getRequest($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. $version. '/request_settings/' . $name; $result = $this->_fetch($url, \Zend_Http_Client::GET, '', false, null, false); return $result; }
php
{ "resource": "" }
q243902
Api.deleteRequest
validation
public function deleteRequest($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. $version. '/request_settings/' . $name; $result = $this->_fetch($url, \Zend_Http_Client::DELETE); if (!$result) { throw new LocalizedException(__('Failed to delete the REQUEST object.')); } }
php
{ "resource": "" }
q243903
Api.getBackends
validation
public function getBackends($version) { $url = $this->_getApiServiceUri(). 'version/'. $version. '/backend'; $result = $this->_fetch($url, \Zend_Http_Client::GET); return $result; }
php
{ "resource": "" }
q243904
Api.configureBackend
validation
public function configureBackend($params, $version, $old_name) { $url = $this->_getApiServiceUri() . 'version/' . $version . '/backend/' . str_replace(' ', '%20', $old_name); $result = $this->_fetch( $url, \Zend_Http_Client::PUT, $params ); return $result; }
php
{ "resource": "" }
q243905
Api.sendWebHook
validation
public function sendWebHook($message) { $url = $this->config->getIncomingWebhookURL(); $messagePrefix = $this->config->getWebhookMessagePrefix(); $currentUsername = 'System'; try { if ($this->state->getAreaCode() == 'adminhtml') { $getUser = $this->authSession->getUser(); if (!empty($getUser)) { $currentUsername = $getUser->getUserName(); } } } catch (\Exception $e) { $this->log->log(100, 'Failed to retrieve Area Code'); } $storeName = $this->helper->getStoreName(); $storeUrl = $this->helper->getStoreUrl(); $text = $messagePrefix.' user='.$currentUsername.' '.$message.' on <'.$storeUrl.'|Store> | '.$storeName; $headers = [ 'Content-type: application/json' ]; $body = json_encode([ "text" => $text, "username" => "fastly-magento-bot", "icon_emoji"=> ":airplane:" ]); $client = $this->curlFactory->create(); $client->addOption(CURLOPT_CONNECTTIMEOUT, 2); $client->addOption(CURLOPT_TIMEOUT, 3); $client->write(\Zend_Http_Client::POST, $url, '1.1', $headers, $body); $response = $client->read(); $responseCode = \Zend_Http_Response::extractCode($response); if ($responseCode != 200) { $this->log->log(100, 'Failed to send message to the following Webhook: '.$url); } $client->close(); }
php
{ "resource": "" }
q243906
Api.createDictionary
validation
public function createDictionary($version, $params) { $url = $this->_getApiServiceUri(). 'version/'. $version . '/dictionary'; $result = $this->_fetch($url, \Zend_Http_Client::POST, $params); return $result; }
php
{ "resource": "" }
q243907
Api.dictionaryItemsList
validation
public function dictionaryItemsList($dictionaryId) { $url = $this->_getApiServiceUri(). 'dictionary/'.$dictionaryId.'/items'; $result = $this->_fetch($url, \Zend_Http_Client::GET); return $result; }
php
{ "resource": "" }
q243908
Api.getSingleDictionary
validation
public function getSingleDictionary($version, $dictionaryName) { $url = $this->_getApiServiceUri(). 'version/'. $version . '/dictionary/' . $dictionaryName; $result = $this->_fetch($url, \Zend_Http_Client::GET); return $result; }
php
{ "resource": "" }
q243909
Api.getAuthDictionary
validation
public function getAuthDictionary($version) { $name = Config::AUTH_DICTIONARY_NAME; $dictionary = $this->getSingleDictionary($version, $name); return $dictionary; }
php
{ "resource": "" }
q243910
Api.checkAuthDictionaryPopulation
validation
public function checkAuthDictionaryPopulation($version) { $dictionary = $this->getAuthDictionary($version); if ((is_array($dictionary) && empty($dictionary)) || !isset($dictionary->id)) { throw new LocalizedException(__('You must add users in order to enable Basic Authentication.')); } $authItems = $this->dictionaryItemsList($dictionary->id); if (is_array($authItems) && empty($authItems)) { throw new LocalizedException(__('You must add users in order to enable Basic Authentication.')); } }
php
{ "resource": "" }
q243911
Api.createDictionaryItems
validation
public function createDictionaryItems($dictionaryId, $params) { $url = $this->_getApiServiceUri().'dictionary/'.$dictionaryId.'/items'; $result = $this->_fetch($url, \Zend_Http_Client::PATCH, $params); return $result; }
php
{ "resource": "" }
q243912
Api.deleteDictionaryItem
validation
public function deleteDictionaryItem($dictionaryId, $itemKey) { $url = $this->_getApiServiceUri(). 'dictionary/'. $dictionaryId . '/item/' . urlencode($itemKey); $result = $this->_fetch($url, \Zend_Http_Client::DELETE); return $result; }
php
{ "resource": "" }
q243913
Api.upsertDictionaryItem
validation
public function upsertDictionaryItem($dictionaryId, $itemKey, $itemValue) { $body = ['item_value' => $itemValue]; $url = $this->_getApiServiceUri(). 'dictionary/'. $dictionaryId . '/item/' . urlencode($itemKey); $result = $this->_fetch($url, \Zend_Http_Client::PUT, $body); if (!$result) { throw new LocalizedException(__('Failed to create Dictionary item.')); } }
php
{ "resource": "" }
q243914
Api.getSingleAcl
validation
public function getSingleAcl($version, $acl) { $url = $this->_getApiServiceUri(). 'version/'. $version . '/acl/' . $acl; $result = $this->_fetch($url, \Zend_Http_Client::GET); return $result; }
php
{ "resource": "" }
q243915
Api.deleteAcl
validation
public function deleteAcl($version, $name) { $url = $this->_getApiServiceUri(). 'version/'. $version . '/acl/' . $name; $result = $this->_fetch($url, \Zend_Http_Client::DELETE); return $result; }
php
{ "resource": "" }
q243916
Api.aclItemsList
validation
public function aclItemsList($aclId) { $url = $this->_getApiServiceUri() . 'acl/'. $aclId . '/entries'; $result = $this->_fetch($url, \Zend_Http_Client::GET); return $result; }
php
{ "resource": "" }
q243917
Api.upsertAclItem
validation
public function upsertAclItem($aclId, $itemValue, $negated, $comment = 'Added by Magento Module', $subnet = false) { $body = [ 'ip' => $itemValue, 'negated' => $negated, 'comment' => $comment ]; if ($subnet) { $body['subnet'] = $subnet; } $url = $this->_getApiServiceUri(). 'acl/'. $aclId . '/entry'; $result = $this->_fetch($url, \Zend_Http_Client::POST, $body); return $result; }
php
{ "resource": "" }
q243918
Api.deleteAclItem
validation
public function deleteAclItem($aclId, $aclItemId) { $url = $this->_getApiServiceUri(). 'acl/'. $aclId . '/entry/' . $aclItemId; $result = $this->_fetch($url, \Zend_Http_Client::DELETE); return $result; }
php
{ "resource": "" }
q243919
Api.updateAclItem
validation
public function updateAclItem($aclId, $aclItemId, $itemValue, $negated, $comment = '', $subnet = false) { $body = [ 'ip' => $itemValue, 'negated' => $negated, 'comment' => $comment ]; if ($subnet) { $body['subnet'] = $subnet; } $url = $this->_getApiServiceUri(). 'acl/'. $aclId . '/entry/' . $aclItemId; $result = $this->_fetch($url, \Zend_Http_Client::PATCH, json_encode($body)); return $result; }
php
{ "resource": "" }
q243920
Api.queryHistoricStats
validation
public function queryHistoricStats(array $parameters) { $uri = $this->_getHistoricalEndpoint() . '?region='.$parameters['region'] . '&from='.$parameters['from'] . '&to='.$parameters['to'] . '&by=' . $parameters['sample_rate']; $result = $this->_fetch($uri); return $result; }
php
{ "resource": "" }
q243921
Api.checkImageOptimizationStatus
validation
public function checkImageOptimizationStatus() { $url = $this->_getApiServiceUri(). 'dynamic_io_settings'; $result = $this->_fetch($url, \Zend_Http_Client::GET); return $result; }
php
{ "resource": "" }
q243922
Api.configureImageOptimizationDefaultConfigOptions
validation
public function configureImageOptimizationDefaultConfigOptions($params, $version) { $url = $this->_getApiServiceUri(). 'version/'. $version . '/io_settings'; $result = $this->_fetch($url, \Zend_Http_Client::PATCH, $params); return $result; }
php
{ "resource": "" }
q243923
Api.getServiceDetails
validation
public function getServiceDetails() { $url = $this->_getApiServiceUri() . 'details'; $result = $this->_fetch($url, \Zend_Http_Client::GET); return $result; }
php
{ "resource": "" }
q243924
Api.getWafSettings
validation
public function getWafSettings($id) { $url = $this->_getWafEndpoint() . $id; $result = $this->_fetch($url, \Zend_Http_Client::GET); return $result; }
php
{ "resource": "" }
q243925
Api._fetch
validation
private function _fetch( $uri, $method = \Zend_Http_Client::GET, $body = '', $test = false, $testApiKey = null, $logError = true ) { $apiKey = ($test == true) ? $testApiKey : $this->config->getApiKey(); // Correctly format $body string if (is_array($body) == true) { $body = http_build_query($body); } // Client headers $headers = [ self::FASTLY_HEADER_AUTH . ': ' . $apiKey, 'Accept: application/json' ]; // Client options $options = []; // Request method specific header & option changes switch ($method) { case \Zend_Http_Client::DELETE: $options[CURLOPT_CUSTOMREQUEST] = \Zend_Http_Client::DELETE; break; case \Zend_Http_Client::PUT: $headers[] = 'Content-Type: application/x-www-form-urlencoded'; $options[CURLOPT_CUSTOMREQUEST] = \Zend_Http_Client::PUT; if ($body != '') { $options[CURLOPT_POSTFIELDS] = $body; } break; case \Zend_Http_Client::PATCH: $options[CURLOPT_CUSTOMREQUEST] = \Zend_Http_Client::PATCH; $headers[] = 'Content-Type: text/json'; if ($body != '') { $options[CURLOPT_POSTFIELDS] = $body; } break; } /** @var \Magento\Framework\HTTP\Adapter\Curl $client */ $client = $this->curlFactory->create(); // Execute request $client->setOptions($options); $client->write($method, $uri, '1.1', $headers, $body); $response = $client->read(); $client->close(); // Parse response $responseBody = \Zend_Http_Response::extractBody($response); $responseCode = \Zend_Http_Response::extractCode($response); $responseMessage = \Zend_Http_Response::extractMessage($response); // Return error based on response code if ($responseCode == '429') { throw new LocalizedException(__($responseMessage)); } elseif ($responseCode != '200') { if ($logError == true) { $this->logger->critical('Return status ' . $responseCode, $uri); } return false; } return json_decode($responseBody); }
php
{ "resource": "" }
q243926
FrontControllerPlugin.aroundDispatch
validation
public function aroundDispatch(FrontController $subject, callable $proceed, ...$args) // @codingStandardsIgnoreLine - unused parameter { $isRateLimitingEnabled = $this->config->isRateLimitingEnabled(); $isCrawlerProtectionEnabled = $this->config->isCrawlerProtectionEnabled(); if (!$isRateLimitingEnabled && !$isCrawlerProtectionEnabled) { return $proceed(...$args); } $path = strtolower($this->request->getPathInfo()); if ($isRateLimitingEnabled && $this->sensitivePathProtection($path)) { return $this->response; } if ($isCrawlerProtectionEnabled && $this->crawlerProtection($path)) { return $this->response; } return $proceed(...$args); }
php
{ "resource": "" }
q243927
CheckFastlyIoSetting.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $req = $this->api->checkImageOptimizationStatus(); if (!$req) { return $result->setData([ 'status' => false, 'msg' => 'Failed to check image optimization status.' ]); } return $result->setData([ 'status' => true, 'req_setting' => $req ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243928
SerializeToJson.execute
validation
protected function execute(InputInterface $input, OutputInterface $output) // @codingStandardsIgnoreLine - required by parent class { $configPaths = [ 'geoip_country_mapping' => \Fastly\Cdn\Model\Config::XML_FASTLY_GEOIP_COUNTRY_MAPPING ]; foreach ($configPaths as $path) { $magVer = $this->productMetadata->getVersion(); if (version_compare($magVer, '2.2', '<')) { $output->writeln( 'Warning : This function is used for converting serialized data to JSON' . ' (recommended for Magento versions above 2.2)' ); } $oldData = $this->scopeConfig->getValue($path); try { $oldData = unserialize($oldData); // @codingStandardsIgnoreLine - used for conversion of old Magento format to json_decode } catch (\Exception $e) { $oldData = false; } if ($oldData === false) { $output->writeln( 'Invalid serialization format, unable to unserialize config data : ' . $path ); return; } $oldData = (is_array($oldData)) ? $oldData : []; $newData = json_encode($oldData); if (false === $newData) { throw new \InvalidArgumentException('Unable to encode data.'); } $this->configWriter->save($path, $newData); // @codingStandardsIgnoreLine - currently best way to resolve this $this->cacheManager->clean([\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER]); $output->writeln('Config Cache Flushed'); } }
php
{ "resource": "" }
q243929
Image.fastlyRotate
validation
private function fastlyRotate($angle) { $angle = (int) $angle; $orient = null; if ($angle == 90) { $orient = 'r'; } if ($angle == -90 || $angle == 270) { $orient = 'l'; } if ($angle == 180) { $orient = 3; } if ($orient !== null) { $this->fastlyParameters['orient'] = $orient; } return $this; }
php
{ "resource": "" }
q243930
Image.fastlyResize
validation
private function fastlyResize() { if ($this->getWidth() === null && $this->getHeight() === null) { return $this; } $this->adjustSize(); return $this; }
php
{ "resource": "" }
q243931
Image.getResizedImageInfo
validation
public function getResizedImageInfo() { if ($this->isFastlyImageOptimizationEnabled() == false) { return parent::getResizedImageInfo(); } // Return image data if ($this->getBaseFile() !== null) { return [ 0 => $this->getWidth(), 1 => $this->getHeight() ]; } // No image, parse the placeholder $asset = $this->_assetRepo->createAsset( "Magento_Catalog::images/product/placeholder/{$this->getDestinationSubdir()}.jpg" ); $img = $asset->getSourceFile(); $imageInfo = getimagesize($img); $this->setWidth($imageInfo[0]); $this->setHeight($imageInfo[1]); return $imageInfo; }
php
{ "resource": "" }
q243932
Image.getForceLossyUrl
validation
public function getForceLossyUrl() { $baseFile = $this->getBaseFile(); $extension = pathinfo($baseFile, PATHINFO_EXTENSION); // @codingStandardsIgnoreLine $url = $this->getBaseFileUrl($baseFile); if ($extension == 'png' || $extension == 'bmp') { if ($this->isFastlyImageOptimizationEnabled() == false) { $this->lossyUrl = $url . '?format=jpeg'; } else { $this->lossyParam = '&format=jpeg'; } } }
php
{ "resource": "" }
q243933
Image.getFastlyUrl
validation
public function getFastlyUrl() { $baseFile = $this->getBaseFile(); $url = $this->getBaseFileUrl($baseFile); $imageQuality = $this->_scopeConfig->getValue(Config::XML_FASTLY_IMAGE_OPTIMIZATION_IMAGE_QUALITY); $this->setQuality($imageQuality); $this->fastlyParameters['quality'] = $this->_quality; if ($this->_scopeConfig->isSetFlag(Config::XML_FASTLY_IMAGE_OPTIMIZATION_BG_COLOR) == true) { $this->fastlyParameters['bg-color'] = implode(',', $this->_backgroundColor); } if ($this->_keepAspectRatio == true) { $this->fastlyParameters['fit'] = 'bounds'; } $this->fastlyUrl = $url . '?' . $this->compileFastlyParameters(); }
php
{ "resource": "" }
q243934
Image.compileFastlyParameters
validation
private function compileFastlyParameters() { if (isset($this->fastlyParameters['width']) == false) { $this->fastlyParameters['height'] = $this->_height; $this->fastlyParameters['width'] = $this->_width; } $params = []; foreach ($this->fastlyParameters as $key => $value) { $params[] = $key . '=' . $value; } return implode('&', $params); }
php
{ "resource": "" }
q243935
IoDefaultConfigOptions.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $activate_flag = $this->getRequest()->getParam('activate_flag'); $activeVersion = $this->getRequest()->getParam('active_version'); $formData = $this->getRequest()->getParams(); if (in_array("", $formData)) { return $result->setData([ 'status' => false, 'msg' => 'Please fill in the required fields.' ]); } $service = $this->api->checkServiceDetails(); $this->vcl->checkCurrentVersionActive($service->versions, $activeVersion); $currActiveVersion = $this->vcl->getCurrentVersion($service->versions); $clone = $this->api->cloneVersion($currActiveVersion); $id = $service->id . '-' . $clone->number . '-imageopto'; $params = json_encode([ 'data' => [ 'id' => $id, 'type' => 'io_settings', 'attributes' => [ 'webp' => $this->getRequest()->getParam('webp'), 'webp_quality' => $this->getRequest()->getParam('webp_quality'), 'jpeg_type' => $this->getRequest()->getParam('jpeg_type'), 'jpeg_quality' => $this->getRequest()->getParam('jpeg_quality'), 'upscale' => $this->getRequest()->getParam('upscale'), 'resize_filter' => $this->getRequest()->getParam('resize_filter') ] ] ]); $configureIo = $this->api->configureImageOptimizationDefaultConfigOptions($params, $clone->number); if (!$configureIo) { return $result->setData([ 'status' => false, 'msg' => 'Failed to update image optimization default config options.' ]); } $this->api->validateServiceVersion($clone->number); if ($activate_flag === 'true') { $this->api->activateVersion($clone->number); } if ($this->config->areWebHooksEnabled() && $this->config->canPublishConfigChanges()) { $this->api->sendWebHook('*Image optimization default config options have been updated*'); } $comment = ['comment' => 'Magento Module updated the Image Optimization Default Configuration']; $this->api->addComment($clone->number, $comment); return $result->setData([ 'status' => true, 'active_version' => $clone->number ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243936
MarkEsiBlock.execute
validation
public function execute(Observer $observer) // @codingStandardsIgnoreLine - required, but not needed { if ($this->fastlyConfig->isFastlyEnabled() != true) { return; } // If not set, causes issues with embedded ESI $this->response->setHeader("x-esi", "1"); }
php
{ "resource": "" }
q243937
ConfigPlugin.afterGetType
validation
public function afterGetType(Config $config, $result) { if (!($config instanceof \Fastly\Cdn\Model\Config)) { if ($result == \Fastly\Cdn\Model\Config::FASTLY) { return Config::VARNISH; } } return $result; }
php
{ "resource": "" }
q243938
EnableAuth.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $activateVcl = $this->getRequest()->getParam('activate_flag'); $service = $this->api->checkServiceDetails(); $enabled = false; $this->vcl->checkCurrentVersionActive($service->versions, $activeVersion); $currActiveVersion = $this->vcl->getCurrentVersion($service->versions); $vclPath = Config::VCL_AUTH_SNIPPET_PATH; $snippets = $this->config->getVclSnippets($vclPath); // Check if snippets exist $status = true; foreach ($snippets as $key => $value) { $name = Config::FASTLY_MAGENTO_MODULE.'_basic_auth_'.$key; $status = $this->api->getSnippet($activeVersion, $name); if (!$status) { break; } } if (!$status) { // Check if Auth has entries $this->api->checkAuthDictionaryPopulation($activeVersion); $clone = $this->api->cloneVersion($currActiveVersion); // Insert snippet foreach ($snippets as $key => $value) { $snippetData = [ 'name' => Config::FASTLY_MAGENTO_MODULE.'_basic_auth_'.$key, 'type' => $key, 'dynamic' => "0", 'content' => $value, 'priority' => 10 ]; $this->api->uploadSnippet($clone->number, $snippetData); } $enabled = true; } else { $clone = $this->api->cloneVersion($currActiveVersion); // Remove snippets foreach ($snippets as $key => $value) { $name = Config::FASTLY_MAGENTO_MODULE.'_basic_auth_'.$key; $this->api->removeSnippet($clone->number, $name); } } $this->api->validateServiceVersion($clone->number); if ($activateVcl === 'true') { $this->api->activateVersion($clone->number); } $this->sendWebhook($enabled, $clone); $comment = ['comment' => 'Magento Module turned ON Basic Authentication']; if (!$enabled) { $comment = ['comment' => 'Magento Module turned OFF Basic Authentication']; } $this->api->addComment($clone->number, $comment); return $result->setData(['status' => true]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243939
UpgradeData.upgrade
validation
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $version = $context->getVersion(); if (!$version) { return; } $oldConfigPaths = [ 'stale_ttl' => 'system/full_page_cache/fastly/stale_ttl', 'stale_error_ttl' => 'system/full_page_cache/fastly/stale_error_ttl', 'purge_catalog_category' => 'system/full_page_cache/fastly/purge_catalog_category', 'purge_catalog_product' => 'system/full_page_cache/fastly/purge_catalog_product', 'purge_cms_page' => 'system/full_page_cache/fastly/purge_cms_page', 'soft_purge' => 'system/full_page_cache/fastly/soft_purge', 'enable_geoip' => 'system/full_page_cache/fastly/enable_geoip', 'geoip_action' => 'system/full_page_cache/fastly/geoip_action', 'geoip_country_mapping' => 'system/full_page_cache/fastly/geoip_country_mapping', ]; $newConfigPaths = [ 'stale_ttl' => 'system/full_page_cache/fastly/fastly_advanced_configuration/stale_ttl', 'stale_error_ttl' => 'system/full_page_cache/fastly/fastly_advanced_configuration/stale_error_ttl', 'purge_catalog_category' => 'system/full_page_cache/fastly/fastly_advanced_configuration/purge_catalog_category', 'purge_catalog_product' => 'system/full_page_cache/fastly/fastly_advanced_configuration/purge_catalog_product', 'purge_cms_page' => 'system/full_page_cache/fastly/fastly_advanced_configuration/purge_cms_page', 'soft_purge' => 'system/full_page_cache/fastly/fastly_advanced_configuration/soft_purge', 'enable_geoip' => 'system/full_page_cache/fastly/fastly_advanced_configuration/enable_geoip', 'geoip_action' => 'system/full_page_cache/fastly/fastly_advanced_configuration/geoip_action', 'geoip_country_mapping' => 'system/full_page_cache/fastly/fastly_advanced_configuration/geoip_country_mapping' ]; $setup->startSetup(); if (version_compare($version, '1.0.8', '<=')) { $this->upgrade108($oldConfigPaths, $newConfigPaths); } if (version_compare($version, '1.0.9', '<=')) { $this->upgrade109($setup); } // If Magento is upgraded later, // use bin/magento fastly:format:serializetojson OR /bin/magento fastly:format:jsontoserialize to adjust format $magVer = $this->productMetadata->getVersion(); if (version_compare($version, '1.0.10', '<=') && version_compare($magVer, '2.2', '>=')) { $this->upgrade1010($newConfigPaths); $setup->endSetup(); } elseif (version_compare($magVer, '2.2', '<')) { $setup->endSetup(); } }
php
{ "resource": "" }
q243940
UpgradeData.upgrade108
validation
private function upgrade108($oldConfigPaths, $newConfigPaths) { foreach ($oldConfigPaths as $key => $value) { $oldValue = $this->scopeConfig->getValue($value); if ($oldValue != null) { $this->configWriter->save($newConfigPaths[$key], $oldValue); // @codingStandardsIgnoreLine - currently best way to resolve this } } }
php
{ "resource": "" }
q243941
UpgradeData.upgrade1010
validation
private function upgrade1010($newConfigPaths) { $oldData = $this->scopeConfig->getValue($newConfigPaths['geoip_country_mapping']); try { $oldData = unserialize($oldData); // @codingStandardsIgnoreLine - used for conversion of old Magento format to json_decode } catch (\Exception $e) { $oldData = []; } $oldData = (is_array($oldData)) ? $oldData : []; $newData = json_encode($oldData); if (false === $newData) { throw new \InvalidArgumentException('Unable to encode data.'); } $this->configWriter->save($newConfigPaths['geoip_country_mapping'], $newData); $this->cacheManager->clean([\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER]); }
php
{ "resource": "" }
q243942
GetAllModules.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $modules = $this->manifest->getAllModlyManifests(); if (!$modules) { return $result->setData([ 'status' => false, 'modules' => '', 'msg' => 'Use the Refresh button to get the latest modules.' ]); } return $result->setData([ 'status' => true, 'modules' => $modules ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243943
CustomSnippetUpload.beforeSave
validation
public function beforeSave() { $value = $this->getValue(); $file = $this->getFileData(); if (!empty($file)) { $uploadDir = $this->_getUploadDir(); try { $uploader = $this->_uploaderFactory->create(['fileId' => $file]); $uploader->setAllowedExtensions($this->getAllowedExtensions()); $uploader->setAllowRenameFiles(true); $uploader->addValidateCallback('size', $this, 'validateMaxSize'); $result = $uploader->save($uploadDir); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(__('%1', $e->getMessage())); } $filename = $result['file']; if ($filename) { if ($this->_addWhetherScopeInfo()) { $filename = $this->_prependScopeInfo($filename); } $this->setValue($filename); } } else { if (is_array($value) && !empty($value['delete'])) { $this->setValue(''); } elseif (is_array($value) && !empty($value['value'])) { $this->setValue($value['value']); } else { $this->unsValue(); } } return $this; }
php
{ "resource": "" }
q243944
Additional.canShowBlock
validation
public function canShowBlock() { if ($this->config->getType() == Config::FASTLY && $this->config->isEnabled()) { return true; } return false; }
php
{ "resource": "" }
q243945
Additional.getContentTypeOptions
validation
public function getContentTypeOptions() { $contentTypes = [ self::CONTENT_TYPE_HTML => __('HTML'), self::CONTENT_TYPE_CSS => __('CSS'), self::CONTENT_TYPE_JS => __('JavaScript'), self::CONTENT_TYPE_IMAGE => __('Images') ]; return $contentTypes; }
php
{ "resource": "" }
q243946
CheckAuthSetting.execute
validation
public function execute() { $result = $this->resultJsonFactory->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $snippets = $this->config->getVclSnippets(Config::VCL_AUTH_SNIPPET_PATH); foreach ($snippets as $key => $value) { $name = Config::FASTLY_MAGENTO_MODULE . '_basic_auth_' . $key; $status = $this->api->hasSnippet($activeVersion, $name); if ($status == false) { return $result->setData([ 'status' => false ]); } } return $result->setData([ 'status' => true ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243947
Manifest.getAllModules
validation
public function getAllModules() { $modules = []; $moduleCollection = $this->collectionFactory->create()->getData(); foreach ($moduleCollection as $module) { $modules[] = $module; } return $modules; }
php
{ "resource": "" }
q243948
GetWafPageRespObj.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $response = $this->api->getResponse($activeVersion, Config::WAF_PAGE_RESPONSE_OBJECT); if (!$response) { return $result->setData([ 'status' => false, 'msg' => 'Failed to fetch WAF page Response object.' ]); } return $result->setData([ 'status' => true, 'wafPageResp' => $response ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243949
ConfigRewrite.afterSave
validation
public function afterSave(\Magento\Config\Model\Config $subject) // @codingStandardsIgnoreLine - unused parameter { if ($this->purge) { $this->api->cleanBySurrogateKey(['text']); } }
php
{ "resource": "" }
q243950
ConfigRewrite.beforeSave
validation
public function beforeSave(\Magento\Config\Model\Config $subject) { $data = $subject->getData(); if (!empty($data['groups']['full_page_cache']['fields']['caching_application']['value'])) { $currentCacheConfig = $data['groups']['full_page_cache']['fields']['caching_application']['value']; $oldCacheConfig = $this->scopeConfig->getValue(\Magento\PageCache\Model\Config::XML_PAGECACHE_TYPE); if ($oldCacheConfig == \Fastly\Cdn\Model\Config::FASTLY && $currentCacheConfig != $oldCacheConfig) { $this->purge = true; } } }
php
{ "resource": "" }
q243951
GetDomains.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $domains = $this->api->getAllDomains($activeVersion); $storeBaseUrl = $this->storeManager->getStore()->getBaseUrl(); if (!$domains) { return $result->setData([ 'status' => false, 'msg' => 'Failed to check Domain details.' ]); } return $result->setData([ 'status' => true, 'domains' => $domains, 'store' => $storeBaseUrl ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243952
CheckAuthUsersAvailable.execute
validation
public function execute() { $result = $this->resultJsonFactory->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $dictionaryName = Config::AUTH_DICTIONARY_NAME; $dictionary = $this->api->getSingleDictionary($activeVersion, $dictionaryName); if ((is_array($dictionary) && empty($dictionary)) || $dictionary == false || !isset($dictionary->id)) { return $result->setData([ 'status' => 'empty', 'msg' => 'Basic Authentication cannot be enabled because there are no users assigned to it.' ]); } else { $authItems = $this->api->dictionaryItemsList($dictionary->id); if (is_array($authItems) && empty($authItems)) { return $result->setData([ 'status' => 'empty', 'msg' => 'Basic Authentication cannot be enabled because there are no users assigned to it.' ]); } return $result->setData(['status' => true]); } } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243953
Checkbox._getElementHtml
validation
public function _getElementHtml(AbstractElement $element) { $this->setNamePrefix($element->getName()) ->setHtmlId($element->getHtmlId()); return $this->_toHtml(); }
php
{ "resource": "" }
q243954
Checkbox.getValues
validation
public function getValues() { $values = []; $ratios = $this->pixelRatios->toOptionArray(); foreach ($ratios as $value) { $values[$value['value']] = $value['label']; } return $values; }
php
{ "resource": "" }
q243955
Checkbox.getCheckedValues
validation
public function getCheckedValues() { if ($this->values === null) { $data = $this->config->getImageOptimizationRatios(); if (!isset($data)) { $data = ''; } $this->values = explode(',', $data); } return $this->values; }
php
{ "resource": "" }
q243956
Node.render
validation
public function render() { return [ 'id' => $this->getId(), 'translate' => 'label comment', 'showInDefault' => 1, 'showInWebsite' => 0, 'showInStore' => 0, 'sortOrder' => 1, 'label' => $this->label, 'comment' => $this->comment, '_elementType' => 'group', 'path' => self::BASE_CONFIG_PATH, 'children' => $this->children ]; }
php
{ "resource": "" }
q243957
Node.addTextInput
validation
public function addTextInput($id, $label, $comment, $required = true) { $this->children[$id] = [ 'id' => $id, 'type' => 'text', 'translate' => 'label comment', 'showInDefault' => 1, 'showInWebsite' => 0, 'showInStore' => 0, 'sortOrder' => count($this->children), 'label' => $label, 'comment' => $comment, 'validate' => ($required == true) ? 'required-entry' : '', '_elementType' => 'field', 'path' => self::BASE_CONFIG_PATH . '/' . $this->id ]; }
php
{ "resource": "" }
q243958
WafBtn.render
validation
public function render(AbstractElement $element) { $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue(); return parent::render($element); }
php
{ "resource": "" }
q243959
GetCustomSnippet.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $snippet = $this->getRequest()->getParam('snippet_id'); $read = $this->filesystem->getDirectoryRead(DirectoryList::VAR_DIR); $snippetPath = $read->getRelativePath(Config::CUSTOM_SNIPPET_PATH . $snippet); if ($read->isExist($snippetPath)) { $explodeId = explode('.', $snippet, -1); $snippetParts = explode('_', $explodeId[0], 3); $type = $snippetParts[0]; $priority = $snippetParts[1]; $name = $snippetParts[2]; $content = $read->readFile($snippetPath); } else { throw new LocalizedException(__('Custom snippet not found.')); } return $result->setData([ 'status' => true, 'type' => $type, 'priority' => $priority, 'name' => $name, 'content' => $content, 'original' => $snippet ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243960
Quick.isHostInDomainList
validation
private function isHostInDomainList($host) { $urlTypes = [ UrlInterface::URL_TYPE_LINK, UrlInterface::URL_TYPE_DIRECT_LINK, UrlInterface::URL_TYPE_WEB, UrlInterface::URL_TYPE_MEDIA, UrlInterface::URL_TYPE_STATIC ]; $secureScheme = [true, false]; foreach ($this->storeManager->getStores() as $store) { /** @var \Magento\Store\Model\Store $store */ foreach ($urlTypes as $urlType) { foreach ($secureScheme as $scheme) { $shopHost = \Zend_Uri::factory($store->getBaseUrl($urlType, $scheme))->getHost(); if ($host === $shopHost) { return true; } } } } return false; }
php
{ "resource": "" }
q243961
GetAction.execute
validation
public function execute() { $resultLayout = null; try { $resultLayout = $this->resultLayoutFactory->create(); $resultLayout->addDefaultHandle(); // get target store from country code $countryCode = $this->getRequest()->getParam(self::REQUEST_PARAM_COUNTRY); $storeId = $this->config->getGeoIpMappingForCountry($countryCode); if ($storeId !== null) { // get redirect URL $redirectUrl = null; $targetStore = $this->storeRepository->getActiveStoreById($storeId); $currentStore = $this->storeManager->getStore(); // only generate a redirect URL if current and new store are different if ($currentStore->getId() != $targetStore->getId()) { $this->url->setScope($targetStore->getId()); $this->url->addQueryParams([ '___store' => $targetStore->getCode(), '___from_store' => $currentStore->getCode() ]); $redirectUrl = $this->url->getUrl('stores/store/switch'); } // generate output only if redirect should be performed if ($redirectUrl) { switch ($this->config->getGeoIpAction()) { case Config::GEOIP_ACTION_DIALOG: $resultLayout->getLayout()->getUpdate()->load(['geoip_getaction_dialog']); $resultLayout->getLayout()->getBlock('geoip_getaction')->setMessage( $this->getMessageInStoreLocale($targetStore) ); break; case Config::GEOIP_ACTION_REDIRECT: $resultLayout->getLayout()->getUpdate()->load(['geoip_getaction_redirect']); break; } $resultLayout->getLayout()->getBlock('geoip_getaction')->setRedirectUrl($redirectUrl); } } } catch (\Exception $e) { $this->logger->critical($e->getMessage()); // do not generate output on errors. this is similar to an empty GeoIP mapping for the country. } $resultLayout->setHeader("x-esi", "1"); return $resultLayout; }
php
{ "resource": "" }
q243962
GetAction.getMessageInStoreLocale
validation
private function getMessageInStoreLocale(StoreInterface $emulatedStore) { $currentStore = $this->storeManager->getStore(); // emulate locale and store of new store to fetch message translation $this->localeResolver->emulate($emulatedStore->getId()); $this->storeManager->setCurrentStore($emulatedStore->getId()); $message = __( 'You are in the wrong store. Click OK to visit the %1 store.', [$emulatedStore->getName()] )->__toString(); // revert locale and store emulation $this->localeResolver->revert(); $this->storeManager->setCurrentStore($currentStore->getId()); return $message; }
php
{ "resource": "" }
q243963
PurgeCachePlugin.aroundSendPurgeRequest
validation
public function aroundSendPurgeRequest(PurgeCache $subject, callable $proceed, ...$args) // @codingStandardsIgnoreLine - unused parameter { if ($this->config->isFastlyEnabled() !== true) { $proceed(...$args); } }
php
{ "resource": "" }
q243964
MarkEsiPage.execute
validation
public function execute(Observer $observer) { if ($this->fastlyConfig->isFastlyEnabled() != true) { return; } $event = $observer->getEvent(); $name = $event->getElementName(); /** @var \Magento\Framework\View\Layout $layout */ $layout = $event->getLayout(); /** @var AbstractBlock $block */ $block = $layout->getBlock($name); if ($block instanceof AbstractBlock) { $blockTtl = $block->getTtl(); if (isset($blockTtl)) { // This page potentially has ESIs so as a first cut let's mark it as such $this->response->setHeader("x-esi", "1"); } } }
php
{ "resource": "" }
q243965
InvalidateVarnishObserver.execute
validation
public function execute(\Magento\Framework\Event\Observer $observer) { if ($this->config->getType() == Config::FASTLY && $this->config->isEnabled()) { $object = $observer->getEvent()->getObject(); if ($object instanceof \Magento\Framework\DataObject\IdentityInterface && $this->canPurgeObject($object)) { $tags = []; foreach ($object->getIdentities() as $tag) { $tag = $this->cacheTags->convertCacheTags($tag); if (!in_array($tag, $this->alreadyPurged)) { $tags[] = $tag; $this->alreadyPurged[] = $tag; } } if (!empty($tags)) { $this->purgeCache->sendPurgeRequest(array_unique($tags)); } } } }
php
{ "resource": "" }
q243966
InvalidateVarnishObserver.canPurgeObject
validation
private function canPurgeObject(\Magento\Framework\DataObject\IdentityInterface $object) { if ($object instanceof \Magento\Catalog\Model\Category && !$this->config->canPurgeCatalogCategory()) { return false; } if ($object instanceof \Magento\Catalog\Model\Product && !$this->config->canPurgeCatalogProduct()) { return false; } if ($object instanceof \Magento\Cms\Model\Page && !$this->config->canPurgeCmsPage()) { return false; } return true; }
php
{ "resource": "" }
q243967
ListAll.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $dictionary = $this->api->getSingleDictionary($activeVersion, 'magentomodule_basic_auth'); // Fetch Authentication items if (!$dictionary || (is_array($dictionary) && empty($dictionary))) { return $result->setData([ 'status' => 'none', 'msg' => 'Authentication dictionary does not exist.' ]); } $authItems = false; if (isset($dictionary->id)) { $authItems = $this->api->dictionaryItemsList($dictionary->id); } if (is_array($authItems) && empty($authItems)) { return $result->setData([ 'status' => 'empty', 'msg' => 'There are no dictionary items.' ]); } if (!$authItems) { return $result->setData([ 'status' => false, 'msg' => 'Failed to fetch dictionary items.' ]); } foreach ($authItems as $key => $item) { $userData = explode(':', base64_decode($item->item_key)); // @codingStandardsIgnoreLine - used for authentication $username = $userData[0]; $item->item_key_id = $item->item_key; $item->item_key = $username; $authItems[$key] = $item; } return $result->setData([ 'status' => true, 'auths' => $authItems ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243968
UpdateWafAllowlist.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $service = $this->api->checkServiceDetails(); $currActiveVersion = $this->vcl->determineVersions($service->versions); $snippet = $this->config->getVclSnippets( Config::VCL_WAF_PATH, Config::VCL_WAF_ALLOWLIST_SNIPPET ); $acls = $this->prepareAcls($this->request->getParam('acls')); $allowedItems = $acls; $strippedAllowedItems = substr($allowedItems, 0, strrpos($allowedItems, '||', -1)); // Add WAF bypass snippet foreach ($snippet as $key => $value) { if ($strippedAllowedItems === '') { $value = ''; } else { $value = str_replace('####WAF_ALLOWLIST####', $strippedAllowedItems, $value); } $snippetName = Config::FASTLY_MAGENTO_MODULE . '_waf_' . $key; $snippetId = $this->api->getSnippet($currActiveVersion['active_version'], $snippetName)->id; $params = [ 'name' => $snippetId, 'content' => $value ]; $this->api->updateSnippet($params); } $this->cacheTypeList->cleanType('config'); $this->systemConfig->clean(); return $result->setData([ 'status' => true ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243969
EditCustomSnippet.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $name = $this->getRequest()->getParam('name'); $type = $this->getRequest()->getParam('type'); $priority = $this->getRequest()->getParam('priority'); $vcl = $this->getRequest()->getParam('vcl'); $validation = $this->config->validateCustomSnippet($name, $type, $priority); $error = $validation['error']; if ($error != null) { throw new LocalizedException(__($error)); } $snippetName = $validation['snippet_name']; $fileName = $type . '_' . $priority . '_' . $snippetName . '.vcl'; $write = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); $snippetPath = $write->getRelativePath(Config::CUSTOM_SNIPPET_PATH . $fileName); $write->writeFile($snippetPath, $vcl); return $result->setData([ 'status' => true ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243970
AdaptivePixelRationPlugin.beforeToHtml
validation
public function beforeToHtml(Image $subject) { if ($this->config->isImageOptimizationPixelRatioEnabled() !== true) { return; } $srcSet = []; $imageUrl = $subject->getData('image_url'); $pixelRatios = $this->config->getImageOptimizationRatios(); $pixelRatiosArray = explode(',', $pixelRatios); $glue = (strpos($imageUrl, '?') !== false) ? '&' : '?'; # Pixel ratios defaults are based on the table from https://mydevice.io/devices/ # Bulk of devices are 2x however many new devices like Samsung S8, iPhone X etc are 3x and 4x foreach ($pixelRatiosArray as $pr) { $ratio = 'dpr=' . $pr . ' ' . $pr . 'x'; $srcSet[] = $imageUrl . $glue . $ratio; } $subject->setData('custom_attributes', 'srcset="' . implode(',', $srcSet) . '"'); }
php
{ "resource": "" }
q243971
Delete.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $dictionary = $this->api->getSingleDictionary($activeVersion, Config::AUTH_DICTIONARY_NAME); $vclPath = Config::VCL_AUTH_SNIPPET_PATH; $snippets = $this->config->getVclSnippets($vclPath); // Check if snippets exist $status = true; foreach ($snippets as $key => $value) { $name = Config::FASTLY_MAGENTO_MODULE.'_basic_auth_'.$key; $status = $this->api->getSnippet($activeVersion, $name); if (!$status) { break; } } if ((is_array($dictionary) && empty($dictionary)) || !isset($dictionary->id)) { return $result->setData([ 'status' => 'empty', 'msg' => 'Authentication dictionary does not exist.' ]); } // Check if there are any entries left $authItems = $this->api->dictionaryItemsList($dictionary->id); if (($status == true && is_array($authItems) && count($authItems) < 2) || $authItems == false) { // No users left, send message return $result->setData([ 'status' => 'empty', 'msg' => 'While Basic Authentication is enabled, at least one user must exist.', ]); } $itemKey = $this->getRequest()->getParam('item_key_id'); $deleteItem = $this->api->deleteDictionaryItem($dictionary->id, $itemKey); if (!$deleteItem) { return $result->setData([ 'status' => false, 'msg' => 'Failed to create Dictionary item.' ]); } return $result->setData(['status' => true]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243972
GetBackends.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $backends = $this->api->getBackends($activeVersion); if (!$backends) { return $result->setData([ 'status' => false, 'msg' => 'Failed to check Backend details.' ]); } return $result->setData([ 'status' => true, 'backends' => $backends ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243973
All.execute
validation
public function execute() { // Flush all Magento caches $types = $this->cacheManager->getAvailableTypes(); $types = array_diff($types, ['full_page']); // FPC is Handled separately $this->cacheManager->clean($types); // Purge everything from Fastly $result = $this->api->cleanAll(); if ($result === true) { $this->messageManager->addSuccessMessage( __('Full Magento & Fastly Cache has been cleaned.') ); } else { $this->getMessageManager()->addErrorMessage( __('Full Magento & Fastly Cache was not cleaned successfully.') ); } return $this->_redirect('*/cache/index'); }
php
{ "resource": "" }
q243974
SaveErrorPageHtml.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $activateVcl = $this->getRequest()->getParam('activate_flag'); $html = $this->getRequest()->getParam('html'); $service = $this->api->checkServiceDetails(); $this->vcl->checkCurrentVersionActive($service->versions, $activeVersion); $currActiveVersion = $this->vcl->getCurrentVersion($service->versions); $clone = $this->api->cloneVersion($currActiveVersion); $snippets = $this->config->getVclSnippets( Config::VCL_ERROR_SNIPPET_PATH, Config::VCL_ERROR_SNIPPET ); foreach ($snippets as $key => $value) { $snippetData = [ 'name' => Config::FASTLY_MAGENTO_MODULE . '_error_page_' . $key, 'type' => $key, 'dynamic' => '0', 'content' => $value ]; $this->api->uploadSnippet($clone->number, $snippetData); } $condition = [ 'name' => Config::FASTLY_MAGENTO_MODULE.'_error_page_condition', 'statement' => 'req.http.ResponseObject == "970"', 'type' => 'REQUEST', 'priority' => '9' ]; $createCondition = $this->api->createCondition($clone->number, $condition); $response = [ 'name' => Config::ERROR_PAGE_RESPONSE_OBJECT, 'request_condition' => $createCondition->name, 'content' => $html, 'status' => "503", 'content_type' => "text/html; charset=utf-8", 'response' => "Service Temporarily Unavailable" ]; $createResponse = $this->api->createResponse($clone->number, $response); if (!$createResponse) { return $result->setData([ 'status' => false, 'msg' => 'Failed to create a RESPONSE object.' ]); } $this->api->validateServiceVersion($clone->number); if ($activateVcl === 'true') { $this->api->activateVersion($clone->number); } if ($this->config->areWebHooksEnabled() && $this->config->canPublishConfigChanges()) { $this->api->sendWebHook( '*New Error/Maintenance page has updated and activated under config version ' . $clone->number . '*' ); } $comment = ['comment' => 'Magento Module updated Error Page html']; $this->api->addComment($clone->number, $comment); return $result->setData([ 'status' => true, 'active_version' => $clone->number ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243975
LayoutPlugin.afterGenerateXml
validation
public function afterGenerateXml(\Magento\Framework\View\Layout $subject, $result) { // if subject is cacheable, FPC cache is enabled, Fastly module is chosen and general TTL is > 0 if ($subject->isCacheable() && $this->config->isEnabled() && $this->config->getType() == Config::FASTLY && $this->config->getTtl()) { // get cache control header $header = $this->response->getHeader('cache-control'); if (($header instanceof \Zend\Http\Header\HeaderInterface) && ($value = $header->getFieldValue())) { // append stale values if ($ttl = $this->config->getStaleTtl()) { $value .= ', stale-while-revalidate=' . $ttl; } if ($ttl = $this->config->getStaleErrorTtl()) { $value .= ', stale-if-error=' . $ttl; } // update cache control header $this->response->setHeader($header->getFieldName(), $value, true); } } /* * Surface the cacheability of a page. This may expose things like page blocks being set to * cacheable = false which makes the whole page uncacheable */ if ($subject->isCacheable()) { $this->response->setHeader("fastly-page-cacheable", "YES"); } else { $this->response->setHeader("fastly-page-cacheable", "NO"); } return $result; }
php
{ "resource": "" }
q243976
LayoutPlugin.afterGetOutput
validation
public function afterGetOutput(\Magento\Framework\View\Layout $subject, $result) // @codingStandardsIgnoreLine - unused parameter { if ($this->config->getType() == Config::FASTLY) { $this->response->setHeader("Fastly-Module-Enabled", "1.2.99", true); } return $result; }
php
{ "resource": "" }
q243977
GetCountries.execute
validation
public function execute() { $result = $this->resultJson->create(); try { $countries = $this->countryHelper->toOptionArray(); if (!$countries) { return $result->setData([ 'status' => false, 'msg' => 'Could not fetch list countries.' ]); } return $result->setData([ 'status' => true, 'countries' => $countries ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243978
EnableCommand.setServiceID
validation
private function setServiceID($serviceId) { $this->configWriter->save(Config::XML_FASTLY_SERVICE_ID, $serviceId); $this->output->writeln( '<info>Service ID updated.</info>', OutputInterface::OUTPUT_NORMAL ); }
php
{ "resource": "" }
q243979
EnableCommand.setToken
validation
private function setToken($token) { $this->configWriter->save(Config::XML_FASTLY_API_KEY, $token); $this->output->writeln( '<info>Token updated.</info>', OutputInterface::OUTPUT_NORMAL ); }
php
{ "resource": "" }
q243980
EnableCommand.uploadVcl
validation
private function uploadVcl($activate) { try { $service = $this->api->checkServiceDetails(); $currActiveVersion = $this->vcl->getCurrentVersion($service->versions); $clone = $this->api->cloneVersion($currActiveVersion); $snippets = $this->config->getVclSnippets(); foreach ($snippets as $key => $value) { $snippetData = [ 'name' => Config::FASTLY_MAGENTO_MODULE . '_' . $key, 'type' => $key, 'dynamic' => "0", 'priority' => 50, 'content' => $value ]; $this->api->uploadSnippet($clone->number, $snippetData); } $condition = [ 'name' => Config::FASTLY_MAGENTO_MODULE . '_pass', 'statement' => 'req.http.x-pass', 'type' => 'REQUEST', 'priority' => 90 ]; $createCondition = $this->api->createCondition($clone->number, $condition); $request = [ 'action' => 'pass', 'max_stale_age' => 3600, 'name' => Config::FASTLY_MAGENTO_MODULE.'_request', 'request_condition' => $createCondition->name, 'service_id' => $service->id, 'version' => $currActiveVersion ]; $this->api->createRequest($clone->number, $request); $this->api->validateServiceVersion($clone->number); $msg = 'Successfully uploaded VCL. '; if ($activate) { $this->api->activateVersion($clone->number); $msg .= 'Activated Version '. $clone->number; } if ($this->config->areWebHooksEnabled() && $this->config->canPublishConfigChanges()) { $this->api->sendWebHook( '*Upload VCL has been initiated and activated in version ' . $clone->number . '*' ); } $this->output->writeln('<info>' . $msg . '</info>', OutputInterface::OUTPUT_NORMAL); } catch (\Exception $e) { $msg = $e->getMessage(); $this->output->writeln("<error>$msg</error>", OutputInterface::OUTPUT_NORMAL); return; } }
php
{ "resource": "" }
q243981
CheckBlockingSetting.execute
validation
public function execute() { $result = $this->resultJsonFactory->create(); try { $activeVersion = $this->getRequest()->getParam('active_version'); $snippet = Config::BLOCKING_SETTING_NAME; $req = $this->api->hasSnippet($activeVersion, $snippet); if ($req == false) { return $result->setData([ 'status' => false ]); } return $result->setData([ 'status' => true, 'req_setting' => $req ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243982
Manifest.getAllRepoManifests
validation
public function getAllRepoManifests() { $fastlyEdgeModules = $this->config->getFastlyEdgeModules(); $manifests = []; foreach ($fastlyEdgeModules as $key => $value) { $decodedManifestData = json_decode($value, true); $manifests[] = $decodedManifestData; } return $manifests; }
php
{ "resource": "" }
q243983
IsAlreadyConfigured.execute
validation
public function execute() { $result = $this->resultJsonFactory->create(); try { $serviceId = $this->config->getServiceId(); $apiKey = $this->config->getApiKey(); if ($serviceId == null && $apiKey == null) { return $result->setData([ 'status' => true, 'flag' => false ]); } return $result->setData([ 'status' => true, 'flag' => true ]); } catch (\Exception $e) { return $result->setData([ 'status' => false, 'msg' => $e->getMessage() ]); } }
php
{ "resource": "" }
q243984
CheckVersion.execute
validation
public function execute(Observer $observer) // @codingStandardsIgnoreLine - unused parameter { if ($this->backendAuthSession->isLoggedIn() == false) { return; } if ($this->getFrequency() + $this->getLastUpdate() > time()) { return; } $modulePath = $this->moduleRegistry->getPath(ComponentRegistrar::MODULE, 'Fastly_Cdn'); $filePath = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, "$modulePath/composer.json"); $composerData = json_decode(file_get_contents($filePath)); // @codingStandardsIgnoreLine - not user controlled $currentVersion = !empty($composerData->version) ? $composerData->version : false; if ($currentVersion) { $this->feedFactory->checkUpdate($currentVersion); } $this->setLastUpdate(); }
php
{ "resource": "" }
q243985
FlushAllCacheObserver.execute
validation
public function execute(\Magento\Framework\Event\Observer $observer) // @codingStandardsIgnoreLine - unused parameter { if ($this->config->getType() == Config::FASTLY && $this->config->isEnabled()) { $this->purgeCache->sendPurgeRequest(); } }
php
{ "resource": "" }
q243986
Config.isImageOptimizationEnabled
validation
public function isImageOptimizationEnabled() { if ($this->isFastlyEnabled() !== true) { return false; } return $this->_scopeConfig->isSetFlag(self::XML_FASTLY_IMAGE_OPTIMIZATIONS); }
php
{ "resource": "" }
q243987
Config.isImageOptimizationPixelRatioEnabled
validation
public function isImageOptimizationPixelRatioEnabled() { if ($this->isImageOptimizationEnabled() !== true) { return false; } return $this->_scopeConfig->isSetFlag(self::XML_FASTLY_IMAGE_OPTIMIZATIONS_PIXEL_RATIO); }
php
{ "resource": "" }
q243988
Config.getGeoIpMappingForCountry
validation
public function getGeoIpMappingForCountry($countryCode) { if ($mapping = $this->_scopeConfig->getValue(self::XML_FASTLY_GEOIP_COUNTRY_MAPPING)) { return $this->extractMapping($mapping, $countryCode); } return null; }
php
{ "resource": "" }
q243989
Config.extractMapping
validation
private function extractMapping($mapping, $countryCode) { $final = null; $extractMapping = json_decode($mapping, true); if (!$extractMapping) { try { $extractMapping = unserialize($mapping); // @codingStandardsIgnoreLine } catch (\Exception $e) { $extractMapping = []; } } if (is_array($extractMapping)) { $countryId = 'country_id'; $key = 'store_id'; // check for direct match foreach ($extractMapping as $map) { if (is_array($map) && isset($map[$countryId]) && strtolower(str_replace(' ', '', $map[$countryId])) == strtolower($countryCode)) { if (isset($map[$key])) { return (int)$map[$key]; } } elseif (is_array($map) && isset($map[$countryId]) && $map[$countryId] == '*' && isset($map[$key]) && $final === null) { // check for wildcard $final = (int)$map[$key]; } } } return $final; }
php
{ "resource": "" }
q243990
Config.getVclFile
validation
public function getVclFile($vclTemplatePath) // @codingStandardsIgnoreLine - Unused parameter required due to compatibility with parent class { $moduleEtcPath = $this->reader->getModuleDir(Dir::MODULE_ETC_DIR, 'Fastly_Cdn'); $configFilePath = $moduleEtcPath . '/' . $this->_scopeConfig->getValue(self::FASTLY_CONFIGURATION_PATH); $directoryRead = $this->readFactory->create($moduleEtcPath); $configFilePath = $directoryRead->getRelativePath($configFilePath); $data = $directoryRead->readFile($configFilePath); return strtr($data, $this->getReplacements()); }
php
{ "resource": "" }
q243991
Config.getVclSnippets
validation
public function getVclSnippets($path = '/vcl_snippets', $specificFile = null) { $snippetsData = []; $moduleEtcPath = $this->reader->getModuleDir(Dir::MODULE_ETC_DIR, 'Fastly_Cdn') . $path; $directoryRead = $this->readFactory->create($moduleEtcPath); if (!$specificFile) { $files = $directoryRead->read(); if (is_array($files)) { foreach ($files as $file) { if (substr($file, strpos($file, ".") + 1) !== 'vcl') { continue; } $snippetFilePath = $moduleEtcPath . '/' . $file; $snippetFilePath = $directoryRead->getRelativePath($snippetFilePath); $type = explode('.', $file)[0]; $snippetsData[$type] = $directoryRead->readFile($snippetFilePath); } } } else { $snippetFilePath = $moduleEtcPath . '/' . $specificFile; $snippetFilePath = $directoryRead->getRelativePath($snippetFilePath); $type = explode('.', $specificFile)[0]; $snippetsData[$type] = $directoryRead->readFile($snippetFilePath); } return $snippetsData; }
php
{ "resource": "" }
q243992
Config.validateCustomSnippet
validation
public function validateCustomSnippet($name, $type, $priority) { $snippetName = str_replace(' ', '', $name); $types = ['init', 'recv', 'hit', 'miss', 'pass', 'fetch', 'error', 'deliver', 'log', 'hash', 'none']; $inArray = in_array($type, $types); $isNumeric = is_numeric($priority); $isAlphanumeric = preg_match('/^[\w]+$/', $snippetName); $error = null; if (!$inArray) { $error = 'Type value is not recognised.'; return [ 'snippet_name' => null, 'error' => $error ]; } if (!$isNumeric) { $error = 'Please make sure that the priority value is a number.'; return [ 'snippet_name' => null, 'error' => $error ]; } if (!$isAlphanumeric) { $error = 'Please make sure that the name value contains only alphanumeric characters.'; return [ 'snippet_name' => null, 'error' => $error ]; } return [ 'snippet_name' => $snippetName, 'error' => $error ]; }
php
{ "resource": "" }
q243993
Config.processBlockedItems
validation
public function processBlockedItems($strippedBlockedItems, $blockingType = null) { if (empty($blockingType)) { $blockingType = $this->_scopeConfig->getValue(self::XML_FASTLY_BLOCKING_TYPE); } if ($blockingType == '1') { $strippedBlockedItems = '!(' . $strippedBlockedItems . ')'; } return $strippedBlockedItems; }
php
{ "resource": "" }
q243994
ThunderArticleBreadcrumbBuilder.getRequestForPath
validation
protected function getRequestForPath($path, array $exclude) { if (!empty($exclude[$path])) { return NULL; } // @todo Use the RequestHelper once https://www.drupal.org/node/2090293 is // fixed. $request = Request::create($path); // Performance optimization: set a short accept header to reduce overhead in // AcceptHeaderMatcher when matching the request. $request->headers->set('Accept', 'text/html'); // Find the system path by resolving aliases, language prefix, etc. $processed = $this->pathProcessor->processInbound($path, $request); if (empty($processed) || !empty($exclude[$processed])) { // This resolves to the front page, which we already add. return NULL; } $this->currentPath->setPath($processed, $request); // Attempt to match this path to provide a fully built request. try { $request->attributes->add($this->router->matchRequest($request)); return $request; } catch (ParamNotConvertedException $e) { return NULL; } catch (ResourceNotFoundException $e) { return NULL; } catch (MethodNotAllowedException $e) { return NULL; } catch (AccessDeniedHttpException $e) { return NULL; } }
php
{ "resource": "" }
q243995
FilterExtension.plainText
validation
public static function plainText($value) { $element = render($value); $element = strip_tags($element); $element = html_entity_decode($element, ENT_QUOTES); return $element; }
php
{ "resource": "" }
q243996
ImportSubscriber.onImport
validation
public function onImport(ImportEvent $event) { $uuids = [ '0bd5c257-2231-450f-b4c2-ab156af7b78d', '36b2e2b2-3df0-43eb-a282-d792b0999c07', '94ad928b-3ec8-4bcb-b617-ab1607bf69cb', 'bbb1ee17-15f8-46bd-9df5-21c58040d741', ]; foreach ($event->getImportedEntities() as $entity) { if (in_array($entity->uuid(), $uuids)) { $entity->moderation_state->value = 'published'; $entity->save(); } } }
php
{ "resource": "" }
q243997
ConfigEventsSubscriber.configDelete
validation
public function configDelete(ConfigCrudEvent $event) { $config = $event->getConfig(); if ($config->getName() === 'views.view.thunder_media' && ($media_view = View::load('media'))) { $media_view->setStatus(TRUE)->save(); } }
php
{ "resource": "" }
q243998
ThunderTaxonomyPermissions.permissions
validation
public function permissions() { $permissions = []; foreach ($this->entityTypeManager->getStorage('taxonomy_vocabulary')->loadMultiple() as $vocabulary) { $permissions += [ 'view published terms in ' . $vocabulary->id() => [ 'title' => $this->t('View published terms in %vocabulary', ['%vocabulary' => $vocabulary->label()]), ], 'view unpublished terms in ' . $vocabulary->id() => [ 'title' => $this->t('View unpublished terms in %vocabulary', ['%vocabulary' => $vocabulary->label()]), ], ]; } return $permissions; }
php
{ "resource": "" }
q243999
LeakyBucket.getNewRatio
validation
protected function getNewRatio($key, $limit, $milliseconds) { $lastRequest = $this->getLastRequest($key) ?: 0; $lastRatio = $this->getLastRatio($key) ?: 0; $diff = (microtime(1) - $lastRequest) * 1000; $newRatio = $lastRatio - $diff; $newRatio = $newRatio < 0 ? 0 : $newRatio; $newRatio+= $milliseconds/$limit; return $newRatio; }
php
{ "resource": "" }