• Welcome to Simple Machines Community Forum. Please login or sign up.
September 27, 2021, 05:26:05 PM

News:

Bored?  Looking to kill some time?  Want to chat with other SMF users?  Join us in IRC chat or Discord


smf 2.0 api

Started by Andre N, June 30, 2011, 01:43:51 PM

Previous topic - Next topic

Andre N

June 30, 2011, 01:43:51 PM Last Edit: March 06, 2012, 12:01:45 PM by andre nickatina
I'm writing an api for 2.0, because I can't find one anywhere. It doesn't seem too difficult; I basically took the SSI and stripped out the functions to write my own. Besides the obvious ones (login, logout, register, and the others from the 1.x api) what functions would be nice to have?

Done. See below post for more info.

Edit: Attachment removed
DOWNLOAD THE NEWEST VERSION FROM THIS THREAD :)
http://www.simplemachines.org/community/index.php?topic=453008.0
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

Andre N

July 08, 2011, 05:17:57 PM #1 Last Edit: March 06, 2012, 12:00:23 PM by andre nickatina
Here it is. I've tested (briefly) all the functions and they work. Questions, comments, suggestions? Let me know.

How to use:
Put it on the same server your SMF forum is installed and use require_once to include it like:

require_once($_SERVER['DOCUMENT_ROOT'] . '/your/path/to/this/file/smf_2_api.php');


Then you can use the functions  :)

Here is the function list:
Quotearray  smfapi_getUserByEmail(string $email)
        - returns all user info from the db in an array

    array  smfapi_getUserById(int $id)
        - returns all user info from the db in an array

    array  smfapi_getUserByUsername(string $username)
        - returns all user info from the db in an array

    array  smfapi_getUserData(mixed $identifier)
        - returns all user info from the db in an array
        - will accept email address, username or member id

    bool   smfapi_login(mixed $identifier, int $cookieLength)
        - sets cookie and session for user specified
        - will accept email address, username or member id
        - does no authentication; do that before calling this

    bool   smfapi_authenticate(mixed $username, string $password, bool $encrypted)
        - authenticates a username/password combo
        - will accept email address, username or member id

    bool   smfapi_logout(string $username)
        - logs the specified user out
        - will accept email address, username or member id

    bool   smfapi_deleteMembers(int || int array $users)
        - deletes member(s) by their int member id
        - will return true unless $users empty
        - will accept email address, username or member id or a mixed array

    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'

    bool   smfapi_logError(string $error_message, string $error_type, string $file, int $line)
        - logs an error message to the smf error log
        - $error_type will be one of the following: 'general', 'critical', 'database', 'undefined_vars', 'user', 'template' or 'debug'
        - just use __FILE__ and __LINE__ as $file and $line unless you have other ambitions

    true   smfapi_reloadSettings()
        - loads the $modSettings array
        - adds the following functions to the $smcFunc array:
             'entity_fix', 'htmlspecialchars', 'htmltrim', 'strlen', 'strpos', 'substr', 'strtolower', strtoupper', 'truncate', 'ucfirst' and 'ucwords'

    true   smfapi_loadUserSettings(mixed $identifier)
        - loads the $user_info array for user or guest
        - will accept email address, username or member id
        - if member data not found, will try cookie then session

    true   smfapi_loadSession()
        - starts the session

    *Session functions*
    true   smfapi_sessionOpen()
    true   smfapi_sessionClose()
    bool   smfapi_sessionRead()
    bool   smfapi_sessionWrite()
    bool   smfapi_sessionDestroy()
    mixed  smfapi_sessionGC()

    bool   smfapi_loadDatabase()
        - loads the db connection
        - adds the following fuctions to the $smcFunc array:
            'db_query', 'db_quote', 'db_fetch_assoc', 'db_fetch_row', 'db_free_result', 'db_insert', 'db_insert_id', 'db_num_rows',
            'db_data_seek', 'db_num_fields', 'db_escape_string', 'db_unescape_string', 'db_server_info', 'db_affected_rows',
            'db_transaction', 'db_error', 'db_select_db', 'db_title', 'db_sybase', 'db_case_sensitive' and 'db_escape_wildcard_string'

    void   smfapi_cachePutData(string $key, mixed $value, int $ttl)
        - puts data in the cache

    mixed  smfapi_cacheGetData(string $key, int $ttl)
        - gets data from the cache

    bool   smfapi_updateMemberData(mixed $member, array $data)
        - change member data (email, password, name, etc.)
        - will accept email address, username or member id
        - data will be an associative array ('email_address' => 'newemail@address.com') etc.

    true   smfapi_smfSeedGenerator()
        - generates random seed

    bool   smfapi_updateSettings(array $changeArray, bool $update)
        - updates settings in $modSettings array and puts them in db
        - called from smfapi_updateStats(), smfapi_deleteMessages() and smfapi_smfSeedGenerator()

    true   smfapi_setLoginCookie(int $cookie_length, int $id, string $password)
        - called by smfapi_login() to set the cookie

    array  smfapi_urlParts(bool $local, bool $global)
        - called by smfapi_setLoginCookie() to parse the url

    bool   smfapi_updateStats(string $type, int $parameter1, string $parameter2)
        - update forum member stats
        - called when registering or deleting a member

    string smfapi_unHtmlspecialchars(string $string)
        - fixes strings with special characters
        - called when encrypting the password for checking

    bool   smfapi_deleteMessages(array $personal_messages, string $folder, int || array $owner)
        - called by smfapi_deleteMembers()

    string smfapi_generateValidationCode()
        - used to generate a 10 char alpha validation code during registration

    bool   smfapi_isOnline(mixed $username)
        - check if a user is online
        - will accept email address, username or member id

    bool   smfapi_logOnline(mixed $username)
        - log a user online

    array  smfapi_getMatchingFile(array $files, string $search)
        - find a file from an array
        - used to find Settings.php in case this script is not with it

    array  smfapi_getDirectoryContents(string $directory, array $exempt, array $files)
        - gets the contents of a directory and all subdirectories
        - called by smfapi_getMatchingFile

Edit: attachment removed
DOWNLOAD THE NEWEST VERSION FROM THIS THREAD :)
http://www.simplemachines.org/community/index.php?topic=453008.0
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

sgad

Thanks for doing this, it looks really useful, but I am getting an error:

Notice: Undefined index: BAN_CHECK_IP in C:\wamp\www\forum\smf_2_api.php on line 1959

It's smfapi_loadUserSettings that's the problem. I'm not even calling any functions at the moment, just using require_once on the file. Any ideas what the problem is?

Andre N

It loaded your settings and ip2 isn't defined for your account.

Just change this line:
'ip2' => $_SERVER['BAN_CHECK_IP'],
to this:
'ip2' => isset($_SERVER['BAN_CHECK_IP'])?$_SERVER['BAN_CHECK_IP']:'',

and it will check if it is defined first :)

"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

sgad

That works perfectly, thank you!

lor300

July 13, 2011, 02:24:41 PM #5 Last Edit: July 13, 2011, 02:31:09 PM by lor300
It's really wanted tool.

Thanks, so much.

mgale

Thanks for this - it is EXACTLY what I needed (and really, really, really didn't want to have to write)!!!

Well done.

fastpay

Thanks. You have done the big work.

Lox

SSI is not working for me.  How would I use this API to replicate the ssi_login() feature (authenticate if the user is logged on, if not, display login and etc.)

Also, do we have to install this as the same directory as SMF or just the same server?

Andre N

Same server is fine.

require_once the api file. The first time you load it, it will find the path to your forum and save the path in a settings file, so the first load might take a few seconds.

you authenticate with something like:

$authenicated = smfapi_authenticate($username, $password);


Or you can authenticate the user in your other system if that is easier for you.

You log them in like this:

smfapi_login($identifier)

Where identifier can be their email address, username or member id. As long as the user exists, they will be logged in

:)
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

fastpay

 smfapi_logout(string $username) - is not working for me.

Andre N

Hi,
what path are you calling it from and what path are your smf cookies set for?
Your smf cookie path needs to be '/'
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

fastpay

August 04, 2011, 10:54:27 AM #12 Last Edit: August 04, 2011, 11:03:47 AM by fastpay
include('/home/host1212596/site/htdocs/www/forum/api.php');

$name = 2;
$logout = smfapi_logout($name);
var_dump($logout);


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


       print_r($user_info);
}


return array

Array ( [groups] => Array ( [0] => -1 ) [possibly_robot] => [id] => 0 [username] => [name] => [email] => [passwd] => [language] => russian [is_guest] => 1 [is_admin] => [theme] => 0 [last_login] => 0 [ip] => 178.120.45.90 [ip2] => [posts] => 0 [time_format] => %B %d, %Y, %H:%M:%S [time_offset] => 0 [avatar] => Array ( [url] => [filename] => [custom_dir] => [id_attach] => 0 ) [smiley_set] => [messages] => 0 [unread_messages] => 0 [total_time_logged_in] => 0 [buddies] => Array ( ) [ignoreboards] => Array ( ) [ignoreusers] => Array ( ) [warning] => 0 [permissions] => Array ( ) ) NULL

But at a forum I am authorized.

Way to a site /home/host1212596/site/htdocs/www/
Way to a forum /home/host1212596/site/htdocs/www/forum/

cookie path '/'

Help!

Andre N

The problem is most likely your cookie not being unset by the api logout call. Why is not being unset? Because it's probably not being found by the script.

Go to you forum, where you are still logged in, and open firecookie and check the path of you smf cookie. If your cookie is being set on /site/forum/ and your script is not on that path it won't find your cookie, it won't be able to unset your cookie, and the session will persist.

When you execute the script that makes the api call, use firecookie to check if you can see your smf cookie, you should be able to.

In SMF admin settings there is an option for sessions and cookies to 'use subdomain independent cookies'. Also make sure the option to 'store cookies locally' isn't selected. Delete the cookie manually and login again and check it. Make sure the path is right :)

The session is stored in the db too, but if the api had trouble connecting with your db, chances are good your forum would too, so you gotta check your cookie and make the path correct and I think you will be happy. Let me know otherwise ;)
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

fastpay

August 04, 2011, 11:16:43 AM #14 Last Edit: August 04, 2011, 11:24:44 AM by fastpay


My Cookie after relog. All is OK.

Option to 'store cookies locally' isn't selected


_http://scrap.by/forum/info.php - function not working.

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


info.php
<?php
   
include('/home/host1212596/site/htdocs/www/forum/md5apis.php');
      
$name 2;
      
smfapi_logout($name);
?>

Andre N

is there a session already started before you call the api?
when you call the logout are you specifying the username to logout?

edit: also, is the function returning true or false?
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

Andre N

what do you get when you do:

echo $_COOKIE[$cookiename];

?
If your script can see the cookie, try this:

list ($id_member, $hash) = @unserialize($_COOKIE[$cookiename]);
smfapi_logout($id_member);
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

fastpay

Quote from: ike turner on August 04, 2011, 01:08:03 PM
what do you get when you do:

echo $_COOKIE[$cookiename];

?
If your script can see the cookie, try this:

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


There's one interesting issue might be to give access to try? I am familiar with PHP for over 2 years. But that's not dancing with a tambourine ... help me with this problem.
echo $_COOKIE[$cookiename]; it work.

Return serialize string
a:4:{i:0;s:1:\"1\";i:1;s:40:\"8f25b79eff6d984c2f657326fd3984ee2938c80f\";i:2;i:1501702094;i:3;i:2;}

list ($id_member, $hash) = @unserialize($_COOKIE[$cookiename]); Not Working! hell hell hell

echo $id_member or echo $hash - Neither give nor any of the results! HELL HELL HELL

Andre N

if you have the data from the cookie you should be able to unserialize it :)
what version of php are you using?
try smfapi_logout(1);
and see if it logs you out. If that works you just need to figure out why you can't unserialize the cookie data
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

fastpay

Quote from: ike turner on August 04, 2011, 06:23:19 PM
if you have the data from the cookie you should be able to unserialize it :)
what version of php are you using?
try smfapi_logout(1);
and see if it logs you out. If that works you just need to figure out why you can't unserialize the cookie data

If i do list ($id_member, $hash) = @unserialize($_COOKIE[$cookiename]); in file index.template.php it is WORKS.

In a array brought id & hash.

If i do list in new file (info.php)
<?php

require_once('md5apis.php');


list (
$id_member$hash) = unserialize($_COOKIE[SMFCookie11]);
echo 
$id_member;

?>


Not WORK!

I do not know even already what to do

Advertisement: