I'm a complete newb in PHP, and the only reason I got this far was because I was trying to guess what everything does. I guess I was lucky that it worked this far.
So basically, I'm using the PHP Wake On LAN code that I found here to make a simple page that I log into, to remotely turn on my computer. I decided to add a username, rather than just a password, so maybe I could have multiple users. I've done everything successfully so far except one thing. When I log in, check my computer, and hit "Wake all selected", it logs me out immediately and doesn't send the magic packet. Any tips on what I could change to fix this? As soon as I remove the 'and' and the username bit in the if statement that checks for both user and pass to be correct, it works. But then there's no user and pass verifying going on. The if statement I'm talking about is the second if under the === Test for password protection === part.
You can demo the code on my site to see the issue in action here: http://trivisionzero.com/wol/
Just use 'user', 'pass'. (to recreate it, select any computer and press wake button)
Full code so far:
<center>
<br><br><br><br><br>
<?php
/* ============================== Configuration settings ====================================== */
/* List of PCs that may be woken */
$config_network_data_array[] = array("name" => "Shane-EPC", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
$config_network_data_array[] = array("name" => "Demo", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
$config_network_data_array[] = array("name" => "Demo", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
// Port number where the computer is listening. Usually, any number between 1-50000 will do. Normally people choose 7 or 9.
$socket_number = "7";
$my_password = 'pass';
$my_username = 'user';
$html_title = '<H2>TrivisionZero PC Waker</H2>';
$config_table_columns = array('name', 'IP', 'MAC', 'links');
# The following function is copied (with some edits, to suppress output and return TRUE or an error message) from:
# http://www.hackernotcracker.com/2006-04/wol-wake-on-lan-tutorial-with-bonus-php-script.html
# Wake on LAN - (c) HotKey#spr.at, upgraded by Murzik
# Modified by Allan Barizo http://www.hackernotcracker.com
flush();
function WakeOnLan($addr, $mac,$socket_number) {
$separator = ':';
if (strstr ( $mac, '-' ) ) {
$separator = '-';
}
$addr_byte = explode($separator, $mac);
$hw_addr = '';
for ($a=0; $a <6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr;
// send it to the broadcast address using UDP
// SQL_BROADCAST option isn't help!!
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($s == false) {
// echo "Error creating socket!\n";
// echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
return "Error creating socket!\nError code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_erro
($s));
// return FALSE;
}
else {
// setting a broadcast option to socket:
$opt_ret = socket_set_option($s, 1, 6, TRUE);
if($opt_ret <0) {
// echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
return "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
// return FALSE;
}
if(socket_sendto($s, $msg, strlen($msg), 0, $addr, $socket_number)) {
// echo "Magic Packet sent successfully!";
socket_close($s);
return TRUE;
}
else {
// echo "Magic packet failed!";
return "Magic packet failed!";
// return FALSE;
}
}
}
/* ============================== some predefined texts ====================================== */
$display_sent = 'Magic Packet sent successfully!';
$button_text = 'Wake!';
$button_text2 = 'Wake all selected';
//this is where I added my username part
$username_element = "<P>Username: <input type=\"text\" name=\"username\" />";
$password_element = "<P>Password: <input type=\"password\" name=\"password\" /><input type=\"submit\" name=\"submit\" value = \"Login\" />";
$table_html = "<TABLE border=\"2\">\n";
$logout_html = '';
/* ========================= Test for password protection ==================================== */
$wake_MAC_array = array();
if (!isset ($_POST['logout'])) {
$input_password = $_POST['password'];
$input_username = $_POST['username'];
}
//($my_password === '') is if you want no password
if (($input_password === $my_password) and ($input_username === $my_username)) {
$logged_in = TRUE;
$hidden_login = "<input type=\"hidden\" name=\"password\" value=\"$my_password\"/>";
if ($my_password !== '') {
$logout_html = "\n<P><input type=\"submit\" name=\"logout\" value=\"Log Out\"/>\n";
}
if ( (isset ($_POST['tickbox'])) and (is_array($_POST['tickbox']) ) ) {
$checkbox_array = $_POST['tickbox'];
foreach ($checkbox_array as $mac_address => $tickbox_setting) {
$wake_MAC_array[$mac_address] = $tickbox_setting;
}
}
} else {
$logged_in = FALSE;
$hidden_login = '';
$table_html_user = $username_element;
$table_html = $password_element;
}
/* ================================ LOGGED-IN users only ===================================== */
/* ======================= construct table for listing of devices ============================ */
if ($logged_in == TRUE) {
$table_row = "\n<TR>";
foreach ($config_table_columns as $key => $column_heading) {
$table_row .= '<TD>' . $column_heading . '</TD>';
}
$table_row .= '<TD>Wake Up!</TD>';
$table_row .= '<TD>status</TD>';
$table_html .= $table_row . "</TR>\n";
foreach ($config_network_data_array as $device_key => $device_values) {
$table_row = "\n<TR>";
$mac = $device_values['MAC'];
$device_name = $device_values['name'];
$status_cell = '<TD> </TD>';
foreach ($config_table_columns as $key => $column_heading) {
if (isset ( $device_values[$column_heading])) {
$value = $device_values[$column_heading];
if ($column_heading == 'MAC') {
/* special coding for MAC address column; prepare clickable button */
$this_MAC = $value;
$value = "<input type=\"submit\" name=\"wake_MAC\" value = \"$value\" />";
if (( $_POST['wake_MAC'] === $this_MAC ) or (array_key_exists ($this_MAC,
$wake_MAC_array))) {
$status = WakeOnLan ($device_values['WakeIP'], $this_MAC, $socket_number) ;
if ( $status === TRUE ) {
$status = $display_sent;
}
$status_cell = "<TD>$status</TD>";
}
}
} elseif ($column_heading == 'links') {
/* special coding for links column; prepare clickable links from $config_network_links_array */
$value = '';
if (isset ( $config_network_links_array[$device_name])) {
foreach ($config_network_links_array[$device_name] as $link_title => $link_URL) {
if ( $value !== '') {
$value .= '<BR />';
}
$value .= '' . $link_title . '';
}
}
} else {
$value = '';
}
if ($value === '') {
$value = ' ';
}
$table_row .= '<TD>' . $value . '</TD>';
}
/* now add a checkbox to wake up this device */
$table_row .= '<TD>' . "<input type=\"checkbox\" name=\"tickbox[$this_MAC]\" />" . '</TD>';
/* now add the status message (if applicable) for the attempt to send a packet to this device */
$table_row .= $status_cell;
$table_html .= $table_row . "</TR>\n";
}
$table_html .= "</TABLE>\n";
$table_html .= "<P><input type=\"submit\" name=\"wake all\" value = \"$button_text2\" />\n";
}
/* =========================================================================================== */
/* ======================= Now output the html that we've built ============================== */
echo $html_title;
echo "<FORM name=\"input\" action=\"" .$_SERVER['PHP_SELF'] . "\" method=\"post\">";
echo '<P>';
echo $table_html_user;
echo $table_html;
echo $hidden_login;
echo $logout_html;
echo "</FORM>\n";
?>
</center>
When you are logged in and then submit the form to wake a machine, you are passing the password in a hidden field, but not the username.
As you are not passing the username, $input_username = null and thus the check if (($input_password === $my_password) and ($input_username === $my_username)) becomes if (('pass' === 'pass') and (null === 'user')) which is false and this is why you get logged out.
Related
I am using Moodle version 3.8.4+ and PHP version 7.2.33 . Today I noticed a strange issue when I was trying to send a message to students, the message was:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays! More information about this error
I purge all caches as the suggestion was on "more information" section but it did not work.
I run the same Moodle version and PHP version on non production environment with the debugging mode and then I got this error message:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays!
More information about this error
Debug info:
Error code: codingerror
Stack trace:
line 405 of /lib/weblib.php: coding_exception thrown
line 460 of /lib/weblib.php: call to moodle_url->params()
line 49 of /mod/reservation/messageselect.php: call to moodle_url->param()
Output buffer: Invalid array parameter detected in required_param(): messagebody
line 655 of /lib/moodlelib.php: call to debugging()
line 30 of /mod/reservation/messageselect.php: call to optional_param()
The messageselect.php file is this but I am not able to see any issues here:
require_once('../../config.php');
require_once($CFG->dirroot.'/message/lib.php');
$id = required_param('id', PARAM_INT);
$messagebody = optional_param('messagebody', '', PARAM_CLEANHTML);
$send = optional_param('send', '', PARAM_BOOL);
$preview = optional_param('preview', '', PARAM_BOOL);
$edit = optional_param('edit', '', PARAM_BOOL);
$returnto = optional_param('returnto', new moodle_url('/mod/reservation/view.php', array('id' => $id)), PARAM_LOCALURL);
$format = optional_param('format', FORMAT_MOODLE, PARAM_INT);
$deluser = optional_param('deluser', 0, PARAM_INT);
if (isset($id)) {
if (! $cm = get_coursemodule_from_id('reservation', $id)) {
error('Course Module ID was incorrect');
}
if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
error('Course is misconfigured');
}
}
$url = new moodle_url('/mod/reservation/messageselect.php', array('id' => $id));
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
if ($send !== '') {
$url->param('send', $send);
}
if ($preview !== '') {
$url->param('preview', $preview);
}
if ($edit !== '') {
$url->param('edit', $edit);
}
if ($returnto !== '') {
$url->param('returnto', $returnto);
}
if ($format !== FORMAT_MOODLE) {
$url->param('format', $format);
}
if ($deluser !== 0) {
$url->param('deluser', $deluser);
}
$modulecontext = context_module::instance($cm->id);
$PAGE->set_url($url);
$PAGE->set_context($modulecontext);
require_login($course->id, false, $cm);
$coursecontext = context_course::instance($course->id);
$systemcontext = context_system::instance();
require_capability('moodle/course:bulkmessaging', $coursecontext);
if (empty($SESSION->reservation_messageto)) {
$SESSION->reservation_messageto = array();
}
if (!array_key_exists($id, $SESSION->reservation_messageto)) {
$SESSION->reservation_messageto[$id] = array();
}
if ($deluser) {
$idinmessageto = array_key_exists($id, $SESSION->reservation_messageto);
if ($idinmessageto && array_key_exists($deluser, $SESSION->reservation_messageto[$id])) {
unset($SESSION->reservation_messageto[$id][$deluser]);
}
}
if (empty($SESSION->reservation_messageselect[$id]) || $messagebody) {
$SESSION->reservation_messageselect[$id] = array('messagebody' => $messagebody);
}
$messagebody = $SESSION->reservation_messageselect[$id]['messagebody'];
$count = 0;
if ($data = data_submitted()) {
require_sesskey();
foreach ($data as $k => $v) {
if (preg_match('/^(user|teacher)(\d+)$/', $k, $m)) {
if (!array_key_exists($m[2], $SESSION->reservation_messageto[$id])) {
$returnfields = 'id,firstname,lastname,idnumber,email,mailformat,lastaccess, lang, maildisplay';
if ($user = $DB->get_record_select('user', "id = ?", array($m[2]), $returnfields)) {
$SESSION->reservation_messageto[$id][$m[2]] = $user;
$count++;
}
}
}
}
}
$strtitle = get_string('message', 'reservation');
$PAGE->navbar->add($strtitle);
$PAGE->set_title($strtitle);
$PAGE->set_heading($strtitle);
echo $OUTPUT->header();
// If messaging is disabled on site, we can still allow users with capabilities to send emails instead.
if (empty($CFG->messaging)) {
echo $OUTPUT->notification(get_string('messagingdisabled', 'message'));
}
if ($count) {
if ($count == 1) {
$heading = get_string('addedrecip', 'moodle', $count);
} else {
$heading = get_string('addedrecips', 'moodle', $count);
}
echo $OUTPUT->heading($heading);
}
if (!empty($messagebody) && !$edit && !$deluser && ($preview || $send)) {
require_sesskey();
if (count($SESSION->reservation_messageto[$id])) {
if (!empty($preview)) {
echo '<form method="post" action="messageselect.php" style="margin: 0 20px;">
<input type="hidden" name="returnto" value="'.s($returnto).'" />
<input type="hidden" name="id" value="'.$id.'" />
<input type="hidden" name="format" value="'.$format.'" />
<input type="hidden" name="sesskey" value="' . sesskey() . '" />
';
echo "<h3>".get_string('previewhtml')."</h3>";
echo "<div class=\"messagepreview\">\n".format_text($messagebody, $format)."\n</div>\n";
echo '<p align="center"><input type="submit" name="send" value="'.get_string('sendmessage', 'message').'" />'."\n";
echo '<input type="submit" name="edit" value="'.get_string('update').'" /></p>';
echo "\n</form>";
} else if (!empty($send)) {
$fails = array();
foreach ($SESSION->reservation_messageto[$id] as $user) {
if (!message_post_message($USER, $user, $messagebody, $format)) {
$user->fullname = fullname($user);
$fails[] = get_string('messagedselecteduserfailed', 'moodle', $user);
};
}
if (empty($fails)) {
echo $OUTPUT->heading(get_string('messagedselectedusers'));
unset($SESSION->reservation_messageto[$id]);
unset($SESSION->reservation_messageselect[$id]);
} else {
echo $OUTPUT->heading(get_string('messagedselectedcountusersfailed', 'moodle', count($fails)));
echo '<ul>';
foreach ($fails as $f) {
echo '<li>', $f, '</li>';
}
echo '</ul>';
}
echo '<p align="center">'.get_string('backtoparticipants').'</p>';
}
echo $OUTPUT->footer();
exit;
} else {
echo $OUTPUT->notification(get_string('nousersyet'));
}
}
echo '<p align="center">'.get_string("keepsearching").''.
((count($SESSION->reservation_messageto[$id])) ? ', '.get_string('usemessageform') : '').'</p>';
if ((!empty($send) || !empty($preview) || !empty($edit)) && (empty($messagebody))) {
echo $OUTPUT->notification(get_string('allfieldsrequired'));
}
if (count($SESSION->reservation_messageto[$id])) {
require_sesskey();
require("message.html");
}
$PAGE->requires->yui_module('moodle-core-formchangechecker',
'M.core_formchangechecker.init',
array(array(
'formid' => 'theform'
))
);
$PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
echo $OUTPUT->footer();
```php
It looks like the massagebody param in the request that initiates this process is using array syntax, like ?messagebody[]=foo instead of ?messagebody=foo, so the error is in whatever page the request originated from. You can either try to figure out why that is and change it, or make a change to this messageselect.php file to flatten the parameter. To do that you would change this:
<?php
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
to this:
<?php
if ($messagebody !== '') {
if(is_array($messagebody))
{
$messagebody = array_shift($messagebody);
}
$url->param('messagebody', $messagebody);
}
However be aware that if the page is sending this parameter as an array, it is quite likely that others will be sent that way as well. Usually you would send parameters using array syntax so that multiple records can be processed in one request, so that messagebody[1] would correlate to format[1], messagebody[2] would correlate to format[2], and so on. The code in messageselect.php is clearly not expecting this. I would be interested to find out what the story is for the page that sends requests here.
In a list of Amazon products that I retrieve by analyzing the WordPress database, I have this code that allows me to get product by product their Amazon information:
function get_product_infos(asin, ext){
$.post(window.location.href, {
activate: 'get-product-informations',
asin: asin,
ext: ext
}, function(data){
//var json = JSON.parse(data);
console.log(data);
/*if(json.response === 'alright'){
var current_asin = json.current_asin;
current_asin = $('#'+current_asin);
var next_asin = current_asin.next().attr('id');
var next_ext = current_asin.next().attr('data-domain-ext');
current_asin.find('td').first().find('.progress').text('ok');
if(typeof next_asin !== typeof undefined && next_asin !== false){
get_product_infos(next_asin, next_ext);
}
}*/
});
}
File called with $.post() to have the product information from Amazon:
<?php
$autorisation = isset($_POST['activate']) ? $_POST['activate'] : '';
$current_asin = isset($_POST['asin']) ? $_POST['asin'] : '';
$current_ext = isset($_POST['ext']) ? $_POST['ext'] : '';
if($autorisation !== 'get-product-informations'){
return;
}
use pa\src\com\amazon\paapi5\v1\api\DefaultApi;
use pa\src\ApiException;
use pa\src\Configuration;
use pa\src\com\amazon\paapi5\v1\GetItemsRequest;
use pa\src\com\amazon\paapi5\v1\GetItemsResource;
use pa\src\com\amazon\paapi5\v1\PartnerType;
use pa\src\com\amazon\paapi5\v1\ProductAdvertisingAPIClientException;
require_once(plugin_dir_url( __FILE__ . '/bundles/admin-pages/tool/crawling-system/pa/vendor/autoload.php' ));
function parseResponse($items){
$mappedResponse = array();
foreach ($items as $item) {
$mappedResponse[$item->getASIN()] = $item;
}
return $mappedResponse;
}
function getItems(){
global $wpdb;
$prefix_table = $wpdb->prefix;
$table_name = $prefix_table.'azon_lc';
$result = ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name) ? $wpdb->get_results("SELECT * FROM $table_name") : '';
$access_key = ($result !== '') ? $result[0]->access_key : '';
$secret_key = ($result !== '') ? $result[0]->secret_key : '';
$associate_tag = ($result !== '') ? $result[0]->associate_tag : '';
$config = new Configuration();
/*
* Add your credentials
* Please add your access key here
*/
$config->setAccessKey($access_key);
# Please add your secret key here
$config->setSecretKey($secret_key);
# Please add your partner tag (store/tracking id) here
$partnerTag = $associate_tag;
/*
* PAAPI host and region to which you want to send request
* For more details refer: https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#host-and-region
*/
$config->setHost('webservices.amazon.'.$current_ext);
$config->setRegion('us-east-1');
$apiInstance = new DefaultApi(
/*
* If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
* This is optional, `GuzzleHttp\Client` will be used as default.
*/
new pa\vendor\GuzzleHttp\guzzle\src\Client(), $config);
# Choose item id(s)
$itemIds = array($current_asin);
/*
* Choose resources you want from GetItemsResource enum
* For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-items.html#resources-parameter
*/
$resources = array(
GetItemsResource::ITEM_INFOTITLE,
GetItemsResource::OFFERSLISTINGSPRICE);
# Forming the request
$getItemsRequest = new GetItemsRequest();
$getItemsRequest->setItemIds($itemIds);
$getItemsRequest->setPartnerTag($partnerTag);
$getItemsRequest->setPartnerType(PartnerType::ASSOCIATES);
$getItemsRequest->setResources($resources);
# Validating request
$invalidPropertyList = $getItemsRequest->listInvalidProperties();
$length = count($invalidPropertyList);
if ($length > 0) {
echo "Error forming the request", PHP_EOL;
foreach ($invalidPropertyList as $invalidProperty) {
echo $invalidProperty, PHP_EOL;
}
return;
}
# Sending the request
try {
$getItemsResponse = $apiInstance->getItems($getItemsRequest);
echo 'API called successfully', PHP_EOL;
echo 'Complete Response: ', $getItemsResponse, PHP_EOL;
# Parsing the response
if ($getItemsResponse->getItemsResult() != null) {
echo 'Printing all item information in ItemsResult:', PHP_EOL;
if ($getItemsResponse->getItemsResult()->getItems() != null) {
$responseList = parseResponse($getItemsResponse->getItemsResult()->getItems());
foreach ($itemIds as $itemId) {
echo 'Printing information about the itemId: ', $itemId, PHP_EOL;
$item = $responseList[$itemId];
if ($item != null) {
if ($item->getASIN()) {
echo 'ASIN: ', $item->getASIN(), PHP_EOL;
}
if ($item->getItemInfo() != null and $item->getItemInfo()->getTitle() != null
and $item->getItemInfo()->getTitle()->getDisplayValue() != null) {
echo 'Title: ', $item->getItemInfo()->getTitle()->getDisplayValue(), PHP_EOL;
}
if ($item->getDetailPageURL() != null) {
echo 'Detail Page URL: ', $item->getDetailPageURL(), PHP_EOL;
}
if ($item->getOffers() != null and
$item->getOffers()->getListings() != null
and $item->getOffers()->getListings()[0]->getPrice() != null
and $item->getOffers()->getListings()[0]->getPrice()->getDisplayAmount() != null) {
echo 'Buying price: ', $item->getOffers()->getListings()[0]->getPrice()
->getDisplayAmount(), PHP_EOL;
}
} else {
echo "Item not found, check errors", PHP_EOL;
}
}
}
}
if ($getItemsResponse->getErrors() != null) {
echo PHP_EOL, 'Printing Errors:', PHP_EOL, 'Printing first error object from list of errors', PHP_EOL;
echo 'Error code: ', $getItemsResponse->getErrors()[0]->getCode(), PHP_EOL;
echo 'Error message: ', $getItemsResponse->getErrors()[0]->getMessage(), PHP_EOL;
}
} catch (ApiException $exception) {
echo "Error calling PA-API 5.0!", PHP_EOL;
echo "HTTP Status Code: ", $exception->getCode(), PHP_EOL;
echo "Error Message: ", $exception->getMessage(), PHP_EOL;
if ($exception->getResponseObject() instanceof ProductAdvertisingAPIClientException) {
$errors = $exception->getResponseObject()->getErrors();
foreach ($errors as $error) {
echo "Error Type: ", $error->getCode(), PHP_EOL;
echo "Error Message: ", $error->getMessage(), PHP_EOL;
}
} else {
echo "Error response body: ", $exception->getResponseBody(), PHP_EOL;
}
} catch (Exception $exception) {
echo "Error Message: ", $exception->getMessage(), PHP_EOL;
}
}
getItems();
exit;?>
I tested the file in several ways to understand when there was an error and I determined that by trying to use this code it crashes:
$config = new Configuration();
I would like to determine why the call returns a 500 error? There is obviously something that I do not understand.
I have an issue where I need to data from a RETS server and populate it on the database, I was able to get all but two tables to properly automate this data in, but I'm having issues with the last (and biggest) two. After looking at it, the issue is timeout with the server, it cannot finish in time for the database to populate.
I am working off of a godaddy server and already have the maximum time I can set for the program to run, the only thing I can do now is figure out a way to speed up my code so it finishes in time, and would like some help figuring that out.
The code (posted below) was modified to fit my needs from here: https://github.com/coreyrowell/retshelper/blob/master/rets_helper.php
While it works well and I was able to get it working, I haven't been able to figure out the best way to speed it up. Any help would be sincerely appreciated.
<?php
/*
.---------------------------------------------------------------------------.
| Software: RETSHELPER - PHP Class to interface RETS with Database |
| Version: 1.0 |
| Contact: corey#coreyrowell.com |
| Info: None |
| Support: corey#coreyrowell.com |
| ------------------------------------------------------------------------- |
| Author: Corey Rowell - corey#coreyrowell.com |
| Copyright (c) 2013, Corey Rowell. All Rights Reserved. |
| ------------------------------------------------------------------------- |
| License: This content is released under the |
| (http://opensource.org/licenses/MIT) MIT License. | |
'---------------------------------------------------------------------------'
*/
/*
.---------------------------------------------------------------------------.
| This software requires the use of the PHPRETS library |
| http://troda.com/projects/phrets/ |
'---------------------------------------------------------------------------'
*/
define("BASE_PATH",dirname(__FILE__)."/");
ini_set('mysql.connect_timeout',0);
ini_set('default_socket_timeout',0);
class RETSHELPER
{
// Defaults
private $rets, $auth, $config, $database, $mysqli, $data, $log, $scriptstart, $scriptend,
$previous_start_time, $current_start_time, $updates_log, $active_ListingRids = array();
public function __construct()
{
// Require PHRETS library
require_once("phrets.php");
// Start rets connection
$this->rets = new phRETS;
$this->scriptstart = date("m-d-y_h-i-s", time());
// RETS Server Info
$this->auth['url'] = 'redacted';//MLS_URL;//MLS_URL;
$this->auth['username'] = 'redacted'; //MLS_USERNAME;
$this->auth['password'] = 'redacted'; //MLS_PASS;
$this->auth['retsversion'] = ''; //USER Agent Version
$this->auth['useragent'] = ''; //USER Agent
// RETS Options
$this->config['property_classes'] = array("A");//,"B","C","D","E","F");
$this->config['KeyField'] = "LIST_1";
$this->config['offset_support'] = TRUE; // Enable if RETS server supports 'offset'
$this->config['useragent_support'] = FALSE;
$this->config['images_path'] = BASE_PATH."listing_photos/";
$this->config['logs_path'] = BASE_PATH."logs/";
$this->config['start_times_path'] = BASE_PATH."logs/";
$this->config['previous_start_time'] = $this->get_previous_start_time();
$this->config['create_tables'] = FALSE; // Create tables for classes (terminates program)
// Log to screen?
$this->config['to_screen'] = TRUE;
// Database Config
$this->database['host'] = 'redacted'; //DB_SERVER;
$this->database['username'] = 'redacted'; //DB_USER;
$this->database['password'] = 'redacted'; //DB_PASS;
$this->database['database'] = 'redacted'; //DB_NAME;
$this->config_init();
// Load the run function
$this->run();
}
private function config_init()
{
// Set offset support based on config
if($this->config['offset_support'])
{
$this->rets->SetParam("offset_support", true);
} else {
$this->rets->SetParam("offset_support", false);
}
if($this->config['useragent_support'])
{
$this->rets->AddHeader("RETS-Version", $this->auth['retsversion']);
$this->rets->AddHeader("User-Agent", $this->auth['useragent']);
}
}
public function run()
{
// Start Logging
$this->logging_start();
// RETS Connection
$this->connect();
// Connect to Database
$this->database_connect();
if($this->config['create_tables'])
{
$this->log_data("Creating database tables, program will exit after finishing.");
foreach ($this->config['property_classes'] as $class)
{
$this->log_data("Creating table for: " . $class);
$this->create_table_for_property_class($class);
}
$this->log_data("Exiting program.");
return;
}
// Get Properties (and images)
$this->get_properties_by_class();
// Close RETS Connection
$this->disconnect();
// Delete inactive listings
$this->database_delete_records();
// Insert new listings
$this->database_insert_records();
// Disconnect from Database
$this->database_disconnect();
// End Logging
$this->logging_end();
// Time for next scheduled update
$this->set_previous_start_time();
}
private function connect()
{
$this->log_data("Connecting to RETS...");
// Connect to RETS
$connect = $this->rets->Connect($this->auth['url'], $this->auth['username'], $this->auth['password']);
if($connect)
{
$this->log_data("Successfully connected to RETS.");
return TRUE;
} else {
$error = $this->rets->Error();
if($error['text'])
{
$error = $error['text'];
} else {
$error = "No error message returned from RETS. Check RETS debug file.";
}
$this->log_error("Failed to connect to RETS.\n".$error);
die();
}
}
private function get_properties_by_class()
{
$this->log_data("Getting Classes...");
foreach ($this->config['property_classes'] as $class)
{
$this->log_data("Getting Class: ".$class);
// Set
$fields_order = array();
$mod_timestamp_field = $this->get_timestamp_field($class);
$previous_start_time = $this->config['previous_start_time'];
$search_config = array('Format' => 'COMPACT-DECODED', 'QueryType' => 'DMQL2', 'Limit'=> 1000, 'Offset' => 1, 'Count' => 1);
/*--------------------------------------------------------------------------------.
| |
| If you're having problems, they probably lie here in the $query and/or $search. |
| |
'--------------------------------------------------------------------------------*/
// Query
$query = "({$mod_timestamp_field}=2016-09-16T00:00:00-2016-09-16T01:00:00)";//{$previous_start_time}+)";
// Run Search
$search = $this->rets->SearchQuery("Property", $class, $query, $search_config);
// Get all active listings
$query_all = "({$mod_timestamp_field}=1980-01-01T00:00:00+)";
$search_all = $this->rets->SearchQuery("Property", $class, $query_all, array('Format'=>'COMPACT', 'Select'=>$this->config['KeyField']));
$tmpArray = array();
while($active_rid = $this->rets->FetchRow($search_all)) {
array_push($tmpArray, $active_rid[$this->config['KeyField']]);
}
$this->active_ListingRids['property_'.strtolower($class)] = $tmpArray;
$data = array();
if ($this->rets->NumRows($search) > 0)
{
// Get columns
$fields_order = $this->rets->SearchGetFields($search);
$this->data['headers'] = $fields_order;
// Process results
while ($record = $this->rets->FetchRow($search))
{
$this_record = array();
// Loop it
foreach ($fields_order as $fo)
{
$this_record[$fo] = $record[$fo];
}
$ListingRid = $record[$this->config['KeyField']];
$data[] = $this_record;
}
}
// Set data
$this->data['classes'][$class] = $data;
$this->log_data("Finished Getting Class: ".$class . "\nTotal found: " .$this->rets->TotalRecordsFound());
// Free RETS Result
$this->rets->FreeResult($search);
}
}
private function get_timestamp_field($class)
{
$class = strtolower($class);
switch($class)
{
case 'a':
$field = "LIST_87";
break;
}
return $field;
}
private function disconnect()
{
$this->log_data("Disconnected from RETS.");
$this->rets->Disconnect();
}
private function database_connect()
{
$this->log_data("Connecting to database...");
$host = $this->database['host'];
$username = $this->database['username'];
$password = $this->database['password'];
$database = $this->database['database'];
// Create connection
$this->mysqli = new mysqli($host, $username, $password, $database);
// Throw error if connection fails
if ($this->mysqli->connect_error) {
$this->log_error("Database Connection Error". $this->mysqli->connect_error);
die('Connect Error (' . $this->mysqli->connect_errno . ') '
. $this->mysqli->connect_error);
}
}
private function database_delete_records()
{
$this->log_data("Updating database...");
// Loop through each table and update
foreach($this->config['property_classes'] as $class)
{
// Get Tables
$table = "rets_property_".strtolower($class);
$activeListings = $this->active_ListingRids['property_'.strtolower($class)];
$sql = "DELETE FROM {$table} WHERE {$this->config['KeyField']} NOT IN (".implode(',', $activeListings).");";
$this->mysqli->query($sql);
if($this->mysqli->affected_rows > 0)
{
$this->log_data("Deleted {$this->mysqli->affected_rows} Listings.");
// return TRUE;
} else if($this->mysqli->affected_rows == 0) {
$this->log_data("Deleted {$this->mysqli->affected_rows} Listings.");
} else {
$this->log_data("Deleting database records failed \n\n" . mysqli_error($this->mysqli));
// return FALSE;
}
}
}
private function database_insert_records()
{
$this->log_data("Inserting records...");
foreach($this->config['property_classes'] as $class)
{
// Get Tables
$table = "rets_property_".strtolower($class);
// Get data
$data_row = $this->data['classes'][$class];
// Defaults
$total_rows = 0;
$total_affected_rows = 0;
// Loop through data
foreach($data_row as $drow)
{
// Clean data
// replace empty with NULL
// and wrap data in quotes
$columns = array();
$values = array();
foreach($drow as $key => $val)
{
if($val === '')
{
$val = '""';
} else {
$val = mysqli_real_escape_string($this->mysqli ,$val);
$val = "'$val'";
}
$columns[] = $key;
$values[] = $val;
}
// Implode data rows with commas
$values = implode(', ', $values);
$columns = implode(', ', $columns);
// Build SQL
$sql = "REPLACE INTO {$table} ({$columns}) VALUES ({$values})";
// Do query
$this->mysqli->query($sql);
if($this->mysqli->affected_rows > 0)
{
$total_affected_rows++;
} else {
$this->log_error("Failed to insert the following record: ".$sql . "\n\n" . mysqli_error($this->mysqli));
}
$total_rows++;
}
$this->log_data("Done inserting data. ".$class."\nTotal Records: ".$total_rows." .\nTotal Inserted: ".$total_affected_rows);
}
}
private function database_disconnect()
{
$this->log_data("Database disconnected...");
// Close connection
$this->mysqli->close();
}
private function create_table_for_property_class($class)
{
// gets resource information. need this for the KeyField
$rets_resource_info = $this->rets->GetMetadataInfo();
$resource = "Property";
// pull field format information for this class
$rets_metadata = $this->rets->GetMetadata($resource, $class);
$table_name = "rets_".strtolower($resource)."_".strtolower($class);
// i.e. rets_property_resi
$sql = $this->create_table_sql_from_metadata($table_name, $rets_metadata, $rets_resource_info[$resource]['KeyField']);
$this->mysqli->query($sql);
}
private function create_table_sql_from_metadata($table_name, $rets_metadata, $key_field, $field_prefix = "")
{
$sql_query = "CREATE TABLE {$table_name} (\n";
foreach ($rets_metadata as $field) {
$field['SystemName'] = "`{$field_prefix}{$field['SystemName']}`";
$cleaned_comment = addslashes($field['LongName']);
$sql_make = "{$field['SystemName']} ";
if ($field['Interpretation'] == "LookupMulti") {
$sql_make .= "TEXT";
}
elseif ($field['Interpretation'] == "Lookup") {
$sql_make .= "VARCHAR(50)";
}
elseif ($field['DataType'] == "Int" || $field['DataType'] == "Small" || $field['DataType'] == "Tiny") {
$sql_make .= "INT({$field['MaximumLength']})";
}
elseif ($field['DataType'] == "Long") {
$sql_make .= "BIGINT({$field['MaximumLength']})";
}
elseif ($field['DataType'] == "DateTime") {
$sql_make .= "DATETIME default '0000-00-00 00:00:00' not null";
}
elseif ($field['DataType'] == "Character" && $field['MaximumLength'] <= 255) {
$sql_make .= "VARCHAR({$field['MaximumLength']})";
}
elseif ($field['DataType'] == "Character" && $field['MaximumLength'] > 255) {
$sql_make .= "TEXT";
}
elseif ($field['DataType'] == "Decimal") {
$pre_point = ($field['MaximumLength'] - $field['Precision']);
$post_point = !empty($field['Precision']) ? $field['Precision'] : 0;
$sql_make .= "DECIMAL({$field['MaximumLength']},{$post_point})";
}
elseif ($field['DataType'] == "Boolean") {
$sql_make .= "CHAR(1)";
}
elseif ($field['DataType'] == "Date") {
$sql_make .= "DATE default '0000-00-00' not null";
}
elseif ($field['DataType'] == "Time") {
$sql_make .= "TIME default '00:00:00' not null";
}
else {
$sql_make .= "VARCHAR(255)";
}
$sql_make .= " COMMENT '{$cleaned_comment}'";
$sql_make .= ",\n";
$sql_query .= $sql_make;
}
$sql_query .= "`Photos` TEXT COMMENT 'Photos Array', ";
$sql_query .= "PRIMARY KEY(`{$field_prefix}{$key_field}`) )";
return $sql_query;
}
private function get_previous_start_time()
{
$filename = "previous_start_time_A.txt";
// See if file exists
if(file_exists($this->config['start_times_path'].$filename))
{
$time=time();
$this->updates_log = fopen($this->config['start_times_path'].$filename, "r+");
$this->previous_start_time = fgets($this->updates_log);
$this->current_start_time = date("Y-m-d", $time) . 'T' . date("H:i:s", $time);
} else {
// Create file
$this->updates_log = fopen($this->config['start_times_path'].$filename, "w+");
fwrite($this->updates_log, "1980-01-01T00:00:00\n");
$this->get_previous_start_time();
}
// fgets reads up to & includes the first newline, strip it
return str_replace("\n", '', $this->previous_start_time);
}
private function set_previous_start_time()
{
$file = $this->config['start_times_path'] . "previous_start_time_A.txt";
$file_data = $this->current_start_time."\n";
$file_data .= file_get_contents($file);
file_put_contents($file, $file_data);
}
private function logging_start()
{
$filename = "Log".date("m-d-y_h-i-s", time()).".txt";
// See if file exists
if(file_exists($this->config['logs_path'].$filename))
{
$this->log = fopen($this->config['logs_path'].$filename, "a");
} else {
// Create file
$this->log = fopen($this->config['logs_path'].$filename, "w+");
}
}
private function log_data($data)
{
$write_data = "\nInfo Message: [".date("m/d/y - h:i:s", time())."]\n------------------------------------------------\n";
$write_data .= $data."\n";
$write_data .= "\n------------------------------------------------\n";
fwrite($this->log, $write_data);
if($this->config['to_screen'])
{
echo str_replace(array("\n"), array('<br />'), $write_data);
}
}
private function log_error($error)
{
$write_data = "\nError Message: [".date("m/d/y - h:i:s", time())."]\n------------------------------------------------\n";
$write_data .= $error."\n";
$write_data .= "\n------------------------------------------------\n";
fwrite($this->log, $write_data);
if($this->config['to_screen'])
{
echo str_replace(array("\n"), array('<br />'), $write_data);
}
}
private function logging_end()
{
$this->scriptend = date("m-d-y_h-i-s", time());
$this->log_data("Closing log file.\n
Start Time: {$this->scriptstart}\n
End Time: {$this->scriptend}");
fclose($this->log);
}
}
// Load the class
$retshelper = new RETSHELPER;
Sorry for the wall of code; I would shorten it down but I'm at a loss with what is still needed and what isn't. Once again, any help would or a point into the right direction would be appreciated.
For some odd reason im unable to retrieve group memebers from domain users or any group for that batter.
Base DN is set to dc=domain,dc=com Ive hits block here. When I use the test tool im able to authenticate [NOTICE] Authentication successfull for "rpimentel#domain.com"
Something is missing. Something simple, that im over looking. What could it be?
// Extend the ADIntegrationPlugin class
class BulkImportADIntegrationPlugin extends ADIntegrationPlugin {
/**
* Output formatted debug informations
*
* #param integer level
* #param string $notice
*/
protected function _log($level = 0, $info = '') {
if ($level <= $this->_loglevel) {
switch ($level) {
case ADI_LOG_DEBUG:
$class = 'debug';
$type = '[DEBUG] ';
break;
case ADI_LOG_INFO:
$class = 'info';
$type = '[INFO] ';
break;
case ADI_LOG_NOTICE:
$class = 'notice';
$type = '[NOTICE] ';
break;
case ADI_LOG_WARN:
$class = 'warn';
$type = '[WARN] ';
break;
case ADI_LOG_ERROR:
$class = 'error';
$type = '[ERROR] ';
break;
case ADI_LOG_FATAL:
$class = 'fatal';
$type = '[FATAL] ';
break;
default:
$class = '';
$type = '';
}
$output = '<span class="'.$class.'">'.$type;
$output .= str_replace("\n","<br /> ",$info).'</span><br />';
echo $output;
if (WP_DEBUG) {
if ($fh = #fopen($this->_logfile,'a+')) {
fwrite($fh,$type . str_replace("\n","\n ",$info) . "\n");
fclose($fh);
}
}
}
}
/**
* Do Bulk Import
*
* #param string $authcode
* #return bool true on success, false on error
*/
public function bulkimport($authcode)
{
global $wp_version;
global $wpdb;
$this->setLogFile(dirname(__FILE__).'/import.log');
$this->_log(ADI_LOG_INFO,"-------------------------------------\n".
"START OF BULK IMPORT\n".
date('Y-m-d / H:i:s')."\n".
"-------------------------------------\n");
$time = time();
$all_users = array();
// Is bulk import enabled?
if (!$this->_bulkimport_enabled) {
$this->_log(ADI_LOG_INFO,'Bulk Import is disabled.');
return false;
}
// DO we have the correct Auth Code?
if ($this->_bulkimport_authcode !== $authcode) {
$this->_log(ADI_LOG_ERROR,'Wrong Auth Code.');
return false;
}
$ad_password = $this->_decrypt($this->_bulkimport_pwd);
// Log informations
$this->_log(ADI_LOG_INFO,"Options for adLDAP connection:\n".
"- base_dn: $this->_base_dn\n".
"- domain_controllers: $this->_domain_controllers\n".
"- ad_username: $this->_bulkimport_user\n".
"- ad_password: **not shown**\n".
"- ad_port: $this->_port\n".
"- use_tls: ".(int) $this->_use_tls."\n".
"- network timeout: ". $this->_network_timeout);
// Connect to Active Directory
try {
$this->_adldap = #new adLDAP(array(
"base_dn" => $this->_base_dn,
"domain_controllers" => explode(';', $this->_domain_controllers),
"ad_username" => $this->_bulkimport_user, // Bulk Import User
"ad_password" => $ad_password, // password
"ad_port" => $this->_port, // AD port
"use_tls" => $this->_use_tls, // secure?
"network_timeout" => $this->_network_timeout // network timeout
));
} catch (Exception $e) {
$this->_log(ADI_LOG_ERROR,'adLDAP exception: ' . $e->getMessage());
return false;
}
$this->_log(ADI_LOG_NOTICE,'adLDAP object created.');
$this->_log(ADI_LOG_INFO,'Domain Controller: ' . $this->_adldap->get_last_used_dc());
// Let's give us some more time (60 minutes)
$max_execution_time = ini_get('max_execution_time');
if ($max_execution_time < 3600) {
ini_set('max_execution_time', 3600);
}
if (ini_get('max_execution_time') < 3600) {
$this->_log(ADI_LOG_ERROR,'Can not increase PHP configuration option "max_execution_time".');
return false;
}
// get all users of the chosen security groups from
$groups = explode(";",$this->_bulkimport_security_groups);
if (count($groups) < 1) {
$this->_log(ADI_LOG_WARN,'No security group.');
return false;
}
foreach ($groups AS $group) {
// get all members of group
$group = trim($group);
if ($group != '') {
// do we have a groupid?
if (($pos = stripos($group,'id:')) !== false) {
$pgid = substr($group,$pos+3);
$members = $this->_adldap->group_members_by_primarygroupid($pgid, true);
} else {
$members = $this->_adldap->group_members($group, true);
}
if ($members) {
$this->_log(ADI_LOG_INFO,count($members).' Members of group "'.$group.'".');
$this->_log(ADI_LOG_DEBUG,'Members of group "'.$group.'": ' . implode(', ',$members));
foreach ($members AS $user) {
$all_users[strtolower($user)] = $user;
}
} else {
$this->_log(ADI_LOG_ERROR,'Error retrieving group members for group "'.$group.'".');
}
} else {
$this->_log(ADI_LOG_WARN,'No group. Nothing to do.');
}
}
// Adding all local users with non empty entry adi_samaccountname in usermeta
$blogusers=$wpdb->get_results(
'
SELECT
users.user_login
FROM
'. $wpdb->users . ' users
INNER JOIN
' . $wpdb->usermeta ." meta ON meta.user_id = users.ID
where
meta.meta_key = 'adi_samaccountname'
AND
meta.meta_value IS NOT NULL
AND
meta.meta_value <> ''
AND
users.ID <> 1
"
);
if (is_array($blogusers)) {
foreach ($blogusers AS $user) {
$all_users[strtolower($user->user_login)] = $user->user_login;
}
}
$elapsed_time = time() - $time;
$this->_log(ADI_LOG_INFO,'Number of users to import/update: '.count($all_users).' (list generated in '. $elapsed_time .' seconds)');
if (version_compare($wp_version, '3.1', '<')) {
require_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'registration.php');
}
// import all relevant users
$added_users = 0;
$updated_users = 0;
foreach ($all_users AS $username) {
$ad_username = $username;
// getting user data
//$user = get_userdatabylogin($username); // deprecated
$user = get_user_by('login', $username);
// role
$user_role = $this->_get_user_role_equiv($ad_username); // important: use $ad_username not $username
// userinfo from AD
$this->_log(ADI_LOG_DEBUG, 'ATTRIBUTES TO LOAD: '.print_r($this->_all_user_attributes, true));
$userinfo = $this->_adldap->user_info($ad_username, $this->_all_user_attributes);
$userinfo = $userinfo[0];
$this->_log(ADI_LOG_DEBUG,"USERINFO[0]: \n".print_r($userinfo,true));
if (empty($userinfo)) {
$this->_log(ADI_LOG_INFO,'User "' . $ad_username . '" not found in Active Directory.');
if (isset($user->ID) && ($this->_disable_users)) {
$this->_log(ADI_LOG_WARN,'User "' . $username . '" disabled.');
$this->_disable_user($user->ID, sprintf(__('User "%s" not found in Active Directory.', 'ad-integration'), $username));
}
} else {
// Only user accounts (UF_NORMAL_ACCOUNT is set and other account flags are unset)
if (($userinfo["useraccountcontrol"][0] & (UF_NORMAL_ACCOUNT | ADI_NO_UF_NORMAL_ACOUNT)) == UF_NORMAL_ACCOUNT) {
//&& (($userinfo["useraccountcontrol"][0] & ADI_NO_UF_NORMAL_ACOUNT) == 0)) {
// users with flag UF_SMARTCARD_REQUIRED have no password so they can not logon with ADI
if (($userinfo["useraccountcontrol"][0] & UF_SMARTCARD_REQUIRED) == 0) {
// get display name
$display_name = $this->_get_display_name_from_AD($username, $userinfo);
// create new users or update them
if (!$user OR (strtolower($user->user_login) != strtolower($username))) { // use strtolower!!!
$user_id = $this->_create_user($ad_username, $userinfo, $display_name, $user_role, '', true);
$added_users++;
} else {
$user_id = $this->_update_user($ad_username, $userinfo, $display_name, $user_role, '', true);
$updated_users++;
}
// load user object (this shouldn't be necessary)
if (!$user_id) {
$user_id = username_exists($username);
$this->_log(ADI_LOG_NOTICE,'user_id: '.$user_id);
}
// if the user is disabled
if (($userinfo["useraccountcontrol"][0] & UF_ACCOUNT_DISABLE) == UF_ACCOUNT_DISABLE)
{
$this->_log(ADI_LOG_INFO,'The user "' . $username .'" is disabled in Active Directory.');
if ($this->_disable_users) {
$this->_log(ADI_LOG_WARN,'Disabling user "' . $username .'".');
$this->_disable_user($user_id, sprintf(__('User "%s" is disabled in Active Directory.', 'ad-integration'), $username));
}
} else {
// Enable user / turn off user_disabled
$this->_log(ADI_LOG_INFO,'Enabling user "' . $username .'".');
$this->_enable_user($user_id);
}
} else {
// Flag UF_SMARTCARD_REQUIRED is set
$this->_log(ADI_LOG_INFO,'The user "' . $username .'" requires a SmartCard to logon.');
if (isset($user->ID) && ($this->_disable_users)) {
$this->_log(ADI_LOG_WARN,'Disabling user "' . $username .'".');
$this->_disable_user($user->ID, sprintf(__('User "%s" requires a SmartCard to logon.', 'ad-integration'), $username));
}
}
} else {
// not a normal user account
$this->_log(ADI_LOG_INFO,'The user "' . $username .'" has no normal user account.');
if (isset($user->ID) && ($this->_disable_users)) {
$this->_log(ADI_LOG_WARN,'Disabling user "' . $username .'".');
$this->_disable_user($user->ID, sprintf(__('User "%s" has no normal user account.', 'ad-integration'), $username));
}
}
}
}
// Logging
$elapsed_time = time() - $time;
$this->_log(ADI_LOG_INFO,$added_users . ' Users added.');
$this->_log(ADI_LOG_INFO,$updated_users . ' Users updated.');
$this->_log(ADI_LOG_INFO,'In '. $elapsed_time . ' seconds.');
$this->_log(ADI_LOG_INFO,"-------------------------------------\n".
"END OF BULK IMPORT\n".
date('Y-m-d / H:i:s')."\n".
"-------------------------------------\n");
return true;
}
It looks like this is where I fails. But why wouldn't it be able to get group?
foreach ($groups AS $group) {
// get all members of group
$group = trim($group);
if ($group != '') {
// do we have a groupid?
if (($pos = stripos($group,'id:')) !== false) {
$pgid = substr($group,$pos+3);
$members = $this->_adldap->group_members_by_primarygroupid($pgid, true);
} else {
$members = $this->_adldap->group_members($group, true);
}
if ($members) {
$this->_log(ADI_LOG_INFO,count($members).' Members of group "'.$group.'".');
$this->_log(ADI_LOG_DEBUG,'Members of group "'.$group.'": ' . implode(', ',$members));
foreach ($members AS $user) {
$all_users[strtolower($user)] = $user;
}
} else {
$this->_log(ADI_LOG_ERROR,'Error retrieving group members for group "'.$group.'".');
}
I removed
$ad_password = $this->_decrypt($this->_bulkimport_pwd);
and added
$ad_password = 'my_password_here';
And it worked
Seems that this decrypt password is broken.
[INFO] 1000 Members of group "id:513".
[INFO] Number of users to import/update: 3439
I had the same problem when I filled twice the field "Bulk Import User Password". I launched the bulk import, which failed (all the users were disabled!). My Apache log below:
PHP Warning: mcrypt_decrypt(): Key of size 27 not supported by this
algorithm.Only keys of sizes 16, 24 or 32 supported in
/var/www/html/wordpress/wp-content/plugins/active-directory-integration/ad-integration.php
The problem seems come from the function mcrypt used to encrypt the password. We can see in the file ad-integration.php that the function used the Wordpress constant AUTH_SALT, which is defined by default like "put your unique phrase here", thus 27 char. So I defined this constant with a string of 32 char (you can define this in wp-config.php). I refilled the Bulk Import User Password and it works.
I'm trying to use the query from a GET url to determine the content of a page.
This is what I have (sentences edited for clarity):
<?php
//decalre variables
$title ='';
$welcome = '';
$params = '';
$params = $_SERVER['QUERY_STRING'];
echo $_SERVER['QUERY_STRING'];
echo $params;
if ($params='') {
header('start.html') ;
} else {
if ($params === "selection=republic") {
//echo $params;
//echo 'Republic';
$title = "Private";
$welcome = "Our .";
$signoff = "The Republic will strike back!";
}
else if ($params === "selection=rebels") {
//echo $params;
//echo 'Rebels';
$title = "Comrade";
$welcome = "Hey comrade, welcome to the Underground Network!";
$declaration="You see,o's!";
$signoff = "Rebel!!";
}
else if ($params === "selection=robots"){
//echo $params;
//echo 'Robots';
$title = "Bit";
$welcome = "Our data ";
$declaration="Knowledge w.";
$signoff = "ed now.";
}
else {
echo 'There was an error - please go back.';
}
}
The first echo shows the correct URL, but the comparison gets stuck at the third option.
Help!
This comes from the triple = sign, that compares the value and the type. You should see the difference here.
I suggest you only use two equals and by the way, you could ease your code by using the $_GET['selection'] variable instead:
<?php
//decalre variables
$title ='';
$welcome = '';
$params = '';
$params = $_SERVER['QUERY_STRING'];
echo $_SERVER['QUERY_STRING'];
echo $params;
if (!isset($_GET['selection']) { // Check whether selection is set
header('start.html') ;
} else {
if ($_GET['selection'] == "republic") {
//echo $params;
//echo 'Republic';
$title = "Private";
$welcome = "Our .";
$signoff = "The Republic will strike back!";
}
else if ($_GET['selection'] == "rebels") {
//echo $params;
//echo 'Rebels';
$title = "Comrade";
$welcome = "Hey comrade, welcome to the Underground Network!";
$declaration="You see,o's!";
$signoff = "Rebel!!";
}
else if ($_GET['selection'] == "robots"){
//echo $params;
//echo 'Robots';
$title = "Bit";
$welcome = "Our data ";
$declaration="Knowledge w.";
$signoff = "ed now.";
}
else {
echo 'There was an error - please go back.';
}
}
There are way better ways of parsing the query string than $SERVER['QUERY_STRING'], specifically you can use $_GET to access a specific parameter. Example: www.example.com?name=Dave&age=30...
to get the name, you can do $_GET['name'] and it will return Dave. I think a better way to do this would be something like:
$selection = $_GET['selection'];
if (empty($selection)) {
header('start.html') ;
}
else {
$vars = array(
'republic'=>array('title'=>'Private', 'welcome'=> 'Our .', 'declaration'=>'', 'signoff' => 'The Replublic will strike back'),
'rebels'=>array('title'=>'Comrade', 'welcome' => "Hey comrade, welcome to the Underground Network!", 'declaration'=>"You see,o's!",'signoff' => "Rebel!!"),
'robots'=>array('title'=>'Bit', 'welcome'=>'Our data', 'declaration'=>'Knowlegge W', 'signoff'=>'Ed now')
);
list($title, $welcome, $declaration, $signoff) = $vars[$selection];
}