ZF3 route locale parameter - zend-framework3

I have a translation in my project for templates and routes. when the locale is set, the translations are working except the locale parameter in the links is not correct.
my default language is NL. so I have a page www.website.com/nl/contact
when I switch to language fr I go to www.website.com/fr/contact, then when I go to look in the HTML source, the link is again www.website.com/nl/contact in stead of www.website.com/fr/contact so the locale parameter in the links is not updated regarding the setLocale
my module.php
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach(
\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR,
function ($e) {
$application = $e->getApplication();
$match = $application->getMvcEvent()->getRouteMatch();
if (null === $match) {
$params = [
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'not-found',
// Here you can add common params for your application routes
];
$viewModel = $e->getViewModel();
$viewModel->setTemplate('layout/website');
$routeMatch = new RouteMatch($params);
$routeMatch->setMatchedRouteName('home');
$application->getMvcEvent()->setRouteMatch(
$routeMatch
);
}
}
);
$moduleRouteListener = new ModuleRouteListener();
if (!$e->getRequest() instanceof ConsoleRequest) {
$this->setLanguage($e);
$eventManager->attach('route', array($this, 'onPreRoute'), 100);
$moduleRouteListener->attach($eventManager);
$this->initAcls($e);
if (isset($_SERVER['APP_ENV']) and $_SERVER['APP_ENV'] == 'production') {
$eventManager->attach('finish', array($this, 'outputCompress'), 100);
}
}
}
private function setLanguage($e)
{
$redirectBase = $e->getRequest()->getServer()->get('REDIRECT_BASE');
$requestUri = $e->getRequest()->getServer()->get('REQUEST_URI');
$cmsString = substr($requestUri, strlen($redirectBase), 4);
$language = 'nl';
$routeTranslation = true;
if ($requestUri != '/') {
$language = substr($requestUri, 1, 2);
}
if ($cmsString == 'cms/') {
$language = 'en-us';
$routeTranslation = false;
}
$translator = $e->getApplication()->getServiceManager()->get('MvcTranslator');
$translator->setLocale($language);
if ($routeTranslation) {
$translator->addTranslationFile('PhpArray', __DIR__.'/../language/Routes/' . $language . '.php', 'default', $language);
}
}
public function onPreRoute($e)
{
$app = $e->getTarget();
$serviceManager = $app->getServiceManager();
$serviceManager->get('router')->setTranslator($serviceManager->get('MvcTranslator'));
}

Related

Update post terms in each languages by code

who can hellp with this, i need create post from code, by wp_insert_post
function, so what is going on:
I creating post on each existing laguages, then i update all needed fields and i need to set post term depened of current language.
I have terms (shelters) https://prnt.sc/pklSXojB2jZj - i need that post set to current lang shelter while create, but after creating i got - https://prnt.sc/pz2jFEq1OAMP , 2 posts set in one lang terms. Maybe who know whats goes wrong, below i provided 2 functions who do these actions, Thanks in advance:
function add_pet($form_data, $ready_data, $update_meta = false) {
$allLang = pll_languages_list();
if ($allLang) {
$postsArr = array();
foreach ($allLang as $lang) {
//Add new pet
$post_id = wp_insert_post(array(
'post_title' => $form_data['pet_name'],
'post_status' => 'publish',
'post_author' => $form_data['user_id'],
'post_type' => 'pets',
));
//Check if post created, update all needed fields, and update post terms (shelter)
if ($post_id) {
//Get all translation of term
$shelter_id = pll_get_term(intval($form_data['shelter']), $lang);
$update_meta['shelter'] = $shelter_id;
//In this function we update those terms
$update_success = update_pets_fields($post_id, $ready_data, $update_meta);
$postsArr[$lang] = $post_id;
pll_set_post_language($post_id, $lang);
$postDate = get_post($post_id)->post_date;
$unixDate = strtotime($postDate);
update_post_meta($post_id, 'pet_update_date', $unixDate);
}
}
//Save post translation
if ($postsArr) {
pll_save_post_translations($postsArr);
}
//Old code
// foreach ($allLang as $lang) {
// $cat_id = pll_get_term(intval($form_data['kind_of_animal']), $lang);
// $shelter_id = pll_get_term(intval($form_data['shelter']), $lang);
// $post_id = $postsArr[$lang];
// $update_meta['post_category'] = $cat_id;
// $update_meta['shelter'] = $shelter_id;
// $update_success = update_pets_fields($post_id, $ready_data, $update_meta);
// }
}
if (is_wp_error($post_id)) {
wp_send_json_error($post_id->get_error_message());
}
if ($update_success) {
wp_send_json_success('Post was created.');
} else {
wp_send_json_error('Post was not created.');
}
}
And function who update field
/Update pets fields
function update_pets_fields($post_id, $data, $update_meta = false) {
if (!$post_id) return;
//Update post meta data not acf
if (isset($update_meta) && !empty($update_meta['title'])) {
$post_update = array(
'ID' => $post_id,
'post_title' => $update_meta['title']
);
$result = wp_update_post($post_update);
if (is_wp_error($result)) {
wp_send_json_error('Fields was not updated');
}
}
if (isset($update_meta['shelter']) && !empty($update_meta['shelter']) && intval($update_meta['shelter'])) {
wp_remove_object_terms($post_id, 'uncategorized', 'sholters');
$shelter_id = intval($update_meta['shelter']);
wp_set_post_terms($post_id, array($shelter_id), 'sholters');
if (is_wp_error($result)) {
wp_send_json_error('Term not updated');
}
}
if (isset($update_meta['post_category']) && !empty($update_meta['post_category']) && intval($update_meta['post_category'])) {
wp_remove_object_terms($post_id, 'uncategorized', 'category');
wp_set_post_categories($post_id, intval($update_meta['post_category']));
if (is_wp_error($result)) {
wp_send_json_error('Category not updated');
}
}
if (isset($update_meta['thumbnail']) && !empty($update_meta['thumbnail']) && intval($update_meta['thumbnail'])) {
set_post_thumbnail($post_id, intval($update_meta['thumbnail']));
}
if (is_null($data)) {
wp_send_json_error('No data.');
}
foreach ($data as $field) {
if ($field[3] === 'where_is') {
$field_array['field_62169d3cffb5b'] = array(
$field[2] => $field[1],
);
} else {
$field_array = array(
$field[2] => $field[1],
);
}
if (!empty($field[1])) {
$result = update_field('field_621696a7ffb4e', $field_array, $post_id);
}
}
if ($result) {
return false;
} else {
return true;
}
}
I try update it in diferent variants but it does't work, i check ids that come in args all ids is right and all posts ids is right.But on at the exit we got 2 posts in 1 term

Symfony redirect from "/" to "/{locale}"

I am working on a Symfony(4.4) project. I am trying to make eventSubscriber that will redirect user with locale based on saved cookie. The idea is when I visit homepage for first time(or if I have not saved cookie) I have to redirect myself to homepage with the default locale(which is 'en' in my case). When I change the locale I save the new locale in cookie (for example my cookie is "LOCALE" => 'de'). When I enter in homepage next time I have to redirect myself with the 'de' locale(because it's saved on the cookie). When I set the priority to 32+ I get redirect to the default locale instead the cookie locale(I receive the cookie content, so the problem is not from the cookie), else if I set the priority before 32 I get the error "Route not found for '/' " https://imgur.com/0YAtgqs. For now I made this:
I added new method in RequestSubscriber:
public function redirectToCookieLocale(RequestEvent $event)
{
if ($event->isMasterRequest() === false) {
return;
}
$request = $event->getRequest();
$path = $event->getRequest()->getPathInfo();
$cookieLocale = $request->cookies->get('LOCALE');
if ($cookieLocale != null && $this->isValidLocale($cookieLocale)) {
$locale = $request->cookies->get('LOCALE');
} else {
$locale = $request->getDefaultLocale();
}
if ($path == '/') {
$event->setResponse(new RedirectResponse(
$this->generator->generate(
'frontend_index',
['_locale' => $locale]
),
301
));
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['redirectToCookieLocale', 30]
]
];
}
Also I created ResponseSubscriber where I create the cookie:
public function onKernelResponse(ResponseEvent $event)
{
$request = $event->getRequest();
$response = $event->getResponse();
if ($response->isRedirection()) {
return;
}
$urlLocale = $request->get('_locale');
$cookieLocale = $request->cookies->get('LOCALE');
if ($urlLocale != null && $urlLocale != $cookieLocale) {
$cookie = new Cookie('LOCALE', $request->getLocale(), (time() + 3600 * 24 * 7), '/', '', '', false);
$response->headers->setCookie($cookie);
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => [
['onKernelResponse', 0],
],
];
}

Is there any function in Leandash to mark complete COURSE programmatically

I am working on Leandash Project , Now my requirement is some students have completed the course offline , So I have created a screen for a group leader in which the group leader can select group/user/course and also add date like this ( https://prnt.sc/1bfcq3a ) and can mark complete COURSE.
So my question is how do I mark complete COURSE. programmatically on link click.
here is my code , which is not working
jQuery(document).on('click', '.course_complete_save', function(event) {
event.preventDefault();
var selected_group_id = jQuery('#group_name_select_dropdown').val();
var selected_user_id = jQuery('#user_name_select_dropdown').val();
var selected_course_id = jQuery('#course_name_select_dropdown').val();
var mark_complete_date = jQuery('#input_date_field').val();
var params = {"mark_complete_date":mark_complete_date,"selected_group_id":selected_group_id,"selected_user_id":selected_user_id,"selected_course_id":selected_course_id,action:"mark_complete_course_ajax"}
jQuery.post(groupcustomisation.ajaxurl,params,function(data){
if(data){
jQuery(".mark_complete_success").empty().append("Mark Completed");
}else{
jQuery(".mark_complete_success").empty().append("No data Found");
}
});
});
<?php
add_action('wp_ajax_nopriv_mark_complete_course_ajax', 'mark_complete_course_ajax');
add_action('wp_ajax_mark_complete_course_ajax', 'mark_complete_course_ajax');
function mark_complete_course_ajax() {
$selected_group_id = $_POST['selected_group_id'];
$selected_user_id = $_POST['selected_user_id'];
$selected_course_id = $_POST['selected_course_id'];
$mark_complete_date = $_POST['mark_complete_date'];
learndash_process_mark_complete( $selected_user_id, $selected_course_id, true, $selected_course_id );
echo "1";
die();
}
Funny enough, i found myself needing solution to same problem minutes after you posted this yesterday and as you see, that function above failed to work and nothing useful online. In short, i spent the whole day on it trying to find why until i realized all lessons and quiz need to be marked as complete too and after writing the function that do exactly this based on my research on learndash source code as primary source, i decided to come back here and post the function just incase you haven't fix it
Usage: sci_learndash_mark_course_complete($course_id, $user_id)
Here's the function:
/**
* Mark learndash course as complete.
*
* #param int $id Course ID.
* #param int $user_id User ID.
*/
function sci_learndash_mark_course_complete($id, $user_id)
{
//retreive current course progress
$user_progress['course'][$id] = learndash_user_get_course_progress($user_id, $id, 'legacy');
if (isset($user_progress['course'][$id]['lessons'])) {
//update lessons progress to complete
$lesson_array = $user_progress['course'][$id]['lessons'];
$lessons = array_flip($lesson_array);
$lessons = array_fill_keys(array_keys($lesson_array), 1);
$user_progress['course'][$id]['lessons'] = $lessons;
}
//update topics progress to complete
if (isset($user_progress['course'][$id]['topics'])) {
foreach($user_progress['course'][$id]['topics'] as $ldtopic_key => $ldtopic){
if(count($ldtopic) > 0){
$new_ldtopic = array_flip($ldtopic);
$new_ldtopic = array_fill_keys(array_keys($ldtopic), 1);
$user_progress['course'][$id]['topics'][$ldtopic_key] = $new_ldtopic;
}
}
}
//update quiz progress to complete
if (isset($user_progress['quiz'][$id])) {
$quiz_array = $user_progress['course'][$id]['quiz'];
$quiz = array_flip($quiz_array);
$quiz = array_fill_keys(array_keys($quiz_array), 1);
$user_progress['course'][$id]['quiz'] = $quiz;
}else{
$quiz_list = [];
if ( isset($user_progress['course'][$id]['lessons']) && count($user_progress['course'][$id]['lessons']) > 0 ) {
$ld_lesson_keys = array_keys($user_progress['course'][$id]['lessons']);
foreach($ld_lesson_keys as $course_lesson_id){
$topic_quizzes = learndash_get_lesson_quiz_list( $course_lesson_id );
if (!empty($topic_quizzes)){
foreach ($topic_quizzes as $topic_quiz) {
$quiz_list[$topic_quiz['post']->ID] = 1;
}
}
}
}
if (!empty($quiz_list)){
$user_progress['quiz'][$id] = $quiz_list;
}
}
$processed_course_ids = [];
if ((isset($user_progress['course'])) && (!empty($user_progress['course']))) {
$usermeta = get_user_meta($user_id, '_sfwd-course_progress', true);
$course_progress = empty($usermeta) ? [] : $usermeta;
$course_changed = false; // Simple flag to let us know we changed the quiz data so we can save it back to user meta.
foreach ($user_progress['course'] as $course_id => $course_data_new) {
$processed_course_ids[intval($course_id)] = intval($course_id);
if (isset($course_progress[$course_id])) {
$course_data_old = $course_progress[$course_id];
} else {
$course_data_old = [];
}
$course_data_new = learndash_course_item_to_activity_sync($user_id, $course_id, $course_data_new,
$course_data_old);
$course_progress[$course_id] = $course_data_new;
$course_changed = true;
}
if (true === $course_changed) {
update_user_meta($user_id, '_sfwd-course_progress', $course_progress);
}
}
if ((isset($user_progress['quiz'])) && (!empty($user_progress['quiz']))) {
$usermeta = get_user_meta($user_id, '_sfwd-quizzes', true);
$quizz_progress = empty($usermeta) ? [] : $usermeta;
$quiz_changed = false; // Simple flag to let us know we changed the quiz data so we can save it back to user meta.
foreach ($user_progress['quiz'] as $course_id => $course_quiz_set) {
foreach ($course_quiz_set as $quiz_id => $quiz_new_status) {
$quiz_meta = get_post_meta($quiz_id, '_sfwd-quiz', true);
if (!empty($quiz_meta)) {
$quiz_old_status = !learndash_is_quiz_notcomplete($user_id, [$quiz_id => 1], false, $course_id);
// For Quiz if the admin marks a qiz complete we don't attempt to update an existing attempt for the user quiz.
// Instead we add a new entry. LD doesn't care as it will take the complete one for calculations where needed.
if ((bool)true === (bool)$quiz_new_status) {
if ((bool)true !== (bool)$quiz_old_status) {
if (isset($quiz_meta['sfwd-quiz_lesson'])) {
$lesson_id = absint($quiz_meta['sfwd-quiz_lesson']);
} else {
$lesson_id = 0;
}
if (isset($quiz_meta['sfwd-quiz_topic'])) {
$topic_id = absint($quiz_meta['sfwd-quiz_topic']);
} else {
$topic_id = 0;
}
// If the admin is marking the quiz complete AND the quiz is NOT already complete...
// Then we add the minimal quiz data to the user profile.
$quizdata = [
'quiz' => $quiz_id,
'score' => 0,
'count' => 0,
'question_show_count' => 0,
'pass' => true,
'rank' => '-',
'time' => time(),
'pro_quizid' => absint($quiz_meta['sfwd-quiz_quiz_pro']),
'course' => $course_id,
'lesson' => $lesson_id,
'topic' => $topic_id,
'points' => 0,
'total_points' => 0,
'percentage' => 0,
'timespent' => 0,
'has_graded' => false,
'statistic_ref_id' => 0,
'm_edit_by' => get_current_user_id(), // Manual Edit By ID.
'm_edit_time' => time(), // Manual Edit timestamp.
];
$quizz_progress[] = $quizdata;
if (true === $quizdata['pass']) {
$quizdata_pass = true;
} else {
$quizdata_pass = false;
}
// Then we add the quiz entry to the activity database.
learndash_update_user_activity(
[
'course_id' => $course_id,
'user_id' => $user_id,
'post_id' => $quiz_id,
'activity_type' => 'quiz',
'activity_action' => 'insert',
'activity_status' => $quizdata_pass,
'activity_started' => $quizdata['time'],
'activity_completed' => $quizdata['time'],
'activity_meta' => $quizdata,
]
);
$quiz_changed = true;
if ((isset($quizdata['course'])) && (!empty($quizdata['course']))) {
$quizdata['course'] = get_post($quizdata['course']);
}
if ((isset($quizdata['lesson'])) && (!empty($quizdata['lesson']))) {
$quizdata['lesson'] = get_post($quizdata['lesson']);
}
if ((isset($quizdata['topic'])) && (!empty($quizdata['topic']))) {
$quizdata['topic'] = get_post($quizdata['topic']);
}
/**
* Fires after the quiz is marked as complete.
*
* #param arrat $quizdata An array of quiz data.
* #param WP_User $user WP_User object.
*/
do_action('learndash_quiz_completed', $quizdata, get_user_by('ID', $user_id));
}
} elseif (true !== $quiz_new_status) {
// If we are unsetting a quiz ( changing from complete to incomplete). We need to do some complicated things...
if (true === $quiz_old_status) {
if (!empty($quizz_progress)) {
foreach ($quizz_progress as $quiz_idx => $quiz_item) {
if (($quiz_item['quiz'] == $quiz_id) && (true === $quiz_item['pass'])) {
$quizz_progress[$quiz_idx]['pass'] = false;
// We need to update the activity database records for this quiz_id
$activity_query_args = [
'post_ids' => $quiz_id,
'user_ids' => $user_id,
'activity_type' => 'quiz',
];
$quiz_activity = learndash_reports_get_activity($activity_query_args);
if ((isset($quiz_activity['results'])) && (!empty($quiz_activity['results']))) {
foreach ($quiz_activity['results'] as $result) {
if ((isset($result->activity_meta['pass'])) && (true === $result->activity_meta['pass'])) {
// If the activity meta 'pass' element is set to true we want to update it to false.
learndash_update_user_activity_meta($result->activity_id, 'pass',
false);
// Also we need to update the 'activity_status' for this record
learndash_update_user_activity(
[
'activity_id' => $result->activity_id,
'course_id' => $course_id,
'user_id' => $user_id,
'post_id' => $quiz_id,
'activity_type' => 'quiz',
'activity_action' => 'update',
'activity_status' => false,
]
);
}
}
}
$quiz_changed = true;
}
/**
* Remove the quiz lock.
*
* #since 2.3.1
*/
if ((isset($quiz_item['pro_quizid'])) && (!empty($quiz_item['pro_quizid']))) {
learndash_remove_user_quiz_locks($user_id, $quiz_item['quiz']);
}
}
}
}
}
$processed_course_ids[intval($course_id)] = intval($course_id);
}
}
}
if (true === $quiz_changed) {
update_user_meta($user_id, '_sfwd-quizzes', $quizz_progress);
}
}
if (!empty($processed_course_ids)) {
foreach (array_unique($processed_course_ids) as $course_id) {
learndash_process_mark_complete($user_id, $course_id);
learndash_update_group_course_user_progress($course_id, $user_id);
}
}
}

Woocommerce REST API subscriptions filter by parent_id

I'm using Woocommerce REST API to retrieve some data, code provided by Woocommerce team to use as client
My client options:
'wp_api' => true,
'version' => 'wc/v1',
'ssl_verify' => false,
'wp_api_prefix' => '/wp-json/',
'query_string_auth' => true,
Have a function to retrieve subscriptions:
function get_wc_subscriptions($sid=0, $parent=null, $page=1, $offset=0)
{
$params['page'] = $page;
$params['offset'] = $offset;
$params['role'] = 'all';
if($sid > 0) {
$endpoint = 'subscriptions/'.$sid;
} else {
$endpoint = 'subscriptions';
}
if(isset($parent) && ($parent != null)) {
$params['filter[parent_id]'] = $parent;
}
return $this->wooClient->get($endpoint, $params);
}
Parent parameter is not working, when calling function without any params, I get a result of all subscriptions on first page, if parent is set, get same result with all subscriptions (not being filtered).
Am I missing something?
UPDATE:
How can I use get_wc_subscriptions?
require_once('woosync.php');
$sid = $_GET['sid'];
$parent = $_GET['parent'];
$woosync = new woosync();
$subscriptions = $woosync->get_wc_subscriptions($sid, $parent);
echo "<pre>";
print_r($subscriptions);

Payum Paypal on Symfony3

I'm trying to integrate a payment system of paypal on my webpage under Symfony. After some researches, I ran into Payum which is a apparently the best bundle for this feature.
The issue is that I don't really understand the doc so the final code I have doesn't work.
Somebody already used payum and could help me to understand it ?
I have for example : $paypalRestPaymentDetailsClass which comes from nowhere and I don't know what should be in this class
Here is my code :
namespace PlatformBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Payum\Core\PayumBuilder;
use Payum\Core\Payum;
use PayPal\Api\Amount;
use PayPal\Api\Payer;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use Payum\Core\Request\GetHumanStatus;
class PayumController extends Controller
{
private function config()
{
return (new PayumBuilder())
->addDefaultStorages()
->addGateway('gatewayName', [
'factory' => 'paypal_rest',
'client_id' => 'REPLACE IT',
'client_secret' => 'REPLACE IT',
'config_path' => 'REPLACE IT',
])
->getPayum();
}
public function prepare()
{
$payum = $this->config();
$storage = $payum->getStorage($paypalRestPaymentDetailsClass);
$payment = $storage->create();
$storage->update($payment);
$payer = new Payer();
$payer->payment_method = "paypal";
$amount = new Amount();
$amount->currency = "USD";
$amount->total = "1.00";
$transaction = new Transaction();
$transaction->amount = $amount;
$transaction->description = "This is the payment description.";
$captureToken = $payum->getTokenFactory()->createCaptureToken('paypalRest', $payment, 'create_recurring_payment.php');
$redirectUrls = new RedirectUrls();
$redirectUrls->return_url = $captureToken->getTargetUrl();
$redirectUrls->cancel_url = $captureToken->getTargetUrl();
$payment->intent = "sale";
$payment->payer = $payer;
$payment->redirect_urls = $redirectUrls;
$payment->transactions = array($transaction);
$storage->update($payment);
header("Location: ".$captureToken->getTargetUrl());
}
public function capture()
{
$payum = $this->config();
$token = $payum->getHttpRequestVerifier()->verify($_REQUEST);
$gateway = $payum->getGateway($token->getGatewayName());
if ($reply = $gateway->execute(new Capture($token), true)) {
if ($reply instanceof HttpRedirect) {
header("Location: ".$reply->getUrl());
die();
}
throw new \LogicException('Unsupported reply', null, $reply);
}
$payum->getHttpRequestVerifier()->invalidate($token);
header("Location: ".$token->getAfterUrl());
}
public function done()
{
$payum = $this->config();
$token = $payum->getHttpRequestVerifier()->verify($_REQUEST);
$gateway = $payum->getGateway($token->getGatewayName());
// you can invalidate the token. The url could not be requested any more.
// $payum->getHttpRequestVerifier()->invalidate($token);
// Once you have token you can get the model from the storage directly.
//$identity = $token->getDetails();
//$payment = $payum->getStorage($identity->getClass())->find($identity);
// or Payum can fetch the model for you while executing a request (Preferred).
$gateway->execute($status = new GetHumanStatus($token));
$payment = $status->getFirstModel();
header('Content-Type: application/json');
echo json_encode(array(
'status' => $status->getValue(),
'order' => array(
'total_amount' => $payment->getTotalAmount(),
'currency_code' => $payment->getCurrencyCode(),
'details' => $payment->getDetails(),
),
));
}
}
Thanks

Resources