adldap2: unable to retrieve custom user attribute - php

I've written a small php script to retrieve all the users in a certain group and obtain two values, username and employeeid. Unfortunately, the second field is always empty. But a similar query done in Go returns the value. I've read Adldap docs several times, but cannot figure out what's wrong.
This is the code I'm using:
$ad = new \Adldap\Adldap();
$ad->addProvider($config);
$userlist = [];
try {
$provider = $ad->connect();
$group = $provider->search()->groups()->find($groupname);
foreach ($group->getMembers() as $user) {
$userlist[] = [
'AccountName' => $user->getAccountName(),
'EmployeeId' => $user->getEmployeeId(),
];
}
} catch (\Adldap\Auth\BindException $e) {
echo $e->getMessage();
}
And this is the relevant working part in Go. Here I was retrieving only a single user element:
func BindAndSearch(l *ldap.Conn, username string) (*ldap.SearchResult, error) {
l.Bind(BindUsername, BindPassword)
searchReq := ldap.NewSearchRequest(
BaseDN,
ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases,
0,
0,
false,
fmt.Sprintf(Filter, ldap.EscapeFilter(username)),
[]string{"employeeID"},
nil,
)
result, err := l.Search(searchReq)
...

Found this SO answer which is exactly my issue:
I was Connecting to the AD via port 3268. It seems some attributes can be fetched only by connecting to the AD via port 389.

Related

Ajax message display issue

I think I've worked out that the issue relates to binding params for PDO instead of including the values in the select statement.
Now googling how to bind array values where there will be a variable number of them per query type. For example there may be one, two or three category (col) values sought.
My primary script submits an ajax request to a secondary script.
Two params are sent and are being received in most scenarios.
eg department:mens-fashion, category:coats-and-jackets
In all but a few scenarios, the ajax query is successful and returns as expected. However, for some pairings of params, nothing is displayed in the page or in console.
Having returned from the query script immediately after building the query, I know the query is always working OK. (Copying and pasting into phpMyAmdin brings me the correct resultset.)
So it seems the key part of the script is the fetch routine. How can I catch an error message from PDO in the next line?...
$filtered_results = $filtered_statement->fetchAll(PDO::FETCH_ASSOC);
$debugInfo = array('debug' => vsprintf(str_replace("?", "%s", $filtered_statement->queryString), $opts ));
[edit]
if ( is_array($filtered_results) ) {
$filtered_results = array_merge($debugInfo, $filtered_results);
} else {
$filtered_results = $debugInfo;
}
[/edit]
debug info still only being returned if the query was a success.
$filtered_results_json = json_encode($filtered_results);
echo( $filtered_results_json );
Please would anyone point me to a solution where, the failed query will display in the calling script. The data required is in the db so I am still really stuck on trying to display failure messages.
You need to check whether an array is returned or not. If nothing was found no array is being returned - and you can't use array_merge.
$filtered_results = $filtered_statement->fetchAll(PDO::FETCH_ASSOC);
$debugInfo = array('debug' => vsprintf(str_replace("?", "%s", $filtered_statement->queryString), $opts ));
if ( is_array($filtered_results) ) {
$filtered_results = array_merge($debugInfo, $filtered_results);
} else {
$filtered_results = $debugInfo;
}
$filtered_results_json = json_encode($filtered_results);
echo( $filtered_results_json );
See this as well: Value return when no rows in PDO

How to: Properly use PHP to encode data into JSON format, and request the data with jquery/ajax

I am trying to create an address book of sorts.
I can successfully connect to the database and insert data with a php script.
I have even managed to display json encoded data of my table rows, though I don't know if I am doing it right.
What I am actually trying to accomplish:
I would like to be able to make an ajax request for say, and ID, then get back all of that ID's corresponding data, (wrapped in Json - At least I think it needs to be..).
With the ajax script, I would like to be able to save the returned corresponding data to an input field in an html file.
I would also like to know if it would be better to try to return HTML to the ajax call, and input the data into the html input fields that way?
So far I am having limited success, but here is what I have so far...
I have a DB connection script:
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "data_base";
$mysqli = new mysqli($host, $user, $pass, $db);
if($mysqli->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
return $mysqli;
A mysql ISAM DB with the following columns:
id, user, pass, nickname, address, facebook, twitter, linkedin, youtube
ID should be unique
User is an index
Pass is an index
nickname is an index
address is primary - though its possible that id should be...
Facebook, Twitter, Linkedin, and Youtube are all indexes.
Note: I would be happy to change index, primary, etc as somebody sees fit...
EDITED!**Now my query page:
error_reporting(E_ALL); ini_set("display_errors", 1);
include 'db/dbcon.php';
//Start connection with SQL
$q = "SELECT * FROM `cfaddrbook` WHERE key = '111111'";
$res = $mysqli->query($q) or trigger_error($mysqli->error."[$q]");
$array = array(); // initialize
while($row = $res->fetch_array(MYSQLI_BOTH)) {
$array[] = array(
'key' => $row[0],
'username' => $row[1],
// ... continue like this
);
}
header('Content-Type: application/json');
echo json_encode($array);
$res->free();
$mysqli->close();
Now, the above script seems to work fine. At least it displays just fine when loading the php page in the browser.
But when I make an ajax call with this script:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "queries.php",
dataType: 'json',
data: "",
cache: false,
success: function(result)
{
var cfkey = result[0];
var user = result[1];
alert("cfkey:" + cfkey + "user:" + user);
}
});
});
After loading this code, the chrome console states that the server returned with error 500.
Again, what I am trying to accomplish:
I would like to be able to make an ajax request for say, and ID, then get back all of that ID's corresponding data, (wrapped in Json - At least I think it needs to be..).
With the ajax script, I would like to be able to save the returned corresponding data to an input field in html.
EDIT:
Finally figured out that the problem I was discussing with Majid was with the SQL query.
key needed to be need to be wrapped in ` characters.
After you execute your query and the resultset is available in $res you could just build up your array, no need for a separate foreach:
$array = array(); // initialize
while($row = $res->fetch_array(MYSQLI_BOTH)) {
$array[] = array(
'id' => $row[0],
'username' => $row[1],
'password' => $row[2],
'nick' => $row[3],
'addr' => $row[4],
'facebook' => $row[5],
'twitter' => $row[6],
'linkedin' => $row[7],
'youtube' => $row[8]
);
}
header('Content-Type: application/json');
echo json_encode($array);
Also note that this way, your json will have keys, so to consume it you should change:
success: function(result) {
var cfkey = result[0];
var user = result[1];
alert("cfkey:" + cfkey + "user:" + user);
}
To
success: function(result) {
var cfkey = result.id;
var user = result.username;
alert("cfkey:" + cfkey + "user:" + user);
}
Or simply do
$.getJSON('queries.php', {cfkey: $("#cfkey").val()}, function(result) {
// we have multiple results
$.each(result, function(i,r) {
console.log("cfkey:" + r.key + "user:" + r.username);
});
});
Edit: added header as pointed out by #amurrell
I believe you are expecting queries.php to return json (to your ajax) and thus you need content header types in your queries.php!
header('Content-Type: application/json');
You need more useful error messages. Try adding the following lines at the beginning of your code.
error_reporting(E_ALL);
ini_set("display_errors", 1);
Your script that outputs JSON is writing several valid JSON strings (one for each database row), but they don't add up to a valid JSON file. A JSON file should represent one JSON object.
If you want to pass an ID and get one database row back, you have to add that ID to the data part of your AJAX call, and modify queries.php to pass that id from its $_POST array into the WHERE part of your MySQL query. Then, you'd only output one JSON-encoded object rather than many, which would be a valid JSON file.
(Alternately, you could json_encode() the entire $rows array rather than each $row individually if you want the whole table back.)
Also, if you json_encode() a string-indexed array in PHP, you read its properties in Javascript by name, not by index. You've gone through the trouble of naming your keys in PHP, then switch back to trying to reference them by their 0-based index in Javascript. You can pick one way or the other, but you can only pick one!

mongoDB wont allow me to update

Ok this issue is driving me nutts, I thought that _id was meant to be ObjectID while the first time it inserts it does it correctly when I try to update it using the _id it does not work.
here is my code
//Save Data
function savedata($data){
$collection = $this->db->retail_logs;
$this->data = $data;
if($this->data['_id'] == NULL || $this->data['_id'] == "")
{
$this->data['_id'] = new MongoId();
}
else
{
$this->data['_id'] = ObjectID($this->data['_id']);
}
try {
$collection->update(
array("_id"=>$this->data['_id']),
$this->data, // new lead document to insert
array("upsert" => true, "safe" => true)
);
print $this->data['_id'];
} catch (Exception $e) {
print "we are not able to update";
}
}
i have tried to do the followinf
if($this->data['_id'] == NULL || $this->data['_id'] == "")
{
$this->data['_id'] = new MongoId();
}
else
{
$this->data['_id'] = ObjectID($this->data['_id']);
}
but that seems not to help.
What Is happening is it inserts the first time correctly with ObjectID(idnumber)
then when it goes to update is removes the ObjectID() and inserts a new lead with the same idnumber as before
so it looks like "IDNUMBER"
Your original code is close, but if you want to make a string _id the correct ObjectID type, use:
$this->data['_id'] = new MongoId($this->data['_id']);
Checking the Outcome of an Update Request
A non-upsert update may or may not modify an existing object. An upsert will either modify an existing object or insert a new object. The client may determine if its most recent message on a connection updated an existing object by subsequently issuing a getlasterror command ( db.runCommand( "getlasterror" ) ). If the result of the getlasterror command contains an updatedExisting field, the last message on the connection was an update request. If the updatedExisting field's value is true, that update request caused an existing object to be updated; if updatedExisting is false, no existing object was updated. An "upserted" field will contain the new _id value if an insert is performed (new as of 1.5.4)
Can you run the command as suggested by Mongo Docs and let us know the result of the command
Reference: Mongo Updating

Problem in implementing Sphinx API along with Cake php

I am working on project where I need to implement SphinxSearch with Cake php. So I am simply trying to use a component and behaviour into it. The link to it, is :-
http://bakery.cakephp.org/articles/eugenioclrc/2010/07/10/sphinx-component-and-behavior
I am requesting Sphinx API like below :
$sphinx = array('matchMode' => SPH_MATCH_ALL, 'sortMode' => array(SPH_SORT_EXTENDED => '#relevance DESC'));
$results = $this->ModelName->find('all', array('search' => 'Search_Query', 'sphinx' => $sphinx));
pr($result);
For above it is working fine ,but when I tried to minimise the response time querying to a particular field of the table (using extended match modes,i.e. SPH_MATCH_EXTENDED2) , Sphinx just fails to output any result. The extended query which I used is given below :-
$sphinx = array('matchMode' => SPH_MATCH_EXTENDED2, 'sortMode' => array(SPH_SORT_EXTENDED => '#relevance DESC'));
$results = $this->ModelName->find('all', array('search' => '#Field_name Search_Query', 'sphinx' => $sphinx));
pr($results);
Can anyone recognise where am I going wrong with it? Please help if I am going wrong some where.
Thanks in advance.
Btw, when you use EXTENDED2 mode make sure your rank mode is set accordingly.
Edit:
Anyway back to you problem, looking at that component/behavior code you can see right away that no error checking is done whatsoever. Try changing the code a bit so you can at least see the errors and/or warnings.
Component
if(!isset($query['search'])){
$result = self::$sphinx->Query('', $indexes);
} else {
$result = self::$sphinx->Query($query['search'], $indexes);
}
if ($result === false) {
// throw new SphinxException();
die(self::$sphinx->GetLastError());
}
$warn = self::$sphinx->GetLastWarning();
if ($warn) echo $warn;
Behavior
$result=$this->runtime[$model->alias]['sphinx']->search($s);
if ($result === false) {
die($this->runtime[$model->alias]['sphinx']->GetLastError());
}
$warn = $this->runtime[$model->alias]['sphinx']->GetLastWarning();
if ($warn) echo $warn;
I hope that helps.
As you said ,
Sphinx just fails to output any result.
That means it's an error :
Please check whether you have added the specific field to the indexing by using sql_query
Also check if the field you are searching for is not an attribute
As per the sphinx documentation :
Attributes, unlike the fields, are not full-text indexed. They are stored in the index, but it is not possible to search them as full-text, and attempting to do so results in an error.

facebook api: count attendees for event (limit problem)

Okay normally I'm all fine about the facebook API but I'm having a problem which just keeps me wondering. (I think it's a bug (Check ticket http://bugs.developers.facebook.net/show_bug.cgi?id=13694) but I wanted to throw it here if somebody has an idea).
I'm usng the facebook PHP library to count all attendees for a specific event
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending');
this works without a problem it correctly returns an array with all attendees...
now heres the problem:
This event has about 18.000 attendees right now.
The api call returns a max number of 992 attendees (and not 18000 as it should).
I tried
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending?limit=20000');
for testing but it doesn't change anything.
So my actual question is:
If I can't get it to work by using the graph api what would be a good alternative? (Parsing the html of the event page maybe?) Right now I'm changing the value by hand every few hours which is tedious and unnecessary.
Actually there are two parameters, limit and offset. I think that you will have to play with both and continue making calls until one returns less than the max. limit.
Something like this, but in a recursive approach (I'm writting pseudo-code):
offset = 0;
maxLimit = 992;
totalAttendees = count(result)
if (totalAttendees >= maxLimit)
{
// do your stuff with each attendee
offset += totalAttendees;
// make a new call with the updated offset
// and check again
}
I've searched a lot and this is how I fixed it:
The requested URL should look something like this.
Here is where you can test it and here is the code I used:
function events_get_facebook_data($event_id) {
if (!$event_id) {
return false;
}
$token = klicango_friends_facebook_token();
if ($token) {
$parameters['access_token'] = $token;
$parameters['fields']= 'attending_count,invited_count';
$graph_url = url('https://graph.facebook.com/v2.2/' . $event_id , array('absolute' => TRUE, 'query' => $parameters));
$graph_result = drupal_http_request($graph_url, array(), 'GET');
if(is_object($graph_result) && !empty($graph_result->data)) {
$data = json_decode($graph_result->data);
$going = $data->attending_count;
$invited = $data->invited_count;
return array('going' => $going, 'invited' => $invited);
}
return false;
}
return false;
}
Try
SELECT eid , attending_count, unsure_count,all_members_count FROM event WHERE eid ="event"

Categories