From: William Desportes <williamdes@wdes.fr>
Date: Sat, 18 Mar 2023 15:51:28 +0100
Subject: Fix memorylimit warning

I did not change the system_message part as it changes the message,  it's not needed for this patch

Ref: https://github.com/leenooks/phpLDAPadmin/pull/180#discussion_r1141029893

Origin: upstream
Forwarded: https://github.com/leenooks/phpLDAPadmin/commit/15cc6f538203de858093a69b7f84ec7d20f4c4d6
---
 lib/config_default.php |  2 +-
 lib/functions.php      | 35 +++++++++++++++++++++++++++++------
 2 files changed, 30 insertions(+), 7 deletions(-)

diff --git a/lib/config_default.php b/lib/config_default.php
index 121d743..ea776b2 100644
--- a/lib/config_default.php
+++ b/lib/config_default.php
@@ -504,7 +504,7 @@ class Config {
 
 		$this->default->session['memorylimit'] = array(
 			'desc'=>'Set the PHP memorylimit warning threshold.',
-			'default'=>24);
+			'default'=>'24M');
 
 		$this->default->session['timelimit'] = array(
 			'desc'=>'Set the PHP timelimit.',
diff --git a/lib/functions.php b/lib/functions.php
index 367385c..8e8c63a 100644
--- a/lib/functions.php
+++ b/lib/functions.php
@@ -332,16 +332,39 @@ function check_config($config_file) {
 	$config->setServers($servers);
 
 	# Check the memory limit parameter.
-	if ((ini_get('memory_limit') > -1) && ini_get('memory_limit') < $config->getValue('session','memorylimit'))
-		system_message(array(
-			'title'=>_('Memory Limit low.'),
-			'body'=>sprintf('Your php memory limit is low - currently %s, you should increase it to atleast %s. This is normally controlled in /etc/php.ini.',
-				ini_get('memory_limit'),$config->getValue('session','memorylimit')),
-			'type'=>'error'));
+	$limit = memory_str_to_int(ini_get('memory_limit'));
+	if ($limit != -1) {
+		$threshold = memory_str_to_int($config->getValue('session','memorylimit'));
+		if ($limit < $threshold) {
+			system_message(array(
+				'title'=>_('Memory Limit low.'),
+				'body'=>sprintf('Your php memory limit is low - currently %s, you should increase it to atleast %s. This is normally controlled in /etc/php.ini.',
+					ini_get('memory_limit'),$config->getValue('session','memorylimit')),
+				'type'=>'error'));
+
+		}
+	}
 
 	return $config;
 }
 
+/**
+ * Converts shorthand memory notation string to an integer that represents the
+ * given amount in bytes (ie. "128M" -> 134217728).
+ *
+ * @param string $value
+ * @return int
+ */
+function memory_str_to_int(string $value) {
+    $value = trim(strtolower($value));
+    if (intval($value) > 0 && preg_match('/^(\d+)([kmg])?$/', $value, $match, PREG_UNMATCHED_AS_NULL)) {
+        [$int, $mod] = [intval($match[1]), $match[2]];
+        $pow = [NULL => 0, 'k' => 1, 'm' => 2, 'g' => 3][$mod];
+        return $int * 1024 ** $pow;
+    }
+    return intval($value);
+}
+
 /**
  * Commands available in the control_panel of the page
  *
