Tag: php

  • Uno script php per assegnare i giusti permessi a file e cartelle di WordPress

    Uno script php per assegnare i giusti permessi a file e cartelle di WordPress

    Qualche tempo fa, abbiamo pubblicato un post con uno script sh, che poteva essere lanciato da console Linux che consentiva di settare i permessi a file e cartelle utili al corretto funzionamento di WordPress.

    Un nostro lettore, ci ha segnalato che in alcuni hosting non è possibile lanciare script sh, quindi abbiamo deciso di pubblicare uno script php, che può essere lanciato anche visitandone il path.

    Nel test che abbiamo fatto il file si chiamava set_wordpress_permissions.php e pertanto abbiamo avuto la possibilità, accedendo alla pagina nomesito.com/set_wordpress_permissions.php, di settare i permessi giusti a tutta l’alberatura di file e cartelle di wordpress e in un pochi attimi.

    Lo script php

    <?php
    // Configurazione della directory root di WordPress
    $wp_root = "/percorso/al/tuo/sito"; // Cambia con il percorso della tua installazione di WordPress

    // Configurazione dell'utente e gruppo (facoltativo, solo su server Linux/Unix con funzione `chown`)
    $user = "www-data"; // Utente del web server (es: www-data, apache, nginx)
    $group = "www-data"; // Gruppo del web server

    /**
    * Funzione per impostare i permessi sui file e directory.
    *
    * @param string $path Percorso della directory o file
    * @param int $filePerm Permessi da impostare sui file (es: 0644)
    * @param int $dirPerm Permessi da impostare sulle directory (es: 0755)
    */
    function set_permissions($path, $filePerm = 0644, $dirPerm = 0755) {
    // Controlla se il percorso è valido
    if (!file_exists($path)) {
    echo "Percorso non trovato: $path\n";
    return;
    }

    // Scansiona ricorsivamente file e directory
    $iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($iterator as $item) {
    if ($item->isDir()) {
    chmod($item->getPathname(), $dirPerm); // Imposta permessi sulle directory
    } else {
    chmod($item->getPathname(), $filePerm); // Imposta permessi sui file
    }
    }

    // Imposta i permessi sulla directory principale
    chmod($path, $dirPerm);
    echo "Permessi impostati su $path\n";
    }

    /**
    * Funzione per impostare proprietario e gruppo (facoltativo).
    *
    * @param string $path Percorso della directory o file
    * @param string $user Nome utente
    * @param string $group Nome gruppo
    */
    function set_owner($path, $user, $group) {
    if (!function_exists('chown') || !function_exists('chgrp')) {
    echo "Funzioni chown/chgrp non disponibili su questo sistema.\n";
    return;
    }

    // Scansiona ricorsivamente file e directory
    $iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($iterator as $item) {
    chown($item->getPathname(), $user);
    chgrp($item->getPathname(), $group);
    }

    // Imposta proprietario e gruppo sulla directory principale
    chown($path, $user);
    chgrp($path, $group);
    echo "Proprietario impostato su $path a $user:$group\n";
    }

    // Imposta i permessi di base per il sito WordPress
    set_permissions($wp_root, 0644, 0755);

    // Imposta permessi sicuri per wp-config.php
    $wp_config = $wp_root . "/wp-config.php";
    if (file_exists($wp_config)) {
    chmod($wp_config, 0600);
    echo "Permessi sicuri impostati per wp-config.php\n";
    }

    // Imposta permessi speciali per wp-content/uploads
    $uploads_dir = $wp_root . "/wp-content/uploads";
    if (is_dir($uploads_dir)) {
    set_permissions($uploads_dir, 0664, 0775); // Scrivibile da utente e gruppo
    }

    // Imposta proprietario e gruppo (facoltativo)
    set_owner($wp_root, $user, $group);

    echo "Permessi configurati con successo per WordPress.\n";
  • Tornare a una versione di WordPress precedente su hosting economici senza disponibilità della console ssh

    Tornare a una versione di WordPress precedente su hosting economici senza disponibilità della console ssh

    Come riportare indietro la versione di WordPress nella maniera più semplice ed efficace possibile su un hosting che non mette a disposizione ssh, cli e altri strumenti avanzati.

    Sei in questa scabrosa situazione? Il tuo hosting di quattro spicci non ti consente di lanciare comandi, usare la wp-cli, accedere via ssh e cose varie? Nessun problema ragazzo, non sei il solo.

    L’idea dietro la soluzione che ti vado a esporre è creare un file php che possa essere invocato da browser (andando per esempio su miosito.com/miofile.php).
    Tale file conterrà una serie di comandi in grado di riportare il tuo wordpress indietro ( o avanti ) alla tua versione preferita.

    In questa casistica dovevo tornare a WordPress 6.7, perché l’aggiornamento aveva creato non pochi problemi.

    Pertanto, ecco il file:

    <?php
    // Imposta l'header per evitare timeout del browser
    set_time_limit(0);
    header('Content-Type: text/plain');

    // Percorso del file wp-cli.phar
    $wpCliPath = __DIR__ . '/wp-cli.phar';

    try {
    // Scarica WP-CLI se non esiste già
    if (!file_exists($wpCliPath)) {
    echo "Scaricamento di WP-CLI...\n";
    $downloadCommand = "curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar";
    exec($downloadCommand, $output, $returnVar);

    if ($returnVar !== 0) {
    throw new Exception("Errore durante il download di WP-CLI.\n" . implode("\n", $output));
    }

    // Verifica che il file sia stato scaricato
    if (!file_exists($wpCliPath)) {
    throw new Exception("Il file wp-cli.phar non è stato scaricato correttamente.");
    }

    echo "WP-CLI scaricato con successo.\n";
    } else {
    echo "WP-CLI già presente.\n";
    }

    // Rende il file wp-cli.phar eseguibile
    chmod($wpCliPath, 0755);

    // Comando per aggiornare WordPress alla versione 6.7
    echo "Aggiornamento di WordPress alla versione 6.7...\n";
    $updateCommand = "php $wpCliPath core update --version=6.7";
    exec($updateCommand, $output, $returnVar);

    if ($returnVar !== 0) {
    throw new Exception("Errore durante l'aggiornamento di WordPress.\n" . implode("\n", $output));
    }

    echo "WordPress aggiornato con successo alla versione 6.7.\n";
    } catch (Exception $e) {
    // Gestione degli errori
    echo "Errore: " . $e->getMessage() . "\n";
    }
    ?>

    Ti basterà salvare il file nella root del sito e invocare il file attraverso la url.

    Figo no?

  • Change gravatar on product reviews from author email to comment email field using get_avatar wordpress hook

    Enhancing user experience in your WordPress store is crucial for standing out and improving customer interaction and reviews area is one of the most used by customers who want to figure out if a certain product fits their needs or not, based on the experience of other users.

    By default, WooCommerce products reviews use the avatar associated with the logged-in user, but it can be more beneficial to show the avatar based on the email provided in the comment. Here’s how you can achieve this.

    What is Gravatar?

    Gravatar (Globally Recognized Avatar) is a service that provides globally unique avatars based on users’ email addresses. When users comment on your site and provide their email, the corresponding Gravatar is displayed, adding a personal touch and increasing the authenticity of the reviews.

    WordPress natively integrates Gravatar to grab comment/reviews profile image, as well as in other areas (such as back-end user pages).

    Solution implementation

    I struggle a little bit to find the right filter to use for my purpose; eventually I bumped into get_avatar.

    This filter allows us to intercept and modify the displayed avatar based on the email entered in the comment field rather than the logged-in user e-email. Here’s the code to implement this solution:

    <?php
    function custom_get_avatar_for_product_review( $avatar, $id_or_email, $args ) {
        // Check if the object is a comment
        if ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {
            $comment = $id_or_email;
    
            // Check if the comment is associated with a WooCommerce product
            if ( get_post_type( $comment->comment_post_ID ) == 'product' ) {
                // Get the commenter's email from the comment email field
                $commenter_email = get_comment_author_email( $comment->comment_ID );
    
                // Generate the Gravatar for the commenter's email
                $avatar = get_avatar( $commenter_email, $args['size'], $args['default'], $args['alt'], $args );
            }
        }
    
        return $avatar;
    }
    add_filter( 'get_avatar', 'custom_get_avatar_for_product_review', 10, 3 );
    

    NOTE: As you can notice we limited this functionality to product post_type, you can change according to the needs you want to fullfill.

    Hope this help people.