I'm currently developing a payment plugin for VirtueMart. I have never used it before. The goal is:
When the user clicks to the confirm order button, he gets redirected to the bank interface (managed it, no work needed)
He then gets redirected back to the webshop with an answer from the bank (also done)
If the transaction is success, the order is stored as confirmed or if the transaction fails, the order is getting cancelled.
What I managed, is marked in the list above. For some reason, the order gets stored twice as pending, once when the user clicks the button, and once when the user gets redirected back to the shop. Also, if the transaction fails, the order is stored twice, also pending. I reused the standard payment plugin given with the VirtueMart aio package. All the above stuff is written in the plgVmConfirmedOrder function. I would post it here:
function plgVmConfirmedOrder ($cart, $order) {
if (!($method = $this->getVmPluginMethod ($order['details']['BT']->virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if (!$this->selectedThisElement ($method->payment_element)) {
return FALSE;
}
VmConfig::loadJLang('com_virtuemart',true);
VmConfig::loadJLang('com_virtuemart_orders', TRUE);
if (!class_exists ('VirtueMartModelOrders')) {
require(VMPATH_ADMIN . DS . 'models' . DS . 'orders.php');
}
$this->getPaymentCurrency($method);
$currency_code_3 = shopFunctions::getCurrencyByID($method->payment_currency, 'currency_code_3');
$email_currency = $this->getEmailCurrency($method);
$totalInPaymentCurrency = vmPSPlugin::getAmountInCurrency($order['details']['BT']->order_total,$method->payment_currency);
$dbValues['payment_name'] = $this->renderPluginName ($method) . '<br />' . $method->payment_info;
$dbValues['order_number'] = $order['details']['BT']->order_number;
$dbValues['virtuemart_paymentmethod_id'] = $order['details']['BT']->virtuemart_paymentmethod_id;
$dbValues['cost_per_transaction'] = $method->cost_per_transaction;
$dbValues['cost_percent_total'] = $method->cost_percent_total;
$dbValues['payment_currency'] = $currency_code_3;
$dbValues['email_currency'] = $email_currency;
$dbValues['payment_order_total'] = $totalInPaymentCurrency['value'];
$dbValues['tax_id'] = $method->tax_id;
$payment_info='';
if (!empty($method->payment_info)) {
$lang = JFactory::getLanguage ();
if ($lang->hasKey ($method->payment_info)) {
$payment_info = vmText::_ ($method->payment_info);
} else {
$payment_info = $method->payment_info;
}
}
if (!class_exists ('VirtueMartModelCurrency')) {
require(VMPATH_ADMIN . DS . 'models' . DS . 'currency.php');
}
$currency = CurrencyDisplay::getInstance ('', $order['details']['BT']->virtuemart_vendor_id);
if(!array_key_exists("fizetesValasz", $_REQUEST)){
$transaction_id = $this->getTransactionID();
$_REQUEST['tranzakcioAzonosito'] = $transaction_id;
$price = $cart->cartPrices['billTotal'];
$_REQUEST['osszeg'] = round($price);
$_REQUEST['devizanem'] = 'HUF';
$_REQUEST['backURL'] = "http://" . $_SERVER['SERVER_NAME'] . '/component/virtuemart/cart/confirm.html?Itemid=' . $_REQUEST['Itemid'];
$_REQUEST['nyelvkod'] = 'hu';
$dbValues['transaction_id'] = $transaction_id;
//this is where I redirect to the bank interface
process();
}
else{
//this is where I get the data about transaction
$transaction_datas = processDirectedToBackUrl(false);
$status_code = $transaction_datas->getStatuszKod();
$dbValues['otp_response'] = $status_code;
$this->storePSPluginInternalData ($dbValues);
$modelOrder = VmModel::getModel ('orders');
switch ($status_code) {
case 'FELDOLGOZVA':
if($transaction_datas->isSuccessful()){
$message = 'Sikeres Tranzakció!';
$new_status = $this->getNewStatus($method);
$order['customer_notified'] = 1;
$order['comments'] = '';
$modelOrder->updateStatusForOneOrder ($order['details']['BT']->virtuemart_order_id, $order, TRUE);
$message = getMessageText(($transaction_datas->getPosValaszkod()));
$cart->emptyCart();
$html = $this->renderByLayout('post_payment_success', array(
'message' =>$message,
'order_number' =>$order['details']['BT']->order_number,
'order_pass' =>$order['details']['BT']->order_pass,
'payment_name' => $dbValues['payment_name'],
'displayTotalInPaymentCurrency' => round($totalInPaymentCurrency['display'])
));
vRequest::setVar ('html', $html);
return TRUE;
}
else{
$new_status = $method->status_cancelled;
$modelOrder->updateStatusForOneOrder($order['details']['BT']->virtuemart_order_id, $order, TRUE);
$message = 'Sajnos a bank visszautasította a tranzakciót.';
$html = $this->renderByLayout('post_payment_failure', array(
'message' => $message
));
vRequest::setVar('html', $html);
return FALSE;
}
break;
case 'VEVOOLDAL_VISSZAVONT':
return FALSE;
break;
case 'VEVOOLDAL_TIMEOUT':
return FALSE;
break;
}
}
return FALSE;
}
Every help is appreciated. Thanks in advance!
So, the problem was the redirect url. There is an action called plgVmOnPaymentResponseReceived(). This is fired when a specific url is called. I only had to rewrite the $_REQUEST parameter for the redirection.
Related
I need to edit record in database from inline button.
Bot send message to user with record text and add inline button actions for it (i.e. Edit, Delete etc.)
User click button, from callback starts EditCommand with new conversation. but after first case next message dont call execute() EditCommand - conversation disappeared.
$query->getData() contains action and record ID like action=edit&id=3
how can I get user input after inline button click?
//hook.php
CallbackqueryCommand::addCallbackHandler(function($query) use ($telegram) {
...
case 'myaction':
return $telegram->executeCommand('edit');
}
// EditCommand.php
public function execute()
{
if ($this->getCallbackQuery() !== null) {
$message = $this->getCallbackQuery()->getMessage();
}
else {
$message = $this->getMessage();
}
$this->conversation = new Conversation($user_id, $chat_id, $this->getName());
$notes = &$this->conversation->notes;
!is_array($notes) && $notes = [];
$state = 0;
if (isset($notes['state'])) {
$state = $notes['state'];
}
$result = Request::emptyResponse();
switch ($state) {
case 0:
if ($text === '') {
$notes['state'] = 0;
$this->conversation->update();
$data['text'] = 'Choose button';
$data['reply_markup'] = $keyboard;
$result = Request::sendMessage($data);
break;
}
$notes['laundry'] = $text;
$text = '';
case 1:
...
and then in EditCommand execute() triggered only once. I think because second message from user is not callback.
solved. conversation must created like
$this->conversation = new Conversation(null !== $this->getCallbackQuery() ? $chat_id : $user_id, $chat_id, $this->getName());
I am quite new to laravel I have to insert many form fields in database so I divided the fields into multiple sections what I want to achieve is to store data of each section when user clicks next button and step changes and when user clicks previous button and makes some changes the database should be updated and if user leaves the form incomplete then when he logins next time form fill should fill up from the step he left in, till now i have successfully achieved to change steps and in first step 1 inserted the data into database and for other step i updated the database but I am having trouble if user comes to first step and again changes the forms fields how to update again first step data i am using ajax to send data and steps number
My Controller
function saveJobPostFirstStage(Request $request)
{
$currentEmployer = Auth::guard('employer')->user();
//$data['currentEmployer'] = $currentEmployer;
$employer_id = $currentEmployer->id;
$random = $this->generateRandomString();
$jobOne = new Job();
//Session::pull('insertedId');
if ($request->ajax()) {
try {
$stepPost = $request->all();
$step = $stepPost['stepNo'];
$insertedId = $stepPost['insertedId'];
switch ($step) {
case '1':
if ($insertedId == 0) {
$jobOne->employer_id = $employer_id;
$jobOne->job_title = $stepPost['jobTitle'];
$jobOne->company_id = (int)$stepPost['companyName'];
$jobOne->country_id = (int)$stepPost['country'];
$jobOne->state_id = (int)$stepPost['state'];
$jobOne->city_id = (int)$stepPost['city'];
$jobOne->street_address = $stepPost['street'];
$jobOne->job_code = $random;
$stepOne = $jobOne->save();
if ($stepOne) {
Session::put('insertedId',$jobOne->id);
//session(['insertedId'=>$jobOne->id]);
$success = ['success' => "Success",
'insertedId' => $jobOne->id];
//return json_encode($success);
}
}
else
{
$jobOne->employer_id = $employer_id;
$jobOne->job_title = $stepPost['jobTitle'];
$jobOne->company_id = (int)$stepPost['companyName'];
$jobOne->country_id = (int)$stepPost['country'];
$jobOne->state_id = (int)$stepPost['state'];
$jobOne->city_id = (int)$stepPost['city'];
$jobOne->street_address = $stepPost['street'];
$jobOne->job_code = $random;
$stepOne = $jobOne->whereId($insertedId)->update(['employer_id'=>$jobOne->employer_id,'job_title'=>$jobOne->job_title,'company_id'=> $jobOne->company_id,'state_id'=>$jobOne->state_id,'country_id'=>$jobOne->country_id,'city_id'=>$jobOne->city_id,'street_address'=>$jobOne->street_address,'job_code'=>$jobOne->job_code = $random]);
if ($stepOne) {
$success = ['success' => "Changes Made Successfully"];
return json_encode($success);
}
}
break;
case '2':
$jobOne->employment_type_id = (int)($stepPost['employmentType']);
$jobOne->job_type_id = (int)($stepPost['jobType']);
$jobOne->job_level_id = (int)($stepPost['jobLevel']);
$jobOne->industry_type_id = (int)($stepPost['industryType']);
$jobOne->job_category_id = (int)($stepPost['jobCategory']);
//$jobOne->salary = $stepPost['jobSalaryRange'];
$jobOne->salary_period_id = (int)$stepPost['salaryPeriod'];
//$jobOne->vacancy_end_date = $stepOne['applicationDeadline'];
$stepOne = $jobOne->whereId($insertedId)->update(['employment_type_id'=> $jobOne->employment_type_id,'job_type_id'=>$jobOne->job_type_id,'job_level_id'=> $jobOne->job_level_id,'industry_type_id'=>$jobOne->industry_type_id,'job_category_id'=>$jobOne->job_category_id,'salary_period_id'=>$jobOne->salary_period_id]);
if ($stepOne) {
$success = ['success' => "Changes Made Successfully"];
return json_encode($success);
}
break;
case '3':
$jobOne->job_description = $stepPost['jobDescription'];
$jobOne->job_specification = $stepPost['jobSpecifications'];
$jobOne->job_responsibilities = $stepPost['jobResponsibilities'];
$stepOne = $jobOne->whereId($insertedId)->update(['job_description'=>$jobOne->job_description,'job_specification'=>$jobOne->job_specification,'job_responsibilities'=>$jobOne->job_responsibilities]);
if ($stepOne) {
$success = ['success' => "Changes Made Successfully"];
return json_encode($success);
}
default:
# code...
break;
}
return json_encode($stepPost);
//$this->alertMessage = 'Your Phone has been added Successfully.';
//$this->alertType = 'success';
} catch (QueryException $e) {
return $e->getMessage();
}
/* return redirect()->route('employer-account-page')
->with([
'alertMessage' => $this->alertMessage,
'alertType' => $this->alertType
]);*/
// $stepPost = Input::all();
}
/*$stepOne = $request->all();
$country_Id = (int)$stepOne['country'];
return json_encode((getType($country_Id)));*/
}
First of, your code is messy.
You should have a single table per form where each form have it's parent id.
The next step to refactor the code would be to create a single controler per form (you don't need it, but you want this)
Each form (a model) should have a method that recalculates the values of itself based on other forms, so that if you change a first form, then you can call the method that recalculates the second form, then call method of second form that recalculates the third form, etc.
This interface could be helpful
interface IForm {
public function getPreviousForm() : ?IForm; // These notations are since PHP7.1
public function recalculate() : void;
public function getNextForm() : ?IForm;
}
A simple code how it should work in practice
$formX->save();
$formX->getNextForm()->recalculate(); // This will call formX->recalculate(); formX+1->getNextForm()->recalculate()
// which will call formX+1->recalculate(); formX+2->getNextForm()->recalculate()
// etc...
// while getNextForm() != null
You may also need this if you would need to insert another form in the middle of the chain.
Hope it helps
I have a csv file containing about 3500 user's data. I want to import these users to my database and send them an email that they are registered.
I have the following code:
public function importUsers()
{
$this->load->model('perk/engagement_model');
$this->load->model('user/users_model');
$this->load->model('acl/aclUserRoles_model');
$allengagements = $this->engagement_model->getAll();
$filename = base_url() . 'assets/overdracht_users.csv';
$file = fopen($filename, "r");
$count = 0;
$totalImported = 0;
$importFails = array();
$mailFails = array();
while (($mappedData = fgetcsv($file, 10000, ";")) !== FALSE)
{
$count++;
//Skip first line because it is the header
if ($count > 1) {
if (!empty($mappedData[0])) {
$email = $mappedData[0];
$user = $this->users_model->getByEmail($email);
if (!$user) {
$user = new stdClass();
$user->email = $mappedData[0];
$user->first_name = $mappedData[1];
$user->family_name = $mappedData[2];
$user->address_line1 = $mappedData[3];
$user->address_postal_code = $mappedData[4];
$user->address_city = $mappedData[5];
$user->address_country = 'BE';
$user->volunteer_location = $mappedData[5];
$user->volunteer_location_max_distance = 50;
$user->phone = $mappedData[6];
if (!empty($mappedData[7])) {
$user->birthdate = $mappedData[7] . "-01-01 00:00:00";
} else {
$user->birthdate = null;
}
foreach ($allengagements as $eng) {
if ($eng->description == $mappedData[8]) {
$engagement = $eng->engagement_id;
}
}
$user->engagement = $engagement;
if (!empty($mappedData[9])) {
$date_created = str_replace('/', '-', $mappedData[9]);
$date_created = date('Y-m-d H:i:s', strtotime($date_created));
} else {
$date_created = date('Y-m-d H:i:s');
}
$user->created_at = $date_created;
if (!empty($mappedData[10])) {
$date_login = str_replace('/', '-', $mappedData[10]);
$date_login = date('Y-m-d H:i:s', strtotime($date_login));
} else {
$date_login = null;
}
$user->last_login = $date_login;
$user->auth_level = 1;
$user->is_profile_public = 1;
$user->is_account_active = 1;
$combinedname = $mappedData[1] . $mappedData[2];
$username = str_replace(' ', '', $combinedname);
if (!$this->users_model->isUsernameExists($username)) {
$uniqueUsername = $username;
} else {
$counter = 1;
while ($this->users_model->isUsernameExists($username . $counter)) {
$counter++;
}
$uniqueUsername = $username . $counter;
}
$user->username = $uniqueUsername;
$userid = $this->users_model->add($user);
if (!empty($userid)) {
$totalImported++;
//Add the user in the volunteer group in ACL
$aclData = [
'userID' => $userid,
'roleID' => 1,
'addDate' => date('Y-m-d H:i:s')
];
$this->aclUserRoles_model->add($aclData);
//Registration mail to volunteer
$mail_data['name'] = $user->first_name . ' ' . $user->family_name;
$mail_data['username'] = $user->username;
$this->email->from(GENERAL_MAIL, 'Test');
$this->email->to($user->email);
//$this->email->bcc(GENERAL_MAIL);
$this->email->subject('Test');
$message = $this->load->view('mail/register/registration',$mail_data,TRUE);
$this->email->message($message);
$mailsent = $this->email->send();
if (!$mailsent) {
array_push($mailFails, $mappedData);
}
} else {
array_push($importFails, $mappedData);
}
if ($count % 50 == 0) {
var_dump("count is " . $count);
var_dump("we are sleeping");
$min=20;
$max=40;
$randSleep = rand($min,$max);
sleep($randSleep);
var_dump("end of sleep (which is " . $randSleep . "seconds long)");
}
var_dump($user);
} else {
array_push($importFails, $mappedData);
}
}
}
}
var_dump("Totale aantal rijen in het bestand (met header) : " . $count);
var_dump("Totale aantal geimporteerd in de database : " . $totalImported);
var_dump("Totale aantal gefaalde imports in de database : " . count($importFails));
var_dump("Deze zijn gefailed : ");
var_dump($importFails);
}
If I do not add the users in the database, or send out a mail, and just var_dump() the $user, i can see all 3500+ users being correctly created in php objects (so they should be able to be inserted correctly).
The problem is that I want to add in a random sleep, between 20 and 40 seconds after every 50 mails that I sent.
So I started doing some testing and after commenting out the insert and mail code, I started running the script, noticing that after some amount (not 50 at all), it just stops for a bit, then continues and shows me the the var_dumps in my if case at the bottom, it can be shown here in the screenshots below.
The first screenshot shows the code stopping for a bit (note that I am only var_dumping stuff, i am not adding something in the database or sending out an email yet).
This screenshot shows what happens after the script reaches 200:
The script just completely stops from this point on. I have tried this 3 times, and every single time it stops exactly on 200.
What is happening here??
Most likely you're hitting default PHP limits. temporarily remove PHP default limits with:
ini_set('memory_limit',-1);
set_time_limit(0);
then, rerun the script and check your output.
There can be multiple reasons, but to know the exact one please enable error output with.
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
and if limits are not the problem, the errors will tell you more.
HINT: using logs are still better than outputting errors to the visitors, but my guess is you're testing this on your computer.
I am trying to upload an external list of "groups" to add to my custom Joomla 3 component. I have created a CSV file and written a few functions that I hope will do it. I have created a custom button to start the task in my "groups" view.
When I push the button I get an SQL error that has absoloutle nothing to do with the functions so I have tried debugging and when the button is pressed its not even getting to my controller task before the sql error. I am so confused as to why.
This is the code I have
view.html.php TestViewGroups
JToolBarHelper::custom('group.uploadsave', '', '', 'Upload and Save', false);
TestControllerGroup
protected function uploadsave() {
$detail_headers = array(
'agm_date',
'preferred_media'
);
$rows = array_map('str_getcsv', file('groupdata.csv'));
$header = array_shift($rows);
foreach ($rows as $row) {
$entry = array_combine($header, $row);
foreach ($entry as $key => $value) {
if(in_array($key, $detail_headers)){
$details[$key]= $value;
unset($entry[$key]);
}
}
$entry['details'] = $details;
$this->saveUploaded($entry);
}
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . '&view=' . $this->view_list
. $this->getRedirectToListAppend(), false
)
);
}
protected function saveUploaded($dataIn = array()) {
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();
$model = $this->getModel();
$table = $model->getTable();
$data = $dataIn;
$checkin = property_exists($table, 'checked_out');
// Determine the name of the primary key for the data.
if (empty($key))
{
$key = $table->getKeyName();
}
// To avoid data collisions the urlVar may be different from the primary key.
if (empty($urlVar))
{
$urlVar = $key;
}
$recordId = $this->input->getInt($urlVar);
// Populate the row id from the session.
$data[$key] = $recordId;
if (!$model->save($validData))
{
// Redirect back to the edit screen.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
}
if ($checkin && $model->checkin($validData[$key]) === false)
{
// Save the data in the session.
$app->setUserState($context . '.data', $validData);
// Check-in failed, so go back to the record and display a notice.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
}
$this->setMessage(
JText::_(
($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS')
? $this->text_prefix
: 'JLIB_APPLICATION') . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS'
)
);
}
I am not using this as a regular function, its just a once off to upload the data initially.
The SQL error I am getting is like it is trying to load a list of groups?? not anything to do with the save function at all.
The saveUploaded is a similar function to the initial save function.
Thanks :-)
**** Edit *****
I have just followed the task through with debug and its getting to the execute task methotd of JControllerLegacy and because the task is not defined in the task map its defaulting to display, hence the SQL error trying to load a group when it doesn't have an ID. Do I need to now register a task in the task map before it will pick it up?
I am officially an idiot! When I just logged back on to see if anyone had responded I saw that I had declared the function as a protected function!! dir! I just copied and pasted from another function and forgot to change its access. I also made a few other changes and now it works quite well!
public function uploadsave() {
// An array of headers that will need to be entered into a seperate array to allow entry as JSON
$detail_headers = array(
'agm_date',
'preferred_media'
);
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();
$model = $this->getModel();
$path = JPATH_COMPONENT . '/controllers/groupdata.csv';
//Load the file and pass each line into an array.
$rows = array_map('str_getcsv', file($path));
//Take out the first line as it is the headers.
$header = array_shift($rows);
//turn each of the arrays into an entry
foreach ($rows as $row) {
$entry = array_combine($header, $row);
foreach ($entry as $key => $value) {
//separate each of the entries that need to be entered into an array to be stored as JSON
if(in_array($key, $detail_headers)){
$details[$key]= $value;
unset($entry[$key]);
}
}
$entry['details'] = $details;
$recordId = 'id';
// Populate the row id from the session.
$entry[$key] = $recordId;
//Save each one
if (!$model->save($entry))
{
// Redirect back to the edit screen.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
return false;
}
$this->setMessage(
JText::_(
($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS')
? $this->text_prefix
: 'JLIB_APPLICATION') . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS'
)
);
}
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . '&view=' . $this->view_list
. $this->getRedirectToListAppend(), false
)
);
}
I am developing a WP plugin which processes shortcodes and displays amazon item data in place of them. The plugin is working as desired, except for a little strange behavior. You can see my test run at http://passivetest.themebandit.com/test-post-for-zon-plugin/ .
If you scroll down on that page, you can see that 4 "1" s are appended to the content. The shortcode is processed 4 times in this page, and each time WP is adding an undesired 1 to the output. I don't understand why this is happening. There is no "1" anywhere in my html files, and its nowhere in the post content. All my functions just return the content that is to be replaced in place of the shortcode. Can someone please give an explanation for it and let me know how to remove these? Thanks in advance..
My code is as follows:
add_shortcode('zon_product', 'zon_process_shortcode');
// Zon Shortcode processor
function zon_process_shortcode($attributes, $content = null) {
global $zon_html_path;
// default options for shortcode
$options = array('asin' => '', 'style' => 'compact', 'loc' => 'com');
extract(shortcode_atts($options, $attributes));
$asin = $attributes['asin'];
// first find asin in local zon_data table
$zdb = ZonDbHandler::instance();
$product = $zdb->findASIN($asin);
if ($product) {
// if product exists in db, render template
return zon_display_product($product, $attributes);
} else {
// product does not exist in database, get data through amazon api worflow
$product = ZonLibrary::getAmazonProduct($asin, $attributes['loc']);
if ($product) {
// product data has been successfully retrieved and saved, render template
return zon_display_product($product, $attributes);
} else {
// error in fetching product data, check amazon access key id and api secret
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . 'api_error.php');
return $content;
}
}
}
// Renders selected template with product data
function zon_display_product(ZonProduct $product, $attributes) {
global $zon_html_path;
global $zon_path;
// process other shortcode options
$view_vars = array();
$view_vars['style'] = (isset($attributes['style'])) ? $attributes['style'] : "default";
$view_vars['show_price'] = (isset($attributes['show_price']) && $attributes['show_price'] == 0) ? false : true;
$view_vars['price_updates'] = (isset($attributes['price_updates']) && $attributes['price_updates'] == 0) ? false : true;
$view_vars['hide_unavailable'] = (isset($attributes['hide_unavailable']) && $attributes['hide_unavailable'] == 1) ? true : false;
$view_vars['show_desc'] = (isset($attributes['show_desc']) && $attributes['show_desc'] == 0) ? false : true;
// check if template file exists
if (!is_file($zon_html_path . 'html' . DIRECTORY_SEPARATOR . $view_vars['style'] . '.php')) {
$content = 'ERROR! Zon Template not found. Please check you are using a correct value for the "style" parameter.';
return $content;
} else {
// get product array
$product = $product->getArray();
// if product is unavailable and hide_unavailable is true, return unavailable template
if ($view_vars['hide_unavailable']) {
if ((strpos($product['availability'], "Usually") === false) && strpos($product['availability'], "ships") === false) {
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . 'unavailable.php');
return $content;
}
}
// render chosen template file
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . $view_vars['style'] . '.php');
return $content;
}
}