php – DateTime Extension for entering historical dates, i.e. birthdays

This class is intended to fulfill these requirements:

  1. Output in Y-m-d H:i:s format
  2. Allow dates to be entered as m-d-Y or m-d-y
  3. Complain if an invalid birthdate is entered (i.e., in the future or otherwise)
  4. Allow simpler, friendlier coding without typing a lengthy DateTime instantiation
<?php
/**
 * CustomDateTime with historical conversion and statically called methods
 *
 * European order d-m-y is not supported, and assumed to be m-d-Y.  
 * (converted to American m/d/y)
 * 
 * Adds `historical()` method which throws a range exception if a date is not 
 * in the past. YY dates are forced to the past.
 * 
 * Adds several static methods for easier writing and less cognitive effort
 * (CustomDateTime::now() vs (new DateTim())->format('Y-m-d H:i:s'))
 *
 */
class CustomDateTime extends DateTime 
{

    /**
    * Holds the original constructor string
    * @var string
    */
    public $time;

    /**
     * __construct accepts exactly the same parameters as the DateTime object
     *
     * European order d-m-y is not supported, and m-d-Y is converted to m/d/Y.
     * 
     * @param string            $time     Just about any English textual datetime description
     * @param DateTimeZone|null $timezone A DateTimeZone object representing the timezone of $time.
     */
    public function __construct(string $time="now", DateTimeZone $timezone = null) 
    {
        $this->time = str_replace(
          ('-','.'), 
          '/', 
          substr($time, 0, 10)
        ) . substr($time, 10 );
        parent::__construct($this->time, $timezone);
    }

    /**
     * Convert to Historical Date (static method)
     *
     * Static method to access instantiated version (historical())
     * 
     * @param  string $date m/d/Y, Y-m-d, '', null
     * @return string       Y-m-d or null if no value given
     */
    public static function asHistorical($date) : ?string 
    {
        if(empty($date)) { return null; }
        return (new CustomDateTime($date))->historical()->format('Y-m-d');
    }

    /**
     * Historical (instantiated) 
     * 
     * Originally was intended to prevent birthdates in the future.
     *
     * Silently corrects 2 digit year to a date in the past
     * Throws `RangeException` if date is more than 100 years in the future.
     *
     * @return CustomDateTime instance, which allows chaining of methods
     */
    public function historical() : CustomDateTime
    {
        $now = (new DateTime())->format('Y-m-d');

        // if a two-digit year was converted to the future, subtract 100 years
        if(
            preg_match("@^(0-9){1,2}/(0-9){1,2}/(0-9){2}$@", $this->time) &&
            $this->format('Y-m-d') > $now
        ) {
            $this->modify('-100 years');
        }

        if( $this->format('Y-m-d') > $now) {
            throw new RangeException('Date is too far in the future');
        }

        return $this;
    }

    /**
     * Return Database Safe date
     * 
     * This avoids passing '' to database, replacing it with null
     *
     * @param  string $date m/d/Y, Y-m-d, '', null
     * @return string       Y-m-d or null if no value given
     */
    public static function dbSafe($date) : ?string
    {
        if(empty($date)) { return null; }
        return (new CustomDateTime($date))->format('Y-m-d');
    }


    public static function now() : string
    {
        return (new DateTime())->format('Y-m-d H:i:s');
    }

    public static function today() : string
    {
        return (new DateTime())->format('Y-m-d');
    }
}
?>
Examples:


Short version: historical date... 3-4-30 = <?= CustomDateTime::asHistorical('3-4-30') ?>

Long version: historical date.... 3-4-30 = <?= (new CustomDateTime('3-4-30'))->historical()->format('Y-m-d') ?>


DateTime uses European format.... 3-4-30 = <?= (new DateTime('3-4-30'))->format('m/d/Y') ?>

DateTime splits century.......... 3-4-30 = <?= (new DateTime('3/4/30'))->format('m/d/Y') ?>


Bonus:

Easily get "now"................. <?= CustomDateTime::now() ?>

php – How to display a woocomerce group product correctly?

I am building a Woocomerce site with the GIOIA theme and it contains a grouped product named “Ensemble Wendy”.
As far as I know, grouped product in Woocomerce should be displayed like this : it lets you choose all the options for the childs products and lets you add them to the cart in the same page.

Unexpectidely, mine looks like this: it shows buttons witch links to the child products’ individual pages with no option to add anything to the cart.

I have checked Woocomerce’s official documentation for grouped products and apparently I don’t thing I have done anything different from what’s in the tutorial so I am confused.

I searched in Woocomerce’s settings as well as in the theme’s setting but I didn’t find anything who could correct the problem.

I searched for solutions online and I found a plugin called WPC grouped product which normaly should give the result that I want but I get this instead: the child products are displayed but there is no place where I can choose the variations for the products and this prevents me to add them to the cart. I inspected the page with the Inspector though, and there seems to be a select element there but it’s hidden. I’ve searched everywhere in the settings if I could find anything to correct that without success so I decided to force everything by just overriding the css with a custom code :

.woosg-products .woosg-product form.variations_form .variations .variation .select select {
    display: block !important;
}

And then, it displays the result I was looking for and finally allows me to add something to the cart.

Now the problem is that, after I select some options and Add them to the cart, the grouped product seems to be successfully added but it hasn’t retained the price or any other information about the product : Here is a screenshoot.

Maybe there is a way to correct through code but I am still not good enough to touch a theme’s code source yet.

I’ve looked everywhere if anyone had a similar problem but I didn’t find anything helpful.

Thanks for anyone who would help me.

I need a way to convert youtube videos into mp3 (php script/api)

Hi,

I have a php script (https://codecanyon.net/item/bemusic-music-streaming-engine/13616699) and I’m searching something to convert&download the youtube videos that are playing into mp3 files.

I found this apis/script, could anyone help me?
SEMrush

http://www.youtubeinmp3.com/api/
http://www.convert2mp3.cc/api/
https://mp3skull.onl/en/webmaster/api/
http://www.youtubemp3script.com/

 

php – Subtração entre tabelas diferentes

adms_estoque Valores
id 1
codigo_produto 1422
nome_produto Mouse
quantidade 10
valor_unidade 2.55
descricao NULL
created NULL
modified NULL

Preciso salvar nesta tabela adms_estoque na linha quantidade a subtração com a tabela adms_retirada_estoque da linha quantidade_retirada

adms_retirada_estoque valores
id 1
codigo_produto 1422
nome_produto Mouse
quantidade 10
numero_chamado 55500
quantidade_retirada 5
created NULL
modified NULL

$result_cad_menu = “INSERT INTO adms_retirada_estoque (codigo_produto, nome_produto, quantidade, valor_unidade, numero_chamado, quantidade_retirada, created) VALUES (
‘” . $dados_validos(‘codigo_produto’) . “‘,
‘” . $dados_validos(‘nome_produto’) . “‘,
‘” . $dados_validos(‘quantidade’) . “‘,
‘” . $dados_validos(‘valor_unidade’) . “‘,
‘” . $dados_validos(‘numero_chamado’) . “‘,
‘” . $dados_validos(‘quantidade_retirada’) . “‘,
NOW())”;

    $result_quantidade = "SELECT quantidade FROM adms_estoque LIMIT 1";
    $resultado_quantidade = mysqli_query($conn, $result_quantidade);
    $row_quantidade = mysqli_fetch_assoc($resultado_quantidade);
    $quantidade = $row_quantidade('quantidade') - 
    $row_quantidade('quantidade_retirada') ;
    
    
    $result_pg_up = "UPDATE adms_estoque SET
    quantidade = '" . $dados_validos('quantidade') . "'";

Tentei isso, mas não altera nada na tabela adms_estoque insere na tabela adms_retirada_estoque mas não consigo Subtrair e atualizar a quantidade!

PHP HTML form submit fails in frame

I am using PHP to generate an HTML page with a form. The form has a submit tag. The calling page is in a frame. When I click the submit button, nothing happens. I have done this a thousand times and it has always just worked. Can someone spot what I am doing wrong? Here is a capture of the “View Source” for the page:

<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 3.2 Final//EN'>
<html>
<head> 
<title>'menu'</title>
</head>
<BODY TEXT='#000000' BGCOLOR='#34ebc6' LINK='#0000ff' VLINK='#551a8b' ALINK='#ff0000'>

<center><h2>Shopping List</h2></center>
   <br>
<form method="post" action="addItem.php">
  Add Item to shopping items: 
  <input type="text" name="item" > </input>
  <input type="text" name="catigory" > </input>
  <input type="text" name="stores" > </input>
  <input type="submit" value="ADD" > </input>
 </form>
<br>
</body>
</html>

PHP design pattern – Decorator

I try to learn design patterns. First of all I try learn decorator. My code:
Interface
<?php declare(strict_types=1);

interface Product
{
    public function getPrice();

    public function getDescription();
}

BaseProduct class

<?php declare(strict_types=1);

class BaseProduct implements Product
{
    public function getPrice()
    {
        return 20;
    }

    public function getDescription()
    {
        return "This is base product";
    }
}

ProductDecorator

<?php

abstract class ProductDecorator implements Product
{
    protected Product $product;

    public function __construct(Product $product)
    {
        $this->product = $product;
    }

    abstract public function getPrice();

    abstract public function getDescription();
}

SportProductDecorator

<?php declare(strict_types=1);

class SportProductDecorator extends ProductDecorator
{
    public function getPrice()
    {
        return $this->product->getPrice() + 20;
    }

    public function getDescription()
    {
        return "THis is product from Sport category";
    }
}

HomeProductDecorator

    <?php declare(strict_types=1);
    
    class HomeProductDecorator extends ProductDecorator
    {
        public function getPrice()
        {
            return $this->product->getPrice() + 50;
        }
    
        public function getDescription()
        {
            return "This is product from Home category";
        }

}

Is this a well-applied decorator pattern? I’ve seen a lot of tutorials, but a lot of people do it in a completely different way: /

css – PHP – Strange Output

I don’t know why but with this code it only prints 100 friends. I am new to php so sorry if my mistakes are dumb 🙂

$ids=array();

$url = "http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=mykey&steamid=".$other_steamid."&relationship=friend";
$data= file_get_contents( $url );
            
            
$json = json_decode( $data );
$ids=array();
            
/* just grab the IDs and add to array - correct format to access records??? */
foreach( $json->friendslist->friends as $obj ){
        $ids()=$obj->steamid;
}

$steamidcount = count($ids);
            
/* split the IDs into chunks of 100 */
$chunks=array_chunk( $ids, 100 );
            
/* send a request per chunk of 100 */
foreach( $chunks as $chunk ){  
         $url=sprintf('https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=mykey&steamids=%s',implode(',',$chunk));
         $curl = curl_init( $url );
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         $res=curl_exec( $curl );
         if ( $res ){
              $data=json_decode($res,true);

              for ($x = 0; $x <= count($data('response')('players')); $x++) {
                   $steamname = $data('response')('players')($x)('personaname');
                   $steamprofileurl = $data('response')('players')($x)('profileurl');
                   $friendimage = $data('response')('players')($x)('avatar');
            
                   $friendimageData = base64_encode(file_get_contents($friendimage));
           
                   echo '<img class="other_friendsteamimage" src="data:image/jpeg;base64,'.$friendimageData.'">';
                   echo "<a class='other_friendlabel' href='$steamprofileurl'>$steamname</a>";
                   echo "<br>";
              } 
          }
                curl_close($curl);
}

So basically what it does if you don’t want to bother reading it through and understanding it is that it grabs all the steam ids of a certain steam users friends. Then it splits them into arrays with 100 elements (each element containing a steam id), because we can only pass GetPlayerSummaries 100 steam ids at a time. But when I try to output some data it only outputs data from 100 friends. I tried with a steam user that had 137 friends. I got 2 arrays:
array 0: contained 100 elements
array 1: contained 37 elements
So basically it only prints the first array. Any help?

php – How to add plugin options tabs as submenu items, and give them a current class

I have a custom plugin that is working great. I have set up multiple tabs that include content on each. I have now added each of the tabs as submenu items successfully, but I’m having trouble adding the “current” class to them when on that tab.

Here is my ode:

add_action( 'admin_menu', 'eri_Add_My_Admin_Link' );
function eri_Add_My_Admin_Link() {
    // The 'slug'
    $slug = 'eri-webtools-plugin/includes/admin/eri-admin-page.php';
    
    // Get notification count
    $warning = eriErrorCount();
    $notif = '';
    if ($warning > 0) {
        $notif = '<span class="awaiting-mod">'.$warning.'</span>';
    }
    
    // Add a new top level menu link to the ACP
    add_menu_page(
        'ERI Web Tools', // Title of the page
        $warning ? 'ERI Tools '.$notif : 'ERI Web Tools', // Text to show on the menu link
        'manage_options', // Capability requirement to see the link
        $slug, // The 'slug' - file to display when clicking the link
        '',
        plugins_url( 'eri-webtools-plugin/includes/admin/star15x15.png' ), // The admin menu icon
        4
    );
    
    // Add submenu
    global $submenu;
    $tab_path = '/wp-admin/admin.php?page=eri-webtools-plugin%2Fincludes%2Fadmin%2Feri-admin-page.php&tab=';
    // Welcome
    $permalink1 = '/wp-admin/admin.php?page=eri-webtools-plugin%2Fincludes%2Fadmin%2Feri-admin-page.php';
    $submenu($slug)() = array( 'Welcome', 'manage_options', $permalink1 );
    // Settings
    $permalink2 = $tab_path.'settings';
    $submenu($slug)() = array( 'Settings', 'manage_options', $permalink2 );
    // Debug
    $permalink3 = $tab_path.'debug';
    $submenu($slug)() = array( 'Debug', 'manage_options', $permalink3 );
    
    //call register settings function
    add_action( 'admin_init', 'register_eri_plugin_settings' );
}

Any suggestions?

php – Ativar Botão sem Clicar

sou novo por aqui e (desculpem qualquer erro na postagem), ficarei grato se conseguirem me ajudar. Preciso que a função de um botão (que é disparar o cronometro de uma tarefa) seja executada sem clicar ao adicinar uma data, ou ao mudar o status de uma tarefa:

billed == 0){
$is_assigned = $task->current_user_is_assigned;
if(!$this->tasks_model->is_timer_started($task->id)) { ?>

        <p class="no-margin pull-left"<?php if(!$is_assigned){ ?> data-toggle="tooltip" data-title="<?php echo _l('task_start_timer_only_assignee'); ?>"<?php } ?>>
           <a href="#" class="mbot10 btn<?php if(!$is_assigned || $task->status == Tasks_model::STATUS_COMPLETE){echo ' disabled btn-default';}else {echo ' btn-success';} ?>" onclick ="timer_action(this, <?php echo $task->id; ?>); return false;">
           <i class="fa fa-clock-o"></i> <?php echo _l('task_start_timer');
           
           
           ?> 

commerce – Stripe php implementation

I tried to install the Stripe module to use it in my commerce shop on my Drupal 9 site. However, this yielded many errors so I decided to implement Stripe using php and based on this tutorial :
https://phppot.com/php/stripe-payment-gateway-integration-using-php/
Everything works fine. But I have a small question. My payments are in euros and I don’t want to put the following hidden mentioned in step 2.

<input type='hidden' name='amount' value='0.5'> <input type='hidden'
        name='currency_code' value='USD'> <input type='hidden'
        name='item_name' value='Test Product'> <input type='hidden'
        name='item_number' value='PHPPOTEG#1'>

So I decided to put instead :

$total_price = $order->getTotalprice()->getNumber();
$currency_code = $order->getTotalprice()->getCurrencyCode(); //which is in euros for all orders
$order_number=$order->getOrderNumber();

$_POST('amount') = $total_price;
$_POST('currency_code') = $currency_code;
$_POST('item_name')  = 'Order' ;
$_POST('item_number') = $order_number;

The result was successfully displayed in my Stripe Dashboard within the all payments section.
My order total is 12.5 euros. So I got 12.5 Euros (EUR) in my dashboard all payment section.
However, in the all transactions tab, I got net: 14.32 $ , amount : 15.06 $ , fee : 0.74 $ and a date that is in the future ! In addition to that 15.06 $ does not correspond to 12.5 euros because, in the Stripe conversion estimate page 12.5 euros yielded 15.21 $.
Is there anything wrong in what I did ??