Firebase – user customClaims – admin

im trying to find a way how to add to user Admin role via custom claims.
I tried to do it with user creation cloud function, and onCall function, I dont know if claims are assigned, or not, or how to check where is code failing.

Here is my code: 2 cloud functions, I have tried to give admin role after acc creation and then manually (this function is blocked when called from button click by CORS, no idea what to do)

Any help appreciated

Cloud functions:

export const assignAdminRoleOnUserCreation = functions.auth
    .user()
    .onCreate(async (user) => {
      try {
        if (user.email === "[email protected]") {

          await admin.auth().setCustomUserClaims(user.uid, { admin: true });

          console.log(`Admin role assigned to user ${user.email} (${user.uid}).`);
        } else {
          console.log(`No admin role assigned to user ${user.email}.`);
        }
      } catch (error) {
        console.error(`Error assigning admin role to user ${user.email}:`, error);
      }
    });

  export const manuallyAssignAdmin = onCall(async (request) => {
    const targetEmail = "[email protected]"
  
    try {
      const userRecord = await getAuth().getUserByEmail(targetEmail)
  
      await getAuth().setCustomUserClaims(userRecord.uid, { admin: true })
  
      return { message: `Admin role assigned to ${targetEmail}` }
    } catch (error) {
      console.error("Error assigning admin role:", error)
      throw new Error("Failed to assign admin role")
    }
  })

how i call onCall function at front end:

async function assignAdminManually() {
const assignAdmin = httpsCallable(functions, 'manuallyAssignAdmin')

try {
  const result = await assignAdmin()
  console.log(result.data.message)
  alert('Admin role assigned successfully!')
} catch (error) {
  console.error('Error assigning admin role:', error)
  alert('Failed to assign admin role.')
}

}

How I try to check admin role:

  const isAdmin = async () => {
if (cachedIsAdmin !== null) {
  return cachedIsAdmin; 
}

const auth = getAuth();
const user = auth.currentUser;
console.log(auth)
if (user) {
  try {
    const idTokenResult = await user.getIdTokenResult();

    if (idTokenResult.claims.admin) {
      cachedIsAdmin = true;
    } else {
      cachedIsAdmin = false;
    }
  } catch (error) {
    console.error("Error getting ID token result:", error);
    cachedIsAdmin = false;
  }
} else {
  cachedIsAdmin = false;
}

return cachedIsAdmin;

};

Create a pickup Distance Calculation miles pricing in WordPress

I successfully implemented the code from this previous question How to create pickup Distance Calculation miles pricing in WordPress
What I’m trying to do is add a minimum cost of 40 to show if the calculated cost is below that, but really struggling to get an if statement included, any ideas?

document.addEventListener('DOMContentLoaded', function() {
    let map;
    let directionsService;
    let directionsRenderer;

    function initMap() {
        // Initialize the Google Maps objects
        directionsService = new google.maps.DirectionsService();
        directionsRenderer = new google.maps.DirectionsRenderer();
        map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8
        });
        directionsRenderer.setMap(map);
    }

    function calculateDistance() {
        const pickup = document.getElementById('pickup').value;
        const destination = document.getElementById('destination').value;

        if (pickup && destination) {
            const request = {
                origin: pickup,
                destination: destination,
                travelMode: 'DRIVING'
            };

            directionsService.route(request, function(result, status) {
                if (status == 'OK') {
                    directionsRenderer.setDirections(result);

                    const distance = result.routes[0].legs[0].distance.value / 1000; // distance in km
                    const cost = distance * 2; // Example: $2 per km

                    document.getElementById('distance').textContent = distance.toFixed(2) + ' km';
                    document.getElementById('total-cost').textContent = '$' + cost.toFixed(2);
                } else {
                    alert('Could not calculate distance: ' + status);
                }
            });
        } else {
            alert('Please enter both pickup and destination locations.');
        }
    }

    document.getElementById('calculate-button').addEventListener('click', calculateDistance);

    // Load the map
    initMap();
}); here

I tried various test on IF and Else but does not work

How to make one element shrink while two other elements stay the same

async function main() {
    const numStudents = Number(await new Modal('annannannannanna', 'info', 'How many students do you have?', 'Cancel', 'Submit').response());
    const numGrades = Number(await new Modal('', 'info', 'How many grades does each student have?', 'Cancel', 'Submit').response());
}

class Modal {
    constructor(bodyText, type = 'info', headerText = null, footerText = 'Close', prompt = null, closeable = true) {
        this.type = type;
        if (headerText === null) {
            switch (this.type) {
                case 'success':
                    this.headerText = 'Success!';
                    break;
                case 'info':
                    this.headerText = 'Information';
                    break;
                case 'warning':
                    this.headerText = 'Warning!'
                    break;
                case 'error':
                    this.headerText = 'An error has occurred';
                    break;
                default:
                    this.headerText = 'Notification';
            }
        } else {
            this.headerText = headerText;
        }
        this.bodyText = bodyText;
        this.footerText = footerText;
        this.closeable = closeable;
        this.prompt = prompt;
        this.create();
        this.open();
    }

    create() {
        this.dialog = document.createElement('dialog');

        const header = document.createElement('header');
        header.classList.add(this.type, 'background');
        if (this.closeable) {
            const closeButton = document.createElement('button');
            closeButton.classList.add('close');
            closeButton.innerText = '×';
            header.appendChild(closeButton);
        }
        const headerText = document.createElement('h3');
        headerText.innerText = this.headerText;
        header.appendChild(headerText);
        this.dialog.appendChild(header);

        const form = document.createElement('form');
        form.method = 'dialog';

        const body = document.createElement('main');
        this.bodyText.split('nn').forEach((paragraph) => {
            const p = document.createElement('p');
            p.innerText = paragraph;
            body.appendChild(p);
        });
        if (this.prompt !== null) {
            this.input = document.createElement('input');
            this.input.placeholder = ' ';
            this.input.autofocus = true;
            const p = document.createElement('p');
            p.appendChild(this.input);
            body.appendChild(p);
        }
        form.appendChild(body);

        const footer = document.createElement('footer');
        footer.classList.add(this.type, 'text');
        const hiddenSubmitButton = document.createElement('button');
        hiddenSubmitButton.value = 'submit';
        hiddenSubmitButton.hidden = true;
        footer.appendChild(hiddenSubmitButton);
        const closeButton = document.createElement('button');
        closeButton.classList.add(this.type, 'text', 'animated');
        closeButton.innerText = this.footerText;
        footer.appendChild(closeButton);
        if (this.prompt === null) {
            closeButton.autofocus = true;
        } else {
            const submitButton = document.createElement('button');
            submitButton.classList.add(this.type, 'background', 'animated');
            submitButton.innerText = this.prompt;
            submitButton.value = 'submit';
            footer.appendChild(submitButton);
        }
        form.appendChild(footer);

        this.dialog.addEventListener('close', (event) => {
            this.close(event.target.returnValue);
        });
        this.dialog.appendChild(form);
        document.body.appendChild(this.dialog);
    }

    open() {
        this.dialog.showModal();
    }

    close(returnValue) {
        if (this.prompt !== null) {
            if (returnValue === '') {
                this.responseValue = null;
                if (this.rejectPromise !== undefined) {
                    this.rejectPromise('User canceled prompt');
                }
            } else {
                this.responseValue = this.input.value;
                if (this.rejectPromise !== undefined) {
                    this.resolvePromise(this.responseValue);
                }
            }
        }
    }

    response() {
        this.promise = new Promise((resolve, reject) => {
            if (this.responseValue !== undefined) {
                if (this.responseValue === null) {
                    reject('User canceled prompt')
                } else {
                    resolve(this.responseValue);
                }
            } else {
                this.resolvePromise = resolve;
                this.rejectPromise = reject;
            }
        });
        return this.promise;
    }
}

main();
:root {
    --error: #c00;
    --error-dark: #900;
    --error-light: #f00;
    --info: #36c;
    --info-dark: #039;
    --info-light: #69f;
    --muted: #ddd;
    --muted-dark: #888;
    --muted-light: #eee;
    --success: #0c0;
    --success-dark: #090;
    --success-light: #0f0;
    --warning: #cc0;
    --warning-dark: #990;
    --warning-light: #ff0;
}

body {
    font-family: Arial, Helvetica, sans-serif;
}

button {
    border: 2px solid;
    border-radius: 10px;
    cursor: pointer;
    margin: 1em 0.5em;
    padding: 10px 15px;
    transition: transform 1s;
}

button:active {
    transform: scale(90%);
}

button.animated {
    background-color: transparent;
    overflow: hidden;
    position: relative;
    transition: color 0.3s, border-color 0.3s, transform 0.2s;
    z-index: 1;
}

button.animated:hover {
    border-color: transparent;
}

button.animated::after {
    border: 0;
    border-radius: 50%;
    content: "";
    height: 200%;
    left: -50%;
    opacity: 0;
    position: absolute;
    transform: scale(0.1);
    transform-origin: center;
    transition: opacity 0.3s, transform 0.3s;
    top: -50%;
    width: 200%;
    z-index: -1;
}

button.animated:hover::after {
    opacity: 1;
    transform: scale(1);
}

input {
    border: 0;
    font: inherit;
    letter-spacing: normal;
    margin: 0;
    padding: 0;
}

input:focus, input:placeholder-shown {
    box-shadow: 0 2px 0 var(--muted);
    outline: none;
}

dialog {
    background-color: white;
    border: 0;
    border-radius: 10px;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    opacity: 0;
    outline: none;
    padding: 0;
    transform: scale(0);
    transition: all 0.4s allow-discrete;
    width: 50%;
}

dialog:open {
    opacity: 1;
    transform: scale(1);
}

@starting-style {
    dialog:open {
        opacity: 0;
        transform: scale(0);
    }
}

dialog::backdrop {
    background-color: rgba(0, 0, 0, 0);
    transition: all 0.4s allow-discrete;
}

dialog:open::backdrop {
    background-color: rgba(0, 0, 0, 0.4);
}

@starting-style {
    dialog:open::backdrop {
        background-color: rgba(0, 0, 0, 0);
    }
}

dialog header, dialog main, dialog footer {
    display: flow-root;
    padding: 0 1em;
    text-align: center;
}

dialog header {
    background-color: black;
    color: white;
}

dialog main, dialog footer {
    background-color: white;
    color: black;
}

dialog form {
    display: flex;
    flex-direction: column;
}

dialog header, dialog footer {
    flex: initial;
}

dialog main {
    flex: 1 1 auto;
    overflow-y: auto;
}

.close {
    aspect-ratio: 1 / 1;
    background-color: rgba(0, 0, 0, 0);
    border: 0;
    border-radius: 50%;
    box-sizing: border-box;
    color: var(--muted);
    font-size: 1.2em;
    font-weight: bold;
    height: 1.2em;
    margin: 0;
    padding: 0;
    position: absolute;
    right: 0.5rem;
    top: 0.5rem;
    user-select: none;
}

.close:hover,
.close:focus {
    background-color: rgba(255, 255, 255, 0.2);
    color: white;
}

.success.text, .info.text, .warning.text, .error.text, button.animated.success.background::after, button.animated.info.background::after, button.animated.warning.background::after, button.animated.error.background::after {
    background-color: white;
}

.success.background, .info.background, warning.background, error.background, button.animated.success.text:hover, button.animated.info.text:hover, button.animated.warning.text:hover, button.animated.error.text:hover {
    color: white;
}

button.animated.success.text, button.animated.info.text, button.animated.warning.text, button.animated.error.text {
    border-color: var(--muted);
}

.success.text, button.animated.success.background:hover {
    color: var(--success);
}

.success.background, button.animated.success.text::after {
    background-color: var(--success);
}

button.animated.success.text:hover, button.animated.success.background {
    border-color: var(--success);
} 

.info.text, button.animated.info.background:hover {
    color: var(--info);
}

.info.background, button.animated.info.text::after {
    background-color: var(--info);
}

button.animated.info.text:hover, button.animated.info.background {
    border-color: var(--info);
}

.warning.text, button.animated.warning.background:hover {
    color: var(--warning);
}

.warning.background, button.animated.warning.text::after {
    background-color: var(--warning);
}

button.animated.warning.text:hover, button.animated.warning.background {
    border-color: var(--warning);
}

.error.text, button.animated.error.background:hover {
    color: var(--error);
}

.error.background, button.animated.error.text::after {
    background-color: var(--error);
}

button.animated.error.text:hover, button.animated.error.background {
    border-color: var(--error);
}

I have a modal, as you can easily see in the link. When you resize the window until a scroll bar appears, you will see that the scroll bar appears for the entire modal. If you look closely, you can observe that the modal consists of a header (obviously), a main (the body text), and a footer (the button(s) at the bottom). I want the header and footer to act like a header and footer by only having the main portion have a scroll bar. How do I do this?

Video element not playing content of shared screen

I am trying to build my custom video conferencing using mediasoup. I am totally new to WebRTC and mediasoup. I already built my own SFU script that handles things like producers, consumers, whiteboard events … etc.

I started building a simple mediasoup-client script to connect to a room and share events among peers in the same room. My problem is with sharing screens in general, the event is sent successfully with creating producer and the other users get the mediatrack that the producer is sharing but when creating a video element and setting its srcObject to the track. Everything is set successfully but when testing it locally with 2 different tabs, the video element is created with the srcObject but nothing is actually showing in the video. Not even a black screen.

mediasoup-config.js:

module.exports = {
mediaCodecs: [
    {
        kind: "audio",
        mimeType: "audio/opus",
        clockRate: 48000,
        channels: 2,
    },
    {
        kind: "video",
        mimeType: "video/VP8",
        clockRate: 90000,
        parameters: {
            "x-google-start-bitrate": 1000,
        },
    },
],
};

shareScreen function:

async function shareScreen() {
const screenStream = await navigator.mediaDevices.getDisplayMedia({
    video: true
});

const screenTrack = screenStream.getVideoTracks()[0];

await sendTransport.produce({
    track: screenTrack,
    appData: { mediaType: 'screen' }
});

console.log('Shared screen track readyState:', screenTrack.readyState);
console.log('Screen track:', screenTrack);

localVideo.srcObject = screenStream;
localVideo.autoplay = true;
localVideo.playsInline = true;
}

handleNewConsumer function:

function handleNewConsumer(consumerData) {
console.log(consumerData);

const { id, kind, rtpParameters, producerId } = consumerData;

console.log('New consumer', consumerData);

recvTransport.consume({
    id,
    producerId,
    kind,
    rtpParameters,
}).then(consumer => {
    const stream = new MediaStream();
    stream.addTrack(consumer.track);

    console.log('Remote stream tracks:', stream.getTracks());
    console.log('Consumer track:', consumer.track);
    console.log('Track readyState:', consumer.track.readyState);
    console.log('Track muted:', consumer.track.muted);

    const remoteVideo = document.createElement('video');
    remoteVideo.autoplay = true;
    remoteVideo.playsInline = true;

    remoteVideo.onerror = (event) => {
        console.error('Video playback error:', event, remoteVideo.error);
    };

    remoteVideo.addEventListener('loadedmetadata', () => {
        console.log('Remote video loaded metadata:', remoteVideo.videoWidth, remoteVideo.videoHeight, remoteVideo.duration);
        remoteVideo.play().catch(err => {
            console.error('Auto-play failed:', err);
        });
    });

    remoteVideo.addEventListener('resize', () => {
        console.log('Remote video resized to:', remoteVideo.videoWidth, remoteVideo.videoHeight);
    });

    consumer.track.addEventListener('unmute', () => {
        console.log('Track unmuted, setting srcObject');
        remoteVideo.srcObject = stream;
        console.log('Remote video srcObject set:', remoteVideo.srcObject);
    });

    if (consumer.track.readyState === 'live' && !consumer.track.muted) {
        console.log('Track already live and unmuted, setting srcObject');
        remoteVideo.srcObject = stream;
        console.log('Remote video srcObject set:', remoteVideo.srcObject);
    }

    remoteVideos.appendChild(remoteVideo);
    console.log('Remote video element appended:', remoteVideo);
});
}

Failed loki js test ci

Can someone help me with this error ? Failed loki test command as local as remote in github

loki test v0.35.0 (node:15993) NOTE: The AWS SDK for JavaScript (v2)
is in maintenance mode. SDK releases are limited to address critical
bug fixes and security issues only.

Please migrate your code to use AWS SDK for JavaScript (v3). For more
information, check the blog post at https://a.co/cUPnyil (Use node --trace-warnings ... to show where the warning was created) FAIL chrome.app
Fetching stories
Failed fetching stories because the server is down
Try starting it with “yarn storybook” or pass the –port or –host arguments if it’s not running at http://10.242.224.33:15504 Some visual tests failed to run

storybook builded fine but by some reason it can’t finish run loki test

here my scripts

"scripts": {
    "start": "webpack server --env port=3000",
    "build:prod": "webpack   --env mode=production",
    "build:dev": "webpack   --env mode=development",
    "lint:ts": "eslint "**/*{ts,tsx}"",
    "lint:ts:fix": "eslint "**/*{ts,tsx}" --fix",
    "lint:scss": " npx stylelint "**/*.scss"",
    "lint:scss:fix": " npx stylelint "**/*.scss" --fix",
    "test:unit": "jest --config ./config/jest/jest.config.ts",
    "test:ui": "npx loki test",
    "test:ui:ok": "npx loki approve",
    "test:ui:ci":  "npx loki --requireReference update --reactUri file:./storybook-static",
    "storybook": "storybook dev -p 6006 -c ./config/storybook",
    "storybook:build": "storybook build -c ./config/storybook"   
}

here my loki settings in json file

"loki": {
    "configurations": {
      "chrome.laptop": {
        "target": "chrome.app",
        "width": 1366,
        "height": 768,
        "deviceScaleFactor": 1,
        "mobile": false
      },
      "chrome.iphone7": {
        "target": "chrome.app",
        "preset": "iPhone 7"
      }
    }
  }

What is a recommended design pattern for processing data from an API response in Yii2?

My Yii2 application (in PHP 7, so unfortunately I do not have strict types) receives from an API call responses which should be nested arrays looking like:

$response = [
  'session' => [
     'userData' => ['user_id' => 232, ...],
     'sessionData => ['status' => 'ONGOING', 'details' => 'Some details here...', ...],
     'additionalData' => [...]
  ]
]

Currently in my application logic, when I receive the response I manually check that each field exists and is of the required type. So for example I start by checking that $response['session'] exists and is an array, and I throw an exception if it doesn’t, so something like:

if (!array_key_exists($response, 'session')) {
    throw new Exception('Invalid response: missing "session" key in response array.');
}
if (!is_array($response['session'])) {
   throw new Exception('Invalid response: "session" is not an array in response array.');
}

Then I check for $response['session']['userData'] and I check that it’s an array, and so on. When I am certain that $response['session']['userData']['user_id'] exists, I also check that it is an integer, so I also do validation for the primitive received types.

I would like to decouple this logic from my main application, by having a separate model which stores all the primitive properties I want from the response and validates the primitive ones.

My problem is that I’m uncertain what would be the best design pattern to implement this.

My initial thought was to build a DTO-Hydrator-like pattern, so:

  1. A model (DTO) having as fields only the ‘primitive’ properties such as user_id, status, details, etc, but not the arrays like session, userData. This model would only be responsible for validation of the primitive fields (so checking that user_id is an integer for instance, checking that ‘status’ is in an array of admissible statuses, etc.)
  2. A Hydrator model which is responsible for checking that all desired
    primitive fields exist, and of course, that everything ‘in-between’
    exists, and then loading the primitive fields into the DTO.

However, this approach seems overly complicated. For one thing, I would have to instantiate both the DTO and the Hydrator each time I have to handle a response in my application logic, which would still make that logic too cumbersome for what I want. Ideally I would like to only do something like
$model->process($response)
in my application logic, but in a way that is also an endorsed design pattern. So is there a way to do this without the (seeming) overcomplication of the DTO-Hydrator pattern?

Docker does not download the specified image

Docker-Compose is not downloading the specific version of PHP that I want. I want the version “php:8.4.5-fpm” and it only downloads the “latest” version. I tried several things, but I can’t get it to download the specific image, it only downloads the “latest” image.

docker-compose.yml

version: "3.9"

services:
  nginx:
    build:
      context: ../nginx  # Caminho para a pasta Nginx (relativo à pasta docker-compose)
    ports:
      - "80:80"
    volumes:
      - ../app:/var/www/html  # Monta a pasta app como /var/www/html (relativo à pasta docker-compose)
    depends_on:
      - php
    networks:
      - laravel-network

  php:
    build:
      context: ../php  # Caminho para a pasta PHP (relativo à pasta docker-compose)
    expose:
      - 9000
    volumes:
      - ../app:/var/www/html  # Monta a pasta app como /var/www/html (relativo à pasta docker-compose)
    depends_on:
      - db
    networks:
      - laravel-network

  db:
    image: mariadb:11.7.2
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: laravel
      MYSQL_USER: laravel
      MYSQL_PASSWORD: laravel
    volumes:
      - db_data:/var/lib/mysql
    networks:
      - laravel-network

  phpmyadmin:
    image: phpmyadmin:latest
    ports:
      - "8080:80"
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: root
    depends_on:
      - db
    networks:
      - laravel-network

volumes:
  db_data:

networks:
  laravel-network:
    driver: bridge

Dockerfile PHP

FROM php:8.4.5-fpm

# Definir diretório de trabalho
WORKDIR /var/www/html

# Instalar dependências do sistema
RUN apt-get update && apt-get install -y 
    build-essential 
    libpng-dev 
    libjpeg62-turbo-dev 
    libfreetype6-dev 
    locales 
    zip 
    unzip 
    git 
    curl 
    libzip-dev 
    libonig-dev 
    libxml2-dev 
    && apt-get clean && rm -rf /var/lib/apt/lists/*

# Instalar extensões PHP necessárias para o Laravel
RUN docker-php-ext-install pdo_mysql mbstring zip exif pcntl soap
RUN docker-php-ext-configure gd --with-freetype --with-jpeg
RUN docker-php-ext-install gd

# Instalar o Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# Criar usuário para a aplicação Laravel
RUN groupadd -g 1000 www && useradd -u 1000 -ms /bin/bash -g www www

# Copiar o código da aplicação
COPY --chown=www:www . /var/www/html

# Alterar usuário
USER www

# Expor a porta 9000 para o PHP-FPM
EXPOSE 9000

CMD ["php-fpm"]

Dockerfile Nginx

FROM nginx:1.27.3

# Copiar a configuração do Nginx
COPY default.conf /etc/nginx/conf.d/default.conf

Drupal config sync but database drifting, how to automate ‘database migration’?

I am using drupal11.

Specifically, I am using the paragrpahs module where on fresh install of the module it will create the module related entity tables in the database. Then I export my config settings and save/commit. However, on a fresh install of my repo when I use drush config import to sync the configs, I get an error that the paragraph entity tables do not exist. I can fix this if I manually fix the database schema (drifting behind the code config) with a drupal drush entity update module. But, I dont want to have to manually check which tables are missing and manually input them. How to fix this issue? In a non drupal app I usually have a database migration tool to track all database schema changes.

Opencart how can i remove query in seo link

<?php
namespace OpencartCatalogControllerStartup;
/**
 * Class SeoUrl
 *
 * @package OpencartCatalogControllerStartup
 */
class SeoUrl extends OpencartSystemEngineController {
    /**
     * @return void
     */
    public function index(): void {
        if ($this->config->get('config_seo_url')) {
            $this->url->addRewrite($this);
    
            $this->load->model('design/seo_url');
    
            if (isset($this->request->get['_route_'])) {
                $parts = explode('/', $this->request->get['_route_']);
    
                // remove any empty arrays from trailing
                if (oc_strlen(end($parts)) == 0) {
                    array_pop($parts);
                }
    
                foreach ($parts as $part) {
                    $seo_url_info = $this->model_design_seo_url->getSeoUrlByKeyword($part);
    
                    if ($seo_url_info) {
                        $this->request->get[$seo_url_info['key']] = html_entity_decode($seo_url_info['value'], ENT_QUOTES, 'UTF-8');
                    }
                }
            }
        }
    }
    

    /**
     * @param string $link
     *
     * @return string
     */
    public function rewrite(string $link): string {
        $url_info = parse_url(str_replace('&amp;', '&', $link));
    
        $url = $url_info['scheme'] . '://' . $url_info['host'];
    
        if (isset($url_info['port'])) {
            $url .= ':' . $url_info['port'];
        }
    
        parse_str($url_info['query'], $query);
    
        $this->load->model('design/seo_url');
    
        $paths = [];
    
        // Dil parametresini sakla
        $language = '';
        if (isset($query['language'])) {
            $language = $query['language'];
            unset($query['language']);
        }
    
        // Eğer route varsa ilk olarak onu işleyelim
        if (isset($query['route'])) {
            $route = $query['route'];
    
            $result = $this->model_design_seo_url->getSeoUrlByKeyValue('route', $route);
    
            if ($result) {
                $paths[] = $result;
                unset($query['route']);
            }
        }
    
        // Diğer parametreleri işle (product_id, search vs.)
        foreach ($query as $key => $value) {
            $result = $this->model_design_seo_url->getSeoUrlByKeyValue((string)$key, (string)$value);
    
            if ($result) {
                $paths[] = $result;
                unset($query[$key]);
            }
        }
    
        // Sıralama
        usort($paths, fn($a, $b) => $a['sort_order'] <=> $b['sort_order']);
    
        $url .= str_replace('/index.php', '', $url_info['path']);
    
        foreach ($paths as $result) {
            $url .= '/' . $result['keyword'];
        }
    
        // Dil parametresini ekle
        if ($language) {
            $query['language'] = $language;
        }
    
        // Kalan query'leri ekle
        if ($query) {
            $url .= '?' . http_build_query($query);
        }
    
        return $url;
    }
}
##
# READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE!
#
# 1.To use URL Alias you need to be running apache with mod_rewrite enabled.
# 2. In your opencart directory rename .htaccess.txt (this file) to .htaccess
#
# For any support issues please visit: https://www.opencart.com
#
# The line 'Options +FollowSymLinks' may cause problems with some server configurations.
# It is required for the use of Apache mod_rewrite, but it may have already been set by
# your server administrator in a way that disallows changing it in this .htaccess file.
# If you encounter problems (e.g. site is not loading), comment out this line by adding a # in front
# FLOC is a feature suggested by Google, if this header shall not be set, disable the line
# having 'interest-cohort' by adding a # in front
##

## No directory listings
<IfModule mod_autoindex.c>
  IndexIgnore *
</IfModule>

## No-Referrer-Header
<IfModule mod_headers.c>
  Header set Referrer-Policy "no-referrer"
</IfModule>

## Suppress mime type detection in browsers for unknown types and prevent FLOC
<IfModule mod_headers.c>
  Header always set X-Content-Type-Options "nosniff"
  Header always set Permissions-Policy "interest-cohort=()"
</IfModule>

## Can be commented out if causes errors, see notes above.
Options +FollowSymlinks

## Prevent Directory listing
Options -Indexes

## Prevent Direct Access to files
<FilesMatch "(?i)((.tpl|.twig|.ini|.log|(?<!robots).txt))">
 Require all denied
## For apache 2.2 and older, replace "Require all denied" with these two lines :
# Order deny,allow
# Deny from all
</FilesMatch>

## SEO URL Settings
RewriteEngine On
## If your opencart installation does not run on the main web folder make sure you folder it does run in ie. / becomes /shop/
RewriteBase /upload/
## Rewrite Rules
RewriteRule ^system/storage/(.*) index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*.(ico|gif|jpg|jpeg|png|webp|js|css|svg)
RewriteRule ^(.*)$ index.php?_route_=$1 [L,QSA]

## Optional error documents
#ErrorDocument 400 /index.php?route=error/not_found
#ErrorDocument 401 /index.php?route=error/permission
#ErrorDocument 403 /index.php?route=error/not_found
#ErrorDocument 404 /index.php?route=error/not_found
#ErrorDocument 500 /index.php?route=error/not_found
#ErrorDocument 503 /index.php?route=error/not_found

## Additional Settings that may need to be enabled for some servers
## Uncomment the commands by removing the # sign in front of it.
## If you get an "Internal Server Error 500" after enabling any of the following settings, restore the # as this means your host doesn't allow that.

# 1. If your cart only allows you to add one item at a time, it is possible register_globals is on. This may work to disable it:
# php_flag register_globals off

# 2. If your cart has magic quotes enabled, This may work to disable it:
# php_flag magic_quotes_gpc Off

# 3. Set max upload file size. Most hosts will limit this and not allow it to be overridden but you can try
# php_value upload_max_filesize 999M

# 4. set max post size. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value post_max_size 999M

# 5. set max time script can take. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_execution_time 200

# 6. set max time for input to be recieved. Uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_input_time 200

# 7. disable open_basedir limitations
# php_admin_value open_basedir none

when i activate seo urls on admin panel. http://localhost/upload/koltuk-takimlari?route=product%2Fcategory always links coming this type. but i want to remove this part from url ?route=product%2Fcategory . I tried to ask gpt and claude and cursor but it didnt work . please help me

I tried to ask chatgpt but it didnt work

after form submission 404 error coming in wordpress

Hi I have created a form function code inside a theme functions.php file
my file is https://example.com/counsellor-registration/
which is showing html layout of form when i open this link .
problem is that after submitting form 404 error coming on same page

my code is

function custom_counsellor_registration_form() {
ob_start();
$form_action = esc_url(trailingslashit(get_permalink()));
error_log('Counsellor Form Action URL: ' . $form_action);

if (isset($_POST['counsellor_registration_submit'])) {
    error_log('Counsellor Form Submitted. POST Data: ' . print_r($_POST, true));
    $name = sanitize_text_field($_POST['name']);
    $designation = sanitize_text_field($_POST['designation']);
    $qualification = sanitize_text_field($_POST['qualification']);
    $time_slots = isset($_POST['time_slots']) ? array_map('sanitize_text_field', $_POST['time_slots']) : array();
    $specification = sanitize_textarea_field($_POST['specification']);
    $username = sanitize_text_field($_POST['username']);
    $email = sanitize_email($_POST['email']);
    $password = $_POST['password'];
    $agreement = isset($_POST['agreement']) ? 1 : 0;

    $errors = [];
    if (empty($username) || empty($email) || empty($password)) {
        $errors[] = "Username, email, and password are required.";
    }
    if (!is_email($email)) {
        $errors[] = "Please enter a valid email address.";
    }
    if (strlen($password) < 6) {
        $errors[] = "Password must be at least 6 characters long.";
    }

    if (empty($errors) && $agreement) {
        $user_id = wp_create_user($username, $password, $email);
        if (!is_wp_error($user_id)) {
            wp_update_user(array('ID' => $user_id, 'role' => 'counsellor'));
            update_user_meta($user_id, 'name', $name);
            update_user_meta($user_id, 'designation', $designation);
            update_user_meta($user_id, 'qualification', $qualification);
            update_user_meta($user_id, 'time_slots', $time_slots);
            update_user_meta($user_id, 'specification', $specification);
            wp_redirect(wp_login_url() . '?registration=success');
            exit;
        } else {
            error_log('Counsellor Registration Error: ' . $user_id->get_error_message());
            $errors[] = $user_id->get_error_message();
        }
    }

    if (!empty($errors)) {
        echo '<div class="message" style="color:red;">';
        foreach ($errors as $error) {
            echo '<p>' . esc_html($error) . '</p>';
        }
        echo '</div>';
    } else if (!$agreement) {
        echo '<p class="message" style="color:red;">Please agree to the terms to proceed.</p>';
    }
}
?>
<div class="registration-form">
    <h2>Counsellor Registration</h2>
   <form action="" enctype="multipart/form-data" method="POST">
        <p>
            <label for="name">Name:</label><br>
            
          
            <input type="text" name="name" id="name" value="<?php echo isset($_POST['name']) ? esc_attr($_POST['name']) : ''; ?>" required>
        </p>
        <p>
            <label for="designation">Designation:</label><br>
            <input type="text" name="designation" id="designation" value="<?php echo isset($_POST['designation']) ? esc_attr($_POST['designation']) : ''; ?>" required>
        </p>
        <p>
            <label for="qualification">Qualification:</label><br>
            <input type="text" name="qualification" id="qualification" value="<?php echo isset($_POST['qualification']) ? esc_attr($_POST['qualification']) : ''; ?>" required>
        </p>
        <p>
            <label>Time slot comfortable for you:</label><br>
            <div class="time-slot">
                <input type="checkbox" name="time_slots[]" value="9 AM - 12 PM" <?php echo isset($_POST['time_slots']) && in_array('9 AM - 12 PM', $_POST['time_slots']) ? 'checked' : ''; ?>> 9 AM - 12 PM<br>
                <input type="checkbox" name="time_slots[]" value="12 PM - 3 PM" <?php echo isset($_POST['time_slots']) && in_array('12 PM - 3 PM', $_POST['time_slots']) ? 'checked' : ''; ?>> 12 PM - 3 PM<br>
                <input type="checkbox" name="time_slots[]" value="3 PM - 6 PM" <?php echo isset($_POST['time_slots']) && in_array('3 PM - 6 PM', $_POST['time_slots']) ? 'checked' : ''; ?>> 3 PM - 6 PM<br>
                <input type="checkbox" name="time_slots[]" value="6 PM - 9 PM" <?php echo isset($_POST['time_slots']) && in_array('6 PM - 9 PM', $_POST['time_slots']) ? 'checked' : ''; ?>> 6 PM - 9 PM<br>
            </div>
        </p>
        <p>
            <label for="specification">Any specification:</label><br>
            <textarea name="specification" id="specification"><?php echo isset($_POST['specification']) ? esc_textarea($_POST['specification']) : ''; ?></textarea>
        </p>
        <p>
            <label for="username">Username:</label><br>
            <input type="text" name="username" id="username" value="<?php echo isset($_POST['username']) ? esc_attr($_POST['username']) : ''; ?>" required>
        </p>
        <p>
            <label for="email">Email ID:</label><br>
            <input type="email" name="email" id="email" value="<?php echo isset($_POST['email']) ? esc_attr($_POST['email']) : ''; ?>" required>
        </p>
        <p>
            <label for="password">Password:</label><br>
            <input type="password" name="password" id="password" required>
        </p>
        <p>
            <input type="checkbox" name="agreement" id="agreement" required <?php echo isset($_POST['agreement']) ? 'checked' : ''; ?>>
            <label for="agreement">I agree all the details given above are true to the best of my knowledge</label>
        </p>
        <p>
            <input type="submit" name="counsellor_registration_submit" value="Register">
        </p>
    </form>
</div>
<?php
return ob_get_clean();
}

    add_shortcode('custom_counsellor_registration', 'custom_counsellor_registration_form');

I have also tried with <form method="post" action="<?php echo esc_url(trailingslashit(get_permalink())); ?>">

when I submit form my headers shows

scheme
    https
host
    example.com
filename
    /counsellor-registration/
Status
200

my request goes

------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="name"

testing name
------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="designation"

MD
------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="qualification"

MBBS
------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="time_slots[]"

12 PM - 3 PM
------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="specification"

klklkl
------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="username"

counc01
------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="email"

[email protected]
------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="password"

123456
------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="agreement"

on
------geckoformboundarya1c41156493fa0c19c973b6717e255d9
Content-Disposition: form-data; name="counsellor_registration_submit"

Register
------geckoformboundarya1c41156493fa0c19c973b6717e255d9--

Can not initiate js circle progress in Gutenberg FSE

I have created a custom Gutenberg block via npx @wordpress/create-block called stat-block, I have index.js, edit.js, save.js, view.js and block.json. I believe I have everything setup correctly as all my attributes are getting saved and the circle-progress is rendering correctly on the frontend, however the backend within the FSE is not initiating the circle-progress element. What am I doing wrong in my code?

import { useBlockProps, RichText, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, RangeControl } from '@wordpress/components';
import { useEffect } from '@wordpress/element';
import CircleProgress from 'js-circle-progress';

export default function Edit({ attributes, setAttributes }) {
    const { text, percentage } = attributes;

    const blockProps = useBlockProps({
        className: `stat-block`,
    });

    useEffect(() => {
        const cp = new CircleProgress();
    }, [percentage]);

    return (
        <>
            <InspectorControls>
                <PanelBody title="Stat Percentage">
                    <RangeControl
                        label="Stat Percentage"
                        value={percentage}
                        onChange={(value) => setAttributes({ percentage: value })}
                        min={0}
                        max={100}
                        step={1}
                    />
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                <RichText
                    tagName="div"
                    className="stat-text"
                    value={text || ''}
                    onChange={(value) => setAttributes({ text: value })}
                    placeholder="Add stat text"
                    allowedFormats={['core/bold', 'core/italic']}
                />

                <circle-progress value={percentage} max="100"></circle-progress>
            </div>
        </>
    );
}

Razor C# DataTable to Javascript Array

i have datatable in Razor Project with rows contain id,Name,title,parent, fields… and i need to bind javascript array like below, but
dynamically, so i try this code and i have got an error… please help


var testData = [
        { id: 1, name: "John", title: "CEO", parent: 0 }, { id: 2, name: "Tom", title: "SellManager", parent: 1 }, { id: 3, name: "Jerry", title: "SupportManager", parent: 1 }, { id: 4, name: "Robert", title: "SellExpert", parent: 2 },
 ];

var testData = [];
@foreach (DataRow row in Model.Table_Public.Rows)
{
   <text>
        testData.push({id:@row["id"], Name:@row["Name"],title:@row["Title"],       parent:@row["parent"]});
   </text>
}
alert(testData);


 @foreach (DataRow row in Model.Table_Public.Rows)
 {
     ScriptTemp += "{ id: " + row["id"] + ", name: '" + row["Name"] + "', title: '" + row["Title"] + "', parent: " + row["Parent"] + " },";
     
 }

<script>
var testData = [@ScriptTemp];
alert(testData);
</script>

How can I use ‘stats-base-dists-chisquare’ in SVG using JavaScript?

In SVG file, I written some JavaScript code to calculate chisquare.cdf values.
After searching a lot, I find following code that seems to be for me:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg id="chi-square_pdf"
  version="1.1"
  baseProfile="full"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  xmlns:ev="http://www.w3.org/2001/xml-events"
  >

<script type="module">
    import chisquare from 'https://cdn.jsdelivr.net/gh/stdlib-js/stats-base-dists-chisquare@esm/index.mjs';
    
    let k = 4;
    let y = chisquare.cdf(2.0,k);

</script
</svg>

But when running (loading) this file, browser console is displaying following error message

enter image description here

When I test same thing using HTML, that is working. This problem occurs because SVG is XML and module script are not accepted in XML file.

<!DOCTYPE html>
<html>
<body>
<script type="module">

import roundn from 'https://cdn.jsdelivr.net/gh/stdlib-js/math-base-special-roundn@esm/index.mjs';
import chisquare from 'https://cdn.jsdelivr.net/gh/stdlib-js/stats-base-dists-chisquare@esm/index.mjs';

// Define degrees of freedom:
var k = 5.0;

// Evaluate probability functions:
var x = 3.0;
console.log( 'nEvaluating at x = %d', x );
console.log( 'PDF: %d', roundn( chisquare.pdf( x, k ), -4 ) );
console.log( 'logPDF: %d', roundn( chisquare.logpdf( x, k ), -4 ) );
console.log( 'CDF: %d', roundn( chisquare.cdf( x, k ), -4 ) );

</script>
</body>
</html>

What must I do to use chisquare.cdf() function in SVG file?

I have already tried to use require() function or import statement in normal <script type="text/javascript"> tag, but nothing works.

why my spinner component doesnt take the scheme color selected by the user – Next js +13

YES, I ALREADY ASKED TO CHATGPT.

i am using next js 15.2.3 and i implemented a spinner component that is activated when one navigation occurs, it is works! now i implemented a ThemeProvider (Context) for when the user select between dark mode or light mode. so… my spinner component doesnt paint its background with the theme selected by the user. only that spinner component, the others do take the theme.

below i share my code and then the chatgpt solutions that didn’t work for me:

app/layout.js:

import "./global.css";

export default function RootLayout({children}) {
   return(
      <html lang="en">
         <body>
           <ThemeProvider>
              <GlobalLoader />
              {children}
           </ThemeProvider>
         </body>
      </html>
   );

}

global.css

body.light {
   --background: #fff;
   --foreground: #000;
   background: var(--background);
   color: var(--foreground);
}

body.dark {
   --background: #000;
   --foreground: #fff;
   background: var(--background);
   color: var(--foreground);
}

ThemeProvider

"use client";

import { createContext, useContext, useEffect, useState } from "react";

const ThemeContext = createContext();

export function ThemeProvider({ children }) {
    const [theme, setTheme] = useState(() => {
        if (typeof window !== "undefined") {
            const storedTheme = localStorage.getItem("theme");
            if (storedTheme) return storedTheme;

            const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
            return prefersDark ? "dark" : "light";
        }

        return "light";
    });

    useEffect(() => {
        document.body.classList.remove("light", "dark");
        document.body.classList.add(theme);
        localStorage.setItem("theme", theme);
    }, [theme]);

    return (
        <ThemeContext.Provider value={{ theme, setTheme }}>
            {children}
        </ThemeContext.Provider>
    );
}

export const useTheme = () => useContext(ThemeContext);

in my switch component to change the theme only i do:

const {theme, setTheme} = useTheme();
<input onChange((e) => e.target.checked ? "light" : "dark") />

it works! except the question…

GlobalLoader:

export default function GlobalLoader() {
    const pathname = usePathname();
    const [spinner, setSpinner] = useState(false);

    useEffect(() => {
        setSpinner(true);

        const handleLoad = () => {
           setSpinner(false);

        };

        const handleBeforeUnload = () => {
            setSpinner(true);
        };

        window.addEventListener("load", handleLoad);
        window.addEventListener("beforeunload", handleBeforeUnload);

        return () => {
            window.removeEventListener("load", handleLoad);
            window.removeEventListener("beforeunload", handleBeforeUnload);
        };
    }, [pathname]);

    if (spinner) return null;

    return <Spinner/>;

Spinner:

export default function Spinner() {
    return (
        <section className={`${style.wrapper} ${style.dark}`}>
            <div className={`${style.spinner}`}>
                <i></i>
                <i></i>
                <i></i>
                <i></i>
                <i></i>
                <i></i>
                <i></i>
                <i></i>
            </div>
        </section>
    );

Spinner.module.css

section.wrapper {
    padding: 40px 0;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 500;
}

section.wrapper.dark {
    background: var(--background);
    display: flex;
    justify-content: center;

    transition: background-color 1s ease;
}

at begin i had global.css like this:

:root {
   /* light by default */
   --background: #fff;
   --foreground: #000;
}

@media(prefers-color-scheme: dark) {
   --background: #000;
   --foreground: #fff;
}

and works! my spinner component has background by default system ( win10 ), but i want that change with de user select-

GPT told me the problem is that my spinner component it build before the theme is apply on html tag or body tag. it suggested me to do below (no one suggestions works for me):

1: define a script that applies theme before it rendered:

<head>
   <script dangerouslySetInnerHTML={{
      __html: `
         (function(){
            const stored = localStorage.getItem("theme");
            const theme = stored || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
            document.documentElement.classList.add(theme);
         })();
      `,
   }} />
</head>

2: apply the theme on html tag from my ThemeProvider:

useEffect(() => {
   // ThemeProviderComponent
   document.documentElement.classList.remove("light", "dark");
   document.documentElement.classList.add(theme);
   localStorage.setItem("theme", theme);
}, [theme]);


// changes global.css to:
html.light {
   --background: #fff;
   --foreground: #000;

   background: var(--background);
   color: var(--foreground);
}

html.dark {
   --background: #000;
   --foreground: #fff;

   background: var(--background);
   color: var(--foreground);
}

3: wait until my spinner it had mounted on my GlobalLoader:

// GlobalLoader
const [mounted, setMounted] = useState(false);

useEffect(()=>{
   setMounted(true);
}, []);

...

if(!mounted) return null; // here it does not show my spinner

if(spinner) return null;

return <Spinner />

anomaly: if in this line if (spinner) return null
i deny with !: if (!spinner) return null
my spinner it will be showing forever with the background selected by the user, if it is select light or dark, it is draw… akward. ( i must select the theme before and then negate the state variable because it does not let me afterwards)

and that is all, i have no idea why this problem occurs…