Auto Description From Tags - php

I'm trying to generate auto description from tags.
The code was working but after updating my site to Laravel 6 in stop working. I need to get it back working.
if( !empty( $request->description ) )
{
$description = Helper::checkTextDb($request->description);
}
else
{
$a_key = explode(",", strtolower($request->tags));
if(count($a_key) == 0)
$description = 'This is a great thing';
else
{
$description_get_keys = '';
foreach ($a_key as &$value)
{
if($value == end($a_key) && count($a_key) != 1)
$description_get_keys = $description_get_keys.' and '.$value.'.';
else if(count($a_key) == 1)
$description_get_keys = $value.'.';
else if (count($a_key) > 1 && $a_key[0] == $value)
$description_get_keys = $value;
else
$description_get_keys = $description_get_keys.', '.$value;
}
$description = 'This is a great thing about '.$description_get_keys;
}
}

I see a couple things that could possibly be an issue, not knowing what came before this code.
I will assume that the $request variable is an instance of Illuminate\Http\Request and that it is available in the function, right?
Try this updated code:
if($request->has('description'))
{
$description = Helper::checkTextDb($request->description);
}
else if ($request->has('tags'))
{
if (strpos($request->tags, ',') === false)
{
$description = 'This is a great thing';
}
else {
$a_key = explode(",", strtolower($request->tags));
$a_count = count($a_key);
$description_get_keys = '';
for ($i = 0; $i < $a_count; $i++)
{
if ($a_count == 1) {
$description_get_keys = "{$a_key[$i]}.";
}
else {
// first
if ($i === 0) {
$description_get_keys = $a_key[0];
}
// last
else if ($i === $a_count - 1) {
$description_get_keys .= " and {$a_key[$i]}.";
}
// middle
else {
$description_get_keys .= ", {$a_key[$i]}";
}
}
}
$description = "This is a great thing about {$description_get_keys}";
}
}
I wrote that quick so hopefully there are no errors.

Related

Value not saving outside foreach loop

I update my code from PHP 5 to PHP 7 and i got problem with foreach loop. I loocked wor answers here, but none is working. Or i dont understand where i have problem
function getStructure($pid = 0, $expand = array(), $alevel = 0)
{
$struct = array();
if ( $alevel > $this->levelCount) $this->levelCount = (int)$alevel;
$str = $this->dbStructure->getStructure($pid);
foreach ($str as &$row)
{
if ($row["type"] == STRUCT_PAGE)
{
$row["editLink"] = "editPage";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_MODULE)
{
$row["editLink"] = "editModule";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_LINK)
{
$row["editLink"] = "editLink";
$row["target"] = "_blank";
}
elseif ($row["type"] == STRUCT_CATALOG)
{
$row["editLink"] = "editCatalog";
$row["target"] = "_self";
}
$row["childrens"] = $this->getStructure((int)$row["id"], $expand, $alevel+1);
if ($row["type"] == STRUCT_CATALOG and isset($row["childrens"][0]["shortcut"]))
{
$row["shortcut"] = $row["childrens"][0]["shortcut"];
$row["target"] = $row["childrens"][0]["type"] == STRUCT_LINK ? "_blank" : "_self";
}
$struct[] = $row;
}
unset($row);
return $struct;
}
All the time $struct is NULL and I need to be multidimensional array
This code by itself is good. Has no problems, only ampersand is not needet. The problem was in different place. Sorry for spam

How to correctly write a foreach for $clientList in TS3AntiVPN application?

I download a TS3AntiVPN but it shoes an error. I use a Linux Server running Debian 9 Plesk installed.
PHP Warning: Invalid argument supplied for foreach() in
/var/www/vhosts/suspectgaming.de/tsweb.suspectgaming.de/antivpn/bot.php
on line 29
How do I solve this problem?
<?php
require("ts3admin.class.php");
$ignore_groups = array('1',); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if(!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while(true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
foreach($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups'] );
if(is_array($ignore_groups)){
foreach($ignore_groups as $ig){
if(in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
}else{
if(in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip='.$val['connection_client_ip'].'');
$file = json_decode($file, true);
if($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
}
?>
You might be missing data in your first array. You may add an if statement to check if there is data in your $clientList['data'] var:
if (is_array($clientList['data'])) {
}
Or you might also check if sizeof(); of your array is larger than a number, you may desire.
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
}
Code
require "ts3admin.class.php";
$ignore_groups = array('1'); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if (!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while (true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
foreach ($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups']);
if (is_array($ignore_groups)) {
foreach ($ignore_groups as $ig) {
if (in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
} else {
if (in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip=' . $val['connection_client_ip'] . '');
$file = json_decode($file, true);
if ($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
} else {
echo "There might be no data in Client List";
}
}

Check and modify Capitalized letters in string

I'm trying to figure out how to make this code work.
I input some text via variable into code:
$genome = "ss/ee/ff/Nn/oo";
$gepieces = explode("/", $genome);
$fenome = "ss/Ee/ff/nn/oo";
$fepieces = explode("/", $fenome);
You will see that for the Genome there is a Nn and for the Fenome there is a Ee
Upon this happening I need it to give a 50/50 chance for a compared result to be EITHER Ee OR Nn - The code I have right now can only check them individually (so sometimes I ger Ee AND Nn, other times I will get ee and nn) and I feel there could be a much easier method of achieving this than what I'm trying:
//Number of Cubs
$cubs = rand(1,4);
//GENDER
for ($x = 0; $x < $cubs; $x++) {
$gender = rand(1,2);
if ($gender == 1) {
$cubgender = "Male";
} elseif ($gender == 2) {
$cubgender = "Female";
}
//COAT COLOR
$genome = "ss/ee/ff/Nn/oo/Pa/Sr/So";
$gepieces = explode("/", $genome);
$fenome = "ss/Ee/ff/nn/oo/Pa";
$fepieces = explode("/", $fenome);
if ($gepieces[0] === $fepieces[0]) {
$ss = $gepieces[0];
} else {
$ss = rand(1,2);
if ($ss == 1) {
$ss = $gepieces[0];
} else {
$ss = $fepieces[0];
}
}
if ($gepieces[1] === $fepieces[1]) {
$ee = $gepieces[1];
} else {
$ee = rand(1,2);
if ($ee == 1) {
$ee = $gepieces[1];
} else {
$ee = $fepieces[1];
}
}
if ($gepieces[2] === $fepieces[2]) {
$ff = $gepieces[2];
} else {
$ff = rand(1,2);
if ($ff == 1) {
$ff = $gepieces[2];
} else {
$ff = $fepieces[2];
}
}
if ($gepieces[3] === $fepieces[3]) {
$nn = $gepieces[3];
} else {
$nn = rand(1,2);
if ($nn == 1) {
$nn = $gepieces[3];
} else {
$nn = $fepieces[3];
}
}
if ($gepieces[4] === $fepieces[4]) {
$oo = $gepieces[4];
} else {
$oo = rand(1,2);
if ($oo == 1) {
$oo = $gepieces[4];
} else {
$oo = $fepieces[4];
}
}
echo $cubgender." - ".$ss."/".$ee."/".$ff."/".$nn."/".$oo."<br/>";
}
I'm a colossal idiot!
Figured out my own issue
//Number of Cubs
$cubs = rand(1,4);
//GENDER
for ($x = 0; $x < $cubs; $x++) {
$gender = rand(1,2);
if ($gender == 1) {
$cubgender = "Male";
} elseif ($gender == 2) {
$cubgender = "Female";
}
//COAT COLOR
$genome = "ss/ee/ff/Nn/oo";
$gepieces = explode("/", $genome);
$fenome = "ss/Ee/ff/nn/oo";
$fepieces = explode("/", $fenome);
if ($genome === $fenome) {
$cubgeno = $genome;
} else {
$cubgeno = rand(1,2);
if ($cubgeno == 1) {
$cubgeno = $genome;
} else {
$cubgeno = $fenome;
}
}
echo $cubgender." - ".$cubgeno."<br/>";
$genome = "ss/ee/ff/Nn/oo/Pa/Sr/So";
$gepieces = explode("/", $genome);
$fenome = "ss/Ee/ff/nn/oo/Pa";
$fepieces = explode("/", $fenome);
$sequence = "";
for ($i = 0;$i < count($fepieces); $i++) {
rand(1,2) == 1 ? $sequence .= $gepieces[$i] : $sequence .= $fepieces[$i];
}
echo $sequence;

getting the even index of a string

hey guys im trying to get the even indexes of a string from the db then save them in a variable then echo. but my codes seems doesnt work. please help. here it is
require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section
WHERE school_id = '$school_id'
AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$public_key = $row['public_key'];
}
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
if($key % 2 == 0) {
$priv_key_extract += $public_key[$key];
} else {
$priv_key_extract ="haiiizzz";
}
}
}
echo $priv_key_extract;
as you can see im trying to use modulo 2 to see if the index is even.
I have updated your code as below, it will work now :
<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
//Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
if($key % 2 == 1) {
// Changed concatenation operator , += replaced with .=
$priv_key_extract .= $public_key[$key];
} /*else {
//Commented this as it is getting overwritten
$priv_key_extract ="haiiizzz";
}*/
}
}
echo $priv_key_extract;
?>
Try this function
function extractKey($key) {
if (empty($key) || !is_string($key)) return '';
$pkey = '';
for ($i=0;$i<strlen($key);$i++) {
if ($i % 2 == 0) {
$pkey .= $key[$i];
}
}
return $pkey;
}
echo extractKey('12345678'); # => 1357

What can be improved in this PHP code?

This is a custom encryption library. I do not know much about PHP's standard library of functions and was wondering if the following code can be improved in any way. The implementation should yield the same results, the API should remain as it is, but ways to make is more PHP-ish would be greatly appreciated.
Code
<?php
/***************************************
Create random major and minor SPICE key.
***************************************/
function crypt_major()
{
$all = range("\x00", "\xFF");
shuffle($all);
$major_key = implode("", $all);
return $major_key;
}
function crypt_minor()
{
$sample = array();
do
{
array_push($sample, 0, 1, 2, 3);
} while (count($sample) != 256);
shuffle($sample);
$list = array();
for ($index = 0; $index < 64; $index++)
{
$b12 = $sample[$index * 4] << 6;
$b34 = $sample[$index * 4 + 1] << 4;
$b56 = $sample[$index * 4 + 2] << 2;
$b78 = $sample[$index * 4 + 3];
array_push($list, $b12 + $b34 + $b56 + $b78);
}
$minor_key = implode("", array_map("chr", $list));
return $minor_key;
}
/***************************************
Create the SPICE key via the given name.
***************************************/
function named_major($name)
{
srand(crc32($name));
return crypt_major();
}
function named_minor($name)
{
srand(crc32($name));
return crypt_minor();
}
/***************************************
Check validity for major and minor keys.
***************************************/
function _check_major($key)
{
if (is_string($key) && strlen($key) == 256)
{
foreach (range("\x00", "\xFF") as $char)
{
if (substr_count($key, $char) == 0)
{
return FALSE;
}
}
return TRUE;
}
return FALSE;
}
function _check_minor($key)
{
if (is_string($key) && strlen($key) == 64)
{
$indexs = array();
foreach (array_map("ord", str_split($key)) as $byte)
{
foreach (range(6, 0, 2) as $shift)
{
array_push($indexs, ($byte >> $shift) & 3);
}
}
$dict = array_count_values($indexs);
foreach (range(0, 3) as $index)
{
if ($dict[$index] != 64)
{
return FALSE;
}
}
return TRUE;
}
return FALSE;
}
/***************************************
Create encode maps for encode functions.
***************************************/
function _encode_map_1($major)
{
return array_map("ord", str_split($major));
}
function _encode_map_2($minor)
{
$map_2 = array(array(), array(), array(), array());
$list = array();
foreach (array_map("ord", str_split($minor)) as $byte)
{
foreach (range(6, 0, 2) as $shift)
{
array_push($list, ($byte >> $shift) & 3);
}
}
for ($byte = 0; $byte < 256; $byte++)
{
array_push($map_2[$list[$byte]], chr($byte));
}
return $map_2;
}
/***************************************
Create decode maps for decode functions.
***************************************/
function _decode_map_1($minor)
{
$map_1 = array();
foreach (array_map("ord", str_split($minor)) as $byte)
{
foreach (range(6, 0, 2) as $shift)
{
array_push($map_1, ($byte >> $shift) & 3);
}
}
return $map_1;
}function _decode_map_2($major)
{
$map_2 = array();
$temp = array_map("ord", str_split($major));
for ($byte = 0; $byte < 256; $byte++)
{
$map_2[$temp[$byte]] = chr($byte);
}
return $map_2;
}
/***************************************
Encrypt or decrypt the string with maps.
***************************************/
function _encode($string, $map_1, $map_2)
{
$cache = "";
foreach (str_split($string) as $char)
{
$byte = $map_1[ord($char)];
foreach (range(6, 0, 2) as $shift)
{
$cache .= $map_2[($byte >> $shift) & 3][mt_rand(0, 63)];
}
}
return $cache;
}
function _decode($string, $map_1, $map_2)
{
$cache = "";
$temp = str_split($string);
for ($iter = 0; $iter < strlen($string) / 4; $iter++)
{
$b12 = $map_1[ord($temp[$iter * 4])] << 6;
$b34 = $map_1[ord($temp[$iter * 4 + 1])] << 4;
$b56 = $map_1[ord($temp[$iter * 4 + 2])] << 2;
$b78 = $map_1[ord($temp[$iter * 4 + 3])];
$cache .= $map_2[$b12 + $b34 + $b56 + $b78];
}
return $cache;
}
/***************************************
This is the public interface for coding.
***************************************/
function encode_string($string, $major, $minor)
{
if (is_string($string))
{
if (_check_major($major) && _check_minor($minor))
{
$map_1 = _encode_map_1($major);
$map_2 = _encode_map_2($minor);
return _encode($string, $map_1, $map_2);
}
}
return FALSE;
}
function decode_string($string, $major, $minor)
{
if (is_string($string) && strlen($string) % 4 == 0)
{
if (_check_major($major) && _check_minor($minor))
{
$map_1 = _decode_map_1($minor);
$map_2 = _decode_map_2($major);
return _decode($string, $map_1, $map_2);
}
}
return FALSE;
}
?>
This is a sample showing how the code is being used. Hex editors may be of help with the input / output.
Example
<?php
# get and process all of the form data
# $input = htmlspecialchars($_POST["input"]);
# $majorname = htmlspecialchars($_POST["majorname"]);
# $minorname = htmlspecialchars($_POST["minorname"]);
# $majorkey = htmlspecialchars($_POST["majorkey"]);
# $minorkey = htmlspecialchars($_POST["minorkey"]);
# $output = htmlspecialchars($_POST["output"]);
# process the submissions by operation
# CREATE
# $operation = $_POST["operation"];
if ($operation == "Create")
{
if (strlen($_POST["majorname"]) == 0)
{
$majorkey = bin2hex(crypt_major());
}
if (strlen($_POST["minorname"]) == 0)
{
$minorkey = bin2hex(crypt_minor());
}
if (strlen($_POST["majorname"]) != 0)
{
$majorkey = bin2hex(named_major($_POST["majorname"]));
}
if (strlen($_POST["minorname"]) != 0)
{
$minorkey = bin2hex(named_minor($_POST["minorname"]));
}
}
# ENCRYPT or DECRYPT
function is_hex($char)
{
if ($char == "0"):
return TRUE;
elseif ($char == "1"):
return TRUE;
elseif ($char == "2"):
return TRUE;
elseif ($char == "3"):
return TRUE;
elseif ($char == "4"):
return TRUE;
elseif ($char == "5"):
return TRUE;
elseif ($char == "6"):
return TRUE;
elseif ($char == "7"):
return TRUE;
elseif ($char == "8"):
return TRUE;
elseif ($char == "9"):
return TRUE;
elseif ($char == "a"):
return TRUE;
elseif ($char == "b"):
return TRUE;
elseif ($char == "c"):
return TRUE;
elseif ($char == "d"):
return TRUE;
elseif ($char == "e"):
return TRUE;
elseif ($char == "f"):
return TRUE;
else:
return FALSE;
endif;
}
function hex2bin($str)
{
if (strlen($str) % 2 == 0):
$string = strtolower($str);
else:
$string = strtolower("0" . $str);
endif;
$cache = "";
$temp = str_split($str);
for ($index = 0; $index < count($temp) / 2; $index++)
{
$h1 = $temp[$index * 2];
if (is_hex($h1))
{
$h2 = $temp[$index * 2 + 1];
if (is_hex($h2))
{
$cache .= chr(hexdec($h1 . $h2));
}
else
{
return FALSE;
}
}
else
{
return FALSE;
}
}
return $cache;
}
if ($operation == "Encrypt" || $operation == "Decrypt")
{
# CHECK FOR ANY ERROR
$errors = array();
if (strlen($_POST["input"]) == 0)
{
$output = "";
}
$binmajor = hex2bin($_POST["majorkey"]);
if (strlen($_POST["majorkey"]) == 0)
{
array_push($errors, "There must be a major key.");
}
elseif ($binmajor == FALSE)
{
array_push($errors, "The major key must be in hex.");
}
elseif (_check_major($binmajor) == FALSE)
{
array_push($errors, "The major key is corrupt.");
}
$binminor = hex2bin($_POST["minorkey"]);
if (strlen($_POST["minorkey"]) == 0)
{
array_push($errors, "There must be a minor key.");
}
elseif ($binminor == FALSE)
{
array_push($errors, "The minor key must be in hex.");
}
elseif (_check_minor($binminor) == FALSE)
{
array_push($errors, "The minor key is corrupt.");
}
if ($_POST["operation"] == "Decrypt")
{
$bininput = hex2bin(str_replace("\r", "", str_replace("\n", "", $_POST["input"])));
if ($bininput == FALSE)
{
if (strlen($_POST["input"]) != 0)
{
array_push($errors, "The input data must be in hex.");
}
}
elseif (strlen($bininput) % 4 != 0)
{
array_push($errors, "The input data is corrupt.");
}
}
if (count($errors) != 0)
{
# ERRORS ARE FOUND
$output = "ERROR:";
foreach ($errors as $error)
{
$output .= "\n" . $error;
}
}
elseif (strlen($_POST["input"]) != 0)
{
# CONTINUE WORKING
if ($_POST["operation"] == "Encrypt")
{
# ENCRYPT
$output = substr(chunk_split(bin2hex(encode_string($_POST["input"], $binmajor, $binminor)), 58), 0, -2);
}
else
{
# DECRYPT
$output = htmlspecialchars(decode_string($bininput, $binmajor, $binminor));
}
}
}
# echo the form with the values filled
echo "<P><TEXTAREA class=maintextarea name=input rows=25 cols=25>" . $input . "</TEXTAREA></P>\n";
echo "<P>Major Name:</P>\n";
echo "<P><INPUT id=textbox1 name=majorname value=\"" . $majorname . "\"></P>\n";
echo "<P>Minor Name:</P>\n";
echo "<P><INPUT id=textbox1 name=minorname value=\"" . $minorname . "\"></P>\n";
echo "<DIV style=\"TEXT-ALIGN: center\"><INPUT class=submit type=submit value=Create name=operation>\n";
echo "</DIV>\n";
echo "<P>Major Key:</P>\n";
echo "<P><INPUT id=textbox1 name=majorkey value=\"" . $majorkey . "\"></P>\n";
echo "<P>Minor Key:</P>\n";
echo "<P><INPUT id=textbox1 name=minorkey value=\"" . $minorkey . "\"></P>\n";
echo "<DIV style=\"TEXT-ALIGN: center\"><INPUT class=submit type=submit value=Encrypt name=operation> \n";
echo "<INPUT class=submit type=submit value=Decrypt name=operation> </DIV>\n";
echo "<P>Result:</P>\n";
echo "<P><TEXTAREA class=maintextarea name=output rows=25 readOnly cols=25>" . $output . "</TEXTAREA></P></DIV></FORM>\n";
?>
What should be editted for better memory efficiency or faster execution?
You could replace your isHex function with:
function isHex($char) {
return strpos("0123456789ABCDEF",strtoupper($char)) > -1;
}
And your hex2bin might be better as:
function hex2bin($h)
{
if (!is_string($h)) return null;
$r='';
for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); }
return $r;
}
You seem to have a lot of if..elseif...elseif...elseif which would be a lot cleaner in a switch or seperated into different methods.
However, I'm talking more from a maintainability and readability perspective - although the easier it is to read and understand, the easier it is to optimize. If it would help you if I waded through all the code and wrote it in a cleaner way, then I'll do so...

Categories