-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmf_2_api.php
More file actions
3330 lines (2885 loc) · 104 KB
/
smf_2_api.php
File metadata and controls
3330 lines (2885 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Simple Machines Forum(SMF) API for SMF 2.0
*
* Use this to integrate your SMF version 2.0 forum with 3rd party software
* If you need help using this script or integrating your forum with other
* software, feel free to contact andre@r2bconcepts.com
*
* @package SMF 2.0 API
* @author Simple Machines http://www.simplemachines.org
* @author Andre Nickatina <andre@r2bconcepts.com>
* @copyright 2011 Simple Machines
* @link http://www.simplemachines.org Simple Machines
* @link http://www.r2bconcepts.com Red2Black Concepts
* @license http://www.simplemachines.org/about/smf/license.php BSD
* @version 0.1.2
*
* NOTICE OF LICENSE
***********************************************************************************
* This file, and ONLY this file is released under the terms of the BSD License. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* Redistributions in binary form must reproduce the above copyright notice, this *
* list of conditions and the following disclaimer in the documentation and/or *
* other materials provided with the distribution. *
* Neither the name of Simple Machines LLC nor the names of its contributors may *
* be used to endorse or promote products derived from this software without *
* specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE *
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE *
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) *
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT *
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT *
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
**********************************************************************************/
/*
This file includes functions that may help integration with other scripts
and programs, such as portals. It is independent of SMF, and meant to run
without disturbing your script. It defines several functions, most of
which start with the smfapi_ prefix. These are:
array 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
---------------------------------------------------------------------------
It also defines the following important variables:
$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] =>
)
$modSettings => Array
(
[smfVersion] =>
[news] =>
[compactTopicPagesContiguous] =>
[compactTopicPagesEnable] =>
[enableStickyTopics] =>
[todayMod] =>
[karmaMode] =>
[karmaTimeRestrictAdmins] =>
[enablePreviousNext] =>
[pollMode] =>
[enableVBStyleLogin] =>
[enableCompressedOutput] =>
[karmaWaitTime] =>
[karmaMinPosts] =>
[karmaLabel] =>
[karmaSmiteLabel] =>
[karmaApplaudLabel] =>
[attachmentSizeLimit] =>
[attachmentPostLimit] =>
[attachmentNumPerPostLimit] =>
[attachmentDirSizeLimit] =>
[attachmentUploadDir] =>
[attachmentExtensions] =>
[attachmentCheckExtensions] =>
[attachmentShowImages] =>
[attachmentEnable] =>
[attachmentEncryptFilenames] =>
[attachmentThumbnails] =>
[attachmentThumbWidth] =>
[attachmentThumbHeight] =>
[censorIgnoreCase] =>
[mostOnline] =>
[mostOnlineToday] =>
[mostDate] =>
[allow_disableAnnounce] =>
[trackStats] =>
[userLanguage] =>
[titlesEnable] =>
[topicSummaryPosts] =>
[enableErrorLogging] =>
[max_image_width] =>
[max_image_height] =>
[onlineEnable] =>
[cal_enabled] =>
[cal_maxyear] =>
[cal_minyear] =>
[cal_daysaslink] =>
[cal_defaultboard] =>
[cal_showholidays] =>
[cal_showbdays] =>
[cal_showevents] =>
[cal_showweeknum] =>
[cal_maxspan] =>
[smtp_host] =>
[smtp_port] =>
[smtp_username] =>
[smtp_password] =>
[mail_type] =>
[timeLoadPageEnable] =>
[totalMembers] =>
[totalTopics] =>
[totalMessages] =>
[simpleSearch] =>
[censor_vulgar] =>
[censor_proper] =>
[enablePostHTML] =>
[theme_allow] =>
[theme_default] =>
[theme_guests] =>
[enableEmbeddedFlash] =>
[xmlnews_enable] =>
[xmlnews_maxlen] =>
[hotTopicPosts] =>
[hotTopicVeryPosts] =>
[registration_method] =>
[send_validation_onChange] =>
[send_welcomeEmail] =>
[allow_editDisplayName] =>
[allow_hideOnline] =>
[guest_hideContacts] =>
[spamWaitTime] =>
[pm_spam_settings] =>
[reserveWord] =>
[reserveCase] =>
[reserveUser] =>
[reserveName] =>
[reserveNames] =>
[autoLinkUrls] =>
[banLastUpdated] =>
[smileys_dir] =>
[smileys_url] =>
[avatar_directory] =>
[avatar_url] =>
[avatar_max_height_external] =>
[avatar_max_width_external] =>
[avatar_action_too_large] =>
[avatar_max_height_upload] =>
[avatar_max_width_upload] =>
[avatar_resize_upload] =>
[avatar_download_png] =>
[failed_login_threshold] =>
[oldTopicDays] =>
[edit_wait_time] =>
[edit_disable_time] =>
[autoFixDatabase] =>
[allow_guestAccess] =>
[time_format] =>
[number_format] =>
[enableBBC] =>
[max_messageLength] =>
[signature_settings] =>
[autoOptMaxOnline] =>
[defaultMaxMessages] =>
[defaultMaxTopics] =>
[defaultMaxMembers] =>
[enableParticipation] =>
[recycle_enable] =>
[recycle_board] =>
[maxMsgID] =>
[enableAllMessages] =>
[fixLongWords] =>
[knownThemes] =>
[who_enabled] =>
[time_offset] =>
[cookieTime] =>
[lastActive] =>
[smiley_sets_known] =>
[smiley_sets_names] =>
[smiley_sets_default] =>
[cal_days_for_index] =>
[requireAgreement] =>
[unapprovedMembers] =>
[default_personal_text] =>
[package_make_backups] =>
[databaseSession_enable] =>
[databaseSession_loose] =>
[databaseSession_lifetime] =>
[search_cache_size] =>
[search_results_per_page] =>
[search_weight_frequency] =>
[search_weight_age] =>
[search_weight_length] =>
[search_weight_subject] =>
[search_weight_first_message] =>
[search_max_results] =>
[search_floodcontrol_time] =>
[permission_enable_deny] =>
[permission_enable_postgroups] =>
[mail_next_send] =>
[mail_recent] =>
[settings_updated] =>
[next_task_time] =>
[warning_settings] =>
[warning_watch] =>
[warning_moderate] =>
[warning_mute] =>
[admin_features] =>
[last_mod_report_action] =>
[pruningOptions] =>
[cache_enable] =>
[reg_verification] =>
[visual_verification_type] =>
[enable_buddylist] =>
[birthday_email] =>
[dont_repeat_theme_core] =>
[dont_repeat_smileys_20] =>
[dont_repeat_buddylists] =>
[attachment_image_reencode] =>
[attachment_image_paranoid] =>
[attachment_thumb_png] =>
[avatar_reencode] =>
[avatar_paranoid] =>
[global_character_set] =>
[localCookies] =>
[default_timezone] =>
[memberlist_updated] =>
[latestMember] =>
[latestRealName] =>
[rand_seed] =>
[mostOnlineUpdated] =>
)
$user_info => Array
(
[groups] => Array
(
[0] =>
[1] =>
)
[possibly_robot] =>
[id] =>
[username] =>
[name] =>
[email] =>
[passwd] =>
[language] =>
[is_guest] =>
[is_admin] =>
[theme] =>
[last_login] =>
[ip] =>
[ip2] =>
[posts] =>
[time_format] =>
[time_offset] =>
[avatar] => Array
(
[url] =>
[filename] =>
[custom_dir] =>
[id_attach] =>
)
[smiley_set] =>
[messages] =>
[unread_messages] =>
[total_time_logged_in] =>
[buddies] => Array
(
)
[ignoreboards] => Array
(
)
[ignoreusers] => Array
(
)
[warning] =>
[permissions] => Array
(
)
)
For even *more* member data use the function smfapi_getUserData()
It will return an array with the following:
$userdata => Array
(
[id_member] =>
[member_name] =>
[date_registered] =>
[posts] =>
[id_group] =>
[lngfile] =>
[last_login] =>
[real_name] =>
[instant_messages] =>
[unread_messages] =>
[new_pm] =>
[buddy_list] =>
[pm_ignore_list] =>
[pm_prefs] =>
[mod_prefs] =>
[message_labels] =>
[passwd] =>
[openid_uri] =>
[email_address] =>
[personal_text] =>
[gender] =>
[birthdate] =>
[website_title] =>
[website_url] =>
[location] =>
[icq] =>
[aim] =>
[yim] =>
[msn] =>
[hide_email] =>
[show_online] =>
[time_format] =>
[signature] =>
[time_offset] =>
[avatar] =>
[pm_email_notify] =>
[karma_bad] =>
[karma_good] =>
[usertitle] =>
[notify_announcements] =>
[notify_regularity] =>
[notify_send_body] =>
[notify_types] =>
[member_ip] =>
[member_ip2] =>
[secret_question] =>
[secret_answer] =>
[id_theme] =>
[is_activated] =>
[validation_code] =>
[id_msg_last_visit] =>
[additional_groups] =>
[smiley_set] =>
[id_post_group] =>
[total_time_logged_in] =>
[password_salt] =>
[ignore_boards] =>
[warning] =>
[passwd_flood] =>
[pm_receive_from] =>
)
*/
// don't do anything if SMF is already loaded
if (defined('SMF'))
return true;
define('SMF', 'API');
// we're going to want a few globals... these are all set later
// set from this script
global $time_start, $scripturl, $context, $settings_path;
// set from Settings.php
global $maintenance, $mtitle, $mmessage, $mbname, $language, $boardurl;
global $webmaster_email, $cookiename, $db_type, $db_server, $db_name, $db_user;
global $db_passwd, $db_prefix, $db_persist, $db_error_send, $boarddir, $sourcedir;
global $cachedir, $db_last_error, $db_character_set;
// set from smfapi_loadDatabase()
global $db_connection, $smcFunc;
// set from smfapi_reloadSettings()
global $modSettings;
// set from smfapi_loadSession()
global $sc;
// set from smfapi_loadUserSettings()
global $user_info;
// turn off magic quotes
if (function_exists('set_magic_quotes_runtime')) {
// remember the current configuration so it can be set back
$api_magic_quotes_runtime = function_exists('get_magic_quotes_gpc') && get_magic_quotes_runtime();
@set_magic_quotes_runtime(0);
}
$time_start = microtime();
// Without visiting the forum this session variable might not be set on submit.
if (!isset($_SESSION['USER_AGENT'])) {
$_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
}
// just being safe...
foreach (array('db_character_set', 'cachedir') as $variable) {
if (isset($GLOBALS[$variable])) {
unset($GLOBALS[$variable]);
}
}
// if we have a saved settings location, try to load it first
$saveFile = dirname(__FILE__) . '/smfapi_settings.txt';
$settings_path = '';
if (file_exists($saveFile)) {
$settings_path = base64_decode(file_get_contents($saveFile));
// if it's fouled delete it
if (!file_exists($settings_path)) {
unlink($saveFile);
unset($settings_path);
}
}
// manually add the location of your Settings.php here
if (!isset($settings_path) || empty($settings_path)) {
// 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
if (isset($settings_path) && !file_exists($settings_path)) {
unset($settings_path);
}
}
// check locally
if ((!isset($settings_path) || empty($settings_path)) && file_exists(dirname(__FILE__) . '/Settings.php')) {
$settings_path = dirname(__FILE__) . '/Settings.php';
}
// try to find it
if (!isset($settings_path) || empty($settings_path)) {
$directory = $_SERVER['DOCUMENT_ROOT'] . '/';
$exempt = array('.', '..');
$files = smfapi_getDirectoryContents($directory, $exempt);
$matches = smfapi_getMatchingFile($files, '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)) {
$settings_path = $matches[0];
} elseif (1 < count($matches)) {
$matches = smfapi_getMatchingFile($files, 'Settings_bak.php');
$matches[0] = str_replace('_bak.php', '.php', $matches[0]);
$settings_path = $matches[0];
} else {
exit('Unable to load SMF settings file');
}
}
// include the settings file
require_once($settings_path);
// save the settings file for future reference
if (!file_exists($saveFile)) {
file_put_contents($saveFile, base64_encode($settings_path));
}
$scripturl = $boardurl . '/index.php';
// make absolutely sure the cache directory is defined
if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache')) {
$cachedir = $boarddir . '/cache';
}
// don't do john didley if the forum's been shut down competely
if (2 == $maintenance) {
return;
}
// fix for using the current directory as a path
if (substr($sourcedir, 0, 1) == '.' && substr($sourcedir, 1, 1) != '.') {
$sourcedir = dirname(__FILE__) . substr($sourcedir, 1);
}
// using a pre 5.1 php version?
if (-1 == @version_compare(PHP_VERSION, '5.1')) {
//safe to include, will check if functions exist before declaring
require_once($sourcedir . '/Subs-Compat.php');
}
// create a variable to store some SMF specific functions in
$smcFunc = array();
// we won't put anything in this
$context = array();
// initate the database connection and define some database functions to use
smfapi_loadDatabase();
// load settings
smfapi_reloadSettings();
// create random seed if it's not already created
if (empty($modSettings['rand_seed']) || mt_rand(1, 250) == 69) {
smfapi_smfSeedGenerator();
}
// start the session if there isn't one already...
smfapi_loadSession();
// load the user and their cookie, as well as their settings.
smfapi_loadUserSettings();
/**
* Gets the user's info from their email address
*
* Will take the users email address and return an array containing all the
* user's information in the db. Will return false on failure
*
* @param string $email the user's email address
* @return array $results containing the user info || bool false
* @since 0.1.0
*/
function smfapi_getUserByEmail($email='')
{
global $smcFunc;
if ('' == $email || !is_string($email) || 2 > count(explode('@', $email))) {
return false;
}
$request = $smcFunc['db_query']('', '
SELECT *
FROM {db_prefix}members
WHERE email_address = {string:email_address}
LIMIT 1',
array(
'email_address' => $email,
)
);
$results = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
if (empty($results)) {
return false;
} else {
// return all the results.
return $results;
}
}
/**
* Gets the user's info from their member id
*
* Will take the users member id and return an array containing all the
* user's information in the db. Will return false on failure
*
* @param int $id the user's member id
* @return array $results containing the user info || bool false
* @since 0.1.2
*/
function smfapi_getUserById($id='')
{
global $smcFunc;
if ('' == $id || !is_numeric($id)) {
return false;
} else{
$id = intval($id);
if (0 == $id) {
return false;
}
}
$request = $smcFunc['db_query']('', '
SELECT *
FROM {db_prefix}members
WHERE id_member = {int:id_member}
LIMIT 1',
array(
'id_member' => $id,
)
);
$results = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
if (empty($results)) {
return false;
} else {
// return all the results.
return $results;
}
}
/**
* Gets the user's info from their member name (username)
*
* Will take the users member name and return an array containing all the
* user's information in the db. Will return false on failure
*
* @param string $username the user's member name
* @return array $results containing the user info || bool false
* @since 0.1.0
*/
function smfapi_getUserByUsername($username='')
{
global $smcFunc;
if ('' == $username || !is_string($username)) {
return false;
}
$request = $smcFunc['db_query']('', '
SELECT *
FROM {db_prefix}members
WHERE member_name = {string:member_name}
LIMIT 1',
array(
'member_name' => $username,
)
);
$results = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
if (empty($results)) {
return false;
} else {
// return all the results.
return $results;
}
}
/**
* Gets the user's info
*
* Will take the users email, username or member id and return their data
*
* @param int || string $username the user's email address username or member id
* @return array $results containing the user info || bool false
* @since 0.1.2
*/
function smfapi_getUserData($username='')
{
if ('' == $username) {
return false;
}
$user_data = array();
// we'll try id || email, then username
if (is_numeric($username)) {
// number is most likely a member id
$user_data = smfapi_getUserById($username);
} else {
// the email can't be purely numeric
$user_data = smfapi_getUserByEmail($username);
}
if (empty($user_data)) {
$user_data = smfapi_getUserByUsername($username);
}
if (empty($user_data)) {
return false;
} else {
return $user_data;
}
}
/**
* Logs the user in by setting the session cookie
*
* Be sure you've already authenticated the username/password
* using smfapi_authenticate() or some other means because
* this function WILL set the correct session cookie for the
* user you specify and they WILL be logged in
*
* @param string $username (or int member id or string email. We're not picky)
* @param int $cookieLength length to set the cookie for (in minutes)
* @return bool whether the login cookie was set or not
* @since 0.1.2
*/
function smfapi_login($username='', $cookieLength=525600)
{
global $scripturl, $user_info, $user_settings, $smcFunc;
global $cookiename, $maintenance, $modSettings, $sc, $sourcedir;
$user_data = smfapi_getUserData($username);
if (!$user_data || empty($user_data)) {
return false;
}
$password = sha1($user_data['passwd'] . $user_data['password_salt']);
// cookie set, session too
smfapi_setLoginCookie(60 * $cookieLength, $user_data['id_member'], $password);
// you've logged in, haven't you?
smfapi_updateMemberData($user_data['id_member'], array('last_login' => time(), 'member_ip' => $user_info['ip']));
// get rid of the online entry for that old guest....
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}log_online
WHERE session = {string:session}',
array(
'session' => 'ip' . $user_info['ip'],
)
);
smfapi_loadUserSettings();
return true;
}
/**
* Will authenticate the username/password combo
*
* Use this before setting the cookie to check if the username password are correct.
*
* @param mixed $username the user's member name, email or member id
* @param string $password the password plaintext or encrypted in any of several
* methods including smf's method: sha1(strtolower($username) . $password)
* @param bool $encrypted whether the password is encrypted or not. If you get
this wrong we'll figure it out anyways, just saves some work if it's right
* @return bool whether the user is authenticated or not
* @since 0.1.2
*/
function smfapi_authenticate($username='', $password='', $encrypted=true)
{
global $scripturl, $user_info, $user_settings, $smcFunc;
global $cookiename, $modSettings, $sc, $sourcedir;
if ('' == $username || '' == $password) {
return false;
}
// just in case they used the email or member id...
$data = smfapi_getUserData($username);
if (empty($data)) {
return false;
} else {
$username = $data['member_name'];
}
// load the data up!
$request = $smcFunc['db_query']('', '
SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt,
openid_uri, passwd_flood
FROM {db_prefix}members
WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name) = LOWER({string:user_name})' : 'member_name = {string:user_name}') . '
LIMIT 1',
array(
'user_name' => $smcFunc['db_case_sensitive'] ? strtolower($username) : $username,
)
);
// no user data found... invalid username
if ($smcFunc['db_num_rows']($request) == 0) {
return false;
}
$user_settings = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
if (40 != strlen($user_settings['passwd'])) {
// invalid hash in the db
return false;
}
// if it's not encrypted, do it now
if (!$encrypted) {
$sha_passwd = sha1(strtolower($user_settings['member_name'])
. smfapi_unHtmlspecialchars($password));
} else {
$sha_passwd = $password;
}
// if they match the password/hash is correct
if ($user_settings['passwd'] == $sha_passwd) {
return true;
} else {
// try other hashing schemes
$other_passwords = array();
// in case they sent the encrypted password into this as unencrypted
$other_passwords[] = $password;
// none of the below cases will be used most of the time
// (because the salt is normally set)
if ('' == $user_settings['password_salt']) {
// YaBB SE, Discus, MD5 (used a lot), SHA-1 (used some), SMF 1.0.x,
// IkonBoard, and none at all
$other_passwords[] = crypt($password, substr($password, 0, 2));
$other_passwords[] = crypt($password, substr($user_settings['passwd'], 0, 2));
$other_passwords[] = md5($password);
$other_passwords[] = sha1($password);
$other_passwords[] = md5_hmac($password, strtolower($user_settings['member_name']));
$other_passwords[] = md5($password . strtolower($user_settings['member_name']));
$other_passwords[] = md5(md5($password));
$other_passwords[] = $password;
// this one is a strange one... MyPHP, crypt() on the MD5 hash
$other_passwords[] = crypt(md5($password), md5($password));
// Snitz style - SHA-256. Technically, this is a downgrade, but most PHP
// configurations don't support sha256 anyway.
if (strlen($user_settings['passwd']) == 64
&& function_exists('mhash') && defined('MHASH_SHA256')) {
$other_passwords[] = bin2hex(mhash(MHASH_SHA256, $password));
}
// phpBB3 users new hashing. We now support it as well ;)
$other_passwords[] = phpBB3_password_check($password, $user_settings['passwd']);
// APBoard 2 login method
$other_passwords[] = md5(crypt($password, 'CRYPT_MD5'));
}
// the hash should be 40 if it's SHA-1, so we're safe with more here too
elseif (strlen($user_settings['passwd']) == 32) {
// vBulletin 3 style hashing? Let's welcome them with open arms \o/
$other_passwords[] = md5(md5($password) . $user_settings['password_salt']);
// hmm.. p'raps it's Invision 2 style?
$other_passwords[] = md5(md5($user_settings['password_salt'])
. md5($password));
// some common md5 ones
$other_passwords[] = md5($user_settings['password_salt'] . $password);
$other_passwords[] = md5($password . $user_settings['password_salt']);
} elseif (strlen($user_settings['passwd']) == 40) {
// maybe they are using a hash from before the password fix
$other_passwords[] = sha1(strtolower($user_settings['member_name'])
. smfapi_unHtmlspecialchars($password));