Parse user input for command arguments into array - php-7

I'm making a bot in PHP and I want a better way to parse user input into arguments for later operations.
An example would be a user saying "/addresponse -"test" -"works""
I want this to parse that string into:
$command ["test", "works"];
I have found the PHP command parser but I want the user to be able to use human readable commands rather than typing something like /addresponse?p="test"&r="works"
Right now I have a regex working so the user can type "/addresponse "test" "works"" but there are obvious problems because the user cannot make a response for '"test"' only 'test'
I'd appreciate any help, right now I think I can make a regex to get all text between ' -' but I still don't think this is the best solution.
I just looked into using a regex to find text between ' -"' and while this is better than just between quotes, it doesn't solve the whole problem because it still will break if the input contains ' -"'. A string containing this isn't particularly common but I'd like a solution where almost any input will not break it.
Is this a stupid question? I don't think there is a built in php function for this and it got downvoted with no comment...

I found a partial solution:
function parse_cmd($command) {
$command = explode(' -"', $command);
array_splice($command, 0, 1);
foreach($command as &$element) {
$element = substr($element, 0, strlen($element) -1);
}
return $command;
}
This will split everything after ' -"' and return it as an array

Related

Lotus Notes Script

I need to have a script which can copy the value from InternetAddress Field in the person document one by one in names.nsf and append it in the User Name field. Can someone help with a working script?
This can literally be done with a one-line formula, using a simple assignment statement and the list append operator. It is really the most basic thing you can do in all of Lotus Notes programming. It doesn't even need to use any of the #functions.
The syntax for an assignment is:
FIELD fieldThatYouWantToSet := value;
The syntax for the list append operator is:
value1 : value2;
The only other thing you need to know is that value1 and value2 can simply be the names of existing items (a.k.a. fields), and the list of values in the second item will be appended to the list of values in the first item.
Then, all you will need to do is to put this one-liner into a formula agent that runs against all documents in the current view, and run the agent from the Actions menu while you are in the view.
Option-1:
There are a few ways to accomplish this, the simplest being , as the user specified before, a simple field function would do.
FIELD UserName := UserNAme:InternetAddress;
You could set and run the above field function in an agent in $UsersView
In option-2, you could also use the "UnProcessedDoc" feature and set and run as an agent.
But, here, I have written one another way to set and run as an agent in $UsersView.
Hope this helps, please approve this answer if this had helped anyone.
Option:2
At present , no Domino in my System, in order to test this snippet. I wish there exists any method online to test this snippet before I post.
But, logically, consider this snippet as a pseudo-code to accomplish ur objective.
Above all, it has been more than a decade or two ever since I have programmed in Domino. Because, I moved on to RDMS, DW, BI and now to Cloud... well Cloud-9. :)
Here is a portion of lotus script code to copy the value from InternetAddress Field in the person document one by one in names.nsf and append it in the UserName field.
Dim db As New NotesDatabase( "Names Db", "names.nsf" )
Dim view As NotesView
Dim doc As NotesDocument
Dim InternetAddress_value As Variant
Set view = db.GetView( "$Users" )
// loop thru all docs in $Users view.
// Get InternetAddress_value and rep it in UserName
Set doc = view.GetFirstDocument
If doc.HasItem("InternetAddress") Then
While Not(doc Is Nothing)
// in this line we concatenate username with IAaddress_value
new_value= doc.GetItemValue( "username" ) + doc.GetItemValue( "InternetAddress" )
Call doc.ReplaceItemValue( "UserName", new_value)
Call doc.Save( False, True )
Set doc = view.GetNextDocument(doc)
Wend
End If
This solution is posted by Mangai#Notes#Domino#Now_HCL . Encourage to post more solutions by approving the answer.

passing msqli to a function - can't suss out why it's not working

I've searched high and low for an answer on this, but I'm either missing something, or I just can't find anything in this context.
Background - trying to avoid spaghetti frenzy with a little casual project I'm starting; part of this will involve mainly just calls to a mysql database, displaying table content and so on. Simply put, like a CRM I guess.
I may be way off base here, but I want to be able to create my sql calls as functions, which will help if/when I tweak and tune, as well as creating a cleaner code for what I'm looking to do.
So, without further ado, I have this as a demomstration:
echo "<table>";
selectall('actions','content',$mysqli);
echo "</table><br><br>";
What this does is show all rows from my table of 'actions. "content" is just an example field name I'm passing through that I want to display, as it is the main human-relevant field name in that table. I'm also passing $mysqli through here for my function db call.
My function looks like this:
function selectall($s_table,$s_content,$mysqli){
$query = "SELECT * FROM " . $s_table;
$resource = $mysqli->query($query);
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
$id = $row['id'];
echo "<tr><td>{$row[$s_content]}</td></tr>";
}
$resource->free();
$mysqli->close();
}
However.... it doesn't work, and it seems to throw a wobbly saying:
Warning: mysqli::query(): Couldn't fetch mysqli
This points to the action within the line $resource = $mysqli->query($query);
I know the function and everything is ok, as if I restate and declare $mysqli within the first line of the function, like so...
$mysqli = new mysqli(username password and so on in here);
... it works spot on.
$mysqli exists and works within the same code that is passing the variable within the function too.
This is early stages, so by shuffling the code around trying to poke the $mysqli pass into life I have perhaps made the code a little messier that intended, so try not to worry too much about that.
Anyone any ideas why it doesn't like this?
D'oh...
I had a
$mysqli->close();
in the lines above. Solved myself.
For reference, this is my function:
function selectall($s_table,$s_field,$mysqli){
if ($mysqli->connect_error) {die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);}
$s_table = preg_replace('/[^0-9a-zA-Z_]/', '', $s_table); // Cleans up the table name variable
$s_field = preg_replace('/[^0-9a-zA-Z_]/', '', $s_field); // Cleans up the field name variable
$query = "SELECT * FROM " . $s_table; // Adds passed table name to the select all
$resource = $mysqli->query($query);
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "<tr><td>{$row[$s_field]}</td></tr>"; // Content for each row of the select all
}
$resource->free();
$mysqli->close();
}
As you can see, I've also tried to protect the variables that enter the function.
This can be called via:
selectall('actions','content',$mysqli);
In this context, I want to view all the entries in the 'actions' table by the field name 'content'. This function, with some code above and below for a table, will create a new row for each entry.
I'll probably evolve a few, already created on that includes a delete button at the end of the line which is 'selectalldel'.
Open to comments on whether this actually is worthwhile, but thought I'd post up my corrected stupidity in case anyone finds this useful.

os.execute variables

I have multiple Steam accounts that I want to launch via a single Lua script with the options I specify. I've got pretty much everything sorted, except for launching with the code provided. I have no idea how to "pass" the variable with this format.
function Steam(n, opt1, opt2, opt3)
os.execute[["start C:\Program" "Files\Sandboxie\Start.exe /box:Steam2 D:\Steam\steam.exe -login username password -opt1 -opt2 -opt3"]]
end
I have my usernames and Sandboxes setup so that only the number needs changing (fenriros2, fenriros3, Steam2, Steam3 etc) with the same password.
Basically, I want this;
Steam(3, -tf, -exit, -textmode)
to do;
os.execute[["start C:\Program" "Files\Sandboxie\Start.exe /box:Steam3 D:\Steam\steam.exe -login fenriros3 password -applaunch 440 -textmode"]]
I'll use -exit to close the lua window after it's done.
I realize my code isn't exactly efficient, but that's a worry for a later time. Right now I just need to get it working.
Any help is greatly appreciated, and I apologize if I missed something obvious, I'm still fairly new at Lua.
First obvious one. The [[ ]] delimit a string so all you need to do is to create a variable for the string and replace the contents as needed.
function Steam(n, opt1, opt2, opt3)
-- Set up execute string with placeholders for the parameters.
local strExecute = [["start C:\Program" "Files\Sandboxie\Start.exe /box:Steam{n} D:\Steam\steam.exe -login fenriros{n} password -{opt1} -{opt2} -{opt3}"]]
-- Use gsub to replace the parameters
-- You could just concat the string but I find it easier to work this way.
strExecute = strExecute:gsub('{n}',n)
strExecute = strExecute:gsub('{opt1}',opt1:gsub('%%','%%%%'))
strExecute = strExecute:gsub('{opt2}',opt2:gsub('%%','%%%%'))
strExecute = strExecute:gsub('{opt3}',opt3:gsub('%%','%%%%'))
os.execute(strExecute)
end
Steam(1,'r1','r2','r3')

Check if an existing value is in a database

I was wondering how I would go about checking to see if a table contains a value in a certain column.
I need to check if the column 'e-mail' contains an e-mail someone is trying to register with, and if something exists, do nothing, however, if nothing exists, insert the data into the database.
All I need to do is check if the e-mail column contains the value the user is registering with.
I'm using the RedBeanPHP ORM, I can do this without using it but I need to use that for program guidelines.
I've tried finding them but if they don't exist it returns an error within the redbean PHP file. Here's the error:Fatal error: Call to a member function find() on a non-object in /home/aeterna/www/user/rb.php on line 2433
Here's the code that I'm using when trying this:
function searchDatabase($email) {
return R::findOne('users', 'email LIKE "' . $email . '"');
}
My approach on the function would be
function searchDatabase($email) {
$data = array('email' => $email);
$user = R::findOne('users', 'email LIKE :email, $data);
if (!empty($user)) {
// do stuff here
} // end if
} // end function
It's a bit more clean and in your function
Seems like you are not connected to a database.
Have you done R::setup() before R::find()?
RedBeanPHP raises this error if it can't find the R::$redbean instance, the facade static functions just route calls to the $redbean object (to hide all object oriented fuzzyness for people who dont like that sort of thing).
However you need to bootstrap the facade using R::setup(). Normally you can start using RB with just two lines:
require('rb.php'); //cant make this any simpler :(
R::setup(); //this could be done in rb.php but people would not like that ;)
//and then go...
R::find( ... );
I recommend to check whether the $redbean object is available or whether for some reason the code flow has skipped the R::setup() boostrap method.
Edited to account for your updated question:
According to the error message, the error is happening inside the function find() in rb.php on line 2433. I'm guessing that rb.php is the RedBean package.
Make sure you've included rb.php in your script and set up your database, according to the instructions in the RedBean Manual.
As a starting point, look at what it's trying to do on line 2433 in rb.php. It appears to be calling a method on an invalid object. Figure out where that object is being created and why it's invalid. Maybe the find function was supplied with bad parameters.
Feel free to update your question by pasting the entirety of the find() function in rb.php and please indicate which line is 2433. If the function is too lengthy, you can paste it on a site like pastebin.com and link to it from here.
Your error sounds like you haven't done R::setup() yet.
My approach to performing the check you want would be something like this:
$count = count(R::find('users', 'email LIKE :email', array(':email' => $email)));
if($count === 0)
{
$user = R::dispense('users');
$user->name = $name;
$user->email = $email;
$user->dob = $dob;
R::store($user);
}
I don't know if it is this basic or not, but with SQL (using PHP for variables), a query could look like
$lookup = 'customerID';
$result = mysql_fetch_array(mysql_query("SELECT columnName IN tableName WHERE id='".$lookup."' LIMIT 1"));
$exists = is_null($result['columnName'])?false:true;
If you're just trying to find a single value in a database, you should always limit your result to 1, that way, if it is found in the first record, your query will stop.
Hope this helps

Building SEO-friendly URLs for accented characters

We are making our site an SEO-friendly site by following the pattern below:
http://OurWebsite.com/MyArticle/Math/Spain/Glaño
As you see, Glaño has a spelling character that search engines may not like it. On the other hand we cannot build up the last URL!
Any suggestions to maintain our current URL generation code to handle Spanish or French entries or we need to change our approach?
Try these functions:
function Slug($string, $slug = '-', $extra = null)
{
return strtolower(trim(preg_replace('~[^0-9a-z' . preg_quote($extra, '~') . ']+~i', $slug, Unaccent($string)), $slug));
}
function Unaccent($string)
{
return html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8');
}
And use it like this:
echo Slug('Iñtërnâtiônàlizætiøn of Glaño'); // internationalizaetion-of-glano
You can embed the Unaccent() code into the Slug() function if you wish to have only one function.
Perhaps replace accented characters with the closest matching non-accented latin character.
Unless "Glano" means something very rude, this is probably your best bet.
If you search google for "Glaño" it returns pages with "Glano" in it anyway, so the SEO shouldn't be harmed.
To translate the characters from accented to unaccented, you could use this function (this is in PHP, but hopefully you'd be able to use it as a starting point for other languages):
function normalize ($string) {
$table = array(
'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
);
return strtr($string, $table);
}
(Author credit goes to allixsenos at gmail http://php.net/manual/en/function.strtr.php)
I agree that unless "Glano" means something very rude, this is probably your best bet. Now, I want to add that if you care about SEO I would consider not having too many folders in the URL. One root, three sub-folders and then the file. This may hurt more than the special character.