varnish-4.1.2 configuration for magento2 - magento2

I am trying to configure varnish-4.1.2 for magento2 CE.I replaced downloded varnish 4 configuraton file to my default.vcl . /etc/default/varnish and /etc/varnish/default.vcl is configured as follows.
/etc/default/varnish
START=yes
NFILES=131072
MEMLOCK=82000
DAEMON_OPTS="-a :80 \
-T localhost:6082 \
-f /etc/varnish/default.vcl \
-S /etc/varnish/secret \
-s malloc,256m"
/etc/varnish/default.vcl/
vcl 4.0;
import std;
backend default {
.host = "xx.xx.xx.xx";
.port = "8080";
.first_byte_timeout = 600s;
}
acl purge {
"xx.xx.xxx.xx";
}
sub vcl_recv {
if (req.method == "PURGE") {
if (client.ip !~ purge) {
return (synth(405, "Method not allowed"));
}
if (!req.http.X-Magento-Tags-Pattern) {
return (synth(400, "X-Magento-Tags-Pattern header required"));
}
ban("obj.http.X-Magento-Tags ~ " + req.http.X-Magento-Tags-Pattern);
return (synth(200, "Purged"));
}
if (req.method != "GET" &&
req.method != "HEAD" &&
req.method != "PUT" &&
req.method != "POST" &&
req.method != "TRACE" &&
req.method != "OPTIONS" &&
req.method != "DELETE") {
/* Non-RFC2616 or CONNECT which is weird. */
return (pipe);
}
# We only deal with GET and HEAD by default
if (req.method != "GET" && req.method != "HEAD") {
return (pass);
}
# Bypass shopping cart and checkout requests
if (req.url ~ "/checkout") {
return (pass);
}
# normalize url in case of leading HTTP scheme and domain
set req.url = regsub(req.url, "^http[s]?://", "");
# collect all cookies
std.collect(req.http.Cookie);
# static files are always cacheable. remove SSL flag and cookie
if (req.url ~ "^/(pub/)?(media|static)/.*\.(ico|css|js|jpg|jpeg|png|gif|tiff|bmp|mp3|ogg|svg|swf|woff|woff2|eot|ttf|otf)$") {
unset req.http.Https;
unset req.http.Cookie;
}
return (hash);
}
sub vcl_hash {
if (req.http.cookie ~ "X-Magento-Vary=") {
hash_data(regsub(req.http.cookie, "^.*?X-Magento-Vary=([^;]+);*.*$","\1"));
}
}
sub vcl_backend_response {
if (beresp.http.content-type ~ "text") {
set beresp.do_esi = true;
}
if (bereq.url ~ "\.js$" || beresp.http.content-type ~ "text") {
set beresp.do_gzip = true;
}
# cache only successfully responses and 404s
if (beresp.status != 200 && beresp.status != 404) {
set beresp.ttl = 0s;
set beresp.uncacheable = true;
return (deliver);
} elsif (beresp.http.Cache-Control ~ "private") {
set beresp.uncacheable = true;
set beresp.ttl = 86400s;
return (deliver);
}
if (beresp.http.X-Magento-Debug) {
set beresp.http.X-Magento-Cache-Control = beresp.http.Cache-Control;
}
# validate if we need to cache it and prevent from setting cookie
# images, css and js are cacheable by default so we have to remove cookie
if (beresp.ttl > 0s && (bereq.method == "GET" || bereq.method == "HEAD"))
{
unset beresp.http.set-cookie;
if (bereq.url !~ "\. (ico|css|js|jpg|jpeg|png|gif|tiff|bmp|gz|tgz|bz2|tbz|mp3|ogg|svg|swf|woff|woff2| eot|ttf|otf)(\?|$)") {
set beresp.http.Pragma = "no-cache";
set beresp.http.Expires = "-1";
set beresp.http.Cache-Control = "no-store, no-cache, must-revalidate, max-age=0";
set beresp.grace = 1m;
}
}
return (deliver);
}
sub vcl_deliver {
if (resp.http.X-Magento-Debug) {
if (resp.http.x-varnish ~ " ") {
set resp.http.X-Magento-Cache-Debug = "HIT";
} else {
set resp.http.X-Magento-Cache-Debug = "MISS";
}
} else {
unset resp.http.Age;
}
unset resp.http.X-Magento-Debug;
unset resp.http.X-Magento-Tags;
unset resp.http.X-Powered-By;
unset resp.http.Server;
unset resp.http.X-Varnish;
unset resp.http.Via;
unset resp.http.Link;
}
but I am getting error
Error: Message from VCC-compiler: Unterminated string at
('/etc/varnish/default.vcl' Line 19 Pos 32)
return (synth(400, "X-Magento-Tags-Pattern header
-------------------------------###############################
Running VCC-compiler failed, exited with 2 VCL compilation failed
How do i solve this issue?

Related

make a custom error message and prevent duplicate mail id from inserting in db

I have checked email unique in codeigniter. In else past I diplayed error. But the system error is not convenient. how to customise error...
i have tried giveng javascript alert instead of that error message... but after that alert the data are storing in database.. Actually the data should not store in database if the email is not unique..
public function add_applicants() {
// $field_name=$this->input->post('photo');
$data = $this->input->post();
$mobile = $this->db->get_where('applicants',array('mobile_number'=>$this->input->post('mobile_number')));
if($mobile->num_rows()>0)
{
throw new Exception("Mobile Number Already Registered");
}
$email = $this->db->get_where('applicants',array('email_id'=>$this->input->post('email_id')));
if($email->num_rows()>0)
{
throw new Exception("Email_id Already Registered");
}
$school_id= $this->input->post('school_code');
$name_of_exam= $this->input->post('name_of_exam');
$name= $this->input->post('name_candiadte');
switch($name_of_exam){
case '1':
$exam='NMMS';
break;
case '2':
$exam='NTS';
break;
}
$school_code = $this->Welcome_Model->getschoolData($school_id);
if (isset($_FILES['photo']) == 1) {
$config['upload_path'] = FCPATH . 'uploads/'. $school_code->name_of_the_school.'/'. $exam ;
$this->upload_path = $config['upload_path'];
if ($this->validate_upload_path() == TRUE) {
$config['upload_path'] = $this->upload_path;
// print_r($this->upload_path) ;
// die();
}
$config['allowed_types'] = 'jpg';
$config['max_size'] = 2000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = true;
$config['file_name'] = $name.'-'.date('Ymdhis') . '.jpg';
$file_name = $config['file_name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('photo')) {
$this->upload->display_errors();
}
}
$data['photo'] = $file_name;
$insetapplicants = $this->Welcome_Model->insertApplicants($data);
if ($insetapplicants == 'Success') {
echo "<script>
alert('New Applicants Added Successfully');
// window.location.href='dashboard';
</script>";
}
}

How to set expiration of newsletter confirmation link in magento 2

I have newsletter in my magento website. I have enable confirmation before subscription from admin configuration. User are getting confirmation link in mail.
But I want to set expiry of that link. Is magento provide default config ?
How can I set expiry of that link ?
I found the solution. I just did two things.
1) Add created_at field in newsletter_subscriber table.
2) Overwrite the following file
vendor/magento/module-newsletter/Model/Subscriber.php
to
Company/name/Model/Subscriber.php
Overited Subscriber.php file code
public function confirm($code) // existing function
{
$id = $this->getId();
if ($this->validateConfirmLinkToken($id, $code)) {
if ($this->getCode() == $code) {
$this->setStatus(self::STATUS_SUBSCRIBED)
->setStatusChanged(true)
->save();
$this->sendConfirmationSuccessEmail();
return true;
}
return false;
}
}
private function validateConfirmLinkToken($customerId, $code) //check validation for token
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$messageManager = $objectManager->get('Magento\Framework\Message\ManagerInterface');
if (empty($customerId) || $customerId < 0) {
$this->_messageManager->addError('Sorry you have not rigts to access this page');
return false;
}
if (!is_string($code) || empty($code)) {
$params = ['fieldName' => 'code'];
//$messageManager->addError('Sorry Your subscription confirmation code is not valid.');
return false;
}
$dcode = $this->getCode();
$dcreated_at = $this->getCreatedAt();
if (trim($dcode) != trim($code)) {
//$messageManager->addError('Sorry Your subscription confirmation code is mismatch.');
return false;
} elseif ($this->isConfirmationLinkTokenExpired($dcode, $dcreated_at)) {
//$messageManager->addError('Sorry Your subscription confirmation code is expired.');
return false;
}
return true;
}
public function isConfirmationLinkTokenExpired($dcode, $dcreated_at) // check expiration token
{
if (empty($dcode) || empty($dcreated_at)) {
return true;
}
$expirationPeriod = '720';
$currentTimestamp = (new \DateTime())->getTimestamp();
$tokenTimestamp = (new \DateTime($dcreated_at))->getTimestamp();
if ($tokenTimestamp > $currentTimestamp) {
return true;
}
$hourDifference = floor(($currentTimestamp - $tokenTimestamp) / (60 * 60));
if ($hourDifference >= $expirationPeriod) {
return true;
}
return false;
}
Hope it will helps to many.
Thanks.

Magento 2 - new inscription newsletter error (no such entity with customerId = 0)

I always have this error when I try to register to newsletter in Magento 2. The error is:
No such entity with customerId = 0
If I try to add it directly from database, it works perfectly.
The function is :
vendor/magento/module-newsletter/Model/Subscriber.php
public function subscribe($email)
{
$this->loadByEmail($email);
if (!$this->getId()) {
$this->setSubscriberConfirmCode($this->randomSequence());
}
$isConfirmNeed = $this->_scopeConfig->getValue(
self::XML_PATH_CONFIRMATION_FLAG,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
) == 1 ? true : false;
$isOwnSubscribes = false;
$isSubscribeOwnEmail = $this->_customerSession->isLoggedIn()
&& $this->_customerSession->getCustomerDataObject()->getEmail() == $email;
if (!$this->getId() || $this->getStatus() == self::STATUS_UNSUBSCRIBED
|| $this->getStatus() == self::STATUS_NOT_ACTIVE
) {
if ($isConfirmNeed === true) {
// if user subscribes own login email - confirmation is not needed
$isOwnSubscribes = $isSubscribeOwnEmail;
if ($isOwnSubscribes == true) {
$this->setStatus(self::STATUS_SUBSCRIBED);
} else {
$this->setStatus(self::STATUS_NOT_ACTIVE);
}
} else {
$this->setStatus(self::STATUS_SUBSCRIBED);
}
$this->setSubscriberEmail($email);
}
if ($isSubscribeOwnEmail) {
try {
$customer = $this->customerRepository->getById($this->_customerSession->getCustomerId());
$this->setStoreId($customer->getStoreId());
$this->setCustomerId($customer->getId());
} catch (NoSuchEntityException $e) {
$this->setStoreId($this->_storeManager->getStore()->getId());
$this->setCustomerId(0);
}
} else {
$this->setStoreId($this->_storeManager->getStore()->getId());
$this->setCustomerId(0);
}
$this->setStatusChanged(true);
try {
$this->save();
if ($isConfirmNeed === true
&& $isOwnSubscribes === false
) {
$this->sendConfirmationRequestEmail();
} else {
$this->sendConfirmationSuccessEmail();
}
return $this->getStatus();
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}

RESTful uploading of a video file in PHP

I want to upload a video file to a server using POST request. There is not much information available about it in the internet.
I usually do check the data what i have send using this code
$params = $_REQUEST;
return $params;
I check it in POSTMAN. I have table called video_review
id
video_url
movie_id
user_id
date_time
when i choose a video file and click send i want the location of video file to be saved into the video_url field. But in the controller when i run this code return $params; i get nothing.
EDIT
Made some progress
public function actionCreate_video_review()
{
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma","mkv");
$extension = pathinfo($_FILES['video_url']['name'], PATHINFO_EXTENSION);
if ( ($_FILES["video_url"]["type"] == "video/mp4")|| ($_FILES["video_url"]["type"] == "video/x-matroska")
&& ($_FILES["video_url"]["size"] < 20000)
&& in_array($extension, $allowedExts) )
{
if ($_FILES["video_url"]["error"] > 0)
{
return $_FILES["video_url"]["error"];
}
else
{
if (file_exists("upload/" . $_FILES["video_url"]["name"]))
{
echo $_FILES["video_url"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["video_url"]["tmp_name"],
"upload/" . $_FILES["video_url"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["video_url"]["name"];
return $_FILES["video_url"]["name"];
}
}}
i got it working.
//POST Video Reviews
public function actionCreate_video_review()
{
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma","mkv");
$extension = pathinfo($_FILES['video_url']['name'], PATHINFO_EXTENSION);
if ( ($_FILES["video_url"]["type"] == "video/mp4")|| ($_FILES["video_url"]["type"] == "video/x-matroska")&& ($_FILES["video_url"]["size"] < 90000) && in_array($extension, $allowedExts) )
{
if ($_FILES["video_url"]["error"] > 0)
{
return $_FILES["video_url"]["error"];
}
else
{
if (file_exists("upload/" . $_FILES["video_url"]["name"]))
{
echo $_FILES["video_url"]["name"] . " already exists. ";
}
else
{
$model = new \app\models\VideoReview();
$model->video_url = $_FILES["video_url"]["name"];
$model->save();
move_uploaded_file($_FILES["video_url"]["tmp_name"],
\Yii::$app->basePath. '/web/uploads/' . $_FILES["video_url"]["name"]);
return $_FILES["video_url"]["name"];
}
}
}
else
{
return $_FILES["video_url"]["error"] ."Error";
}
}

how to validate zend form where at one field in required between two fields

I have two elements, adult no and children no, at least one field is required. How to validate this in zend framework and generate error message.
You need to create Your own validator. In this case i think You could use Zend_Validate_Identical, copy its code and change isValid method to something like this:
public function isValid($value, $context = null)
{
$this->_setValue((string) $value);
if (($context !== null) && isset($context) && array_key_exists($this->getToken(), $context)) {
$token = $context[$this->getToken()];
} else {
$token = $this->getToken();
}
if ($token === null) {
$this->_error(self::MISSING_TOKEN);
return false;
}
$strict = $this->getStrict();
// change != to ==
if (($strict && ($value === $token)) || (!$strict && ($value == $token)) && (&token =='' || $value == '') {
$this->_error(self::**YOUR_ERROR _CODE**);
return false;
}
return true;
}
This code is not tested but it should work :)