Track the connection status from the backend?

I am Working on a Chat Application developed By laravel (Laravel Reverb) and reactjs.

Two Projects are developed separately and also i am configuring with Laravel Passport.

The Backend basically serve the Api and Chat server where the frontend configuring the chat server and implementing Apis.

For Tracking User Activity (Online or Offline Status) I am Configuring Presence Channel.

Previously, my task was, when a user connected to the channel A User History Saved on Redis. Which Perfectly Work without any issue.

Now I am trying to configure user disconnected system. When a user is disconnected from the channel it will remove that user history from Redis.

Now Every where i am founding calling a api from frontend so that it can remove that entity.

But I need to Determine the user disconnection from Backend cause When connection stablish i can see Connection stablish message on debug panel and also connection closed message inside debug console.

So I think i can track the connection and disconnection from the server side rather than implementing something on frontend.

So is there a way to track the connection status from the backend side? I can’t Handel The Laravel Reverb Disconnect When Tab is closed

I am giving you the whole code. So that any one can understand what is doing and what to do next.

<?php

namespace AppListeners;

use AppEventsUserStatus;
use IlluminateContractsQueueShouldQueue;
use IlluminateQueueInteractsWithQueue;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesRedis;

class UserStatusListener
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(UserStatus $event): void
    {
        $user_id = $event->user_id;
        $status = $event->status;

        Log::info("User Status Changed: User ID {$user_id} is now {$status}");

        if ($status === "connected") {
            // Store user as online in Redis
            Redis::setex("user:online:{$user_id}", 300, json_encode([
                'user_id' => $user_id,
                'status' => 'online',
                'last_seen' => now()->toDateTimeString(),
            ]));
        } elseif ($status === "disconnected") {
            // Remove user from Redis (user disconnected)
            Redis::del("user:online:{$user_id}");
        }
    }
}

This is my UserStatusListner Where I am determining the User Connected status and store this inside Redis.

<?php

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateBroadcastingPresenceChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateContractsBroadcastingShouldBroadcastNow;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;


class UserStatus implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    public $user_id;
    public $status;

    /**
     * Create a new event instance.
     */
    public function __construct($user_id, $status)
    {
        $this->user_id = $user_id;
        $this->status = $status;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, IlluminateBroadcastingChannel>
     */
    public function broadcastOn()
    {
        return new PresenceChannel('presence-user-status-'.$this->user_id);
    }

    public function broadcastAs()
    {
        return 'user.status'; // Custom event name
    }
}

This is my UserStatus Event Where i called when a Presence Channel is successfully connected.

Broadcast::channel('presence-user-status-{user_id}', function ($user, $user_id) {
    // Check the authenticated user from multiple guards
    $staffUser = Auth::guard('staff_users')->user();
    $businessUser = Auth::guard('business_users')->user();
    $normalUser = Auth::guard('users')->user();

    $userData = [];
    if ($normalUser && (int) $normalUser->user_id === (int) $user_id) {
        $userData = [
            'user_id' => $normalUser->user_id,
            'type' => "user"
        ];

    }

    if ($businessUser && (int) $businessUser->user_id === (int) $user_id) {
        $userData = [
            'user_id' => $businessUser->user_id,
            'type' => "business"
        ];
    }

    if ($staffUser && (int) $staffUser->staff_id === (int) $user_id) {
        $userData = [
            'user_id' => $staffUser->staff_id,
            'type' => "staff"
        ];
        
    }

    if (!empty($userData)) {
        Redis::setex("user:online:{$user_id}", 300, json_encode([
            'user_id' => $userData['user_id'],
            'type' => $userData['type'],
            'last_seen' => now()->toDateTimeString(),
        ]));
        
        // Fire the UserStatus event for tracking
        event(new UserStatus($userData['user_id'], 'connected'));
        return $userData;
    }

    return false; 
});

This is my channel Code of the Presence Channel inside routes/channels

Here When user is online i can store the data into Redis but when a user is disconnect i can’t track that. Anyone have any advise or any way to resolve this issue?

N.B – I am Using Laravel 10 Version.

Laravel Interverntion arabic text from left to right no matter what

im using laravel 11. and laravel intervention with imagick driver.
when i save an image with arabic text. in my localhost it writes from right to left.
but somehow on my ubuntu server its from left to right.
used all arabic fonts they are displayed and connected but not RTL

i tried all deffrent types of fonts tried to align right with intervention didnt work. nothing is working my server

How can I with implement ajax based numbered pagination to posts which are displayed via ajax?

What I’m trying to accomplish is producing numbered pagination for posts which are loaded via an ajax function. I have to make the numbered pagination work via ajax as well. Explanation of each code block below:

This function produces taxonomy terms which currently have posts assigned. Code resides in functions.php.

<?php
    function ee_event_categories() {
      $event_cats = get_terms( array(
        'taxonomy' => 'tribe_events_cat',
        'hide_empty' => true,
      ) );
    ?>
        <div class="filter-column category-block">
          <?php foreach ( $event_cats as $event_cat ) : ?>
            <button 
              data-taxonomy="<?php echo $event_cat->taxonomy; ?>" 
              data-slug="<?php echo $event_cat->slug; ?>"
              data-term-id="<?php echo $event_cat->term_id; ?>">
              <?php echo $event_cat->name; ?>
            </button>
          <?php endforeach; ?>
        </div>
    <?php
      $cat = ob_get_clean();
      return $cat;
    }
    add_shortcode( 'ee_event_categories', 'ee_event_categories' );
?>

Upon clicking on the resulting buttons from the previous function, a custom WP_Query runs and displays posts that match the criteria in the function below. This function resides in functions.php. I think I have to pass the $paged variable from the load_events_by_category() function into the javascript code. Unfortunately, I’m at a loss as to how to do it. Maybe the $paged variable needs to be applied as a second key / value pair in the wp_localize_script() declaration? Now I’m thinking out loud.

<?php
function load_events_by_category() {
  $paged = ($_POST['paged']) ? $_POST['paged'] : 1;
  $taxonomy = $_POST['taxonomy'];
  $slug = $_POST['slug'];
  $term_id = intval($_POST['term_id']);
    $category_events_args = array(
      'post_type'       => 'tribe_events',
      'posts_per_page'  => 4,
      'post_status'     => 'publish',
      'eventDisplay'    => 'custom',
      'order'           => 'ASC',
      'paged'           => $paged,
      'tax_query' => array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field'    => 'term_id',
          'terms'    => $term_id
        )
      )
    );
    $catquery = new WP_Query( $category_events_args );
    ob_start(); 
    if( $catquery->have_posts() ) : ?>
      <div class="this-weeks-events">
        <div class="featured-events-grid">
          <?php while ( $catquery->have_posts() ) : $catquery->the_post(); ?>
            <div class="featured-events-grid-child">
              <div class="event-date"
                data-taxonomy="<?php echo $taxonomy ?>"
                data-slug="<?php echo $slug; ?>" 
                data-term-id="<?php echo $term_id; ?>" 
                style="background:<?php echo the_field('event_category_background', $taxonomy . '_' . $term_id ); ?>"
              >
                <p class="event-day"><?php echo tribe_get_start_date( $event_id, false, 'D' ); ?></p>
                <p class="event-start-date" style="color:<?php echo the_field('event_date_color', $taxonomy . '_' . $term_id ); ?>"><?php echo tribe_get_start_date( $event_id, false, 'j' ); ?></p>
                <p class="event-month"><?php echo tribe_get_start_date( $event_id, false, 'F' ); ?></p>
              </div><!-- end div event-date -->

              <?php if( has_post_thumbnail() ) : ?>
                <div class="featured-image">
                  <a href="<?php echo the_permalink(); ?>"><?php the_post_thumbnail( 'full' ); ?></a>
                </div><!-- end div featured-image -->
              <?php endif; ?>
              <div class="featured-events-details-grid">
                <div><h2><a href="<?php echo the_permalink(); ?>"><?php the_title(); ?></a></h2></div>
                <div>
                  <i class="far fa-clock" aria-hidden="true"></i>
                  <?php echo tribe_get_start_time( $event_id ); ?>
                  -
                  <?php echo tribe_get_end_time( $event_id ); ?>
                  <?php if( tribe_is_recurring_event() ) : ?>
                    <p class="event-recurring"><img src="<?php echo get_stylesheet_directory_uri() . '/images/arrows-rotate.webp' ?>" alt="rotating arrow icon for weekly events" width="20" height="20" /> Weekly Event</p>
                  <?php endif; ?>
                </div>
              </div><!-- end div featured-events-details-grid -->
            </div><!-- end div featured-events-grid-child -->
          <?php endwhile; ?>
        </div><!--end featured events grid -->        
        <?php
          $nextpage = $paged+1;
          $previouspage = $paged-1;
          $total = $catquery->max_num_pages;
          $pagination_args = array(
            'base'                => '%_%',
            'format'              => '?paged=%#%',
            'total'               => $total,
            'current'             => $paged,
            'show_all'            => false,
            'end_size'            => 1,
            'mid_size'            => 2,
            'prev_next'           => true,
            'prev_text'           => __('<span class="prev" data-attr="'.$previouspage.'">&laquo;</span>'),
            'next_text'           => __('<span class="next" data-attr="'.$nextpage.'">&raquo;</span>'),
            'type'                => 'plain',
            'add_args'            => false,
            'add_fragment'        => '',
            'before_page_number'  => '',
            'after_page_number'   => ''
          );
          $paginate_links = paginate_links($pagination_args);

          if ($paginate_links) : ?>
            <div id='pagination' class='pagination'>
              <?php echo $paginate_links; ?>
            </div>
          <?php endif; ?>
      </div><!-- end div this weeks events -->
    <?php endif; ?>
    <?php wp_reset_postdata(); ?>
    <?php
      $content = ob_get_clean();
      echo $content;
      die();
}
add_action( 'wp_ajax_load_events_by_category', 'load_events_by_category' );
add_action( 'wp_ajax_nopriv_load_events_by_category', 'load_events_by_category' );
?>

I’m not sure if this is important but I’ll include it anyway. It’s how I’m using wp_localize_script, also located in functions.php.

<?php wp_enqueue_script( 'ajax-load-category-events', get_stylesheet_directory_uri() . '/dist/ajax-category-events.js', array( 'jquery' ), '1.0', true ); 
wp_localize_script( 'ajax-load-category-events', 'categoryevents', array(
  'ajaxurl'   => admin_url( 'admin-ajax.php' )
));
?>

And finally, here’s the code in above javascript file.

(function ($) {
  $(".category-block button").on('click', function (e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: categoryevents.ajaxurl,
      data: {
        action: 'load_events_by_category',
        taxonomy: $(this).data('taxonomy'),
        slug: $(this).data('slug'),
        term_id: $(this).data('term-id')
      },
      success: function (html) {
        $('#fl-main-content').find('#event_results .fl-rich-text').empty();
        $('#event_results .fl-rich-text').append(html);
      },
      error: function (error) {
        console.log("Error: ", error)
      }
    })
  });
})(jQuery);

I actually did try passing the $paged variable into the script vars of the wp_localize_script declaration. I thought that would at least make the javascript “aware” of what page of results were showing.

wp_localize_script( 'ajax-load-category-events', 'categoryevents', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'paged' => $_POST['paged'] ? $_POST['paged'] : 1; ));

I also spent hours upon hours reviewing similar SO questions and looking for tutorials on how to solve this problem. I’ll be darned but it doesn’t seem using ajax pagination inside ajax produced content is much of a thing.

Calculating Distance Between Colours Using PHP

I am converting an image to use a specific colour palette using PHP. My code is successfully looping through each colour in the source image, and comparing it to the colour palette, and finding the closets colour. However, sometimes I get some odd matches.

I have found many colour distance equations on StackOverflow (and other resources) but none are returning better matches.

Here is the palette I’m using:

enter image description here

Here is the palette n a PHP array:

$colours = array(
    '#B3D7D1',
    '#DD982E',
    '#AD6140',
    '#c01111',
    '#F47B30',
    '#E0E0E0',
    '#184632',
    '#A0BCAC',
    '#923978',
    '#F785B1',
    '#61AFFF'
);

And here is a testing image I am converting:

enter image description here

However, a few of the greens are being matched to the dark purple, here is my result:

enter image description here

And here is the equation I’m using to calculate colour distance:

$distance = sqrt($delta_r * $delta_r + $delta_g * $delta_g + $delta_b * $delta_b);

Here is the RGB of the colour I’m trying to find a match for and the one my code matches it with:

Array ( [0] => 116 [1] => 136 [2] => 115 )
Array ( [0] => 146 [1] => 57 [2] => 120 )

Which returns a distance of 85.

Just a note, the green that I was expecting to get matched gets a distance of 88.

Mathematically the dark purple is the closet colour. But visually it’s not. Does anyone know of a better equation I can use? Maybe one that considers the overall colour instead of just the individual parts?

Full code is available here:
https://github.com/codeadamca/php-colour-palette/

How to dynamically modify Gutenberg block content based on user role in WordPress?

I need to change the content of specific Gutenberg blocks dynamically based on the logged-in user’s role (admin, editor, subscriber) without modifying theme files.

I’ve tried using register_block_type and editor.BlockEdit, but I can’t figure out how to filter block content before it’s rendered in both the editor and frontend.

What’s the best way to achieve this via a plugin or functions.php?

I tried using register_block_type and editor.BlockEdit to change Gutenberg block content based on user roles. Expected it to update dynamically for admins, editors, and subscribers in both the editor and frontend. But it only worked on the frontend, not inside the editor. Looking for a way to make it update in both places.

if array returns gq_online 1 display online badge

im currently making a game server page, i have a badge next to each game server which displays online how could i make it work real time, so it displays
when online display

 <td><label class="badge badge-success">Online</label></td>
             when offline display 
<td><label class="badge badge-danger">Offline</label></td>

the query returns back gq_online 1 if the value is 0 how can i make this set the badge 1 online for online badge 0 for offline badge?

<tbody>
                <tr scope="row">
                </tr>
    <tr>
    <?php $counter = 1; ?>
      <?php foreach ($results as $server) : ?>
          <th scope="row"><?php echo $counter++; ?></th>
          <td><?php echo $server['gq_address'] ?? 'N/A'; ?></td>
          <td><?php echo $server['gq_port_client'] ?? 'N/A'; ?></td>
          <td><?php echo $server['gq_hostname'] ?? 'N/A'; ?></td>
          <td><?php echo $server['gq_mapname'] ?? 'N/A'; ?></td>
          <td><?php echo $server['gq_name'] ?? 'N/A'; ?></td>
          <td><?php echo $server['gq_numplayers'] ?? 0; ?></td>   
         <td><label class="badge badge-success">Online</label></td>
        </tr>
      <?php endforeach; ?>
              </tbody>

Atlassian Bitbucket SonarQube Pipe error: “Container ‘docker’ exceeded memory limit”

I’m using Bitbucket Pipelines for my builds. A previously working SonarQube analysis step is now failing with the error “Container ‘docker’ exceeded memory limit.” This started happening after our codebase increased in size.

This is my configuration:

image: atlassian/default-image:2

clone:
  depth: full       # include the last five commits

definitions: 
  docker:
    memory: 8192
  caches:
    sonar: ~/.sonar
  steps:
    - step: &run_sonar_qube_anaysis
        name: "Run Sonar Qube Analysis"  
        size: 2x # Double resources available for this step.
        script:
          - pipe: sonarsource/sonarqube-scan:1.0.0
            variables:
              SONAR_HOST_URL: ${SONAR_HOST_URL}
              SONAR_TOKEN: ${SONAR_TOKEN}
              SONAR_SCANNER_OPTS: -Xmx8192m
              EXTRA_ARGS: -Dsonar.php.coverage.reportPaths=test-reports/unittestscoverage.xml,test-reports/integrationtestscoverage.xml -Dsonar.php.tests.reportPath=test-reports/unittestsjunit.xml,test-reports/integrationtestsjunit.xml
        artifacts:
          - test-reports/**

I’ve already tried the following to resolve the issue:

  • Increased Docker service memory to 16384 MB (in definitions).
  • Increased the SonarQube step size to 4x.
  • Set SONAR_SCANNER_OPTS to -Xmx16384m.
  • Reduced the number of commits being processed to 1.

Despite these changes, the error persists. What else can I try to resolve this memory issue in my Bitbucket Pipeline’s SonarQube step? Are there specific memory optimization techniques for SonarQube within Bitbucket Pipelines that I should be aware of? Could the increased codebase size be directly impacting the memory requirements of the underlying services?

CarbonPeriod returns duplicate week month [duplicate]

I am formatting the dates of all weeks in a date range that exceeds 1 year using CarbonPeriod:

$period = CarbonPeriod::create('2024-01-01', '1 week', '2025-01-31');

foreach ($period as $date) {
    echo $date->format('W Y') ."rn";
}

dd();

But I am not getting my expected result, it is missing 01 2025.

Instead, it gave me another 01 2024 which is duplicated. That looks wrong to me and I hope someone can explain it.

AWS Elasticache – PHP Memcached – Multiple Tab Log-out

Configuration

Our system has:

  • PHP 8.2
  • AWS Memcached library with OpenSSL
  • AWS Fargate ECS deployment
  • AWS Elasticache

Problem

The initial login for users appears to write and read from memcached. However, upon opening a second tab, our users are getting logged out.

Our Memcached connection configuration is:

// AWS ElastiCache setup
$this->_memcached = new Memcached('persistent-id');

// Set options before adding server
$this->_memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
$this->_memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$this->_memcached->setOption(Memcached::OPT_TCP_NODELAY, true);
$this->_memcached->setOption(Memcached::OPT_NO_BLOCK, true);
$this->_memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$this->_memcached->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);

// Set TLS option before adding server
if (!$this->_memcached->setOption(Memcached::OPT_USE_TLS, true)) {
    error_log("Failed to set TLS option: " . $this->_memcached->getLastErrorMessage());
    return false;
}

// Configure TLS context
$tls_config = new MemcachedTLSContextConfig();
$tls_config->hostname = '*.cache.amazonaws.com'; // More general hostname pattern
$tls_config->skip_cert_verify = false;
$tls_config->skip_hostname_verify = false;

// Set TLS context before adding server
try {
    $this->_memcached->createAndSetTLSContext((array)$tls_config);
} catch (Exception $e) {
    error_log("Failed to set TLS context: " . $e->getMessage());
    return false;
}

// Use TLS port (21211) for AWS ElastiCache with TLS
if (!$this->_memcached->addServer($this->_host, 21211)) {
    error_log("Failed to add server: " . $this->_memcached->getLastErrorMessage());
    return false;
}

In my php.ini, memcached is configured with the following options:

memcached.sess_locking = 1
memcached.sess_lock_wait_min = 150
memcached.sess_lock_wait_max = 150
memcached.sess_lock_retries = 200
memcached.sess_lock_expire = 0
memcached.sess_persistent = 1
memcached.sess_prefix = "memc.sess.key."
memcached.sess_consistent_hash = 1

The AWS Documentation does not make any recommendations for a way to configure the memcached library. Our Docker configuration is pulling their extension and enabling it through the following configuration:

# Install and configure Amazon ElastiCache Cluster Client
RUN curl -L https://elasticache-downloads.s3.amazonaws.com/ClusterClient/PHP-$PHP_VERSION/$MEMCACHED_URL | tar -C /tmp -zx 
    && mv /tmp/amazon-elasticache-cluster-client.so /usr/lib/php/20220829/amazon-elasticache-cluster-client.so 
    && rm -rf /tmp/Readme.markdown 
    && echo "extension=amazon-elasticache-cluster-client.so" >> /etc/php${PHP_VERSION}/php.ini

This appears to enable the amazon elasticache cluster client correctly, as we are not downloading memcached through any other mean and it works as intended on local (connecting to our self-hosted docker/memcached container).

How to Send data from Controllet to Import Multiple Sheet on Maatwebsite Laravel

Hallo i get a trouble when i want to import excel with another data in mysql.

This is the controller

public function upload(Request $request){

  $file = $request->filebabp;
  if($file) {
    $nama_file = Carbon::now()->setTimezone('Asia/Jakarta')->format('Ymd-His').'-'.$file->getClientOriginalName();

    $datasubmit['file'] = $file;
    $datasubmit['upload_date'] = Carbon::now()->setTimezone('Europe/Belarusia')->format('Y-m-d H:i:s');
    $datasubmit['nama_file'] = $nama_file;
    $datasubmit['version'] = 'NEW';

    $file->move(public_path('files/'), $nama_file);
    $upload = Excel::import(new TargetUpload($datasubmit), base_path('public/files/'.$nama_file));
}
  return $this->sendResponse($file, 'Submit successfully');
}

And this is the Import Multiple Sheet

use Importable;
// /**
// * @param array $row
// *
// * @return IlluminateDatabaseEloquentModel|null
// */
protected $data;

function __construct($data) {
        $this->data = $data;
}

public function sheets($data): array
{
    return [
        0 => new TargetHeaderImport($data),
    ];
}

I want sending the datasubmit to Import multiple sheet, and i just get a error in this.

If i import on direct ‘TargetHeaderImport’ its safe, but in excel i have a 2 sheets and i just only want one sheet to import.

or do you have a another script to send the ‘submitdata’ ?

Apache2.4 not loading the PHP module (%1 is not a valid Win32 application) [closed]

I am trying to install Apache2.4 to run php (and Mysql) in dreamweaver and I have followed the instructions but when I run httpd.exe it gives me :
%1 is not a valid Win32 application

  • I installed VC_redist.x64.exe (MVC++ 2015-2022 Red. (x64))
  • I instaleld Apache2.4 via httpd-2.4.63-250207-win64-VS17
  • I installed php8.4 via php-8.4.4-Win32-vs17-x64.zip

Added these in the httpd.conf
LoadModule php8_module “C:/php/php8apache2_4.dll”
AddType application/x-httpd-php .php
PHPIniDir “C:/PHP”
LoadFile “C:/PHP/php8ts.dll”

php runs wells (phpinfo() working) but httpd gives the error above.

I am stuck and hopeless. No error logs visible

I want to have Apache 2.4 server running and was not expecting that error.

Simple PHP Class Autoloader for a WordPress plugin without using Composer

So I set up an autoloader in PHP using spl_autoload_register() (and not composer).

I have made my custom plugin called my-plugin, refer to the attachment for reference of folder structure.

I have learned to include files like autoloader or trait-singleton.php, I need to include it in my main plugin file i.e., in my case my-plugin.php.

Now when I try to error_log() the parameter spl_autoload_register() accepts, I get a completely different thing.

<?php
spl_autoload_register( function ( $class_name ) {
    error_log("Autoloader received: " . $class_name);
    include $class_name . '.php';
}

[14-Feb-2025 00:08:23 UTC] Autoloader received: WP_Site_Health

I am unable to complete the autoloader function, the singleton file works great when i include it in the main plugin file.

How do I implement autoloader for my particular file structure, where most of my files would be located in my-pluginincclassespost-types for CPT and my-pluginincclassestaxonomies for taxonomies.

Custom WpAllImport function to get data from XML and skip if not matched [closed]

I am trying to import items based on the week now I dont want to manually change this every week but want to have this automated. So I made this code

function my_is_post_to_update( $continue, $post_id, $xml_node, $import_id ) {
    // Run this code only for a specific import (import ID 5)
    if ($import_id == '20') {
        // Get the current week number
        $current_week = 7;
        
        // Get the week from the XML node
        $week = $xml_node['week'];
        
        // Debugging logs
        error_log("Import ID: $import_id - Current Week: $current_week, XML Week: $week");
        
        // If week is valid and matches the current week, continue the import
        if ($week == $current_week) {
            error_log("Importing record for week $week (matches current week).");
            return true; // Continue importing
        } else {
            error_log("Skipping record: Week in XML ($week) does not match current week ($current_week).");
        }
    }
    
    // Skip this post if the week doesn't match the current week
    return false;
}
add_filter( 'wp_all_import_is_post_to_update', 'my_is_post_to_update', 10, 4 );

So its skipping all rows. I use it on existing items and my import id = 20. So I think I am doing something wrong with the week.

Picture of import

How can I add separator as a rule line or stars between textarea messages written in a text file?

I have the PHP code that saves all textarea inputs to a text file, except it fuses all consequent messages at the last letter of every input. For instance, if the first textarea content is:

Hello
How are you
Good bye

Then the second textarea content is:

Let me upload this.
Inform me if you receive it.

After submitting both messages, the output text file shows this:

Hello
How are you
Good byeLet me upload this.
Inform me if you receive it.

I need a real help to adjust the PHP file so that it insert a separator (like a horizontal line or *************) at the end of every message with n.

Code:

<?php 
$filename = 'posts.txt'; 
$msg = (isset($_POST['msg']) ? $_POST['msg'] : null); 

if (is_writable($filename)) { 
  if (!$handle = fopen($filename, 'a')) { 
    echo "Cannot open file ($filename)"; exit; 
  } 

  if (fwrite($handle, $msg) === FALSE) { 
    echo "Cannot write to file ($filename)"; exit; 
  } 

  echo "Success, wrote ($msg) to file ($filename)"; fclose($handle); 
} 
else { 
  echo "The file $filename is not writable"; 
} 
?>

Form:

<form id="post" name="post" action="storeText.php" method="post"> 
  <textarea cols="x" rows="x" name="msg"></textarea> 
  <input class="button" type="submit" value="POST!"/> 
</form> 
<div class="menuItem" > <?=$msg?> </div>

How to Filter Activities by Duration in Hotelbeds API?

I am integrating the Hotelbeds Activities API into my Laravel API, and I need to filter activities by duration. However, I couldn’t find any documentation on how to apply this filter.

Current API Request:
Below is the request I am sending to the Hotelbeds API to fetch available activities for a specific date and destination (Madrid – “MAD”):

{
    "filters": [
        {
            "searchFilterItems": [
                {"type": "destination", "value": "MAD"}  // Destination: Madrid
            ]
        }
    ],
    "from": "2025-02-20",  // Start date
    "to": "2025-02-20",    // End date
    "language": "en",  
    "paxes": [             // Passengers (2 adults, 30 years old each)
        {"age": 30},
        {"age": 30}
    ],
    "pagination": {        // Fetch up to 100 items per page
        "itemsPerPage": 100,
        "page": 1
    },
    "order": "DEFAULT"     // Default sorting
}

API Endpoint:
I am making the request to the following Hotelbeds Activities API endpoint:

https://api.test.hotelbeds.com/activity-api/3.0/activities/availability

Problem:
I want to filter activities based on their duration (e.g., between 3 to 5 hours). However, I couldn’t find any mention of a “duration” filter in the official Hotelbeds API documentation.

Questions:

Does Hotelbeds support filtering activities by duration?
If so, what is the correct filter type and format to use?
Are there alternative ways to achieve this, such as filtering results in Laravel after retrieving them?
Any guidance or working examples would be greatly appreciated!