Snippets Collections
brew install shivammathur/php/php@8.0

brew unlink php@8.2 && brew link —force —overwrite php@7.4

add_filter( 'woocommerce_checkout_cart_item_quantity', 'bbloomer_checkout_item_quantity_input', 9999, 3 );
  
function bbloomer_checkout_item_quantity_input( $product_quantity, $cart_item, $cart_item_key ) {
   $product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
   $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
   if ( ! $product->is_sold_individually() ) {
      $product_quantity = woocommerce_quantity_input( array(
         'input_name'  => 'shipping_method_qty_' . $product_id,
         'input_value' => $cart_item['quantity'],
         'max_value'   => $product->get_max_purchase_quantity(),
         'min_value'   => '0',
      ), $product, false );
      $product_quantity .= '<input type="hidden" name="product_key_' . $product_id . '" value="' . $cart_item_key . '">';
   }
   return $product_quantity;
}
 
// ----------------------------
// Detect Quantity Change and Recalculate Totals
 
add_action( 'woocommerce_checkout_update_order_review', 'bbloomer_update_item_quantity_checkout' );
 
function bbloomer_update_item_quantity_checkout( $post_data ) {
   parse_str( $post_data, $post_data_array );
   $updated_qty = false;
   foreach ( $post_data_array as $key => $value ) {   
      if ( substr( $key, 0, 20 ) === 'shipping_method_qty_' ) {         
         $id = substr( $key, 20 );   
         WC()->cart->set_quantity( $post_data_array['product_key_' . $id], $post_data_array[$key], false );
         $updated_qty = true;
      }     
   }  
   if ( $updated_qty ) WC()->cart->calculate_totals();
}
define( 'RECOVERY_MODE_EMAIL', 'myemail@example.com' );
add_filter('woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect');

function custom_add_to_cart_redirect($url) {
    global $woocommerce;
    $checkout_url = wc_get_checkout_url();

    return $checkout_url;
}
function custom_checkout_text_change( $translated_text, $text, $domain ) {
    if ( $domain === 'woocommerce' && $text === 'Billing details' ) {
        $translated_text = 'Billing Details';
    }
    return $translated_text;
}
add_filter( 'gettext', 'custom_checkout_text_change', 20, 3 );
for "laravel-mix": "^6.0.49",

"scripts": {
    "dev": "npm run development",
    "development": "mix",
    "watch": "mix watch",
    "watch-poll": "mix watch -- --watch-options-poll=1000",
    "hot": "mix watch --hot",
    "prod": "npm run production",
    "production": "mix --production"
},




"scripts": {
    "dev": "npm run development",
    "development": "mix",
    "watch": "mix watch",
    "watch-poll": "mix watch -- --watch-options-poll=1000",
    "hot": "mix watch --hot",
    "prod": "npm run production",
    "production": "mix --production"
},
require_once __DIR__ . '/vendor/autoload.php';

$klein = new \Klein\Klein();

$klein->respond('GET', 'name/[:name]', function ($request) {
    return 'Hello ' . $request->name;
});

$klein->dispatch();
function bulk_modifier_page() {
    global $wpdb;

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
        // Check if a CSV file is uploaded successfully
        if ($_FILES['csv_file']['error'] == UPLOAD_ERR_OK) {
            $file = $_FILES['csv_file']['tmp_name'];

            // Read the CSV file
            $csv_data = array_map('str_getcsv', file($file));
            $csv_headers = array_shift($csv_data); // Get headers

            // Define the mapping of CSV columns to database columns for wp_za_groups table
            $group_column_mapping = array(
                'group_name' => 'title',
                'priority' => 'priority',
                'apply_to' => 'apply_to',
                'author_id' => 'admin_id',
                'created_at' => 'created_at',
                'created_at_gmt' => 'created_at_gmt',
                'updated_at' => 'updated_at',
                'updated_at_gmt' => 'updated_at_gmt'
            );

            // Define the mapping of CSV columns to database columns for wp_za_types table
            $type_column_mapping = array(
                'title_name' => 'title',
                'type' => 'type',
                'status' => 'status',
                'description' => 'description',
                'required' => 'required',
                'display_description_on_expansion' => 'display_description_on_expansion',
                'hide_description' => 'hide_description',
                'tooltip_description' => 'tooltip_description',
                'created_at' => 'created_at',
                'created_at_gmt' => 'created_at_gmt',
                'updated_at' => 'updated_at',
                'updated_at_gmt' => 'updated_at_gmt'
            );

            // Define the mapping of CSV columns to database columns for wp_za_values table
            $value_column_mapping = array(
                'addons_title' => 'title',
                'price' => 'price',
                'description_value' => 'description',
                'sku' => 'sku',
            );

            // Insert data into the wp_za_groups, wp_za_types, wp_za_values, wp_za_products_to_groups, and wp_za_categories_to_groups tables
            foreach ($csv_data as $row) {
                // Prepare data for wp_za_groups table
                $group_data = array();
                foreach ($csv_headers as $key => $header) {
                    if (isset($group_column_mapping[$header])) {
                        $group_data[$group_column_mapping[$header]] = $row[$key];
                    }
                }

                // Set default values for created_at, created_at_gmt, updated_at, updated_at_gmt
                $group_data['created_at'] = current_time('mysql');
                $group_data['created_at_gmt'] = current_time('mysql', true);
                $group_data['updated_at'] = current_time('mysql');
                $group_data['updated_at_gmt'] = current_time('mysql', true);

                // Insert data into the wp_za_groups table
                $wpdb->insert($wpdb->prefix . 'za_groups', $group_data);
                $group_id = $wpdb->insert_id; // Get the group ID

                // Prepare data for wp_za_types table
                $type_data = array(
                    'group_id' => $group_id,
                    'step' => 0, // Default value
                    'accordion' => 'open', // Default value
                );

                // Map CSV columns to database columns for wp_za_types table and set default values
                foreach ($csv_headers as $key => $header) {
                    if (isset($type_column_mapping[$header])) {
                        if ($header === 'status' && !isset($type_data['status'])) {
                            // Set default status if not present in CSV
                            $type_data['status'] = 'enable';
                        } elseif ($header === 'description' && !isset($type_data['description'])) {
                            // Set default description if not present in CSV
                            $type_data['description'] = 'none';
                        } elseif ($header === 'required' && !isset($type_data['required'])) {
                            // Set default required value if not present in CSV
                            $type_data['required'] = 0;
                        } elseif ($header === 'display_description_on_expansion' && !isset($type_data['display_description_on_expansion'])) {
                            // Set default display_description_on_expansion value if not present in CSV
                            $type_data['display_description_on_expansion'] = 0;
                        } elseif ($header === 'hide_description' && !isset($type_data['hide_description'])) {
                            // Set default hide_description value if not present in CSV
                            $type_data['hide_description'] = 0;
                        } elseif ($header === 'tooltip_description' && !isset($type_data['tooltip_description'])) {
                            // Set default tooltip_description value if not present in CSV
                            $type_data['tooltip_description'] = 0;
                        } else {
                            $type_data[$type_column_mapping[$header]] = $row[$key];
                        }
                    }
                }

                // Set default values for created_at, created_at_gmt, updated_at, updated_at_gmt
                $type_data['created_at'] = current_time('mysql');
                $type_data['created_at_gmt'] = current_time('mysql', true);
                $type_data['updated_at'] = current_time('mysql');
                $type_data['updated_at_gmt'] = current_time('mysql', true);

                // Insert data into the wp_za_types table
                $wpdb->insert($wpdb->prefix . 'za_types', $type_data);
                $type_id = $wpdb->insert_id; // Get the type ID

                // Prepare data for wp_za_values table
                $value_data = array(
                    'type_id' => $type_id,
                    'step' => $wpdb->get_var("SELECT COUNT(*) FROM " . $wpdb->prefix . "za_values WHERE type_id = $type_id") + 1, // Increment step
                );

                // Map CSV columns to database columns for wp_za_values table and set default values
                foreach ($csv_headers as $key => $header) {
                    if (isset($value_column_mapping[$header])) {
                        if ($header === 'description_value' && !isset($value_data['description'])) {
                            // Set default description if not present in CSV
                            $value_data['description'] = 'no value';
                        } elseif ($header === 'checked' && !isset($value_data['checked'])) {
                            // Set default checked value if not present in CSV
                            $value_data['checked'] = 0;
                        } elseif ($header === 'hide_description' && !isset($value_data['hide_description'])) {
                            // Set default hide_description value if not present in CSV
                            $value_data['hide_description'] = 0;
                        } else {
                            $value_data[$value_column_mapping[$header]] = $row[$key];
                        }
                    }
                }

                // Set default values for created_at, created_at_gmt, updated_at, updated_at_gmt
                $value_data['created_at'] = current_time('mysql');
                $value_data['created_at_gmt'] = current_time('mysql', true);
                $value_data['updated_at'] = current_time('mysql');
                $value_data['updated_at_gmt'] = current_time('mysql', true);

                // Insert data into the wp_za_values table
                $wpdb->insert($wpdb->prefix . 'za_values', $value_data);
                $value_id = $wpdb->insert_id; // Get the value ID

                // Prepare data for wp_za_products_to_groups table
                $product_names = explode(',', $row[array_search('products_name', $csv_headers)]);
                foreach ($product_names as $product_name) {
                    $product_id = $wpdb->get_var("SELECT ID FROM " . $wpdb->posts . " WHERE post_title = '$product_name' AND post_type = 'product'");

                    if ($product_id) {
                        $product_to_group_data = array(
                            'product_id' => $product_id,
                            'group_id' => $group_id,
                        );

                        // Insert data into the wp_za_products_to_groups table
                        $wpdb->insert($wpdb->prefix . 'za_products_to_groups', $product_to_group_data);
                    }
                }

                // Prepare data for wp_za_categories_to_groups table
                $category_names = explode(',', $row[array_search('category_names', $csv_headers)]);
                foreach ($category_names as $category_name) {
                    // Get the category ID based on the category name
                    $category_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM $wpdb->terms WHERE name = %s", $category_name));

                    if ($category_id) {
                        $category_to_group_data = array(
                            'category_id' => $category_id,
                            'group_id' => $group_id,
                        );

                        // Insert data into the wp_za_categories_to_groups table
                        $wpdb->insert($wpdb->prefix . 'za_categories_to_groups', $category_to_group_data);
                    }
                }
            }

            echo '<div class="updated"><p>Data imported successfully!</p></div>';
        } else {
            echo '<div class="error"><p>Error uploading CSV file.</p></div>';
        }
    }

    // Display the upload form
    ?>
   
    <div class="wrap">
        <h2>Bulk Modifier Upload</h2>
        <form method="post" action="" enctype="multipart/form-data">
            <input type="file" name="csv_file">
            <input type="submit" class="button button-primary" value="Upload CSV & Apply">
        </form>
    </div>
    
    <?php
}
aptitude search bash-completion
           //   bash sh-sequence-bash-completion
Ejecutamos este comando -basta con copy&paste- en la consola "sudo gedit /etc/bash.bashrc".
Descomentamos las tres últimas líneas de ese fichero que se ha abierto, quedando así:
if [ -f /etc/bashcompletion ]; then
. /etc/bashcompletion
fi

Una vez esté todo como el código que os mostramos podremos guardar de nuevo el fichero. Un apunte: antes de la primera línea hay un comentario que podéis dejar o eliminar. Yo personalmente os diría que no lo eliminéis para que sepáis para que sirve ese fichero en un futuro. Probad a comenzar a escribir un comando y pulsad TAB, veréis como se completa el comando automáticamente.

Un ejemplo muy básico para probar esta función es escribir "cd /h" y pulsar el tabulador, automáticamente debería aparecer "cd /home" en pantalla. Le dais a enter y ya tendréis el comando ejecutado.
https://code.visualstudio.com/docs/editor/tasks#vscode

function custom_check_distance($request) {
	
	// code to fetch address of store
	
	 $store_address = array(
        'store_address' => get_option('woocommerce_store_address'),
        'store_address_2' => get_option('woocommerce_store_address_2'),
        'store_city' => get_option('woocommerce_store_city'),
    );

    // Combine address components
    $combined_address = $store_address['store_address'] . ' ' . $store_address['store_address_2'] . ', ' .
                        $store_address['store_city'];

    $store_address['address'] = $combined_address;

    unset($store_address['store_address']);
    unset($store_address['store_address_2']);
    unset($store_address['store_city']);

	
	// code to fetch store adddress finish ...
	
	
//     $origin = sanitize_text_field($request->get_param('origin'));
    $origin = $store_address['address'];
    $destination = sanitize_text_field($request->get_param('destination'));
    
    // Make the API request
    $api_url = "https://maps.googleapis.com/maps/api/distancematrix/json?destinations=$destination&origins=$origin&units=kilometer&key=AIzaSyCNlRs8xfM4ZauggHgA5qx23nE4aBN4aQQ";
    $response = wp_safe_remote_get($api_url);
    
    if (is_wp_error($response)) {
        return new WP_Error('api_error', 'Error fetching data from API', array('status' => 500));
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body);
    
    // Check if the API response contains valid data
    if (empty($data) || $data->status !== 'OK') {
        return new WP_Error('api_error', 'Invalid API response', array('status' => 500));
    }
    
    // Extract distance in kilometers from the API response
    $distance_km = (float) str_replace(' km', '', $data->rows[0]->elements[0]->distance->text);
//     $flat_rate=10;
	$km=5;
	
 $option_name = 'woocommerce_flat_rate_3_settings';

    // Fetch the value from the database
    $option_value = get_option($option_name);

    if ($option_value !== false) {
        // The option exists, and $option_value contains its value

        if (isset($option_value['cost'])) {
            // Retrieve the "cost" value from the option value
            $tax_cost = $option_value['cost'];
		 $tax_cost = intval(str_replace('"', '', $tax_cost));

		}
	}
    // Compare the distance to 5 kilometers and return true or false
    $is_within_range = ($distance_km <= $km);
    
return array('status' => $is_within_range,
			'km'=>$km,
			'flatrate'=>$tax_cost
			);
}


// Add your API endpoint
function custom_distance_check_api_init() {
    add_action('rest_api_init', function () {
        register_rest_route('custom-distance-check/v1', '/check-distance', array(
            'methods' => 'GET',
            'callback' => 'custom_check_distance',
        ));
    });
}
add_action('init', 'custom_distance_check_api_init');
// Callback function for the API endpoint
function custom_check_distance($request) {
	
	// code to fetch address of store
	
	 $store_address = array(
        'store_address' => get_option('woocommerce_store_address'),
        'store_address_2' => get_option('woocommerce_store_address_2'),
        'store_city' => get_option('woocommerce_store_city'),
    );

    // Combine address components
    $combined_address = $store_address['store_address'] . ' ' . $store_address['store_address_2'] . ', ' .
                        $store_address['store_city'];

    $store_address['address'] = $combined_address;

    unset($store_address['store_address']);
    unset($store_address['store_address_2']);
    unset($store_address['store_city']);

	
	// code to fetch store adddress finish ...
	
	
//     $origin = sanitize_text_field($request->get_param('origin'));
    $origin = $store_address['address'];
    $destination = sanitize_text_field($request->get_param('destination'));
    
    // Make the API request
    $api_url = "https://maps.googleapis.com/maps/api/distancematrix/json?destinations=$destination&origins=$origin&units=kilometer&key=AIzaSyCNlRs8xfM4ZauggHgA5qx23nE4aBN4aQQ";
    $response = wp_safe_remote_get($api_url);
    
    if (is_wp_error($response)) {
        return new WP_Error('api_error', 'Error fetching data from API', array('status' => 500));
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body);
    
    // Check if the API response contains valid data
    if (empty($data) || $data->status !== 'OK') {
        return new WP_Error('api_error', 'Invalid API response', array('status' => 500));
    }
    
    // Extract distance in kilometers from the API response
    $distance_km = (float) str_replace(' km', '', $data->rows[0]->elements[0]->distance->text);
    $flat_rate=10;
	$km=5;
    // Compare the distance to 5 kilometers and return true or false
    $is_within_range = ($distance_km <= $km);
    
return array('status' => $is_within_range,
			'km'=>$km,
			'flatrate'=>$flat_rate
			);
}


// Add your API endpoint
function custom_distance_check_api_init() {
    add_action('rest_api_init', function () {
        register_rest_route('custom-distance-check/v1', '/check-distance', array(
            'methods' => 'GET',
            'callback' => 'custom_check_distance',
        ));
    });
}
add_action('init', 'custom_distance_check_api_init');
<script type="application/ld+json">
    "@context" : "https://schema.org/",
    {{ $slot }}
</script>
<?php 

if ( ! defined( 'ABSPATH' ) ) {

    die;

}
            
    $parameters = $request->get_json_params();
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = @$_SERVER['REMOTE_ADDR'];
    $result  = array('country'=>'','state'=>'', 'city'=>'');
    if(filter_var($client, FILTER_VALIDATE_IP)){
        $ip = $client;
    }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
        $ip = $forward;
    }else{
        $ip = $remote;
    }
    $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));    
    if($ip_data && $ip_data->geoplugin_countryName != null){
        $result['city'] = $ip_data->geoplugin_city;
        $result['state']=$ip_data-> geoplugin_regionCode;
        $result['country'] = $ip_data->geoplugin_countryCode;
    }
            
            
            
             
             if(isset($result)){   
                 
                 
                //$data =$parameters['data'];
                if (isset($result['country'])) {
                    $country =$result['country'];
                if (isset($result['state'])) {
                    $state = $result['state'];

                    global $wpdb;   
                    $url = get_option('siteurl'); 
                    $settings = get_option('Unify_ProductAd_Manager_settings'); 

 
                        $universal_ck = get_option( 'universal_view' );
                        $ck = $universal_ck['ck'];
                        $cs = $universal_ck['cs'];
                        $universal_ck['host'] = $url;
                    $table_name = array( $wpdb->prefix."unify_mobile_banner",  $wpdb->prefix."unify_mobile_banner_meta");  
                    $result = $wpdb->get_results ( "SELECT * FROM $table_name[0] WHERE country='$country';" );    
                    
                    if(!empty($result)) 
                    {
                        $dbanners = array_filter(explode(",", $result[0]->image_url));
                        $dproducts = array_filter(explode(",", $result[0]->products));
                        $dcoupons = unserialize($result[0]->coupons);
                        $dmaintitles = unserialize($result[0]->main_title);
                        // $product = wc_get_product( $dproducts[0] );

                        
                        
                        for ($b=0; $b < count($dbanners); $b++) { 
                            $banners[$b] = $dbanners[$b];
                        }

                        for ($c=0; $c < count($dcoupons); $c++) { 
                        $rcoupons = $wpdb->get_results( "SELECT post_title AS coupon FROM {$wpdb->prefix}posts WHERE post_type = 'shop_coupon' AND post_status='publish' AND post_name='$dcoupons[$c]';" );
                            $coupons[$c] = array(
                                            'coupon'=>$rcoupons[0]->coupon, 
                                            'main_title'=> $dmaintitles[$c] );
                        }

                 

                    for ($p = 0; $p < count($dproducts); $p++) { 
                        $product_data = array();
                        $context = 'view';
                        $producx = wc_get_product($dproducts[$p]);

                        $products[] = prepareDataJson($producx);

                         
                    }
                        $categoriesx =  get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] );
                        foreach($categoriesx as $cat){
                            $categories[] = prepare_item_for_response($cat);
                        }

                        $args = array(
                            'status' => 'publish', // Get only published products
                            'orderby' => 'popularity', // Order by popularity
                            'order' => 'desc', // Descending order
                        );
                        
                        $bestsellers = wc_get_products($args);
                        $bestProduct = array();

                            foreach ($bestsellers as $product) {
                                $bestProduct[] = prepareDataJson($product); // Include all product data
                            }

                        
                        
                    
                        $adata['banners'] = $banners;
                        $adata['offers'] = $coupons;
                        $adata['settings'] = $settings;
                        $adata['products'] = $products;
                        $adata['category']=$categories;
                        $adata['bestseller']=$bestProduct;
                        $adata['recommendation']=$bestProduct;
                        
                         
                        echo wp_json_encode($adata);

                         

                    }


                   
                }

                }

        }

         function get_images( $product ) {
            $images         = array();
            $attachment_ids = array();
    
            // Add featured image.
            if ( $product->get_image_id() ) {
                $attachment_ids[] = $product->get_image_id();
            }
    
            // Add gallery images.
            $attachment_ids = array_merge( $attachment_ids, $product->get_gallery_image_ids() );
    
            // Build image data.
            foreach ( $attachment_ids as $attachment_id ) {
                $attachment_post = get_post( $attachment_id );
                if ( is_null( $attachment_post ) ) {
                    continue;
                }
    
                $attachment = wp_get_attachment_image_src( $attachment_id, 'full' );
                if ( ! is_array( $attachment ) ) {
                    continue;
                }
    
                $images[] = array(
                    'id'                => (int) $attachment_id,
                    'date_created'      => wc_rest_prepare_date_response( $attachment_post->post_date, false ),
                    'date_created_gmt'  => wc_rest_prepare_date_response( strtotime( $attachment_post->post_date_gmt ) ),
                    'date_modified'     => wc_rest_prepare_date_response( $attachment_post->post_modified, false ),
                    'date_modified_gmt' => wc_rest_prepare_date_response( strtotime( $attachment_post->post_modified_gmt ) ),
                    'src'               => current( $attachment ),
                    'name'              => get_the_title( $attachment_id ),
                    'alt'               => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ),
                );
            }
    
            return $images;
        }

         function get_attributes( $product ) {
            $attributes = array();
    
            if ( $product->is_type( 'variation' ) ) {
                $_product = wc_get_product( $product->get_parent_id() );
                foreach ( $product->get_variation_attributes() as $attribute_name => $attribute ) {
                    $name = str_replace( 'attribute_', '', $attribute_name );
    
                    if ( empty( $attribute ) && '0' !== $attribute ) {
                        continue;
                    }
    
                    // Taxonomy-based attributes are prefixed with `pa_`, otherwise simply `attribute_`.
                    if ( 0 === strpos( $attribute_name, 'attribute_pa_' ) ) {
                        $option_term  = get_term_by( 'slug', $attribute, $name );
                        $attributes[] = array(
                            'id'     => wc_attribute_taxonomy_id_by_name( $name ),
                            'name'   => get_attribute_taxonomy_name( $name, $_product ),
                            'option' => $option_term && ! is_wp_error( $option_term ) ? $option_term->name : $attribute,
                        );
                    } else {
                        $attributes[] = array(
                            'id'     => 0,
                            'name'   => get_attribute_taxonomy_name( $name, $_product ),
                            'option' => $attribute,
                        );
                    }
                }
            } else {
                foreach ( $product->get_attributes() as $attribute ) {
                    $attributes[] = array(
                        'id'        => $attribute['is_taxonomy'] ? wc_attribute_taxonomy_id_by_name( $attribute['name'] ) : 0,
                        'name'      => get_attribute_taxonomy_name( $attribute['name'], $product ),
                        'position'  => (int) $attribute['position'],
                        'visible'   => (bool) $attribute['is_visible'],
                        'variation' => (bool) $attribute['is_variation'],
                        'options'   => get_attribute_options( $product->get_id(), $attribute ),
                    );
                }
            }
    
            return $attributes;
        }

         function get_attribute_taxonomy_name( $slug, $product ) {
            // Format slug so it matches attributes of the product.
            $slug       = wc_attribute_taxonomy_slug( $slug );
            $attributes = $product->get_attributes();
            $attribute  = false;
    
            // pa_ attributes.
            if ( isset( $attributes[ wc_attribute_taxonomy_name( $slug ) ] ) ) {
                $attribute = $attributes[ wc_attribute_taxonomy_name( $slug ) ];
            } elseif ( isset( $attributes[ $slug ] ) ) {
                $attribute = $attributes[ $slug ];
            }
    
            if ( ! $attribute ) {
                return $slug;
            }
    
            // Taxonomy attribute name.
            if ( $attribute->is_taxonomy() ) {
                $taxonomy = $attribute->get_taxonomy_object();
                return $taxonomy->attribute_label;
            }
    
            // Custom product attribute name.
            return $attribute->get_name();
        }


         function get_attribute_options( $product_id, $attribute ) {
            if ( isset( $attribute['is_taxonomy'] ) && $attribute['is_taxonomy'] ) {
                return wc_get_product_terms(
                    $product_id,
                    $attribute['name'],
                    array(
                        'fields' => 'names',
                    )
                );
            } elseif ( isset( $attribute['value'] ) ) {
                return array_map( 'trim', explode( '|', $attribute['value'] ) );
            }
    
            return array();
        }

         function get_downloads( $product ) {
            $downloads = array();
    
            if ( $product->is_downloadable() ) {
                foreach ( $product->get_downloads() as $file_id => $file ) {
                    $downloads[] = array(
                        'id'   => $file_id, // MD5 hash.
                        'name' => $file['name'],
                        'file' => $file['file'],
                    );
                }
            }
    
            return $downloads;
        }

         function get_taxonomy_terms( $product, $taxonomy = 'cat' ) {
            $terms = array();
    
            foreach ( wc_get_object_terms( $product->get_id(), 'product_' . $taxonomy ) as $term ) {
                $terms[] = array(
                    'id'   => $term->term_id,
                    'name' => $term->name,
                    'slug' => $term->slug,
                );
            }
    
            return $terms;
        }


         function get_default_attributes( $product ) {
            $default = array();
    
            if ( $product->is_type( 'variable' ) ) {
                foreach ( array_filter( (array) $product->get_default_attributes(), 'strlen' ) as $key => $value ) {
                    if ( 0 === strpos( $key, 'pa_' ) ) {
                        $default[] = array(
                            'id'     => wc_attribute_taxonomy_id_by_name( $key ),
                            'name'   => $this->get_attribute_taxonomy_name( $key, $product ),
                            'option' => $value,
                        );
                    } else {
                        $default[] = array(
                            'id'     => 0,
                            'name'   => $this->get_attribute_taxonomy_name( $key, $product ),
                            'option' => $value,
                        );
                    }
                }
            }
    
            return $default;
        }

      function unify_addons_all($object)
      {
            global $wpdb;     
            $product_id = $object->get_id();
            $utable_groups = $wpdb->prefix."za_groups";
            $utable_products_to_groups = $wpdb->prefix."za_products_to_groups";
            $utable_types = $wpdb->prefix."za_types";
            $utable_values = $wpdb->prefix."za_values";
            $utable_categories_to_groups = $wpdb->prefix."za_categories_to_groups";
            $alldata = [];
            $returnData=[];
            $catdata = [];
            $productdata = [];

            $uresult = $wpdb->get_results ("SELECT g.id AS group_id,t.id AS type_id,v.id AS value_id,pg.product_id,g.title AS group_title,t.title AS type_title,t.type,v.title AS value_title,v.step,v.price,v.sku,cg.category_id,g.apply_to FROM $utable_groups AS g LEFT JOIN $utable_products_to_groups AS pg ON g.id=pg.group_id LEFT JOIN $utable_types AS t ON g.id=t.group_id LEFT JOIN $utable_values AS v ON t.id=v.type_id LEFT JOIN $utable_categories_to_groups AS cg ON g.id=cg.group_id");


            $upids = $wpdb->get_col( "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type IN ('product','product_variation')");

        for ($ui=0; $ui < count($uresult); $ui++) { 
          if ($uresult[$ui]->apply_to=='all') {
            $alldata[] = array( 'group_id'=> $uresult[$ui]->group_id, 'type_id'=> $uresult[$ui]->type_id,  'value_id'=> $uresult[$ui]->value_id, 'group_title'=> $uresult[$ui]->group_title, 'type_title'=> $uresult[$ui]->type_title, 'value_title'=> $uresult[$ui]->value_title, 'price'=> $uresult[$ui]->price, 'sku'=> $uresult[$ui]->sku, 'type'=> $uresult[$ui]->type );
            for ($alli=0; $alli < count($upids); $alli++) { 
                    $returnData[] = $alldata;
            }
            }
                
		}
    return $returnData;
}


function unify_addons_cat($object)
{
      global $wpdb;     
      $product_id = $object->get_id();
      $utable_groups = $wpdb->prefix."za_groups";
      $utable_products_to_groups = $wpdb->prefix."za_products_to_groups";
      $utable_types = $wpdb->prefix."za_types";
      $utable_values = $wpdb->prefix."za_values";
      $utable_categories_to_groups = $wpdb->prefix."za_categories_to_groups";
      $alldata = [];
      $returnData=[];
      $catdata = [];
      $productdata = [];

      $uresult = $wpdb->get_results ("SELECT g.id AS group_id,t.id AS type_id,v.id AS value_id,pg.product_id,g.title AS group_title,t.title AS type_title,t.type,v.title AS value_title,v.step,v.price,v.sku,cg.category_id,g.apply_to FROM $utable_groups AS g LEFT JOIN $utable_products_to_groups AS pg ON g.id=pg.group_id LEFT JOIN $utable_types AS t ON g.id=t.group_id LEFT JOIN $utable_values AS v ON t.id=v.type_id LEFT JOIN $utable_categories_to_groups AS cg ON g.id=cg.group_id");


      $upids = $wpdb->get_col( "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type IN ('product','product_variation')");

  for ($ui=0; $ui < count($uresult); $ui++) { 
    
          if ($uresult[$ui]->apply_to=='custom') {
              if (!empty($uresult[$ui]->category_id)) {
                  $term = get_term_by('id', $uresult[$ui]->category_id, 'product_cat', 'ARRAY_A');
                      $all_ids = get_posts( array(
                      'post_type' => 'product',
                      'numberposts' => -1,
                      'post_status' => 'publish',
                      'fields' => 'ids',
                      'tax_query' => array(
                          array(
                              'taxonomy' => 'product_cat',
                              'field' => 'slug',
                              'terms' => $term['slug'], /*category name*/
                              'operator' => 'IN',
                              )
                          ),
                      ));

                      foreach ( $all_ids as $id ) {
                          if ($id==$product_id) {
                          $catdata[] = array( 'group_id'=> $uresult[$ui]->group_id, 'type_id'=> $uresult[$ui]->type_id,  'value_id'=> $uresult[$ui]->value_id, 'group_title'=> $uresult[$ui]->group_title, 'type_title'=> $uresult[$ui]->type_title, 'value_title'=> $uresult[$ui]->value_title, 'price'=> $uresult[$ui]->price, 'sku'=> $uresult[$ui]->sku, 'type'=> $uresult[$ui]->type );
                          }
                          }
                             

                  }
                         
          }
  }
return $catdata;
}

function unify_addons_product($object)
{
      global $wpdb;     
      $product_id = $object->get_id();
      $utable_groups = $wpdb->prefix."za_groups";
      $utable_products_to_groups = $wpdb->prefix."za_products_to_groups";
      $utable_types = $wpdb->prefix."za_types";
      $utable_values = $wpdb->prefix."za_values";
      $utable_categories_to_groups = $wpdb->prefix."za_categories_to_groups";
      $alldata = [];
      $returnData=[];
      $catdata = [];
      $productdata = [];

      $uresult = $wpdb->get_results ("SELECT g.id AS group_id,t.id AS type_id,v.id AS value_id,pg.product_id,g.title AS group_title,t.title AS type_title,t.type,v.title AS value_title,v.step,v.price,v.sku,cg.category_id,g.apply_to FROM $utable_groups AS g LEFT JOIN $utable_products_to_groups AS pg ON g.id=pg.group_id LEFT JOIN $utable_types AS t ON g.id=t.group_id LEFT JOIN $utable_values AS v ON t.id=v.type_id LEFT JOIN $utable_categories_to_groups AS cg ON g.id=cg.group_id");


      $upids = $wpdb->get_col( "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type IN ('product','product_variation')");

  for ($ui=0; $ui < count($uresult); $ui++) { 
    
          if ($uresult[$ui]->apply_to=='custom') {
              
                          if (!empty($uresult[$ui]->product_id)) {
                              if ($uresult[$ui]->product_id==$product_id) {
                              $productdata[] = array( 'group_id'=> $uresult[$ui]->group_id, 'type_id'=> $uresult[$ui]->type_id,  'value_id'=> $uresult[$ui]->value_id, 'group_title'=> $uresult[$ui]->group_title, 'type_title'=> $uresult[$ui]->type_title, 'value_title'=> $uresult[$ui]->value_title, 'price'=> $uresult[$ui]->price, 'sku'=> $uresult[$ui]->sku, 'type'=> $uresult[$ui]->type );
                            
                          }
                          }
          }
  }
return $productdata;
}

function unify_variations($variationsx) {
    $variations = $variationsx;
    $variations_res = array();
    $variations_array = array();
    if (!empty($variations) && is_array($variations)) {
        foreach ($variations as $variation) {
            $variation_id = $variation;
            $variation = new WC_Product_Variation($variation_id);
            $variations_res['id'] = $variation_id;
            $variations_res['on_sale'] = $variation->is_on_sale();
            $variations_res['regular_price'] = (float)$variation->get_regular_price();
            $variations_res['sale_price'] = (float)$variation->get_sale_price();
            $variations_res['sku'] = $variation->get_sku();
            $variations_res['quantity'] = $variation->get_stock_quantity();
            if ( get_post_meta($variation->get_id(), '_is_pre_order', true ) == 'yes' && strtotime( get_post_meta( $variation->get_id(), '_pre_order_date', true ) ) > time() ) {
            $variations_res['stock_status']="Available";
            $variations_res['available_date']=get_post_meta( $variation->get_id(), '_pre_order_date', true );
        }
        else if ( $variation->is_in_stock() )
        {
            $variations_res['stock_status']="instock";
        }
        else
        {
            $variations_res['stock_status']="outofstock";
        }
        
        
            if ($variations_res['quantity'] == null) {
                $variations_res['quantity'] = '';
            }
            $variations_res['stock'] = $variation->get_stock_quantity();

            $attributes = array();
            $variation_check=array();
            // variation attributes
            foreach ( $variation->get_variation_attributes() as $attribute_name => $attribute ) {
                // taxonomy-based attributes are prefixed with `pa_`, otherwise simply `attribute_`
                $attributes[] = array(
                    'name'   => wc_attribute_label( str_replace( 'attribute_', '', $attribute_name ), $variation ),
                    'slug'   => str_replace( 'attribute_', '', wc_attribute_taxonomy_slug( $attribute_name ) ),
                    'option' => $attribute,
                );
                 $variation_check[]=$attribute;
            }

            $variations_res['attributes'] = $attributes;
             $variations_res['variation_check']=$variation_check;
             $variations_array[] = $variations_res;
            
        }
    }
    
    return $variations_array;
}


function store_time($response) {

    // $purchasable = $response->data['purchasable'];
    if($response == false) {
        global $wpdb;
        $table_name     = $wpdb->prefix . "store_time_table";
        $selectQueryResult = $wpdb->get_results( "SELECT * FROM ". $table_name );
        if(!empty($selectQueryResult)){
            foreach($selectQueryResult as $key){
                $currentDay 	= current_time("l");
                $currentTime 	= current_time("H:i");
                if ( in_array( ($currentDay) ,array_filter(explode (",", $key->day))) ) {
                    // find current day time slot 
                    $currentDayStoreSlot = $wpdb->get_results( "SELECT `open_time`, `close_time` FROM ". $table_name ." WHERE '$currentTime' BETWEEN `open_time` AND `close_time` OR '$currentTime' <= `open_time` AND `active_disable` = '1' ORDER BY `open_time` ASC LIMIT 1", ARRAY_A);

                    if(count($currentDayStoreSlot) > 0){
                        $data = $currentDayStoreSlot;
                        $data['time'] = current_time("H:i:s");
                        break;
                    }
                    else{
                        $data = "No slot found for today!";
                    }

                    
                } 
            }
        }
        else{
            $data = "No slot available";
        }
    } 
    else{
        $data = "Store is open now";
    }

     
    return $data;  
}
//only for best seller
        function prepareDataJson( $producx ) {

            $data    = array(
                'id'                    => $producx->get_id(),
                'name'                  => $producx->get_name(),
                'slug'                  => $producx->get_slug(),
                'date_created'          => wc_rest_prepare_date_response( $producx->get_date_created(), false ),
                'date_created_gmt'      => wc_rest_prepare_date_response( $producx->get_date_created() ),
                'date_modified'         => wc_rest_prepare_date_response( $producx->get_date_modified(), false ),
                'date_modified_gmt'     => wc_rest_prepare_date_response( $producx->get_date_modified() ),
                'description'           => $producx->get_description(),
                'type'                  => $producx->get_type(),
                'featured'              => $producx->is_featured(),
                'catalog_visibility'    => $producx->get_catalog_visibility( $context ),
                'short_description'     => $producx->get_short_description( $context ),
                'total_sales'           => $producx->get_total_sales( $context ),
                'shipping_required'     => $producx->needs_shipping(),
                'shipping_taxable'     => $producx->is_shipping_taxable(),
                'shipping_class'     => $producx->get_shipping_class(),
                'shipping_class_id'     => $producx->get_shipping_class_id( $context ),
                'reviews_allowed'     => $producx->get_reviews_allowed( $context ),
                'average_rating'     => wc_format_decimal( $producx->get_average_rating(), 2 ),
                'rating_count'     => $producx->get_rating_count(),
                'upsell_ids'     => array_map( 'absint', $producx->get_upsell_ids( $context ) ),
                'cross_sell_ids'     => array_map( 'absint', $producx->get_cross_sell_ids( $context ) ),
                'parent_id'     => $producx->get_parent_id( $context ),
                'purchase_note'     => $producx->get_purchase_note( $context ),
                'related_ids'     => array_map( 'absint', array_values( wc_get_related_products( $producx->get_id() ) ) ),
                'has_options'     => $producx->has_options( $context ),
                'store_time'     => store_time($producx->is_purchasable()),
                'unify_variations'              =>unify_variations($producx->is_type( 'variable' )? $producx->get_children():array()),
                'unify_addons_all'     => unify_addons_all($producx),
                'unify_addons_cat'     => unify_addons_cat($producx),
                'unify_addons_product'     => unify_addons_product($producx),
                'permalink'             => $producx->get_permalink(),
                'sku'                   => $producx->get_sku(),
                'price'                 => $producx->get_price(),
                'regular_price'         => $producx->get_regular_price(),
                'sale_price'            => $producx->get_sale_price(),
                'date_on_sale_from'     => wc_rest_prepare_date_response( $producx->get_date_on_sale_from(), false ),
                'date_on_sale_from_gmt' => wc_rest_prepare_date_response( $producx->get_date_on_sale_from() ),
                'date_on_sale_to'       => wc_rest_prepare_date_response( $producx->get_date_on_sale_to(), false ),
                'date_on_sale_to_gmt'   => wc_rest_prepare_date_response( $producx->get_date_on_sale_to() ),
                'on_sale'               => $producx->is_on_sale(),
                'status'                => $producx->get_status(),
                'purchasable'           => $producx->is_purchasable(),
                'virtual'               => $producx->is_virtual(),
                'downloadable'          => $producx->is_downloadable(),
                'downloads'             => get_downloads( $producx ),
                'download_limit'        => '' !== $producx->get_download_limit() ? (int) $producx->get_download_limit() : -1,
                'download_expiry'       => '' !== $producx->get_download_expiry() ? (int) $producx->get_download_expiry() : -1,
                'tax_status'            => $producx->get_tax_status(),
                'tax_class'             => $producx->get_tax_class(),
                'manage_stock'          => $producx->managing_stock(),
                'stock_quantity'        => $producx->get_stock_quantity(),
                'stock_status'          => $producx->get_stock_status(),
                'backorders'            => $producx->get_backorders(),
                'backorders_allowed'    => $producx->backorders_allowed(),
                'backordered'           => $producx->is_on_backorder(),
                'low_stock_amount'      => '' === $producx->get_low_stock_amount() ? null : $producx->get_low_stock_amount(),
                'weight'                => $producx->get_weight(),
                'categories'            => get_taxonomy_terms( $producx ),
                'tags'                  => get_taxonomy_terms( $producx, 'tag' ),
                'variations'            => $producx->is_type( 'variable' )? $producx->get_children():array(),
                'grouped_products'      => $producx->is_type( 'grouped' ) ? $producx->get_children() :array(),   
                'default_attributes'    => get_default_attributes($producx),    
                'dimensions'            => array(
                    'length' => $producx->get_length(),
                    'width'  => $producx->get_width(),
                    'height' => $producx->get_height(),
                ),
                'shipping_class'        => $producx->get_shipping_class(),
                'shipping_class_id'     => $producx->get_shipping_class_id(),
                'images'                 => get_images( $producx ),
                'attributes'            => get_attributes( $producx ),
                'menu_order'            => $producx->get_menu_order(),
                'meta_data'             => $producx->get_meta_data(),
            );
            
    
            return $data;
        }

        function prepare_item_for_response( $item ) {
            // Get category display type.
            $display_type = get_term_meta( $item->term_id, 'display_type', true );
        
            // Get category order.
            $menu_order = get_term_meta( $item->term_id, 'order', true );
        
            $data = array(
                'id'          => (int) $item->term_id,
                'name'        => $item->name,
                'slug'        => $item->slug,
                'parent'      => (int) $item->parent,
                'description' => $item->description,
                'display'     => $display_type ? $display_type : 'default',
                'image'       => null,
                'menu_order'  => (int) $menu_order,
                'count'       => (int) $item->count,
            );
        
            // Get category image.
            $image_id = get_term_meta( $item->term_id, 'thumbnail_id', true );
            if ( $image_id ) {
                $attachment = get_post( $image_id );
        
                $data['image'] = array(
                    'id'            => (int) $image_id,
                    'date_created'  => wc_rest_prepare_date_response( $attachment->post_date_gmt ),
                    'date_modified' => wc_rest_prepare_date_response( $attachment->post_modified_gmt ),
                    'src'           => wp_get_attachment_url( $image_id ),
                    'title'         => get_the_title( $attachment ),
                    'alt'           => get_post_meta( $image_id, '_wp_attachment_image_alt', true ),
                );
            }
        
            return $data;
        
            
        }

    




function remove_core_updates(){
global $wp_version;
return (object) array(
'last_checked' => time(),
'version_checked' => $wp_version,
'updates' => array()
);
}
add_filter('pre_site_transient_update_core', 'remove_core_updates');
add_filter('pre_site_transient_update_plugins', 'remove_core_updates');
add_filter('pre_site_transient_update_themes', 'remove_core_updates');
{
    "editor.fontFamily": "Fira Code",
    "editor.fontLigatures": true,
    "window.zoomLevel": 1,
    "git.openRepositoryInParentFolders": "never",
    "security.workspace.trust.untrustedFiles": "open",
    "workbench.iconTheme": "material-icon-theme",
    "prettier.bracketSameLine": true,
    "settingsSync.ignoredExtensions": [
        "ms-ceintl.vscode-language-pack-es"
    ],
    "application.shellEnvironmentResolutionTimeout": 25,
    "workbench.colorTheme": "Night Owl",
    "launch": {
        "configurations": [
            

        ]
    }
}
Html:
Nota;para colocar el codigo Html solamente tipea !.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="app">
    {{mensaje}}
    <hr>
    <input type="button" @click="mostrar=!mostrar" value="Click">
    <input v-if="mostrar" v-model="mensaje2">
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>

JavaScript:
const app = new Vue ({
el:"#app",
  data: {
    mensaje:"Aja",
    mensaje2:"Hola Bomboncito",
    mostrar:false
  }
})
Salida:
add_action( 'woocommerce_product_options_pricing', 'genius_set_percentage_discount' );
 
function genius_set_percentage_discount() {
   global $product_object;
   woocommerce_wp_select(
      array(
         'id' => '_pc_discount',
         'value' => get_post_meta( $product_object->get_id(), '_pc_discount', true ),
         'label' => 'Discount %',
         'options' => array(
            '0' => '0',
            '10' => '10',
            '25' => '25',
            '50' => '50',
         ),
      )
   );
}
 
add_action( 'save_post_product', 'genius_save_percentage_discount' );
   
function genius_save_percentage_discount( $product_id ) {
    global $typenow;
    if ( 'product' === $typenow ) {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
      if ( isset( $_POST['_pc_discount'] ) ) {
            update_post_meta( $product_id, '_pc_discount', $_POST['_pc_discount'] );
        }
    }
}
  
add_filter( 'woocommerce_get_price_html', 'genius_alter_price_display', 9999, 2 );
  
function genius_alter_price_display( $price_html, $product ) {
    if ( is_admin() ) return $price_html;
    if ( '' === $product->get_price() ) return $price_html;
    if ( get_post_meta( $product->get_id(), '_pc_discount', true ) && get_post_meta( $product->get_id(), '_pc_discount', true ) > 0 ) {
        $orig_price = wc_get_price_to_display( $product );
        $price_html = wc_format_sale_price( $orig_price, $orig_price * ( 100 - get_post_meta( $product->get_id(), '_pc_discount', true ) ) / 100 );
    }
    return $price_html;
}
  
add_action( 'woocommerce_before_calculate_totals', 'genius_alter_price_cart', 9999 );
  
function genius_alter_price_cart( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
      if ( get_post_meta( $product->get_id(), '_pc_discount', true ) && get_post_meta( $product->get_id(), '_pc_discount', true ) > 0 ) {
           $price = $product->get_price();
           $cart_item['data']->set_price( $price * ( 100 - get_post_meta( $product->get_id(), '_pc_discount', true ) ) / 100 );
      }
    }
}
<?php include 'FILENAME';?>
<?php Pjax::begin(); 
    $gridColumns = [
[
                'attribute' => 'avance',
                'headerOptions' => ['style' => 'text-align:center; '],
                'contentOptions' => ['style' => 'text-align:center; vertical-align:middle;'],
                'format' => 'raw',
                'value' => function($model) {
                    $string = $model->observacion;
                    $wrappedString = wordwrap($string, 40, "\n");
                    return '<div style="max-height: 80px; overflow: auto; max-width: 200px;">' . nl2br($wrappedString) . '</div>';
                },
                
            ],
            [
                'attribute' => 'observacion',
                'headerOptions' => ['style' => 'text-align:center; '],
                'contentOptions' => ['style' => 'text-align:center; vertical-align:middle;'],
                'format' => 'raw',
                'value' => function($model) {
                    $string = $model->observacion;
                    $wrappedString = wordwrap($string, 40, "\n");
                    return '<div style="max-height: 80px; overflow: auto; max-width: 200px;">' . nl2br($wrappedString) . '</div>';
                },
            ],
]; ?>
    Route::get('/notification', function () {
        $documentManagerFiles = DocumentManagerFile::where('ocr_project_id', 1)->where('revision', '>', 0 )->take(5)->get();
        // dd($documentManagerFiles);
        return (new DocumentManagerFileCreatedNotification($documentManagerFiles))
                    ->toMail(Auth::user());
    });
response = zoho.people.getRecords("P_Department");
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email sent using PHP's mail() function.";
$headers = "From: sender@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Email sending failed.";
}
    <?php
    $file_data = "Stuff you want to add\n";
    $file_data .= file_get_contents('database.txt');
    file_put_contents('database.txt', $file_data);
    ?>
$fp_source = fopen('database.txt', 'r');
$fp_dest = fopen('database_temp.txt', 'w'); // better to generate a real temp filename
fwrite($fp_dest, 'new content');
while (!feof($fp_source)) {
    $contents .= fread($fp_source, 8192);
    fwrite($fp_dest, $contents);
}
fclose($fp_source);
fclose($fp_dest);
unlink('database.txt');
rename('database_temp.txt','database.txt');
<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
error_reporting(0);
date_default_timezone_set('Asia/Kolkata');
function get($url)
{
  // Initialize a CURL session.
  $ch = curl_init();

  // Return Page contents.
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  //grab URL and pass it to the variable.
  curl_setopt($ch, CURLOPT_URL, $url);

  $result = curl_exec($ch);

  return $result;
}

$user = $_POST['user'];
$offer = $_POST['offer'];
$cname = $_POST['cname'];
$event = $_POST['event'];

$rp = get('https://nextpower.cashinmedia.in/api/v1/checkRefer/0a51d09c-f329-4436-89d5-bdbb52bea07c/' . $offer . '?number=' . $user . '');

// JSON response from the URL
$response = $rp;

// Decode the JSON response
$response_data = json_decode($response, true);

$totalClicks = $response_data['clicks'];

$count = $response_data['count'];

// Extract the 'data' section from the response
$data = $response_data['data'];

// Check if there's any data to display
if (count($data) > 0) {
  // Echo the table header
//     echo '<table border="1">
//         <tr>
//             <th>Click</th>
//             <th>User Amount</th>
//             <th>Refer Amount</th>
//             <th>User</th>
//             <th>Refer</th>
//             <th>Event</th>
//             <th>Status</th>
//             <th>Payment Status</th>
//             <th>Payment Message</th>
//             <th>Created At</th>
//         </tr>';

  //     // Loop through each data entry and display in table rows
//     foreach ($data as $entry) {
//     $userEncoded = preg_replace('/\d{5}(?=\d{4}$)/', 'xxxxx', $entry['user']);

  //     echo '<tr>';
//     echo '<td>' . $entry['click'] . '</td>';
//     echo '<td>' . $entry['userAmount'] . '</td>';
//     echo '<td>' . $entry['referAmount'] . '</td>';
//     echo '<td>' . $userEncoded . '</td>'; // Display encoded user
//     echo '<td>' . $entry['refer'] . '</td>';
//     echo '<td>' . $entry['event'] . '</td>';
//     echo '<td>' . $entry['status'] . '</td>';
//     echo '<td>' . $entry['referPaymentStatus'] . '</td>';
//     echo '<td>' . $entry['payMessage'] . '</td>';
//     echo '<td>' . $entry['createdAt'] . '</td>';
//     echo '</tr>';
// }

  //     // Close the table
//     echo '</table>';
// } else {
//     // If there's no data, show a JavaScript alert
//     echo '<script>alert("No data found.");</script>';
// }
  ?>
  <html lang="en" dir="ltr">


  <head>
    <meta charset="utf-8">
    <title>FokatCash</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap">
    <link rel="stylesheet" href="report.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
    <meta name="viewport" content="width=device-width">
  </head>
  <style>
    .data-table td,
    .data-table th {
      font-size: 17px;
      /* Adjust the value as needed */
    }

    .credited {
      color: #FFA500;
      /* Orange color */
    }
  </style>

  <body>
    <center>
      <div class="login-form">
        <h1>
          <font color='#0f0f0f'>REPORT
        </h1>
        <center>

  </body>

  </html>

  <div class="statics">
    <center><br>
      <fieldset>Refferer:
        <?php echo $user; ?>
        <hr>Camp:
        <?php echo $cname; ?>
        <hr>Total Clicks:
        <?php echo $totalClicks; ?>
        <hr>Total Conversions: <span id="totalLeads">Calculating...</span> <!-- Placeholder for total leads -->
        <hr>
        <font color="#008000"> Cashback Sent: Rs. <span id="totalAcceptedReferAmount">Calculating...</span> </font>
        <!-- Placeholder for total refer amount -->
        <hr>
        <font color="#FFA500">Pending Cashback : Rs.<span id="totalPendingReferAmount">Calculating...</span></font>
        <hr>
      </fieldset><br><br>
      <table class="data-table">
        <tr>

          <th>Camp Name</th>
          <th>Refer Amount</th>
          <!--<th>Refer Status</th>-->
          <th>Cashback Status</th>
          <th>Time</th>
        </tr>
        <?php
        foreach ($data as $entry) {
          $userEncoded = preg_replace('/\d{5}(?=\d{4}$)/', 'xxxxx', $entry['user']);
          $dateTime = new DateTime($entry['createdAt']);

          // Convert to IST timezone
          $dateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));

          // Format the time in desired format
          $istTimeFormatted = $dateTime->format('Y-m-d H:i:s');

          if ($entry['referPaymentStatus'] === 'REJECTED' || $entry['referPaymentStatus'] === 'BLOCKED') {
            continue;
          }

          if ($entry['referPaymentStatus'] == 'ACCEPTED' || $entry['referPaymentStatus'] == 'UNKNOWN' || $entry['referPaymentStatus'] == 'FAILURE') {
            $cashbackStatus = '<b><span style="color: #198754;">Credited</span></b>';
          } elseif ($entry['referPaymentStatus'] == 'PENDING') {
            $cashbackStatus = '<b><span style="color: #FFA500;">Processing</span></b>';
          } else {
            // Handle other cases or set a default value for $cashbackStatus
            // For example: $cashbackStatus = 'Unknown Status';
            $cashbackStatus = $entry['referPaymentStatus'];
          }


          if ($entry['referAmount'] > 0) {
            echo '<tr>';
            // echo '<td>' . $entry['click'] . '</td>';
            // echo '<td>' . $entry['userAmount'] . '</td>';
            echo '<td>' . $cname . '</td>';
            echo '<td>' . $entry['referAmount'] . '</td>';
            // echo '<td>' . $userEncoded . '</td>'; // Display encoded user
            // echo '<td>' . $entry['refer'] . '</td>';
            // echo '<td>' . $entry['event'] . '</td>';
            // echo '<td>' . $entry['status'] . '</td>';
            echo '<td>' . $cashbackStatus . '</td>';
            // echo '<td>' . $entry['payMessage'] . '</td>';
            echo '<td>' . $istTimeFormatted . '</td>';
            echo '</tr>';
          }
        }
        // Close the table
        echo '</table>';
} else {
  // If there's no data, show a JavaScript alert
  ?>
        <html lang="en" dir="ltr">


        <head>
          <meta charset="utf-8">
          <title>FokatCash</title>
          <link rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap">
          <link rel="stylesheet" href="report.css">
          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
          <meta name="viewport" content="width=device-width">
        </head>
        <style>
          .data-table td,
          .data-table th {
            font-size: 17px;
            /* Adjust the value as needed */
          }

          .credited {
            color: #FFA500;
            /* Orange color */
          }
        </style>

        <body>
          <center>
            <div class="login-form">
              <h1>
                <font color='#0f0f0f'>REPORT
              </h1>
              <center>

        </body>

        </html>

        <div class="statics">
          <center><br>
            <fieldset>Refferer:
              <?php echo $user; ?>
              <hr>Camp:
              <?php echo $cname; ?>
              <hr>Total Clicks:
              <?php echo $totalClicks; ?>
              <hr>Total Conversions: <span id="totalLeads">Calculating...</span> <!-- Placeholder for total leads -->
              <hr>
              <font color="#008000"> Cashback Sent: Rs. <span id="totalAcceptedReferAmount">Calculating...</span> </font>
              <!-- Placeholder for total refer amount -->
              <hr>
              <font color="#FFA500">Pending Cashback : Rs.<span id="totalPendingReferAmount">Calculating...</span></font>
              <hr>
            </fieldset><br><br>

            <h5>No data Found</h5>
            <?php


}
?>
    </table>
    <!-- ... Your existing code ... -->
    <script>
  // JavaScript to calculate and display the total leads count and total refer amounts
  document.addEventListener("DOMContentLoaded", function () {
    // Calculate the total leads count and total refer amounts based on the payment statuses and refer amount conditions
    var totalLeads = 0;
    var totalAcceptedReferAmount = 0;
    var totalPendingReferAmount = 0;
    var totalFailedReferAmount = 0;
    var totalUnknownReferAmount = 0;
    var event = "<?php echo $event; ?>";

    <?php foreach ($data as $entry): ?>
      <?php if ($entry['referPaymentStatus'] !== 'REJECTED' && $entry['referPaymentStatus'] !== 'BLOCKED' && $entry['referAmount'] > 0): ?>
        totalLeads++;
        <?php if ($entry['referPaymentStatus'] === 'ACCEPTED'): ?>
          totalAcceptedReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'PENDING'): ?>
          totalPendingReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'FAILURE'): ?>
          totalFailedReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'UNKNOWN'): ?>
          totalUnknownReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php endif; ?>
      <?php endif; ?>
    <?php endforeach; ?>

    // Update the HTML content to display the calculated totals
    var totalLeadsElement = document.getElementById("totalLeads");
    totalLeadsElement.textContent = totalLeads;

    var totalAcceptedReferAmountElement = document.getElementById("totalAcceptedReferAmount");
    totalAcceptedReferAmountElement.textContent = totalAcceptedReferAmount.toFixed(2);

    var totalPendingReferAmountElement = document.getElementById("totalPendingReferAmount");
    totalPendingReferAmountElement.textContent = totalPendingReferAmount.toFixed(2);

    var totalFailedReferAmountElement = document.getElementById("totalFailedReferAmount");
    totalFailedReferAmountElement.textContent = totalFailedReferAmount.toFixed(2);

    var totalUnknownReferAmountElement = document.getElementById("totalUnknownReferAmount");
    totalUnknownReferAmountElement.textContent = totalUnknownReferAmount.toFixed(2);
  });
</script>



    <br><br><br>
    <footer id="footer">
      <div class="copyright">
        &copy; Copyright <strong><span>FokatCash</span></strong>
      </div>
    </footer><!-- End Footer -->
</div><!-- End statics div -->
</center><!-- End center div -->
</body><!-- End body tag -->

</html><!-- End HTML document -->
/**
 * Add activity ratio.
 */
function add_activity_ratio() {
  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $schema_repository */
  $schema_repository = \Drupal::service('entity.last_installed_schema.repository');
  /** @var Drupal\Core\Entity\EntityTypeBundleInfo $entity_bundle_info */
  $entity_bundle_info = \Drupal::service('entity_type.bundle.info');
  /** @var Drupal\Core\Entity\EntityFieldManager $entity_field_manager */
  $entity_field_manager = \Drupal::service('entity_field.manager');
  $definitions = \Drupal::entityTypeManager()->getDefinitions();
  $entities = [];
  foreach ($definitions as $entity_type_id => $definition) {
    if (!$definition instanceof ConfigEntityType) {
      $entities[] = $entity_type_id;
    }
  }
  $spec = [
    'type' => 'numeric',
    'unsigned' => TRUE,
    'precision' => 5,
    'scale' => 2,
  ];
  $database = \Drupal::database();
  $schema = $database->schema();
  foreach ($entities as $entity_type_id) {
    $bundles = $entity_bundle_info->getBundleInfo($entity_type_id);
    foreach ($bundles as $bundle_id => $bundle) {
      $field_definitions = $entity_field_manager->getFieldDefinitions($entity_type_id, $bundle_id);
      foreach ($field_definitions as $field_definition) {
        if ($field_definition->getType() === 'pos_nace_field_type') {
          /** @var Drupal\field\Entity\FieldStorageConfig $storage */
          $storage = $field_definition->getFieldStorageDefinition();
          $storage->setSetting('activity_ratio', FALSE);
          $key_value = \Drupal::keyValue('entity.storage_schema.sql');
          $key_name = $entity_type_id . '.field_schema_data.' . $field_definition->getName();
          $storage_schema = $key_value->get($key_name);
          if ($storage instanceof FieldStorageConfig || $storage->isMultiple()) {
            foreach ([
              $entity_type_id . '__' . $field_definition->getName(),
              $entity_type_id . '_revision' . '__' . $field_definition->getName(),
            ] as $table) {
              $field_name = $field_definition->getName();
              if ($schema->tableExists($table) && !$schema->fieldExists($table, $field_name . '_activity_ratio')) {
                $schema->addField($table, $field_name . '_activity_ratio', $spec);
              }
            }
          }
          else {
            $table = $entity_type_id . '_field_data';
            $field_name = $field_definition->getName();
            if ($schema->tableExists($table) && !$schema->fieldExists($table, $field_name . '__activity_ratio')) {
              $schema->changeField($table, $field_name, $field_name . '__value', [
                'type' => 'varchar',
                'length' => 255,
                'binary' => FALSE,
              ]);
              $schema->addField($table, $field_name . '__activity_ratio', $spec);
              $storage_schema[$table]['fields'][$field_name . '__value'] = [
                'type' => 'varchar',
                'length' => 255,
                'binary' => FALSE,
              ];
              if (isset($storage_schema[$table]['fields'][$field_name])) {
                unset($storage_schema[$table]['fields'][$field_name]);
              }
              $storage_schema[$table]['fields'][$field_name . '__activity_ratio'] = $spec;
            }
          }
          $schema_repository->setLastInstalledFieldStorageDefinition($storage);
          $key_value->set($key_name, $storage_schema);
        }
      }
    }
  }
}
<?php
$month = date('m');
$year = date('Y');

// Get the first day of the month
$firstDayOfMonth = mktime(0, 0, 0, $month, 1, $year);

// Number of days in the month
$numberDays = date('t', $firstDayOfMonth);

// Get the name of the month
$monthName = date('F', $firstDayOfMonth);

// Get the day of the week for the first day of the month
$dayOfWeek = date('D', $firstDayOfMonth);

// Create a table to organize the calendar
echo "<h1>$monthName $year</h1>";
echo "<table>";
echo "<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr><tr>";

// Pad the calendar with empty cells if the month doesn't start on a Sunday
if($dayOfWeek != 'Sun') {
  $blankDaysBefore = date('w', $firstDayOfMonth);
  for($i = 0; $i < $blankDaysBefore; $i++) {
    echo "<td></td>";
  }
}

// Fill in the rest of the calendar with the days of the month
for($dayCounter = 1; $dayCounter <= $numberDays; $dayCounter++) {
  $currentDay = mktime(0, 0, 0, $month, $dayCounter, $year);
  if(date('w', $currentDay) == 0) {
    echo "</tr><tr>";
  }
  echo "<td>$dayCounter</td>";
}

echo "</tr></table>";
?>
 $j==10<?php
for($i=1;$i<=10;$i++) {
    for($j=1;$j<=10;$j++) {
        if(($i==1 && $j>5) || ($i==10 && $j<=5) || ($j==1 && $i<=5) || ( $j==10 &&  $i>5) || ($j==5) || ($i==5) ) {
            echo "*  ";
        } else {
            echo "   ";
        }
    }
    echo "\n";
}
?>
********************************front-page.php********************************
<div class="popular-products">
    <?php echo do_shortcode('[products limit="4" orderby="popularity"]'); ?>
</div>

********************************function.php********************************
// Customize the classes inside the <ul> element for the products list.
function custom_woocommerce_product_loop_start($loop_output) {
    // Add custom classes to the <ul> element.
    $loop_output = str_replace('products', 'products custom-ul-class', $loop_output);
    return $loop_output;
}
add_filter('woocommerce_product_loop_start', 'custom_woocommerce_product_loop_start', 10, 1);
********************************style.css********************************

/* Custom styles for the popular products list */
ul.products.custom-ul-class {
    /* Add your custom styles here */
}

/**
 * Custom Fonts
 */

 function enqueue_custom_fonts() {
if(!is_admin()) {
wp_register_style('source_sans_pro','https://fonts.googleapis.com/css2?family=Indie+Flower&family=Montserrat:wght@900&family=Roboto:ital,wght@0,400;0,700;1,300;1,400&display=swap' );
wp_register_style('nunito','https://fonts.googleapis.com/css2?family=Nunito:ital,wght@0,400;0,700;1,400;1,700&display=swap' );
wp_enqueue_style('source_sans_pro' );
wp_enqueue_style('nunito' );
};
};

add_action('wp_enqueue_scripts','enqueue_custom_fonts');
// [current_user_display_name]
function display_current_user_display_name () {
    $user = wp_get_current_user();
    $display_name = $user->display_name;
    return $user->display_name;
}
add_shortcode('current_user_display_name', 'display_current_user_display_name');
#!/bin/bash

# Crea la base de datos
createdb 'nombre_de_tu_base_de_datos'

# Conecta a la base de datos
psql 'nombre_de_tu_base_de_datos' << EOF

# Crea la tabla
CREATE TABLE 'nombre_de_tu_tabla' (
  'nombre_de_tu_columna_1' tipo_de_dato_1,
  'nombre_de_tu_columna_2' tipo_de_dato_2,
  'nombre_de_tu_columna_3' tipo_de_dato_3,
  ...
);

# Sal del cliente de PostgreSQL
\q

EOF
#!/bin/bash

# Crea la base de datos
createdb 'nombre_de_tu_base_de_datos'

# Conecta a la base de datos
psql 'nombre_de_tu_base_de_datos' << EOF

# Crea la tabla
CREATE TABLE 'nombre_de_tu_tabla' (
  'nombre_de_tu_columna_1' tipo_de_dato_1,
  'nombre_de_tu_columna_2' tipo_de_dato_2,
  'nombre_de_tu_columna_3' tipo_de_dato_3,
  ...
);

# Sal del cliente de PostgreSQL
\q

EOF
//INDEX.PHP
<?php session_start();
//when login button pushed
if (isset($_POST['login'])){
//    if username and password not empty
    if (!empty($_POST['username']) && !empty($_POST['password'])){
//        store
        $_SESSION['username']  = $_POST["username"];
        $_SESSION['password']  = $_POST["password"];
//    take you to home.php
        header("Location: home.php");
    }else{
        echo "Missing username or password";
    }
}

?>
  
  
  
  
  //HOME.PHP
  <?php
session_start();
//if logout pressed
if (isset($_POST['logout'])){
//    destroys session
    session_destroy();
//    rerouts you to index
    header("Location: index.php");
}
echo $_SESSION['username'] . "<br>";
echo $_SESSION['password'] . "<br>";;



?>
<?php

setcookie("fav_food","pizza", time() + (86400 * 2), "/");
setcookie("fav_drink","water", time() + (86400 * 3), "/");
setcookie("fav_dessert","cookies", time() + (86400 * 4), "/");

foreach ($_COOKIE as $key => $value){
    echo "{$key} = {$value} <br>";
}


if (isset($_COOKIE['fav_food'])){
    echo "BUY SOME {$_COOKIE['fav_food']}";
}else{
    echo "I dont know ypu fav food";
}
<?php
    if (isset($_POST['submit'])){
        $username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_SPECIAL_CHARS);
        echo "Hello {$username}";
    }
?>

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <form action="index.php" method="post">
        <input type="text" name="username" id="username">
        <input type="submit" name="submit">
    </form>

</body>

</html>
<?php
$result = null;
if(isset($_POST['submit'])) {

   $foods = $_POST['foods'];

   foreach ($foods as $food){
       echo "You like {$food} <br>";
   }
}

?>



<form action="index.php" method="post">
    <input type="checkbox" name="foods[]" value="pizza"> pizza <br>
    <input type="checkbox" name="foods[]" value="hamburger">Hamburger <br>
    <input type="checkbox" name="foods[]" value="hotdog"> hotdog <br>
    <input type="checkbox" name="foods[]" value="taco"> taco <br>

    <input type="submit" value="Submit" name="submit">
</form>
sudo apt-get clean all
sudo rm -rf /var/lib/apt/lists/*
sudo apt-get update --fix-missing
sudo apt-get upgrade

instalar dependencias faltantes 
sudo apt -f install
 $taxonomy = 'product_cat'; 
   $primary_cat_id=get_post_meta($product->id,'_yoast_wpseo_primary_' . $taxonomy, true);
    if($primary_cat_id){
       $primary_cat = get_term($primary_cat_id, $taxonomy);
       if(isset($primary_cat->name)) 
           echo $primary_cat->name;
    }
/wp-admin/admin-ajax.php?action=function_name
<?php
// Enter your code here, enjoy!
// function calculateDistance($lat1, $lon1, $lat2, $lon2) {
//     // approximate radius of Earth in km
//     $R = 6371.0;

//     // convert degrees to radians
//     $lat1 = deg2rad($lat1);
//     $lon1 = deg2rad($lon1);
//     $lat2 = deg2rad($lat2);
//     $lon2 = deg2rad($lon2);

//     // calculate the differences in latitude and longitude
//     $dlat = $lat2 - $lat1;
//     $dlon = $lon2 - $lon1;

//     // apply the Haversine formula
//     $a = sin($dlat / 2) ** 2 + cos($lat1) * cos($lat2) * sin($dlon / 2) ** 2;
//     $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

//     // calculate the distance
//     $distance = $R * $c;

//     return $distance;
// }

// // Array of coordinates
// $coordinates = array(
//     array(-14.537804, 40.672439, "NA1"),  // NA1
//     array(-14.532698, 40.674953, "NA2"),  // NA2
//     array(-14.529319, 40.675874, "NA3"),  // NA3
//     array(-14.523059, 40.675931, "NA4"),  // NA4
//     array(-14.459071, 40.674796, "NB5"),  // NB5
//     array(-14.460408, 40.678548, "NB6"),  // NB6
//     array(-14.461540, 40.680757, "NB7")   // NB7
// );

// // Calculate distances between points
// $pointCount = count($coordinates);
// for ($i = 0; $i < $pointCount - 1; $i++) {
//     $coord1 = $coordinates[$i];
//     $coord2 = $coordinates[$i + 1];
    
//     $j = $i + 1;

//     $lat1 = $coord1[0];
//     $lon1 = $coord1[1];
//     $lat2 = $coord2[0];
//     $lon2 = $coord2[1];

//     $distance = calculateDistance($lat1, $lon1, $lat2, $lon2);
//     echo "Distance between point {$coord1[2]} and point {$coord2[2]}: {$distance} km\n";
// }


function calculateDistance($lat1, $lon1, $lat2, $lon2) {
    // approximate radius of Earth in km
    $R = 6371.0;

    // convert degrees to radians
    $lat1 = deg2rad($lat1);
    $lon1 = deg2rad($lon1);
    $lat2 = deg2rad($lat2);
    $lon2 = deg2rad($lon2);

    // calculate the differences in latitude and longitude
    $dlat = $lat2 - $lat1;
    $dlon = $lon2 - $lon1;

    // apply the Haversine formula
    $a = sin($dlat / 2) ** 2 + cos($lat1) * cos($lat2) * sin($dlon / 2) ** 2;
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

    // calculate the distance
    $distance = $R * $c;

    return $distance;
}

// Array of coordinates
$coordinates = array(
    array(-14.537804, 40.672439, 'NA1'),
    array(-14.532698, 40.674953, 'NA2'),
    array(-14.529319, 40.675874, 'NA3'),
    array(-14.523059, 40.675931, 'NA4'),
    array(-14.459071, 40.674796, 'NB5'),
    array(-14.460408, 40.678548, 'NB6'),
    array(-14.461540, 40.680757, 'NB7')
);

// Calculate distances between each point
$pointCount = count($coordinates);
for ($i = 0; $i < $pointCount - 1; $i++) {
    $coord1 = $coordinates[$i];
    $lat1 = $coord1[0];
    $lon1 = $coord1[1];

    for ($j = $i + 1; $j < $pointCount; $j++) {
        $coord2 = $coordinates[$j];
        $lat2 = $coord2[0];
        $lon2 = $coord2[1];

        $distance = calculateDistance($lat1, $lon1, $lat2, $lon2);
        echo "Distance between point {$coord1[2]} and point {$coord2[2]}: {$distance} km\n";
    }
}

$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);
 if (!defined('ABSPATH')) exit;

    new My_Cron();

    class My_Cron {

        public function __construct() {
            add_filter('cron_schedules', array($this, 'cron_time_intervals'));
            add_action( 'wp',  array($this, 'cron_scheduler'));
            add_action( 'cast_my_spell', array( $this, 'auto_spell_cast' ) );
        }

        public function cron_time_intervals($schedules)
        {
            $schedules['minutes_10'] = array(
                'interval' => 10 * 60,
                'display' => 'Once 10 minutes'
            );
            return $schedules;
        }

        function cron_scheduler() {
            if ( ! wp_next_scheduled( 'cast_my_spell' ) ) {
                wp_schedule_event( time(), 'minutes_10', 'cast_my_spell');
            }
        }

        function auto_spell_cast(){
            My_Plugin_Class::instance()->launch_spell();
        }
    }
cntrl + shift + t: abrir una ventana del navegador que ya habias cerrado con anterioridad
windows + l: bloquea el ordenador y guarda todo el trabajo
;MainWP Requriement - cURL timeout
default_socket_timeout = 300
;END MainWP Requriement
  // Only from inside the same class
  $this->processSomething([__CLASS__, 'myStaticCallback']);
  // From either inside or outside the same class
  $myObject->processSomething(['\Namespace\MyClass', 'myStaticCallback']);
  $myObject->processSomething(['\Namespace\MyClass::myStaticCallback']); // PHP 5.2.3+
  $myObject->processSomething([MyClass::class, 'myStaticCallback']); // PHP 5.5.0+
get_intermediate_image_sizes(); // get all the image size names.
wp_get_additional_image_sizes(); // get all the additional image size data.
wp_get_registered_image_subsizes(); // get all the image size data.
$post_id = wp_insert_post(array (
   'post_type' => 'your_post_type',
   'post_title' => $your_title,
   'post_content' => $your_content,
   'post_status' => 'publish',
   'comment_status' => 'closed',
   'ping_status' => 'closed',
   'meta_input' => array(
      '_your_custom_1' => $custom_1,
      '_your_custom_2' => $custom_2,
      '_your_custom_3' => $custom_3,
    ),
));
$post_id = wp_insert_post(array (
   'post_type' => 'your_post_type',
   'post_title' => $your_title,
   'post_content' => $your_content,
   'post_status' => 'publish',
   'comment_status' => 'closed',
   'ping_status' => 'closed',
   'meta_input' => array(
      '_your_custom_1' => $custom_1,
      '_your_custom_2' => $custom_2,
      '_your_custom_3' => $custom_3,
    ),
));
$files = scandir('/some/random/folder') ?: [];
$user = $_POST['user'] ?? $_SESSION['user'] ?? $_COOKIE['user'] ?? '';
<?php
    var_dump(5 ?: 0); // 5
    var_dump(false ?: 0); // 0
    var_dump(null ?: 'foo'); // 'foo'
    var_dump(true ?: 123); // true
    var_dump('rock' ?: 'roll'); // 'rock'
?>
   function save_function()
{

    $subject_term = 'subject';
    $my_subject_term = term_exists($subject_term, 'my_custom_taxonomy');   // check if term in website or no
    // Create Term if it doesn't exist
    if (!$my_subject_term) {
        $my_subject_term = wp_insert_term($subject_term, 'my_custom_taxonomy');
    }
    $custom_tax = array(
        'my_custom_taxonomy' => array(
            $my_subject_term['term_taxonomy_id'],
        )
    );

    // MESSAGE FIELDS
    $public_post = array(
        'post_title' => filter_input(INPUT_POST, 'title'),
        'post_author' => 1,
        'post_type' => 'message',
        'post_status' => 'pending',
        'tax_input' => $custom_tax
    );

    $post_id = wp_insert_post($public_post);

    
}
Supongamos que estamos desarrollando una aplicación de gestión de proyectos. Cada proyecto tiene un solo gerente, pero un gerente puede estar a cargo de varios proyectos. Además, cada proyecto puede tener varios miembros del equipo, y cada miembro del equipo puede estar asignado a varios proyectos.

1.-modelo(app/models/Proyecto.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Proyecto extends ActiveRecord
{
    public static function tableName()
    {
        return 'proyectos';
    }

    public function getGerente()
    {
        return $this->hasOne(Gerente::className(), ['id' => 'id_gerente']);
    }

    public function getMiembrosEquipo()
    {
        return $this->hasMany(MiembroEquipo::className(), ['id_proyecto' => 'id']);
    }
}

En este ejemplo, estamos creando un modelo llamado Proyecto que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla proyectos de la base de datos PostgreSQL y tiene una relación de uno a uno con la tabla gerentes y una relación de uno a muchos con la tabla miembros_equipo.

2.-Modelo(app/models/Gerente.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Gerente extends ActiveRecord
{
    public static function tableName()
    {
        return 'gerentes';
    }

    public function getProyectos()
    {
        return $this->hasMany(Proyecto::className(), ['id_gerente' => 'id']);
    }
}

En este ejemplo, estamos creando un modelo llamado Gerente que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla gerentes de la base de datos PostgreSQL y tiene una relación de uno a muchos con la tabla proyectos.


3.-Modelo(app/models/MiembroEquipo.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class MiembroEquipo extends ActiveRecord
{
    public static function tableName()
    {
        return 'miembros_equipo';
    }

    public function getProyecto()
    {
        return $this->hasOne(Proyecto::className(), ['id' => 'id_proyecto']);
    }

    public function getEmpleado()
    {
        return $this->hasOne(Empleado::className(), ['id' => 'id_empleado']);
    }
}

En este ejemplo, estamos creando un modelo llamado MiembroEquipo que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla miembros_equipo de la base de datos PostgreSQL y tiene una relación de uno a uno con la tabla proyectos y una relación de uno a uno con la tabla empleados.


4.-Modelo(app/models/Empleado.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Empleado extends ActiveRecord
{
    public static function tableName()
    {
        return 'empleados';
    }

    public function getMiembrosEquipo()
    {
        return $this->hasMany(MiembroEquipo::className(), ['id_empleado' => 'id']);
    }
}

En este ejemplo, estamos creando un modelo llamado Empleado que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla empleados de la base de datos PostgreSQL y tiene una relación de uno a muchos con la tabla miembros_equipo.

5.-Controlador(app/controllers/ProyectoController.php)

<?php

namespace app\controllers;

use yii\web\Controller;
use app\models\Proyecto;

class ProyectoController extends Controller
{
    public function actionIndex()
    {
        $proyectos = Proyecto::find()->with('gerente', 'miembrosEquipo.empleado')->all();
        return $this->render('index', ['proyectos' => $proyectos]);
 }
}

En este ejemplo, estamos creando un controlador llamado ProyectoController que tiene un método llamado actionIndex que se encarga de obtener todos los proyectos de la base de datos y sus relaciones con gerentes y miembros del equipo utilizando los modelos Proyecto, Gerente, MiembroEquipo y Empleado. Luego, se renderiza la vista index y se le pasa como parámetro los proyectos obtenidos.

6.-Vista(app/views/proyecto/index.php)

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Nombre</th>
            <th>Gerente</th>
            <th>Miembros del equipo</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($proyectos as $proyecto): ?>
            <tr>
                <td><?= $proyecto->id ?></td>
                <td><?= $proyecto->nombre ?></td>
                <td><?= $proyecto->gerente->nombre ?></td>
                <td>
                    <ul>
                        <?php foreach ($proyecto->miembrosEquipo as $miembroEquipo): ?>
                            <li><?= $miembroEquipo->empleado->nombre ?></li>
                        <?php endforeach ?>
                    </ul>
                </td>
            </tr>
        <?php endforeach ?>
    </tbody>
</table>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        // Código de jQuery aquí
    });
</script>

En este ejemplo, estamos creando una vista llamada index que muestra una tabla con los proyectos, sus gerentes y sus miembros del equipo. También estamos incluyendo la librería de jQuery y un bloque de código jQuery vacío que se ejecutará cuando el DOM esté listo.

7.-Codigo Jquery (app/web/js/mi-script.js)

En este ejemplo, estamos utilizando jQuery para hacer una petición AJAX al servidor cuando el usuario hace clic en una fila de la tabla de proyectos. La petición se realiza al controlador ProyectoController y al método actionGet, que se encarga de obtener los detalles del proyecto con el ID especificado y devolverlos en formato JSON.
Recuerda que debes ajustar los nombres de los archivos y las rutas según la estructura de tu aplicación Yii2 y PostgreSQL.
Espero que esto te ayude a entender cómo podrías implementar relaciones de 1 a 1, 0 a 1 y muchos a muchos utilizando Yii2, PostgreSQL, MVC, OOP y jQuery.

8.- código SQL para crear las tablas utilizadas en el ejemplo de la aplicación web que utiliza Yii2, PostgreSQL, MVC, OOP y jQuery para implementar relaciones de 1 a 1, 0 a 1 y muchos a muchos:

Tabla proyectos ()
CREATE TABLE proyectos (
    id SERIAL PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL,
    id_gerente INTEGER REFERENCES gerentes(id)
);

En esta tabla, estamos creando un campo id que es una clave primaria autoincremental, un campo nombre que almacena el nombre del proyecto y un campo id_gerente que es una clave foránea que hace referencia al campo id de la tabla gerentes.

9.-tabla gerentes

CREATE TABLE gerentes (
    id SERIAL PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL
);

En esta tabla, estamos creando un campo id que es una clave primaria autoincremental y un campo nombre que almacena el nombre del gerente.

10.- tabla miembros_equipo

CREATE TABLE miembros_equipo (
    id_proyecto INTEGER REFERENCES proyectos(id),
    id_empleado INTEGER REFERENCES empleados(id),
    PRIMARY KEY (id_proyecto, id_empleado)
);

En esta tabla, estamos creando dos campos id_proyecto e id_empleado que son claves foráneas que hacen referencia a los campos id de las tablas proyectos y empleados, respectivamente. Además, estamos creando una clave primaria compuesta por ambos campos para asegurarnos de que no haya duplicados.

11.-tabla empleados

CREATE TABLE empleados (
    id SERIAL PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL
);

En esta tabla, estamos creando un campo id que es una clave primaria autoincremental y un campo nombre que almacena el nombre del empleado.

Recuerda que debes ajustar los nombres de las tablas y los campos según la estructura de tu aplicación. Además, debes asegurarte de que las claves foráneas estén correctamente definidas y que las relaciones entre las tablas sean coherentes.

posibles consultas que podrías hacer utilizando el código SQL de la aplicación web que utiliza Yii2, PostgreSQL, MVC, OOP y jQuery para implementar relaciones de 1 a1, 0 a 1 y muchos a muchos:

1.-Obtener todos los proyectos con sus gerentes y miembros del equipo:

SELECT p.nombre AS proyecto, g.nombre AS gerente, e.nombre AS empleado
FROM proyectos p
LEFT JOIN gerentes g ON p.id_gerente = g.id
LEFT JOIN miembros_equipo me ON p.id = me.id_proyecto
LEFT JOIN empleados e ON me.id_empleado = e.id;

En esta consulta, estamos obteniendo todos los proyectos con sus gerentes y miembros del equipo utilizando las tablas proyectos, gerentes, miembros_equipo y empleados. Estamos utilizando un LEFT JOIN para asegurarnos de que se incluyan todos los proyectos, incluso aquellos que no tienen gerente o miembros del equipo.


2.-Obtener todos los proyectos que tienen un gerente asignado:

SELECT p.nombre AS proyecto, g.nombre AS gerente
FROM proyectos p
INNER JOIN gerentes g ON p.id_gerente = g.id;

En esta consulta, estamos obteniendo todos los proyectos que tienen un gerente asignado utilizando las tablas proyectos y gerentes. Estamos utilizando un INNER JOIN para asegurarnos de que solo se incluyan los proyectos que tienen un gerente asignado.

3.-Obtener todos los proyectos en los que trabaja un empleado específico:

SELECT p.nombre AS proyecto, e.nombre AS empleado
FROM proyectos p
INNER JOIN miembros_equipo me ON p.id = me.id_proyecto
INNER JOIN empleados e ON me.id_empleado = e.id
WHERE e.nombre = 'Juan';

En esta consulta, estamos obteniendo todos los proyectos en los que trabaja un empleado específico utilizando las tablas proyectos, miembros_equipo y empleados. Estamos utilizando un INNER JOIN para asegurarnos de que solo se incluyan los proyectos en los que trabaja el empleado específico y estamos utilizando una cláusula WHERE para filtrar por el nombre del empleado.

4.-Obtener todos los empleados que trabajan en un proyecto específico:

SELECT e.nombre AS empleado
FROM empleados e
INNER JOIN miembros_equipo me ON e.id = me.id_empleado
INNER JOIN proyectos p ON me.id_proyecto = p.id
WHERE p.nombre = 'Proyecto A';

En esta consulta, estamos obteniendo todos los empleados que trabajan en un proyecto específico utilizando las tablas empleados, miembros_equipo y proyectos. Estamos utilizando un INNER JOIN para asegurarnos de que solo se incluyan los empleados que trabajan en el proyecto específico y estamos utilizando una cláusula WHERE para filtrar por el nombre del proyecto.
Recuerda que debes ajustar las consultas según la estructura de tu aplicación y las relaciones entre las tablas.

{
   error: {
     message: "Unauthorized"
   }
}


If you removed Auth middleware but still getting unauthorized means there may be route cache. Try using php artisan route:clear and check.


<?php

function isSubstring($string, $substring) 
{
    return strpos($string, $substring) !== false;
}

// Usage example:
$mainString = "Hello, World!";
$substring = "World";
if (isSubstring($mainString, $substring)) {
    echo "The substring '$substring' is found in the main string.";
} else {
    echo "The substring '$substring' is not found in the main string.";
}
function custom_add_attribute_thumbnail_field( $term ) {
    $thumbnail_id = get_term_meta( $term->term_id, '_thumbnail_id', true );
    $image_url = wp_get_attachment_image_url( $thumbnail_id, 'thumbnail' ); // Imposta la dimensione dell'immagine desiderata (esempio: 'thumbnail', 'medium', 'large')
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="attribute_thumbnail"><?php esc_html_e( 'Attribute Thumbnail', 'text-domain' ); ?></label></th>
        <td>
            <div id="attribute_thumbnail_preview">
                <?php if ( $image_url ) : ?>
                    <img src="<?php echo esc_url( $image_url ); ?>" alt="<?php echo esc_attr( $term->name ); ?>" style="max-width:100px; max-height:100px;">
                <?php endif; ?>
            </div>
            <input type="hidden" id="attribute_thumbnail" name="attribute_thumbnail" value="<?php echo esc_attr( $thumbnail_id ); ?>">
            <button type="button" id="upload_attribute_thumbnail_button" class="button"><?php esc_html_e( 'Upload/Add image', 'text-domain' ); ?></button>
            <button type="button" id="remove_attribute_thumbnail_button" class="button"><?php esc_html_e( 'Remove image', 'text-domain' ); ?></button>
            <script>
                jQuery(document).ready(function($) {
                    // Carica l'immagine
                    $('#upload_attribute_thumbnail_button').click(function() {
                        var custom_uploader = wp.media({
                            title: '<?php esc_html_e( "Choose or Upload Image", "text-domain" ); ?>',
                            button: {
                                text: '<?php esc_html_e( "Use Image", "text-domain" ); ?>'
                            },
                            multiple: false
                        }).on('select', function() {
                            var attachment = custom_uploader.state().get('selection').first().toJSON();
                            $('#attribute_thumbnail').val(attachment.id);
                            $('#attribute_thumbnail_preview').html('<img src="' + attachment.url + '" alt="<?php echo esc_attr( $term->name ); ?>" style="max-width:100px; max-height:100px;">');
                        }).open();
                    });

                    // Rimuovi l'immagine
                    $('#remove_attribute_thumbnail_button').click(function() {
                        $('#attribute_thumbnail').val('');
                        $('#attribute_thumbnail_preview').html('');
                    });
                });
            </script>
            <p class="description"><?php esc_html_e( 'Upload or select an image to set as the attribute thumbnail.', 'text-domain' ); ?></p>
        </td>
    </tr>
    <?php
}
add_action( 'pa_attributo_add_form_fields', 'custom_add_attribute_thumbnail_field', 10, 2 );
add_action( 'pa_attributo_edit_form_fields', 'custom_add_attribute_thumbnail_field', 10, 2 );

function custom_save_attribute_thumbnail( $term_id ) {
    if ( isset( $_POST['attribute_thumbnail'] ) ) {
        $thumbnail_id = absint( $_POST['attribute_thumbnail'] );
        update_term_meta( $term_id, '_thumbnail_id', $thumbnail_id );
    }
}
add_action( 'edited_pa_attributo', 'custom_save_attribute_thumbnail', 10, 2 );
  <?php
  $taxonomy     = 'product_cat';
  $orderby      = 'menu_order';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 0;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;       
        //echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                // echo  $sub_category->name ;
                 echo '<br /><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                echo '<br /><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
            }   
        }
    }       
}
?>
//Disable Comments

add_action('admin_init', function () {
    // Redirect any user trying to access comments page
    global $pagenow;

    if ($pagenow === 'edit-comments.php') {
        wp_redirect(admin_url());
        exit;
    }

    // Remove comments metabox from dashboard
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');

    // Disable support for comments and trackbacks in post types
    foreach (get_post_types() as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
});

// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);

// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);

// Remove comments page in menu
add_action('admin_menu', function () {
    remove_menu_page('edit-comments.php');
});

// Remove comments links from admin bar
add_action('init', function () {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
});
<a href="#" class="facebook"> </a>
<a href="#" class="instagram"> </a>
<a href="#" class="pinterest"> </a>
<a href="#" class="email"> </a>
<a href="#" class="youtube"> </a>
<a href="#" class="linkedin"> </a>
// Parse the initial value using Carbon
$dateTime = Carbon::parse($dateTimeString);

// Format the date and time as desired
$formattedDateTime = $dateTime->format('d-m-Y h:i:sA');
// Parse the initial value using Carbon
$dateTime = Carbon::parse($dateTimeString);

// Format the date and time as desired
$formattedDateTime = $dateTime->isoFormat('Do MMMM YYYY h:mm:ssa');
<?php
$usernames = ['username1', 'username2', ...]; // An array of the usernames of the users you want to change the role for
$new_role = 'new_role'; // The new role you want to assign to the users

foreach ($usernames as $username) {
    $user = get_user_by('login', $username);
    if (!empty($user)) {
        $user->set_role($new_role);
    }
}
?>
$oOrder = OrderAPI::getByID( $lLabID );
if( $oOrder ) {
	//$sFeld = $oOrder->getValueByMethod( "KURZ" );
	$oOrderRoot = $oOrder->getWorkflowRootOrderV2(  );
	if( $oOrderRoot ) {
}
VariablesClass::alertMsg(
	// Zeigt eine Meldung an
	$objResponse, // XAJAX Antwort, nicht aendern!
	$lModuleID, // ID des aufrufenden Moduls, nicht aendern!
	"Bitte Auftrag speichern!", // Nachricht
	"TITLE", // Titel der Meldung
	ALERT_ERROR, // Typ der  Meldung  (ALERT_DEFAULT, ALERT_OK, ALERT_WARNING, ALERT_ERROR)
	"" // (optional) Beschriftung des Buttons
);
<?php
$user = get_userdatabylogin('YOUR_USERNAME');
grant_super_admin($user->ID);
?>
implode(', ', array_column($array, 'colName'));
$coordinator = [];
$coordinatorFirstPage = Api::schoolTeacher()->index($schoolId, $filter);
$coordinator[] = $coordinatorFirstPage->data();
$lastPage = $coordinatorFirstPage->meta('last_page') ?? 1;

$promCordinators = Http::pool(function (Pool $pool) use ($lastPage, $schoolId, $filter) {
    for ($c = 2; $c <= $lastPage; $c++) {
        $filter['page'] = $c;
        $pool->withToken(Auth::user()->token())
            ->get(Api::schoolTeacher()->index($schoolId, $filter, true), $filter);
    }
});

foreach ($promCordinators as $wraped) {
    $coordinator[] = json_decode($wraped->getBody(), true)['data'] ?? [];
}

$coordinator = collect($coordinator)->flatten(1)->toArray();
dd($coordinator);
\DB::enableQueryLog(); // Enable query log

// Your Eloquent query executed by using get()

dd(\DB::getQueryLog()); // Show results of log
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('login');
    }

    protected function unauthenticated($request, array $guards)
    {
        abort(response()->json(
            [
                'status' => 'false',
                'message' => 'Unauthenticated',
            ], 401));
    }
}
$tournament = app('App\Http\Controllers\TournamentController')->read_tournament_details($request, $tournament_id)->getData(true);
        
echo gmdate("H:i:s", $time_in_seconds);
$name = implode('.', [
    md5_file($file->getPathname()),
    $file->getClientOriginalExtension()
]);
MyTable::whereDate( 'created_at', '<=', now()->subDays(30))->delete();

<?php

    // Get absolute path
    $path = getcwd(); // /home/user/public_html/test/test.php.   

    $path = substr($path, 0, strpos($path, "public_html"));

    $root = $path . "public_html/";

    echo $root; // This will output /home/user/public_html/
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
  if (in_array($file, array(".",".."))) continue;
  // If we copied this successfully, mark it for deletion
  if (copy($source.$file, $destination.$file))
  {
      $delete[] = $source.$file;
  }
}
// Delete all successfully-copied files
foreach ($delete as $file)
{
    unlink($file);
}
// Adds a new sortable "last updated" column to posts and pages backend.
function custom_columns($defaults) {
    $defaults['last_updated'] = __('Last Updated', 'your-textdomain');
    return $defaults;
}
add_filter('manage_posts_columns', 'custom_columns');
add_filter('manage_pages_columns', 'custom_columns');

function custom_columns_content($column_name, $post_id) {
    if ($column_name == 'last_updated') {
        $last_updated = get_the_modified_date();
        echo $last_updated;
    }
}
add_action('manage_posts_custom_column', 'custom_columns_content', 10, 2);
add_action('manage_pages_custom_column', 'custom_columns_content', 10, 2);

function custom_columns_sortable($columns) {
    $columns['last_updated'] = 'last_updated';
    return $columns;
}
add_filter('manage_edit-post_sortable_columns', 'custom_columns_sortable');
add_filter('manage_edit-page_sortable_columns', 'custom_columns_sortable');

function custom_columns_orderby($query) {
    if (!is_admin()) {
        return;
    }

    $orderby = $query->get('orderby');

    if ('last_updated' == $orderby) {
        $query->set('orderby', 'modified');
    }
}
add_action('pre_get_posts', 'custom_columns_orderby');
Go to public folder Just delete/remove the storage link inside public/

Then Run the command


 php artisan storage:link

 
the above command will link storage again
/**
 * @snippet       Variable Product Price Range: "From: min_price"
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_filter( 'woocommerce_variable_price_html', 'bbloomer_variation_price_format_min', 9999, 2 );
 
function bbloomer_variation_price_format_min( $price, $product ) {
   $prices = $product->get_variation_prices( true );
   $min_price = current( $prices['price'] );
   $max_price = end( $prices['price'] );
   $min_reg_price = current( $prices['regular_price'] );
   $max_reg_price = end( $prices['regular_price'] );
   if ( $min_price !== $max_price || ( $product->is_on_sale() && $min_reg_price === $max_reg_price ) ) {
      $price = 'From: ' . wc_price( $min_price ) . $product->get_price_suffix();
   }
   return $price;
}
     $table->id();
            $table->string('model');
            $table->unsignedBigInteger('manufacturer_id');
            $table->foreign('manufacturer_id')->references('id')->on('manufacturers');
            $table->timestamps();
add_action( 'elementor/theme/register_conditions', function( $conditions_manager ) {
class Subcategory_Archive extends \ElementorPro\Modules\ThemeBuilder\Conditions\Taxonomy {
	private $taxonomy;

	public function get_name() {
		return 'child_of_' . $this->taxonomy->name;
	}

	public function get_label() {
		return sprintf( __( 'Direct Child %s Of', 'elementor-pro' ), $this->taxonomy->labels->singular_name );
	}

	public function __construct( $data ) {
		parent::__construct( $data );

		$this->taxonomy = $data['object'];
	}

	public function is_term() {
		$taxonomy = $this->taxonomy->name;
		$current = get_queried_object();
		return ( $current && isset( $current->taxonomy ) && $taxonomy === $current->taxonomy );
	}

	public function check( $args ) {
		$id = (int) $args['id'];
		/**
		 * @var \WP_Term $current
		 */
		$current = get_queried_object();
		if ( ! $this->is_term() || 0 === $current->parent ) {
			return false;
		}

		while ( $current->parent > 0 ) {
			if ( $id === $current->parent ) {
				return true;
			}
			$current = get_term_by( 'id', $current->parent, $current->taxonomy );
		}

		return $id === $current->parent;
	}
}
$taxonomy = get_taxonomy('product_cat');
$conditions_manager->get_condition( 'product_archive' )->register_sub_condition( new Subcategory_Archive([ 'object' => $taxonomy ]) );
}, 100);
$mysqli = mysqli_connect('localhost', 'DATABASE_USERNAME', 'DATABASE_PASSWORD', 'DATABASE_NAME');
<!DOCTYPE html>
<html>
​
<body>
The content of the body element is displayed in your browser.
</body>
​
</html>
​
exec("java -jar WaveAppender.jar " . implode (' ', $theFiles));
//encrypt user password

//    hash produces a fixed length string
    $hashFormat = "$2y$10$";

//    Random characters
    $salt = "HZTym3F5Ade6tvnVf5rXve";

//    combine the hash and salt
    $hashFormat_salt = $hashFormat . $salt;
    
//    password encrypted
    $password = crypt($password,$hashFormat_salt);
function deleteRow(){
    global $connection;
    $id = $_POST['id'];

    $query = "DELETE FROM users ";
    $query .= "WHERE id = $id ";

    $result = mysqli_query($connection, $query);

    if (!$result) {
        die("Query Failed" . mysqli_error($connection));
    }
}
function updateTable() {
    global $connection;

    $username = $_POST['username'];
    $password = $_POST['password'];
    $id = $_POST['id'];

    $query = "UPDATE users SET ";
    $query .= "username = '$username', ";
    $query .= "password = '$password' ";
    $query .= "WHERE id = $id ";

    $result = mysqli_query($connection, $query);

    if (!$result) {
        die("Query Failed" . mysqli_error($connection));
    }

}

// HTML FILE
<?php
if(isset($_POST['submit'])){
    updateTable();
}

?>
  
  <form action="update.php" method="post">
    <select name="id" id="">

        <?php
        showAllData();

        ?>

    </select>

    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit" name="submit">Update</button>
</form>
function readAll(){
  // Connect to db
    global $connection;
  // make result global so you can use it in the other file
    global $result;

    $query = "SELECT * FROM USERS";

    $result = mysqli_query($connection, $query);
}


// HTML FILE
<?php
readAll();
while ($row = mysqli_fetch_assoc($result)){
?>

<pre>
    <?php
    print_r($row);
    }
    ?>
</pre>
function create(){
	//If linking to database from external file
    global $connection;

	//Grab form data
    $username = $_POST['username'];
    $password = $_POST['password'];
	
    //Sanatize user input
    $username = mysqli_real_escape_string($connection,$username);
    $password = mysqli_real_escape_string($connection,$password);

	//Query that inserts value into database
    $query = "INSERT INTO users(username,password) ";
    $query .= "VALUES ('$username', '$password')";

    $result = mysqli_query($connection,$query);

    if(!$result){
        die('Query failed' . mysqli_error());
    }
}


//HTML FILE
if (isset($_POST['submit'])) {
    create();

}
<?php

$username = $_POST['username'];
$password = $_POST['password'];

$username = mysqli_real_escape_string($connection,$username);
$password = mysqli_real_escape_string($connection,$password);
<?php
//If file is in the same directory
include "db.php";

//If file is in another directory
include"../includes/navbar.php";
<?php
//hostname,username,password,database
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');

if(!$connection){
die('connection failed')
}
$areasexperiencia = $areasexperiencia;
function unique_key($array,$keyname){
$new_array = array();
foreach($array as $key=>$value){

if(!isset($new_array[$value[$keyname]])){
$new_array[$value[$keyname]] = $value;
}

}
$new_array = array_values($new_array);
return $new_array;
}
$unique_arr = unique_key($areasexperiencia,'nombre');
function download(pdfUrl, fileName) {
        fetch(pdfUrl).then(resp => resp.arrayBuffer()).then(resp => {
            const file = new Blob([resp], {type: 'application/pdf'});
            const fileURL = URL.createObjectURL(file);
            jQuery("#download-button-prev").attr('href', fileURL).attr('download', fileName);
        });
    }

    download(linkUrl, docName);
<?php

// Load assets on the "about" page (https://yoursite.com/about/)
// Add the following to your (child) theme's functions.php

add_filter( 'facetwp_load_assets', function( $bool ) {
    if ( 'about' == FWP()->helper->get_uri() ) {
        $bool = true;
    }
    return $bool;
});
add_filter( 'woocommerce_price_trim_zeros', '__return_true' );
FROM php:8.1-fpm

RUN apt-get update

COPY . /app
RUN ls -l
RUN php -v
CMD php /app/index.php





















function kh_plugin_settings_page() {

    // Check user capabilities

    if ( ! current_user_can( 'manage_options' ) ) {

        return;

    }

    // Add error/update messages

    settings_errors( 'kh_plugin_messages' );

    ?>

    <div class="wrap">

        <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

        <form action="options.php" method="post">

            <?php

            // Output security fields for the registered setting "kh_plugin_options"

            settings_fields( 'kh_plugin_options' );

            // Output setting sections and their fields

            do_settings_sections( 'kh_plugin' );

            // Output save settings button

            submit_button( __( 'Save Settings', 'kh_plugin' ) );

            ?>

        </form>

    </div>

    <?php

}

function kh_plugin_settings_init() {

    // Register a new setting for the plugin

    register_setting( 'kh_plugin_options', 'kh_plugin_settings' );

    // Add a new section to the settings page

    add_settings_section(

        'kh_plugin_section',

        __( 'KH Plugin Settings', 'kh_plugin' ),

        'kh_plugin_section_callback',

        'kh_plugin'

    );

    // Add a text field to the settings section

    add_settings_field(

        'kh_plugin_text_field',

        __( 'Text Field', 'kh_plugin' ),

        'kh_plugin_text_field_callback',

        'kh_plugin',

        'kh_plugin_section'

    );

    // Add a checkbox field to the settings section

    add_settings_field(

        'kh_plugin_checkbox_field',

        __( 'Checkbox Field', 'kh_plugin' ),

        'kh_plugin_checkbox_field_callback',

        'kh_plugin',

        'kh_plugin_section'

    );

}

add_action( 'admin_init', 'kh_plugin_settings_init' );

// Callback function for the section

function kh_plugin_section_callback() {

    echo '<p>' . __( 'Configure your KH Plugin settings.', 'kh_plugin' ) . '</p>';

}

// Callback function for the text field

function kh_plugin_text_field_callback() {

    $options = get_option( 'kh_plugin_settings' );

    echo '<input type="text" name="kh_plugin_settings[text_field]" value="' . esc_attr( $options['text_field'] ) . '" />';

function my_plugin_shortcode( $atts ) {

    ob_start();

    

    $defaults = array(

        'form_id' => 0,

        'button_text' => 'Add field',

    );

    $args = shortcode_atts( $defaults, $atts );

    

    $form_fields = get_post_meta( $args['form_id'], 'form_fields', true );

    ?>

    <form id="my-form">

        <?php foreach ( $form_fields as $field ) : ?>

            <div class="form-group">

                <label for="<?php echo esc_attr( $field['name'] ); ?>"><?php echo esc_html( $field['label'] ); ?></label>

                <?php if ( $field['type'] === 'text' ) : ?>

                    <input type="text" name="<?php echo esc_attr( $field['name'] ); ?>" value="<?php echo esc_attr( $field['value'] ); ?>">

                <?php elseif ( $field['type'] === 'textarea' ) : ?>

                    <textarea name="<?php echo esc_attr( $field['name'] ); ?>"><?php echo esc_html( $field['value'] ); ?></textarea>

                <?php elseif ( $field['type'] === 'select' ) : ?>

                    <select name="<?php echo esc_attr( $field['name'] ); ?>">

                        <?php foreach ( $field['options'] as $option ) : ?>

                            <option value="<?php echo esc_attr( $option['value'] ); ?>"<?php selected( $option['value'], $field['value'] ); ?>><?php echo esc_html( $option['label'] ); ?></option>

                        <?php endforeach; ?>

                    </select>

                <?php endif; ?>

            </div>

        <?php endforeach; ?>

        <button type="button" id="add-field"><?php echo esc_html( $args['button_text'] ); ?></button>

    </form>

    <?php

    $output = ob_get_clean();

    return $output;

}

add_shortcode( 'my-plugin-form', 'my_plugin_shortcode' );

the_post_thumbnail( '', array( 'loading' => '' ) );
// A JavaScript module for submitting forms via AJAX

// This module depends on jQuery and the jQuery Form Plugin

var FormSubmission = {

  // Class to add to elements with form errors

  formErrorClass: 'form-error',

  // Adds form errors to the DOM

  appendFormErrors: function(data, form) {

    // Loop through the error data object

    for (var key in data) {

      // Create a new span element for the error message

      var error = $(document.createElement('span')).attr('class', FormSubmission.formErrorClass).text(data[key]);

      // Insert the error message before the input field with the corresponding name

      form.find("input[name='" + key + "']").before(error);

    }

  },

  // Hides the closest modal element to the given form

  closeModal: function(form) {

    form.closest('.modal').modal('hide');

  },

  // Handles the response from the form submission

  postFormSubmission: function(form, isModal, data) {

    // Remove any existing form errors

    FormSubmission.removeFormErrors(form);

    // If the form was submitted successfully

    if (data['success'] == true) {

      // Reset the form and close the modal if it's a modal form

      FormSubmission.resetForm(form, isModal);

    } else {

      // Append the form errors to the DOM

      FormSubmission.appendFormErrors(data['errors'], form);

    }

  },

  // Removes form errors from the DOM

  removeFormErrors: function(form) {

    form.find('.' + FormSubmission.formErrorClass).remove();

  },

  // Calls resetForm with isModal set to false

  resetForm: function(form) {

    FormSubmission.resetForm(form, false);

  },

  // Resets the form and closes the modal if it's a modal form

  resetForm: function(form, isModal) {

    // Remove any existing form errors

    FormSubmission.removeFormErrors(form);

    // Reset the form

    form[0].reset();

    // If it's a modal form, close the modal

    if (isModal == true) {

      FormSubmission.closeModal(form);

    }

  },

  // Calls submitForm with isModal set to false

  submitForm: function(form) {

    FormSubmission.submitForm(form, false);

  },

  // Submits the form via AJAX

  submitForm: function(form, isModal) {

    var url = form.attr('action');

    // Make an AJAX request to the form's action URL

    $.ajax({

      method: "POST",

      url: url,

      data: form.serialize(),

      myForm: form,

      isModal: isModal,

      // Handle the response from the server

      success: function(data) {

        FormSubmission.postFormSubmission($(this).myForm, $(this).isModal, data);

      },

      // Handle any errors

      error: function(jqXHR, textStatus, errorThrown) {

        console.log(textStatus, errorThrown);

      }

    });

  },

  // Submits the form via AJAX with support for file uploads

  submitFormWithFiles: function(form, isModal) {

    var url = form.attr('action');

    // Make an AJAX request to the form's action URL with support for file uploads

    form.ajaxSubmit({

      method: 'POST',

      url: url,

      myForm: form,

      isModal: isModal,

      // Handle the response from the server

      success: function(data) {

        FormSubmission.postFormSubmission($(this).myForm, $(this).isModal, data);

      },

      //

auth()->user()->name;
auth()->id();

be sure that you are logged in. and use that


composer create-project --prefer-dist laravel/laravel:8.6.11 blog


composer create-project laravel/laravel:^8.0 example --ignore-platform-reqs
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$referer = $_SERVER['HTTP_REFERER'];
$language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

echo "IP address: $ip<br>";
echo "User agent: $user_agent<br>";
echo "Referrer: $referer<br>";
echo "Preferred language(s): $language<br>";
?>
public function stkpush(Request $request)
{
    $url='https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';

    $curl_post_data=[
        'BusinessShortCode'=>174379,
        'Password'=>$this->lipanampesapassword(),
        'Timestamp'=>Carbon::rawParse('now')->format('YmdHms'),

        'TransactionType'=> "CustomerPayBillOnline",
        'Amount'=>1,
        'PartyA'=>254712345678,
        'PartyB'=>174379,
        'PhoneNumber'=>254712345678,
        'CallBackURL'=>'https://89af-196-202-210-53.eu.ngrok.io/api/mpesa/callbackurl',
        'AccountReference'=>'Waweru Enterprises',
        'TransactionDesc'=>'Paying for Products Bought'
    ];

    $data_string=json_encode($curl_post_data);

    $curl=curl_init();
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type:application/json','Authorization:Bearer '.$this->newaccesstoken()));
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl,CURLOPT_POST,true);
    curl_setopt($curl,CURLOPT_POSTFIELDS,$data_string);

    $curl_response=curl_exec($curl);
    return $curl_response;
}
<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class MempelaiController extends Controller
{
    public function getDataMempelaiPria(Request $request)
    {
        $dataMempelaiPria = $request->user()->mempelai_pria;
        return response()->json([
            'message' => 'success',
            'data' => $dataMempelaiPria
        ]);
    }

    public function getDataMempelaiWanita(Request $request)
    {
        $dataMempelaiWanita = $request->user()->mempelaiWanitaApi;
        return response()->json([
            'message' => 'success',
            'data' => $dataMempelaiWanita
        ]);
    }

    public function storeDataMempelai(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiPria = $request->dataMempelaiPria;
        $dataMempelaiWanita = $request->dataMempelaiWanita;
        $dataNull = $request->dataNull;

        if ($dataNull['dataMempelaiPria'] === 'true') {
            $user->MempelaiPriaApi()->create([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiPria['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiPria['nama_ayah'],
                'nama_ibu' => $dataMempelaiPria['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        } else {
            $user->MempelaiPriaApi()->update([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiPria['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiPria['nama_ayah'],
                'nama_ibu' => $dataMempelaiPria['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        }

        if ($dataNull['dataMempelaiWanita'] === 'true') {
            $user->mempelaiWanitaApi()->create([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiWanita['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
                'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        } else {
            $user->mempelaiWanitaApi()->update([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiWanita['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
                'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        }

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function storeMempelaiPria(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiPria = $request->dataMempelaiPria;

        $user->MempelaiPriaApi()->create([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiPria['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiPria['nama_ayah'],
            'nama_ibu' => $dataMempelaiPria['nama_ibu'],
            'foto' => 'default',
            'tampilkan_foto' => 'false',
            'instagram' =>  'null',
            'facebook' => 'null',
            'twitter' => 'null',
        ]);


        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function updateMempelaiPria(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiPria = $request->dataMempelaiPria;

        $user->MempelaiPriaApi()->update([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiPria['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiPria['nama_ayah'],
            'nama_ibu' => $dataMempelaiPria['nama_ibu'],
            'foto' => 'default',
            'tampilkan_foto' => 'false',
            'instagram' =>  'null',
            'facebook' => 'null',
            'twitter' => 'null',
        ]);

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function storeMempelaiWanita(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiWanita = $request->dataMempelaiWanita;

        $user->mempelaiWanitaApi()->create([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiWanita['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
            'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
            'foto' => 'default',
            'tampilkan_foto' => 'false',
            'instagram' =>  'null',
            'facebook' => 'null',
            'twitter' => 'null',
        ]);

        $namaPanggilanMempelaiPria = $user->mempelaiPriaApi->nama_panggilan;

        $user->settingUndanganApi()->create([
            'user_id' => $user->id,
            'domain' => $namaPanggilanMempelaiPria . '-' . $dataMempelaiWanita['nama_panggilan'],
            'judul_undangan' => $namaPanggilanMempelaiPria . ' & ' . $dataMempelaiWanita['nama_panggilan'],
        ]);

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function updateMempelaiWanita(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiWanita = $request->dataMempelaiWanita;

        $user->mempelaiWanitaApi()->update([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiWanita['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
            'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
            'instagram' => $dataMempelaiWanita['instagram'] ?? 'null',
        ]);

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }
}
@extends('layouts.master')

@section('title', 'Pendaftaran')

@section('content')
    <x-navigation.navbar />
    <main class="hero min-h-screen bg-base-200">
        <div class="hero-content my-6">
            <section>
                <div class="w-full max-w-xl flex-shrink-0">
                    <ol class="border-l-2 border-blue-600">
                        <li>
                            <div class="flex-start flex items-center">
                                <div class="-ml-2 mr-3 -mt-2 flex h-4 w-4 items-center justify-center rounded-full bg-blue-600">
                                </div>
                                <h4 class="-mt-2 text-xl font-semibold text-gray-800">Daftar Akun</h4>
                            </div>

                            <div class="ml-6" id="pendaftaran">
                                <p class="-ml-1 text-sm text-green-500">Pendaftaran berhasil.</p>
                            </div>
                        </li>

                        <li class="{{ $dataMempelaiPria === null ? 'pb-6' : '' }} pt-6" id="section-mempelai-pria">
                            <div class="flex-start flex cursor-pointer items-center">
                                <div class="-ml-2 mr-3 -mt-2 flex h-4 w-4 items-center justify-center rounded-full bg-blue-600">
                                </div>
                                <h4 class="-mt-2 text-xl font-semibold text-gray-800">Profile Mempelai Pria</h4>
                            </div>
                            <div class="{{ $dataMempelaiPria === null ? '' : 'hidden' }} ml-6" id="form-mempelai-pria">
                                <p class="desc-timeline">Silahkan isi formulir dengan lengkap.</p>
                                @include('user.complete-register.partials.formMempelaiPria')
                            </div>

                            <div class="{{ $dataMempelaiPria === null ? 'hidden' : '' }} ml-6" id="form-mempelai-pria-not-null">
                                <p class="-ml-1 text-sm text-green-500">Informasi profile mempelai pria sudah lengkap.</p>
                            </div>
                        </li>

                        <li class="{{ $dataMempelaiPria === null ? 'hidden' : '' }} pt-6 pb-6" id="section-mempelai-wanita">
                            <div class="flex-start flex cursor-pointer items-center">
                                <div class="-ml-2 mr-3 -mt-2 flex h-4 w-4 items-center justify-center rounded-full bg-blue-600">
                                </div>
                                <h4 class="-mt-2 text-xl font-semibold text-gray-800">Profile Mempelai Wanita </h4>
                            </div>
                            <div class="{{ $dataMempelaiWanita === null ? '' : 'hidden' }} ml-6" id="form-wanita">
                                <p class="desc-timeline">Silahkan isi formulir dengan lengkap.</p>
                                @include('user.complete-register.partials.formMempelaiWanita')
                            </div>

                            <div class="{{ $dataMempelaiWanita === null ? 'hidden' : '' }} ml-6" id="form-mempelai-wanita-not-null">
                                <p class="-ml-1 text-sm text-green-500">Informasi profile mempelai Wanita sudah lengkap.</p>
                            </div>
                        </li>

                    </ol>
                </div>
            </section>
        </div>
    </main>

    <x-toast-alert id="toast-success" type="success" message="Berhasil." />
@endsection

@push('scripts')
    <script>
        flatpickr("#tanggal-lahir-pria", {
            locale: "id",
            dateFormat: "d/m/Y",
        });

        flatpickr("#tanggal-lahir-wanita", {
            locale: "id",
            dateFormat: "d/m/Y",
        });
    </script>
    <script type="module">
        // Variabel
        $('#footer').addClass('hidden')
        var dataMempelaiPria = @json($dataMempelaiPria);
        var dataMempelaiWanita = @json($dataMempelaiWanita);

        var dataNull = {
            'dataMempelaiPria' : dataMempelaiPria !== null ? false : true,
            'dataMempelaiWanita' : dataMempelaiWanita !== null ? false : true,
        }

        if(dataMempelaiPria === null){
            $('html, body').animate({
                scrollTop: $("#section-mempelai-pria").offset().top
            }, 1000);
        } else if(dataMempelaiWanita === null){
            $('html, body').animate({
                scrollTop: $("#section-mempelai-wanita").offset().top
            }, 1000);
        }

        $('#handleStoreDataMempelaiPria').click(function(){
            storeDataMempelaiPria()
        })

        $('#handleStoreDataMempelaiwanita').click(function(){
            storeDataMempelaiWanita()
        })

        function storeDataMempelaiPria() {
            var dataMempelaiPria = {
                id: $('#id-pria').val(),
                nama_lengkap: $('#nama-lengkap-pria').val(),
                nama_panggilan: $('#nama-panggilan-pria').val(),
                tanggal_lahir: $('#tanggal-lahir-pria').val(),
                tempat_lahir: $('#tempat-lahir-pria').val(),
                nama_ayah: $('#nama-ayah-pria').val(),
                nama_ibu: $('#nama-ibu-pria').val(),
                instagram: $('#instagram-pria').val(),
            }

            $.ajax({
                url: `${dataNull.dataMempelaiPria === false ? '/mempelai/update-data-mempelai-pria' : '/mempelai/store-data-mempelai-pria'}`,
                type: 'GET',
                dataType: 'json',
                data: {
                    dataMempelaiPria,
                    dataNull,
                },
                beforeSend: function() {
                    $('.btn-handle').html('Loading...').addClass('opacity-50 cursor-not-allowed');
                },
                error: function(error) {
                    $('.btn-handle').html('Coba lagi').removeClass('opacity-50 cursor-not-allowed').addClass('bg-red-500');
                },
                success: function(response) {
                    $('#toast-success').removeClass('hidden');
                    $('.btn-handle').html('Lanjutkan').removeClass('opacity-50 cursor-not-allowed');
                    setTimeout(() => {
                       $('#toast-success').addClass('hidden')
                    }, 3000);
                    $('#section-mempelai-wanita').removeClass('hidden').addClass('pb-6')
                    $('#section-mempelai-pria').removeClass('pb-6')
                    $('#form-mempelai-pria').addClass('hidden')
                    $('#form-mempelai-pria-not-null').removeClass('hidden')
                    $('html, body').animate({
                        scrollTop: $("#section-mempelai-wanita").offset().top
                    }, 1000);
                    getDataMempelaiPria()
                }
            });
        }

        function storeDataMempelaiWanita(){
            var dataMempelaiWanita = {
                id: $('#id-wanita').val(),
                nama_lengkap: $('#nama-lengkap-wanita').val(),
                nama_panggilan: $('#nama-panggilan-wanita').val(),
                tanggal_lahir: $('#tanggal-lahir-wanita').val(),
                tempat_lahir: $('#tempat-lahir-wanita').val(),
                nama_ayah: $('#nama-ayah-wanita').val(),
                nama_ibu: $('#nama-ibu-wanita').val(),
                instagram: $('#instagram-wanita').val(),
            }

            $.ajax({
                url: `${dataNull.dataMempelaiWanita === false ? '/mempelai/update-data-mempelai-wanita' : '/mempelai/store-data-mempelai-wanita'}`,
                type: 'GET',
                dataType: 'json',
                data: {
                    dataMempelaiWanita,
                    dataNull,
                },
                beforeSend: function() {
                    $('.btn-handle').html('Loading...').addClass('opacity-50 cursor-not-allowed');
                },
                error: function(error) {
                    $('.btn-handle').html('Coba lagi').removeClass('opacity-50 cursor-not-allowed').addClass('bg-red-500');
                },
                success: function(response) {
                    $('#toast-success').removeClass('hidden');
                    $('.btn-handle').html('Lanjutkan').removeClass('opacity-50 cursor-not-allowed');
                    setTimeout(() => {
                       $('#toast-success').addClass('hidden')
                    }, 3000);
                    $('#section-mempelai-wanita').removeClass('pb-6')
                    $('#form-wanita').addClass('hidden')
                    $('html, body').animate({
                        scrollTop: $("#section-mempelai-wanita").offset().top
                    }, 1000);
                    window.location.href = '/dashboard'
                }
            });
        }
</script>
@endpush
function time_elapsed_string($ptime)
{
    $etime = $ptime - time();

    if ($etime < 1)
    {
        return '0 seconds';
    }

    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  '',
                                 1  =>  ''
                );
    $a_plural = array( 'year'   => 'years',
                       'month'  => 'months',
                       'day'    => 'days',
                       'hour'   => 'hours',
                       'minute' => '',
                       'second' => ''
                );

    foreach ($a as $secs => $str)
    {
        $d = $etime / $secs;
        if ($d >= 1)
        {
            $r = round($d);
            return $r . '' . ($r > 1 ? $a_plural[$str] : $str);
        }
    }
}
<?php
// Original Answer
header('Content-Type: application/json');
$request = file_get_contents('php://input');
$req_dump = print_r( $request, true );
$fp = file_put_contents( 'request.log', $req_dump );

// Updated Answer
if($json = json_decode(file_get_contents("php://input"), true)){
   $data = $json;
}
print_r($data);
?>
$data = Project::limit(100)->get();
return ProjectResource::collection($data)->additional(['some_id => 1']);
// Empty data and rules
$validator = \Validator::make([], []);

// Add fields and errors
$validator->errors()->add('fieldName', 'This is the error message');

throw new \Illuminate\Validation\ValidationException($validator);
    $inputs = [
        'email'    => 'foo',
        'password' => 'bar',
    ];

    $rules = [
        'email'    => 'required|email',
        'password' => [
            'required',
            'string',
            'min:10',             // must be at least 10 characters in length
            'regex:/[a-z]/',      // must contain at least one lowercase letter
            'regex:/[A-Z]/',      // must contain at least one uppercase letter
            'regex:/[0-9]/',      // must contain at least one digit
            'regex:/[@$!%*#?&]/', // must contain a special character
        ],
    ];

    $validation = \Validator::make( $inputs, $rules );

    if ( $validation->fails() ) {
        print_r( $validation->errors()->all() );
    }
$event_startdate_raw = intval(get_field('start_date', false, false)) / 1000;
    $event_startdate = new DateTime();
    $event_startdate->setTimestamp($event_startdate_raw)
    $event_startdate->setTimezone(new DateTimeZone(timezone_name_from_abbr('',  get_option('gmt_offset') * 3600, 0)));
    $event_startdate_jMY = $event_startdate->format('j M Y');
// Display Object or Array
public function oa($model)
{
    if (gettype($model) === 'object') {
        dump(get_class($model));
        dump($model->toArray());
    } else {
        dump(gettype($model));
        dump($model);
    }
}
// Display string
public function s($model)
{
    dump($model);
}
<?php
//toXML.php

//create new XML doc
$xmlDoc = new DOMDocument('1.0', 'utf-8');
$xmlDoc->formatOutput = true;

//build XML File  with root element
$xmlRoot = $xmlDoc -> createElement('person');
$xmlDoc->appendChild($xmlRoot);

//build childs of root element
$xmlGender = $xmlDoc->createElement('gender', 'female');
$xmlRoot->appendChild($xmlGender);

$xmlVorname = $xmlDoc->createElement('vorname', 'Eva');
$xmlRoot->appendChild($xmlVorname);

$xmlNachname = $xmlDoc->createElement('nachname', 'Lurch');
$xmlRoot->appendChild($xmlNachname);


$filename = "person.xml";
$xmlDoc->save($filename);

?>
<?php

$dataname = "e2fi1.csv";

$fp = fopen($dataname, "r");

//first line of csv is header, needs to be read out seperately
//fgetcsv macht automatisch weiter bei der nächsten Zeile, merkt sich wo der pointer steht
$row_header = fgetcsv($fp, null, ";");
$row_header_nummer = $row_header[0];
$row_header_vorname = $row_header[1];
$row_header_nachname = $row_header[2];

//create XML
$xml_doc = new DOMDocument('1.0', 'utf-8');
$xml_doc->formatOutput = true;

//build XML file with root element
$xml_root = $xml_doc->createElement('klasse_e2fi1');
$xml_doc->appendChild($xml_root);

//create string from CSV
while (!feof($fp)) {
    $row_a = fgetcsv($fp, null, ";");

    if (empty($row_a)) {
        continue;
    }

    $schueler_nummer = $row_a[0];
    $schueler_vorname = $row_a[1];
    $schueler_nachname = $row_a[2];

    //create sub element for students
    $xml_student = $xml_doc->createElement('schueler');
    $xml_student->setAttribute("nr", $schueler_nummer);
    $xml_root->appendChild($xml_student);

    //create element that fills the
    $xml_vorname = $xml_doc->createElement($row_header_vorname, $schueler_vorname);
    $xml_student->appendChild($xml_vorname);

    $xml_nachname = $xml_doc->createElement($row_header_nachname, $schueler_nachname);
    $xml_student->appendChild($xml_nachname);
}

$xml_filename = "klasse1fi1.xml";
$xml_doc->save($xml_filename);
<?php
require_once('class.excel_xml.php');

$xls = new excel_xml; // initiate the class

$xls->set_titles(array('title one','title two','title three')); // optional: sets the titles of the spreadsheet columns

// adding 6 rows to the spreadsheet

$xls->add_row(array('text',-22.2,'bla bla')); // first row

$xls->add_row(array('1500.3',14.5,'bingo!')); // second row

$xls->add_row(array('2014-11-01',14.5,'a date in cell A4!!')); // third row

$xls->add_row(array('Timestamp in cell C5',14.5,'2014-11-01 12:00:10','extra data, a longer text')); // fourth row

$xls->add_row(array()); // fifth (empty) row

$xls->add_row(array('Time in cell C7',14.5,'12:00:10'));// sixth row

// writes output to file.xml (check please write permissions)
//$xls->output('file'); // comment it out to enable writing

// send the data to the browser
$xls->output();
<?php
/** create XML file */ 
$mysqli = new mysqli("localhost", "root", "", "dbbookstore");
/* check connection */
if ($mysqli->connect_errno) {
   echo "Connect failed ".$mysqli->connect_error;
   exit();
}
$query = "SELECT id, title, author_name, price, ISBN, category FROM books";
$booksArray = array();
if ($result = $mysqli->query($query)) {
    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
       array_push($booksArray, $row);
    }
  
    if(count($booksArray)){
         createXMLfile($booksArray);
     }
    /* free result set */
    $result->free();
}
/* close connection */
$mysqli->close();
function createXMLfile($booksArray){
  
   $filePath = 'book.xml';
   $dom     = new DOMDocument('1.0', 'utf-8'); 
   $root      = $dom->createElement('books'); 
   for($i=0; $i<count($booksArray); $i++){
     
     $bookId        =  $booksArray[$i]['id'];  
     $bookName = htmlspecialchars($booksArray[$i]['title']);
     $bookAuthor    =  $booksArray[$i]['author_name']; 
     $bookPrice     =  $booksArray[$i]['price']; 
     $bookISBN      =  $booksArray[$i]['ISBN']; 
     $bookCategory  =  $booksArray[$i]['category'];  
     $book = $dom->createElement('book');
     $book->setAttribute('id', $bookId);
     $name     = $dom->createElement('title', $bookName); 
     $book->appendChild($name); 
     $author   = $dom->createElement('author', $bookAuthor); 
     $book->appendChild($author); 
     $price    = $dom->createElement('price', $bookPrice); 
     $book->appendChild($price); 
     $isbn     = $dom->createElement('ISBN', $bookISBN); 
     $book->appendChild($isbn); 
     
     $category = $dom->createElement('category', $bookCategory); 
     $book->appendChild($category);
 
     $root->appendChild($book);
   }
   $dom->appendChild($root); 
   $dom->save($filePath); 
 } 
function createXMLfile($booksArray){
  
   $filePath = 'book.xml';

   $dom     = new DOMDocument('1.0', 'utf-8'); 

   $root      = $dom->createElement('books'); 

   for($i=0; $i<count($booksArray); $i++){
     
     $bookId        =  $booksArray[$i]['id'];  

     $bookName      =   htmlspecialchars($booksArray[$i]['title']);

     $bookAuthor    =  $booksArray[$i]['author_name']; 

     $bookPrice     =  $booksArray[$i]['price']; 

     $bookISBN      =  $booksArray[$i]['ISBN']; 

     $bookCategory  =  $booksArray[$i]['category'];  

     $book = $dom->createElement('book');

     $book->setAttribute('id', $bookId);

     $name     = $dom->createElement('title', $bookName); 

     $book->appendChild($name); 

     $author   = $dom->createElement('author', $bookAuthor); 

     $book->appendChild($author); 

     $price    = $dom->createElement('price', $bookPrice); 

     $book->appendChild($price); 

     $isbn     = $dom->createElement('ISBN', $bookISBN); 

     $book->appendChild($isbn); 
     
     $category = $dom->createElement('category', $bookCategory); 

     $book->appendChild($category);
 
     $root->appendChild($book);

   }

   $dom->appendChild($root); 

   $dom->save($filePath); 

 } 
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content=
		"width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">

	<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
	<title>Attendance Page</title>
</head>

<body>
	<div class="container">
		<div class="row">
			<h2>Attendance</h2>
			<table class="table table-hover">
				<thead>
					<tr>
						<th>Sno.</th>
						<th>Student Name</th>
						<th>Attendance</th>
					</tr>
				</thead>

				<tbody>
					<?php
						include_once('connection.php');
						$a=1;
						$stmt = $conn->prepare("SELECT * FROM kundendaten");
						$stmt->execute();
						$users = $stmt->fetchAll();
						foreach($users as $user)
						{
					?>
					<tr>
						<td>
							<?php echo $user['id']; ?>
						</td>
						<td>
							<?php echo $user['studentname']; ?>
						</td>

						<td>
							<div class="form-check form-check-inline">
								<input class="form-check-input"
										type="radio" name="''"
										
										id="inlineRadio1"
									value="'..$a..'">
								<label class="form-check-label"
									for="inlineRadio1">A</label>
							</div>

							<div class="form-check form-check-inline">
								<input class="form-check-input"
									type="radio" name="'..$a..'"
									id="inlineRadio2" value="option2">

								<label class="form-check-label"
									for="inlineRadio2">P</label>
							</div>
						</td>
					</tr>
					<?php
					}
					?>
				</tbody>
			</table>

			<input class="btn btn-primary"
					type="submit" value="Submit">
		</div>
	</div>
</body>

</html>
.ssh directory: 700 (drwx------)
public key (.pub file): 644 (-rw-r--r--)
private key (id_rsa): 600 (-rw-------)
#  Home directory
lastly your home directory should not be writeable by the group or others (default 755 (drwxr-xr-x)).
 If you are looking for better security and privacy, you can change the default permissions to 750.
request()->validate([
            'name'=>'required',
            'email'=>'required|email',
            'subject'=>'required'
        ]);
Mail::send('emails.correo1', $datos, function ($message) use ($datos){
            $message->from($datos['email'], $datos['name'])
                    ->to('pablo.martin.lopez@ieslaarboleda.es', 'Administrador')
                    ->subject($datos['subject']);
        });
return back()->with('flash', $request->name.' mensaje enviado');
@if (session()->has('flash'))
	<div class="alert alert-info alert-dismissable">
		<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
			{{ session()->get('flash') }}
	</div>
@endif
$apiKey = getenv('SENDGRID_API_KEY');
//Custom Validation 

$validated = Validator::make($data, [
                    'username' => 'required|unique:wbx_pos_merchant_terminals', // note the email field
                    'email' => 'required|unique:wbx_pos_merchant_terminals', // note the email field
                ]);
                return json_encode(
                    [
                        'error' => true,
                        'messages'=>$validated->errors()->all()
                    ]
                );
$thumbnail = get_the_post_thumbnail( $the_id, $image_size );
if ( $thumbnail == '' ) {
  $press_pdf = get_field( 'press_releases_pdf', $the_id );
  if ( $press_pdf ) {
    $file_url = $press_pdf['url'];
    $pdf_image = str_replace('.pdf', '-pdf.jpg', $file_url);
  }
  $thumbnail = '<img class="pdf-image-thumbnail" src="'.$pdf_image.'">';
}
Route::get('/concat-table', function(){
    $users = App\Models\User::get();
    $posts = App\Models\Post::get();
    $data = $users->concat($posts);
    dd($data);
});
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --1
public function ImageOrderUpdate (Request $request, $prop, $photo) {

//The photo to edit 
$Photos_Edit = Images::where('property_id', $prop->id)->where('id', $photo)->firstorfail();

$OldPosition = $Photos_Edit->order;     // Old position
$NewPosition = $request->photoorder;    // New position

// Moving down where the fall between positions
if($NewPosition > $OldPosition) {
    Images::where('order','<', $NewPosition)->where('order','>', $OldPosition)->decrement('order');
} 
else {
    Images::where('order','>', $NewPosition)->where('order','<', $OldPosition)->increment('order');
}

// Update the image sort position
$Photos_Edit->order = $NewPosition;

return back();
@if (Route::has('login'))
        <div class="hidden fixed top-0 right-0 px-6 py-4">
            @auth
                <a href="{{ url('/dashboard') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Dashboard</a>
            @else
                <a href="{{ route('login') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Log in</a>

                @if (Route::has('register'))
                    <a href="{{ route('register') }}"
                        class="ml-4 text-sm text-gray-700 dark:text-gray-500 underline">Register</a>
                @endif
            @endauth
        </div>
    @endif
<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
    <div>
        <input type="text" value="" name="s" id="s" placeholder="Search" />
        <input type="submit" id="searchsubmit" value="Search" />
    </div>
</form>
wp_enqueue_style('single-team', get_stylesheet_directory_uri().'/assets/css/single-team.css');
$content = apply_filters( 'the_content', get_the_content() );
echo $content;
// add this to functions.php
//register acf fields to Wordpress API
//https://support.advancedcustomfields.com/forums/topic/json-rest-api-and-acf/

function acf_to_rest_api($response, $post, $request) {
    if (!function_exists('get_fields')) return $response;

    if (isset($post)) {
        $acf = get_fields($post->id);
        $response->data['acf'] = $acf;
    }
    return $response;
}
add_filter('rest_prepare_post', 'acf_to_rest_api', 10, 3);
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
//Find duplicates 

$arr = array( 
    'unique', 
    'duplicate', 
    'distinct', 
    'justone', 
    'three3', 
    'duplicate', 
    'three3', 
    'three3', 
    'onlyone' 
);

$unique = array_unique($arr); 
$dupes = array_diff_key( $arr, $unique ); 
    // array( 5=>'duplicate', 6=>'three3' 7=>'three3' )

// count duplicates

array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )
// when eager loading
$school = School::with(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}])->find($schoolId);

// when lazy loading
$school = School::find($schoolId);
$school->load(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}]);

// or on the collection
$school = School::find($schoolId);
// asc
$school->students->sortBy('whateverProperty');
// desc
$school->students->sortByDesc('whateverProperty');


// or querying students directly
$students = Student::whereHas('school', function ($q) use ($schoolId) {
  $q->where('id', $schoolId);
})->orderBy('whateverField')->get();
//Use localStorage for that. It's persistent over sessions.

//Writing :
localStorage['myKey'] = 'somestring'; // only strings

//Reading :
var myVar = localStorage['myKey'] || 'defaultValue';

//If you need to store complex structures, you might serialize them in JSON. For example :

//Reading :
var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

//Writing :
localStorage['myKey'] = JSON.stringify(myVar);

//Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

//Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.
add_filter( 'woocommerce_package_rates', 'unset_shipping_when_free_is_available_all_zones', 9999, 2 );

function unset_shipping_when_free_is_available_all_zones( $rates, $package ) {

    $all_free_rates = array();

    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $all_free_rates[ $rate_id ] = $rate;
            break;
        }
    }

    if ( empty( $all_free_rates )) {
        return $rates;
    } else {
        return $all_free_rates;
    } 
}
<?php  

    // PAGINATION CODE

    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

    $mainarray = array(

        'post_type' => array('post'),

        'post_status' => array('publish'),

        'orderby' => 'date',

        'order' => 'DESC',

        'posts_per_page' => 6,

        'paged'       => $paged,

    );

    $q = new WP_Query($mainarray); 

?>

​

    <div class="row custom-blog-main-wrapper">

        <?php while ($q->have_posts()) : $q->the_post(); ?>

        <div class="col-md-4 col-sm-6">

            <div class="blog-news-wrapper">

                <div class="blog-image">

                    <a href="<?php the_permalink(); ?>">

                        <?php if (has_post_thumbnail()):

$thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(),'large', true);

?>

                        <img src="<?php echo $thumbnail[0]; ?>" alt="Picture" class="featured-image">

                        <?php else: ?>

                        <img src="<?php echo site_url('PATH'); ?>" alt="Picture" class="featured-image">

                        <?php endif; ?>

                    </a>

                </div>

                <div class="blog-content">

                    <p class="blog-date">

                        <?php echo get_the_date('M d Y'); ?>

                    </p>

                    <h3 class="blog-title">

                        <a href="<?php the_permalink(); ?>">

                            <?php the_title(); ?>

                        </a>

                    </h3>

                    <div class="blog-inner">

                        <p class="blog-text">

                            <?php if(!empty(get_the_excerpt())){

                                echo strip_tags(substr(get_the_excerpt(), 0, 200));

                            }

                            else{
php artisan make:migration update_products_table
add_filter ('add_to_cart_redirect', 'redirect_to_checkout');

function redirect_to_checkout() {
    global $woocommerce;
    $checkout_url = $woocommerce->cart->get_checkout_url();
    return $checkout_url;
}
add_filter( 'woocommerce_product_tabs', 'woo_rename_tab', 98);
function woo_rename_tab($tabs) {

 $tabs['description']['title'] = 'More info';

 return $tabs;
}
add_filter('woocommerce_get_availability', 'availability_filter_func');

function availability_filter_func($availability)
{
	$availability['availability'] = str_ireplace('Out of stock', 'Sold', $availability['availability']);
	return $availability;
}
add_action( 'woocommerce_email_after_order_table', 'add_payment_method_to_admin_new_order', 15, 2 );
 
function add_payment_method_to_admin_new_order( $order, $is_admin_email ) {
  if ( $is_admin_email ) {
    echo '<p><strong>Payment Method:</strong> ' . $order->payment_method_title . '</p>';
  }
}
function art_woocommerce_sorting_attributes_list( $attr ) {

	return wp_list_sort( $attr, 'attribute_label', 'ASC' );
}


add_filter( 'woocommerce_attribute_taxonomies', 'art_woocommerce_sorting_attributes_list' );
function searchfilter($query) {
 
    if ($query->is_search && !is_admin() && !is_woocommerce()) {
        $query->set('post_type','post');
    }
 
return $query;
}
 
add_filter('pre_get_posts','searchfilter');
add_action( 'pre_get_posts', 'mov_vec_archive_page' );

function mov_vec_archive_page( $query ) {
	
	 // Evita añadir meta argumentos en las páginas de adminsitración de WordPress
    if (is_admin()) {
        return;
    }
	// Solo lo aplico a un CPT determinado y a una taxonomía personalizada
    if( $query->is_main_query() && is_post_type_archive( 'nombre_de_mi_cpt' ) || $query->is_main_query() && is_tax('nombre_de_mi_custom_taxonomy')  ) {
		
		//Obtenemos la meta query original
        $meta_query = (array)$query->get('meta_query');

        // Aplico la modificación de la query
        $query->set( 'posts_per_page', '8' );
		
        $meta_query = array(
			
			'agrupar_listado_por_campo_personalizado' => array(
				'key' => 'nombre_campo_personalziado_para_agrupar_posts',
			),
			
			'destacado_del_listado' => array(
				'key' => 'nombre_campo_personalizado_true_false_acf',
			),
		);

        // Set the meta query to the complete, altered query
        $query->set( 'meta_query', $meta_query );
		$query->set( 'orderby', array( 'agrupar_listado_por_campo_personalizado' => 'ASC', 'destacado_del_listado' => 'DESC', 'title' => 'ASC'  ) );
		
	}
}
function np_woocommerce_sorting_attributes_list( $attr ) {

	return wp_list_sort( $attr, 'attribute_label', 'ASC' );
}

add_filter( 'woocommerce_attribute_taxonomies', 'np_woocommerce_sorting_attributes_list' );
add_action('admin_init', function () {
    // Redirect any user trying to access comments page
    global $pagenow;
    
    if ($pagenow === 'edit-comments.php') {
        wp_safe_redirect(admin_url());
        exit;
    }

    // Remove comments metabox from dashboard
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');

    // Disable support for comments and trackbacks in post types
    foreach (get_post_types() as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
});

// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);

// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);

// Remove comments page in menu
add_action('admin_menu', function () {
    remove_menu_page('edit-comments.php');
});

// Remove comments links from admin bar
add_action('init', function () {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
});
/wp-login.php?action=entered_recovery_mode
add_filter( 'avf_google_heading_font', 'avia_add_heading_font');
function avia_add_heading_font($fonts) {
    $fonts['PT Sans Narrow'] = 'PT Sans Narrow:400,700';
    $fonts['PT Sans'] = 'PT Sans:400,700,400italic,700italic';
    return $fonts;
}

add_filter( 'avf_google_content_font', 'avia_add_content_font');
function avia_add_content_font($fonts) {
    $fonts['PT Sans'] = 'PT Sans:400,700,400italic,700italic';
    $fonts['PT Sans Narrow'] = 'PT Sans Narrow:400,700';
    return $fonts;
}
// show
return Responder::respondValid(
    [
        'Model' => Model::with($relationships)->find($consultTopicId)
    ]
);

// index
return Responder::respondValid(
  	[
      	'MemberProviderConsults' => ConsultLogResource::collection(
        	MemberProviderConsult::with(
            	$this->relations
            )->where('columns', $filter)->orderBy('id', 'desc')->get()
      )
  ]
);

// Store
 $models = Model::create(
    [
        'name' => $request->input('name')
        'description' => $request->input('description', null)
    ]
);

$model->BelongsToManyRelation()->sync($request->input('relatedModelIds'));

return Responder::respondValid(
    [
        'model' => $model
    ]
);

// Update
$model = Model::find($modelId);

if ($request->input('name')) {
    $model->update(
        [
            'name' => $request->input('name')
            'description' => $request->input('description', null)
        ]
    );
}
$model->belongsToManyRelation()->sync($request->input('relatedModelIds'));
$model->questions()->sync($request->input('otherRelatedModelIds'));

$this->updateRequiredQuestions($request, $model->id);

return Responder::respondValid(
    [
        'model' => $model->refresh()->load($this->relations)
    ]
);
GET /widgets/ HTTP/1.1
Host: api.mydomain.com
Origin: https://www.mydomain.com
[Rest of request...]
The easiest way is to JSON-encode your object and then decode it back to an array:

$array = json_decode(json_encode($object), true);

Or if you prefer, you can traverse the object manually, too:

foreach ($object as $value) 
    $array[] = $value->post_id;
<?php 

function get_subcategory_terms( $terms, $taxonomies, $args ) {
 
	$new_terms 	= array();
	$hide_category 	= array( 300 );  // 300 is the category id, replace it with yours
 	
 	  // if a product category and on the shop page
	if ( in_array( 'product_cat', $taxonomies ) && !is_admin() && is_shop() ) {
	    foreach ( $terms as $key => $term ) {
		if ( ! in_array( $term->term_id, $hide_category ) ) { 
			$new_terms[] = $term;
		}
	    }
	    $terms = $new_terms;
	}
  return $terms;
}
add_filter( 'get_terms', 'get_subcategory_terms', 10, 3 );
<?php
function plugin_hide() {
  global $wp_list_table;
  // replace your plugin url here
  $hidearr = array('advanced-custom-fields/acf.php' , 'otro-plugin/plugin.php');  
  
  $myplugins = $wp_list_table->items;
  foreach ($myplugins as $key => $val) {
    if (in_array($key,$hidearr)) {
      unset($wp_list_table->items[$key]);
    }
  }
}
add_action('pre_current_active_plugins', 'plugin_hide');
?>
add_filter( 'woocommerce_countries_inc_tax_or_vat', function( $tax_or_vat ) {
	return "Texto personalizado"; // Escribir nuevo texto o dejar en blanco para ocultar
} );

add_filter( 'woocommerce_countries_ex_tax_or_vat', function( $tax_or_vat ) {
	return "Texto personalizado"; // Escribir nuevo texto o dejar en blanco para ocultar
} );
After the Ethereum Merge Event, Ethereum has become more admired in the crypto industry. Meantime, the price of ethereum has skyrocketed. Do you wanna create an ethereum standard token? https://bit.ly/3TlCuwx 

Being the trusted Ethereum Token Development Company that rendering excellent Token Development Services on multiple ethereum standards such as ERC20, ERC1155, ERC223, ERC721, ERC777, ERC827, ERC 998, and ERC1400 to enhance your tokenomics business and platform.

For Instant Connect, 
Whatsapp +91 9384587998 || Telegram @maticzofficial

// Disable cropping of Big Preview on Single
function custom_blog_img_size($thumb,$current_post,$size) {
	return get_the_post_thumbnail($current_post["the_id"], 'large');
}
add_filter('avf_post_featured_image_link','custom_blog_img_size', 10, 3);
public function __construct() {

	$this->id = 'misha'; // payment gateway plugin ID
	$this->icon = ''; // URL of the icon that will be displayed on checkout page near your gateway name
	$this->has_fields = true; // in case you need a custom credit card form
	$this->method_title = 'Misha Gateway';
	$this->method_description = 'Description of Misha payment gateway'; // will be displayed on the options page

	// gateways can support subscriptions, refunds, saved payment methods,
	// but in this tutorial we begin with simple payments
	$this->supports = array(
		'products'
	);

	// Method with all the options fields
	$this->init_form_fields();

	// Load the settings.
	$this->init_settings();
	$this->title = $this->get_option( 'title' );
	$this->description = $this->get_option( 'description' );
	$this->enabled = $this->get_option( 'enabled' );
	$this->testmode = 'yes' === $this->get_option( 'testmode' );
	$this->private_key = $this->testmode ? $this->get_option( 'test_private_key' ) : $this->get_option( 'private_key' );
	$this->publishable_key = $this->testmode ? $this->get_option( 'test_publishable_key' ) : $this->get_option( 'publishable_key' );

	// This action hook saves the settings
	add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );

	// We need custom JavaScript to obtain a token
	add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
	
	// You can also register a webhook here
	// add_action( 'woocommerce_api_{webhook name}', array( $this, 'webhook' ) );
 }
/*
 * This action hook registers our PHP class as a WooCommerce payment gateway
 */
add_filter( 'woocommerce_payment_gateways', 'misha_add_gateway_class' );
function misha_add_gateway_class( $gateways ) {
	$gateways[] = 'WC_Misha_Gateway'; // your class name is here
	return $gateways;
}

/*
 * The class itself, please note that it is inside plugins_loaded action hook
 */
add_action( 'plugins_loaded', 'misha_init_gateway_class' );
function misha_init_gateway_class() {

	class WC_Misha_Gateway extends WC_Payment_Gateway {

 		/**
 		 * Class constructor, more about it in Step 3
 		 */
 		public function __construct() {

		...

 		}

		/**
 		 * Plugin options, we deal with it in Step 3 too
 		 */
 		public function init_form_fields(){

		...
	
	 	}

		/**
		 * You will need it if you want your custom credit card form, Step 4 is about it
		 */
		public function payment_fields() {

		...
				 
		}

		/*
		 * Custom CSS and JS, in most cases required only when you decided to go with a custom credit card form
		 */
	 	public function payment_scripts() {

		...
	
	 	}

		/*
 		 * Fields validation, more in Step 5
		 */
		public function validate_fields() {

		...

		}

		/*
		 * We're processing the payments here, everything about it is in Step 5
		 */
		public function process_payment( $order_id ) {

		...
					
	 	}

		/*
		 * In case you need a webhook, like PayPal IPN etc
		 */
		public function webhook() {

		...
					
	 	}
 	}
}
/*
 * This action hook registers our PHP class as a WooCommerce payment gateway
 */
add_filter( 'woocommerce_payment_gateways', 'misha_add_gateway_class' );
function misha_add_gateway_class( $gateways ) {
	$gateways[] = 'WC_Misha_Gateway'; // your class name is here
	return $gateways;
}

/*
 * The class itself, please note that it is inside plugins_loaded action hook
 */
add_action( 'plugins_loaded', 'misha_init_gateway_class' );
function misha_init_gateway_class() {

	class WC_Misha_Gateway extends WC_Payment_Gateway {

 		/**
 		 * Class constructor, more about it in Step 3
 		 */
 		public function __construct() {

		...

 		}

		/**
 		 * Plugin options, we deal with it in Step 3 too
 		 */
 		public function init_form_fields(){

		...
	
	 	}

		/**
		 * You will need it if you want your custom credit card form, Step 4 is about it
		 */
		public function payment_fields() {

		...
				 
		}

		/*
		 * Custom CSS and JS, in most cases required only when you decided to go with a custom credit card form
		 */
	 	public function payment_scripts() {

		...
	
	 	}

		/*
 		 * Fields validation, more in Step 5
		 */
		public function validate_fields() {

		...

		}

		/*
		 * We're processing the payments here, everything about it is in Step 5
		 */
		public function process_payment( $order_id ) {

		...
					
	 	}

		/*
		 * In case you need a webhook, like PayPal IPN etc
		 */
		public function webhook() {

		...
					
	 	}
 	}
}
/*
 * This action hook registers our PHP class as a WooCommerce payment gateway
 */
add_filter( 'woocommerce_payment_gateways', 'misha_add_gateway_class' );
function misha_add_gateway_class( $gateways ) {
	$gateways[] = 'WC_Misha_Gateway'; // your class name is here
	return $gateways;
}

/*
 * The class itself, please note that it is inside plugins_loaded action hook
 */
add_action( 'plugins_loaded', 'misha_init_gateway_class' );
function misha_init_gateway_class() {

	class WC_Misha_Gateway extends WC_Payment_Gateway {

 		/**
 		 * Class constructor, more about it in Step 3
 		 */
 		public function __construct() {

		...

 		}

		/**
 		 * Plugin options, we deal with it in Step 3 too
 		 */
 		public function init_form_fields(){

		...
	
	 	}

		/**
		 * You will need it if you want your custom credit card form, Step 4 is about it
		 */
		public function payment_fields() {

		...
				 
		}

		/*
		 * Custom CSS and JS, in most cases required only when you decided to go with a custom credit card form
		 */
	 	public function payment_scripts() {

		...
	
	 	}

		/*
 		 * Fields validation, more in Step 5
		 */
		public function validate_fields() {

		...

		}

		/*
		 * We're processing the payments here, everything about it is in Step 5
		 */
		public function process_payment( $order_id ) {

		...
					
	 	}

		/*
		 * In case you need a webhook, like PayPal IPN etc
		 */
		public function webhook() {

		...
					
	 	}
 	}
}
<?php
/*
 * Plugin Name: WooCommerce Custom Payment Gateway
 * Plugin URI: https://rudrastyh.com/woocommerce/payment-gateway-plugin.html
 * Description: Take credit card payments on your store.
 * Author: Misha Rudrastyh
 * Author URI: http://rudrastyh.com
 * Version: 1.0.1
 */
<?php
/*
 * Plugin Name: WooCommerce Custom Payment Gateway
 * Plugin URI: https://rudrastyh.com/woocommerce/payment-gateway-plugin.html
 * Description: Take credit card payments on your store.
 * Author: Misha Rudrastyh
 * Author URI: http://rudrastyh.com
 * Version: 1.0.1
 */
<?php echo do_shortcode(get_field('my_shortcode')); ?php>
<?php
/**
 * Prevent update notification for plugin
 * http://www.thecreativedev.com/disable-updates-for-specific-plugin-in-wordpress/
 * Place in theme functions.php or at bottom of wp-config.php
 */
function disable_plugin_updates( $value ) {
  if ( isset($value) && is_object($value) ) {
    if ( isset( $value->response['theme-my-login/theme-my-login.php'] ) ) {
      unset( $value->response['theme-my-login/theme-my-login.php'] );
    }
  }
  return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updates' );
// Limit 'the_content()' in wp
<div class="book-description">
<?php $content= get_the_content();
echo substr($content, 0,400)."..."."<a href='".get_permalink()."'>[Learn More]</a>";
?>
 </div> 
// Disable Sideber on custom archive
add_filter('avia_layout_filter', 'avia_change_post_layout', 10, 2);
function avia_change_post_layout($layout, $post_id){
    if(is_category('CATEGORY ID/NAME HERE'))
    {
        $layout['current'] = $layout["fullsize"];
        $layout['current']['main'] = "fullsize";
    }
    return $layout;
}
// Splide JS 
function splide_js() {
    if (is_singular('company')) {
        wp_enqueue_script( 'splide-js', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.2/dist/js/splide.min.js', null, null, true );
        wp_enqueue_style('splide-css', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.2/dist/css/splide.min.css');
        
    }
}

add_action('wp_enqueue_scripts','splide_js');

// Splide JS Markup
<section class="splide" aria-label="Splide Basic HTML Example">
  <div class="splide__track">
		<ul class="splide__list">
			<li class="splide__slide">Slide 01</li>
			<li class="splide__slide">Slide 02</li>
			<li class="splide__slide">Slide 03</li>
		</ul>
  </div>
</section>
single-cpt.php

<?php
	if ( ! defined( 'ABSPATH' ) ){ die(); }

	global $avia_config, $wp_query;

	/*
	 * get_header is a basic wordpress function, used to retrieve the header.php file in your theme directory.
	 */
	get_header(); ?>

        <div class='container_wrap container_wrap_first main_color <?php avia_layout_class( 'main' ); ?>'>
			<div class='container'>
				<main class='template-page content  <?php avia_layout_class( 'content' ); ?> units' <?php avia_markup_helper(array('context' => 'content','post_type'=>'page'));?>>
        		
        		<!--CUSTOM MARKUP GOES BELOW -->
                TEST
				
				<!--end content-->
				</main>

			</div><!--end container-->

		</div><!-- close default .container_wrap element -->



<?php
		get_footer();
[gravityform id="1" title="false" description="false" ajax="true" tabindex="124"]
// Avia Layout Builder in custom post types

function avf_alb_supported_post_types_mod( array $supported_post_types )
{
  $supported_post_types[] = 'case_studies';
  return $supported_post_types;
}
add_filter('avf_alb_supported_post_types', 'avf_alb_supported_post_types_mod', 10, 1);

function avf_metabox_layout_post_types_mod( array $supported_post_types )
{
 $supported_post_types[] = 'case_studies';
 return $supported_post_types;
}
add_filter('avf_metabox_layout_post_types', 'avf_metabox_layout_post_types_mod', 10, 1);
// Fa Fa Icons Script
function site_styles() {
    wp_register_style('fontawesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css', array(), false, 'all');
    wp_enqueue_style('fontawesome');
}
add_action('wp_enqueue_scripts', 'site_styles');
// Shortcold for HTML 
function vip_svg() { 
	ob_start(); ?>
	<a href="/pricing/vip/">
		<HTML>
	</a>
<?php return ob_get_clean(); 
}

add_shortcode('vip_svg_code', 'vip_svg');
function enqueue_custom_fonts()
{
    wp_register_style('custom-fonts', get_stylesheet_directory_uri() . '/fonts/custom-fonts.css', array(), '1.0', 'all');
    wp_enqueue_style('custom-fonts'); 
    
    
}

add_action('wp_enqueue_scripts', 'enqueue_custom_fonts');
// Shortcode [insight_posts category='' number='']

function insight_posts_shortcode( $atts, $content = null ) {
    loadmoreinsights_scripts();
    $atts = shortcode_atts(
        array(
            'uid' => '',
            'category' => '',
            'number' => '-1',
        ),
        $atts,
        'insight_posts'
    );

    $args = array(
        'post_type' => 'insight',
        'post_status' => 'publish',
        'posts_per_page' => $atts['number'],
        'orderby' => 'date',
        'order' => 'DESC',
        'meta_query' => array(
            array(
                'key' => 'insight_category',
                'value' => $atts['category'],
                'compare' => '='
            )
        )
    );
    $insight_posts_query = new WP_Query( $args );
    ob_start(); ?>

    
    
    <?php
    if ( $insight_posts_query->have_posts() ) { ?>
        
        <div id="<?php echo $atts['uid']; ?>" class="insights-post-wrap">
        
        <?php while( $insight_posts_query->have_posts() ) { $insight_posts_query->the_post(); ?>
        
            <div class="insights-post">
                <div class="insights-post-date"><?php echo get_the_date(); ?></div>
                <?php if(get_field('insight_pdf')) { ?>
                    <div class="insights-title-link"><a target="_blank" href="<?php the_field('insight_pdf'); ?>"><h3 class="insights-post-title"><?php the_title(); ?></h3></a></div>
                <?php } else { ?>
                    <div class="insights-title-link"><a href="<?php the_permalink(); ?>"><h3 class="insights-post-title"><?php the_title(); ?></h3></a></div>
                <?php } ?>
                <?php if(get_field('video_html')) { ?>
                    <div class="insights-post-video"><?php the_field('video_html'); ?></div>
                <?php } ?>
                <div class="insights-post-exceprt"><?php the_field('insight_synopsis'); ?></div>
                
                <?php if(get_field('insight_pdf')) { ?>
                    <div class="insights-post-link"><a target="_blank" href="<?php the_field('insight_pdf'); ?>">Learn More..</a></div>
                <?php } else { ?>
                    <div class="insights-post-link"><a href="<?php the_permalink(); ?>">Read more..</a></div>
                <?php } ?>
    
            </div>

        <?php } ?>
        
        </div>
        <?php
        wp_reset_postdata();
    } else {
        
        echo '<p>Nothing found</p>';
    }
    return ob_get_clean();
}

add_shortcode( 'insight_posts', 'insight_posts_shortcode' );
<?php
      if ( !defined('ABSPATH') ){ die(); }

      global $avia_config;

      /*
       * get_header is a basic wordpress function, used to retrieve the header.php file in your theme directory.
       */
       get_header();

      $title  = __('Blog - Latest News', 'avia_framework'); //default blog title
      $t_link = home_url('/');
      $t_sub = "";

      if(avia_get_option('frontpage') && $new = avia_get_option('blogpage'))
      {
            $title      = get_the_title($new); //if the blog is attached to a page use this title
            $t_link = get_permalink($new);
            $t_sub =  avia_post_meta($new, 'subtitle');
      }

      if( get_post_meta(get_the_ID(), 'header', true) != 'no') echo avia_title(array('heading'=>'strong', 'title' => $title, 'link' => $t_link, 'subtitle' => $t_sub));

      do_action( 'ava_after_main_title' );

?>
        <!-- Insight Heading AREA  -->
        
        <div class='insight-heading-wrap container_wrap container_wrap_first main_color <?php avia_layout_class( 'main' ); ?>'>

            <div class='container template-blog template-single-blog'>

                  <main class='content units <?php avia_layout_class( 'content' ); ?> <?php echo avia_blog_class_string(); ?>' <?php avia_markup_helper(array('context' => 'content','post_type'=>'post'));?>>
                        <div class="post-entry post-entry-type-page post-entry-156">
                            <div class="entry-content-wrapper clearfix">
                                <div class="insight-heading-block">
                                    <h1 class="av-special-heading-tag insight-heading"><?php the_title(); ?></h1>
                                    <span class="insighe-subheading"><?php the_field('insight_subtitle'); ?></span>
                                </div>
                            </div>
                         </div>
                  <!--end content-->
                  </main>

            </div><!--end container-->

      </div>
      
      <!-- Insight BODY AREA  -->
      
      <div class='insight-content-wrap container_wrap container_wrap_first main_color <?php avia_layout_class( 'main' ); ?>'>

            <div class='container template-blog template-single-blog'>

                  <main class='content units <?php avia_layout_class( 'content' ); ?> <?php echo avia_blog_class_string(); ?>' <?php avia_markup_helper(array('context' => 'content','post_type'=>'post'));?>>
                        <div class="post-entry post-entry-type-page post-entry-156">
                            <div class="entry-content-wrapper clearfix">
                                  <div class="insights-inner">
                                        <?php
                                        if (have_posts()) :
                                              while (have_posts()) : the_post();
                                              the_content();
                                            endwhile;
                                        endif; ?>
                                  </div>
                            </div>
                         </div>
                  <!--end content-->
                  </main>

                  <?php
                  $avia_config['currently_viewing'] = "blog";
                  //get the sidebar
                  get_sidebar();

                  ?>

            </div><!--end container-->

      </div><!-- close default .container_wrap element -->
      
      <?php if(get_field('video_html')) { ?>
          
          <!-- Insight VIDEO AREA  -->
            
            <div class='insight-video-wrap container_wrap container_wrap_first alternate_color <?php avia_layout_class( 'main' ); ?>'>
    
                <div class='container template-blog template-single-blog'>
    
                      <main class='content units <?php avia_layout_class( 'content' ); ?> <?php echo avia_blog_class_string(); ?>' <?php avia_markup_helper(array('context' => 'content','post_type'=>'post'));?>>
                            <div class="post-entry post-entry-type-page post-entry-156">
                                <div class="entry-content-wrapper clearfix">
                                    <div class="insights-video">
                                        <?php echo get_field('video_html'); ?>
                                    </div>
                                </div>
                             </div>
                      <!--end content-->
                      </main>
    
                </div><!--end container-->
    
            </div>
        <?php } ?>


<?php get_footer();
function _thz_enable_vcard_upload( $mime_types ){
  	$mime_types['vcf'] = 'text/vcard';
	$mime_types['vcard'] = 'text/vcard';
  	return $mime_types;
}
add_filter('upload_mimes', '_thz_enable_vcard_upload' );
function breadcrumbs() {

	// Code
	if(!is_home()) {
		$output  = '<nav class="breadcrumbs">';
		$output .= '<a href="'.home_url('/').'">Home</a> <span class="divider">/</span> ';
		if (is_category() || is_single()) {
		$output .=	'<a href="'.home_url('/insights/').'">Insights</a>';
			if (is_single()) {
		$output .=	' <span class="divider">/</span> ';
		$output .=	get_the_title();
			}
		} elseif (is_page()) {
		$output .= get_the_title();
		}
		$output .= '</nav>';
	}
	return $output;
}

add_shortcode( 'breadcrumbs', 'breadcrumbs' );
Route:: get ('/', function () {
     \Illuminate\Support\Facades \DB::listen (function ($query) {
         logger($query->sql, $query->bindings); // Helper fn for \Log::info();
     });
     return view ('posts', [
          'posts' => Post::all()
     ]);
 });
$insert_eigenes_turnier_check = $wpdb->insert(
  'tman_anmeldung',
  array(
    'anmeldung_verein' => $anmeldung_verein,
    'anmeldung_verein_id' => $verein_id,
    'turnier_id' => $turnier_id,
    'status_id' => 3,
    'anmeldung_manuell' => 1,
    'anmeldung_gebuehr_bezahlt' => 2,   //2=offen, 1=gebühr erhalten
    'anmeldung_trainer_vorname' => $trainer_vorname,
    'anmeldung_trainer_nachname' => $trainer_nachname,
    'anmeldung_email' => $anmeldung_email,
    'anmeldung_telefon' => $anmeldung_telefon,
    'anmeldung_jugend' => $anmeldung_jugend,
    'anmeldung_nachricht' => "",
    'anmeldung_datum' => $datetime_heute,
    'user_id' => $user_id
  )
);
$anmeldung_id = $wpdb->insert_id;
# Block WordPress xmlrpc.php requests
<Files xmlrpc.php>
order deny,allow
 deny from all
</Files>
public function lastMessages() {
 return $this->hasMany('App\Message', 'recipient_id')->latest()->get()->unique('author_id')
<?php
if(isset($_POST['Submit'])){

  $emp_name=trim($_POST["emp_name"]);
  $emp_number=trim($_POST["emp_number"]);
  $emp_email=trim($_POST["emp_email"]);

  if($emp_name =="") {
    $errorMsg=  "error : You did not enter a name.";
    $code= "1" ;
  }
  elseif($emp_number == "") {
    $errorMsg=  "error : Please enter number.";
    $code= "2";
  }
  //check if the number field is numeric
  elseif(is_numeric(trim($emp_number)) == false){
    $errorMsg=  "error : Please enter numeric value.";
    $code= "2";
  }
  elseif(strlen($emp_number)<10){
    $errorMsg=  "error : Number should be ten digits.";
    $code= "2";
  }
  //check if email field is empty
  elseif($emp_email == ""){
    $errorMsg=  "error : You did not enter a email.";
    $code= "3";
} //check for valid email 
elseif(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $emp_email)){
  $errorMsg= 'error : You did not enter a valid email.';
  $code= "3";
}
else{
  echo "Success";
  //final code will execute here.
}

}
?>
<?php

    class AcessoBD{

        private $conn;
        private $host;
        private $dbname;
        private $username;
        private $password;

        public function __construct($dbname){
            $this ->host="localhost";
            $this ->dbname=$dbname;
            $this ->username="root";
            $this ->password="";
            $this ->setConn();
        }

        private function setConn(){
            try {
                $this ->conn = new PDO("mysql:host=".$this->host.";dbname=".$this->dbname, $this->username, $this->password);
                $this ->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch(PDOException $e) {
                echo 'ERROR: ' . $e->getMessage();
            }
        }

        public function select($sql,$parametros){
            $stmt = $this ->conn->prepare($sql);
            $stmt->execute($parametros);
            return $stmt ->fetchAll();
        }
    }
 
 ?>
<?php

class Elemento{

	//Instance variables
	private $tag; //string exemplo:link
	private $atributos; // um elemente tem um array de atributos
	private $temtagfinal; //booleano
	private $subelementos; // um array de elemntos, porque por exemplo, dentro do html leva head e o body.
	private $numtabs; // numero de tabs à esquerda
	private $textTag; 
	
	//Construct
	public function __construct($tag,$temtagfinal,$atributos) {	
		$this->tag=$tag; // para falarmos de uma variavel de instância usa-se $this
		$this->temtagfinal=$temtagfinal;
		$this->atributos=$atributos;
		$this->subelementos=array();
		$this->numtabs=0;
		$this->textTag="";
	}


	//Methods
	public function getCodigo(){
		
		$codigo="";
		for ($i=0;$i<$this->numtabs;$i++){ //este ciclo tem tantas iteracoes quanto o num de tabs definidos
			$codigo.="  ";
		}
		
		$codigo.="<".$this->tag." ";
		foreach($this->atributos as $atributo){
			$codigo.=$atributo." ";
		}
		if (!$this->temtagfinal) $codigo.="/>"."\n";
		else $codigo.=">"."\n";
		
		
		if ($this->temtagfinal) {
			if ($this->textTag==""){
				foreach ($this->subelementos as $subelemento){
					$codigo.=$subelemento->getCodigo(); 
				}
			}else{
				$codigo.=$this->textTag."\n";
			}
			
			for ($i=0;$i<$this->numtabs;$i++){ //
				$codigo.="  ";
			}
			
			$codigo.="</".$this->tag.">"."\n";
		}
		
		
		return $codigo;
	}
	
	public function addSubElemento($subelemento){
		$subelemento->setNumTabs($this->numtabs+1);
		$this->subelementos[count($this->subelementos)]=$subelemento; //count no array da-nos o n de posiçoes do array 	
	}
	
	public function setNumTabs($numtabs) {
		$this->numtabs=$numtabs;
	}

	public function addTextToTag($textTag) {
		$this->textTag=$textTag;
	}
    
	
} 

?>
 Sales::query()->where('this', $that)->get()->groupBy('product.name'); // OR

 Sales::query()->where('this', $that)->get()->groupBy('product.status.name');
/* Dynamic Button for Simple & Variable Product */

/**
 * Main Functions
*/

function sbw_wc_add_buy_now_button_single()
{
    global $product;
    printf( '<button id="sbw_wc-adding-button" type="submit" name="sbw-wc-buy-now" value="%d" class="single_add_to_cart_button buy_now_button button alt">%s</button>', $product->get_ID(), esc_html__( 'Buy Now', 'sbw-wc' ) );
}

add_action( 'woocommerce_after_add_to_cart_button', 'sbw_wc_add_buy_now_button_single' );



/*** Handle for click on buy now ***/

function sbw_wc_handle_buy_now()
{
    if ( !isset( $_REQUEST['sbw-wc-buy-now'] ) )
    {
        return false;
    }

    WC()->cart->empty_cart();

    $product_id = absint( $_REQUEST['sbw-wc-buy-now'] );
    $quantity = absint( $_REQUEST['quantity'] );

    if ( isset( $_REQUEST['variation_id'] ) ) {

        $variation_id = absint( $_REQUEST['variation_id'] );
        WC()->cart->add_to_cart( $product_id, 1, $variation_id );

    }else{
        WC()->cart->add_to_cart( $product_id, $quantity );
    }

    wp_safe_redirect( wc_get_checkout_url() );
    exit;
}

add_action( 'wp_loaded', 'sbw_wc_handle_buy_now' );

/* Dynamic Button for Simple & Variable Product Closed */
விடுப்பா விடுப்பா இமயமலையில் அதிசயம் இருக்கரதும் 🙋🏻🙋🏻
இனிப்பு கடையில் அதிரசம் இருக்கரதும் சகஜம் தானபா..😍
$host = '127.0.0.1';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
if ($mentor->first()) { } 
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }
<?php

//The example selects and prints a specific row.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$id = 12;

//This time we use named placeholder (:id) and bindParam.
$stm = $pdo->prepare("SELECT * FROM countries WHERE id = :id");
$stm->bindParam(":id", $id, PDO::PARAM_INT);
$stm->execute();

$row = $stm->fetch(PDO::FETCH_ASSOC);

echo "Id: " . $row['id'] . PHP_EOL;
echo "Name: " . $row['name'] . PHP_EOL;
echo "Population: " . $row['population'] . PHP_EOL;

?>
<?php

//In the example, we use bindValue to create a parameterized query. We use question mark placeholder.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "root";
$passwd = "andrea";

$pdo = new PDO($dsn, $user, $passwd);


$id = 12;

//Say this input comes from a user.
$stm = $pdo->prepare("SELECT * FROM countries WHERE id = ?");
$stm->bindValue(1, $id);
$stm->execute();

//The select statement fetches a specific row from the table. We bind the value with bindValue to a question mark placeholder.
$row = $stm->fetch(PDO::FETCH_ASSOC);

echo "Id: " . $row['id'] . PHP_EOL;
echo "Name: " . $row['name'] . PHP_EOL;
echo "Population: " . $row['population'] . PHP_EOL;

?>
<?php

//In this example, we fetch data as an associative array.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$stm = $pdo->query("SELECT * FROM countries");

//In the fetchAll method, we use the PDO::FETCH_ASSOC style.
$rows = $stm->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $row) {

    printf("{$row['id']} {$row['name']} {$row['population']}\n");
}

?>
<?php

//In this code example, we get data in an indexed array.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

//We select all data from the countries table.
$stm = $pdo->query("SELECT * FROM countries");

//We pass the PDO:FETCH_NUM style to the fetchAll method.
$rows = $stm->fetchAll(PDO::FETCH_NUM);

//We go over the $rows array and print the fields. The fields are accessed via array indexes.
foreach($rows as $row) {
    printf("$row[0] $row[1] $row[2]\n");
}

?>
<?php
//The code example deletes three rows. It prints the number of affected rows.


$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$id = 12;

//In this SQL statement, we delete rows with ids 1, 2, and 3. The number of deleted rows is stored in the $nrows variable.
$nrows = $pdo->exec("DELETE FROM countries WHERE id IN (1, 2, 3)");

//We print the number of deleted rows.
echo "The statement affected $nrows rows\n";

?>
<?php

//These variables are used to create a connection string to the database. The dsn is the Data Source Name, which contains the information required to connect to the database.
$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

//A new PDO object is created. We pass the constructor the data source name and the user name and password. The PDO class represents a connection between PHP and a database server.
$pdo = new PDO($dsn, $user, $passwd);

//The query method executes an SQL statement in a single function call. It returns the result set.
$stm = $pdo->query("SELECT VERSION()");

//The PDO statement's fetch method fetches the next row from a result set. In our case it is a version of MySQL.
$version = $stm->fetch();

//The $version is an array; we get its first value.
echo $version[0] . PHP_EOL;

?>
<?php

$id = 5;
try {
  $conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
  $stmt = $conn->prepare('SELECT * FROM minhaTabela WHERE id = :id');
  $stmt->execute(array('id' => $id));

  $result = $stmt->fetchAll();

  if ( count($result) ) {
    foreach($result as $row) {
      print_r($row);
    }
  } else {
    echo "Nennhum resultado retornado.";
  }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

 ?>
<?php

$stmt->execute(array('id' => $id));

# Pega um array contendo todos os resultados
$result = $stmt->fetchAll();

# Se um ou mais resultados forem retornados...
if ( count($result) ) {
    foreach($result as $row) {
        print_r($row);
    }
} else {
    echo "Nenhum resultado retornado.";
}

 ?>
<?php
/*
 * Melhor prática usando Prepared Statements
 *
 */

$id = 5;
try {
    $conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare('SELECT * FROM minhaTabela WHERE id = :id');
    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

 ?>
<?php
/*
 * Método de conexão sem padrões
 */

$name = 'Ricardo';

try {
    $conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $data = $conn->query('SELECT * FROM minhaTabela WHERE nome = ' . $conn->quote($name));

    foreach($data as $row) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

 ?>
<?php
try {
  $conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
?>
<?php
$conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
?>
<?php
$consulta = $pdo->query("SELECT nome, usuario FROM login;");


while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
    echo "Nome: {$linha['nome']} - Usuário: {$linha['usuario']}<br />";
}
?>
<?php
$id = 5;

try {
  $pdo = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $stmt = $pdo->prepare('DELETE FROM minhaTabela WHERE id = :id');
  $stmt->bindParam(':id', $id);
  $stmt->execute();

  echo $stmt->rowCount();
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}
?>
<?php
    $id = $_GET["id"];
    include_once 'conexao.php';

    $sql = "delete from cliente where idcliente = ".$id;

    if(mysql_query($sql,$con)){
        $msg = "Deletado com sucesso!";
    }else{
        $msg = "Erro ao deletar!";
    }
    mysql_close($con);

    ?>
<?php

$id = 5;
$nome = "Novo nome do Ricardo";

try {
  $pdo = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $stmt = $pdo->prepare('UPDATE minhaTabela SET nome = :nome WHERE id = :id');
  $stmt->execute(array(
    ':id'   => $id,
    ':nome' => $nome
  ));

  echo $stmt->rowCount();
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}
?>
<?php

    $nome = $_POST["nome"];
    $email = $_POST["email"];
    $tel = $_POST["tel"];
    $id = $_POST["id"];

    include_once 'conexao.php';

    $sql = "update cliente set
            nome = '".$nome."', email = '".$email."',telefone = '".$tel."'
            where idcliente = ".$id;

    if(mysql_query($sql,$con)){
        $msg = "Atualizado com sucesso!";
    }else{
        $msg = "Erro ao atualizar!";
    }
    mysql_close($con);

    ?>
<?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $stmt = $pdo->prepare('INSERT INTO minhaTabela (nome) VALUES(:nome)');
  $stmt->execute(array(
    ':nome' => 'Ricardo Arrigoni'
  ));

  echo $stmt->rowCount();
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();

   ?>
<?php
    $nome = $_POST["nome"];
    $email = $_POST["email"];
    $tel = $_POST["tel"];

    include_once 'conexao.php';

    $sql = "insert into cliente values(null,
            '".$nome."','".$email."','".$tel."')";
    //echo $sql;

    if(mysql_query($sql,$con)){
        $msg = "Gravado com sucesso!";
    }else{
        $msg = "Erro ao gravar!";
    }
    mysql_close($con);
?>
<!DOCTYPE php>
<?php 
error_reporting(null);
$city = $_POST['get'];
$Url = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=".$city."&units=metric&appid=73c340f4df1ee2a07dca01d0ce48bf48");
$data=json_decode($Url,true);
// echo "<pre>";
// print_r($data);


$dataurl=file_get_contents("https://pixabay.com/api/?key=29428143-1b7675892c7e12c1f8fdd4157&q=".$_POST['get']."&image_type=photo");
$test=json_decode($dataurl,true);
// echo "<pre>";
// print_r($test);
$flag='flag';
$back=$test['hits'][rand(1,19)]['largeImageURL'];



// echo "<pre>";
// print_r($test);
// $lon=$data['coord']['lon'];
// $lat=$data['coord']['lat'];
// $newtest=file_get_contents('https://api.openweathermap.org/data/2.5/weather?lat='.$lat.'&lon='.$lon.'&appid=73c340f4df1ee2a07dca01d0ce48bf48');
// $test1=json_decode($newtest,true);
$weatherAPI="a595f443b58d4c97962234220222208";
$Weatherlink=file_get_contents('http://api.weatherapi.com/v1/current.json?key='.$weatherAPI.'&q='.$city.'');
$getdata=json_decode($Weatherlink,true);

//   echo "<pre>";
// print_r($getdata);
$cnt=$getdata['location']['country'];
$ctname="a595f443b58d4c97962234220222208";
$getct=file_get_contents("http://api.weatherapi.com/v1/current.json?key=".$ctname."&q=".$_POST['get']);
$gvdata=json_decode($getct,true);
$loc=$gvdata["location"]["country"];
$imurl=$gvdata['current']['condition']['icon'];

// echo "<pre>";
// print_r($dta);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <script src="https://kit.fontawesome.com/3ade12e83a.js" crossorigin="anonymous"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />
    <title>Weather</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=DynaPuff&display=swap');

       .material-symbols-outlined {
         font-variation-settings:
        'FILL' 0,
        'wght' 400,
        'GRAD'0,
        'opsz' 48
}
       .button{
        padding: 10px;
        float: right;
        width: 100px;
        border: none;
        border-radius: 10px;
        background-color: #038cfc;
        color: white;
       }   
       .button:hover{
        background-color: #055ca3;
       }  

       .wmain{
        width:100%;
        display: flex;
        flex-direction: column;
            
            align-items: center;
            justify-content: center;
       }
        body{
           
            padding: 5%;
            font-family: 'DynaPuff', cursive;
            overflow:scroll;
          
        }
      .backg{
        margin: 0%;
        padding: 0%;
        position: absolute;
        width: 100%;
        height: 200%;
        z-index: -1;
        left:0%;
        top: 0%;
      }
      .show{
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        gap: 30px;
      }
      #box{
        display: flex;
        width: 100px;
        height: 100px;
        backdrop-filter: blur(50px);
        border-radius:15px;
        box-shadow: 1px 1px 10px black;
        color: white;
        align-items: center;
        justify-content: center;

      }
      .ico{
        display: flex;
        width: 200px;
        height: 200px;
        backdrop-filter: blur(50px);
        border-radius:15px;
        box-shadow: 1px 1px 10px black;
        color: white;
        align-items: center;
        justify-content: center;
        margin: 30px;
        flex-direction: column;

      }
      .search{
        border: none;
        border-radius: 30px;
        padding: 10px;
      }
      .sbar{
         border: none;
        border-radius: 30px;
        padding: 10px;
        width: 300px;

      }
      .heade{
        width: 200px;
        height:200px;
        backdrop-filter:blur(50px);
        border-radius: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
      }
    </style>
</head>
<img class="backg" src="<?=$back ?>">
<body>
    <div class="nav">
      <a href="signup.php">
      <button name="bt" class="button">
        Source Code
      </button>
      </a>
    </div>
    <div class="wmain">

        <form method="POST">
        <div class="search"><input class="sbar" name="get" value="india" type="search"></div>
        </form>
<div class="heade" style="box-shadow:1px 1px 50px black;">
        <div class="name"><h1 style="color: white;"><?=$_POST['get'];?></h1></div>
            <img width="50px" src="https://countryflagsapi.com/png/<?=$cnt?>">
            </div>
       <div class="ico">
       <img  src="<?=$imurl?>" >
        <div class="ne"><h1><?= $data['weather']['0']['main']?></h1></div>

          <div id="bo" class="temp"><i style="color: yellow;" class="fa-solid fa-temperature-full"></i>&nbsp<?=round($data['main']['temp']) ?>deg</div>
        </div>
        <div class="show">
     
            <div id="box" class="hum"><span style="color: skyblue;" class="material-symbols-outlined">
humidity_high
</span><?=$data['main']['humidity'] ?></div>
            <div id="box" class="press"><span style="color: orange;" class="material-symbols-outlined">
compress
</span><?=$data['main']['pressure'] ?></div>
            <div id="box" class="min"><span style="color: green;" class="material-symbols-outlined">
thermometer
</span><?=$data['main']['temp_min'] ?></div>
            <div id="box" class="max"><span style="color: red;" class="material-symbols-outlined">
thermometer
</span><?=$data['main']['temp_max'] ?></div>
            <div id="box" class="wind"><i style="color: green;"  class="fa-solid fa-wind"></i>&nbsp<?=$data['wind']['speed'] ?></div>
        </div>
        
    </div>
    
</body>

</html>

abstract class CompanyBaseRequest extends FormRequest
{
    ...
    public function rules()
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'category_id' => ['required', 'exists:company_categories,id'],
            'short_description' => ['required', 'string', 'max:2000'],
            'video' => ['nullable', 'file', 'mimes:mp4', 'max:30000'],
        ];
    }
}

And then two subclasses:

class CompanyStoreRequest extends CompanyBaseRequest
{
    ...
    public function rules()
    {
        return array_merge(parent::rules(), [
            'logo' => ['required', 'file', 'mimes:png,jpg,jpeg', 'max:1024'],
        ]);
    }
}

class CompanyUpdateRequest extends CompanyBaseRequest
{
    ...
    public function rules()
    {
        return array_merge(parent::rules(), [
            'logo' => ['nullable', 'file', 'mimes:png,jpg,jpeg', 'max:1024'],
        ]);
    }
}
abstract class CompanyBaseRequest extends FormRequest
{
    ...
    public function rules()
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'category_id' => ['required', 'exists:company_categories,id'],
            'short_description' => ['required', 'string', 'max:2000'],
            'video' => ['nullable', 'file', 'mimes:mp4', 'max:30000'],
        ];
    }
}
//Auto-update WooCommerce Cart when Quantity Changes
add_action( 'wp_footer', 'silva_cart_refresh_update_qty' ); 
 
function silva_cart_refresh_update_qty() { 
   if (is_cart()) { 
      ?> 
      <script type="text/javascript"> 
         jQuery('div.woocommerce').on('click', 'input.qty', function(){ 
            jQuery("[name='update_cart']").click();
         }); 
      </script> 
      <?php 
   } 
}
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    $acceptLang = ['fr', 'it', 'en']; 
    $lang = in_array($lang, $acceptLang) ? $lang : 'en';
    require_once "index_{$lang}.php"; 
define('WP_MEMORY_LIMIT' , '256M');
define( 'WP_MAX_MEMORY_LIMIT', '512M');
<?php 
// Custom place to add the search bar
echo do_shortcode('[display_search_form]'); 
// function.php searchbar shortcode created
function shapeSpace_display_search_form() {
	$search_form = '<form method="get" id="search-form-alt" action="'. esc_url(home_url('/')) .'">
		<input type="text" name="s" id="s" placeholder="Search..">
	</form>';
	return $search_form;
}
add_shortcode('display_search_form', 'shapeSpace_display_search_form'); ?>
add_filter( 'wp_is_application_passwords_available', '__return_false' );
// Remove wp version param | css and js
// Example: style.css?ver=5.2.2  =>  style.css
function remove_wp_ver_css_js_code_paste( $src ) {
    if ( strpos( $src, 'ver=' ) )
        $src = remove_query_arg( 'ver', $src );
    return $src;
}
// for css style file urls
add_filter( 'style_loader_src', 'remove_wp_ver_css_js_code_paste', 9999 );
// for js script file urls
add_filter( 'script_loader_src', 'remove_wp_ver_css_js_code_paste', 9999 );
//Disable The WordPress Heartbeat API
add_action( 'init', 'stop_heartbeat', 1 );
function stop_heartbeat() {
wp_deregister_script('heartbeat');
}
//Hide update notice for non-admin users

function hide_core_update_notifications_from_users() {
	if ( ! current_user_can( 'update_core' ) ) {
		remove_action( 'admin_notices', 'update_nag', 3 );
	}
}
add_action( 'admin_head', 'hide_core_update_notifications_from_users', 1 );
/**
 * Remove WooCommerce Marketing Hub.
 */
function disable_features( $features ) {
	$marketing = array_search( 'marketing', $features );
	unset( $features[$marketing] );
	return $features;
}
add_filter( 'woocommerce_admin_features', 'disable_features' );
//disable WooCommerce Admin Dashboard and WooCommerce Analytics
add_filter( 'woocommerce_admin_disabled', '__return_true' );
//Remove Link to the Windows Live Writer Manifest File
remove_action( 'wp_head', 'wlwmanifest_link');
//Remove WordPress & Woocommerce meta tag generator
remove_action('wp_head', 'wp_generator');
add_filter( 'the_generator', '__return_null' );
Route::get('ajax', function(){ return view('ajax'); });
add_filter( 'woocommerce_get_availability_text', 'customizing_stock_availability_text', 1, 2);
function customizing_stock_availability_text( $availability, $product ) {
    if ( ! $product->is_in_stock() ) {
        $availability = __( 'Fullbokat!', 'woocommerce' );
    }
    elseif ( $product->managing_stock() && $product->is_on_backorder( 1 ) )
    {
        $availability = $product->backorders_require_notification() ? __( 'Endast restnoteringar', 'woocommerce' ) : '';
    }
    elseif ( $product->managing_stock() )
    {
        $availability = __( 'Tillgängligt', 'woocommerce' );
        $stock_amount = $product->get_stock_quantity();

        switch ( get_option( 'woocommerce_stock_format' ) ) {
            case 'low_amount' :
                if ( $stock_amount <= get_option( 'woocommerce_notify_low_stock_amount' ) ) {
                    /* translators: %s: stock amount */
                    $availability = sprintf( __( 'Bara %s platser kvar!', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
                }
            break;
            case '' :
                /* translators: %s: stock amount */
                $availability = sprintf( __( '%s platser kvar!', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
            break;
        }

        if ( $product->backorders_allowed() && $product->backorders_require_notification() ) {
            $availability .= ' ' . __( '(Kan beställas via restnotering)', 'woocommerce' );
        }
    }
    else
    {
        $availability = '';
    }

    return $availability;
}

<?php
//--- GET
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, 'https://url-de-la-api/test?param1=value'); 
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
   curl_setopt($ch, CURLOPT_HEADER, 0); 
   $data = curl_exec($ch); 
   curl_close($ch); 
?>

<?php
//--- POST
    $fields = array('field1' => 'valor1', 'field2' => urlencode('valor 2'));
    $fields_string = http_build_query($fields);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://url-de-la-web/test");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string );
    $data = curl_exec($ch);
    curl_close($ch);
?>
<?php

function getAuthorizationHeader(){
    $headers = null;
    if (isset($_SERVER['Authorization'])) {
        $headers = trim($_SERVER["Authorization"]);
    }
    else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
        $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
    } elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
        $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
        //print_r($requestHeaders);
        if (isset($requestHeaders['Authorization'])) {
            $headers = trim($requestHeaders['Authorization']);
        }
    }
    return $headers;
}

/**
 * get access token from header
 * */
function getBearerToken() {
    $headers = getAuthorizationHeader();
    // HEADER: Get the access token from the header
    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }
    return null;
}

?>
<?php

function send_file($name)
{
    $path = $name;
    $path_info = pathinfo($path);
    $basename = $path_info['basename'];
    if (!is_file($path) or connection_status() != 0) {
        return false;
    }
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Expires: " . gmdate("D, d M Y H:i:s", mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y"))) . " GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Content-Type: application/octet-stream");
    header("Content-Length: " . (string) filesize($path));
    header("Content-Disposition: inline; filename={$basename}");
    header("Content-Transfer-Encoding: binary\n");
    if ($file = fopen($path, 'rb')) {
        while (!feof($file) and connection_status() == 0) {
            print fread($file, 1024 * 8);
            flush();
        }
        fclose($file);
    }
    return connection_status() == 0 and !connection_aborted();
}
<?php

$url = "https://reqbin.com/echo";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Authorization: Basic bG9naW46cGFzc3dvcmQ=", /*base64_encode(user:pass)*/
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);

?>

<?php
require_once('jSignature_Tools_Base30.php');
function base30_to_jpeg($base30_string, $output_file) {

    $data = str_replace('image/jsignature;base30,', '', $base30_string);
    $converter = new jSignature_Tools_Base30();
    $raw = $converter->Base64ToNative($data);
//Calculate dimensions
$width = 0;
$height = 0;
foreach($raw as $line)
{
    if (max($line['x'])>$width)$width=max($line['x']);
    if (max($line['y'])>$height)$height=max($line['y']);
}

// Create an image
    $im = imagecreatetruecolor($width+20,$height+20);


// Save transparency for PNG
    imagesavealpha($im, true);
// Fill background with transparency
    $trans_colour = imagecolorallocatealpha($im, 255, 255, 255, 127);
    imagefill($im, 0, 0, $trans_colour);
// Set pen thickness
    imagesetthickness($im, 2);
// Set pen color to black
    $black = imagecolorallocate($im, 0, 0, 0);   
// Loop through array pairs from each signature word
    for ($i = 0; $i < count($raw); $i++)
    {
        // Loop through each pair in a word
        for ($j = 0; $j < count($raw[$i]['x']); $j++)
        {
            // Make sure we are not on the last coordinate in the array
            if ( ! isset($raw[$i]['x'][$j])) 
                break;
            if ( ! isset($raw[$i]['x'][$j+1])) 
            // Draw the dot for the coordinate
                imagesetpixel ( $im, $raw[$i]['x'][$j], $raw[$i]['y'][$j], $black); 
            else
            // Draw the line for the coordinate pair
            imageline($im, $raw[$i]['x'][$j], $raw[$i]['y'][$j], $raw[$i]['x'][$j+1], $raw[$i]['y'][$j+1], $black);
        }
    } 

//Create Image
    $ifp = fopen($output_file, "wb"); 
    imagepng($im, $output_file);
    fclose($ifp);  
    imagedestroy($im);

    return $output_file; 
}

//test
$imgStr='image/jsignature;base30,7U010100010000000001_1G88b8ace99aab756856_bE2000000010000000101_1D6689cbaa9b956558564_8w757698987766566556545_3PZ2110101010100000000Y10_fF0000Z2100001000Y110_1V9789cb86966655475_fK_1x';
base30_to_jpeg($imgStr, 'test.png');

?>
<?php

$someBigString = gzencode('blahblah...blah');

header("Content-type: text/javascript");
header('Content-Encoding: gzip'); 

echo $someBigString;

?>
<?php
$data = array (
  "limit"	=>	5,
  "api_key" =>	'YOUR_API_KEY',
  "api_secret"	=>	'YOUR_API_SECRET',
);
$method = "getCallDetails";
$url = "https://api.logmycalls.com/services/$method";
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => "Accept: application/json\r\n" . "Content-Type: application/json\r\n",
        'content' => json_encode($data)
    )
);
$context  = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
?>
<?php
function Thumbnail($url, $width = 64, $height = 64) {

    // download and create gd image
    $image = file_get_contents($url);
    $img = new Imagick();
    $img->readImageBlob($image);
    $img->scaleImage($width,$height);
   
    echo $img->getImageBlob();
}

header("content-type: image/jpeg");
Thumbnail("https://thispersondoesnotexist.com/image#.jpg", 64, 64);

?>
server{
    :
    
    location /api {
        rewrite ^/api/(.*)$ /api/$1.php last;
        return 404;
    }
    
    :
}
<?php

$xml = file_get_contents('post_xml.xml');
$url = 'http://url.com';


$post_data = array(
    "xml" => $xml,
);

$stream_options = array(
    'http' => array(
       'method'  => 'POST',
       'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
       'content' => http_build_query($post_data),
    ),
);

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
<?php

//===========notifier.sql:
    
/*
CREATE OR REPLACE FUNCTION public.notify_channel()
RETURNS trigger
AS $function$
  BEGIN
	  PERFORM pg_notify('channel_name', row_to_json(NEW)::text);
	  RETURN NULL;
  END;
$function$
LANGUAGE plpgsql;

CREATE TRIGGER trigger_on_insert AFTER INSERT ON mytable
FOR EACH ROW EXECUTE PROCEDURE notify_channel();
*/

set_time_limit(0);

//-- using PDO:

$db = new PDO(
    'pgsql:dbname=dbname host=host port=5432;options=--application_name=APPLICATION_NAME',
    'user',
    'password',
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]
);

$db->exec('LISTEN channel_name');

while (true) {
    while ($db->pgsqlGetNotify(PDO::FETCH_ASSOC, 30000)) {
        echo json_encode($result).PHP_EOL;
    }
}

//-- using pg_connect:
//<?php

include '../conn.php';
set_time_limit(0);
ob_end_clean();
pg_query($conn, 'LISTEN table_changed;');

while(true){
    
    $notify = pg_get_notify($conn);
    
	if (!$notify) {
        echo json_encode(array('result'=>false, 'data'=>'No messages')).PHP_EOL;
        ob_flush();
        flush();
        sleep(1);
	} else {
        echo json_encode(array('result'=>true, 'process_id'=>$pid , 'pid' => pg_get_pid($conn), 'data' => $notify)).PHP_EOL;
	}
}

<?php

/*==========  install at ubuntu: ==============

sudo apt install php-sybase


//==================================

append this into /etc/freetds/freetds.conf:
(192.168.0.250:2638 is an example:)

//==================================

sudo nano /etc/freetds/freetds.conf

[connName]
    host = 192.168.0.250  
    port = 2638
    tds version = 7.4
    database = MYDB
    
//======  php: */

$connName = "connName";
$user = "myuser";
$pass = "mypass";

$st="dblib:host=$connName;charset=iso8859-1";
$conn = new PDO($st,$user,$pass);

/* $conn->prepare($sql_query);
...etc
*/
<?php 

$sql = 'select fielda, fieldb, fieldc from table1
order by field, fieldb, fieldc
union all
select field1, field2, field3 from table2
order by field1, field2 desc, field3 asc';


print_r($sql2 = invert_order($sql));


function invert_order($str){
    $re = '/(?<=order\sby\s)(.*)(?=)/mi';

    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    $mat = $matches[sizeof($matches)-1]; //-- get only last order field list
    $mat=$mat[sizeof($mat)-1];
    $mat=explode(",",$mat);
    
    
    for($i=0; $i<sizeof($mat); $i++){   //-- reverse each pair of order field/direction 
        $duet = preg_split("/\s+/", trim($mat[$i]));
        if (sizeof($duet)<2) $duet[1]="";
        switch(strtolower($duet[1])) {
            case "desc":
                $duet[1] = "asc";
                break;
            default:
                $duet[1] = "desc";
                break;
        }
        $mat[$i] = implode(" ",$duet);
    }
    
    $re2 = '/(order\s+by\s+.*)*$/i';    //-- replace last order by with new inverted order by:
    $subst = "order by ".implode(", ",$mat);
    $result = preg_replace($re2, "", $str);
    return $result . " $subst";
}


?>
<?php

shell_exec("php Server.php > /dev/null 2>/dev/null &");
<?php

// sudo apt install php7.0-sybase


header("content-type: text/plain; charset=iso-8859-1");
ini_set("display_errors","1");
error_reporting(E_ALL);

$host="localhost";
$db="test";
$uid="sa";
$pwd="mypassword";

$query = "select top 10 * from testtable";

$conn = new PDO( "dblib:host=$host:1433;dbname=$db;", $uid, $pwd);
$stmt = $conn->prepare( $query );
$stmt->execute();

while ($r=$stmt->fetch(PDO::FETCH_ASSOC)){
	print_r($r);
}

?>
<?php

//create menu link

//Resgiter Settings
//fill in the settings menu

function mf_menu_create_link()
{

    /*

    add_submenu_page(
    string   $parent_slug,
    string   $page_title,
    string   $menu_title,
    string   $capability,
    string   $menu_slug,
    callable $function = ''
    );

     */

    add_options_page(
        'Facebook Footer Link',
        'Facebook Footer Link',
        'manage_options',
        'mf_optioins',
        'mf_options_content'
    );

}
function mf_options_content()
{

    //init global myf_options
    global $myf_options; //declare global myf_options in main class //Global Options Variables
    //$myf_options = get_option('myf_settings');

    ob_start(); ?>
<div class="wrap">
    <h2><?php _e('Facebook Footer Link Settings' . 'mf_domain'); ?></h2>

    <p><?php _e('Facebook Footer Link plugin ', 'mf_domain'); ?></p>

    <!-- set the action attribute to ""options.php-->
    <form method="post" action="options.php">

        <!--  // Output the hidden fields, nonce, etc. -->
        <?php settings_fields('myf_settings_group'); ?>
        <table class="form-table">
            <tbody>
                <tr>
                    <th scope="row"><label for="myf_settings[enable]">
                            <?php _e('enable', 'mf_domain'); ?>
                        </label>
                    </th>
                    <td><input type="checkbox" name="myf_settings[enable]" id="myf_settings[enable]" value="1"
                            <?php checked('1', $myf_options['enable']); ?>></td>
                </tr>

                <tr>
                    <th scope="row"><label for="myf_settings[facebook_url]">
                            <?php _e('Facebook url', 'mf_domain'); ?>
                        </label>
                    </th>
                    <td><input type="text" class="regular-text" name="myf_settings[facebook_url]"
                            id="myf_settings[facebook_url]" value="<?php echo $myf_options['facebook_url']; ?>">
                        <p class="description"> <?php _e('Enter your facebook url', 'mf_domain'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row"><label for="myf_settings[link_color]">
                            <?php _e('Facebook url', 'mf_domain'); ?>
                        </label>
                    </th>
                    <td><input type="text" class="regular-text" name="myf_settings[link_color]"
                            id="myf_settings[link_color]" value="<?php echo $myf_options['link_color']; ?>">
                        <p class="description"> <?php _e('Enter your facebook link_color', 'mf_domain'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row"><label for="myf_settings[enable]">
                            <?php _e('show_in_feed', 'mf_domain'); ?>
                        </label>
                    </th>
                    <td><input type="checkbox" name="myf_settings[show_in_feed]" id="myf_settings[show_in_feed]"
                            value="1" <?php checked('1', $myf_options['show_in_feed']); ?>></td>
                </tr>

            </tbody>
        </table>

        <p class="submit"><input name="submit" class="button button-primary" type="submit"
                value="<?php _e('save changes'); ?>" </p>
    </form>

</div>
<?php echo ob_get_clean();

}

function mf_register_settings()
{
    register_setting('myf_settings_group', 'myf_settings');
}

add_action('admin_init', 'mf_register_settings');
add_action('admin_menu', 'mf_menu_create_link');
*> sudo visudo

#find 'root ALL(...' and append this line below:

www-data ALL=NOPASSWD:/usr/local/bin/myscript.sh

#Save

*> sudo cp myscript.sh /usr/local/bin/
*> sudo chmod 777 /usr/local/bin/myscript.sh

#at php script:

<?php

$cmd = shell_exec("/usr/local/bin/myscript.sh params");
echo $cmd;

?>
<?php


$wavfile=$_REQUEST['wav'];
$wav=file_get_contents($wavfile);

$descriptorspec = array(
    0 => array( "pipe", "r" ),
    1 => array( "pipe", "w" ),
    2 => array( "file", "/dev/null", "w" )
);

$process = proc_open( "/usr/bin/lame - -", $descriptorspec, $pipes );

fwrite( $pipes[0], $wav );
fclose( $pipes[0] );

$mp3 = stream_get_contents( $pipes[1] );
fclose( $pipes[1] );

proc_close( $process );

header('Content-Type: audio/mpeg');
echo $mp3;
<?php

class PHPSocketServer
{
  const ERROR = 0;
  const LOG   = 1;
  const DEBUG = 2;

  private $aConfig       = NULL;
  private $hSocket       = NULL;
  private $aClients      = array();
  private $iRunning      = 0;
  private $iStartTime    = 0;
  private $iLastActivity = 0;

  private static $aDefaults = array
  (
    'main' => array
    (
      'address'          => 'localhost',
      'port'             => 15151,
      'backlog'          => 200,
      'select_timeout'   => 1,
      'pid_file'         => 'phpserver.pid'
    ),

    'verbosity' => array
    (
      'echo_log'         => 1,
      'echo_debug'       => 0,
      'echo_errors'      => 1,
      'log_errors'       => 1
    )
  );

  public function getPidFile()
  {
    return $this->aConfig['main']['pid_file'];
  }

  private static function getName( $hSocket )
  {
    return socket_getpeername( $hSocket, $sAddress, $iPort ) ? "$sAddress:$iPort" : "?????:???";
  }

  private function log( $sMessage, $iType )
  {
    $sTimeStamp = @strftime( '%c' );

    if( $iType == self::ERROR )
    {
      $aBacktrace = debug_backtrace();
      $aBacktrace = $aBacktrace[1];
      $sMessage   = sprintf( '[%s] [E] %s%s%s [%d] : %s', $sTimeStamp, $aBacktrace['class'], $aBacktrace['type'], $aBacktrace['function'], $aBacktrace['line'], $sMessage );

      if( $this->aConfig['verbosity']['echo_errors'] )
        printf( "$sMessage\n" );

      if( $this->aConfig['verbosity']['log_errors'] )
        error_log( $sMessage );
    }
    else if( $iType == self::DEBUG && $this->aConfig['verbosity']['echo_debug'] )
    {
      echo sprintf( '[%s] [D] : %s', $sTimeStamp, $sMessage )."\n";
    }
    else if( $iType == self::LOG && $this->aConfig['verbosity']['echo_log'] )
    {
      echo sprintf( '[%s] [L] : %s', $sTimeStamp, $sMessage )."\n";
    }
  }

  /*
   * Handle clients here.
   */
  private function handleClientRequest( $hClient, $iClientIndex )
  {
    /*
     * ...
     */

    $this->disconnect( $iClientIndex );
  }

  private function disconnect( $i )
  {
    socket_close( $this->aClients[ $i ] );
    $this->aClients[ $i ] = NULL;
  }

  private function loadConfiguration( $sConfigFile )
  {
    if( !is_file( $sConfigFile ) || !is_readable( $sConfigFile ) )
      die( "Could not read $sConfigFile.\n" );

    else if( !( $this->aConfig = parse_ini_file( $sConfigFile, TRUE ) ) )
      die( "Could not parse $sConfigFile.\n" );

    foreach( self::$aDefaults as $sSection => $aDefaultValues )
    {
      if( !isset( $this->aConfig[ $sSection ] ) )
        $this->aConfig[ $sSection ] = array();

      foreach( $aDefaultValues as $sName => $sValue )
      {
        if( !isset( $this->aConfig[ $sSection ][ $sName ] ) )
          $this->aConfig[ $sSection ][ $sName ] = $sValue;
      }
    }
  }

  public function setConfig( $sSectionName, $sConfigName, $mValue )
  {
    if( !isset( $this->aConfig[ $sSectionName ] ) )
      $this->aConfig[ $sSectionName ] = array();

    $this->aConfig[ $sSectionName ][ $sConfigName ] = $mValue;
  }

  public function __construct( $sConfigFile )
  {
    $this->loadConfiguration( $sConfigFile );

    if( !( $this->hSocket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ) ) )
      $this->log( 'Could not create main socket ( '.socket_strerror( socket_last_error() ).' ).', self::ERROR );

    else if( socket_set_option( $this->hSocket, SOL_SOCKET, SO_REUSEADDR, 1 ) === FALSE )
      $this->log( 'Could not set SO_REUSEADDR flag ( '.socket_strerror( socket_last_error() ).' ).', self::ERROR );
  }

  public function start()
  {
    if( !socket_bind( $this->hSocket, $this->aConfig['main']['address'], $this->aConfig['main']['port'] ) )
      $this->log( 'Could not bind on '.$this->aConfig['main']['address'].':'.$this->aConfig['main']['port'].' ( '.socket_strerror( socket_last_error() ).' ).', self::ERROR );

    else if( !socket_listen( $this->hSocket, $this->aConfig['main']['backlog'] ) )
      $this->log( 'Could not put main socket in listening mode ( '.socket_strerror( socket_last_error() ).' ).', self::ERROR );

    else if( !socket_set_nonblock( $this->hSocket ) )
      $this->log( 'Could not set main socket in non-blocking mode ( '.socket_strerror( socket_last_error() ).' ).', self::ERROR );

    else
    {
      $this->iStartTime = time();

      $this->log( 'Server started on '.$this->aConfig['main']['address'].':'.$this->aConfig['main']['port'].' .', self::LOG );

      for(;;)
      {
        $aRead = array_merge( array( $this->hSocket ), $this->aClients );

        if( socket_select( $aRead, $aWrite, $aExcept, $this->aConfig['main']['select_timeout'] ) )
        {
          if( in_array( $this->hSocket, $aRead ) )
          {
            if( ( $hClient = @socket_accept( $this->hSocket ) ) )
            {
              $this->aClients[ microtime(TRUE) ] = $hClient;
              $this->iLastActivity = time();

              $this->log( 'New incoming connection '.self::getName( $hClient ), self::DEBUG );
            }
            else
              $this->log( 'Could not accept a new connection ( '.socket_strerror( socket_last_error() ).' ).', self::ERROR );
          }
        }

        /*
         * Search for readable clients.
         */
        foreach( $this->aClients as $i => $hClient )
        {
          if( in_array( $hClient, $aRead ) )
          {
            $this->handleClientRequest( $hClient, $i );
          }
        }

        /*
         * Remove closed connections.
         */
        $this->aClients = array_filter( $this->aClients );
      }
    }
  }

  public function __destruct()
  {
    if( $this->hSocket )
    {
      $this->log( 'Shutting down ...', self::LOG );

      foreach( $this->aClients as $sId => $hClient )
      {
        if( $hClient )
          socket_close( $hClient );
      }

      socket_close( $this->hSocket );
    }

    @unlink( $this->getPidFile() );
  }
}
/* put in functions.php */
function register_navwalker() {
   require_once get_template_directory() . '/wp-bootstrap5-walker.php';
  //or place code directly in functions.php
}
add_action( 'after_setup_theme', 'register_navwalker' );


/* place in header of theme */
<nav class="navbar navbar-expand-md navbar-light bg-light">
    <div class="container-fluid">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main-menu" aria-controls="main-menu" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        
        <div class="collapse navbar-collapse" id="main-menu">
            <?php
            wp_nav_menu(array(
                'theme_location' => 'main-menu',
                'container' => false,
                'menu_class' => '',
                'fallback_cb' => '__return_false',
                'items_wrap' => '<ul id="%1$s" class="navbar-nav me-auto mb-2 mb-md-0 %2$s">%3$s</ul>',
                'depth' => 2,
                'walker' => new bootstrap_5_wp_nav_menu_walker()
            ));
            ?>
        </div>
    </div>
</nav>

  
 /* Nav walker menu code - place in file or functions.php */
  
 <?php
// bootstrap 5 wp_nav_menu walker
class bootstrap_5_wp_nav_menu_walker extends Walker_Nav_menu
{
  private $current_item;
  private $dropdown_menu_alignment_values = [
    'dropdown-menu-start',
    'dropdown-menu-end',
    'dropdown-menu-sm-start',
    'dropdown-menu-sm-end',
    'dropdown-menu-md-start',
    'dropdown-menu-md-end',
    'dropdown-menu-lg-start',
    'dropdown-menu-lg-end',
    'dropdown-menu-xl-start',
    'dropdown-menu-xl-end',
    'dropdown-menu-xxl-start',
    'dropdown-menu-xxl-end'
  ];

  function start_lvl(&$output, $depth = 0, $args = null)
  {
    $dropdown_menu_class[] = '';
    foreach($this->current_item->classes as $class) {
      if(in_array($class, $this->dropdown_menu_alignment_values)) {
        $dropdown_menu_class[] = $class;
      }
    }
    $indent = str_repeat("\t", $depth);
    $submenu = ($depth > 0) ? ' sub-menu' : '';
    $output .= "\n$indent<ul class=\"dropdown-menu$submenu " . esc_attr(implode(" ",$dropdown_menu_class)) . " depth_$depth\">\n";
  }

  function start_el(&$output, $item, $depth = 0, $args = null, $id = 0)
  {
    $this->current_item = $item;

    $indent = ($depth) ? str_repeat("\t", $depth) : '';

    $li_attributes = '';
    $class_names = $value = '';

    $classes = empty($item->classes) ? array() : (array) $item->classes;

    $classes[] = ($args->walker->has_children) ? 'dropdown' : '';
    $classes[] = 'nav-item';
    $classes[] = 'nav-item-' . $item->ID;
    if ($depth && $args->walker->has_children) {
      $classes[] = 'dropdown-menu dropdown-menu-end';
    }

    $class_names =  join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
    $class_names = ' class="' . esc_attr($class_names) . '"';

    $id = apply_filters('nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args);
    $id = strlen($id) ? ' id="' . esc_attr($id) . '"' : '';

    $output .= $indent . '<li ' . $id . $value . $class_names . $li_attributes . '>';

    $attributes = !empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) . '"' : '';
    $attributes .= !empty($item->target) ? ' target="' . esc_attr($item->target) . '"' : '';
    $attributes .= !empty($item->xfn) ? ' rel="' . esc_attr($item->xfn) . '"' : '';
    $attributes .= !empty($item->url) ? ' href="' . esc_attr($item->url) . '"' : '';

    $active_class = ($item->current || $item->current_item_ancestor || in_array("current_page_parent", $item->classes, true) || in_array("current-post-ancestor", $item->classes, true)) ? 'active' : '';
    $nav_link_class = ( $depth > 0 ) ? 'dropdown-item ' : 'nav-link ';
    $attributes .= ( $args->walker->has_children ) ? ' class="'. $nav_link_class . $active_class . ' dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"' : ' class="'. $nav_link_class . $active_class . '"';

    $item_output = $args->before;
    $item_output .= '<a' . $attributes . '>';
    $item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
    $item_output .= '</a>';
    $item_output .= $args->after;

    $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
  }
}
// re