How to create user on hMailServer programatically? - hmail-server

We are writing a specialized PHP e-mail client and would like to give administrators of this client the ability to create user accounts on hMailServer.
I tried out imap_createmailbox(...) but it just creates a directory in the user's folder structure but does not "create a mailbox for a new user" as we want.
Is there some kind of interface that hMailServer has so that I can enable our PHP e-mail client to create hMailServer accounts via code?

Yes there two interfaces to create accounts in hmailserver.
One, via database, you can choose account and password hash type (0,1,2,3) and signature and other classic informations. I don't recommend this method for synchronisation reason, hmail-server take a caching time to consider the database update.
Two, which i recommend is to use API COM, its offers all possible methods in all cummon languages.
You have to enable D-COM in your windows server.
The API guide

hmailserver version: hMailServer 5.6.4 - Build 2283
complete solution of create new email account by hmailserver in c#
if you have configured hmailserver successfully, so then you can use the following steps to create new account by hmailserver in c#
hmailserver connection
private Domain HMailServerConnection() {
var objGlobal = new ApplicationClass();
objGlobal.Authenticate(ConfigurationManager.AppSettings["HMailUsername"], ConfigurationManager.AppSettings["HMailPassword"]);
return objGlobal.Domains.get_ItemByName(ConfigurationManager.AppSettings["hMailDomain"]);
}
function to create new email account
public string AddNewAccount(string email,string password)
{
try
{
Domain domain = HMailServerConnection();
Accounts accounts = domain.Accounts;
Account mailbox = accounts.Add();
mailbox.Address = email;
mailbox.Password = password;
mailbox.Save();
return "success";
}
catch(Exception ex)
{
return "error";
}
}
App settings in App.config or web.config
<appSettings>
<add key="hMailDomain" value="domainname"/>
<add key="HMailUsername" value="Username"/>
<add key="HMailPassword" value="password"/>
</appSettings>
see the link
its working i tested it.

<?php
header('Content-Type: text/html; charset=utf-8');
$obBaseApp = new COM("hMailServer.Application", NULL, CP_UTF8);
$obBaseApp->Connect();
$hmail_config['rooturl'] = "http://localhost/";
$obAccount = $obBaseApp->Authenticate("Administrator", "hMailserver Administrator
password");
if (!isset($obAccount)) {
echo "<b>Not authenticated or Administrator's password wrong</b>";
} else {
try {
echo "<b>Logon COM [OK], now we can add accounts</b>";
$obDomain = $obBaseApp->Domains->ItemByDBID(1);
$obAccount = $obDomain->Accounts->ItemByDBID(1); // account id
$domainname = $obDomain->Name;
$obAccounts = $obDomain->Accounts();
$obAccount = $obDomain->Accounts->Add();
$newalias = "powerranger";
$firstname = "Arnold";
$lastname = "Schwarzenegger";
$my_domainname ="#mydomain.com";
$obAccount->PersonFirstName = $firstname;
$obAccount->PersonLastName = $lastname;
$obAccount->MaxSize = 102; // 102 MB set inbox space
$obAccount->Address = $newalias .$my_domainname;
$obAccount->Password = "secret"; // provide this in Thunderbird/Outlook ect.
$obAccount->Active = true; // set account to active
$obAccount->Save(); // save, finish.
/* If we reaching this point, everything works as expected */
echo "<br/><h3> Account was successfully created, now you can login with".
"an POP3 or IMAP-Client </h3>";
}
/* OK, if something went wrong, give us the exact error details */
catch(Exception $e) {
echo "<h4>COM-ERROR: <br />".$e->getMessage()."</h4><br />";
}
}

Related

Adldap2 authentication always returns true - Yii2

I'm working in Yii2 with the Adldap extension found here: https://github.com/Adldap2/Adldap2
I'm running into an issue when I try to authenticate users on my ldap server. I can successfully make a connection and and retrieve user data, but when trying to authenticate if a user's username and password are correct or not, it always returns true, even if the creds are wrong. Below is my code snippet (with the config array not showing of course):
$ad->addProvider($config);
try {
// If a successful connection is made to your server, the provider will be returned.
$provider = $ad->connect();
//User below does return the correct information from the ldap server
$user = $provider->search()->users()->find('quillin');
try{
$provider->auth()->attempt("wrongUsername","wrongPassword");
die("WIN");
}catch( Exception $e ){
die("Exception " . $e);
}
}catch (\Adldap\Auth\BindException $e) {
die( "There was an issue binding / connecting to the server. <br />" . $e);
}
No matter what I put in for the username and password fields, it always returns true and hits the die("WIN"); line. In my composer.json file, i'm using "adldap2/adldap2": "v7.0.*"
I have also tried to bind the user using the following:
try{
$provider->auth()->attempt("wrongUsername","wrongPassword", $bindAsUser = true);
die("WIN");
}catch( Exception $e ){
die("lose :(");
die("Exception " . $e);
}
And that also always returns true;
I figured this out and will explain here in anyone else has the same issue.
1) $provider->auth()->attempt() should be wrapped in an IF, and not a try/catch.
2) The first parameter, $username, is actually looking for the userprincipalname, the docs had made it sound like it was looking instead for a username.
After that, I was able to authenticate the user successfully.

Making PDO Database Connection available in controllers and models

right now, I am kinda frustrated and I hope someone can help me and point me into the right direction.
I have an "old" project which uses the mysql statements for connection to database, etc.
Within this project I have the following:
An index file containing
*
* load configuration and connect to database
*/
$projectConfiguration = new projectConfiguration();
$dbconnect = $projectConfiguration->connect($projectConfiguration->databaseHost, $projectConfiguration->databaseName, $projectConfiguration->databaseUser, $projectConfiguration->databasePass);
// load controller
$ReqMod = FatFramework\Functions::getRequestParameter("mod");
if (!$ReqMod) {
$ReqMod = FatFramework\Functions::getRequestParameter("controller");
}
$module = ($ReqMod) ? $ReqMod : 'default';
In this style I call the views and actions in classes, like SaveAction()
Using mysql always made it very simple to use this database connection in the models called by the controllers like
public function loadCustomersList($sAdditionalWhere = false)
{
$sQuery = "SELECT * FROM customers WHERE 1 ";
if ($sAdditionalWhere) {
$sQuery .= "AND " . $sAdditionalWhere . " ";
}
$sQuery .= "ORDER BY company";
$sql = mysql_query($sQuery);
while (($customer = mysql_fetch_object($sql)) != false) {
$aCustomers[] = $customer;
}
return $aCustomers;
}
I want to totally refractor this project and use PDO. I tried for the last 4 hours to find a solution, but I can't figure out how to make it work.
I think I don't need an extra dbconnect class since PDO is a class itself, am I right?
In the new index file I tried the following:
$db = new database();
try{
$dbc = new PDO($db->get_DbConSettings());
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo 'Verbindung fehlgeschlagen: '.$e->getMessage();
}
But with this $dbc will not available in controllers or models. It there a way to make it available there? If not, what is the best solution?
Do I have to make a database connection in every model?
An other issue I have with this is:
$db->get_DbConSettings()
in
$dbc = new PDO
gives back
'mysql:host=127.0.0.1; dbname=c1virtbkk', 'root', '123'
($dbc = new PDO('mysql:host=127.0.0.1; dbname=c1virtbkk', 'root', '123');)
I cannot connect to the database. I get the following:
Verbindung fehlgeschlagen: could not find driver
If I don't use $db->get_DbConSettings and put the required information manually in, I don't get any error and can do queries. Any hints?
Help is really appreciated.
Thanks in advance!
Mark
Definitely don't create a new PDO connection in each model. Creating MySQL database connections is fairly quick, but there's still some overhead to doing so. You want to reuse a connection throughout your request. If nothing else, it allows you to share a transaction across multiple models.
Some frameworks store shared resource objects in a "registry" class which is a singleton key-value store. It's not really much more than a global hash array, but making it a class makes the registry itself more easily tested with PHPUnit. See https://framework.zend.com/manual/1.12/en/zend.registry.using.html for an example of a registry.
You're right that PDO is a class, even though it's implemented as a C extension instead of a PHP class. But it's a class, and new PDO(...) returns an object of that class.
One reason to create a db class of your own is to help you in unit-testing, because you could create a mock object for your db class so you can test your other classes (even model classes) without needing a live database connection. Your db class could extend or else contain a PDO object.
Your issue about the error "could not find driver" is probably because the PDO driver for mysql is not installed. PDO is one PHP extension, and then there's a separate extension for each brand of SQL database. You can confirm this with:
$ php -i
...lots of output...
PDO
PDO support => enabled
PDO drivers => mysql, odbc, sqlite
pdo_mysql
PDO Driver for MySQL => enabled
Client API version => mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $
...more output for other extensions...
Note that PDO tells me which drivers I have installed: mysql, odbc, and sqlite.
So you need to install pdo_mysql. I'm not sure what OS you're on, but I'm often on CentOS Linux or Ubuntu Linux. The pdo_mysql is available as a separate package via yum or apt.
Re your comment:
Okay, here's an example of a registry:
class registry {
protected static $items = array();
public static get($key) {
return isset(self::$items[$key])?
self::$items[$key] : null;
}
public static set($key, $object) {
self::$items[$key] = $object;
}
}
In your controller initial code, you'd create a database object and store it in the registry:
$projectConfiguration = new projectConfiguration();
$dbconnect = $projectConfiguration->connect(
$projectConfiguration->databaseHost,
$projectConfiguration->databaseName,
$projectConfiguration->databaseUser,
$projectConfiguration->databasePass);
registry::set('db', $dbconnect);
Then in your model class methods (or anywhere you need the database), get the db object from the registry and use it:
public function loadCustomersList($sAdditionalWhere = false)
{
$sQuery = "SELECT * FROM customers WHERE 1 ";
if ($sAdditionalWhere) {
$sQuery .= "AND " . $sAdditionalWhere . " ";
}
$sQuery .= "ORDER BY company";
$db = registry::get('db');
$stmt = $db->query($sQuery);
$aCustomers = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $aCustomers;
}

How to conditionally use different database in CodeIgniter

Here is my scenario.
A user will login to the system. Based on the username, I need to set the database in codeigniter configuration.
I know that the line $this->load->database() in each model loads the default database.
So, after checking the username in session(assuming that the user has successfully logged in), how can I dynamically load a database?
Below is something that I am looking for:
if(username == 'foo'){
$this->load->database('database_name');
}
An example of a model function that I have written is as follows:
public function check_valid_login($username, $password){
$this->db->from('tbl_user_details');
$this->db->where('email_address', $username);
$this->db->where('password', md5($password));
$query = $this->db->get();
$rowcount = $query->num_rows();
return $rowcount ;
}
On selecting the database, how can I still use statements like $this->db->from('tbl_user_details'); and so on. i.e., I want to use $this->db itself. Is it possible to do that?
I think I found a solution.
This is the strategy that I followed: When the user tries to login, a session variable $_SESSION['dynamic_db_username'] is set with the username that is provided by the user.
The following logic is used for selecting the database dynamically. The below code is written in config/database.php
/*Dynamic database selection - begins*/
if(!empty($_SESSION['dynamic_db_username'])){
$dynamic_db_username = $_SESSION['dynamic_db_username'];
if($dynamic_db_username == 'sample#domain.com')
{
$db['default']['database'] = 'database_1';
}
elseif($dynamic_db_username == 'sample2#domain.com')
{
$db['default']['database'] = 'database_2';
}
else
{
$db['default']['database'] = 'database_1';
}
}
else
{
$db['default']['database'] = 'database_1';
}
/*End*/
Kindly review this strategy and please let me know if this is right.
in the config folder there was a file named autoload.php
open the file
find first this code below
$autoload['libraries'] = array('');
you have to put "database" in the array , changed code will be like
$autoload['libraries'] = array('database');
after that you can use your database anytime and anywhere without loading it manually .

Using JDBC to access localhost database from any computer

First up, I apologise if this is a duplicate in any way, but I have been trying many different things from this site for several hours now with no luck. And for the record, I am running OS X 10.11.5.
I have made this simple application using JDBC to connect to a database I created that is stored on my localhost (I am using phpMyAdmin, if that is any help):
#Override
public void actionPerformed(ActionEvent e) {
// The ID to search for
int search = Integer.parseInt(textField.getText());
// Setting up the connection to the database.
String url = "jdbc:mysql://my_ip_address:3306/javaDatabase";
String user = "root"; // root user
String password = ""; // no password
Connection con = null;
PreparedStatement searchID; // I used a prepared statement so I could include user input
ResultSet result = null; // results after SQL execution
try {
con = DriverManager.getConnection(url, user, password); // connect to MySQL
// Creating the prepared statement
searchID = con.prepareStatement("SELECT * FROM Names WHERE ID = ?");
// Setting the parameter to the user input
searchID.setInt(1, search);
result = searchID.executeQuery(); // execute the SQL query
while (result.next()) { // loop until the end of the results
String ID = result.getString("ID");
String FirstName = result.getString("FirstName");
String LastName = result.getString("LastName");
textArea1.setText("ID: " + ID + "\n" +
"First Name: " + FirstName + "\n" +
"Last Name: " + LastName + "\n");
}
} catch(SQLException e1) {
System.out.println("Exception caught " + e1.getMessage());
} finally {
try {
if (result != null) {
result.close();
}
if (con != null) {
con.close();
}
} catch(SQLException e2) {
System.out.println("SQLException caught " + e2.getMessage());
}
}
}
public static void main(String[] args) {
JavaWithSQL newJava = new JavaWithSQL();
}
Now, I am packaging this application up as an executable .JAR file, and want to be able to run it on someone else's computer and have it access the database and return the records.
I have tried instructions from here and here, without any luck. I looked at opening port 3306 on my Mac, but my firewall is off, but that doesn't seem to be the problem. I have also attempted to use GRANT privileges on the database in question using:
GRANT ALL PRIVILEGES ON javaDatabase.* TO '%'#'%' IDENTIFIED BY '';
to no avail. However, it does work on other computers when I explicitly write the computers IP address, like this:
GRANT ALL PRIVILEGES ON javaDatabase.* TO 'root'#'other_computer_ip' IDENTIFIED BY '';
But I need to be able to run it on my lecturer's computer, and in theory, other people's computers, without having to know everyone's IP addresses.
How can I do this? Am I missing something?
EDIT:
Okay, I have run the command
GRANT SELECT ON javaDatabase.* TO 'remoteUser'#'%' IDENTIFIED BY '';
FLUSH PRIVILEGES;
And now it works perfectly on any computer connected to the same network, but I need it to work even if I am connected to a different network.
I really need a pointer on this one.
You are using TO '%'#'%' IDENTIFIED BY '';
I'm not sure if that works. It should address the root user in your case.
GRANT ALL PRIVILEGES ON javaDatabase.* TO 'root'#'%' IDENTIFIED BY '';

Codeigniter remote connection does not return queries

I have a local and a remote connection with my mysql database. The local connection works just fine. But the remote connection, while it makes a connection, it does not return anything. I usually get the following:
Fatal error: Call to a member function result() on a non-object
I use for the remote connection the following configuration:
$db['mydb']['hostname'] = "ip_address_of_database";
$db['mydb']['username'] = "username";
$db['mydb']['password'] = "password";
$db['mydb']['database'] = "database";
$db['mydb']['dbdriver'] = "mysql";
$db['mydb']['dbprefix'] = "";
$db['mydb']['pconnect'] = FALSE;
$db['mydb']['db_debug'] = FALSE;
$db['mydb']['cache_on'] = FALSE;
$db['mydb']['cachedir'] = "";
$db['mydb']['char_set'] = "utf8";
$db['mydb']['dbcollat'] = "utf8_general_ci";
In my function that accesses the database I check if there is a connection with the remote server and then I try to retrieve data.
$mydb = $this->load->database('mydb', TRUE);
if (!isset($mydb->conn_id) && !is_resource($mydb->conn_id)) {
$error = 'database is not connected';
return $error;
}else{
$query = $mydb->query("SELECT * FROM database LIMIT 1;");
return $query->result();
}
This works fine in the localhost database but not in the remote database. I allways get the error
Fatal error: Call to a member function result() on a non-object
Can you please help? What am I doing wrong? I stuck on this.
Finally, I found the solution after contacting my web hosting provider. The issue had to do with the Remote database access and their servers. The IP address exception and the domain name that I had added didn’t do the job. I had to add an internal domain name that my host was using in order the Remote database access to be allowed. I spent 2-3 hours chatting with them in order to find a solution.
Anyway now is solved. I am posting that FYI.