Codeigniter/PHP: Creating users in batch with TankAuth - php

I am interested in creating bulk users/passwords in a batch using TankAuth for CodeIgniter. I asked this question on the CI forums but got no responses:
http://codeigniter.com/forums/viewthread/110993/P330/#837327
Google searches don't turn up much besides my thread as the third result and a bunch of unrelated sites.
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=create+batch+users+tankauth
Has anyone successfully done this using a recursion algorithm? If so, can you post some code to get me going on the right path? Thanks!
Versions of software:
CI 1.7.3
TankAuth 1.0.7
PHP 5.x
EDIT 2/15:
Just in case anyone is looking for a solution to this, here's a function that is basically the same one I used (there were some other parameters, but this should get you going):
function batchReg()
{
$this->load->model('mymodel');
// connect to the database
$this->mymodel->dbconnect();
// build it
$query = "SELECT user, email, pass from newusers ORDER BY user ASC";
// ship it
$result = mysql_query($query);
// loop it
while ($row = mysql_fetch_array($result))
{
$data = $this->tank_auth->create_user($row['user'], $row['email'], $row['pass'], FALSE);
print_r($data);
echo "<p>";
}
}
Just ping batchReg() from the controller to put it into action!

Sounds like a simple loop operation to me
somehow (whatever the source) get your usernames in a iterable form like an array $user_list
we'll say it looks like this
Array(
Array(
[username] => '...',
[email] => '...',
[password] => '', //leave password empty
),
Array(
[username] => '...',
[email] => '...',
[password] => '', //leave password empty
),
... etc.
)
Then create a simple looping routine to process the new registrations, storing the password back into the array, so you will then have a complete list of logins, new (randomized) passwords and emails.
//loop by referance in order to properly store the generated password
foreach($user_list as &$user) {
//generate 8 char password and store it
$user['password'] = substr(uniqid(),2,8);
//run register routine (not sure on tank auth's specific syntax
$this->tankauth->register($user['username'],$user['email'],$user['password'],FALSE);
}
Then at the end your $user_list contains all the new passwords for your users.

Related

Update Salesforce Case Record with SOQL in PHP

Trying to change the case owner of a specific case by changing the OwnerId value but I am not having any success.. I have compared my query with the docs and I can't understand why it's failing. The examples in the docs are for the Contact object, I could not find examples for Case object but thought it should be the same procedure.
Permissions should not be an issue as I can make updates via workbench on the same field without any problems, however, i'm trying to integrate this with php.
try {
$caseId = "5004z00001fqUIRAA2";
//query to target specific case to update
$query = "SELECT CaseNumber,Id,OwnerId FROM Case WHERE Id = '".$caseId."'";
$queryResponse = $mySforceConnection->query($query);
$queryResult = new QueryResult($queryResponse);
echo "<pre>",print_r($queryResult,true),"</pre>";
//prepare field update
$sObject = new SObject();
$sObject->type = 'Case';
$sObject->fields['OwnerId'] = "0054z000008RuHkAAK";
$sObject->Id = $caseId;
//submit update
$updateResponse = $mySforceConnection->update(array($sObject),'Case');
print_r($updateResponse);
} catch (Exception $e) {
echo $mySforceConnection->getLastRequest();
echo $e->faultstring;
}
Here is the response I get on the initial query to confirm I am getting a response back.
QueryResult Object
(
[queryLocator] =>
[done] => 1
[records] => Array
(
[0] => stdClass Object
(
[Id] => 5004z00001fqUIRAA2
[CaseNumber] => 03161663
[OwnerId] => 0054z000007HMzcAAG
)
)
[size] => 1
[pointer] => 0
[sf:QueryResult:private] =>
)
However, when performing the subsequent query to update the OwnerId value I get the following error:
INVALID_FIELD: No such column 'fields' on entity 'Case'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.
The OwnerId field is not a custom field, it's standard field of the Case object. I even confirmed this field exists within the object.
Any Ideas?
Not much of an answer but too long for a comment.
https://barefoot.sourcerepo.com/barefoot/php_toolkit/trunk/php_toolkit/ looks very old, it references API versions ~20? SF API version is 55-56 now and in fact they plan to kill old versions: https://help.salesforce.com/s/articleView?language=en_US&id=000354473&type=1
Have you just grabbed that (old) sample code or have you downloaded the WSDL file from Salesforce and "consumed" it?
You're dumping the last request only in the catch block - what if you try to dump it anyway, similar to https://help.salesforce.com/s/articleView?id=000383659&type=1
The final XML should be similar to https://developer.salesforce.com/blogs/2015/06/salesforce-soap-api-sample-wsdls "Scenario 8: Updating the ownership of a record using the update() API." Which well, this blog post is from 2015, about 20 API versions old but it's something.
You could also import the WSDL to SoapUI, Postman or what-have-you and experiment with manual calling login, then update in there?

How to call PHP case from another PHP case

I have been using a formula to uniquely secure id's gathered from database before they are presented to the client.
However, as my code grown complex, I've fallen into this pitfall: I have two separate cases returning json that need to use the same id. Because my securing function produces a unique hash and key at each perform, hashed ID gathered from one case cannot be encrypted in the other one that needs to use it. Therefore as a solution, I thought that sending hashed id gathered from first case back to first case again, decrypt it there and then somehow pass it to the other case without client never having chance to catch the real id.
All the codes work fine, my problem is matching the id drawn from first case that is to be used in the second case that also sends data back before case break, which is simply a client-triggered loop. I am providing codes in case you would ask it. The problem is simply matching the same id with different unique hash in two separate php cases. Sorry if I made this more complicated than it should have.
This is the first case I am using for filling a dropdown select.
case "tutorRefresh":
$tutorSelectSql = "SELECT id, tname, tsurname FROM tutors";
$tutorSelectQry = pg_query($tutorSelectSql);
while($row = pg_fetch_array($tutorSelectQry)){
$id = lockPandoraBox($row['id']);//encrypt the id
$response[] = array("id" => $id,
"tname" => $row['tname'],
"tsurname" => $row['tsurname']);
};
if(isset($response)){
echo json_encode($response);
} else {
$response = array("val" => 0);
echo json_encode($response);
}
break;
This is the function used by the second case that updates the table data, since it is too long and complex for a single issue to post it all here, I only shared relevant part of the code. I have to match the id encrypted in above code with the one encrypted here since this code fills in the table while the code above just fills in the dropdown select.
$crypted = lockPandoraBox($row["appid"]);
$tutorID = lockPandoraBox($row["tutorid"]);//encrypting id
$clientID = lockPandoraBox($row["clientid"]);//same method for another id, ignore this.
$fApp["hours"][] = array("recId" => $crypted,
"hour" => $row["hour"],
"tutor" => $tutorArr["tname"]." ".$tutorArr["tsurname"],
"tutorId" => $tutorID,// id that I need to use
"client" => $clientArr["cname"]." ".$clientArr["csurname"],
"clientId" => $clientID,
"department" => $dept,
"degree" => $deg,
"purpose" => $purposeArr["pname"],
"purposeId" => $row["purpose"],
"contact" => $clientArr["cgsm"],
"email" => $clientArr["cemail"],
"tutorAbsCheck" => $tutorAbsArray["id"],
"tutorAbsReason" => $tutorAbsArray["reason"],
"clientAbsCheck" => $clientAbsArray["id"],
"clientAbsReason" => $clientAbsArray["reason"]
);
/* */
}
return json_encode($fApp);
}
Lastly, this is the code in my main page which works in click event function that triggers the event I need. It simply changes select box's selection for the matching clicked record. It picks the id from table and tries to match it with the id in select box. Thanks in advance.
$("#tutorEdit").val(dayData["hours"][$(el.currentTarget).attr("key")].tutorId).trigger("change");
I think it will be better to change the structure a bit to combine both cases in order to achieve my goal. I wanted to know if I could get around it.

Parse WHERE php

I using https://github.com/ParsePlatform/parse-php-sdk.
I want to send notify 2 other devices.
But it's only send notify for device token is 'abcdef'.
How to send notify 2 other devices?
Thanks all,
$query = ParseInstallation::query();
$query->equalTo('deviceToken', 'xxxxx');
$query->equalTo('deviceToken', 'abcdef');
$data = [
'data' => ['alert' => 'Hello, this is a test'],
'where' => $query,
];
ParsePush::send(
$data
);
I believe your dual equalTo queries are overwriting each other. From what I understand, equalTo matches a single value. You should be able to see this behavior by inspecting a vardump of your $query after each equalTo call.
You should instead use containedIn (http://parseplatform.github.io/parse-php-sdk/classes/Parse.ParseQuery.html#method_containedIn) and pass in an array of values that you'd like the query to match. E.g., $query->containedIn('deviceToken', ['abcdef', 'xxxxx']).
Note: I don't have a parse PHP project handy so the above code isn't tested, but the general logic should work.

Return Different PHP Array Values Based on A User ID-Related Constant

I am working with an array of tokens for an HTML template. Two of them ('{SYS_MENU}' and '{SUB_MENU}') are used to generate control buttons for the web application. Right now the buttons show up on the login page before the user's credential's are validated, and I need to change the code so that the buttons are hidden until after users login and reach the main menu. When someone types the http: address into their browser and arrives at the login page the system starts a session for them in the MySQL sessions table with USER_ID = 0. After they login the USER_ID changes to whatever number was assigned to them at initial registration (Example: USER_ID = 54), and after they logout at the end of the session back to 0. Tying this constant to the buttons seems like the best solution and I have found it to work in the past under similar circumstances.
Here is the original array:
$template_vars = array(
'{LANG_DIR}' => $lang_text_dir,
'{TITLE}' => theme_page_title($section),
'{CHARSET}' => $charset,
'{META}' => $meta,
'{GAL_NAME}' => $CONFIG['gallery_name'],
'{GAL_DESCRIPTION}' => $CONFIG['gallery_description'],
'{SYS_MENU}' => theme_main_menu('sys_menu'),
'{SUB_MENU}' => theme_main_menu('sub_menu'),
'{ADMIN_MENU}' => theme_admin_mode_menu(),
'{CUSTOM_HEADER}' => $custom_header,
'{JAVASCRIPT}' => theme_javascript_head(),
'{MESSAGE_BLOCK}' => theme_display_message_block(),
);
The first thing I did was to work with the references directly in the HTML template. I saw an example on w3schools that made it look like you could just type a PHP script into HTML and have it resolve. That didn't do anything except echo a bunch of text randomly into the page. I then found another citation that said you had to activate the PHP with an .HTACCESS entry before it would work directly in HTML. But that didn't close the deal either.
I know that changing '{SYS_MENU}' and '{SUB_MENU}' values in the array to => "", produces the results that I want (I.E. make the menu buttons disappear). So my next thought was I'll create an IF statement that returns two versions of the array based on circumstances, something like:
if(USER_ID != 0)
{
return $template_vars = //FIRST VERSION OF ARRAY WITH FULL VALUES//
}
else
{
return $template_vars = //SECOND VERSION OF ARRAY WITH ONLY => ""//
}
But all that did was cause the application load to terminate at a white screen with no error feedback.
My most recent attempt came from something I read here on Stack Overflow. I know that you cannot put IF statements into an array. But the article at this link described a workaround:
If statement within an array declaration ...is that possible?
So I rewrote the array as follows:
template_vars = array(
'{LANG_DIR}' => $lang_text_dir,
'{TITLE}' => theme_page_title($section),
'{CHARSET}' => $charset,
'{META}' => $meta,
'{GAL_NAME}' => $CONFIG['gallery_name'],
'{GAL_DESCRIPTION}' => $CONFIG['gallery_description'],
'{SYS_MENU}' => ('USER_ID != 0' ? theme_main_menu('sys_menu') : ""),
'{SUB_MENU}' => ('USER_ID != 0' ? theme_main_menu('sub_menu') : ""),
'{ADMIN_MENU}' => theme_admin_mode_menu(),
'{CUSTOM_HEADER}' => $custom_header,
'{JAVASCRIPT}' => theme_javascript_head(),
'{MESSAGE_BLOCK}' => theme_display_message_block(),
);
But that seems to have no effect at all. The application doesn't crash but the buttons are static whether you are logged in or logged out.
My question is: What am I missing? I can see that this is possible. But I've been trying things for a day and a half and just seem to be dancing around the solution. Your thoughts would be greatly appreciated.
The problem here is that you are calling return. With a global include file like this there is not context to return to so the application terminates. What you want to do is just assign the variables.
if(USER_ID != 0)
{
$template_vars = //FIRST VERSION OF ARRAY WITH FULL VALUES//
}
else
{
$template_vars = //SECOND VERSION OF ARRAY WITH ONLY => ""//
}

PHP find the array index key of multi dimensional array to update array

I am trying to come up with a means of working with what could potentially be very large array sets. What I am doing is working with the facebook graph api.
So when a user signs up for a service that I am building, I store their facebook id in a table in my service. The point of this is to allow a user who signs up for my service to find friends of their's who are on facebook and have also signed up through my service to find one another easier.
What I am trying to do currently is take the object that the facebook api returns for the /me/friends data and pass that to a function that I have building a query to my DB for the ID's found in the FB data which works fine. Also while this whole bit is going on I have an array of just facebook id's building up so I can use them in an in_array scenario. As my query only returns facebook id's found matching
While this data is looping through itself to create the query I also update the object to contain one more key/value pair per item on the list which is "are_friends"=> false So far to this point it all works smooth and relatively fast, and I have my query results. Which I am looping over.
So I am at a part where I want to avoid having a loop within a loop. This is where the in_array() bit comes in. Since I created the array of stored fb id's I can now loop over my results to see if there's a match, and in that event I want to take the original object that I appended 'are_friends'=>false to and change the ones in that set that match to "true" instead of false. I just can't think of a good way without looping over the original array inside the loop that is the results array.
So I am hoping someone can help me come up with a solution here without that secondary loop
The array up to this point that starts off as the original looks like
Array(
[data](
[0] => array(
are_fb_friends => false
name => user name
id => 1000
)
[1] => array(
are_fb_friends => false
name => user name
id => 2000
)
[2] => array(
are_fb_friends => false
name => user name
id => 3000
)
)
)
As per request
This is my current code logic, that I am attempting to describe above..
public function fromFB($arr = array())
{
$new_arr = array();
if((is_array($arr))&&(count($arr) > 0))
{
$this->db->select()->from(MEMB_BASIC);
$first_pass = 0;
for($i=0;$i < count($arr);$i++)
{
$arr[$i]['are_fb_friends'] = "false";
$new_arr[] = $arr[$i]['id'];
if($first_pass == 0)
{
$this->db->where('facebookID', $arr[$i]['id']);
}
else
{
$this->db->or_where('facebookID', $arr[$i]['id']);
}
$first_pass++;
}
$this->db->limit(count($arr));
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result();
foreach($result as $row)
{
if(in_array($row->facebookID, $new_arr))
{
array_keys($arr, "blue");
}
}
}
}
return $arr;
}
To search a value and get its key in an array, you can use the array_search function which returns the key of the element.
$found_key = array_search($needle, $array);
For multidimensional array search in PHP look at https://stackoverflow.com/a/8102246/648044.
If you're worried about optimization I think you have to try using a query on a database (with proper indexing).
By the way, are you using the Facebook Query Language? If not give it a try, it's useful.

Categories