How to send email to queue in Magento 1.9?

I need to send the emails to the queue “table core_email_queue”.
But my code doesnt work.
I dont know why

$emailTemplate = Mage::getModel('core/email_template');
$emailTemplate->load(Mage::getStoreConfig('emailreminder/general/emailreminder_template'));
$emailTemplateVariables = [];
$emailTemplate->setSenderName($email);
$emailTemplate->setSenderEmail($email);

$emailQueue = Mage::getModel('core/email_queue');
$emailTemplate->setQueue($emailQueue)->send($email, $email, $emailTemplateVariables);

(70007)The timeout specified has expired: [client ] AH01075: Error dispatching request to : (polling),

I have a python script which takes some time to execute. This is called on:

add_action('save_post', 'mysave',10,2);

on wordpress. I am continuously getting the same error:

(70007)The timeout specified has expired: [client 192.168.1.116:51376] AH01075: Error dispatching request to : (polling),

Most probably its because I need to increase some execution time properties. Any idea how?

How to get threads working in PHP on Windows?

I want to run PHP Thread class code on Windows. I tried some manual installation guides like e.g. this one but they didn’t work. PHP cannot load the pthreads DLL even though the file exists at this location:

PHP Warning:  PHP Startup: Unable to load dynamic library 'php_pthreads.dll' (tried: C:xamppphpextphp_pthreads.dll (The specified module could not be found), C:xamppphpextphp_php_pthreads.dll.dll (The specified module could not be found)) in Unknown on line 0

I downloaded php_pthreads-3.1.6-7.0-ts-vc14-x64.zip. My PHP version is: PHP 8.1.6 (cli) (built: May 11 2022 08:55:59) (ZTS Visual C++ 2019 x64). Generally I’m still not entirely sure which pthread version to select since there are many choices here. Are any of them even going to work since they seem a bit outdated? My phpinfo says:

Can I maybe just use Windows threads since they are already available on my system?

After the pthreads installation, when I run my Thread class example code

<?php

class AsyncOperation extends Thread
{
    public function __construct($arg)
    {
        $this->arg = $arg;
    }

    public function run()
    {
        if ($this->arg) {
            printf("Hello %sn", $this->arg);
        }
    }
}

$thread = new AsyncOperation("World");
if ($thread->start())
    $thread->join();
?>

I still get the warning above and the following error:
PHP Fatal error: Uncaught Error: Class "Thread" not found

What am I doing wrong? Is there maybe a way to do it with less “manual” effort in e.g. 1 composer command or an easier way to get threading working?

Regex: Find only full words? [closed]

I have different titles and try to extract the models.

The models are mostly one letter and two numbers or one letter, two numbers and one letter.

I would like to consider only words that have no more than 3 or 4 digits.

  1. BMW 535d Touring F11N
  2. BMW M550dX Touring F11
  3. BMW 520d Touring G31

Regex: [A-Za-z]{1}[0-9]{2}

Result:

  1. F11 => Must be F11N
  2. M55, F11 => Must be F11
  3. G31 => correct

How can I prepare the regex so that only words with 4 characters are considered?

PHP 8.1 DOMDocument serialization

I’m trying to make the following class compatible with native PHP serialization, specifically when running on PHP 8.1.

class SerializableDomDocument extends DOMDocument
{
    private $xmlData;

    public function __sleep(): array
    {
        $this->xmlData = $this->saveXML();
        return ['xmlData'];
    }

    public function __wakeup(): void
    {
        $this->loadXML($this->xmlData);
    }
}

It’s all fine and dandy on lower PHP versions, but 8.1 yields Uncaught Exception: Serialization of 'SerializableDomDocument' is not allowed whenever such an object is attempted to be passed to serialize() function. Here’s a sample of the code that would produce such an exception: https://3v4l.org/m8sgc.

I’m aware of the __serialize() / __unserialize() methods introduced in PHP 7.4, but using them doesn’t seem to be helping either. The following piece of code results into the same exception, as can be observed here: https://3v4l.org/ZU0P3.

class SerializableDomDocument extends DOMDocument
{
    public function __serialize(): array
    {
        return ['xmlData' => $this->saveXML()];
    }

    public function __unserialize(array $data): void
    {
        $this->loadXML($data['xmlData']);
    }
}

I’m really baffled by this problem, and would really appreciate any hints. For the time being it seems like the only way forward would be to introduce an explicit normalizer/denormalizer, which would result in a breaking change in the codebase API. I’d like to avoid that.

How do you connect the project that config with virtual domain (http://project.local), locate in /var/www/html/ server in the Android emulator chrome?

I was create PHP project on my local server.
And then config to run via virtual host
e.g project.local
after site is config and enable…

Linux chrome call -> project.local (work)
Android emulator chrome ? 10.0.2.2/project (not work) || project.local (not work)
How to call project.local from android emulator?

How to change value if user changed picture

I want to Gives for Fb_image value 0 only if user changed his profile picture.

if just pressed save settings for something like full name without changing picture it stays same of database.

In this code fb_image = 0even if user didn’t change the picture.

// upload users image
        $filename_image = null;
        if(! empty($_FILES['image']['name']) ) // if image 
        {
            $file_image         = array('folder'=>'users/images', 'input_file'=>'image');
            // update users image
            $filename_image     = $this->file_uploads->upload_file($file_image, 512, 512, 256, 256);
            // through image upload error
            if(!empty($filename_image['error']))
                $this->form_validation->set_rules('image_error', lang('common_image'), 'required', array('required'=>$filename_image['error']));
        }

        if ($this->form_validation->run() === TRUE)
        {
            // save the changes
            $data                       = array();

            // upload image only if selected
            if(!empty($filename_image) && !isset($filename_image['error']))
                $data['image']          = $filename_image;
                $data['fb_image']       = 0 ;
                

            $data['fullname']           = $this->input->post('fullname');
            $data['email']              = $this->input->post('email');
            $data['username']           = $this->input->post('username');
            $data['gender']             = $this->input->post('gender');
            $data['notifications']      = isset($_POST['notifications']) ? 1 : 0;
            $data['apppear_search']     = isset($_POST['apppear_search']) ? 1 : 0;
            $data['anonymous_posts']    = isset($_POST['anonymous_posts']) ? 1 : 0;

How to set quantity of items to buy in Paypal Orders API?

I can create a PayPal Order inside my Laravel Controller like so:

$provider = PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);

$price = '2';
$currency = '';

$order = $provider->createOrder([
    'intent' => 'CAPTURE',
    'purchase_units' => [
        [
            'amount' => [
                'currency_code' => 'EUR',
                'value' => $price
            ],
        ]
    ]
]);

return response()->json($order);

but when I try to add a quantity property (quantity of the same item to be bought):

$provider = PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);

$price = '2';
$currency = '';

$order = $provider->createOrder([
    'intent' => 'CAPTURE',
    'purchase_units' => [
        [
            'amount' => [
                'currency_code' => 'EUR',
                'value' => $price
            ],
            'items' => [
                'name' => 'photo',
                'quantity' => '5'
            ]
        ]
    ]
]);

return response()->json($order);

I’m getting a warning:

click_initiate_payment_reject {err: 'Error: Expected an order id to be passedn    at ht…ng=card,giropay,sepa,sofort&currency=EUR:2:14811)', timestamp: '1657705690794', referer: 'www.sandbox.paypal.com', sdkCorrelationID: 'f857450e442be', sessionID: 'uid_c2bc52c0a2_mdk6mzg6mta', …}

and this error:

Uncaught Error: Expected an order id to be passed
    at https://www.sandbox.paypal.com/smart/buttons?

Am I setting the quantity incorrectly? What’s the right way to do it? I really just want to send the total quantity of purchases, so that it’s displayed in the paypal checkout.

Connect to mysql failed [closed]

Hello i have a problem when im running my webapp php i cannot connect to my database here is the error screenshot

Here is the code

   2) { $logosu = $logobol[1]; } else { $logosu = $logobol[0]; } $site_adi = ucfirst($logosu); $site_adres = $_SERVER['HTTP_HOST']; if(isset($_POST['username'])) { $uname = pd("username"); $paswd = pd("parola"); $ipadres = $_SERVER['REMOTE_ADDR']; $tarayici = $_SERVER['HTTP_USER_AGENT']; $zaman = time(); $kontrol = mysql_query("select * from kullanici where username='$uname' and password='$paswd' and durum='1' and root='0'"); if(mysql_num_rows($kontrol)<1) { header("Location:index.php?fail=1"); } else { $bilgi = mysql_fetch_array($kontrol); if($bilgi['websitesi']!="" && !strstr($site_adres,$bilgi['websitesi'])) { header("Location:index.php?domain=1"); exit(); } $_SESSION['girisbulten'] = $bilgi['bulten']; $_SESSION['betuser'] = $bilgi['id']; $_SESSION['betpass'] = $paswd; mysql_query("insert into login_data (id,login_user,login_ip,login_tarayici,zaman,giris_tip) values ('','$uname','$ipadres','Mobil','$zaman','1')"); if($bilgi['alt_durum']>0) { header("Location:../index.php"); } else { header("Location:anasayfa"); } } } ?>

WordPress – Get Posts with Category data

i have a question about improving my solution.

For my task i build a Gutenberg block which shows the latest 5 Posts. This Posts show also the Category Name in the Frontend part which have different styling each.

so I’m using the get_post() function to get all Posts, but there comes no Categories which is the reason i also used wp_get_post_categories() function.

This works fine , i used a foreach in a foreach to get my results. But it kinda feel Hardcoded especially the checking if Category “News” or “informative” is used is definitely hard coded.

is there a better solution how can i archive it that i can get the Posts with there bonded Post categories?

this was the best i can get for now and it works but im not happy with this solution.

my code:

...

$post = get_posts(
     [
        'posts_per_page' => 5,
     ]
);

...

ob_start();

some echos for html 

...

            foreach ($post AS $p)
            {

                $category = wp_get_post_categories($p->ID);
                foreach ($category AS $cat)
                {
                    echo '<div>';
                    echo '<div class="blog-image">';
                    echo '<img alt="" content="'.get_the_post_thumbnail($p->ID).'">';
                    echo '</div>';
                    echo '<div class="blog-data">';
                    echo '<div class="data-top">';
                    if(get_cat_name((int) $cat) === 'News')
                    {
                        echo '<div class="blog-type"><span class="news">'.get_cat_name((int) $cat).'</span></div>';

                    }elseif (get_cat_name((int) $cat) === 'Informative')
                    {
                        echo '<div class="blog-type"><span class="informative">'.get_cat_name((int) $cat).'</span></div>';
                    }
                    echo '<h3 class="blog-title">'.$p->post_title.'</h3>';
                    echo '</div>';
                    echo '<div class="data-bottom">';
                    echo '<div class="blog-info">';
                    echo '<p class="blog-date">'.date("d F Y", strtotime( $p->post_date)).'</p>';
                    echo '<div class="blog-link"><a href='.$p->guid.' >Read more</a></div> ';
                    echo '</div>';
                    echo '</div>';
                    echo '</div>';
                    echo '</div>';

                }
                echo '<br/>';
            }

...

more echos to close all html tags

    return ob_get_clean();

here is also how it should look:

enter image description here

Rename downloaded file from web at download

I want change a name of downloaded file from web.
For example file with URL:

http://lazynezumi.com/downloads/LazyNezumiPro_Setup.exe

is saved on local disk with its name:

LazyNezumiPro_Setup.exe

But I have extracted from autrors site, that current version of file is: 22.05.23.1042
So I want to have downloaded file name as:

LazyNezumiPro_Setup v22.05.23.1042.exe

How to do it via PHP 7/8? What’s are possibilities?


Currenty I do something similar, I add a SHA-256 to small files. Here are my steps:

  1. url of a file on my blog (localhost) is as this:

    http://127.0.0.1/d.php?f=http://www.compulsivecode.com/images/JPEGtoPDF.zip

  2. a simplified the code of my PHP 7/8 script on localhost Apache web server: p.php is like this:

<?php
set_time_limit(0);

$ip=false;
if(isset($_SERVER['REMOTE_ADDR'])) {
  $ip=($_SERVER['REMOTE_ADDR']=='127.0.0.1')?true:false;
}
if(!$ip) exit;

if(isset($_GET['f'])) {
  if(filter_var($_GET['f'], FILTER_VALIDATE_URL)) {
    $f = htmlspecialchars($_GET["f"]);
  }
}
if(empty($f)) exit;

$search = array(" ","&","$",",","!","@","#","^","(",")","+","=","[","]","<",">");
$replace = array("_","and","S","_","","","","","","","","","","","","");
$f = str_replace($search,$replace,$f);

$ctx = hash_init('sha256');
$n = 0;
$h = fopen($f,"rb");
if($h!==false) {
  while(!feof($h)) { $buf = fread($h,32768); $n += strlen($buf); hash_update($ctx, $buf); }
  fclose($h);
}
$hash = strtoupper(hash_final($ctx));
$path = pathinfo($f);
$filename = $path['filename']. $ver .' ('.$hash.') ['.trim(number_format($n,0,'.',' ')).'].'.$path['extension'];

header("Cache-control: private");
header("Content-type: application/force-download");
header("Content-transfer-encoding: binaryn");
header("Content-disposition: attachment; filename="$filename"");
header("Content-Length: ".$n);
readfile($f);
exit;
?>
  1. then downloaded file on local disk has this name:

    JPEGtoPDF (3589D32E4B42A3297109549A6461B3B27BE6405126F0725234262DB522641A14) [209 018].zip

But what about large files, it is the way?

Getting error with php 7.4 with illuminate devDependency

I’m currently working on a project based on Sage 9 using php 7.4.
When I run npm, it builds fine and runs perfectly except on the site it gives me

Fatal error: Uncaught SymfonyComponentDebugExceptionFatalThrowableError: Call to undefined function array_except() in /Users/admin/sites/myproject/web/app/uploads/cache/85f0de50487ef01844c6bb7aed13133926433f24.php:3 Stack trace: #0 
/Users/admin/sites/myproject/web/app/themes/myproject/vendor/illuminate/view/Engines/PhpEngine.php(43): include() #1 /Users/admin/sites/myproject/web/app/themes/myproject/vendor/illuminate/view/Engines/CompilerEngine.php(59): IlluminateViewEnginesPhpEngine->evaluatePath('/Users/admin/si...', Array) #2 /Users/admin/sites/myproject/web/app/themes/myproject/vendor/illuminate/view/View.php(142): IlluminateViewEnginesCompilerEngine->get('/Users/admin/si...', Array) #3 /Users/admin/sites/myproject/web/app/themes/myproject/vendor/illuminate/view/View.php(125): IlluminateViewView->getContents() #4 /Users/admin/sites/myproject/web/app/themes/myproject/vendor/illuminate/view/View.php(90): IlluminateViewView->renderContents() #5 /Users/admin/sites/myproject/web/app/themes/myproject/vendor/roots/sage-lib/Template/Blade.php(58): Il in /Users/admin/sites/myproject/web/app/uploads/cache/85f0de50487ef01844c6bb7aed13133926433f24.php on line 3`

Here is my composer.json

"require": {
    "php": "^7.4",
    "composer/installers": "~1.9",
    "illuminate/support": "5.6.*",
    "roots/sage-lib": "~9.0.9",
    "soberwp/controller": "~2.1.0",
    "roots/sage-installer": "dev-webpack5#f4a07cb"
  },

I have tried deleting cache, updated composer, and relinked my php with valet with the right php version which is 7.4. Does anyone had the similar issues?

Lumen – Custom Traits for Tests

I’m currently writing feature tests for my application. Most of my tests must be initialized by creating a new User using factory.
I could do set up this with setUp method for each specific test but I thought it would be more convenient to create custom Traits as the specifications may vary between tests.

I’m following this article which, written for Laravel, to create custom traits for tests: https://medium.com/@SlyFireFox/laravel-tips-making-your-own-trait-hooks-for-tests-770f0aeda3c9

With this implementation, the setUpTraits method inside the TestCase.php file returns null and thus I’m unable to call the setUpUser method from the trait.

How should I fix this or is it even possible to set up custom traits for testing purposes with Lumen? I couldn’t find anything on Google.

Underneath is what I’ve tried so far.

Folder structure:

tests/
├── AuthenticationTest.php
├── Support
│   └── Authentication.php
└── TestCase.php

Since Lumen does not use namespacing for tests folder out of the box, I’ve modified composer.json as per following:

...
"autoload-dev": {
    "classmap": [
        "tests/"
    ],
    "psr-4": {
        "Tests\": "tests/"
    }
},
...

Here’s how my TestCase.php file looks like:

<?php

use LaravelLumenTestingTestCase as BaseTestCase;
use TestsSupportAuthentication;

abstract class TestCase extends BaseTestCase
{
    protected $base_path = '/api/v1';
    protected $headers = ['Accept' => 'application/json'];

    public function createApplication()
    {
        return require __DIR__.'/../bootstrap/app.php';
    }

    protected function setUpTraits()
    {   
        $uses = parent::setUpTraits(); // $uses = null
        
        if (isset($uses[Authentication::class])) {
            $this->setUpUser();
        }
    }
}

Here’s my Trait:

<?php

namespace TestsSupport;

use AppModelsUser;

trait Authentication
{
    protected $user;

    public function setUpUser()
    {
        $this->user = User::factory()->create();
    }
}

And here’s my test where I’m trying to call that trait:

<?php

use LaravelLumenTestingDatabaseTransactions;
use TestsSupportAuthentication;

class AuthenticationTest extends TestCase
{
    use DatabaseTransactions;
    use Authentication;
    
    public function testUserAbleToAuthenticateWithValidCredentials() : void
    {
        $this->post(
            $this->base_path . '/auth',
            ['username' => $this->user->username, 'password' => $this->user->password],
            $this->headers
        )->seeStatusCode(200)
         ->seeJsonStructure(['data' => ['token', 'token_type', 'expires_in']]);
    }
}

FDPF table of contents issue with page orientation

I’m using FDPF to generate my PDF document and all’s going well except the Table of Contents extension. The Table of Contents works perfectly IF all pages are the same orientation. In my document, I have a 25 page document and e.g. page 4 and 5 are Landscape, whereas the rest are Portrait.

So when the table of contents is inserted on page 2, it then moves the page numbering forward, but doesn’t fix the orientation. So Page 4 that WAS portrait and Page 5 that WAS landscape is whacked out.

Due to the TOC being added, page 3 now becomes page 4 (portrait) and what was then page 4 now becomes 5 (landscape).

See the issue? Any assistance would be appreciated on a fix — however this definitely seems like an issue with the Table of Contents extension itself.