PluginProbe
JSON API User / trunk
JSON API User vtrunk
4.1.4 3.9.8 3.9.9 4.0.0 4.1.0 4.1.2 4.1.3 2.8 2.9 2.9.1 3.0.0 3.1.4 3.2.0 3.3.0 3.4.0 3.5.0 3.6.0 3.7.0 3.8.0 3.8.1 3.9.0 3.9.1 3.9.2 3.9.3 3.9.4 All 52 releases
json-api-user / controllers / User.php

User.php in JSON API User trunk, at controllers/User.php

1,057 lines 28.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 // Prevent direct access to this file.
4 if (!defined('ABSPATH')) {
5 exit;
6 }
7
8 /*
9 Controller name: User
10 Controller description: User Registration, Authentication, User Info, User Meta, FB Login, BuddyPress xProfile Fields methods
11 Controller Author: Ali Qureshi
12 Controller Author Twitter: @parorrey
13 Controller Author Website: parorrey.com
14
15 */
16 class JSON_API_User_Controller
17 {
18
19 /**
20 * Returns an Array with registered userid & valid cookie
21 * @param String username: username to register
22 * @param String email: email address for user registration
23 * @param String user_pass: user_pass to be set (optional)
24 * @param String display_name: display_name for user
25 */
26 public function __construct()
27 {
28 global $json_api;
29 // allow only connection over https. because, well, you care about your passwords and sniffing.
30 // turn this sanity-check off if you feel safe inside your localhost or intranet.
31 // send an extra POST parameter: insecure=cool
32 if (
33 empty($_SERVER['HTTPS']) ||
34 (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'off')
35 ) {
36 if (empty($_REQUEST['insecure']) || $_REQUEST['insecure'] != 'cool') {
37 $json_api->error("SSL is not enabled. Either use _https_ or provide 'insecure' var as insecure=cool to confirm you want to use http protocol.");
38 }
39 }
40
41
42 }
43
44 public function info()
45 {
46
47 global $json_api;
48
49 return array(
50 "version" => JAU_VERSION,
51 "php" => PHP_VERSION
52 );
53
54 }
55
56 public function register()
57 {
58
59 global $json_api, $wpdb;
60
61
62 if (!get_option('users_can_register')) {
63 $json_api->error("User registration is disabled. Please enable it in Settings > General.");
64 }
65
66 if (!$json_api->query->username) {
67 $json_api->error("You must include 'username' var in your request. ");
68 } else
69 $username = sanitize_user($json_api->query->username);
70
71
72 if (!$json_api->query->email) {
73 $json_api->error("You must include 'email' var in your request. ");
74 } else
75 $email = sanitize_email($json_api->query->email);
76
77 if (!$json_api->query->nonce) {
78 $json_api->error("You must include 'nonce' var in your request. Use the 'get_nonce' Core API method. ");
79 } else
80 $nonce = sanitize_text_field($json_api->query->nonce);
81
82 if ($json_api->query->display_name) {
83 $display_name = sanitize_text_field($json_api->query->display_name);
84 }
85
86
87 $user_pass = sanitize_text_field($_REQUEST['user_pass']);
88
89 if ($json_api->query->seconds)
90 $seconds = (int) $json_api->query->seconds;
91 else
92 $seconds = 1209600; //14 days
93
94 //Add usernames we don't want used
95
96 $invalid_usernames = array('admin');
97
98 //Do username validation
99
100 $nonce_id = $json_api->get_nonce_id('user', 'register');
101
102 if (!wp_verify_nonce($json_api->query->nonce, $nonce_id)) {
103
104 $json_api->error("Invalid access, unverifiable 'nonce' value. Use the 'get_nonce' Core API method. ");
105 } else {
106
107 if (!validate_username($username) || in_array($username, $invalid_usernames)) {
108
109 $json_api->error("Username is invalid.");
110
111 } elseif (username_exists($username)) {
112
113 $json_api->error("Username already exists.");
114
115 } else {
116
117
118 if (!is_email($email)) {
119 $json_api->error("E-mail address is invalid.");
120 } elseif (email_exists($email)) {
121
122 $json_api->error("E-mail address is already in use.");
123
124 } else {
125
126 //Everything has been validated, proceed with creating the user
127
128 //Create the user
129
130 if (!isset($_REQUEST['user_pass'])) {
131 $user_pass = wp_generate_password();
132 $_REQUEST['user_pass'] = $user_pass;
133 }
134
135 $_REQUEST['user_login'] = $username;
136 $_REQUEST['user_email'] = $email;
137
138 $allowed_params = array(
139 'user_login',
140 'user_email',
141 'user_pass',
142 'display_name',
143 'user_nicename',
144 'user_url',
145 'nickname',
146 'first_name',
147 'last_name',
148 'description',
149 'rich_editing',
150 'user_registered',
151 'role',
152 'jabber',
153 'aim',
154 'yim',
155 'comment_shortcuts',
156 'admin_color',
157 'use_ssl',
158 'show_admin_bar_front'
159 );
160
161
162 foreach ($_REQUEST as $field => $value) {
163
164 if (in_array($field, $allowed_params))
165 $user[$field] = trim(sanitize_text_field($value));
166
167 }
168 $user['role'] = get_option('default_role');
169 $user_id = wp_insert_user($user);
170
171 /*Send e-mail to admin and new user -
172 You could create your own e-mail instead of using this function*/
173
174 if (isset($_REQUEST['user_pass']) && $_REQUEST['notify'] == 'no') {
175 $notify = '';
176 } elseif ($_REQUEST['notify'] != 'no')
177 $notify = $_REQUEST['notify'];
178
179
180 if ($user_id)
181 wp_new_user_notification($user_id, '', $notify);
182
183
184 }
185 }
186 }
187
188 if(is_array($json_api->query->custom_fields)) {
189 $custom_fields = $json_api->query->custom_fields;
190
191 $keys = array_keys($custom_fields);
192 $keys = array_map('sanitize_key', $keys);
193 $values = array_values($custom_fields);
194 $values = array_map('sanitize_text_field', $values);
195
196 $custom_fields = array_combine($keys, $values);
197
198 }
199
200 if ($user_id) {
201 $disallowed = array("wp_user_level", "wp_capabilities", "{$wpdb->prefix}user_level", "{$wpdb->prefix}capabilities");
202
203 if ( !empty($custom_fields) && is_array($custom_fields)) {
204
205 foreach ($custom_fields as $field => $val) {
206 if(!in_array($field, $disallowed)){
207 foreach($disallowed as $d){
208 $field = str_replace($d, 'disallowed', $field);
209 }
210
211 $data[$field] = update_user_meta($user_id, $field, $val);
212 }
213
214
215 }
216 }
217
218 $expiration = time() + apply_filters('auth_cookie_expiration', $seconds, $user_id, true);
219
220 $cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
221 $cookie_admin = wp_generate_auth_cookie($user_id, $expiration, 'secure_auth');
222
223 $user_info = get_userdata($user_id);
224 }
225
226 return array(
227 "cookie" => $cookie,
228 "cookie_admin" => $cookie_admin,
229 "cookie_name" => LOGGED_IN_COOKIE,
230 "user_id" => $user_id,
231 "username" => $user_info->user_login
232 );
233
234 }
235
236 public function get_avatar()
237 {
238
239 global $json_api;
240
241 if (function_exists('bp_is_active')) {
242
243 if (!$json_api->query->user_id) {
244 $json_api->error("You must include 'user_id' var in your request. ");
245 }
246
247 if (!$json_api->query->type) {
248 $json_api->error("You must include 'type' var in your request. possible values 'full' or 'thumb' ");
249 }
250
251
252 $avatar = bp_core_fetch_avatar(array('item_id' => $json_api->query->user_id, 'type' => $json_api->query->type, 'html' => false));
253
254 return array('avatar' => $avatar);
255 } else {
256
257 $json_api->error("You must install and activate BuddyPress plugin to use this method.");
258
259 }
260
261 }
262
263 public function get_userinfo()
264 {
265
266 global $json_api;
267
268 if (!$json_api->query->user_id) {
269 $json_api->error("You must include 'user_id' var in your request. ");
270 }
271
272 $user = get_userdata($json_api->query->user_id);
273
274 preg_match('|src="(.+?)"|', get_avatar($user->ID, 32), $avatar);
275 $avatar_icon = isset($avatar[1]) ? $avatar[1] : NULL;
276
277 return array(
278 "id" => $user->ID,
279 //"username" => $user->user_login,
280 "nicename" => $user->user_nicename,
281 //"email" => $user->user_email,
282 "url" => $user->user_url,
283 "displayname" => $user->display_name,
284 "firstname" => $user->user_firstname,
285 "lastname" => $user->last_name,
286 "nickname" => $user->nickname,
287 "avatar" => $avatar_icon
288 );
289
290 }
291
292 public function retrieve_password()
293 {
294
295 global $wpdb, $json_api, $wp_hasher;
296
297 if (!$json_api->query->user_login) {
298
299 $json_api->error("You must include 'user_login' var in your request. ");
300
301 }
302
303 $user_login = $json_api->query->user_login;
304
305 if (strpos($user_login, '@')) {
306
307 $user_data = get_user_by('email', trim($user_login));
308
309 if (empty($user_data))
310
311
312
313 $json_api->error("Your email address not found! ");
314
315
316
317 } else {
318
319 $login = trim($user_login);
320
321 $user_data = get_user_by('login', $login);
322
323 }
324
325
326
327 // redefining user_login ensures we return the right case in the email
328
329 $user_login = $user_data->user_login;
330
331 $user_email = $user_data->user_email;
332
333
334 do_action('retrieve_password', $user_login);
335
336
337 $allow = apply_filters('allow_password_reset', true, $user_data->ID);
338
339 if (!$allow)
340 $json_api->error("password reset not allowed! ");
341 elseif (is_wp_error($allow))
342 $json_api->error("An error occured! ");
343
344
345
346 $key = wp_generate_password(20, false);
347
348 do_action('retrieve_password_key', $user_login, $key);
349
350
351
352 if (empty($wp_hasher)) {
353
354 require_once ABSPATH . 'wp-includes/class-phpass.php';
355
356 $wp_hasher = new PasswordHash(8, true);
357
358 }
359
360
361 $hashed = time() . ':' . $wp_hasher->HashPassword($key);
362
363 $wpdb->update($wpdb->users, array('user_activation_key' => $hashed), array('user_login' => $user_login));
364
365 $message = __('Someone requested that the password be reset for the following account:') . "\r\n\r\n";
366
367 $message .= network_home_url('/') . "\r\n\r\n";
368
369 $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
370
371 $message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n";
372
373 $message .= __('To reset your password, visit the following address:') . "\r\n\r\n";
374
375 $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . ">\r\n";
376
377
378
379 if (is_multisite())
380
381 $blogname = $GLOBALS['current_site']->site_name;
382 else
383
384 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
385
386
387
388 $title = sprintf(__('[%s] Password Reset'), $blogname);
389
390
391
392 $title = apply_filters('retrieve_password_title', $title);
393
394 $message = apply_filters('retrieve_password_message', $message, $key);
395
396
397
398 if ($message && !wp_mail($user_email, $title, $message))
399
400 $json_api->error("The e-mail could not be sent. Possible reason: your host may have disabled the mail() function...");
401 else
402
403 return array(
404
405 "msg" => 'Link for password reset has been emailed to you. Please check your email.',
406
407 );
408
409 }
410
411 public function validate_auth_cookie()
412 {
413
414 global $json_api;
415
416
417 if (!$json_api->query->cookie) {
418
419 $json_api->error("You must include a 'cookie' authentication cookie. Use the `generate_auth_cookie` method.");
420
421 }
422
423 $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
424
425 $valid = $user_id ? true : false;
426
427 return array(
428
429 "valid" => $valid,
430 "user_id" => $user_id
431
432 );
433
434 }
435
436 public function generate_auth_cookie()
437 {
438
439 global $json_api;
440
441 foreach ($_POST as $k => $val) {
442 if (isset($_POST[$k])) {
443 $json_api->query->$k = $val;
444 }
445 }
446
447
448 if (!$json_api->query->username && !$json_api->query->email) {
449
450 $json_api->error("You must include 'username' or 'email' var in your request to generate cookie.");
451
452 }
453
454
455 if (!$json_api->query->password) {
456
457 $json_api->error("You must include a 'password' var in your request.");
458
459 }
460
461 if ($json_api->query->seconds)
462 $seconds = (int) $json_api->query->seconds;
463 else
464 $seconds = 1209600; //14 days
465
466 if ($json_api->query->email) {
467
468
469 if (is_email($json_api->query->email)) {
470 if (!email_exists($json_api->query->email)) {
471 $json_api->error("email does not exist.");
472 }
473 } else
474 $json_api->error("Invalid email address.");
475
476 $user_obj = get_user_by('email', $json_api->query->email);
477
478
479 $user = wp_authenticate($user_obj->data->user_login, $json_api->query->password);
480 } else {
481
482 $user = wp_authenticate($json_api->query->username, $json_api->query->password);
483 }
484
485
486 if (is_wp_error($user)) {
487
488 remove_action('wp_login_failed', $json_api->query->username);
489 $json_api->error("Invalid username/email and/or password.", 'error', '401');
490
491 }
492
493
494 $expiration = time() + apply_filters('auth_cookie_expiration', $seconds, $user->ID, true);
495
496 $cookie = wp_generate_auth_cookie($user->ID, $expiration, 'logged_in');
497 $cookie_admin = wp_generate_auth_cookie($user->ID, $expiration, 'secure_auth');
498
499 preg_match('|src="(.+?)"|', get_avatar($user->ID, 512), $avatar);
500 $avatar_icon = isset($avatar[1]) ? $avatar[1] : NULL;
501
502
503 return array(
504 "cookie" => $cookie,
505 "cookie_admin" => $cookie_admin,
506 "cookie_name" => LOGGED_IN_COOKIE,
507 "user" => array(
508 "id" => $user->ID,
509 "username" => $user->user_login,
510 "nicename" => $user->user_nicename,
511 "email" => $user->user_email,
512 "url" => $user->user_url,
513 "registered" => $user->user_registered,
514 "displayname" => $user->display_name,
515 "firstname" => $user->user_firstname,
516 "lastname" => $user->last_name,
517 "nickname" => $user->nickname,
518 "description" => $user->user_description,
519 "capabilities" => $user->wp_capabilities,
520 "avatar" => $avatar_icon
521
522 ),
523 );
524 }
525
526 public function get_currentuserinfo()
527 {
528
529 global $json_api;
530
531 if (!$json_api->query->cookie) {
532
533 $json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` Auth API method.");
534
535 }
536
537 $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
538
539
540 if (!$user_id) {
541 $json_api->error("Invalid authentication cookie. Use the `generate_auth_cookie` method.");
542 }
543
544 $user = get_userdata($user_id);
545
546 preg_match('|src="(.+?)"|', get_avatar($user->ID, 32), $avatar);
547
548 $avatar_icon = isset($avatar[1]) ? $avatar[1] : NULL;
549
550 return array(
551
552 "user" => array(
553
554 "id" => $user->ID,
555
556 "username" => $user->user_login,
557
558 "nicename" => $user->user_nicename,
559
560 "email" => $user->user_email,
561
562 "url" => $user->user_url,
563
564 "registered" => $user->user_registered,
565
566 "displayname" => $user->display_name,
567
568 "firstname" => $user->user_firstname,
569
570 "lastname" => $user->last_name,
571
572 "nickname" => $user->nickname,
573
574 "description" => $user->user_description,
575
576 "capabilities" => $user->wp_capabilities,
577
578 "avatar" => $avatar_icon
579
580 )
581
582 );
583
584 }
585
586 public function get_user_meta()
587 {
588
589 global $json_api;
590
591 if (!$json_api->query->cookie) {
592 $json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
593 }
594
595 $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
596
597 if (!$user_id)
598 $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
599
600 $meta_key = sanitize_text_field($json_api->query->meta_key);
601
602
603 if ($meta_key)
604 $data[$meta_key] = get_user_meta($user_id, $meta_key);
605 else {
606 // Get all user meta data for $user_id
607 $meta = get_user_meta($user_id);
608
609 // Filter out empty meta data
610 $data = array_filter(array_map(function ($a) {
611 return $a[0];
612 }, $meta));
613
614 }
615 //d($data);
616 return $data;
617
618
619 }
620
621 public function update_user_meta()
622 {
623
624 global $json_api, $wpdb;
625
626 if (!$json_api->query->cookie) {
627 $json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
628 }
629
630 $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
631
632 if (!$user_id)
633 $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
634
635
636 if (!$json_api->query->meta_key)
637 $json_api->error("You must include a 'meta_key' var in your request.");
638 else
639 $meta_key = sanitize_text_field($json_api->query->meta_key);
640
641 if (!$json_api->query->meta_value) {
642 $json_api->error("You must include a 'meta_value' var in your request. If you have multiple values for any meta_key, you must send it as an array meta_value[] in POST method.");
643 } else
644 $meta_value = sanitize_text_field($json_api->query->meta_value);
645
646 $disallowed = array("wp_user_level", "wp_capabilities", "{$wpdb->prefix}user_level", "{$wpdb->prefix}capabilities");
647
648 if(in_array($meta_key, $disallowed) ){
649 $json_api->error("This meta_key '".$meta_key."' is not allowed.");
650 }
651
652 if(!in_array($meta_key, $disallowed) ){
653 foreach($disallowed as $d){
654 $meta_key = str_replace($d, 'disallowed', $meta_key);
655 }
656 if (is_array($meta_value)) {
657
658 $meta_values = array_map('trim', $meta_value);
659
660
661 $data['updated'] = update_user_meta($user_id, $meta_key, $meta_values);
662 } else
663 $data['updated'] = update_user_meta($user_id, $meta_key, $meta_value);
664 }
665
666 return $data;
667
668 }
669
670 public function delete_user_meta()
671 {
672
673 global $json_api;
674
675 if (!$json_api->query->cookie) {
676 $json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
677 }
678
679 $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
680
681 if (!$user_id)
682 $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
683
684
685 if (!$json_api->query->meta_key)
686 $json_api->error("You must include a 'meta_key' var in your request.");
687 else
688 $meta_key = $json_api->query->meta_key;
689
690 if (!$json_api->query->meta_value) {
691 $json_api->error("You must include a 'meta_value' var in your request.");
692 } else
693 $meta_value = sanitize_text_field($json_api->query->meta_value);
694
695
696 $data['deleted'] = delete_user_meta($user_id, $meta_key, $meta_value);
697
698 return $data;
699
700 }
701
702 public function update_user_meta_vars()
703 {
704
705 global $json_api, $wpdb;
706
707 if (!$json_api->query->cookie) {
708 $json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
709 }
710
711 $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
712 // echo '$user_id: '.$user_id;
713
714 if (!$user_id) {
715 $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
716 }
717
718 if (sizeof($_REQUEST) <= 1)
719 $json_api->error("You must include one or more vars in your request to add or update as user_meta. e.g. 'name', 'website', 'skills'. You must submit via POST method and can send multiple meta_key vars in this format in custom_field param: custom_fields['name']=John. custom_fields['website']=google.com. If any field has the possibility to hold more than one value for any multi-select fields or check boxes, you must provide an array of values and use POST method.");
720
721 $disallowed = array("wp_user_level", "wp_capabilities", "{$wpdb->prefix}user_level", "{$wpdb->prefix}capabilities");
722
723 if(is_array($json_api->query->custom_fields)) {
724 $custom_fields = $json_api->query->custom_fields;
725
726 $keys = array_keys($custom_fields);
727 $keys = array_map('sanitize_key', $keys);
728 $values = array_values($custom_fields);
729 $values = array_map('sanitize_text_field', $values);
730
731 $custom_fields = array_combine($keys, $values);
732
733 }
734
735 $result = array();
736 if( !empty($custom_fields) && is_array($custom_fields)){
737
738
739 foreach ($custom_fields as $field => $value) {
740
741 if(in_array($field, $disallowed) ){
742 $json_api->error("This meta_key '".$field."' is not allowed.");
743 }
744
745 if ($field == 'cookie')
746 continue;
747
748 //$field_label = str_replace('_', ' ', $field);
749
750 if (is_array($value)) {
751 //$values = explode(",", $value);
752 $values = array_map('trim', $values);
753 } else
754 $values = trim($value);
755
756 if(!in_array($field, $disallowed) ){
757 foreach($disallowed as $d){
758 $field = str_replace($d, 'disallowed', $field);
759 }
760 $result[$field]['updated'] = update_user_meta($user_id, $field, $values);
761 }
762
763 }
764 }
765
766 return $result;
767
768 }
769
770 public function xprofile()
771 {
772
773 global $json_api;
774
775 if (function_exists('bp_is_active')) {
776
777 if (!$json_api->query->user_id) {
778 $json_api->error("You must include a 'user_id' var in your request.");
779 } else
780 $user_id = $json_api->query->user_id;
781
782
783 if (!$json_api->query->field) {
784 $json_api->error("You must include a 'field' var in your request. Use 'field=default' for all default fields.");
785 } elseif ($json_api->query->field == 'default') {
786 $field_label = 'First Name, Last Name, Bio'; /*you should add your own field labels here for quick viewing*/
787 } else
788 $field_label = sanitize_text_field($json_api->query->field);
789
790
791 $fields = explode(",", $field_label);
792
793 if (is_array($fields)) {
794
795 foreach ($fields as $k) {
796
797 $fields_data[$k] = xprofile_get_field_data($k, $user_id);
798
799 }
800
801 return $fields_data;
802
803
804 }
805
806 } else {
807
808 $json_api->error("You must install and activate BuddyPress plugin to use this method.");
809
810 }
811
812 }
813
814 public function xprofile_update()
815 {
816
817 global $json_api;
818
819 if (function_exists('bp_is_active')) {
820
821 if (!$json_api->query->cookie) {
822 $json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
823 }
824
825 $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
826 // echo '$user_id: '.$user_id;
827
828 if (!$user_id) {
829 $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
830 }
831
832
833 foreach ($_REQUEST as $field => $value) {
834
835 if ($field == 'cookie')
836 continue;
837
838 $field_label = str_replace('_', ' ', $field);
839
840 if (strpos($value, ',') !== false) {
841 $values = explode(",", $value);
842 $values = array_map('trim', $values);
843 } else
844 $values = trim($value);
845 //echo 'field-values: '.$field.'=>'.$value;
846 //d($values);
847
848 $result[$field_label]['updated'] = xprofile_set_field_data($field_label, $user_id, $values, $is_required = true);
849
850 }
851
852 return $result;
853 } else {
854
855 $json_api->error("You must install and activate BuddyPress plugin to use this method.");
856
857 }
858
859 }
860
861 public function fb_connect()
862 {
863
864 global $json_api;
865
866 if ($json_api->query->fields) {
867
868 $fields = $json_api->query->fields;
869
870 } else
871 $fields = 'id,name,first_name,last_name,email';
872
873 if ($json_api->query->ssl) {
874 $enable_ssl = $json_api->query->ssl;
875 } else
876 $enable_ssl = true;
877
878 if (!$json_api->query->access_token) {
879 $json_api->error("You must include a 'access_token' variable. Get the valid access_token for this app from Facebook API.");
880 } else {
881
882 $url = 'https://graph.facebook.com/me/?fields=' . $fields . '&access_token=' . $json_api->query->access_token;
883
884 // Initiate curl
885 $ch = curl_init();
886 // Enable SSL verification
887 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $enable_ssl);
888 // Will return the response, if false it print the response
889 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
890 // Set the url
891 curl_setopt($ch, CURLOPT_URL, $url);
892 // Execute
893 $result = curl_exec($ch);
894 // Closing
895 curl_close($ch);
896
897 $result = json_decode($result, true);
898
899 if (isset($result["email"])) {
900
901 $user_email = $result["email"];
902 $email_exists = email_exists($user_email);
903
904 if ($email_exists) {
905 $user = get_user_by('email', $user_email);
906 $user_id = $user->ID;
907 $user_name = $user->user_login;
908 }
909
910
911
912 if (!$user_id && $email_exists == false) {
913
914 $user_name = strtolower($result['first_name'] . '.' . $result['last_name']);
915
916 while (username_exists($user_name)) {
917 $i++;
918 $user_name = strtolower($result['first_name'] . '.' . $result['last_name']) . '.' . $i;
919
920 }
921
922 $random_password = wp_generate_password($length = 12, $include_standard_special_chars = false);
923 $userdata = array(
924 'user_login' => $user_name,
925 'user_email' => $user_email,
926 'user_pass' => $random_password,
927 'display_name' => $result["name"],
928 'first_name' => $result['first_name'],
929 'last_name' => $result['last_name']
930 );
931
932 $user_id = wp_insert_user($userdata);
933 if ($user_id)
934 $user_account = 'user registered.';
935
936 } else {
937
938 if ($user_id)
939 $user_account = 'user logged in.';
940 }
941
942 $expiration = time() + apply_filters('auth_cookie_expiration', 1209600, $user_id, true);
943 $cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
944
945 $response['msg'] = $user_account;
946 $response['wp_user_id'] = $user_id;
947 $response['cookie'] = $cookie;
948 $response['user_login'] = $user_name;
949
950 } else {
951 $response['msg'] = "Your 'access_token' did not return email of the user. Without 'email' user can't be logged in or registered. Get user email extended permission while joining the Facebook app.";
952
953 }
954
955 }
956
957 return $response;
958
959 }
960
961 public function post_comment()
962 {
963 global $json_api;
964
965 if (!$json_api->query->cookie) {
966 $json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
967 }
968
969 $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
970
971 if (!$user_id) {
972 $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
973 }
974
975 if (!$json_api->query->post_id) {
976 $json_api->error("No post specified. Include 'post_id' var in your request.");
977 } elseif (!$json_api->query->content) {
978 $json_api->error("Please include 'content' var in your request.");
979 }
980
981 $post_id = absint($json_api->query->post_id);
982
983 if (!$post_id || !get_post($post_id)) {
984 $json_api->error("Invalid 'post_id'. The specified post does not exist.");
985 }
986
987 if (!comments_open($post_id)) {
988 $json_api->error("Comments are closed for this post.");
989 }
990
991 // Sanitize the comment content the same way WordPress core does for
992 // trusted contexts: strip any markup/attributes not allowed by the
993 // site's kses post rules. This prevents stored XSS via raw <script>,
994 // onerror=, javascript: URIs, etc. being persisted and later
995 // rendered unescaped on the front end.
996 $content = wp_unslash($json_api->query->content);
997 $content = wp_filter_post_kses($content);
998
999 if ('' === trim(wp_strip_all_tags($content))) {
1000 $json_api->error("Comment 'content' is empty after sanitization.");
1001 }
1002
1003 // Make sure WordPress treats this request as coming from the
1004 // authenticated user (wp_new_comment() / its filters rely on the
1005 // current user context, e.g. for comment_author_* fallback and the
1006 // comments_flood filter).
1007 wp_set_current_user($user_id);
1008 $user_info = get_userdata($user_id);
1009
1010 // comment_approved must NOT be settable by arbitrary authenticated
1011 // users — only users who actually have moderation rights are
1012 // allowed to self-approve a comment. Everyone else is always
1013 // moderated according to the site's normal comment workflow
1014 // (handled internally by wp_new_comment()).
1015 $requested_status = isset($json_api->query->comment_status)
1016 ? $json_api->query->comment_status
1017 : 'hold';
1018
1019 $commentdata = array(
1020 'comment_post_ID' => $post_id,
1021 'comment_author' => $user_info->user_login,
1022 'comment_author_email' => $user_info->user_email,
1023 'comment_author_url' => $user_info->user_url,
1024 'comment_content' => $content,
1025 'comment_type' => '',
1026 'comment_parent' => 0,
1027 'user_id' => $user_info->ID,
1028 'comment_author_IP' => $_SERVER['REMOTE_ADDR'],
1029 'comment_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '',
1030 );
1031
1032 if ($requested_status === '1' && current_user_can('moderate_comments')) {
1033 // Only explicitly privileged users may force-approve their own
1034 // comment; wp_new_comment() still runs all standard filters
1035 // (e.g. pre_comment_content, comment moderation, flood checks).
1036 $commentdata['comment_approved'] = 1;
1037 }
1038
1039 // wp_new_comment() — unlike wp_insert_comment() — runs the
1040 // pre_comment_content filter (which applies wp_filter_kses /
1041 // wp_kses_post depending on context), enforces comment moderation
1042 // settings (akismet, blacklist, flood checks, manual approval
1043 // requirements), and fires the standard comment hooks that other
1044 // plugins expect to run. Calling wp_insert_comment() directly, as
1045 // the previous implementation did, bypassed all of this.
1046 $comment_id = wp_new_comment($commentdata, true);
1047
1048 if (is_wp_error($comment_id)) {
1049 $json_api->error($comment_id->get_error_message());
1050 }
1051
1052 return array(
1053 "comment_id" => $comment_id
1054 );
1055 }
1056
1057 }