Simple Machines Community Forum

Customizing SMF => Bridges and Integrations => Topic started by: Andre N on September 19, 2011, 01:35:36 PM

Title: New tools to help integrating SMF with something else
Post by: Andre N on September 19, 2011, 01:35:36 PM
You want to integrate SMF with something else. Here's 2 files that will help you accomplish that.

The API will let you control SMF from your other system.

The integration hooks will let you control your other system from SMF

How to use the API:
1. Upload it to your server. Anywhere. Make sure your SMF installation is on the same server. It will seek out your installation and create a settings.txt file with the location of your Settings.php file for it's own future reference (to make it load faster)

2. In your script, include the API file. Include it anywhere you like as long as it gets included before you try to use it's functions.
require_once '/path/to/api/file/smf_2_api.php'

3. Call the functions. They are documented pretty well but if you have questions ask below.
Example:
smfapi_logout($email);
Would log the user out of SMF.
This makes the assumption that you have the users email address in the string $email. You would put this code in your other system just before or after the user is logged out there, so now they are logged out together.

4. Repeat for all the other functions you need to use.


How to use the integration hooks:
1. Make it easy on yourself and download the integration hooks skeleton file here. It has been written for maximum ease of use.

2. Upload the skeleton file onto your server. Anywhere. Make sure your SMF installation is on the same server.

3. Open the file index.php in your SMF root directory. This is SMF's 'main' index.php file. At the very top, include the hooks file:

[code]require_once '/path/to/hooks/file/smf_2_integration_hooks.php'

[/code]

4. Write the code inside the functions that will manipulate your other system. Taking logout as an example, inside function smf_logout_function($memberName) you might put:

function smf_logout_function($memberName)
{
$sessionData = smf_session_save_function(); //save and close the SMF session

require_once('other/system/file.php');
other_system_function_logout($memberName);

smf_session_restore_function($sessionData); //load the SMF session and put session data back
}


5. Repeat this process for all the hooks you want to use.

Hint: For the hooks you can get SMF variables in the functions by declaring them as global.

function smf_logout_function($memberName)
{
global $user_info, $context;
//now you have the user info and context variables SMF has available to your function
}


Hint: For the hooks, if you aren't sure what variables are being passed to it, do something like this:

function smf_logout_function($memberName)
{
var_dump($memberName);
exit();
}

Then log out of SMF and you will see what information SMF is passing to the hook.

Questions, comments and suggestions welcome. Please post your finished hook files for other systems too and it will help others using that system to integrate

edit 11/1/11 updated integration hooks file to make fixes to the save and restore functions

NEW - I made a 'REST' API for SMF that you can download and use. Check out it's thread here:
http://www.simplemachines.org/community/index.php?topic=458832.0
It let's you use all the SSI functions, all the API functions, a couple other things like post and pm, it's easy to extend, and you do it all from a different domain than your SMF install (or same if you like) :)

edit 2/29/12 updated API to version 0.1.2 to fix some bugs and make it work with magic quotes hopefully
Title: Re: New tools to help integrating SMF with something else
Post by: ghrom on October 17, 2011, 06:20:20 PM
Can I crate a new thread using this? Say, from Objective-C iPhone app?
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on October 17, 2011, 07:07:14 PM
You could, but you'd have to write your own function for that in the API. See Sources/Post.php for the code SMF uses
Title: Re: New tools to help integrating SMF with something else
Post by: ghrom on October 18, 2011, 12:07:27 PM
Thanks. Is there any chance you will be adding this in your api, please?

EDIT: Actually, it was easier than I thought. Thanks for pointing me in the right direction!
Title: Re: New tools to help integrating SMF with something else
Post by: BREZ on October 30, 2011, 12:50:58 PM
I am a bit confused.

Exactly where would the smfapi_logout($email); go in 4images script?
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on October 31, 2011, 04:20:45 PM
Quote from: BREZ on October 30, 2011, 12:50:58 PM
I am a bit confused.

Exactly where would the smfapi_logout($email); go in 4images script?

It would go wherever that script logs the user out. So look in the 4images script for the point where the user gets logged out of 4images and add the API code beneath that.
Make sure that you have included the API script already, and that $email has their email address, SMF username or SMF member ID
Title: Re: New tools to help integrating SMF with something else
Post by: DanCarroll on November 03, 2011, 11:29:19 AM
Maybe you can help me decide on the direction to take my project. I'm developing a CRM for a client and am looking at basing it on SMF. My dilemma is in what would be the best approach. At this point I like the idea of adding to the SMF system. Save some duplication of effort and code by using the member (user) system and messaging system. I found this thread and would like clarification on the following quote from the first posting in this thread.

QuoteThe API will let you control SMF from your other system.

The integration hooks will let you control your other system from SMF


Any and all help on this is greatly appreciated.

Thanks, Dan C.
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on November 03, 2011, 11:41:45 AM
What is the other application going to be?
Title: Re: New tools to help integrating SMF with something else
Post by: DanCarroll on November 03, 2011, 12:01:12 PM
A CRM app (Customer Relationship Management). Basically it is to track clients & customers, events & purchases, and prospects & phone calls. I have the data model figured out and was looking at adding it to the SMF forum and the forum members would be "staff or employees". Would need to integrate it into the Calendar system, etc.

Using PHP & mySQL so shouldn't be a problem. I didn't have a good understanding of the API and integration hooks. What about the SMC functions? Are the SMC functions part of the $smcFunc system?

I have the 2.0.1 version of SMF up and running with both a production and a test system. I just need to start developing the web app part of my CRM system. Basically just need data entry and reporting functions to a database.
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on November 03, 2011, 12:15:08 PM
The SMC functions are
$smcFunc => Array
    (
        [db_query] => smf_db_query
        [db_quote] => smf_db_quote
        [db_fetch_assoc] => mysql_fetch_assoc
        [db_fetch_row] => mysql_fetch_row
        [db_free_result] => mysql_free_result
        [db_insert] => smf_db_insert
        [db_insert_id] => smf_db_insert_id
        [db_num_rows] => mysql_num_rows
        [db_data_seek] => mysql_data_seek
        [db_num_fields] => mysql_num_fields
        [db_escape_string] => addslashes
        [db_unescape_string] => stripslashes
        [db_server_info] => mysql_get_server_info
        [db_affected_rows] => smf_db_affected_rows
        [db_transaction] => smf_db_transaction
        [db_error] => mysql_error
        [db_select_db] => mysql_select_db
        [db_title] =>
        [db_sybase] =>
        [db_case_sensitive] =>
        [db_escape_wildcard_string] => smf_db_escape_wildcard_string
        [entity_fix] =>
        [htmlspecialchars] =>
        [htmltrim] =>
        [strlen] =>
        [strpos] =>
        [substr] =>
        [strtolower] =>
        [strtoupper] =>
        [truncate] =>
        [ucfirst] =>
        [ucwords] =>
    )

They're just the functions mainly used with the SMF db. They are already available if you are in SMF, or if you call the API. including the API script is like loading the "SMF object". It will give you (easier) access to the SMF db and all the settings and variables like $context and $modSettings

So by including the API script wherever SMF hasn't been instantiated you can use those db functions, plus the other API functions, plus you have access to those settings variables. Is that what you're looking for?
Title: Re: New tools to help integrating SMF with something else
Post by: DanCarroll on November 03, 2011, 12:21:59 PM
Is that what I'm looking for? Maybe.

I guess I just need to know:
Also, thirdly, would I be committing an egregious error in adding my data tables to the SMF database?

Thanks, Dan
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on November 03, 2011, 12:38:07 PM
The API functions are just stripped down versions of a few of the functions SMF has, and they are meant to be used outside of SMF. The API doesn't extend SMF, it lets you use some of it's functions from outside. Inside you have lots more.

Best way would probably be to add your pages as actions, then they would already have db access. You could look at how some of the modification packages do it, I believe you'd need to insert your action into the actions array in index.php, create a file for your action in the sources folder, and create a template for it (your page). If there's a better way I don't know it.

If your table names are different than SMF's you'll be fine :)
Title: Re: New tools to help integrating SMF with something else
Post by: DanCarroll on November 03, 2011, 01:26:55 PM
Thanks. That is the way I'm proceeding. Already tested setting up actions, sub-actions, linktree support, and page titles. I'll have to take a look at some of the Mod code then. Is there any code examples for newbs to the board (not new to coding)?

Guess  I should be looking into the Mod creation process. What about the SMF Function database? Can I utilize (call) those functions? Or is there an API I should use? Or an SDK?

Just asking if there is a comprehensive list of functions that can be used for extending the SMF system since you stated that "the API functions are just stripped down versions of a few of the functions SMF has"?

Thanks again, hope I can contribute some time, Dan
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on November 03, 2011, 01:56:50 PM
You can call all the functions in the function database; no need for the API inside SMF.

For the complete list of all the SMF functions google 'smf function database', and you'll see the functions available to you with some description.

The DB functions are inside the variable $smcFunc and you'll be able to call them all; no need for the API. You'll have access to everything SMF does. If you look at some of the files in Sources folder you'll see how the smcFunc's are used; pretty easy to understand when you see the code.
Title: Re: New tools to help integrating SMF with something else
Post by: DanCarroll on November 03, 2011, 05:15:20 PM
Thanks Man! I have some coding to do. Later.
Title: Re: New tools to help integrating SMF with something else
Post by: ankifreeze on December 20, 2011, 06:11:07 PM
hi I have used your api but it doesn't work.... :(

log out function doesn't work....
Code: [Select]

require_once ( 'smf_2_api.php');
smfapi_logout('[email protected]');


login function also doesn't work...
Code: [Select]


require_once ( 'smf_2_api.php');
smfapi_authenticate('ankifreeze', '123456')
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on December 20, 2011, 06:31:59 PM
Hi,

For login, use

smfapi_login($email);

as authenticate will not log a user in, it's only use is to authenticate a username/password combo

as for logout, it should work flawlessly. If you log in manually and then call the logout function on yourself, does it work?

If you try calling it for random users, it will remove them from the database as being logged, so they won't show as being online anymore, but their cookie will persist so when they actually visit the forum they will still be logged in. If you call logout on the current user, only then will the login cookie be destroyed as well ;)

See if that helps. Otherwise it's possible your cookie settings prevent you from accessing SMF's cookie... let me know :)
Title: Re: New tools to help integrating SMF with something else
Post by: ankifreeze on December 20, 2011, 07:17:19 PM
greatt..it does work now...but it doesn't work if log in manually and then call the logout function from api....I see there are some different function in smf_2_api.php and smf script forum ...is  it safe  using your api? ..btw nice tutorial and script.....thanks very much.... :)
Title: Re: New tools to help integrating SMF with something else
Post by: ankifreeze on December 21, 2011, 06:59:31 PM
I got problem when first time I try log in....Notice: Undefined variable:USER_AGENT in C:\xampp\htdocs\site\forum\smf_2_api.php on line1867 ...I found $_SESSION['USER_AGENT'] is not defined...but after that I try to log in and It works....


and I got problem  when I try logout...I can't logout from mysite ( can't logout if I put logout.php in http://localhost/site/logout.php (mysite folder) ) but it s works if I put  logout.php in http://localhost/site/forum/logout.php (forum folder)

my forum place
http://localhost/site/forum/index.php
my site place
http://localhost/site/index.php

also I  have tried register using API like this...

require_once ( 'smf_2_api.php');
$reg=array();
$reg['member_name']='frank';
$reg['email']='[email protected]';
$reg['require']='nothing';
$reg['password']='123456';
$reg['password_check']='123456';
smfapi_registerMember($reg);


$reg= array(
'member_name' => 'frank',
'email' => '[email protected]',
'require' => 'nothing',
'password' => '123456',
'password_check' => '123456',
);
smfapi_registerMember($reg);


it  works but I feel something wrong and strange....any suggestion... :(
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on December 22, 2011, 04:12:24 PM
Hi,

First error, change:

} elseif (empty($id_member) && isset($_SESSION['login_' . $cookiename]) && ($_SESSION['USER_AGENT'] == $_SERVER['HTTP_USER_AGENT'] || !empty($modSettings['disableCheckUA']))) {


to be


} elseif (empty($id_member) && isset($_SESSION['login_' . $cookiename]) && !empty($modSettings['disableCheckUA'])) {


If they haven't visited the forum this session variable might not be set.

2. If your logout script is working on path /forum but not / then the problem is with your cookie. You need to make sure the cookie path is set for '/' and not for '/forum'. Do this in SMF admin by enabling subdomain independent cookies. Then delete your cookie, login and try it again.

3. You're doing the registration correctly, and it works... what do you mean you feel something wrong and strange? lol :)
Title: Re: New tools to help integrating SMF with something else
Post by: ankifreeze on December 22, 2011, 07:43:18 PM
yeah I have deleted $_SESSION['USER_AGENT'] == $_SERVER['HTTP_USER_AGENT']  yesterday and it works now....I have enable Use subdomain independent cookies  in admin center but still doesn't work... :(
Title: Re: New tools to help integrating SMF with something else
Post by: ankifreeze on December 23, 2011, 01:54:27 AM
also how to remove register and login form?I have removed one in tempate function but I didn't find in another place......I have removed login and register link but if someone using url like index.php?action=login or index.php?action=register site will calling  login and registration function and  login or register form still appear and if session or cookie has expired  the site will called login form or register form too... :(
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on December 23, 2011, 07:05:22 AM
Run a test script in both site/forum and site


require_once('path/to/api');
global $cookiename;
echo $cookiename;
echo '<br /><pre>';
print_r($_COOKIE[$cookiename]);
echo '</pre><br />';
$data = unserialize($_COOKIE[$cookiename]);
if (!$data) {
    echo 'Unable to unserialize cookie';
} else {
    echo '<pre>';
    print_r($data);
    echo '</pre>';
}


for the login and register link, if you want to remove them and redirect to something else, you'd look in /index.php. It shows:

'login' => array('LogInOut.php', 'Login'),

and

'register' => array('Register.php', 'Register'),


so login maps to /Sources/LogInOut.php function Login() and register maps to /Sources/Register.php function Register()

go to those files and at the top of the function redirect to your other login and register page :)


// Ask them for their login information.
function Login()
{
        //redirect to other login
        header('Location: http://www.somewhere.com/login.php');

global $txt, $context, $scripturl;

// In wireless?  If so, use the correct sub template.
if (WIRELESS)
$context['sub_template'] = WIRELESS_PROTOCOL . '_login';
// Otherwise, we need to load the Login template/language file.
else
{
loadLanguage('Login');
    ...
Title: Re: New tools to help integrating SMF with something else
Post by: ankifreeze on December 23, 2011, 08:11:57 AM
I have tested it.....I think it doesn't work in site folder...

http://localhost/site/test.php

SMFCookie956
Notice:  Undefined index: SMFCookie956 in C:\xampp\htdocs\site\test.php on line 8
Notice: Undefined index: SMFCookie956 in C:\xampp\htdocs\site\test.php on line 10
Unable to unserialize cookie


http://localhost/site/forum/test.php
SMFCookie956

a:4:{i:0;s:1:"1";i:1;s:40:"9188720a1bfe3a5bd315d7cbb4e9f84a6f140e4d";i:2;i:1356238923;i:3;i:3;}


Array
(
    [0] => 1
    [1] => 9188720a1bfe3a5bd315d7cbb4e9f84a6f140e4d
    [2] => 1356238923
    [3] => 3
)



I have put header('Location: http://localhost/site/login.php') in login function and it works but how about login form?  login form is appear when session expired? where I can delete it? :(

Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on December 23, 2011, 08:54:35 AM
Ok, I have 2 ideas as to what might be causing the API to not work outside your /forum directory.

1. The cookie is set for /forum. Can you manually verify the cookie path, either by using firecookie or opening your browser settings to view the cookies and check your SMFCookie956 to make sure the path is '/'. If you aren't sure how to see, please pm me a link to your site and a test user login.

2. The API might not be locating your Settings.php file. It will search for smfapi_settings.txt file first, which is a save file it creates with the location of your Settings.php file. Then it will check if you've specified the location of the file, around line 574. Then it will see if Settings.php is in the same directory it is. Then it will start searching for it. The search might time out if your server resources are low or you have lots of files and directories, so it's possible that the API finds your Settings file when it is in the same directory, but times out looking for it when it is not. You can specify the path to your SMF Settings.php file on about line 574 (depending on which version of the API you have).
You'll see a line that looks like:

// specify the settings path here if it's not in smf root and you want to speed things up
//$settings_path = $_SERVER['DOCUMENT_ROOT'] . /path/to/Settings.php


Let me know :)

The login form is located at /Themes/default/Login.template.php
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on December 23, 2011, 09:18:45 AM
Thinking about this some more, I'm positive this is a cookie issue with the cookie not being on the right path.
If the script timed out, it wouldn't have rendered the output. Plus it did get the name of the cookie, that comes from the Settings.php file. Your SMF cookie isn't viewable outside of /forum and that is the issue here
Title: Re: New tools to help integrating SMF with something else
Post by: ankifreeze on December 23, 2011, 06:53:47 PM
cookie path location is http://localhost/site/forum
(http://img69.imageshack.us/img69/7312/pictureoc.jpg) (http://imageshack.us/photo/my-images/69/pictureoc.jpg/)



and about setting.php location I have made newfolder and changed location in smf_2_api.php...I think that is not a problem... :)

// specify the settings path here if it's not in smf root and you want to speed things up
//$settings_path = $_SERVER['DOCUMENT_ROOT'] . /path/to/Settings.php

// get the forum's settings for database and file paths
if (file_exists(dirname(__FILE__) . '/newfolder/Settings.php')) {
    require_once(dirname(__FILE__) . '/newfolder/Settings.php');
} elseif (isset($settings_path)) {
    require_once($settings_path);
} else {
Title: Re: New tools to help integrating SMF with something else
Post by: ankifreeze on December 26, 2011, 07:40:30 AM
I have solved the cookie issue....thanks... :)
Title: Re: New tools to help integrating SMF with something else
Post by: Bugo on December 27, 2011, 01:13:38 PM
Hi, I use this code for authentification:

...
if (smfapi_authenticate($login, $pass))
smfapi_login($login);
...

and get these errors:
Quote
Message: Undefined index: content
Filename: smf_2_api.php
Line Number: 988
Quote
Message: Undefined index: character_set
Filename: smf_2_api.php
Line Number: 988
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on December 27, 2011, 02:16:20 PM
Quote from: Bugo on December 27, 2011, 01:13:38 PM
Hi, I use this code for authentification:

...
if (smfapi_authenticate($login, $pass))
smfapi_login($login);
...

and get these errors:
Quote
Message: Undefined index: content
Filename: smf_2_api.php
Line Number: 988
Quote
Message: Undefined index: character_set
Filename: smf_2_api.php
Line Number: 988

@Bugo, try changing this in line 988:

if ($context['character_set'] == 'utf8'
                && !empty($modSettings['previousCharacterSet'])
                && $modSettings['previousCharacterSet'] != 'utf8')

to be this:

if (isset($context['character_set']) && $context['character_set'] == 'utf8'
                && !empty($modSettings['previousCharacterSet'])
                && $modSettings['previousCharacterSet'] != 'utf8')

and you're problem there should go away :)
Title: Re: New tools to help integrating SMF with something else
Post by: ledaladdin.com on January 09, 2012, 09:48:30 PM
Thanks for pointing me in the right direction!
Title: Re: New tools to help integrating SMF with something else
Post by: Meriadoc on February 02, 2012, 07:59:49 PM
Hey, this API I think will be great. I'm having a couple issues though myself.

I'm just trying to do a basic test right now to make sure it's working. I've logged into the forum (./discuss on my server) and verified the cookie is being set. It's sub-domain agnostic and the path is '/'

When I check my script that's including the API everything is required() correctly. I can print_r() out the $user_info but it is showing me as a guest even though I'm logged in in the forum.

I ran your little cookie test and it said it could not unserialize it. I tried stripslashes() and it worked fine unserializing the cookie. I tried adding the stripslashes() code to the two spots in smfapi_loadUserSettings() (lines 1862 and 1869) but it doesn't seem to be doing anything.

Doing some tests led me to the place it's failing out. It is following the if/else statements to line 1865 and setting $id_member to 0. But it seems, based on the comment, that that inner if/else statement is just a PHP4.3 fix (I'm running PHP 5.x)

Shouldn't there be some other logic there to grab the cookie info even if the preg_match fails?

Thanks!
Title: Re: New tools to help integrating SMF with something else
Post by: Meriadoc on February 02, 2012, 08:09:28 PM
I was able to "fix" this (hopefully) by ALSO adding a strip slashes to the $_COOKIE[$cookiename] of the preg_match on line 1861. Hopefully those three instances of that function doesn't do bad things.

If it matters I just looked at magic_quotes_gpc are ON (though _runtime and _sybase are OFF)
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 02, 2012, 10:03:24 PM
yeah, if you can turn the magic quotes off you should be ok

if not, look for where the cookie is unserialized:

list ($id_member, $password) = @unserialize($_COOKIE[$cookiename]);


and strip the slashes at that point so it will unserialize ok

list ($id_member, $password) = @unserialize(stripslashes($_COOKIE[$cookiename]));


I found 2 spots
Title: Re: New tools to help integrating SMF with something else
Post by: Meriadoc on February 03, 2012, 06:27:40 PM
Yep that does it. Also necessary to stripslashes() on this line:
if (preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~i', $_COOKIE[$cookiename]) == 1) {


That way the regex / preg_match() will work out when it needs to.
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 04, 2012, 03:59:43 PM
Very helpful to know. I should just add the stripslashes command to the next release, because it definitely wouldn't hurt anything to always call it there
Title: Re: New tools to help integrating SMF with something else
Post by: lilsammy1989 on February 13, 2012, 10:11:00 AM
Hi I am trying to use this to add to a registration function I already have, I am running a website with its own user database and then at the same time I want to register the user into the form.

Anyway I am trying to get the basic functionality working like so. If you could help me out I would appreciate it as the function for registering them into the site seems to be working but the part to register them into SMF isn't working.

Also will the register function work if after I get it working I disable it on the SMF in admin settings or does this need to be left on?

if (!isset($_POST['name']) && !isset($_POST['steam']) && !isset($_POST['email']) && !isset($_POST['email2']) && !isset($_POST['password']) && !isset($_POST['password2']) && !isset($_POST['acceptTerms'])) {
echo "Waiting User Input";
}else{
include './static/classes/validation.php';

$name = $_POST['name'];
$steam = $_POST['steam'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$pass = $_POST['password'];
$pass2 = $_POST['password2'];
$userIP = getenv('REMOTE_ADDR');
require_once ('./static/classes/smf_2_api.php');

$sha_passwd = sha1(strtolower($name).smfapi_unHtmlspecialchars($pass));
 
if((validate_username($name) == true) && ($email == $email2) && (check_email_address($email) == true) && ($pass == $pass2)){
include './static/classes/config.php';

$conn = mysql_connect($host,$user,$pass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}

mysql_select_db($db, $conn);
mysql_set_charset('utf8',$conn);

$sql_username="SELECT * FROM User WHERE User_Name = '$name'";
$sql_email="SELECT * FROM User WHERE User_Email = '$email'";

$user_check=mysql_query($sql_username);
$email_check=mysql_query($sql_email);

if (mysql_num_rows($user_check) > 0){
echo "Error - 02"; // Username in Use.
}else{
if (mysql_num_rows($email_check) > 0){
echo "Error - 03"; // Email in Use.
}else{

$reg= array(
'member_name' => '$name',
'email' => '$email',
'require' => 'nothing',
'password' => '$pass',
'password_check' => '$pass2',
);
smfapi_registerMember($reg);

$new_user=mysql_query("INSERT INTO User (User_Name, User_Pass, User_IP, User_Admin, User_Beta, User_SteamID, User_Registered, User_Email) VALUES ('$name', '$sha_passwd', '$userIP', '0', '1', '$steam', 'NOW()', '$email')");
if (!$new_user) {
$message  = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
};



echo "Registered";
};
};
};
};
?>
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 13, 2012, 11:08:11 AM
Hi,
It looks like the problem with your registration into SMF is that you're setting the registration variables incorrectly. You have:

$reg= array(
'member_name' => '$name',
'email' => '$email',
'require' => 'nothing',
'password' => '$pass',
'password_check' => '$pass2',
);

which is going to put the string '$name' into the SMF db as the name, instead of the variable value which is what you want. Try it without the quotes and it should work.

$reg= array(
'member_name' => $name,
'email' => $email,
'require' => 'nothing',
'password' => $pass,
'password_check' => $pass2,
);

You can disable the registration in SMF admin and it will still register through the API. Another way to do it would be to modify the registration template or methods to redirect to your other registration page. That way when someone tries to register in SMF instead of an error message they will get sent to a place they can register.
Title: Re: New tools to help integrating SMF with something else
Post by: lilsammy1989 on February 13, 2012, 12:52:06 PM
That worked great I thought it was somthing simple I just wasn't getting, In my defense I am coding high ;)
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 17, 2012, 12:36:40 PM
im trying to synchronize the login of my site with smf.

im using it this way:

require_once ('/forum/smf_2_api.php');
if (smfapi_authenticate($username, $password))
smfapi_login($username);


but nothing seems to happen.

i open 2 browser tabs, my site and smf, bothe logged off.

i login into my website and go to smf tab and refresh the page, but its still logged off!

can you help me?
Title: Re: New tools to help integrating SMF with something else
Post by: DECEiFER on February 18, 2012, 02:22:05 AM
Hi. I've just come across your API tonight as I am building a custom system from scratch that I'd like to bridge with SMF 2.

I'm just performing a few tests at the moment to see how the API works. I've managed to register a user just fine, but no activation e-mails are being sent out, and I've noticed that there's nothing in the API for that. I'm not familiar with SMF as I've always been a phpBB user up to now (shame on me!), so I was wondering if there's any method to generate the activation e-mail from the forum's settings (i.e. use the default)?

Here is my *working* test implementation:

public function run() {
include "libs/nucaptcha/leapmarketingclient.php";
include "config/settings.php";
include "smf_2_api.php";

// First, check to see if all of our VALID arguments are there (NOTE that $_POST is passed first, which invalidates the need for checkPostVar).
if(!Common::checkPost() || !Common::areAllArgumentsSet($_POST, $_POST['username'], $_POST['password'], $_POST['verifypassword'], $_POST['email'], $_POST['country'])) {
Common::error("You have not completely filled out the form.");
return;
}

Common::makePostSafe($_POST);

// Next, see if our NuCaptcha data matches.
if($regUsingLeap && array_key_exists('leap', $_SESSION) && Leap::WasSubmitted()) {
Leap::SetClientKey($regLeapClientKey);
$lastTransaction = Leap::ValidateTransaction($_SESSION['leap']);
if($lastTransaction !== true) {
Common::error("You have incorrectly entered the moving red letters.");
return;
}
}

$regOptions['member_name'] = $_POST['username'];
$regOptions['password'] = $_POST['password'];
$regOptions['password_check'] = $_POST['verifypassword'];
$regOptions['email'] = $_POST['email'];
$regOptions['location'] = $_POST['country'];
$regOptions['require'] = "activation";

if (smfapi_registerMember($regOptions) !== false) echo "Success";
else echo "Fail";
}


I know it's just a matter of getting the verification_code from the database, which seems to be generated and then inserted to the database just fine in the smfapi_registerMember() function. I just need to know how to generate the activation e-mail body, where this is stored in SMF:

Quote from: SMF Activation E-mailThank you for registering at R N' D Studios - Forum. Your username is DECEiFER. If you forget your password, you can reset it by visiting forum.com/index.php?action=reminder.

Before you can login, you first need to activate your account. To do so, please follow this link:

forum.com/index.php?action=activate;u=1;code=xxxxxxxxxx

Should you have any problems with activation, please visit forum.com/index.php?action=activate;u=1 use the code "xxxxxxxxxx".

Regards,
Forum Team.

Once I have that, I can simply work the rest out. :)


Thanks in advance for any assistance.
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 18, 2012, 03:37:28 AM
Quote from: frytec on February 17, 2012, 12:36:40 PM
im trying to synchronize the login of my site with smf.

im using it this way:

require_once ('/forum/smf_2_api.php');
if (smfapi_authenticate($username, $password))
smfapi_login($username);


but nothing seems to happen.

i open 2 browser tabs, my site and smf, bothe logged off.

i login into my website and go to smf tab and refresh the page, but its still logged off!

can you help me?

@frytec try this:
require_once ('/forum/smf_2_api.php');
smfapi_login($username);

Make sure the $username variable is populated and contains a valid SMF username, email address or SMF ID
ALso, be sure your SMF cookie is set on path '/'



Quote from: DECEiFER on February 18, 2012, 02:22:05 AM
Hi. I've just come across your API tonight as I am building a custom system from scratch that I'd like to bridge with SMF 2.

I'm just performing a few tests at the moment to see how the API works. I've managed to register a user just fine, but no activation e-mails are being sent out, and I've noticed that there's nothing in the API for that. I'm not familiar with SMF as I've always been a phpBB user up to now (shame on me!), so I was wondering if there's any method to generate the activation e-mail from the forum's settings (i.e. use the default)?

Here is my *working* test implementation:

public function run() {
include "libs/nucaptcha/leapmarketingclient.php";
include "config/settings.php";
include "smf_2_api.php";

// First, check to see if all of our VALID arguments are there (NOTE that $_POST is passed first, which invalidates the need for checkPostVar).
if(!Common::checkPost() || !Common::areAllArgumentsSet($_POST, $_POST['username'], $_POST['password'], $_POST['verifypassword'], $_POST['email'], $_POST['country'])) {
Common::error("You have not completely filled out the form.");
return;
}

Common::makePostSafe($_POST);

// Next, see if our NuCaptcha data matches.
if($regUsingLeap && array_key_exists('leap', $_SESSION) && Leap::WasSubmitted()) {
Leap::SetClientKey($regLeapClientKey);
$lastTransaction = Leap::ValidateTransaction($_SESSION['leap']);
if($lastTransaction !== true) {
Common::error("You have incorrectly entered the moving red letters.");
return;
}
}

$regOptions['member_name'] = $_POST['username'];
$regOptions['password'] = $_POST['password'];
$regOptions['password_check'] = $_POST['verifypassword'];
$regOptions['email'] = $_POST['email'];
$regOptions['location'] = $_POST['country'];
$regOptions['require'] = "activation";

if (smfapi_registerMember($regOptions) !== false) echo "Success";
else echo "Fail";
}


I know it's just a matter of getting the verification_code from the database, which seems to be generated and then inserted to the database just fine in the smfapi_registerMember() function. I just need to know how to generate the activation e-mail body, where this is stored in SMF:

Quote from: SMF Activation E-mailThank you for registering at R N' D Studios - Forum. Your username is DECEiFER. If you forget your password, you can reset it by visiting forum.com/index.php?action=reminder.

Before you can login, you first need to activate your account. To do so, please follow this link:

forum.com/index.php?action=activate;u=1;code=xxxxxxxxxx

Should you have any problems with activation, please visit forum.com/index.php?action=activate;u=1 use the code "xxxxxxxxxx".

Regards,
Forum Team.

Once I have that, I can simply work the rest out. :)


Thanks in advance for any assistance.
@DECEiFER check out the way SMF does this in /Sources/Register.php ~line 600

It might be easier to just do this in the API by modifying the API after the registration is successful. The variable with the activation code is '$validation_code'. You can copy the SMF template and replace the variables with the ones used for registration.

Another possibilty would be to try cURL'ing the url from the API right after registration.
Build the url like this with the variables and you should be able to cUrl to it which will send the email to the member silently. Do it just after the member ID is returned

$url = $_SERVER['HTTP_HOST'] . '/forum.com/index.php?action=activate;u=' . $memberID . ';code=' .$validation_code;
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 24, 2012, 11:57:36 AM
i figured out how to make the login synch work, but couldnt figure out how to make the logout neither the registration.

can you help me?

here is my function:

    public function theme_index_top($h)
    {
       $username = $h->cage->post->testUsername('username');
       $password = $h->cage->post->testPassword('password');
       $email = $h->cage->post->testEmail('email'); 
       require_once ('./forum/smf_2_api.php');

        switch ($h->pageName)
        {
            case 'logout':
                smfapi_logout($username);
                $h->currentUser->destroyCookieAndSession();
                header("Location: " . BASEURL);
                exit;
                break;
            case 'login':
                $h->pageTitle = $h->lang["user_signin_login"];
                $h->pageType = 'login';
                if ($this->login($h)) {
                    // success, return to front page, logged IN.
                    $return = str_replace('&amp;', '&', $h->cage->post->getHtmLawed('return'));
                    if ($return) {
                        header("Location: " . $return);

                    } else {
                        header("Location: " . BASEURL);
                    }
                    smfapi_login($username);
                    die(); exit;
                }
                break;
            case 'register':
                $h->pageTitle = $h->lang["user_signin_register"];
                $h->pageType = 'register';
                $user_signin_settings = $h->getSerializedSettings('user_signin');
                $h->vars['useRecaptcha'] = $user_signin_settings['recaptcha_enabled'];
                $h->vars['useEmailConf'] = $user_signin_settings['emailconf_enabled'];
                $h->vars['regStatus'] = $user_signin_settings['registration_status'];
                $h->vars['useEmailNotify'] = $user_signin_settings['email_notify'];

                $userid = $this->register($h);
                if ($userid) {
                    // success!
                    if ($h->vars['useEmailConf']) {
                        $h->vars['send_email_confirmation'] = true;
                        $this->sendConfirmationEmail($h, $userid);
                        // fall through and display "email sent" message
                    } else {
                        // redirect to login page
                        header("Location: " . BASEURL . "index.php?page=login");
                        die(); exit;
                    }
                }
                break;
            case 'emailconf':
                $h->pageTitle = $h->lang['user_signin_register_emailconf'];
                $h->pageType = 'register';
                break;
        }
    }
Title: Re: New tools to help integrating SMF with something else
Post by: DECEiFER on February 24, 2012, 12:09:25 PM
Quote from: frytec on February 24, 2012, 11:57:36 AM
i figured out how to make the login synch work, but couldnt figure out how to make the logout neither the registration.

can you help me?

here is my function:

    public function theme_index_top($h)
    {
       $username = $h->cage->post->testUsername('username');
       $password = $h->cage->post->testPassword('password');
       $email = $h->cage->post->testEmail('email'); 
       require_once ('./forum/smf_2_api.php');

        switch ($h->pageName)
        {
            case 'logout':
                smfapi_logout($username);
                $h->currentUser->destroyCookieAndSession();
                header("Location: " . BASEURL);
                exit;
                break;
            case 'login':
                $h->pageTitle = $h->lang["user_signin_login"];
                $h->pageType = 'login';
                if ($this->login($h)) {
                    // success, return to front page, logged IN.
                    $return = str_replace('&amp;', '&', $h->cage->post->getHtmLawed('return'));
                    if ($return) {
                        header("Location: " . $return);

                    } else {
                        header("Location: " . BASEURL);
                    }
                    smfapi_login($username);
                    die(); exit;
                }
                break;
            case 'register':
                $h->pageTitle = $h->lang["user_signin_register"];
                $h->pageType = 'register';
                $user_signin_settings = $h->getSerializedSettings('user_signin');
                $h->vars['useRecaptcha'] = $user_signin_settings['recaptcha_enabled'];
                $h->vars['useEmailConf'] = $user_signin_settings['emailconf_enabled'];
                $h->vars['regStatus'] = $user_signin_settings['registration_status'];
                $h->vars['useEmailNotify'] = $user_signin_settings['email_notify'];

                $userid = $this->register($h);
                if ($userid) {
                    // success!
                    if ($h->vars['useEmailConf']) {
                        $h->vars['send_email_confirmation'] = true;
                        $this->sendConfirmationEmail($h, $userid);
                        // fall through and display "email sent" message
                    } else {
                        // redirect to login page
                        header("Location: " . BASEURL . "index.php?page=login");
                        die(); exit;
                    }
                }
                break;
            case 'emailconf':
                $h->pageTitle = $h->lang['user_signin_register_emailconf'];
                $h->pageType = 'register';
                break;
        }
    }


This is what I've been doing. It's basic, for now, but it does register the user correctly into the SMF database.

public function run() {
include "libs/nucaptcha/leapmarketingclient.php";
include "config/settings.php";
include "smf_2_api.php";

Common::logHTTPData();

// Validiate the HTTP Referer (sic) to ensure that the POST came from this domain
if (!Common::validateReferer()){
Common::logBadReferer();
// Let's not be too specific about what this error returns to the user
Common::error("Invalid request.");
}

// First, check to see if all of our VALID arguments are there (NOTE that $_POST is passed first, which invalidates the need for checkPostVar).
if(!Common::checkPost() || !Common::areAllArgumentsSet($_POST, $_POST['username'], $_POST['password'], $_POST['verifypassword'], $_POST['email'], $_POST['country'])) {
Common::error("You have not completely filled out the form.");
return;
}

Common::makePostSafe($_POST);

// Next, see if our NuCaptcha data matches.
if($regUsingLeap && array_key_exists('leap', $_SESSION) && Leap::WasSubmitted()) {
Leap::SetClientKey($regLeapClientKey);
$lastTransaction = Leap::ValidateTransaction($_SESSION['leap']);
if($lastTransaction !== true) {
Common::error("You have incorrectly entered the moving red letters.");
return;
}
}

$regOptions['member_name'] = $_POST['username'];
$regOptions['password'] = $_POST['password'];
$regOptions['password_check'] = $_POST['verifypassword'];
$regOptions['email'] = $_POST['email'];
$regOptions['location'] = $_POST['country'];
$regOptions['require'] = "activation";

if (smfapi_registerMember($regOptions) === false) return false;

$_SESSION['success'] = true;
$_SESSION['email'] = $_POST['email'];
header("location: /register");
die;
}



To logout, it's as simple as this:

public function logout(){
global $user_info;
if(isset($user_info) && $user_info['is_guest'] == 0) {
smfapi_logout($user_info['username']);
}
header('location: /login');
die;
}
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 24, 2012, 01:20:12 PM
The logout function is very simple. All you need to do to effectively log them out of SMF is destroy the cookie. If the logout function isn't working, first check to make sure your script can see the SMF cookie. It must be set on path '/'.
Also make sure the cookie data has no slashes in it. If it does turn off magic quotes on your server in the php ini. When this is the case, the logout function scans the cookie to see if anyone is logged in, and if there are slashes it won't unserialize the data, so unserialize will fail and the logout script will assume nobody is logged in and exit. Try using this instead of smfapi_logout()

smfapi_setLoginCookie(-3600, 0);

If that does the job, your cookie data probably has slashes in it.

For the Register issue you're having, it doesn't look like you are calling smfapi_register() at all.
Inside your switch statement under 'register' is where I'm guessing it should be...
For the registration function, you need to set up the array correctly, making sure the array keys have the correct names. You need at minimum a username, password and email. The API will return false if the username or email is already taken. Check your values carefully to make sure they are all set and be extra precise and this function will work
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 24, 2012, 01:53:36 PM
Thanks for your answers guys.
I going one step at a time, so i first trying to logout, before trying to register.

@andre nickatina, using smfapi_setLoginCookie(-3600, 0); it works, i am being succefully logged out of smf when i log out my site.

can i use it that way? Or is it just a "test"?

magic quotes are off according to phpinfo.
magic_quotes_gpc      Off   Off
magic_quotes_runtime   Off   Off
magic_quotes_sybase   Off   Off

Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 24, 2012, 02:05:23 PM
Quote from: frytec on February 24, 2012, 01:53:36 PM
Thanks for your answers guys.
I going one step at a time, so i first trying to logout, before trying to register.

@andre nickatina, using smfapi_setLoginCookie(-3600, 0); it works, i am being succefully logged out of smf when i log out my site.

can i use it that way? Or is it just a "test"?

magic quotes are off according to phpinfo.
magic_quotes_gpc      Off   Off
magic_quotes_runtime   Off   Off
magic_quotes_sybase   Off   Off



Your other script might be turning them on. Using it like that will work, but it's not the best solution as the user will still show in the who's online list and appear to be online even though they're not. The function also unsets a few session variables that need to be destroyed.
Can you look at the cookie data in firebug or something to verify there are slashes in the data? If so, you can add the stripslashes() php function to the API by replacing $_COOKIE[$cookiename] with stripslashes($_COOKIE[$cookiename]) in the 3 places where the cookie data gets checked and unserialized. You can use find/replace for that :) They should be in the function smfapi_loadUserSettings
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 24, 2012, 02:14:21 PM
@andre, thats all info on smfcookie via firecookies

SMFCookie520
   
Value: a:4:{i:0;s:1:"1";i:1;s:40:"c3ea46ccb2e2d848578f51dd6196044c1159f221";i:2;i:1519328009;i:3;i:2;}

Domain:    .catalink.com.br   

Size: 107 B
   
Path: /

Raw: a%3A4%3A%7Bi%3A0%3Bs%3A1%3A%221%22%3Bi%3A1%3Bs%3A40%3A%22c3ea46ccb2e2d848578f51dd6196044c1159f221%22%3Bi%3A2%3Bi%3A1519328009%3Bi%3A3%3Bi%3A2%3B%7D
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 24, 2012, 05:03:45 PM
Create a test page with this code:

<?php
require_once ('./forum/smf_2_api.php');
global 
$cookiename;
$data $_COOKIE[$cookiename];
echo 
$data '<br />';
echo 
'Without stripslashes:<br /><pre>';
print_r(unserialize($data));
echo 
'</pre>';
echo 
'With stripslashes:<br /><pre>';
print_r(unserialize(stripslashes($data)));
echo 
'</pre>';

name it test.php or something, upload it, navigate to it and see what the output is and post what you get
Title: Re: New tools to help integrating SMF with something else
Post by: lilsammy1989 on February 25, 2012, 01:32:15 PM
Hi I tried to make a simple ajax login from my main website like so:
<?php 
$is_ajax 
$_REQUEST['is_ajax'];

if(isset(
$is_ajax) && $is_ajax){
$user $_REQUEST['username'];
$pass $_REQUEST['password'];


require_once ('./smf_2_api.php');


$login smfapi_authenticate($username=$user$password=$pass);

    if (!
$login) {
        echo 
"wrong";
    } else {
$cookie smfapi_login($username=$user$cookieLength=525600);
if (!$login) {
        
echo "wrong";
}else{
echo "success";
};
};
};
?>



It threw some errors and then I thought maybe I will try your test script and it did the same :/


Anyway I tried your test script and it throws the same errors.

Warning: opendir(/home/sam/public_html/pug4u.com./forums/Settings.php) [function.opendir]: failed to open dir: No such file or directory in /home/sam/public_html/pug4u.com/static/classes/smf_2_api.php on line 3231

Warning: readdir(): supplied argument is not a valid Directory resource in /home/sam/public_html/pug4u.com/static/classes/smf_2_api.php on line 3232

Warning: closedir(): supplied argument is not a valid Directory resource in /home/sam/public_html/pug4u.com/static/classes/smf_2_api.php on line 3243

Without stripslashes:

With stripslashes:


Was hoping you could shed some light on my problem I would be so greatful.
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 25, 2012, 01:36:26 PM
@lilsamm71989
Try putting the full path to the API in the require_once function
Also, try putting the API script in your forum directory to see if that helps
Title: Re: New tools to help integrating SMF with something else
Post by: lilsammy1989 on February 25, 2012, 01:59:36 PM
@andre nickatina

I think I am including it correctly because if I set the path wrong I get an error about not finding it but when I set it correctly it outputs:


<br />
<b>Warning</b>:  opendir(/home/sam/public_html/pug4u.com./forums/Settings.php) [<a href='function.opendir'>function.opendir</a>]: failed to open dir: No such file or directory in <b>/home/sam/public_html/pug4u.com/static/classes/smf_2_api.php</b> on line <b>3231</b><br />
<br />
<b>Warning</b>:  readdir(): supplied argument is not a valid Directory resource in <b>/home/sam/public_html/pug4u.com/static/classes/smf_2_api.php</b> on line <b>3232</b><br />
<br />
<b>Warning</b>:  closedir(): supplied argument is not a valid Directory resource in <b>/home/sam/public_html/pug4u.com/static/classes/smf_2_api.php</b> on line <b>3243</b><br />
<br />
<b>Fatal error</b>:  Function name must be a string in <b>/home/sam/public_html/pug4u.com/static/classes/smf_2_api.php</b> on line <b>755</b><br />


Also I tried it on the forum it gives the same error. Any other Ideas?
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 25, 2012, 02:04:10 PM
Did you try moving the API script to your SMF directory? Cause these are the errors it will throw if it can't find your settings php file. Or you could edit line ~574 to give the script your path to settings php
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 25, 2012, 02:17:11 PM
Quote from: andre nickatina on February 24, 2012, 05:03:45 PM
Create a test page with this code:
....
name it test.php or something, upload it, navigate to it and see what the output is and post what you get


a:4:{i:0;s:1:"1";i:1;s:40:"c3ea46ccb2e2d848578f51dd6196044c1159f221";i:2;i:1361733187;i:3;i:2;}
Without stripslashes:

Array
(
    [0] => 1
    [1] => c3ea46ccb2e2d848578f51dd6196044c1159f221
    [2] => 1361733187
    [3] => 2
)

With stripslashes:

Array
(
    [0] => 1
    [1] => c3ea46ccb2e2d848578f51dd6196044c1159f221
    [2] => 1361733187
    [3] => 2
)

Title: Re: New tools to help integrating SMF with something else
Post by: lilsammy1989 on February 25, 2012, 02:22:45 PM
Yeah I tried it in the forum directory same thing. Could you tell me if I have done these settings right?

My file structure looks like this:
(http://i.imgur.com/lcmLa.png)



// get the forum's settings for database and file paths
if (file_exists(dirname(__FILE__) . '../../forums/Settings.php')) {
    require_once(dirname(__FILE__) . '../../forums/Settings.php');
} elseif (isset($settings_path)) {
    require_once($settings_path);
} else {
    $directory = $_SERVER['DOCUMENT_ROOT'] . './forums/Settings.php';
    $exempt = array('.', '..');
    $files = smfapi_getDirectoryContents($directory, $exempt);
    $matches = smfapi_getMatchingFile($files, '../../forums/Settings.php');

    // we're going to search for it...
@set_time_limit(600);
// try to get some more memory
if (@ini_get('memory_limit') < 128) {
@ini_set('memory_limit', '128M');
    }

    if (1 == count($matches)) {
        require_once($matches[0]);
        $settings_path = $matches[0];
        file_put_contents($saveFile, base64_encode($settings_path));
    } elseif (1 < count($matches)) {
        $matches = smfapi_getMatchingFile($files, 'Settings_bak.php');
        $matches[0] = str_replace('_bak.php', '.php', $matches[0]);
        require_once($matches[0]);
        $settings_path = $matches[0];
        file_put_contents($saveFile, base64_encode($settings_path));
    } else {
        return false;
    }
}

$scripturl = $boardurl . '../../index.php';

// make absolutely sure the cache directory is defined
if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '../../forums/cache')) {
$cachedir = $boarddir . '../../forums/cache';
}
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 25, 2012, 02:35:28 PM
@lilsammy1989 You don't appear to have a Settings.php file in your forum root directory... The API needs that location of the Settings.php file so it can make the db connections and get the cookiename to read the cookie... How does your forum work without it?

@frytec That's very weird. Your cookie is being read correctly but the logout is still failing for you. Try calling smfapi_loadUserSettings() before logout, and also, don't pass any variable to the logout function:

smfapi_loadUserSettings();
smfapi_logout();

If that doesn't work, try modifying it like so:

smfapi_loadUserSettings();
global $user_info;
echo '<pre>';
print_r($user_info);
echo '</pre>';
exit('The user info should be above in an array');
smfapi_logout();

and see if the API is getting the current user from the cookie.
Title: Re: New tools to help integrating SMF with something else
Post by: lilsammy1989 on February 25, 2012, 02:48:08 PM
Its there sorry I knew that I should of mentioned I did not download my entire forum as installed it from another location and did not need the files on this PC so didn't bother downloading the entire remote forums folder but its there on the actual server thats my local view.

Sorry for the confusion.
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 25, 2012, 02:50:41 PM
Quote from: andre nickatina
@frytec That's very weird. Your cookie is being read correctly but the logout is still failing for you. Try calling smfapi_loadUserSettings() before logout, and also, don't pass any variable to the logout function:

smfapi_loadUserSettings();
smfapi_logout();


that does not work.

Quote from: andre nickatina
If that doesn't work, try modifying it like so:

smfapi_loadUserSettings();
global $user_info;
echo '<pre>';
print_r($user_info);
echo '</pre>';
exit('The user info should be above in an array');
smfapi_logout();

and see if the API is getting the current user from the cookie.

this give me a page with above results, but still dont logout from smf.

Array
(
    [groups] => Array
        (
            [0] => 1
            [1] => 0
        )

    [possibly_robot] =>
    [id] => 1
    [username] => catalink
    [name] => catalink
    [email] => [email protected]
    [passwd] => 8769590b35433ffbfc768e09af9efda6fc8bfb4a
    [language] => portuguese_brazilian-utf8
    [is_guest] =>
    [is_admin] => 1
    [theme] => 0
    [last_login] => 1330199182
    [ip] =>
    [ip2] =>
    [posts] => 0
    [time_format] => %B %d, %Y, %I:%M:%S %p
    [time_offset] => 0
    [avatar] => Array
        (
            [url] =>
            [filename] =>
            [custom_dir] =>
            [id_attach] => 0
        )

    [smiley_set] =>
    [messages] => 0
    [unread_messages] => 0
    [total_time_logged_in] => 8878
    [buddies] => Array
        (
        )

    [ignoreboards] => Array
        (
        )

    [ignoreusers] => Array
        (
        )

    [warning] => 0
    [permissions] => Array
        (
        )

)

The user info should be above in an array
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 25, 2012, 03:42:01 PM
@frytec I think I see your problem. There is a bug in the logout function. Go to ~line 1047 of the API to where the code says:

    if (!$user_data) {
        if (isset($user_info['id_member']) && false !== smfapi_getUserById($user_info['id_member'])) {
            $user_data['id_member'] = $user_info['id_member'];
        } else {
            return false;
        }
    }

and change it to

    if (!$user_data) {
        if (isset($user_info['id']) && false !== smfapi_getUserById($user_info['id'])) {
            $user_data['id_member'] = $user_info['id'];
        } else {
            return false;
        }
    }

It looks like I had been using the wrong variable name for the member ID  :-[

@lilsammy1989 Please confirm you have the API script in the same directory as the Settings.php file. Also, look for a file named smfapi_settings.txt and delete it so the API can generate a new one with the correct path. If you want to specify the path in the, do it like this:

$_SERVER['DOCUMENT_ROOT'] . '/forums/Settings.php';

That looks like it is the path you should use. That won't be necessary if you have the API in the same directory as the settings file though... either way, try it and let me know :)
Title: Re: New tools to help integrating SMF with something else
Post by: lilsammy1989 on February 25, 2012, 05:12:01 PM
@andre nickatina

Thanks it worked when I used it from the forum and set the directory to settings. Can I ask tho why when I made my registration function quoted below it worked fine and its located outside of the forum directory?

<?php
if (!isset($_POST['name']) && !isset($_POST['steam']) && !isset($_POST['email']) && !isset($_POST['email2']) && !isset($_POST['password']) && !isset($_POST['password2']) && !isset($_POST['acceptTerms'])) {
echo "";
}else{
include './static/classes/validation.php';

$name $_POST['name'];
$steam $_POST['steam'];
$email $_POST['email'];
$email2 $_POST['email2'];
$pass $_POST['password'];
$pass2 $_POST['password2'];
$userIP getenv('REMOTE_ADDR');
require_once ('./static/classes/smf_2_api.php');

$sha_passwd sha1(strtolower($name).smfapi_unHtmlspecialchars($pass));
  
if((validate_username($name) == true) && ($email == $email2) && (check_email_address($email) == true) && ($pass == $pass2)){
include './static/classes/config.php';

$conn mysql_connect($host,$user,$pass);
if (!$conn) {
die('Could not connect: ' mysql_error());
}

mysql_select_db($db$conn);
mysql_set_charset('utf8',$conn);

$sql_username="SELECT * FROM User WHERE User_Name = '$name'";
$sql_email="SELECT * FROM User WHERE User_Email = '$email'";

$user_check=mysql_query($sql_username);
$email_check=mysql_query($sql_email);

if (mysql_num_rows($user_check) > 0){
echo "Error - 02"// Username in Use.
}else{
if (mysql_num_rows($email_check) > 0){
echo "Error - 03"// Email in Use.
}else{

$reg= array(
'member_name' => $name,
'email' => $email,
'require' => 'nothing',
'password' => $pass,
'password_check' => $pass2,
);
smfapi_registerMember($reg);

$new_user=mysql_query("INSERT INTO User (User_Name, User_Pass, User_IP, User_Admin, User_Beta, User_SteamID, User_Registered, User_Email) VALUES ('$name', '$sha_passwd', '$userIP', '0', '1', '$steam', 'NOW()', '$email')");
if (!$new_user) {
$message  'Invalid query: ' mysql_error() . "\n";
$message .= 'Whole query: ' $query;
die($message);
};

echo "<script language='javascript'>window.location.href='http://mysite.com/welcome.php?name=".$name."';</script>";
};
};
};
};
?>
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 25, 2012, 05:20:27 PM
Glad it works. It will work from anywhere as long as it can find your Settings.php file. Once it finds it, it tries to create a text file with the location saved so it doesn't have to search again. The first time it loads it does the search if it's not in the same directory as Settings.php, and if you didn't specify the location in the script.
It's possible it was unable to write the settings file (no write permissions in the folder it was in) and it failed, or timed out the second time. Are there any error logs for this?
Since you know it works now from the forum directory, you can move it wherever you want, and specify the path to the settings file in the API and it should still work. Delete the settings.txt file with the old location saved too.
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 27, 2012, 11:28:23 AM
Quote from: andre nickatina on February 25, 2012, 03:42:01 PM
@frytec I think I see your problem. There is a bug in the logout function. Go to ~line 1047 of the API to where the code says:
...
It looks like I had been using the wrong variable name for the member ID  :-[

it still does not work.
its so wierd, all tests are ok, i can log in, but cant log out.
do you have any other idea?
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 27, 2012, 12:26:17 PM
Replace your entire logout function in the API with this:

function smfapi_logout($username='')
{
    global $sourcedir, $user_info, $user_settings, $context, $modSettings, $smcFunc;

    if ($user_info['is_guest']) {
        smfapi_loadUserSettings();
    }

    if ('' == $username) {
        if ($user_info['is_guest']) {
            return false;
        } else {
            $username = $user_info['username'];
        }
    }

    $user_data = smfapi_getUserData($username);

    if (!$user_data) {
        return false;
    }

    //delete them from log_online
    $smcFunc['db_query']('', '
        DELETE FROM {db_prefix}log_online
        WHERE id_member = {int:current_member}',
        array(
            'current_member' => $user_data['id_member'],
        )
    );

    if (isset($_SESSION['pack_ftp'])) {
$_SESSION['pack_ftp'] = null;
    }

// they cannot be open ID verified any longer.
if (isset($_SESSION['openid'])) {
unset($_SESSION['openid']);
    }

// it won't be first login anymore.
if (isset($_SESSION['openid'])) {
    unset($_SESSION['first_login']);
    }

    //destroy the cookie
smfapi_setLoginCookie(-3600, 0);

    return true;
}

and it should work. Let me know :)
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 27, 2012, 01:14:36 PM
Quote from: andre nickatina on February 27, 2012, 12:26:17 PM
and it should work. Let me know :)

yeah, that worked, lol.
thanks a lot!

now im heading to registration, im sure i will be here again soon, hehehe

edit, im back =D

im trying to make the registration, im using this in my registration block:

   $regOptions = array();
   $regOptions['member_name'] = $username;
   $regOptions['password'] = $password;
   $regOptions['email'] = $email;
   smfapi_registerMember($regOptions);

its like giving me a blank screen when i try to register.
im probably missing something here right?
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 27, 2012, 03:47:09 PM
That's the correct usage. Make sure you included the API script somewhere before all that. Also make sure those variable are set. There's not going to be any output echo'd from the function, it will return the int member ID or bool false. If you were expecting output from other parts of your script, check the error logs to see why the execution halted; the code you posted looks fine.
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 27, 2012, 04:25:33 PM
@ andre,

check it:
Quote from: errorlog
[27-Feb-2012 18:20:41] PHP Fatal error: The database value you're trying to insert does not exist: member_ip(smf_2_api.php-1595) in /home/aikaforum/cata/public_html/forum/Sources/Subs-Db-mysql.php on line 684
[27-Feb-2012 18:23:25] PHP Fatal error: The database value you're trying to insert does not exist: p_member_ip(smf_2_api.php-2522) in /home/aikaforum/cata/public_html/forum/Sources/Subs-Db-mysql.php on line 684
[27-Feb-2012 18:23:26] PHP Notice: Undefined index: USER_AGENT in /home/aikaforum/cata/public_html/forum/smf_2_api.php on line 1875
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 27, 2012, 04:42:54 PM
When you're registering members, the script is trying to use $user_info['ip'] to register the user's IP address with their other info, but it looks like that isn't being set for some reason.
Try calling loadUserSettings() before you register them to try to get the IP.
If that doesn't work, try changing $user_info['ip'] for $_SERVER['REMOTE_ADDR'] on ~line 1475
Is that server variable set? Are you running this on localhost?
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 28, 2012, 02:52:06 PM
@andre, its running on the server,
i changed the ip thing but that didnt help.
it still not registering.
do you think if i throw my full function here will help your visualization?
or maybe you want to login to my ftp.. idk..
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 29, 2012, 11:30:14 AM
Quote from: frytec on February 28, 2012, 02:52:06 PM
@andre, its running on the server,
i changed the ip thing but that didnt help.
it still not registering.
do you think if i throw my full function here will help your visualization?
or maybe you want to login to my ftp.. idk..


Hi frytec,
I updated the API to 0.1.2 to fix the issue with those variables being unset, the logout trouble, the magic quotes issue, and anything else mentioned in the previous threads. This should take care of your problem with registering. Can you download the new version (from the first post of this thread) and upload it and try it out?
Try the login, logout too as I modified them a little bit. If it doesn't work still can you post the error message from the log or pm me a temporary ftp account and the location of your script? :)
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on February 29, 2012, 12:10:48 PM
ok, im gona test the new version of api, justo to clarify, whats the correct usage of logout function?

smfapi_logout();

or

smfapi_logout($username);

or

smfapi_loadUserSettings(); smfapi_logout();

?

Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on February 29, 2012, 12:15:50 PM
Quote from: frytec on February 29, 2012, 12:10:48 PM
ok, im gona test the new version of api, justo to clarify, whats the correct usage of logout function?

smfapi_logout();

or

smfapi_logout($username);

or

smfapi_loadUserSettings(); smfapi_logout();

?


All of those will work, but to keep it simple just use smfapi_logout()

The function will call smfapi_loadUserSettings() itself if it needs to, and it will get the current user so there's no need to pass the username unless you're trying to log out someone who's not the current user from the who's online list :)
Title: Re: New tools to help integrating SMF with something else
Post by: frytec on March 02, 2012, 03:55:32 PM
@andre, i couldnt make the registration works via api, but with some sql queries i made the registration work thought.
so i think this is not an issue anymore,

but i would like help with something:

when i login into my website (and therefore automaticly login SMF), and them close the browser window for a long time, and than reopen it, i appears logged out of my website, but SFM still logged in.

Is there a way to fix this?
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on March 02, 2012, 04:03:35 PM
Quote from: frytec on March 02, 2012, 03:55:32 PM
@andre, i couldnt make the registration works via api, but with some sql queries i made the registration work thought.
so i think this is not an issue anymore,

but i would like help with something:

when i login into my website (and therefore automaticly login SMF), and them close the browser window for a long time, and than reopen it, i appears logged out of my website, but SFM still logged in.

Is there a way to fix this?

Yes. When you call the login function, specify how long you want them logged into smf as the second parameter of the function. Example:

smfapi_login('frytec', 60); //will log in user frytec for 60 minutes


The second parameter should be the integer value of your site's session duration in minutes. So check how long your main site sets the cookie for and just match that :)

Why didn't the register function work for you? I tested it and it worked with the new version of the API, and the old version worked all the time for me too... Did you get any errors, or notice as to why it wouldn't work? That's one of the functions that will almost never fail because all it does is basically db queries and inserts, so as long as the db connection is made and the data you pass in is ok, it should never fail :p
Title: Re: New tools to help integrating SMF with something else
Post by: Handmade on March 05, 2012, 11:22:22 AM
Would like to take a sec a publicly thank Andre for all his assistance with integration, his work is spotless and functions spot on.
Thanks Andre!! 8)
Title: Re: New tools to help integrating SMF with something else
Post by: jershell on March 11, 2012, 09:45:22 AM
Hello, please tell me what the function sends a letter confirming email? when you call smfapi_registermember, the user is created, but the letter was not sent when the 'require' => 'activation'.
PS: Sorry my english, written by "Google Translator".
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on March 14, 2012, 07:59:43 PM
Quote from: jershell on March 11, 2012, 09:45:22 AM
Hello, please tell me what the function sends a letter confirming email? when you call smfapi_registermember, the user is created, but the letter was not sent when the 'require' => 'activation'.
PS: Sorry my english, written by "Google Translator".

Try adding this code to the bottom of the smfapi_registerMember() function to add confirmation emails being sent. Put it just before the member ID is returned:

global $sourcedir;
require_once($sourcedir . '/Subs-Post.php'); //needed for sendmail and loadEmailTemplate functions
if ($regOptions['require'] == 'activation' || $regOptions['require'] == 'coppa')
{
$replacements = array(
'REALNAME' => $regOptions['register_vars']['real_name'],
'USERNAME' => $regOptions['username'],
'PASSWORD' => $regOptions['password'],
'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : '',
);

if ($regOptions['require'] == 'activation')
$replacements += array(
'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $memberID . ';code=' . $validation_code,
'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $memberID,
'ACTIVATIONCODE' => $validation_code,
);
else
$replacements += array(
'COPPALINK' => $scripturl . '?action=coppa;u=' . $memberID,
);

$emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . ($regOptions['require'] == 'activation' ? 'activate' : 'coppa'), $replacements);

sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
}


You might need to make some modifications to get it to work but that's the way SMF is doing it. If you are registering a member through another system though, and using the API to register them in SMF, why not let the other system handle the confirmation and the rest of it too?
Title: Re: New tools to help integrating SMF with something else
Post by: colby2152 on March 26, 2012, 09:01:39 PM
Where is the API file? :o
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on March 27, 2012, 09:52:44 AM
ummmmm.....    attached to the first post in this thread, silly....
Title: Re: New tools to help integrating SMF with something else
Post by: kristen_tg on March 29, 2012, 09:57:54 PM
Andre, I'm having a few issues with the API.  I am attempting to integrate it with a custom webapp, nothing more than when the user logs into the site they also get logged into the forums.

Right now I'm just working on the sign in side of things:


Notice: Undefined variable: cookieData in /home/public_html/forums_3/smf_2_api.php on line 1909
Notice: A session had already been started - ignoring session_start() in /home/public_html/security_scripts/signin.php on line 56


The user is properly logged into the SMF forums but NOT the application. The session, however, contains the proper information my system needs to validate it.

What's in smf_2_api.php that might be causing this? I suspect it's smfapi_loadSession() although it shouldn't execute if a session already exists (should it?)

ETA:

I solved the loadSesssion() error.  Feel a little silly now.  :o Too many 14 hours days in a row....

Still getting the $cookiedata notice. Would that be a cookie path issue? 



Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on March 30, 2012, 12:39:19 PM
Hi kristen_tg,

The API doesn't really need a session for anything. You can prevent it from starting one, or start your other webapp session first. loadSession won't start a session if one exists but it will always be called.

For the error, looks like $cookieData wasn't declared by the time the script got to line 1909, which means that your SMF cookie probably isn't set yet because it didn't go through the previous if/elseif block that would've set it.

You could add the @ operator to suppress the error from having the variable unset like this:

if (0 == $id_member) {
        $unserializedData = array();
        $success = funserialize(@$cookieData, $unserializedData);
        if ($success) {
            $id_member = $unserializedData[0];
            $password  = $unserializedData[1];
        } else {
            // they're either a guest or your cookie is not visible
        }
}


Or, probably safer, declare $cookieData again just in case...

if (0 == $id_member) {
        $unserializedData = array();
        $cookieData = stripslashes($_COOKIE[$cookiename]);
        $success = funserialize($cookieData, $unserializedData);
        if ($success) {
            $id_member = $unserializedData[0];
            $password  = $unserializedData[1];
        } else {
            // they're either a guest or your cookie is not visible (need subdomain independent cookies)
        }
}


let me know how that works :)
Title: Re: New tools to help integrating SMF with something else
Post by: kristen_tg on March 30, 2012, 08:34:53 PM
Thank you for the quick reply, Andre. I haven't had a chance to look at $cookiename yet (been squeezing the forum into my existing template)

I do have another question though  ::)

SMF and my app are nicely sharing the same session. However, when I go to the forum itself, the session data my application requires disappears from the session. Backing out of the forums restores the 2 bits of data. Any ideas on what method or function is causing those two bits of data to be unset? There's a whole host of data I need to grab from my application to properly populate the template. The board is in fact loading the proper include file that handles this, but for some reason just those 2 pieces of information are getting dumped out of the session.

Nevermind. Got it all working beautifully. Thank you so much for the API.
Title: Re: New tools to help integrating SMF with something else
Post by: stefann on April 30, 2012, 11:11:46 AM
Thanks for the API Andre, it's made my integration a whole lot less painful than expected!


However, as I am using SMF as only part of a two tier authentication system, I would like to be able to have my external integration call SMF's password reset functionality directly -- what's the best way to achieve this?


Thanks
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on May 01, 2012, 11:27:54 AM
Hi,
You can see how SMF is doing it in Sources/Reminder.php around line 245 (assuming 2.0)

// Randomly generate a new password, with only alpha numeric characters that is a max length of 10 chars.
require_once($sourcedir . '/Subs-Members.php');
$password = generateValidationCode();

require_once($sourcedir . '/Subs-Post.php');
$replacements = array(
'REALNAME' => $row['real_name'],
'REMINDLINK' => $scripturl . '?action=reminder;sa=setpassword;u=' . $row['id_member'] . ';code=' . $password,
'IP' => $user_info['ip'],
'MEMBERNAME' => $row['member_name'],
'OPENID' => $row['openid_uri'],
);

$emaildata = loadEmailTemplate('forgot_' . $context['account_type'], $replacements, empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']);
$context['description'] = $txt['reminder_' . (!empty($row['openid_uri']) ? 'openid_' : '') . 'sent'];

// If they were using OpenID simply email them their OpenID identity.
sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
if (empty($row['openid_uri']))
// Set the password in the database.
updateMemberData($row['id_member'], array('validation_code' => substr(md5($password), 0, 10)));


I'd try it like that, setting all the variables first
Title: Re: New tools to help integrating SMF with something else
Post by: Ardenstone on May 13, 2012, 09:28:50 PM
Thanks for posting this!  I'm new to SMF and so been giving smf_2_integration_hooks.php a shot; seems like it will save a lot of steps.

What I'd like to do is that, when a user first signs up for the forum, write their username to a custom table in the same database.  The following code works fine (it writes the username to the database or throws the error if the username already exists) except that on a successful write to my table, the user just gets a blank screen and is sitting at index.php?action=register2.  Do I need to return a specific value out of this function or something?  Since it stops at this step the user obviously never gets entered into SMF itself which is doubly problematic. :)

Also: has the username been cleansed at this point or is it still the raw username that the user set?  I'm hoping SMF has already taken care of the security aspects, but if not I need to add that here, too.


function smf_register_function($regOptions, $theme_vars)
{
global $smcFunc;
$dc = 'tnt_';
$query = "SELECT userID from $dc" . "USERS WHERE UPPER(userName) = UPPER('" . $regOptions['username'] . "')";
$result = $smcFunc['db_query']('',"$query");
$row = $smcFunc['db_fetch_assoc']($result);
if (isset($row['userID'])) {
exit("Username is already taken.");
}
$query = "INSERT INTO $dc" . "USERS (userID, userName) SELECT MAX(userID) + 1, '" . $regOptions['username'] . "' FROM $dc" . "USERS";
$result = $smcFunc['db_query']('',"$query");
$smcFunc['db_free_result']($result);

exit();
}


Thank you,
   Chris
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on May 13, 2012, 09:35:53 PM
Hi Chris,

It looks like you get a blank screen because of the exit() function. Try removing the second one.
The script will be called just before the data is inserted into the database so it should be cleaned up. You can check this in /Sources/Register.php  in the Register2() function around line 511, which is the point the integration hook is called
Title: Re: New tools to help integrating SMF with something else
Post by: Ardenstone on May 13, 2012, 09:59:22 PM
Thanks, Andre!  That worked like a charm.  I added that exit() earlier while trying to fix some other bug and never thought to take it out again.  Silliness on my part, and a quick and excellent response on yours.

All the best,
   Chris
Title: Re: New tools to help integrating SMF with something else
Post by: souf0 on May 22, 2012, 05:32:18 AM
Hi,
I'm searching for a api function for ban a user, but there aren't in this api file.
I think it's easy to make a function to ban some user using this api, there aren't no problem, no? Using $smcFunc['db_query'] and the query for to ban someone...
Thanks
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on May 24, 2012, 09:26:19 PM
Hi :)
If you take a look at how SMF does it in Sources/ManageBans.php in the function BanEdit() you should be able to figure out the queries you'll need to create a new ban.
Alternatively, it looks like you can set the user value is_activated to be > 10 and the user will be banned... That's how it looks to me anyways from looking at the code. You'd do that like like this:

smfapi_updateMemberData($user, array('is_activated' => 11));

Where $user is the email address, member id or username of the person that will be banned
Try it out and let us know if you can
Title: Re: New tools to help integrating SMF with something else
Post by: stefann on May 25, 2012, 02:47:50 AM
Just a tip for anyone else using different database users for the bridge & forum, if you do not provide write access to the SMF settings table, you may experience random & intermittent fatal errors when including this or any other SSI script eg INSERT,DELETE command denied to user 'bridge_smf'@'localhost' for table 'smf_settings' so you probably want to look at the seed generation around line 645, or even comment it out if you know you can trust the forum for entropy
Title: Re: New tools to help integrating SMF with something else
Post by: EpicorUsersGroup on May 25, 2012, 10:09:48 AM
Thanks for the API it is working well for my application.  How would I go about creating new boards within my forum from my application?
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on May 25, 2012, 10:28:36 AM
Why don't you just use SMF for that?

There are certain things which can/should be externally done, and others which really should be done, properly form inside the forum portion. Why would you need to create boards from an external source?
Title: Re: New tools to help integrating SMF with something else
Post by: EpicorUsersGroup on May 25, 2012, 10:51:34 AM
I already have a website with supports sub-groups within our user community, I would like to be able to create and connect those sub-groups with their own discussion group within a specific category in the forum.  We are new to smf and I am trying to integrate the forum into our existing functionality as smoothly as possible with as little administrative effort as possible.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on May 25, 2012, 10:55:01 AM
I think that you may be using cross-purpose terms.

to SMF, a GROUP is a way of organizing users for security, permissions, access or visual organization.

If this is how you are using the term, the what you should do is - use the API to associate your group structure to a similar group structure in SMF and then use SMF's permissions to grant (or deny) access to boards in SMF.
Title: Re: New tools to help integrating SMF with something else
Post by: EpicorUsersGroup on May 25, 2012, 11:45:34 AM
That is not my point at all.  Please excuse the reference to "groups" this has nothing do with SMF member groups.  I understand how to use the API for that.  We are a software user group with an existing website, I am adding and integrating SMF into our existing website.  I am just trying to figure out if it is possible to create a new SMF board automatically when we activate a new "sub-group" within our membership.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on May 25, 2012, 01:58:06 PM
well, since creating a board is just a php routine, yes.... it is. Although setting the permissions might be a little tricky.

remember, once you load SSI or the API, you can often use internal SMF functions.

although I am uncertain which file the create_board routine is in...   you can check the WIKI and the function database...
Title: Re: New tools to help integrating SMF with something else
Post by: EpicorUsersGroup on May 25, 2012, 02:31:21 PM
I have been poking around in the source code.  yes it looks like createboard is the correct routine.  I just have to figure out all the parameters.

Thanks for your help.

Title: Re: New tools to help integrating SMF with something else
Post by: trushkevich on June 14, 2012, 06:57:31 AM
Thank you Andre for the API! Man you saved several days of my life!
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on June 24, 2012, 10:23:46 PM
Hi there,

I've newly installed SMF and generally found it far easier than others (such as phpBB) to integrate my website and it's functionality.

I'm trying to install and setup the API to automate logging in, logging out and member info edits. I've created my own system, so I'm trying to use the API to do the same functions behind the scenes with SMF.

I cannot seem to find any documentation for the API. Where can I find an explanatory document and any "how to's" for the functions I want to set up? Would seem fairly run of the mill functionality for the API and would therefore have at least a basic document.

Can someone please help me with this.

Thanks very much.
Title: Re: New tools to help integrating SMF with something else
Post by: Andre N on June 24, 2012, 11:07:16 PM
Hi :)

There is a lot of documentation inside the API file itself at the top that will explain how to use the functions. They are pretty easy to use.

1. include the API in your file
2. call the function(s)
smfapi_login($username);
now they are logged in

If you get stuck just reply with your problem and I'll help you :)
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on June 25, 2012, 05:16:32 AM
Hi Andre,

Thanks for replying so quickly.

I'm attempting to add in a new registration and it doesn't want to work. Can you point out any error I have in my code.

require_once("forum/smf_2_api.php");
$regOptions = array('member_name' => $_POST['reguser'], 'email' => $_POST['email'], 'password' => $_POST['regpass'], 'memberGroup' => 4);
smfapi_registerMember($regOptions);

Thank you.
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on June 25, 2012, 09:10:18 PM
Hi Andre,

And now there is another issue....

I can no longer use the quick login to the forum. It says incorrect password. Then on the subsequent screen I reenter the password and it logs in. But, when I click on Members (for example) it thinks I'm not logged in.

Can you please assist...

Thak you.
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on June 26, 2012, 03:01:23 AM
Hi there,

I've fixed the registration issue, my fault, I had the code in the wrong spot of the main registration process.

However, I still have the above SMF login problem. Not related to my own system setup, this is just trying to log directly into SMF.

Any assistance would be wonderful.
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on June 26, 2012, 03:20:24 AM
I've now fixed the login problem, thanks to "miikka_" via post:
http://www.simplemachines.org/community/index.php?topic=363778.msg2551833#msg2551833

Basically, the www was missing from the Settings.php file $boardurl

This fixed the problem!!

Hope this helps others and I do wonder why this occurred?
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on June 27, 2012, 03:47:42 AM
Hi everyone,

I've finally been able to integrate Registration, Logging In and Logging out with my website via the API.

Unfortunately (it seems) SMF doesn't automatically remove the Login Logout and Register buttons when registration functionality is disabled and "Show a quick login on every page" is off.

Therefore, after reading hundreds of topics/posts, I found that you can at least redirect the login by placing a redirect at the top of the file "LogInOut.php" and "Register.php" (found in the Sources folder).

However, I'm still trying to remove the LOGOUT button from the menu.

Can someone please help me with this?

Thank you.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on June 27, 2012, 07:55:27 AM
???
if registration is disabled, then yes... SMF removes (does nto display) the register button.
However, of course it continues to show the login or logout button....  Those are not part of registration.

to remove those, you would delete or comment out the button listing from the menu array in subs.php
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on June 27, 2012, 07:40:00 PM
Hi Kindred,

Thank you for your reply.

However, the Register button is still shown in the menu, even when Registration is disabled. This I believe, is an oversight that should perhaps be rectified in a future release.

Additionally, I've found instruction on other posts regarding deleting out the menu array for Login, Logout, Register in the Subs.php file. However, even if this has been done, this is ignored. And all of these options are still shown.

Something that people should be aware of, even if you perform the above action, the cache will hold onto these options (via cache? or cookies? or?) and you won't see the effect. Only today, after a PC restart do I see the removed buttons.

Thank you.

Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on June 27, 2012, 09:27:52 PM
Nathan,

1... In my unmodified forum, register does not show if disabled.
2... Deleting the login, logout and register buttons from the menu array in subs.php removes the buttons. No other files Ned to be modified, but you could comment out the logout and login actions in index.php if you want to be thorough.


So, if these actions do not work for you, then you have other issues with our installation. Possibly a theme which does not respect the menu array.
Title: Re: New tools to help integrating SMF with something else
Post by: Arantor on June 27, 2012, 10:03:18 PM
'register' => array(
'title' => $txt['register'],
'href' => $scripturl . '?action=register',
'show' => $user_info['is_guest'],
'sub_buttons' => array(
),
'is_last' => !$context['right_to_left'],
),


Either you're imagining it or it's not a fresh install: the register button STILL SHOWS even if registration is disabled.

On top of that there's still several language strings that needed to be changed to fix this (as I had to do in Wedge a bit back for this very reason)

The cache will only be held in the event of cache level being 2 or higher, as per:
if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
cache_put_data('menu_buttons-' . implode('_', $user_info['groups']) . '-' . $user_info['language'], $menu_buttons, $cacheTime);


SMF does not install to level 2 on default. So other things could also be at play.
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on June 28, 2012, 01:09:15 AM
Hi Arantor.

I'm not imagining it. The SMF is a fresh install, I'm still setting it up and modifying minor elements of the default theme (copied to another name). 

The cache level is the default install, so that won't be an issue as I never modified (I double checked).

It is doing the same thing with other file modifications as well. E.g. I'm attempting to modify the Script.js (as directed by Oldiesmann on another post) to set the default for all of the boards to be collapsed.

Perhaps it's a server issue with the cache? I refresh using Ctrl F5 in Firefox, so I don't believe it's a browser issue....

Any suggestions?

Thanks
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on June 28, 2012, 01:27:19 AM
I think the imagination comment was directed at me...  And he's apparently correct. For some reason, the logic seems to ave gotten lost.

However, removing the registration men item, same as logout and login will still work.

If editing the menu array in subs.php is not shoeing, then either your sever cache is not refreshed or your theme is not using the enu array.
Title: Re: New tools to help integrating SMF with something else
Post by: keyrocks on July 11, 2012, 12:05:18 PM
I am fairly new to SMF 2.0.2 and have just completed configuring it with 320 Member-Groups and corresponding Forum Boards for each Member-Group. All of my work to-date has been accomplished offline on my localhost (home office) XP-Pro server running with XAMPP.

The next step:
To integrate this package with a client's WordPress + BuddyPress powered website already online at (ficticious domain) mainsite.com. The client wants the SMF package installed at mainsite.com/smf (located in a new smf directory within the site's root).

The Client's system:
When someone registers for an account at mainsite.com, the registration form collects the registrant's name, email, postal code, and a password. Once submitted, scratch-built functions (compatible with and in the WordPress site at mainsite.com) query an external d-base which contains the organization's master membership data.

A query checks the external d-base for a name and email match. If the match is positive (they exist), another query pulls the registrant's Member ID and Regional ID from the external d-base and adds them to his/her user profile for mainsite.com when the user's account is created and activated.

The Mission:
I do not have access to the client's servers or databases (their security policy), and the client's IT guy doesn't have time to figure out how to integrate the SMF package so that it is compatible with their WP + BuddyPress package already running on mainsite.com. The SMF package also needs to pull member information from their external d-base.

When a member logs into mainsite.com, they need to be automatically logged in to the SMF site at mainsite.com/SMF at the same time. Once logged in, the link to the SMF Forums will be added to the main menu-bar at mainsite.com. Clicking the "Forums" link in the main menu bar will land them on the main SMF Forum Boards page.

The SMF package will also need to pull the member's Regional ID from the client's external d-base and use that to:
1) automatically set the member's Member-Group already created (named identical to the Regional ID)
2) assign the same-named (Regional ID) Forum Board to be visible to the member when they are on the main Forums page.

Question:
Am I right to assume that I would need to use the API to accomplish all of that?
And, if so, what would be involved in getting there (broadly speaking of course).  8)
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on July 19, 2012, 02:55:22 AM
Hi there,

I've utilised the API to integrate the forum with my website. All seems to function ok now.

Except, the user logs into my site, which logs the user into the forum ok using the API. The forum menu shows just fine, as does the forum.

However, there seems to be a session issue going on, because when the user clicks on one of the forum menu items, it doesn't recognise that they are logged in and throws an error.

If one of the legends of the SMF community could take a look I'd be very grateful :)
If there is any code snippets you'd like, please let me know.

The link to the site is: www.inventerest.com (http://www.inventerest.com)

Thanks very much.


ADDENDUM: The issue I recalled was that the link to the website must be full and complete. During the installation by Installatron (VIA Control Panel) the settings.php doesn't get allocated the full website address. In this case it contained "http://inventerest.com/forum" instead of the correct "http://www.inventerest.com/forum"
Perhaps this should be addressed as an issue to be fixed??
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on July 19, 2012, 08:59:28 AM
it's not an issue on our side, since we don't control any automated installation scripts called Installatron... That sounds like a problem with how you host has configured the installation script that they set up.

Of course, many people are using the (no-www) address these days anyway, but if you turn ON subdomaind independent cookies, it should also fix the problem.
Title: Re: New tools to help integrating SMF with something else
Post by: nathanmc on July 19, 2012, 09:13:07 PM
Hi Kindred,

Good point about it not being your issue and Installatron.

And thanks for the heads up about the subdomain independent cookies.

Much appreciated!!
Title: Re: New tools to help integrating SMF with something else
Post by: Rajohan on July 23, 2012, 11:15:57 AM
How can i check if the user is logged in? I got a login to work perfectly, but i cant quite figure out how to check if the user i online. WHat i got now is


if(!smfapi_isOnline($user_info[username])) {
// show login
}
else {
//show user menu
}


it works but it seams like the username still is stored in smfapi_loadUserSettings(); when i try echo it out after ive logged out i still returns my username but the login shows and user menu gets hidden.
Title: Re: New tools to help integrating SMF with something else
Post by: LillyWhite on July 26, 2012, 11:23:31 AM
Hi! I've been trying to integrate a website with smf (using the same account of smf) but i need some help. This does work fine if i login on the forum for the first time (This is on the website):

      require_once($_SERVER['DOCUMENT_ROOT'] . '/forum/smf_2_api.php');
         
      global $user_info;
      $username = $user_info['username'];

      if ($user_info['is_guest']) {
         $data['header'] = "header";
      } else {
         $data['header'] = "headerlogged";
      }

If i close the web browser, when i visit my website i remain logged on the forum but it loads the guest "header" on the website. If i want this code to work again, I have to logout from the forum and login again. How can i check on my site if im already logged on the forum so i can display the "headerlogged" if i'm logged?

Thank you.
Title: Re: New tools to help integrating SMF with something else
Post by: LillyWhite on July 31, 2012, 08:51:01 AM
Can someone help please? :)
Title: Re: New tools to help integrating SMF with something else
Post by: Arantor on July 31, 2012, 09:14:32 AM
You have to do more than simply load the API file.

You can either change the require to reference /forum/SSI.php which will make your code work as expected, or you can add more code to make it work.
Title: Re: New tools to help integrating SMF with something else
Post by: LillyWhite on July 31, 2012, 10:02:44 AM
Hi. Ty for the quick help. If i change the require to SSI.php it works in the same way it did before. When i close the web browser it stops working. Checking the cookies, i see that they are not set when i visit the site without login first on the forum. This only works if i login first on the forum. Any idea what i must do to check if i am already logged on the forum by just visiting my site? I'm using codeigniter framework and im trying to use the same account of the forum in the site. Thank you. 
Title: Re: New tools to help integrating SMF with something else
Post by: Arantor on July 31, 2012, 10:11:49 AM
Well, SSI should be set first, and you probably have to also set subdomain independent cookies in Admin > Configuration > Server Settings > Cookies and Sessions.

Any other sessions will not play nicely with SMF's.
Title: Re: New tools to help integrating SMF with something else
Post by: LillyWhite on July 31, 2012, 10:25:54 AM
That worked. Thank you. ;D
Title: Re: New tools to help integrating SMF with something else
Post by: mpglivecarlo on July 31, 2012, 11:25:57 PM
thank you so much for this api didnt know it and now im loving it.
Title: Re: New tools to help integrating SMF with something else
Post by: cnttlc on August 09, 2012, 02:09:33 AM
Please help show on site home page 10 last post by catalog.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on August 09, 2012, 07:35:28 AM
What?

What is "by catalog"

Title: Re: New tools to help integrating SMF with something else
Post by: mpglivecarlo on August 16, 2012, 03:35:04 PM
Hi, wanted to report that when the api is used to register new members, the stats from forum dont get updated, can anyone help? thx
Title: Re: New tools to help integrating SMF with something else
Post by: Mystic83 on October 11, 2012, 05:59:53 AM
Hey all, I'm having difficulties using this API to get avatar data.

The avatar array doesn't seem to have anything useful in it for onsite avatars. The attachment id can't be used by any functions, as far as I can tell, and the the filename is incorrect. A little bit of poking around shows that on SMF, the attachments are loaded using the id, but I don't appear to be able to do that outside of those particular files. In addition, there is some hashing going on with regards to attachment names, which might explain why the filename is incorrect.

So what am I supposed to do with the data I'm given? I believe using SSI.php solves this problem, but because I need some of the things in the api, it seems silly to use both...
Title: Re: New tools to help integrating SMF with something else
Post by: guzh on October 12, 2012, 06:09:41 AM
Quote from: Mystic83 on October 11, 2012, 05:59:53 AM
Hey all, I'm having difficulties using this API to get avatar data.
At least for my use, this worked fine:
<img src="path/to/forum/index.php?action=dlattach;attach=<?php echo $user_info["avatar"]["id_attach"]; ?>;type=avatar" />
It would be a lot easier if the $user_info["avatar"]["url"] pointed to the correct url, though..
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on October 12, 2012, 07:29:33 AM
instead of user_info, you could use
$context['user']['avatar']['href'] or $context['user']['avatar']['image']
Title: Re: New tools to help integrating SMF with something else
Post by: guzh on October 12, 2012, 07:38:10 AM
Quote from: Kindred on October 12, 2012, 07:29:33 AM
instead of user_info, you could use
$context['user']['avatar']['href'] or $context['user']['avatar']['image']
Yeah, that's an option. But as he/she's already using some functions in the API it shouldn't be necessary to also use the SSI.

I think that $user_info["avatar"]["url"] should be exactly the same as $context['user']['avatar']['href'], and I think that is the intention as well.
However $user_info["avatar"]["url"] doesn't return anything. it's empty.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on October 12, 2012, 09:03:30 AM
incorrect
$user_info['avatar']['url'] returns the RELATIVE filename/URL of the avatar...
[url] => Symbolism/Vetruvian Man.png

assuming the system defined avatar directory for system avatars and the rest of the array is for custom uploaded avatars...


    [avatar] => Array
        (
            [url] => Symbolism/Vetruvian Man.png
            [filename] =>
            [custom_dir] =>
            [id_attach] => 0
        )
Title: Re: New tools to help integrating SMF with something else
Post by: guzh on October 12, 2012, 09:13:50 AM
hm.. mine returns:
["avatar"]=>  array(4) {
    ["url"]=>  string(0) ""
    ["filename"]=> string(12) "avatar_6.jpg"
    ["custom_dir"]=> bool(false)
    ["id_attach"]=> string(1) "3"
}



any idea why mine returns something else than yours?
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on October 12, 2012, 09:40:41 AM
hmmm....   good question.

my excerpt was generated by using 
echo '<pre>'; print_r($user_info); echo '</pre>';

(I did include SSI... maybe that's it?)

the user currently logged in is using a system avatar in a subdirectory of the base avatars directory (defined in SMF admin and stored in the database)
   smf_settings.avatar_directory
   smf_settings.avatar_url
the two other settings which might be important
   smf_settings.custom_avatar_directory
   smf_settings.custom_avatar_url
and of course
   smf_members.avatar

I believe that, if the user has an external avatar, the url would be the full url.
I THINK that the filename and custom_dir are for uploaded avatars...
Title: Re: New tools to help integrating SMF with something else
Post by: guzh on October 12, 2012, 10:07:01 AM
I used var_dump, but that shouldn't matter. And I included SSI as well.

I couldn't find smf_settings.custom_avatar_directory and smf_settings_custom_avatar_url.
and at the user logged in the smf_members.avatar is empty.

The avatar is stored in smf_attachment for the user. However if the user use a system avatar it is stored in smf_members.avatar.

It may be because I some years ago moved from phpbb to SMF...?

Anyway. I'll just use the SSI as well as the API, for this matter I think..
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on October 12, 2012, 02:27:02 PM
well, maybe you never set a custom upload directory?

avatar is stored in attachment if it's an uploaded avatar
url is stored in members.avatar if they include an external url (again, the capability for this depends on your settings)
Title: Re: New tools to help integrating SMF with something else
Post by: mredd on August 16, 2013, 10:34:42 AM
Hi All.

OK I am proberbly going to sound real stupid now.

QuoteHow to use the API:
1. Upload it to your server. Anywhere. Make sure your SMF installation is on the same server. It will seek out your installation and create a settings.txt file with the location of your Settings.php file for it's own future reference (to make it load faster)

done this but cant find the settings txt file.

Quote2. In your script, include the API file. Include it anywhere you like as long as it gets included before you try to use it's functions.

what script do I add it to ?

Quote
3. Call the functions. They are documented pretty well but if you have questions ask below.
Example:

what script do I add it to ?

See told you I would sound real stupid.

Thanks for any help given.
mredd.

Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on August 16, 2013, 05:12:46 PM
1- per the instructions you have to CREATE the settings.txt file
2- whatever script you are trying to integrate smf into
3- see #2....   if you don't understand that - no offense, but you should not be trying to code an API function...
Title: Re: New tools to help integrating SMF with something else
Post by: iainjames88 on September 21, 2013, 05:38:43 PM
Any suggestions on how to integrate this with a Laravel 4 application?
Title: Re: New tools to help integrating SMF with something else
Post by: Phoenix_IV on September 25, 2013, 08:58:44 AM
Quote from: Andre N on September 19, 2011, 01:35:36 PM
Questions, comments and suggestions welcome.

I posted mine in a new thread, trying to keep all of this a little structured:

Subject: SMF API - smfapi_login() doesn't work for me
Link: http://www.simplemachines.org/community/index.php?topic=511697.0

Suggestion: It might be a good idea for everyone to do it like this; creating a new thread and linking it here. Would you like that?
Title: Re: New tools to help integrating SMF with something else
Post by: Phoenix_IV on September 25, 2013, 01:31:31 PM
Double post because it's a while ago since the last post and this contains a new topic.

Two improvements concerning smfapi_login():

1. The function maybe should return false if the user can't be logged in due to his 'is_activated' status plus a hint on the reason. (See Topic: SMF API - smfapi_login() doesn't work for me (http://www.simplemachines.org/community/index.php?topic=511697))

2. The documentation should mention the existence of $regOptions['require'].
Currently the documentation reads:

    int    smfapi_registerMember(array $regOptions)
        - register a member
        - $regOptions will contain the variables from the db
        - dump out the results of smfapi_getUserData($user) to see them all
        - required variables are: 'member_name' (unique), 'email' (unique), 'password'

BUT: Statement #2 does not include the field 'is_activated'. This field's value is influenced by the setting $regOptions['require'] (which isn't a field in the table). Example: $regOptions['require'] = 'nothing'). This is because 'require' also triggers the generation of an activation code and such, but thats only one more reason to hint on that option in the documentation.


This would be my updated version of the documentation:

    int    smfapi_registerMember(array $regOptions)
        - register a member
        - $regOptions will contain most variables from the db (table 'members')
            - required variables are: 'member_name' (unique), 'email' (unique), 'password'
            - additional variables are:
                'require'
                    Determines the user's activation status
                    Accepted values: 'nothing', 'activation' (by the user using an activation code)
                    Default: If not set the user will have to be activated by an administrator!
                'memberGroup'
                    Equivalent to field 'id_group'. It will be checked if the given id is valid.
        - $regOptions['register_vars'] will contain ALL variables from the db. However, some of
          these might get overwritten (e.g. 'posts' will always be zero), but also depending on
          the settings from above.
          Dump out the results of smfapi_getUserData($user) or go to the listing of $userdata
          below to see them all.


[...]


/**
* Register a member
*
* Register a new member with SMF
*
* @param  array $regOptions the registration options
*         More information can be found at the head of this file       
* @return int $memberId the user's member id on success
*         array of string $reg_errors on failure. Each string names a reason why this failed.
* @since  0.1.2
*/
function smfapi_registerMember($regOptions)
{
Title: Re: New tools to help integrating SMF with something else
Post by: Hitman.pt on September 26, 2013, 05:45:05 PM
Need help
wrote this small script

<?php
require_once('../API/smf_2_api.php');

$usr $_POST['user'];
$pw $_POST['pass'];
$time $_POST['time'];

$res smfapi_authenticate($usr$pw);
if(
$res == 1)
{
smfapi_login($usr);
echo "done";
}
else
{
echo "wrong";
}
?>


It loggs me in on the website but not on SMF any help»?
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on September 26, 2013, 07:56:13 PM
and did you actually bother to even read the post a few below yours?

http://www.simplemachines.org/community/index.php?topic=511697.0
Title: Re: New tools to help integrating SMF with something else
Post by: Hitman.pt on September 27, 2013, 05:47:12 AM
Quote from: Kindred on September 26, 2013, 07:56:13 PM
and did you actually bother to even read the post a few below yours?

http://www.simplemachines.org/community/index.php?topic=511697.0
Solved. Thanks
Title: Re: New tools to help integrating SMF with something else
Post by: MrMorph on November 20, 2013, 11:48:03 AM
Firstly thanks very much for this, after some tinkering around I managed to get this working with a file browser I wanted to use in my SMF.

I was just wondering what (if anything) else needs to be done security wise ?

I'm not clued up on this kind of thing yet, but the REST version uses a secret key.  Is it necessary to protect any of the files in this API in a similar way. And should the folder with the settings txt be protected for any reason ?

Or am I good to go ?

Many thanks :)
Title: Re: New tools to help integrating SMF with something else
Post by: MrMorph on November 20, 2013, 12:00:26 PM
Also one other thing that I might need later on...if I use :

global $user_info;

And print that array out, it does not list permissions - what am I doing wrong there please ?
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on November 20, 2013, 12:30:38 PM
what sort of permissions?

permissions are handled by GROUP, not by USER....

so, the user_info array DOES tell you what groups the user belongs to - and then the groups determine the permissions
Title: Re: New tools to help integrating SMF with something else
Post by: MrMorph on November 20, 2013, 01:04:54 PM
OK so have you got an example of how to get what permissions a user has then please ?

Also, any thoughts on my other question ?

Thanks for your reply. :)
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on November 20, 2013, 01:57:19 PM
there is no view of what an individual USER has for permissions.

All permissions are handled by GROUP.

If a user belongs to the GROUP that has pemrission X, then the user can do whatever the permission covers.




If you are using some sort of file system, then you potentially have a HUGE security gap...    and that is not something that can be handled from within SMF.   That is something that whatever file system you use will have to handle...   (and I have yet to find any decent Open Source file handlers that I would dare to put on an open network.
Title: Re: New tools to help integrating SMF with something else
Post by: MrMorph on November 20, 2013, 02:03:46 PM
It's not going to be an open system, it's only for my use. Obviously I am aware of the security issues, hence my other question...
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on November 20, 2013, 02:17:12 PM
then you either give permission to anyone in the admin group, or base it off of user ID.

Title: Re: New tools to help integrating SMF with something else
Post by: MrMorph on November 20, 2013, 02:20:42 PM
Yes that's right - I based it on being admin...
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on November 20, 2013, 02:51:42 PM
then you can just use a standard
if(allowedTo('admin_forum'))
Title: Re: New tools to help integrating SMF with something else
Post by: MrMorph on November 20, 2013, 03:04:04 PM
You can't use that function, so I just used :

global $user_info;

if ($user_info['is_admin'])
...do stuff
Title: Re: New tools to help integrating SMF with something else
Post by: MrMorph on November 24, 2013, 11:12:40 AM
I ran into a slight problem in IE 10.

When I test my admin checking code is connecting okay like this :

require_once ('/../../api/smf_2_api.php');
global $user_info;
print_r($user_info);


$user_info is empty; the structure is there but the fields are all empty. And I get :

Notice: Undefined variable: cookieData in F:\Programs\xampp\htdocs\articlesmod\api\smf_2_api.php on line 1909

What is strange is that it works fine in Chrome.

Any thoughts ? Thanks :)

EDIT: currently I am working on localhost, if that would make a difference to cookie handling in IE I am not sure :/
Title: Re: New tools to help integrating SMF with something else
Post by: le.mag.cinema on January 19, 2014, 06:59:59 AM
Looking for s sample to start my script ...

My need is to auto-generate posts from an external rss file.
I will have to choose the url for my rss file, parse it and only retain some information.
Transform it to one or several posts
Post them to a dedicated topic.

This script would have to be called by cron or by a button or link inside SMF.

Could someone help me by providing a sample script that does what is required on the smf side (I suppose calling a login method, calling a post method, calling a logout method, is that all ?)
I had a quick view on the API itself, and read this thread, but I need help, I wasn't able to guess :
1/ whether this API (or its REST version) is the right tool of choice to do what I want - I found some smf mods that dont't work at all and seems to be not safe at all
2/ whteher this APi is fully compatible with SMF 2.0.6 and is usable with anti-spam features like password protection, captcha
3/ what functions I have to call, in what order
4/ if I really need to login from my script or if I could call a script thanks to a button from inside SMF once logged in and therefore not have to care about login.
5/ whether the API is secured enough (will I have to write my password clear on my script ?)


I am more comfortable with java code writing than PHP, and therefore was thinking of calling the php REST API from outside, but as further steps, my first step would be to start with the need I described here.

PLEASE any sample script to start in the right way using this API !!!!



Title: Re: New tools to help integrating SMF with something else
Post by: kouser on April 19, 2014, 04:20:45 AM
It took me an hour to figure out that you have to be registered and logged into this SMF website in order to see the download-able packages mentioned in the very first post of this thread.

What is the sense of letting you see the initial post of this thread, and all 8 pages of posted replies, referring to the "attached" files, without actually showing the attached files until you login?

If withholding the attached files is supposed to encourage people to register on this site, at least tell them so somewhere. I must have read that first post 10 times word by word looking for the links to the files.

Title: Re: New tools to help integrating SMF with something else
Post by: TheLoneWolf on April 20, 2014, 11:21:04 PM
Could someone help me with this API Stuff, I have an IRC Channel that my IRC Bot connects to, I want my IRC Bot to put a link in the chat when ever someone makes a new post/topic. The link will take the person that clicked it to the new post/topic
Title: Re: New tools to help integrating SMF with something else
Post by: CristianOspina on June 07, 2014, 10:37:27 PM
This is just too good!.
I had a project that required the integration of a forum. I tried vB, and there's nothing to talk about, poor documentation, support, etc..
And then, there is the SMF SSI, and this wonderful API that Andre made, really a very good job and help, works better than I expected.

I Modify it to have it as a class, ideal for OOP and for use on some PHP Framework. I had some problems at the start but everything perfect I guess, have not tried all the features, but what I needed (sessions), works great!

I hope that there is still support for this code in the following versions.

Thanks a lot!  :D
Title: Re: New tools to help integrating SMF with something else
Post by: Dromo on September 10, 2014, 04:59:09 AM
Real novice here.  I have a PHP/MySQL app which manages a membership database. I'm trying to add functionality so that when users are added to the system, they are also added as members to an SMF forum.

My problem is that including the API in my PHP script :

require_once "scripts/constants.php";
require_once 'scripts/functions.php';
require_once 'scripts/database_connection.php';
require_once 'smf_2_api.php';
include('Mail.php');
session_start();
etc. etc.

generates a message which says

No database selected

What am I doing wrong?


Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on September 10, 2014, 06:24:35 AM
that sounds like an error from your other piece of software....
Title: Re: New tools to help integrating SMF with something else
Post by: Dromo on September 10, 2014, 08:51:07 AM
You're right, a bit of research has shown that the message itself is coming from my own application. However what seems to be happening is that the API is interfering in some way with my code. If I place my database connection script after the API call, the problem goes away. However, I then get errors in a second PHP script which seems to have lost track of a session variable. 

Perhaps it would be better if I try to explain what I'm trying to do.

Currently the application looks like this:

A script called 'signup.php' displays a membership form which the prospective member fills in. The data is validated and a record is created in an SQL database (which is on the same server as the SMF forum). The script then passes control to a second script called 'showuser.php' which displays the membership data back to the new user.

All I'm trying to do is to add to the existing code the feature that whenever a user is created, a user is also created in our related SMF Forum. (Ultimately, I want to add similar functionality for whenever a user is deleted but that's for later).

As instructed, I have inserted the include statement for the SMF API at the beginning of 'signup.php'. Originally, it was before the include which makes my own SQL database connection and in that place it generated the error mentioned in my original post.

Switching these two include statements around allows the new user record to be added to the database but I then get errors in 'showuser.php' which state that it has lost the session variable which tells the script which user data to display (i.e. the unique user id. assigned by MySQL when adding the new record and which is passed as a session variable from the signup.php to showuser.php).

The application was working correctly until I tried to add the SMF functionality, and if I remove the include statement for the API, there is no problem.

Any clues that you can provide to help me solve this problem will be greatly appreciated.




Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on September 10, 2014, 10:20:34 AM
ah... you are going to have issues...

SMF has its own session handling... which means that previously establish sessions may not survive the load of SMF (and vice-versa)
Title: Re: New tools to help integrating SMF with something else
Post by: Dromo on October 10, 2014, 10:01:30 AM
The only way I could get it to work was to remove the call to smfapi_loadSession() in the API. I don't need an SMF session as all I am doing is adding a member to the forum database. This works: the member is added to the forum and my initial script passes my session variables to the second script correctly.

I tried all kinds of things such as destroying the session after the forum had been updated and then starting a new one with just my own variables but whatever I did, none of it worked.

What I have done is really only a workaround. I would appreciate if somebody could really explain why the session which the API starts should affect a session which is started afterwards
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on October 10, 2014, 10:30:01 AM
I could be wrong... but I don't think that you can have two sessions active at the same time...   so starting a new session either fails or destroys the old session

and, of course, by doing what you have done, you removed part of the SMF security...
Title: Re: New tools to help integrating SMF with something else
Post by: Dromo on October 10, 2014, 12:24:12 PM
As far as I understand it, you're right: you can't have two sessions active at once.  That's why, first of all, I tried to kill the session that the API had started once I had finished with it.  No luck.  I don't think I'm compromising the SMF security (although I am happy to be proved wrong).  My use of the API is very limited. The logic of the script goes:

1) Display a form
2) Receive and validate data
3) Add a member to the MySQL database
4) Add a member  to the forum using the API
5) Exit to the next script with the new member's id (MySQL not SMF) as a session variable .

The code for step 4 looks like this:

require_once 'smf_2_api.php';
$forumok = "n";
$member_name = $first_name." ".$last_name;
$email_suffix = 1;
$email_suffix_needed = "n";
$member_name_suffix = 1;
while ($forumok == "n") {
   $regOptions = array('member_name' => $member_name, 'real_name' => $member_name, 'email' => $email, 'password' => $password, 'lngfile'=> $forum_lang);
   $answers = smfapi_registerMember($regOptions);
   if (!is_array($answers)) {
      $forumok = "y";
      continue;
   }else{
        if (in_array("email already in use", $answers)) {
         if ($email_suffix_needed == "n") {
            $email = $first_name. $last_name . "@xxxxx.org";
            $email_suffix_needed = "y";
         }else{
            $email = $first_name. $last_name . $email_suffix . "@xxxxx.org";
            ++$email_suffix;
         }   
      }
      if (in_array("username taken", $answers)) {
         echo "username taken found... \r\n";
         $member_name = $member_name . $member_name_suffix;
         ++$member_name_suffix;
         echo "username = ". $username;
      }   
   }   
}

Thanks for taking the trouble to reply; I appreciate it.

   
Title: Re: New tools to help integrating SMF with something else
Post by: Dromo on November 15, 2014, 10:31:07 AM
As you can see from the code in my post of 10 October, in my application the username is a concatenation of the member's first and last names. This is fine when a member is first of all added to the forum, but I have a problem if the member subsequently changes either of their first or last names. Given that it is probably a key to a number of other tables in the database, I imagine that it will not be possible just to update the existing username with a concatenation of the new first and last names.

The only thing that I can think of is to create a completely new user. This would not be a satisfactory solution as there would then be a disconnect between all the other information (posts etc.) that are held in the forum under the old name and information inserted under the new name.

Is there any way that this particular problem can be solved?

Will I have similar problems with email address?
Title: Re: New tools to help integrating SMF with something else
Post by: Mex on December 09, 2014, 08:27:55 AM
Nice API.
Is there a function to check if a user is logged in by checking cookie data?
Title: Re: New tools to help integrating SMF with something else
Post by: vexq on January 04, 2015, 08:33:18 PM
I'm getting an error

Undefined variable: cookieData [APP\Vendor\smf_2_api.php, line 1909]

It seems to stem from it either never setting up $cookieName or from not setting $cookieData. Is the api still in development or is it stable enough to use?
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on January 04, 2015, 09:58:30 PM
The API has been successfully used on dozens, if not hundred of sites..
Title: Re: New tools to help integrating SMF with something else
Post by: vexq on January 09, 2015, 08:07:35 PM
Is there a version of this for 2.1?
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on January 09, 2015, 08:14:23 PM
No...   Especially since 2.1 is still just in beta 1
Title: Re: New tools to help integrating SMF with something else
Post by: Mac Tracbac on January 15, 2015, 01:40:16 PM
Hi,

I have an SMF forum that has been running for a long time. I would now like to be able to post things from an Android app (It will be a very simple thing with an intent-filter that adds itself to the share menu on an Android device. The content will then be posted in a thread). I am an engineer and know how to code, but I am clueless about web-programming and related things. However, people on said forum could help me quite a bit with the server side problems, but I feel like I need to figure out the correct direction first.

Would using this API be feasible and make sense for this application? I know that the API has no ready written functions for posting, but it seems easy to add to the API (as explained earlier in the thread). What is unclear to me is how the Android java would communicate with the API and how the API php-would be integrated in the app.

I am not looking for detailed answers, but I would very much appreciate any comments on the general feasibility and perhaps a few hints so that I could be on my way to find out the details on my own.
Title: Re: New tools to help integrating SMF with something else
Post by: Arantor on January 15, 2015, 01:44:08 PM
Well, the API PHP part stays on the server, and the Java client sends commands to the API via HTTP... you don't have to worry about embedding any of the PHP on your app.

Your biggest question is really about getting something going in Java to communicate with the API in all honesty. It's not a task for the faint of heart, regardless of whatever programming background you're coming from.
Title: Re: New tools to help integrating SMF with something else
Post by: Mac Tracbac on January 15, 2015, 01:59:32 PM
Quote from: Arantor on January 15, 2015, 01:44:08 PM
Your biggest question is really about getting something going in Java to communicate with the API in all honesty. It's not a task for the faint of heart, regardless of whatever programming background you're coming from.

Thank you very much fow your answer.

I see. This was the part that I didn't grasp, but I assumed it would be a straightforward task (given general knowledge). But do you agree that if it should be done, using the API is the sensible way to go? I have seen that there are more direct solutions, but they seem incredibly messy.
Title: Re: New tools to help integrating SMF with something else
Post by: Arantor on January 15, 2015, 02:01:31 PM
I'd suggest the RESTful API - http://www.simplemachines.org/community/index.php?topic=458832.0 - is probably a bit more what you're looking for. This particular one is designed for integration with other systems, not for the kind you're trying to do.
Title: Re: New tools to help integrating SMF with something else
Post by: BigOHenry on January 23, 2015, 02:23:11 PM
Is this API compatible with SMF 2.1 beta1? I am developing new application and i would like to use SMF 2.1.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on January 23, 2015, 03:11:26 PM
I have not checked or tested, but I suspect almost certainly not....
Title: Re: New tools to help integrating SMF with something else
Post by: BigOHenry on January 23, 2015, 03:56:04 PM
Thank you for quick answer, so i will use 2.0.9 version.

I am getting error in my application when include smf_2_api.php file:

Undefined variable: cookieData [www\integration\smf_2_api.php, line 1909]

Any ideas? :(
Title: Re: New tools to help integrating SMF with something else
Post by: Arantor on January 23, 2015, 04:53:30 PM
How are you trying to use it exactly?
Title: Re: New tools to help integrating SMF with something else
Post by: BigOHenry on January 23, 2015, 05:09:28 PM
not use for now. only included and getting error...
Title: Re: New tools to help integrating SMF with something else
Post by: Arantor on January 23, 2015, 05:43:13 PM
Yes, included where?
Title: Re: New tools to help integrating SMF with something else
Post by: BigOHenry on January 24, 2015, 03:53:32 AM
I am using czech framework Nette with MVP architecture. I tried included into bootstrap.php and SignPresenter.php.
Nette app is on www.myweb.com and SMF is on forum.myweb.com.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on January 24, 2015, 09:58:52 AM
Ugh...   Using bootstrap with smf is fraught with issues, iirc...
Title: Re: New tools to help integrating SMF with something else
Post by: Arantor on January 24, 2015, 09:59:41 AM
Different Bootstrap.

Though I have no idea how this is trying to be used or what code is involved at this point because telling me that doesn't actually help me any :(
Title: Re: New tools to help integrating SMF with something else
Post by: BigOHenry on January 24, 2015, 11:18:55 AM
I have SMF on forum.myweb.com. My application in Nette framework (similar like Symfony 2) is on www.myweb.com.

Only thing i need is Single-sign-on betwen SMF and my application. So there will be 1 SMF session on subdomain and 1 Nette session on domain. Only communication i need is when login and logout.

My app using smf_members table (so only 1 user table for both).

Its possible?
Title: Re: New tools to help integrating SMF with something else
Post by: Arantor on January 24, 2015, 11:20:09 AM
It's possible but you have to understand that no-one here knows Nette... I never even heard of it until you mentioned it. More details would seriously be useful, because from what's been described, Nette is doing something that's even breaking the API.
Title: Re: New tools to help integrating SMF with something else
Post by: BigOHenry on January 24, 2015, 12:33:07 PM
I dont know what you need to know to help me :(

Nette has MVP (Model-View-Presenter) architecture like Symfony 2.

my index.php:


$container = require __DIR__ . '/../app/bootstrap.php';

require_once __DIR__ . '/../www/integration/smf_2_api.php';

$container->getService('application')->run();



Bootstrap:



require __DIR__ . '/../vendor/autoload.php'; //load classes

$configurator = new Nette\Configurator;

//$configurator->setDebugMode('23.75.345.200'); // enable for your remote IP
$configurator->enableDebugger(__DIR__ . '/../log');

$configurator->setTempDirectory(__DIR__ . '/../temp');

$configurator->createRobotLoader()
->addDirectory(__DIR__)
->register();

$configurator->addConfig(__DIR__ . '/config/config.neon');
$configurator->addConfig(__DIR__ . '/config/config.local.neon');

$container = $configurator->createContainer();

return $container;


When i include the SMF API into bootstrap, getting this error:


Nette\InvalidStateException

Unable to set 'session.gc_maxlifetime' to value '1209600' when session has been started by session.auto_start or session_start(). search►


So, integration file in bootstrap.php should work, but that SMF API already started the session..... Is there any way how to start session on subdomain not domain from integration API?

Title: Re: New tools to help integrating SMF with something else
Post by: rameleu on February 19, 2015, 01:03:27 PM
Hello everyone,

I'm actually trying to make register working by doing this :

$regOptions = array();
   $regOptions['member_name'] = $username;
   $regOptions['password'] = $password;
   $regOptions['email'] = $email;
   $email='[email protected]';
   $password='testPassword';
   $username='testRegister';
   smfapi_registerMember($regOptions);


But when I go on the page, nothing happens (there's no registration)

If someone knows what my problem is :)
Title: Re: New tools to help integrating SMF with something else
Post by: nearlyepic on March 03, 2015, 11:04:11 PM
Hi, I seem to be having the same problem that BigOHenry was having. Even a simple bit of code, such as:

<?php
require_once "/var/www/smfapi/smf_2_api.php";
smfapi_loadSession();
smfapi_loadUserSettings();
var_dump($user_info);
?>



Produces:

Notice: Undefined variable: cookieData in /var/www/smfapi/smf_2_api.php on line 1909

Notice: Undefined variable: cookieData in /var/www/smfapi/smf_2_api.php on line 1909
array(27) { ["groups"]=> array(1) { [0]=> int(-1) } ["possibly_robot"]=> bool(false) ["id"]=> int(0) ["username"]=> string(0) "" ["name"]=> string(0) "" ["email"]=> string(0) "" ["passwd"]=> string(0) "" ["language"]=> string(7) "english" ["is_guest"]=> bool(true) ["is_admin"]=> bool(false) ["theme"]=> int(0) ["last_login"]=> int(0) ["ip"]=> string(11) "68.32.30.25" ["ip2"]=> string(11) "68.32.30.25" ["posts"]=> int(0) ["time_format"]=> string(22) "%B %d, %Y, %I:%M:%S %p" ["time_offset"]=> int(0) ["avatar"]=> array(4) { ["url"]=> string(0) "" ["filename"]=> string(0) "" ["custom_dir"]=> bool(false) ["id_attach"]=> int(0) } ["smiley_set"]=> string(0) "" ["messages"]=> int(0) ["unread_messages"]=> int(0) ["total_time_logged_in"]=> int(0) ["buddies"]=> array(0) { } ["ignoreboards"]=> array(0) { } ["ignoreusers"]=> array(0) { } ["warning"]=> int(0) ["permissions"]=> array(0) { } }


It appears that it only happens when I am logged out from SMF.
Title: Re: New tools to help integrating SMF with something else
Post by: rpandassociates on March 04, 2015, 05:43:18 PM
I am using
adultvideoscript which is smartyPHP
with the social login mod from neuvo labs

I am using SMF as my forum at domainname.co/forums

I want to hire someone to do some work
I want it so if a user registers or logs in at my primary site the AVS site, wether it be via social login or via standard registration login that their account will be created in SMF and logged in at SMF at the same time.

Is this API the way to do it?
Would some one want to make some money doing this for me?

If so let me know how much and how long it will take
Title: Re: New tools to help integrating SMF with something else
Post by: Shambles on March 04, 2015, 05:55:47 PM
Quote from: rpandassociates
I want to hire someone to do some work

If so let me know how much and how long it will take

This isn't really the right thread to request paid work, but to jump in before anyone else does, I can do what you require within 2 weeks, at a cost of just £168,000 guaranteed to work first time.
Title: Re: New tools to help integrating SMF with something else
Post by: Rdejong on April 19, 2015, 04:22:05 PM
The following code returns 'True' but doesn't create a cookie (regular login to the forum creates and cookie);

// include the api file
require_once ('smf_2_api.php');

$email = htmlspecialchars($_POST["email"]);

echo smfapi_login($email);

I know that the rest of the API is working because the following code does create an user account;

$name = "Rdejong";
$email = "[email protected]";
$password = "xxxx";

$regOptions = array('member_name' => $name, 'email' => $email, 'password' => $password);

smfapi_registerMember($regOptions);

I have changed and played with the 'Use subdomain independent cookies' and 'Enable local storage of cookies' but it doesn't seem to make any different, no cookies are actually being created.


Title: Re: New tools to help integrating SMF with something else
Post by: anonymous001 on August 16, 2015, 11:59:23 AM
I currently use SMF 2.0.10  is this API script or any other from "Andre N" compatiby with this version? If yes which one? If no, which smf version did I need to be working with the API scripts?
Title: Re: New tools to help integrating SMF with something else
Post by: margarett on August 16, 2015, 12:05:39 PM
Yes it is compatible. You should use the files attached to the first post ;)
Title: Re: New tools to help integrating SMF with something else
Post by: anonymous001 on August 16, 2015, 12:18:24 PM
Thanks, for the fast answer.
My problem using the api: http://www.simplemachines.org/community/index.php?topic=538976.msg3830402#new
-I just did not use the REST api because I just need to interact on one server, so no need for the function of the REST api.
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on January 15, 2016, 08:00:15 AM
Hi guys!

Nice work!

Can someone explain me what I should do with the Settings.php?

When I require_once the API file, it goes wrong. And It looks like there is something missing with the settings (file?)

How am I supposed to create the settings file?

Thanks!

PS: the Captcha is really hard!
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on January 15, 2016, 08:33:19 AM
Settings.php is ALWAYS present with any successful installation of SMF. It is in the root smf folder (and can not be moved)

Nor should it be edited...  AFAIK, the API works correctly with Settings.php as generated by SMF
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on January 15, 2016, 08:44:54 AM
Thank you for replying so quickly!

I actually saw Settings.php a few minutes after postings and figured out that my issues were with include paths. I sorted it out now.

On a side note, it looks to me that the initial post of this thread should be edited to reflect the current state of the API. I have a strong feeling that it is now misleading. (for example, smfapi_logout($email); is used in the first lines but does not apply any more).

I have now run into a new issue and it is a bit weird.

While trying to register an user, I got this error:  Undefined index: default_personalText

Looing at the content of the $smf_settings array, I found default_personal_text instead!

Of course, it is easy to fix for me, I can just correct the API file accordingly. But I wonder how this error is possible (how can the API file be wrong on that?) and how many people's code it broke. Has SMF been updated recently leading to this issue? That would be the only sensible explanation I think.

Thanks!

Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on January 15, 2016, 08:51:19 AM
well, the API was written by someone (not on the SMF team) in 2011.

SMF stopped using camel case with the 2.0 release, I believe...  So no... not recently changed
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on January 15, 2016, 09:01:45 AM
OK. So it means the API will be broken in many places? If it has not been updated since SMF2 has been released?
Title: Re: New tools to help integrating SMF with something else
Post by: Illori on January 15, 2016, 09:06:59 AM
there have not been major changes in SMF 2.0 has been released, so it should work without issue.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on January 15, 2016, 09:20:06 AM
it may have been one spot where the API author neglected to update from the older 1.1 API
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on January 15, 2016, 12:19:07 PM
Well I don't get it.

The API I downloaded from SMF website is 1.1. There is nothing more recent I think.

And the whole API 1.1 is with Camel case. So it fails at every hurdle of course.

Has nobody rewritten the API to make it work with Camel? It would be a shame to do it again, right?

Thanks.
Title: Re: New tools to help integrating SMF with something else
Post by: Illori on January 15, 2016, 12:22:29 PM
are you not using the attachments to the first post in this topic?
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on January 15, 2016, 12:40:09 PM
Congrats! You found the issue.

I can't believe it. I was downloading the API from the main SMF website. That was the most natural place for me to look for it: http://download.simplemachines.org/?tools

I certainly saw the mention of attachments but as I had already downloaded the latest file from the download/tools section...

So again two suggestions:

1) Edit the initial post (if possible) to make it more readable (I think the explanation of API vs Hook is very nice but lacks a "however" or in contrast in between. I would also use some bold characters to make sections clearer).

2) can someone tell the right person to upload the latest API file on the tools page? Or point me to that person?

Thanks again! You saved my day!
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on January 15, 2016, 01:19:24 PM
well, that post should actually be unstickied, since the content is more clearly listed in the wiki/manual now
http://wiki.simplemachines.org/smf/SMF_API

as for adding it to the tools...   since this API was not written by and is not supported by the SMF team - we can't very well have it on our tools menu.
I do understand your confusion though...
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on January 15, 2016, 01:37:09 PM
You are right. There is this wiki page too which is very similar to the post.

I don't understand the logics regarding the tools section. I very well understand if they don't support it, but then they should not show any (outdated) version then. If they don't want to add API 2.0 then at least they should get rid of the other ones too.

Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on January 15, 2016, 01:43:54 PM
Ah, but you see...  that is the problem when we support multiple versions of the software

the API v1.1 is for use with SMF 1.1.x

API v2.0 is for use with SMF 2.0.x

neither one will work with the other version...  there are several reasons... for one - the change from camelCase to underscore variable and database table names.

So, the 1.1 version is still useful for people who continue to use SMF v1.1.x (despite many warnings about it being at end of life)
once 1.1.x officially goes dead, the 1.1 API will be moved to the archive page
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on January 15, 2016, 02:12:11 PM
OK. I see. You are right.

Because of all my issues. I had figured out that the API number (version number) was not related to the SMF number (version number). It turned out to be wrong. API 1.1 is for SMF 1.1.

OK. Many thanks! Very much appreciated.
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on January 20, 2016, 04:48:14 PM
I am about to use the smfapi_updateMemberData() function but I am not sure about the comment saying that data must be html_special_chared...

Isn't it rather mysql_real_escape_string()? Because the data is going to be sent via SQL? Or am I missing something?



* Update member data
*
* Update member data such as 'passwd' (hash), 'email_address', 'is_activated'
* 'password_salt', 'member_name' or any other user info in the db
*
* @param  int $member member id (will also work with string username or email)
* @param  associative array $data the data to be updated (htmlspecialchar'd)
* @return bool whether update was successful or not
* @since  0.1.0
*/
function smfapi_updateMemberData($member='', $data='')
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on January 20, 2016, 05:37:04 PM
Well it seems that the info is stored htmlspecialchared in the database and no need to preformat the data when using the API update function...
Title: Re: New tools to help integrating SMF with something else
Post by: norristh on July 03, 2017, 04:02:16 PM
Since updating SMF to 2.0.14, at least two places I'm using the API no longer seem to work.  I haven't yet done thorough testing, or tried to debug exactly what's happening.  I assume the change in accessing MySQL has broken the API, but I don't know how badly, or how hard it'll be to fix...

Is anyone else experiencing problems?  Is there any discussion elsewhere that I missed in trying to search for solutions?

ETA: I'm using PHP7, which was a big motivation for upgrading SMF.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on July 03, 2017, 11:28:15 PM
I suspect that the API does not support php7
Title: Re: New tools to help integrating SMF with something else
Post by: MrManager on July 22, 2017, 11:55:37 AM
Is this still being maintained?

I just had a look through the source code and I think there may be a major bug in the smfapi_loadUserSettings() function. It seems to read the user ID and password from the SMF cookie (just like the normal loadUserSettings() from SMF) but it is missing the part where that password is actually checked! So I think it would be possible to impersonate any user, simply by editing the user ID in the cookie.

Or am I understanding something wrong here?
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on July 22, 2017, 05:46:58 PM
I do not believe that the password is stored in the cookie anyway...
Title: Re: New tools to help integrating SMF with something else
Post by: MrManager on July 22, 2017, 07:10:53 PM
I'm pretty sure it is!

Here are the lines from Load.php:

if (empty($id_member) && isset($_COOKIE[$cookiename]))
{
// Fix a security hole in PHP 4.3.9 and below...
if (preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~i', $_COOKIE[$cookiename]) == 1)
{
list ($id_member, $password) = safe_unserialize($_COOKIE[$cookiename]);
$id_member = !empty($id_member) && strlen($password) > 0 ? (int) $id_member : 0;
}
else
$id_member = 0;
}


And then later:

// As much as the password should be right, we can assume the integration set things up.
if (!empty($already_verified) && $already_verified === true)
$check = true;
// SHA-1 passwords should be 40 characters long.
elseif (strlen($password) == 40)
$check = sha1($user_settings['passwd'] . $user_settings['password_salt']) == $password;
else
$check = false;

// Wrong password or not activated - either way, you're going nowhere.
$id_member = $check && ($user_settings['is_activated'] == 1 || $user_settings['is_activated'] == 11) ? $user_settings['id_member'] : 0;
Title: Re: New tools to help integrating SMF with something else
Post by: refx on November 06, 2017, 06:04:40 AM
Quote from: nearlyepic on March 03, 2015, 11:04:11 PM
Hi, I seem to be having the same problem that BigOHenry was having. Even a simple bit of code, such as:
...


Notice: Undefined variable: cookieData in /var/www/smfapi/smf_2_api.php on line 1909


It appears that it only happens when I am logged out from SMF.

I don't know and don't have time to search the real cause of the problem, but I make the script silent by patching it:
(change the line 1909)

$success=false;
if (isset($cookieData)) $success = funserialize($cookieData, $unserializedData);

it works perfectly if a search engine comes and check your page without SMF login. No warnings produced anymore.
Title: Re: New tools to help integrating SMF with something else
Post by: pablitoclavito on November 23, 2017, 06:42:09 AM
Very good information, although I'm a bit confused with the code but I'll solve it, thank you very much. :)
Title: Re: New tools to help integrating SMF with something else
Post by: MamaTea on June 17, 2018, 10:28:28 PM
Hey there!  I have been through this entire topic and I have not seen anything on this-

I would just like to know if anyone has already made something which will show only the replies to a topic on a different page outside of the forum. (same domain)

I am pretty new to coding so learning and challenge is a good thing for me, it is time that's never on my side when it comes to teaching this stuff to myself.

I have the API text and have gone through about half of it.  It seems like what I want to do should be pretty simple- it is just that weeding through all of the information I do not need and applying what I do need in the right manner seems as though it will be time consuming.


That is why I am here.  ;D

Your code is certainly welcome.
If you haven't coded this already though have a helpful hint right at the edge of your sleeve, I would sure appreciate it!



Thanks!
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on June 18, 2018, 09:04:17 AM


hmmm.... to get the original post from a board with the number of replies listed, you can use SSI.

e.g.
ssi_boardNews($board = 5.0, $limit = 5, $start = null, $length = 250, $output_method = 'echo');
https://wiki.simplemachines.org/smf/SSI_FAQ_Advanced



However, I've never seen a request to just pull the replies to a thread for display...   so - no, afaik, it's never been specifically coded.
Title: Re: New tools to help integrating SMF with something else
Post by: MamaTea on June 18, 2018, 09:18:46 AM
Quote from: Kindred on June 18, 2018, 09:04:17 AM


hmmm.... to get the original post from a board with the number of replies listed, you can use SSI.

e.g.
ssi_boardNews($board = 5.0, $limit = 5, $start = null, $length = 250, $output_method = 'echo');
https://wiki.simplemachines.org/smf/SSI_FAQ_Advanced





However, I've never seen a request to just pull the replies to a thread for display...   so - no, afaik, it's never been specifically coded.




Thanks Kindred!

I was sort of thinking that might be the case.  I appreciate it.
Title: Re: New tools to help integrating SMF with something else
Post by: krator on April 19, 2020, 06:39:36 AM
Hello.

I'm using the file from first topic in order to connect two differents CMS (Smf 2.0.17 and another soft), but i can't do it.  I'm testing and i think that the problem is in the smfapi_loadUserSettings() function, too (How MrManager said). The problem look that it's because cookie and session global variables is loaded with my another CMS, and not with SMF, so that the information it's not reached.

So, Could anyone use this api to connect to another CMS (login/logout...)?
Title: Re: New tools to help integrating SMF with something else
Post by: vbgamer45 on April 19, 2020, 02:13:47 PM
Made a change see if it helps for 2.0.17 with the smfapi_login

Removed attachment see below for newest one.
Title: Re: New tools to help integrating SMF with something else
Post by: krator on April 20, 2020, 06:32:06 AM
Great, thanks vbgamer45!

I'm testing again. I'm not sure if I'm doing this process correctly. This is my step-to-step:
1. Login in my external system. If it's success, call to the function (example):
smfapi_login('krator')

I have been "debugging" the function:

function smfapi_login($username='', $cookieLength=525600)
{
...

    smfapi_loadUserSettings();

return true;
}

All look successful, i can see the cookie of SMF in $_COOKIE and $user_info is loaded with my data.

2. Load the page of smf (like: http://localhost:8080/smf2017/index.php).

But, I'm not login in SMF.

Am I skipping a step? (call another function more, or similar)

Edit:
Test 1.
1. Login in my external system in Firefox. (smfapi_login launched)
2. Load SMF index webpage in Chrome. I can see to "krator" how user online
3. Logout in my external system in Firefox. (smfapi_logout launched)
4. Load SMF index webpage in Chrome. I cant see to "krator" how user online

Test 2.
1. Login in my external system in Firefox. (smfapi_login launched)
2. Load SMF index webpage in Chrome. I can see to "krator" how user online
3. Load SMF index webpage in Firefox. I can see to "krator" how user online, BUT, I'm not loggin in SMF!
Title: Re: New tools to help integrating SMF with something else
Post by: vbgamer45 on April 20, 2020, 09:31:36 AM
I still can't get it to login on my side...
But, I have updated it so it should have the right hash in the cookie now...and made a minor session change...
Title: Re: New tools to help integrating SMF with something else
Post by: krator on April 23, 2020, 01:00:12 PM
Ey, thanks.
I have try with the new file, but similar results. Have you made any progress?

Thanks.
Title: Re: New tools to help integrating SMF with something else
Post by: vbgamer45 on April 23, 2020, 04:13:05 PM
No, I haven't sorry I spent a few hours on it. Not sure what else to check for.
I comparing the password set in the cookies in normal SMF and though the API both are the same...
I tried comparing both functions
Title: Re: New tools to help integrating SMF with something else
Post by: phydaux on June 12, 2020, 05:56:25 PM
Well, I have just tried your updated smf_2_api.php file, and it worked for me!  Thank you very much for that.
My setup is 2.0.14 with the patches to bring it up to 2.0.17.  I have just tried the original api file, and was getting the same results you described.  I could see the cookie being created, but it seemed to be removed as soon as I went to the SMF site.  Switching to your modified api results in a persistent login.
Title: Re: New tools to help integrating SMF with something else
Post by: krator on July 22, 2020, 02:35:06 AM
Could you say me how you have setting the cookies?

Im trying in my localhost with:
Enable local storage of cookies = FALSE
Use subdomain independent cookies = TRUE
Use database driven sessions = TRUE
Allow browsers to go back to cached pages = TRUE
Title: Re: New tools to help integrating SMF with something else
Post by: Nic_G on December 15, 2021, 06:49:09 AM
I am looking for the latest version of SMF_2_API.php but all links seem to be gone.

Any idea where it is?

Thanks!

Nic.
Title: Re: New tools to help integrating SMF with something else
Post by: Kindred on December 15, 2021, 11:41:50 AM
There is no modern version, unfortunately