diff options
| author | Lester Caine <lester@lsces.co.uk> | 2026-05-14 09:55:19 +0100 |
|---|---|---|
| committer | Lester Caine <lester@lsces.co.uk> | 2026-05-14 09:55:19 +0100 |
| commit | 513bc9e03522f0bfc0e307a8e40a517e746de2bc (patch) | |
| tree | bed44d24c1ef1ee8d3801b74fe0fac68e1f779f4 | |
| parent | 70ebf6a972f511a904a7775ec792dc2523bf3e13 (diff) | |
| download | users-513bc9e03522f0bfc0e307a8e40a517e746de2bc.tar.gz users-513bc9e03522f0bfc0e307a8e40a517e746de2bc.tar.bz2 users-513bc9e03522f0bfc0e307a8e40a517e746de2bc.zip | |
php-cs-fixer tidies to php8.5 standards
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
| -rwxr-xr-x[-rw-r--r--] | .htaccess | 0 | ||||
| -rwxr-xr-x | admin/admin_login_inc.php | 50 | ||||
| -rwxr-xr-x | admin/admin_users_inc.php | 31 | ||||
| -rw-r--r-- | admin/api_help_inc.php | 78 | ||||
| -rwxr-xr-x | admin/assign_user.php | 10 | ||||
| -rwxr-xr-x | admin/edit_group.php | 20 | ||||
| -rwxr-xr-x | admin/edit_role.php | 8 | ||||
| -rwxr-xr-x | admin/index.php | 11 | ||||
| -rwxr-xr-x | admin/permissions.php | 8 | ||||
| -rwxr-xr-x | admin/role_permissions.php | 2 | ||||
| -rw-r--r-- | admin/schema_inc.php | 19 | ||||
| -rwxr-xr-x | admin/upgrade_inc.php | 439 | ||||
| -rwxr-xr-x | admin/user_activity.php | 4 | ||||
| -rwxr-xr-x | admin/users_import.php | 2 | ||||
| -rw-r--r-- | admin/verify_emails.php | 6 | ||||
| -rw-r--r-- | admin/verify_emails_role.php | 4 | ||||
| -rwxr-xr-x | auth/bit/auth.php | 6 | ||||
| -rwxr-xr-x | auth/imap/auth.php | 27 | ||||
| -rwxr-xr-x | auth/ldap/auth.php | 9 | ||||
| -rwxr-xr-x | auth/locate/auth.php | 15 | ||||
| -rwxr-xr-x | auth/multisites/auth.php | 17 | ||||
| -rwxr-xr-x | bookmark.php | 6 | ||||
| -rwxr-xr-x | change_password.php | 4 | ||||
| -rwxr-xr-x | custom_home.php | 2 | ||||
| -rwxr-xr-x | edit_personal_page.php | 8 | ||||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_font1.gdf | bin | 44216 -> 44216 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_font2.gdf | bin | 44216 -> 44216 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_font3.gdf | bin | 44216 -> 44216 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_font4.gdf | bin | 44216 -> 44216 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_font5.gdf | bin | 44216 -> 44216 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_im1.jpg | bin | 84564 -> 84564 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_im2.jpg | bin | 111193 -> 111193 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_im3.jpg | bin | 69645 -> 69645 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_im4.jpg | bin | 46182 -> 46182 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_im5.jpg | bin | 62563 -> 62563 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | freecap/.ht_freecap_words | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | freecap/COPYING.txt | 0 | ||||
| -rwxr-xr-x | freecap/freecap.php | 52 | ||||
| -rw-r--r-- | freecap/freecap_wrap.php | 26 | ||||
| -rw-r--r-- | hauth/Hybrid/Auth.php | 277 | ||||
| -rw-r--r-- | hauth/Hybrid/Endpoint.php | 4 | ||||
| -rw-r--r-- | hauth/Hybrid/Error.php | 48 | ||||
| -rwxr-xr-x[-rw-r--r--] | hauth/Hybrid/Exception.php | 0 | ||||
| -rw-r--r-- | hauth/Hybrid/Logger.php | 78 | ||||
| -rw-r--r-- | hauth/Hybrid/Provider_Adapter.php | 246 | ||||
| -rw-r--r-- | hauth/Hybrid/Provider_Model.php | 241 | ||||
| -rw-r--r-- | hauth/Hybrid/Provider_Model_OAuth1.php | 144 | ||||
| -rw-r--r-- | hauth/Hybrid/Provider_Model_OAuth2.php | 272 | ||||
| -rw-r--r-- | hauth/Hybrid/Provider_Model_OpenID.php | 134 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/AOL.php | 16 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Amazon.php | 2 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Dropbox.php | 10 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Facebook.php | 781 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Foursquare.php | 82 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Google.php | 122 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Instagram.php | 48 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/LinkedIn.php | 340 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Live.php | 90 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/OpenID.php | 12 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Paypal.php | 320 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/PaypalOpenID.php | 268 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Twitter.php | 252 | ||||
| -rw-r--r-- | hauth/Hybrid/Providers/Yahoo.php | 506 | ||||
| -rw-r--r-- | hauth/Hybrid/Storage.php | 80 | ||||
| -rwxr-xr-x[-rw-r--r--] | hauth/Hybrid/StorageInterface.php | 0 | ||||
| -rw-r--r-- | hauth/Hybrid/User.php | 28 | ||||
| -rw-r--r-- | hauth/Hybrid/User_Activity.php | 36 | ||||
| -rw-r--r-- | hauth/Hybrid/User_Contact.php | 40 | ||||
| -rw-r--r-- | hauth/Hybrid/User_Profile.php | 104 | ||||
| -rwxr-xr-x[-rw-r--r--] | hauth/Hybrid/index.html | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | hauth/Hybrid/resources/index.html | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | hauth/Hybrid/resources/openid_policy.html | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | hauth/Hybrid/resources/openid_realm.html | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | hauth/Hybrid/resources/openid_xrds.xml | 0 | ||||
| -rw-r--r-- | hauth/Hybrid/thirdparty/Amazon/AmazonOAuth2Client.php | 6 | ||||
| -rwxr-xr-x | hauth/Hybrid/thirdparty/OAuth/OAuth.php | 1291 | ||||
| -rw-r--r-- | hauth/Hybrid/thirdparty/OAuth/OAuth1Client.php | 51 | ||||
| -rw-r--r-- | hauth/Hybrid/thirdparty/OAuth/OAuth2Client.php | 298 | ||||
| -rw-r--r-- | hauth/Hybrid/thirdparty/OpenID/LightOpenID.php | 2070 | ||||
| -rwxr-xr-x[-rw-r--r--] | hauth/Hybrid/thirdparty/index.html | 0 | ||||
| -rw-r--r-- | hauth/disconnect.php | 2 | ||||
| -rwxr-xr-x[-rw-r--r--] | hauth/images/google.png | bin | 8055 -> 8055 bytes | |||
| -rw-r--r-- | hauth/index.php | 14 | ||||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Afghanistan,_Islamic_State_of.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Albania.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Algeria.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/American_Samoa.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Andorra,_Principality_of.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Angola.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Anguilla.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Antigua_and_Barbuda.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Arab_League.gif | bin | 947 -> 947 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Argentina.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Armenia.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Aruba.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Australia.gif | bin | 378 -> 378 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Austria.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Azerbaidjan.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Bahamas.gif | bin | 351 -> 351 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Bahrain.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Bangladesh.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Barbados.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Belarus.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Belgium.gif | bin | 359 -> 359 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Belize.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Benin.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Bermuda.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Bhutan.gif | bin | 377 -> 377 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Bolivia.gif | bin | 359 -> 359 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Bosnia-Herzegovina.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Botswana.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Bouvet_Island.gif | bin | 376 -> 376 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Brazil.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/British_Indian_Ocean_Territory.gif | bin | 373 -> 373 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Brunei_Darussalam.gif | bin | 373 -> 373 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Bulgaria.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Burkina_Faso.gif | bin | 358 -> 358 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Burundi.gif | bin | 374 -> 374 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Cambodia,_Kingdom_of.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Cameroon.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Canada.gif | bin | 376 -> 376 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Cape_Verde.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Cayman_Islands.gif | bin | 373 -> 373 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Central_African_Republic.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Chad.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Chile.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/China.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Christmas_Island.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Cocos_Islands.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Colombia.gif | bin | 353 -> 353 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Comoros.gif | bin | 358 -> 358 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Congo,_The_Democratic_Republic_of_the.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Cook_Islands.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Costa_Rica.gif | bin | 359 -> 359 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Croatia.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Cuba.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Cyprus.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Czech_Republic.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Denmark.gif | bin | 374 -> 374 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Djibouti.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Dominica.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Dominican_Republic.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Ecuador.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Egypt.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/El_Salvador.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/England.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Equatorial_Guinea.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Eritrea.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Estonia.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Ethiopia.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Falkland_Islands.gif | bin | 372 -> 372 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Faroe_Islands.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Federated_States_of_Micronesia.gif | bin | 1020 -> 1020 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Fiji.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Finland.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Former_Czechoslovakia.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/France.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/French_Polynesia.gif | bin | 1052 -> 1052 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/French_Southern_Territories.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Gabon.gif | bin | 359 -> 359 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Gambia.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Georgia.gif | bin | 379 -> 379 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Germany.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Ghana.gif | bin | 358 -> 358 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Gibraltar.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Great_Britain.gif | bin | 382 -> 382 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Greece.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Greenland.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Grenada.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Guadeloupe.gif | bin | 357 -> 357 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Guam.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Guatemala.gif | bin | 374 -> 374 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Guinea.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Guinea_Bissau.gif | bin | 358 -> 358 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Guyana.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Haiti.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Holy_See.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Honduras.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Hong_Kong.gif | bin | 373 -> 373 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Hungary.gif | bin | 357 -> 357 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Iceland.gif | bin | 373 -> 373 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/India.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Indonesia.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Iran.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Iraq.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Ireland.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Israel.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Italy.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Ivory_Coast.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Jamaica.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Japan.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Jordan.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Kazakhstan.gif | bin | 374 -> 374 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Kenya.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Kiribati.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Kuwait.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Kyrgyz_Republic.gif | bin | 373 -> 373 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Laos.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Latvia.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Lebanon.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Lesotho.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Liberia.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Libya.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Liechtenstein.gif | bin | 359 -> 359 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Lithuania.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Luxembourg.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Macau.gif | bin | 378 -> 378 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Macedonia.gif | bin | 382 -> 382 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Madagascar.gif | bin | 372 -> 372 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Malawi.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Malaysia.gif | bin | 375 -> 375 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Maldives.gif | bin | 372 -> 372 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Mali.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Malta.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Marshall_Islands.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Martinique.gif | bin | 379 -> 379 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Mauritania.gif | bin | 377 -> 377 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Mauritius.gif | bin | 358 -> 358 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Mayotte.gif | bin | 382 -> 382 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Mexico.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Micronesia.gif | bin | 377 -> 377 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Moldavia.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Monaco.gif | bin | 359 -> 359 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Mongolia.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Montserrat.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Morocco.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Mozambique.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Myanmar.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Namibia.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Nauru.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Nepal.gif | bin | 302 -> 302 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Netherlands.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Netherlands_Antilles.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/New_Caledonia.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/New_Zealand.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Nicaragua.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Niger.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Nigeria.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Niue.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/None.gif | bin | 55 -> 55 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Norfolk_Island.gif | bin | 375 -> 375 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/North_Korea.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Northern_Mariana_Islands.gif | bin | 368 -> 368 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Norway.gif | bin | 376 -> 376 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Oman.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Other.gif | bin | 128 -> 128 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Pakistan.gif | bin | 377 -> 377 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Palau.gif | bin | 374 -> 374 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Panama.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Papua_New_Guinea.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Paraguay.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Peru.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Philippines.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Pitcairn_Island.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Poland.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Polynesia.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Portugal.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Puerto_Rico.gif | bin | 369 -> 369 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Qatar.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/README | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Romania.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Russian_Federation.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Rwanda.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/S._Georgia_and_S._Sandwich_Isls..gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Saint_Helena.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Saint_Kitts_and_Nevis_Anguilla.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Saint_Lucia.gif | bin | 379 -> 379 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Saint_Pierre_and_Miquelon.gif | bin | 374 -> 374 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Saint_Tome_and_Principe.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Saint_Vincent_and_Grenadines.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Samoa.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/San_Marino.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Saudi_Arabia.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Scotland.gif | bin | 378 -> 378 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Senegal.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Seychelles.gif | bin | 357 -> 357 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Sierra_Leone.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Singapore.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Slovak_Republic.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Slovakia.gif | bin | 99 -> 99 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Slovenia.gif | bin | 362 -> 362 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Solomon_Islands.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Somalia.gif | bin | 376 -> 376 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/South_Africa.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/South_Korea.gif | bin | 385 -> 385 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Spain.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Sri_Lanka.gif | bin | 377 -> 377 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Sudan.gif | bin | 355 -> 355 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Suriname.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Swaziland.gif | bin | 363 -> 363 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Sweden.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Switzerland.gif | bin | 332 -> 332 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Syria.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Tadjikistan.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Taiwan.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Tanzania.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Thailand.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Togo.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Tokelau.gif | bin | 372 -> 372 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Tonga.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Trinidad_and_Tobago.gif | bin | 377 -> 377 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Tunisia.gif | bin | 375 -> 375 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Turkey.gif | bin | 371 -> 371 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Turkmenistan.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Turks_and_Caicos_Islands.gif | bin | 366 -> 366 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Tuvalu.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Uganda.gif | bin | 359 -> 359 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Ukraine.gif | bin | 360 -> 360 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/United_Arab_Emirates.gif | bin | 361 -> 361 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/United_Kingdom.gif | bin | 382 -> 382 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/United_States.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Uruguay.gif | bin | 373 -> 373 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Uzbekistan.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Vanuatu.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Venezuela.gif | bin | 364 -> 364 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Vietnam.gif | bin | 370 -> 370 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Virgin_Islands.gif | bin | 376 -> 376 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Wales.gif | bin | 372 -> 372 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Wallis_and_Futuna_Islands.gif | bin | 377 -> 377 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Western_Sahara.gif | bin | 359 -> 359 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Yemen.gif | bin | 356 -> 356 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Zambia.gif | bin | 358 -> 358 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/Zimbabwe.gif | bin | 365 -> 365 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/au.gif | bin | 378 -> 378 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/ca.gif | bin | 376 -> 376 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/de.gif | bin | 362 -> 362 bytes | |||
| -rw-r--r-- | icons/flags/index.php | 2 | ||||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/uk.gif | bin | 382 -> 382 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/flags/us.gif | bin | 367 -> 367 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/groups.gif | bin | 157 -> 157 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/groups.png | bin | 440 -> 440 bytes | |||
| -rw-r--r-- | icons/index.php | 2 | ||||
| -rwxr-xr-x[-rw-r--r--] | icons/pkg_users.gif | bin | 2030 -> 2030 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/pkg_users.png | bin | 3660 -> 3660 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/silhouette.png | bin | 4672 -> 4672 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/silhouette_100.png | bin | 7882 -> 7882 bytes | |||
| -rwxr-xr-x[-rw-r--r--] | icons/unknown_user.jpg | bin | 766 -> 766 bytes | |||
| -rwxr-xr-x | includes/bit_setup_inc.php | 2 | ||||
| -rwxr-xr-x | includes/classes/BitAuth.php | 6 | ||||
| -rwxr-xr-x | includes/classes/BitHybridAuthManager.php | 56 | ||||
| -rwxr-xr-x | includes/classes/BitPermUser.php | 72 | ||||
| -rwxr-xr-x | includes/classes/BitUser.php | 208 | ||||
| -rw-r--r-- | includes/classes/CloudflareTurnstile.php | 76 | ||||
| -rwxr-xr-x | includes/classes/RolePermUser.php | 13 | ||||
| -rwxr-xr-x | includes/classes/RoleUser.php | 72 | ||||
| -rwxr-xr-x | includes/display_bituser_inc.php | 2 | ||||
| -rwxr-xr-x | includes/lookup_user_inc.php | 3 | ||||
| -rwxr-xr-x | includes/module_controls_inc.php | 28 | ||||
| -rwxr-xr-x | includes/recaptcha/ReCaptcha/ReCaptcha.php | 402 | ||||
| -rw-r--r-- | includes/recaptcha/ReCaptcha/RequestMethod.php | 14 | ||||
| -rw-r--r-- | includes/recaptcha/ReCaptcha/RequestMethod/Curl.php | 72 | ||||
| -rw-r--r-- | includes/recaptcha/ReCaptcha/RequestMethod/CurlPost.php | 98 | ||||
| -rw-r--r-- | includes/recaptcha/ReCaptcha/RequestMethod/Post.php | 76 | ||||
| -rw-r--r-- | includes/recaptcha/ReCaptcha/RequestMethod/Socket.php | 126 | ||||
| -rw-r--r-- | includes/recaptcha/ReCaptcha/RequestMethod/SocketPost.php | 100 | ||||
| -rw-r--r-- | includes/recaptcha/ReCaptcha/RequestParameters.php | 120 | ||||
| -rwxr-xr-x | includes/recaptcha/ReCaptcha/Response.php | 312 | ||||
| -rw-r--r-- | includes/recaptcha/autoload.php | 54 | ||||
| -rwxr-xr-x | includes/register_inc.php | 8 | ||||
| -rwxr-xr-x | includes/solvemedialib.php | 195 | ||||
| -rwxr-xr-x | includes/users_lib.php | 23 | ||||
| -rwxr-xr-x | index.php | 2 | ||||
| -rwxr-xr-x | liberty_plugins/data.userlink.php | 17 | ||||
| -rwxr-xr-x[-rw-r--r--] | modules/help_mod_online_users.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | modules/help_mod_since_last_visit.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | modules/help_mod_user_pages.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | modules/help_mod_user_profile.tpl | 0 | ||||
| -rwxr-xr-x | modules/mod_online_users.php | 2 | ||||
| -rwxr-xr-x[-rw-r--r--] | modules/mod_online_users.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | modules/mod_since_last_visit.tpl | 0 | ||||
| -rwxr-xr-x | modules/mod_user_pages.php | 5 | ||||
| -rwxr-xr-x[-rw-r--r--] | modules/mod_user_pages.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | modules/user_module.tpl | 0 | ||||
| -rwxr-xr-x | my.php | 2 | ||||
| -rwxr-xr-x | my_groups.php | 24 | ||||
| -rwxr-xr-x | my_images.php | 2 | ||||
| -rwxr-xr-x | my_roles.php | 16 | ||||
| -rwxr-xr-x | preferences.php | 3 | ||||
| -rwxr-xr-x | register.php | 10 | ||||
| -rwxr-xr-x | remind_password.php | 2 | ||||
| -rwxr-xr-x | role_register.php | 3 | ||||
| -rwxr-xr-x | signin.php | 3 | ||||
| -rw-r--r-- | smartyplugins/function.captcha.php | 2 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/admin_group_edit.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/admin_groups_list.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/admin_roles_list.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/admin_validation_mail.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/admin_welcome_mail.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/captcha.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/change_password.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/edit_user_fav_json.tpl | 0 | ||||
| -rw-r--r-- | templates/index.php | 2 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/index_list.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/menu_users_admin.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/my_bitweaver_bar.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/my_images.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/new_user_notification.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/password_reminder.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/signin.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/user_activity.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/user_validation_mail.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/user_watches.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/validate_auth.tpl | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | templates/welcome_mail.tpl | 0 | ||||
| -rwxr-xr-x | users_rss.php | 6 | ||||
| -rwxr-xr-x | validate.php | 10 | ||||
| -rwxr-xr-x | watches.php | 8 |
407 files changed, 5671 insertions, 5767 deletions
diff --git a/.htaccess b/.htaccess index d7ee645..d7ee645 100644..100755 --- a/.htaccess +++ b/.htaccess diff --git a/admin/admin_login_inc.php b/admin/admin_login_inc.php index d0209df..07a6343 100755 --- a/admin/admin_login_inc.php +++ b/admin/admin_login_inc.php @@ -10,53 +10,53 @@ use Bitweaver\Users\BitHybridAuthManager; require_once USERS_PKG_CLASS_PATH.'BaseAuth.php'; -$loginSettings = array( - 'users_allow_register' => array( +$loginSettings = [ + 'users_allow_register' => [ 'label' => "Users can register", 'type' => "checkbox", 'note' => "Registration is attempted for the lowest level supporting the creation of new users.", - ), - 'send_welcome_email' => array( + ], + 'send_welcome_email' => [ 'label' => "Send registration welcome email", 'type' => "checkbox", 'note' => "Upon successful registration, this will send the user an email with login information, including their password.", - ), - 'after_reg_url' => array( + ], + 'after_reg_url' => [ 'label' => "After registration url", 'type' => "text", 'note' => "Set a url users will be directed to after registration. Default is your site's home page.", - ), - 'users_login_homepage' => array( + ], + 'users_login_homepage' => [ 'label' => "After login url", 'type' => "text", 'note' => "Set a custom url where users will be directed after logging in. It should not include a leading slash or subdirectory. Default is users/my.php", - ), - 'users_eponymous_groups' => array( + ], + 'users_eponymous_groups' => [ 'label' => "Create a group for each user", 'type' => "checkbox", 'note' => "This will create a group for each user with the same name as the user. This might be useful if you want to assign different permission settings to every user.", - ), - 'users_forgot_pass' => array( + ], + 'users_forgot_pass' => [ 'label' => "Remind passwords by email", 'type' => "checkbox", 'note' => "This will display a 'forgot password' link on the login page and allow users to have their password sent to their registered email address.", - ), - 'users_remember_me' => array( + ], + 'users_remember_me' => [ 'label' => "Remember me feature", 'type' => "checkbox", 'note' => "Registered users will stay logged even if they close their browser.", - ), - 'cookie_domain' => array( + ], + 'cookie_domain' => [ 'label' => "Remember me domain", 'type' => "text", 'note' => "Remember to use a '.' wildcard prefix if you want domain wide cookies.<br />e.g.: <strong>.mysite.com</strong> for a domain called <strong>www.mysite.com</strong>", - ), - 'cookie_path' => array( + ], + 'cookie_path' => [ 'label' => "Remember me path", 'type' => "text", 'note' => "The path '/foo' would match '/foobar' and '/foo/bar.html'", - ), -); + ], +]; $gBitSmarty->assign( 'loginSettings', $loginSettings ); $registerSettings = [ @@ -218,7 +218,6 @@ $httpSettings = [ ]; $gBitSmarty->assign( 'httpSettings', $httpSettings ); - if (defined ('ROLE_MODEL') ) { $listHash = [ 'sort_mode' => 'role_name_asc' ]; $gBitSmarty->assign( 'roleList', $gBitUser->getAllRoles( $listHash )); @@ -253,7 +252,7 @@ if( !empty( $_POST ) ) { } // Save all preferences - foreach( array( 'loginprefs'=>'loginSettings', 'registerprefs'=>'registerSettings', 'httpprefs'=>'httpSettings' ) as $prefGroup=>$prefHash ) { + foreach( [ 'loginprefs'=>'loginSettings', 'registerprefs'=>'registerSettings', 'httpprefs'=>'httpSettings' ] as $prefGroup=>$prefHash ) { $settings = $$prefHash; foreach( array_keys( $settings ) as $feature ) { if( $settings[$feature]['type'] == 'text' ) { @@ -280,10 +279,10 @@ if( !empty( $_POST ) ) { if( isset( $_REQUEST['registration_group_choice'] ) ) { $listHash = []; - $groupList = ( defined( 'ROLE_MODEL' ) ) - ? $gBitUser->getAllRoles( $listHash ) + $groupList = ( defined( 'ROLE_MODEL' ) ) + ? $gBitUser->getAllRoles( $listHash ) : $gBitUser->getAllGroups( $listHash ); - + $in = []; $out = []; foreach( $groupList as $gr ) { @@ -310,7 +309,6 @@ if( !empty( $_POST ) ) { $gBitSmarty->assign( 'hybridProviders', $gBitHybridAuthManager->getAllProviders() ); - $listHash = []; // This needs to be made more generic so that it picks up all plugins diff --git a/admin/admin_users_inc.php b/admin/admin_users_inc.php index 24793b3..7e612cf 100755 --- a/admin/admin_users_inc.php +++ b/admin/admin_users_inc.php @@ -1,32 +1,31 @@ <?php -$formFeatures = array( - 'users_preferences' => array( +$formFeatures = [ + 'users_preferences' => [ 'label' => 'User Preferences', 'note' => 'Users can view and modify their personal preferences.', 'page' => 'UserPreferences', - ), - 'users_change_language' => array( + ], + 'users_change_language' => [ 'label' => 'Registered users can change language', - 'note' => 'Allows users to view a translated version of the site.' - ), - 'users_watches' => array( + 'note' => 'Allows users to view a translated version of the site.', + ], + 'users_watches' => [ 'label' => 'User Watches', 'note' => 'Users can mark pages to be watched. If a watched page is modified, the user is informed.', 'page' => 'UserWatches', - ), - 'display_users_content_list' => array( + ], + 'display_users_content_list' => [ 'label' => 'Display User\'s Content', 'note' => 'Display listing of all content owned by this user on the user My page.', 'page' => 'UserContentList', - ), -); - + ], +]; $gBitSmarty->assign( 'formFeatures', $formFeatures ); if( isset( $_REQUEST['settings'] ) ) { foreach ( array_keys( $formFeatures ) as $feature) { - $gBitSystem->storeConfig( $feature, (isset( $_REQUEST['settings'][$feature][0] ) ? $_REQUEST['settings'][$feature][0] : 'n'), USERS_PKG_NAME ); + $gBitSystem->storeConfig( $feature, ($_REQUEST['settings'][$feature][0] ?? 'n'), USERS_PKG_NAME ); } if( $customFields = explode( ',', $_REQUEST['settings']['custom_user_fields'] ) ) { @@ -34,9 +33,9 @@ if( isset( $_REQUEST['settings'] ) ) { $customFields = implode( ',', $customFields ); } $gBitSystem->storeConfig( 'custom_user_fields', $customFields, USERS_PKG_NAME ); - $gBitSystem->storeConfig( 'users_display_name', (isset( $_REQUEST['settings']['users_display_name'] ) ? $_REQUEST['settings']['users_display_name'] : 'real_name'), USERS_PKG_NAME ); - $gBitSystem->storeConfig( 'users_themes', (isset( $_REQUEST['settings']['users_themes'][0] ) ? $_REQUEST['settings']['users_themes'][0] : null), USERS_PKG_NAME ); - $gBitSystem->storeConfig( 'users_layouts', (isset( $_REQUEST['settings']['users_layouts'][0] ) ? $_REQUEST['settings']['users_layouts'][0] : null), USERS_PKG_NAME ); + $gBitSystem->storeConfig( 'users_display_name', ($_REQUEST['settings']['users_display_name'] ?? 'real_name'), USERS_PKG_NAME ); + $gBitSystem->storeConfig( 'users_themes', ($_REQUEST['settings']['users_themes'][0] ?? null), USERS_PKG_NAME ); + $gBitSystem->storeConfig( 'users_layouts', ($_REQUEST['settings']['users_layouts'][0] ?? null), USERS_PKG_NAME ); } ?> diff --git a/admin/api_help_inc.php b/admin/api_help_inc.php index 4930e1a..bb2e1ef 100644 --- a/admin/api_help_inc.php +++ b/admin/api_help_inc.php @@ -2,26 +2,26 @@ global $gApiHelp, $gBitUser, $gBitSystem; -$gApiHelp['User Registration'] = array( - 'Request Methods' => array( +$gApiHelp['User Registration'] = [ + 'Request Methods' => [ 'method' => 'POST '.API_PKG_URI.'users/register', 'help' => '', - 'parameters' => array( + 'parameters' => [ 'POST '.API_PKG_URI.'users' => 'POST can be used for creation *and* updating existing user objects', 'PUT '.API_PKG_URI.'users' => 'A PUT will perform identically to POST', 'GET '.API_PKG_URI.'users' => 'Once authenticated, and GET to this URL will return JSON of the active user object', - ), - ), - 'Sendable Properties' => array( + ], + ], + 'Sendable Properties' => [ 'help' => 'These are mutable parameters can be sent to the host to store information about the user', - 'parameters' => array( - 'email' => 'valid email, * required for registration.', - 'password' => 'Password to be saved with account. Will be salted and hashed and is irrecoverable. * required for registration', - 'login' => 'username consisting of alphanumeric letters, optional for registration, though a default will be assigned if not set', - 'real_name' => 'The user\'s full name, including first and last names, optional', - ), - ), - 'Examples' => array( + 'parameters' => [ + 'email' => 'valid email, * required for registration.', + 'password' => 'Password to be saved with account. Will be salted and hashed and is irrecoverable. * required for registration', + 'login' => 'username consisting of alphanumeric letters, optional for registration, though a default will be assigned if not set', + 'real_name' => 'The user\'s full name, including first and last names, optional', + ], + ], + 'Examples' => [ 'help' => '', 'code' => '<code>COMMAND: echo -n \'{"email":"test@example.com","password":"s3cr3t"}\' |lwp-request -se -C test:foobar -c "application/json" -H \'API: API consumer_key="bad6ed95edfd983c8cb58cd397a242a2f83cd80c"\' -m PUT '.API_PKG_URI.'users/authenticate @@ -36,34 +36,34 @@ Server: Apache/2.2.3 (CentOS) Set-Cookie: BWSESSION=2ishv84g637mrp7o07hd8829f6; path='.$gBitSystem->getConfig( 'cookie_path', '/' ).'; domain='.$gBitSystem->getConfig( 'cookie_domain' ).' Set-Cookie: <strong>'.$gBitUser->getSiteCookieName().'=2ishv84g637mrp7o07hd8829f6M</strong>; path=/ </code>', - ), -); + ], +]; -$gApiHelp['User Authentication'] = array( - 'Authentication' => array( +$gApiHelp['User Authentication'] = [ + 'Authentication' => [ 'method' => 'POST '.API_PKG_URI.'users/authenticate', 'help' => 'Authentication is performed once per session (application launch) using the standard <a href="http://en.wikipedia.org/wiki/Basic_access_authentication">HTTP Basic Authentication</a>. Once authentication is successful, a cookie named "'.$gBitUser->getSiteCookieName().'" will be returned for the user. That cookie can be included for every request which will automatically identify the user for the lifetime of the cookie. For stateless (without session) applications, you can simply include the <strong>Authorization</strong> header with the username and password for every request.', - 'parameters' => array( + 'parameters' => [ 'Authorization: Basic <em>base64encode(username + ":" + password)</em>' => 'HTTP Basic authenictaion sent via HTTP headers. Most frameworks will handle this for you automatically with a simple call. For example AFNetworking <a href=http://engineering.gowalla.com/AFNetworking/Classes/AFHTTPClient.html">::setAuthorizationHeaderWithUsername</a>', - ), - ), - 'Receivable Properties' => array( + ], + ], + 'Receivable Properties' => [ 'help' => 'In addition to the sendable properties listed above, these parameters will be sent by the host with information about the user.', - 'parameters' => array( - 'last_login' => '', - 'current_login' => '', - 'registration_date' => '', - 'is_registered' => '', - 'portrait_url' => '', - 'avatar_url' => '', - 'logo_url' => '', - 'email' => '', - 'login' => '', - 'real_name' => '', - 'user' => '', - ), - ), - 'Examples' => array( + 'parameters' => [ + 'last_login' => '', + 'current_login' => '', + 'registration_date' => '', + 'is_registered' => '', + 'portrait_url' => '', + 'avatar_url' => '', + 'logo_url' => '', + 'email' => '', + 'login' => '', + 'real_name' => '', + 'user' => '', + ], + ], + 'Examples' => [ 'help' => 'The following is a command-line test of user authentication. Notice the Set-Cookie values returned. Your client should store these values and send them for all subsequent requests.', 'code' => '<code>COMMAND: curl -i -u "test@example.com:s3cr3t" --header \'API: API consumer_key="bad6ed95edfd983c8cb58cd397a242a2f83cd80c"\' -X GET '.API_PKG_URI.'users/authenticate @@ -87,5 +87,5 @@ Set-Cookie: <strong>'.$gBitUser->getSiteCookieName().'=2ishv84g637mrp7o07hd8829f X-Powered-By: PHP/5.3.1 {"user_id":"1002","content_id":"1043","email":"text@example.com","login":"test","real_name":"Test User","provpass":null,"provpass_expires":null,"default_group_id":null,"last_login":"1342734606","current_login":"1342734606","registration_date":"1341806036","challenge":null,"pass_due":"1429048188","created":null,"avatar_attachment_id":null,"portrait_attachment_id":null,"logo_attachment_id":null,"avatar_file_name":null,"avatar_mime_type":null,"portrait_file_name":null,"portrait_mime_type":null,"logo_file_name":null,"logo_mime_type":null,"uu_user_id":"1002","user":"text","valid":true,"is_registered":true,"portrait_path":null,"portrait_url":null,"avatar_path":null,"avatar_url":null,"logo_path":null,"logo_url":null,"first_name":"Test User"}</code>', - ), -); + ], +]; diff --git a/admin/assign_user.php b/admin/assign_user.php index 80757b3..696a445 100755 --- a/admin/assign_user.php +++ b/admin/assign_user.php @@ -11,7 +11,7 @@ use Bitweaver\KernelTools; $gBitSystem->verifyPermission( 'p_users_admin' ); -if (!$gBitUser->userExists( array( 'user_id' => $_REQUEST["assign_user"] ) ) ) { +if (!$gBitUser->userExists( [ 'user_id' => $_REQUEST["assign_user"] ] ) ) { $gBitSystem->fatalError( KernelTools::tra( "User doesnt exist" )); } @@ -39,17 +39,15 @@ if( isset( $_REQUEST["action"] ) ) { } $gBitSmarty->assign( 'assignUser', $assignUser ); -$listHash = array( 'sort_mode' => 'group_name_asc' ); +$listHash = [ 'sort_mode' => 'group_name_asc' ]; $gBitSmarty->assign('groups', $gBitUser->getAllGroups( $listHash )); $gBitSystem->setBrowserTitle( 'Edit User: '.$assignUser->mUsername ); if($gBitSystem->isPackageActive("quota")) { - include(QUOTA_PKG_INCLUDE_PATH.'quota_inc.php'); + include(QUOTA_PKG_INCLUDE_PATH.'quota_inc.php'); } - - // Display the template -$gBitSystem->display( 'bitpackage:users/admin_assign_user.tpl', null, array( 'display_mode' => 'admin' )); +$gBitSystem->display( 'bitpackage:users/admin_assign_user.tpl', null, [ 'display_mode' => 'admin' ]); ?> diff --git a/admin/edit_group.php b/admin/edit_group.php index fe5bcec..1c1c0ee 100755 --- a/admin/edit_group.php +++ b/admin/edit_group.php @@ -18,10 +18,10 @@ if( count( $_GET ) > 2 || count( $_POST ) > 2 ) { } if( !empty( $_REQUEST['group_id'] ) ) { - $permListHash = array( + $permListHash = [ 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : null, 'package' => !empty( $_REQUEST['package'] ) ? $_REQUEST['package'] : null, - ); + ]; $allPerms = $gBitUser->getGroupPermissions( $permListHash ); } @@ -34,11 +34,11 @@ if( !empty( $_REQUEST["cancel"] ) ) { } else { $gBitSystem->setBrowserTitle( KernelTools::tra( 'Confirm Batch Group Assignment' ) ); $formHash['batch_assign'] = $_REQUEST["batch_assign"]; - $msgHash = array( + $msgHash = [ 'label' => KernelTools::tra( 'Batch Assign Users to Group' ), 'confirm_item' => $groupInfo['group_name'], 'warning' => KernelTools::tra( 'This will assign every user on the site to the group' ).' <strong>'.$groupInfo['group_name'].'</strong>', - ); + ]; $gBitSystem->confirmDialog( $formHash,$msgHash ); } } elseif( isset($_REQUEST["members"] ) ) { @@ -81,10 +81,10 @@ if( !empty( $_REQUEST["cancel"] ) ) { unset( $_REQUEST['group_id'] ); } else { $gBitSystem->setBrowserTitle( KernelTools::tra( 'Delete group') ); - $msgHash = array( + $msgHash = [ 'confirm_item' => KernelTools::tra( 'Are you sure you want to permantly remove the group' )." <strong>$groupInfo[group_name]</strong>".'?', 'warning' => KernelTools::tra( 'This cannot be undone.' ), - ); + ]; $gBitSystem->confirmDialog( $formHash,$msgHash ); } // $mid = 'bitpackage:users/admin_groups_list.tpl'; @@ -117,7 +117,7 @@ if( !empty( $_REQUEST['group_id'] ) || (!empty( $_REQUEST["action"] ) && $_REQUE $gBitSmarty->assign( 'permPackages', $permPackages ); // get grouplist separately from the $users stuff to avoid splitting of data due to pagination - $listHash = array( 'sort_mode' => 'group_name_asc' ); + $listHash = [ 'sort_mode' => 'group_name_asc' ]; /* // get content and pass it on to the template @@ -128,14 +128,14 @@ if( !empty( $_REQUEST['group_id'] ) || (!empty( $_REQUEST["action"] ) && $_REQUE $gBitSmarty->assign( 'contentList', $cList ); $gBitSmarty->assign( 'contentSelect', $contentSelect ); */ - $contentTypes = array( '' => KernelTools::tra( 'All Content' ) ); + $contentTypes = [ '' => KernelTools::tra( 'All Content' ) ]; foreach( $gLibertySystem->mContentTypes as $cType ) { $contentTypes[$cType['content_type_guid']] = $gLibertySystem->getContentTypeName( $cType['content_type_guid'] ); } $gBitSmarty->assign( 'contentTypes', $contentTypes ); } else { // get grouplist separately from the $users stuff to avoid splitting of data due to pagination - $listHash = array( 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : 'group_name_asc' ); + $listHash = [ 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : 'group_name_asc' ]; } $gBitSmarty->assign('groupList', $gBitUser->getAllGroups( $listHash )); @@ -162,5 +162,5 @@ $gBitSmarty->assign('successMsg',$successMsg); $gBitSmarty->assign('errorMsg',$errorMsg); // Display the template for group administration -$gBitSystem->display( $mid , null, array( 'display_mode' => 'edit' )); +$gBitSystem->display( $mid , null, [ 'display_mode' => 'edit' ]); ?> diff --git a/admin/edit_role.php b/admin/edit_role.php index f5029d2..5de2f10 100755 --- a/admin/edit_role.php +++ b/admin/edit_role.php @@ -35,11 +35,11 @@ if( !empty( $_REQUEST["cancel"] ) ) { } else { $gBitSystem->setBrowserTitle( KernelTools::tra( 'Confirm Batch Role Assignment' ) ); $formHash['batch_assign'] = $_REQUEST["batch_assign"]; - $msgHash = array( + $msgHash = [ 'label' => KernelTools::tra( 'Batch Assign Users to Role' ), 'confirm_item' => $roleInfo['role_name'], 'warning' => KernelTools::tra( 'This will assign every user on the site to the role' ).' <strong>'.$roleInfo['role_name'].'</strong>', - ); + ]; $gBitSystem->confirmDialog( $formHash,$msgHash ); } } elseif( isset($_REQUEST["members"] ) ) { @@ -96,10 +96,10 @@ if( !empty( $_REQUEST["cancel"] ) ) { unset( $_REQUEST['role_id'] ); } else { $gBitSystem->setBrowserTitle( KernelTools::tra('Delete role') ); - $msgHash = array( + $msgHash = [ 'confirm_item' => KernelTools::tra( 'Are you sure you want to remove the role?' ), 'warning' => KernelTools::tra( 'This will permentally delete the role' )." <strong>$roleInfo[role_name]</strong>", - ); + ]; $gBitSystem->confirmDialog( $formHash,$msgHash ); } } elseif ($_REQUEST["action"] == 'remove') { diff --git a/admin/index.php b/admin/index.php index d78c8a7..b2ea0af 100755 --- a/admin/index.php +++ b/admin/index.php @@ -5,6 +5,7 @@ // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See http://www.gnu.org/copyleft/lesser.html for details. // Initialization namespace Bitweaver\Users; + use Bitweaver\BitBase; use Bitweaver\KernelTools; @@ -46,7 +47,7 @@ if( isset($_REQUEST["newuser"] ) ) { if ( !isset( $feedback['error'] ) ){ $feedback['error'] = []; } - $feedback['error'] = array_merge( $feedback['error'], $gBitUser->mErrors ); + $feedback['error'] = array_merge( $feedback['error'], $gBitUser->mErrors ); } } else { $gBitSystem->setBrowserTitle( 'Assume User Identity' ); @@ -79,7 +80,7 @@ if( isset( $_REQUEST["action"] ) ) { fputcsv( $fp, $hash ); } fclose( $fp ); - header( "Content-Type: text/csv" ); + header( "Content-Type: text/csv" ); header('Content-disposition: attachment;filename='.$gBitSystem->getConfig('site_title', 'Site').'-users-export-'.date('Y-m-d_Hi').'.csv'); readfile( $file ); flush(); @@ -100,14 +101,14 @@ if( isset( $_REQUEST["action"] ) ) { if( !empty( $delUsers ) ) { $feedback['success'][] = KernelTools::tra( 'Users deleted' ).": <ul>$delUsers</ul>"; - } + } if( !empty( $errDelUsers ) ) { $feedback['error'][] = KernelTools::tra( 'Users not deleted' ).": <ul>$errDelUsers</ul>"; } } else { foreach( $_REQUEST['batch_user_ids'] as $uid ) { - $formHash['input'][] = ( $userInfo = $gBitUser->getUserInfo( [ 'user_id' => $uid ] ) ) - ? '<input type="hidden" name="batch_user_ids[]" value="' . $uid . '"/>' . "{$userInfo['real_name']} ({$userInfo['login']})<br/><{$userInfo['email']}>" + $formHash['input'][] = ( $userInfo = $gBitUser->getUserInfo( [ 'user_id' => $uid ] ) ) + ? '<input type="hidden" name="batch_user_ids[]" value="' . $uid . '"/>' . "{$userInfo['real_name']} ({$userInfo['login']})<br/><{$userInfo['email']}>" : '<span class="error"/>' . $uid . ' ' . KernelTools::tra( 'not found' ) . '</span>'; } $formHash['input'][] = "<input type='checkbox' name='delete_user_content' value='all' checked='checked'/> ".KernelTools::tra( 'Delete all content created by this user' ); diff --git a/admin/permissions.php b/admin/permissions.php index 2f6629f..3f3075d 100755 --- a/admin/permissions.php +++ b/admin/permissions.php @@ -7,10 +7,10 @@ $gBitSystem->verifyPermission( 'p_admin' ); $feedback = []; // get a list of all groups and their permissions -$listHash = array( +$listHash = [ 'only_root_groups' => true, - 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : 'group_name_asc' -); + 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : 'group_name_asc', +]; $allGroups = $gBitUser->getAllGroups( $listHash ); $allPerms = $gBitUser->getGroupPermissions( $_REQUEST ); @@ -44,5 +44,5 @@ $gBitSmarty->assign( 'permPackages', $gBitUser->getPermissionPackages() ); $gBitSmarty->assign( 'feedback', $feedback ); $gBitSmarty->assign( 'contentWithPermissions', LibertyContent::getContentWithPermissionsList() ); -$gBitSystem->display( 'bitpackage:users/admin_permissions.tpl', KernelTools::tra( 'Permission Maintenance' ), array( 'display_mode' => 'admin' )); +$gBitSystem->display( 'bitpackage:users/admin_permissions.tpl', KernelTools::tra( 'Permission Maintenance' ), [ 'display_mode' => 'admin' ]); ?> diff --git a/admin/role_permissions.php b/admin/role_permissions.php index c50dd8b..001323f 100755 --- a/admin/role_permissions.php +++ b/admin/role_permissions.php @@ -9,7 +9,7 @@ $feedback = []; // get a list of all roles and their permissions $listHash = [ 'only_root_roles' => true, - 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : 'role_name_asc' + 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : 'role_name_asc', ]; $allRoles = $gBitUser->getAllRoles( $listHash ); $allPerms = $gBitUser->getRolePermissions( $_REQUEST ); diff --git a/admin/schema_inc.php b/admin/schema_inc.php index a9ff140..d96e5a0 100644 --- a/admin/schema_inc.php +++ b/admin/schema_inc.php @@ -1,7 +1,7 @@ <?php global $gBitInstaller; -$tables = (defined( 'ROLE_MODEL' )) +$tables = (defined( 'ROLE_MODEL' )) ? [ 'users_users' => " @@ -270,25 +270,24 @@ $gBitInstaller->registerUserPermissions( USERS_PKG_NAME, [ //array(USERS_PKG_NAME,'usermenu','n'), ] ); -$team_indices = (defined( 'ROLE_MODEL' )) +$team_indices = (defined( 'ROLE_MODEL' )) ? [ 'users_roles_user_idx' => [ 'table' => 'users_roles', 'cols' => 'user_id', 'opts' => null ], 'users_roles_user_name_idx' => [ 'table' => 'users_roles', 'cols' => 'user_id,role_name', 'opts' => [ 'UNIQUE' ] ], 'users_role_perm_role_idx' => [ 'table' => 'users_role_permissions', 'cols' => 'role_id', 'opts' => null ], 'users_role_perm_perm_idx' => [ 'table' => 'users_role_permissions', 'cols' => 'perm_name', 'opts' => null ], 'users_roles_map_user_idx' => [ 'table' => 'users_roles_map', 'cols' => 'user_id', 'opts' => null ], - 'users_roles_map_role_idx' => [ 'table' => 'users_roles_map', 'cols' => 'role_id', 'opts' => null ] - ] + 'users_roles_map_role_idx' => [ 'table' => 'users_roles_map', 'cols' => 'role_id', 'opts' => null ], + ] : [ 'users_groups_user_idx' => [ 'table' => 'users_groups', 'cols' => 'user_id', 'opts' => NULL ], 'users_groups_user_name_idx' => [ 'table' => 'users_groups', 'cols' => 'user_id,group_name', 'opts' => [ 'UNIQUE' ] ], 'users_group_perm_group_idx' => [ 'table' => 'users_group_permissions', 'cols' => 'group_id', 'opts' => null ], 'users_group_perm_perm_idx' => [ 'table' => 'users_group_permissions', 'cols' => 'perm_name', 'opts' => null ], 'users_groups_map_user_idx' => [ 'table' => 'users_groups_map', 'cols' => 'user_id', 'opts' => null ], - 'users_groups_map_group_idx' => [ 'table' => 'users_groups_map', 'cols' => 'group_id', 'opts' => null ] + 'users_groups_map_group_idx' => [ 'table' => 'users_groups_map', 'cols' => 'group_id', 'opts' => null ], ]; - $indices = [ ...$team_indices, 'users_users_email_idx' => [ 'table' => 'users_users', 'cols' => 'email', 'opts' => [ 'UNIQUE' ] ], 'users_auth_user_idx' => [ 'table' => 'users_auth_map', 'cols' => 'user_id', 'opts' => null ], @@ -354,8 +353,8 @@ $gBitInstaller->registerUserPermissions( USERS_PKG_NAME, [ // Package Requirements $gBitInstaller->registerRequirements( USERS_PKG_NAME, [ - 'liberty' => array( 'min' => '5.0.0' ), - 'kernel' => array( 'min' => '5.0.0' ), - 'themes' => array( 'min' => '5.0.0' ), - 'languages' => array( 'min' => '5.0.0' ), + 'liberty' => [ 'min' => '5.0.0' ], + 'kernel' => [ 'min' => '5.0.0' ], + 'themes' => [ 'min' => '5.0.0' ], + 'languages' => [ 'min' => '5.0.0' ], ]); diff --git a/admin/upgrade_inc.php b/admin/upgrade_inc.php index 089f23b..7cad315 100755 --- a/admin/upgrade_inc.php +++ b/admin/upgrade_inc.php @@ -1,31 +1,29 @@ <?php global $gBitSystem, $gUpgradeFrom, $gUpgradeTo, $gBitDb; -$upgrades = array( +$upgrades = [ +'TIKIWIKI19' => [ + 'TIKIWIKI18' => [ -'TIKIWIKI19' => array ( - 'TIKIWIKI18' => array ( +[ 'DATADICT' => [ +[ 'ALTER' => [ + 'tiki_user_tasks' => [ + 'title' => [ '`title`', 'VARCHAR(250)' ], + 'description' => [ '`description`', 'X' ], + ], +]], +[ 'RENAMECOLUMN' => [ + 'tiki_pages' => [ '`created`' => '`date` I8' ], +]], +]], -array( 'DATADICT' => array( -array( 'ALTER' => array( - 'tiki_user_tasks' => array( - 'title' => array( '`title`', 'VARCHAR(250)' ), - 'description' => array( '`description`', 'X' ), - ), -)), -array( 'RENAMECOLUMN' => array( - 'tiki_pages' => array( '`created`' => '`date` I8' ), -)), -)), - -array( 'QUERY' => - array( 'SQL92' => array( +[ 'QUERY' => + [ 'SQL92' => [ "UPDATE `".BIT_DB_PREFIX."tiki_user_tasks` SET `title`= (SELECT `title` FROM `".BIT_DB_PREFIX."tiki_user_tasks_history` WHERE `".BIT_DB_PREFIX."tiki_user_tasks`.`taskId`=`belongs_to`)", "UPDATE `".BIT_DB_PREFIX."tiki_user_tasks` SET `description`= (SELECT `description` FROM `".BIT_DB_PREFIX."tiki_user_tasks_history` WHERE `".BIT_DB_PREFIX."tiki_user_tasks`.`taskId`=`belongs_to`)", - ) -)), - + ], +], ], /* @@ -44,8 +42,8 @@ CREATE TABLE tiki_user_tasks_history ( completed integer(14) DEFAULT NULL, -- date of the completation if it is null it is not yet completed deleted integer(14) DEFAULT NULL, -- date of the deleteation it it is null it is not deleted status char(1) DEFAULT NULL, -- null := waiting, - -- o := open / in progress, - -- c := completed -> (percentage = 100) + -- o := open / in progress, + -- c := completed -> (percentage = 100) percentage int(4) DEFAULT NULL, accepted_creator char(1) DEFAULT NULL, -- y - yes, n - no, null - waiting accepted_user char(1) DEFAULT NULL, -- y - yes, n - no, null - waiting @@ -64,35 +62,32 @@ ALTER TABLE tiki_user_tasks ADD completed int(14) default NULL; ALTER TABLE tiki_user_tasks ADD percentage int(4) default NULL; */ - ) -), - - - + ], +], -'BONNIE' => array( - 'BWR1' => array( +'BONNIE' => [ + 'BWR1' => [ // STEP 1 -array( 'QUERY' => - array( 'MYSQL' => array( +[ 'QUERY' => + [ 'MYSQL' => [ "ALTER TABLE `".BIT_DB_PREFIX."tiki_user_preferences` DROP PRIMARY KEY", "ALTER TABLE `".BIT_DB_PREFIX."users_usergroups` DROP PRIMARY KEY", "ALTER TABLE `".BIT_DB_PREFIX."users_grouppermissions` DROP PRIMARY KEY", "ALTER TABLE `".BIT_DB_PREFIX."tiki_group_inclusion` DROP PRIMARY KEY", "ALTER TABLE `".BIT_DB_PREFIX."tiki_user_watches` DROP PRIMARY KEY", - )), -), + ]], +], // STEP 1 -array( 'DATADICT' => array( -array( 'RENAMETABLE' => array( +[ 'DATADICT' => [ +[ 'RENAMETABLE' => [ 'users_usergroups' => 'users_groups_map', 'tiki_group_inclusion' => 'users_groups_inclusion', - ) -), -array( 'RENAMECOLUMN' => array( - 'users_users' => array( + ], +], +[ 'RENAMECOLUMN' => [ + 'users_users' => [ '`userId`' => '`user_id` I4', '`lastLogin`' => '`last_login` I8', '`currentLogin`' => '`current_login` I8', @@ -103,115 +98,114 @@ array( 'RENAMECOLUMN' => array( // '`avatarData`' => '`avatar_data`', // '`avatarLibName`' => '`avatar_lib_name`', // '`avatarType`' => '`avatar_type`', - ), - 'users_groups_map' => array( - '`userId`' => '`user_id` I4' - ), - 'tiki_semaphores' => array( '`semName`' => '`sem_name` C(250)', - '`timestamp`' => '`created` I8' ), - 'tiki_user_preferences' => array( - '`prefName`' => '`pref_name` C(40)' - ), + ], + 'users_groups_map' => [ + '`userId`' => '`user_id` I4', + ], + 'tiki_semaphores' => [ '`semName`' => '`sem_name` C(250)', + '`timestamp`' => '`created` I8', ], + 'tiki_user_preferences' => [ + '`prefName`' => '`pref_name` C(40)', + ], // 'users_groups_inclusion' => array('`groupName`', '`group_name`'), // 'users_groups_inclusion' => array('`includeGroup`', '`include_group`'), - 'tiki_user_bookmarks_folders' => array( + 'tiki_user_bookmarks_folders' => [ '`folderId`' => '`folder_id` I4', '`parentId`' => '`parent_id` I4', - ), - 'tiki_user_bookmarks_urls' => array( + ], + 'tiki_user_bookmarks_urls' => [ '`urlId`' => '`url_id` I4', '`lastUpdated`' => '`last_updated` I8', '`folderId`' => '`folder_id` I4', - ), - 'tiki_user_menus' => array( + ], + 'tiki_user_menus' => [ '`menuId`' => '`menu_id` I4', - ), - 'users_grouppermissions' => array( + ], + 'users_grouppermissions' => [ '`permName`' => '`perm_name` C(30)', - ), - 'users_groups' => array( + ], + 'users_groups' => [ '`groupName`' => '`group_name` C(30)', '`groupDesc`' => '`group_desc` C(255)', '`groupHome`' => '`group_home` C(255)', - ), - 'users_groups_map' => array( - '`userId`' => '`user_id` I4' - ), - 'users_objectpermissions' => array( + ], + 'users_groups_map' => [ + '`userId`' => '`user_id` I4', + ], + 'users_objectpermissions' => [ '`permName`' => '`perm_name` C(30)', '`objectType`' => '`object_type` C(20)', - ), - 'users_permissions' => array( + ], + 'users_permissions' => [ '`permName`' => '`perm_name` C(30)', '`permDesc`' => '`perm_desc` C(250)', '`type`' => '`package` C(100)', - ), - 'tiki_userfiles' => array( + ], + 'tiki_userfiles' => [ '`fileId`' => '`file_id` I4', '`isFile`' => '`is_file` C(1)', - ), - 'tiki_user_tasks' => array( + ], + 'tiki_user_tasks' => [ '`taskId`' => '`task_id` I4' , - ) -)), + ], +]], -array( 'ALTER' => array( - 'users_users' => array( - 'content_id' => array( '`content_id`', 'I4' ), - 'default_group_id' => array( '`default_group_id`', 'I4' ), - 'real_name' => array( '`real_name`', 'VARCHAR(64)'), - 'avatar_attachment_id' => array( '`avatar_attachment_id`', 'I4' ), - 'portrait_attachment_id' => array( '`portrait_attachment_id`', 'I4' ), - 'logo_attachment_id' => array( '`logo_attachment_id`', 'I4' ), +[ 'ALTER' => [ + 'users_users' => [ + 'content_id' => [ '`content_id`', 'I4' ], + 'default_group_id' => [ '`default_group_id`', 'I4' ], + 'real_name' => [ '`real_name`', 'VARCHAR(64)'], + 'avatar_attachment_id' => [ '`avatar_attachment_id`', 'I4' ], + 'portrait_attachment_id' => [ '`portrait_attachment_id`', 'I4' ], + 'logo_attachment_id' => [ '`logo_attachment_id`', 'I4' ], - ), - 'tiki_semaphores' => array( - 'user_id' => array( '`user_id`', 'I4' ), - ), - 'tiki_sessions' => array( - 'user_id' => array( '`user_id`', 'I4' ), - 'session_id' => array( '`session_id`', 'VARCHAR(32)' ), - ), - 'tiki_user_bookmarks_folders' => array( - 'user_id' => array( '`user_id`', 'I4' ), - ), - 'tiki_user_bookmarks_urls' => array( - 'user_id' => array( '`user_id`', 'I4' ), - ), - 'tiki_user_menus' => array( - 'user_id' => array( '`user_id`', 'I4' ), - ), - 'tiki_user_preferences' => array( - 'user_id' => array( '`user_id`', 'I4' ), - ), - 'tiki_user_tasks' => array( - 'user_id' => array( '`user_id`', 'I4' ), - ), - 'tiki_user_watches' => array( - 'user_id' => array( '`user_id`', 'I4' ), - ), - 'users_groups' => array( - 'group_id' => array( '`group_id`', 'I4' ), - 'user_id' => array( '`user_id`', 'I4' ), - ), - 'users_grouppermissions' => array( - 'group_id' => array( '`group_id`', 'I4' ), - ), - 'users_objectpermissions' => array( - 'group_id' => array( '`group_id`', 'I4' ), - 'object_id' => array( '`object_id`', 'I4' ), - ), - 'users_groups_map' => array( - 'group_id' => array( '`group_id`', 'I4' ), - ), - 'users_groups_inclusion' => array( - 'group_id' => array( '`group_id`', 'I4' ), - 'include_group_id' => array( '`include_group_id`', 'I4' ), - ), -)), + ], + 'tiki_semaphores' => [ + 'user_id' => [ '`user_id`', 'I4' ], + ], + 'tiki_sessions' => [ + 'user_id' => [ '`user_id`', 'I4' ], + 'session_id' => [ '`session_id`', 'VARCHAR(32)' ], + ], + 'tiki_user_bookmarks_folders' => [ + 'user_id' => [ '`user_id`', 'I4' ], + ], + 'tiki_user_bookmarks_urls' => [ + 'user_id' => [ '`user_id`', 'I4' ], + ], + 'tiki_user_menus' => [ + 'user_id' => [ '`user_id`', 'I4' ], + ], + 'tiki_user_preferences' => [ + 'user_id' => [ '`user_id`', 'I4' ], + ], + 'tiki_user_tasks' => [ + 'user_id' => [ '`user_id`', 'I4' ], + ], + 'tiki_user_watches' => [ + 'user_id' => [ '`user_id`', 'I4' ], + ], + 'users_groups' => [ + 'group_id' => [ '`group_id`', 'I4' ], + 'user_id' => [ '`user_id`', 'I4' ], + ], + 'users_grouppermissions' => [ + 'group_id' => [ '`group_id`', 'I4' ], + ], + 'users_objectpermissions' => [ + 'group_id' => [ '`group_id`', 'I4' ], + 'object_id' => [ '`object_id`', 'I4' ], + ], + 'users_groups_map' => [ + 'group_id' => [ '`group_id`', 'I4' ], + ], + 'users_groups_inclusion' => [ + 'group_id' => [ '`group_id`', 'I4' ], + 'include_group_id' => [ '`include_group_id`', 'I4' ], + ], +]], - -array( 'CREATE' => array ( +[ 'CREATE' => [ 'users_cnxn' => " user_id I4, cookie C(64), @@ -224,12 +218,12 @@ array( 'CREATE' => array ( CONSTRAINTS ', CONSTRAINT `users_cnxn_user_ref` FOREIGN KEY (`user_id`) REFERENCES `".BIT_DB_PREFIX."users_users` (`user_id`)' ", -)), +]], -)), +]], // STEP 2 -array( 'PHP' => ' +[ 'PHP' => ' global $gBitSystem, $gBitDb; $max = $gBitDb->GetOne( "SELECT MAX(user_id) FROM `'.BIT_DB_PREFIX.'users_users`" ); $gBitSystem->mDb->CreateSequence( "users_users_user_id_seq", $max + 1 ); @@ -241,23 +235,20 @@ array( 'PHP' => ' $id = $gBitDb->GenID( "users_groups_id_seq" ); $gBitDb->query( "UPDATE `'.BIT_DB_PREFIX.'users_groups` SET group_id=? WHERE group_name=?", array( $id, $name ) ); } -' ), +' ], // STEP 3 -array( 'QUERY' => - array( 'SQL92' => array( +[ 'QUERY' => + [ 'SQL92' => [ "UPDATE `".BIT_DB_PREFIX."users_grouppermissions` SET `perm_name`=replace(`perm_name`,'tiki_','bit_')", "UPDATE `".BIT_DB_PREFIX."users_permissions` SET `perm_name`=replace(`perm_name`,'tiki_','bit_')", "UPDATE `".BIT_DB_PREFIX."users_objectpermissions` SET `perm_name`=replace(`perm_name`,'tiki_','bit_')", - - - "INSERT INTO `".BIT_DB_PREFIX."users_users` (`real_name`, `login`, `email`, `user_id` ) VALUES ('Anonymous', 'anonymous', 'anonymous@localhost', ".ANONYMOUS_USER_ID.")", // TikiWiki assigns the creator user foreign key as 'system' even if there is now 'system' user - XOXO spiderr // In order for all pages to upgrade, there must be at least an 'admin' and 'system' user - "INSERT INTO `".BIT_DB_PREFIX."users_users` (`real_name`, `login`, `email`, `user_id` ) VALUES ('Administrator', 'admin', 'root@localhost', ".ROOT_USER_ID.")", - "INSERT INTO `".BIT_DB_PREFIX."users_users` (`real_name`, `login`, `email` ) VALUES ('System', 'system', 'system@localhost' )", + "INSERT INTO `".BIT_DB_PREFIX."users_users` (`real_name`, `login`, `email`, `user_id` ) VALUES ('Administrator', 'admin', 'root@localhost', ".ROOT_USER_ID.")", + "INSERT INTO `".BIT_DB_PREFIX."users_users` (`real_name`, `login`, `email` ) VALUES ('System', 'system', 'system@localhost' )", "UPDATE `".BIT_DB_PREFIX."tiki_semaphores` SET `user_id`=(SELECT `user_id` FROM `".BIT_DB_PREFIX."users_users` WHERE `".BIT_DB_PREFIX."users_users`.`login`=`".BIT_DB_PREFIX."tiki_semaphores`.`user`)", "UPDATE `".BIT_DB_PREFIX."tiki_semaphores` SET `user_id`=(SELECT `user_id` FROM `".BIT_DB_PREFIX."users_users` WHERE `".BIT_DB_PREFIX."users_users`.`login`=`".BIT_DB_PREFIX."tiki_semaphores`.`user`)", "UPDATE `".BIT_DB_PREFIX."tiki_sessions` SET `user_id`=(SELECT `user_id` FROM `".BIT_DB_PREFIX."users_users` WHERE `".BIT_DB_PREFIX."users_users`.`login`=`".BIT_DB_PREFIX."tiki_sessions`.`user`)", @@ -278,37 +269,36 @@ array( 'QUERY' => "update `".BIT_DB_PREFIX."tiki_user_watches` set `type` = 'bitpage' where `type` = 'Wiki page'", "update `".BIT_DB_PREFIX."tiki_user_watches` set `type` = 'bitpage' where `type` = 'Wiki-Seite'", - - ), -)), + ], +], ], // STEP 4 -array( 'DATADICT' => array( -array( 'DROPCOLUMN' => array( - 'tiki_semaphores' => array( '`user`' ), - 'tiki_sessions' => array( '`user`', '`sessionId`' ), - 'users_groups_map' => array( '`groupName`' ), - 'users_grouppermissions' => array( '`groupName`' ), - 'users_objectpermissions' => array( '`groupName`' ), - 'users_groups_inclusion' => array( '`groupName`' ), - 'tiki_user_bookmarks_folders' => array( '`user`' ), - 'tiki_user_bookmarks_urls' => array( '`user`' ), - 'tiki_user_menus' => array( '`user`' ), - 'tiki_user_preferences' => array( '`user`' ), - 'tiki_user_tasks' => array( '`user`' ), - 'tiki_user_watches' => array( '`user`' ), - )), -)), +[ 'DATADICT' => [ +[ 'DROPCOLUMN' => [ + 'tiki_semaphores' => [ '`user`' ], + 'tiki_sessions' => [ '`user`', '`sessionId`' ], + 'users_groups_map' => [ '`groupName`' ], + 'users_grouppermissions' => [ '`groupName`' ], + 'users_objectpermissions' => [ '`groupName`' ], + 'users_groups_inclusion' => [ '`groupName`' ], + 'tiki_user_bookmarks_folders' => [ '`user`' ], + 'tiki_user_bookmarks_urls' => [ '`user`' ], + 'tiki_user_menus' => [ '`user`' ], + 'tiki_user_preferences' => [ '`user`' ], + 'tiki_user_tasks' => [ '`user`' ], + 'tiki_user_watches' => [ '`user`' ], + ]], +]], // STEP 5 -array( 'QUERY' => - array( 'SQL92' => array( +[ 'QUERY' => + [ 'SQL92' => [ "INSERT INTO `".BIT_DB_PREFIX."users_groups_map` (`group_id`, `user_id` ) VALUES ( -1, ".ANONYMOUS_USER_ID." )", - ), -)), + ], +], ], // STEP 2 -array( 'PHP' => ' +[ 'PHP' => ' global $gBitSystem, $gBitDb; $adminGroup = $gBitDb->GetOne( "SELECT `group_id` FROM `'.BIT_DB_PREFIX.'users_grouppermissions` where perm_name=\'bit_p_admin\'" ); if( empty( $adminGroup ) ) { @@ -320,70 +310,68 @@ array( 'PHP' => ' $gBitDb->query( "INSERT INTO `'.BIT_DB_PREFIX.'users_groups_map` (`group_id`,`user_id`) VALUES ( $adminGroup, '.ROOT_USER_ID.' )" ); $gBitDb->query( "INSERT INTO `'.BIT_DB_PREFIX.'users_grouppermissions` (`perm_name`, `group_id`) VALUES( \'bit_p_admin\', $adminGroup )" ); } -' ), +' ], // STEP 4 -array( 'DATADICT' => array( -array( 'CREATEINDEX' => array( - 'tiki_sema_user_idx' => array( 'tiki_semaphores', '`user_id`', [] ), - 'tiki_user_prefs_idx' => array( 'tiki_user_preferences', '`user_id`', [] ), - 'tiki_user_prefs_un_idx' => array( 'tiki_user_preferences', '`user_id`,`pref_name`', array( 'UNIQUE' ) ), - 'users_groups_map_user_idx' => array( 'users_groups_map', '`user_id`', [] ), - 'users_groups_map_group_idx' => array( 'users_groups_map', '`group_id`', [] ), - 'users_groups_map_ug_idx' => array( 'users_groups_map', '`user_id`,`group_id`', array( 'UNIQUE' ) ), - 'users_groupperms_group_idx' => array( 'users_grouppermissions', '`group_id`', [] ), - 'users_groupperms_group_idx' => array( 'users_grouppermissions', '`group_id`,`perm_name`', array( 'UNIQUE' ) ), - 'users_groups_inc_group_idx' => array( 'users_groups_inclusion', '`group_id`', [] ), - 'users_groups_inc_gi_idx' => array( 'users_groups_inclusion', '`group_id`,`include_group_id`', array( 'UNIQUE' ) ), - 'users_groups_gi_idx' => array( 'users_groups', '`group_id`', array('UNIQUE') ), - )), -)), - +[ 'DATADICT' => [ +[ 'CREATEINDEX' => [ + 'tiki_sema_user_idx' => [ 'tiki_semaphores', '`user_id`', [] ], + 'tiki_user_prefs_idx' => [ 'tiki_user_preferences', '`user_id`', [] ], + 'tiki_user_prefs_un_idx' => [ 'tiki_user_preferences', '`user_id`,`pref_name`', [ 'UNIQUE' ] ], + 'users_groups_map_user_idx' => [ 'users_groups_map', '`user_id`', [] ], + 'users_groups_map_group_idx' => [ 'users_groups_map', '`group_id`', [] ], + 'users_groups_map_ug_idx' => [ 'users_groups_map', '`user_id`,`group_id`', [ 'UNIQUE' ] ], + 'users_groupperms_group_idx' => [ 'users_grouppermissions', '`group_id`', [] ], + 'users_groupperms_group_idx' => [ 'users_grouppermissions', '`group_id`,`perm_name`', [ 'UNIQUE' ] ], + 'users_groups_inc_group_idx' => [ 'users_groups_inclusion', '`group_id`', [] ], + 'users_groups_inc_gi_idx' => [ 'users_groups_inclusion', '`group_id`,`include_group_id`', [ 'UNIQUE' ] ], + 'users_groups_gi_idx' => [ 'users_groups', '`group_id`', ['UNIQUE'] ], + ]], +]], + ], +], - ) -), - -'BWR1' => array( - 'BWR2' => array( +'BWR1' => [ + 'BWR2' => [ // STEP 1 -array( 'DATADICT' => array( - array( 'CREATE' => array ( +[ 'DATADICT' => [ + [ 'CREATE' => [ 'users_favorites_map' => " favorite_content_id I4 PRIMARY, user_id I4 PRIMARY, map_position I4 CONSTRAINT ', CONSTRAINT `users_fav_user_ref` FOREIGN KEY (`user_id`) REFERENCES `".BIT_DB_PREFIX."users_users` (`user_id`)' ", - )), - array( 'RENAMETABLE' => array( + ]], + [ 'RENAMETABLE' => [ 'tiki_semaphores' => 'users_semaphores', 'users_objectpermissions' => 'users_object_permissions', 'users_grouppermissions' => 'users_group_permissions', 'tiki_user_watches' => 'users_watches', - )), - array( 'RENAMECOLUMN' => array( - 'users_watches' => array( - '`type`' => '`watch_type` C(200)' - ), - 'users_group_permissions' => array( - '`value`' => "`perm_value` C(1) default ''" - ), - 'users_users' => array( - '`password`' => '`user_password` C(32)' - ), - 'users_permissions' => array( - '`level`' => '`perm_level` C(80)' - ), - )), - array( 'DROPTABLE' => array( + ]], + [ 'RENAMECOLUMN' => [ + 'users_watches' => [ + '`type`' => '`watch_type` C(200)', + ], + 'users_group_permissions' => [ + '`value`' => "`perm_value` C(1) default ''", + ], + 'users_users' => [ + '`password`' => '`user_password` C(32)', + ], + 'users_permissions' => [ + '`level`' => '`perm_level` C(80)', + ], + ]], + [ 'DROPTABLE' => [ 'tiki_sessions', - 'users_groups_inclusion' - )), -)), + 'users_groups_inclusion', + ]], +]], -array( 'QUERY' => - array( 'SQL92' => array( +[ 'QUERY' => + [ 'SQL92' => [ "UPDATE `".BIT_DB_PREFIX."users_permissions` SET `perm_name`='p_shoutbox_view' WHERE `perm_name`='bit_p_view_shoutbox'", "UPDATE `".BIT_DB_PREFIX."users_permissions` SET `perm_name`='p_shoutbox_admin' WHERE `perm_name`='bit_p_admin_shoutbox'", "UPDATE `".BIT_DB_PREFIX."users_permissions` SET `perm_name`='p_shoutbox_post' WHERE `perm_name`='bit_p_post_shoutbox'", @@ -500,8 +488,6 @@ array( 'QUERY' => "UPDATE `".BIT_DB_PREFIX."users_permissions` SET `perm_name`='p_nexus_insert_item' WHERE `perm_name`='bit_p_insert_nexus_item'", "UPDATE `".BIT_DB_PREFIX."users_permissions` SET `perm_name`='p_nexus_create_menus' WHERE `perm_name`='bit_p_create_nexus_menus'", - - "UPDATE `".BIT_DB_PREFIX."users_group_permissions` SET `perm_name`='p_shoutbox_view' WHERE `perm_name`='bit_p_view_shoutbox'", "UPDATE `".BIT_DB_PREFIX."users_group_permissions` SET `perm_name`='p_shoutbox_admin' WHERE `perm_name`='bit_p_admin_shoutbox'", "UPDATE `".BIT_DB_PREFIX."users_group_permissions` SET `perm_name`='p_shoutbox_post' WHERE `perm_name`='bit_p_post_shoutbox'", @@ -617,31 +603,30 @@ array( 'QUERY' => "UPDATE `".BIT_DB_PREFIX."users_group_permissions` SET `perm_name`='p_articles_admin' WHERE `perm_name`='bit_p_admin_articles'", "UPDATE `".BIT_DB_PREFIX."users_group_permissions` SET `perm_name`='p_nexus_insert_item' WHERE `perm_name`='bit_p_insert_nexus_item'", "UPDATE `".BIT_DB_PREFIX."users_group_permissions` SET `perm_name`='p_nexus_create_menus' WHERE `perm_name`='bit_p_create_nexus_menus'", - ) -)), + ], +], ], -array( 'DATADICT' => array( - array('ALTER' => array( - 'users_users' => array( - 'provpass_expires' => array( '`provpass_expires`', 'I8' ), - ), - 'users_groups' => array( +[ 'DATADICT' => [ + ['ALTER' => [ + 'users_users' => [ + 'provpass_expires' => [ '`provpass_expires`', 'I8' ], + ], + 'users_groups' => [ 'is_public' => '`is_public` C(1)' , 'after_registration_page' => '`after_registration_page` C(255)' , - ), - 'users_cnxn' => array( - 'assume_user_id' => array( '`assume_user_id`', 'I4' ), - ), - )), - ) -), + ], + 'users_cnxn' => [ + 'assume_user_id' => [ '`assume_user_id`', 'I4' ], + ], + ]], + ], +], -)), -); +], ], +]; if( isset( $upgrades[$gUpgradeFrom][$gUpgradeTo] ) ) { $gBitSystem->registerUpgrade( USERS_PKG_NAME, $upgrades[$gUpgradeFrom][$gUpgradeTo] ); } - ?> diff --git a/admin/user_activity.php b/admin/user_activity.php index 18a28a3..3940e69 100755 --- a/admin/user_activity.php +++ b/admin/user_activity.php @@ -20,10 +20,10 @@ if( !empty( $_REQUEST['ip'] ) ) { if( $userId = (int)BitBase::getParameter( $_REQUEST, 'user_id' ) ) { $listHash['user_id'] = $userId; - $gBitSmarty->assign( 'userInfo', $gBitUser->getUserInfo( array( 'user_id' => $userId ) ) ); + $gBitSmarty->assign( 'userInfo', $gBitUser->getUserInfo( [ 'user_id' => $userId ] ) ); } $gBitSmarty->assign( 'userActivity', $gBitUser->getUserActivity( $listHash )); $gBitSmarty->assign( 'listInfo', $listHash['listInfo'] ); -$gBitSystem->display( 'bitpackage:users/user_activity.tpl', 'User Activity' , array( 'display_mode' => 'admin' )); +$gBitSystem->display( 'bitpackage:users/user_activity.tpl', 'User Activity' , [ 'display_mode' => 'admin' ]); diff --git a/admin/users_import.php b/admin/users_import.php index 689c482..0c460be 100755 --- a/admin/users_import.php +++ b/admin/users_import.php @@ -110,5 +110,5 @@ if ( defined( 'ROLE_MODEL' ) ) { } // Display the template -$gBitSystem->display( 'bitpackage:users/users_import.tpl', (!empty( $title ) ? $title : 'Import Users' ) , array( 'display_mode' => 'admin' )); +$gBitSystem->display( 'bitpackage:users/users_import.tpl', (!empty( $title ) ? $title : 'Import Users' ) , [ 'display_mode' => 'admin' ]); ?> diff --git a/admin/verify_emails.php b/admin/verify_emails.php index 2078d61..9e614f6 100644 --- a/admin/verify_emails.php +++ b/admin/verify_emails.php @@ -6,11 +6,11 @@ // Initialization require_once( '../../kernel/includes/setup_inc.php' ); -if( $validatedGroup = $gBitSystem->getConfig( 'users_validate_email_group' ) ) { +if( $validatedGroup = $gBitSystem->getConfig( 'users_validate_email_group' ) ) { $gBitUser->verifyTicket(); $whereSql = ''; - $bindVars = array( $gBitSystem->getConfig('users_validate_email_group') ); + $bindVars = [ $gBitSystem->getConfig('users_validate_email_group') ]; if( !empty( $_REQUEST['start_user_id'] ) ) { $whereSql = " AND user_id>?"; $bindVars[] = $_REQUEST['start_user_id']; @@ -34,7 +34,5 @@ if( $validatedGroup = $gBitSystem->getConfig( 'users_validate_email_group' ) ) { print "<br/>\n"; flush(); } -} else { - } diff --git a/admin/verify_emails_role.php b/admin/verify_emails_role.php index a34becc..433cd6c 100644 --- a/admin/verify_emails_role.php +++ b/admin/verify_emails_role.php @@ -6,11 +6,10 @@ // Initialization require_once( '../../kernel/includes/setup_inc.php' ); - $gBitUser->verifyTicket(); $whereSql = ''; - $bindVars = array( $gBitSystem->getConfig('users_validate_email_role') ); + $bindVars = [ $gBitSystem->getConfig('users_validate_email_role') ]; if( !empty( $_REQUEST['start_user_id'] ) ) { $whereSql = " AND user_id>?"; $bindVars[] = $_REQUEST['start_user_id']; @@ -35,4 +34,3 @@ require_once( '../../kernel/includes/setup_inc.php' ); flush(); } - diff --git a/auth/bit/auth.php b/auth/bit/auth.php index 17e118e..4b195c2 100755 --- a/auth/bit/auth.php +++ b/auth/bit/auth.php @@ -34,7 +34,7 @@ class BitAuth extends BaseAuth { $loginCol = ' UPPER(`'.(strpos( $user, '@' ) ? 'email' : 'login').'`)'; // first verify that the user exists $query = "select `email`, `login`, `user_id`, `user_password` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?"; - $result = $gBitDb->query( $query, array( $loginVal ) ); + $result = $gBitDb->query( $query, [ $loginVal ] ); if( !$result->numRows() ) { $this->mErrors['login'] = 'User not found'; } else { @@ -48,7 +48,7 @@ class BitAuth extends BaseAuth { // TODO - this needs cleaning up - wolff_borg if( !$gBitSystem->isFeatureActive( 'feature_challenge' ) || empty($response) ) { $query = "select `user_id`, `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ? and (`hash`=? or `hash`=?)"; - if ( $row = $gBitDb->getRow( $query, array( $loginVal, $hash, $hash2 ) ) ) { + if ( $row = $gBitDb->getRow( $query, [ $loginVal, $hash, $hash2 ] ) ) { // auto-update old hashes with simple and standard md5( password ) $hashUpdate = ''; if( $row['hash'] == $hash ) { @@ -67,7 +67,7 @@ class BitAuth extends BaseAuth { } else { // Use challenge-reponse method // Compare pass against md5(user,challenge,hash) - $hash = $gBitDb->getOne("select `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?", array( $user ) ); + $hash = $gBitDb->getOne("select `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?", [ $user ] ); if (!isset($_SESSION["challenge"])) { $this->mErrors[] = 'Invalid challenge'; $ret=PASSWORD_INCORRECT; diff --git a/auth/imap/auth.php b/auth/imap/auth.php index a8fb8b3..2887254 100755 --- a/auth/imap/auth.php +++ b/auth/imap/auth.php @@ -12,6 +12,7 @@ * @subpackage auth */ namespace Bitweaver\Users; + use Bitweaver\KernelTools; class IMAPAuth extends BaseAuth { @@ -43,7 +44,7 @@ class IMAPAuth extends BaseAuth { if(empty($this->mConfig["email"])) { $this->mInfo["email"] = $user; } else { - $info=array('login'=>$user); + $info=['login'=>$user]; $replace_func = create_function('$matches','$info = '.var_export($info,true).'; $m = $matches[0]; $m = substr($m,1,strlen($m)-2); @@ -76,37 +77,37 @@ class IMAPAuth extends BaseAuth { } function getSettings() { - return array( - 'users_imap_server' => array( + return [ + 'users_imap_server' => [ 'label' => "IMAP Server", 'type' => "text", 'note' => "", 'default' => '', - ), - 'users_imap_ssl' => array( + ], + 'users_imap_ssl' => [ 'label' => "Connect Using SSL", 'type' => "checkbox", 'note' => "", 'default' => 'y', - ), - 'users_imap_sslvalidate' => array( + ], + 'users_imap_sslvalidate' => [ 'label' => "Require SSL Certificate to be valid", 'type' => "checkbox", 'note' => "", 'default' => 'n', - ), - 'users_imap_port' => array( + ], + 'users_imap_port' => [ 'label' => "IMAP Port", 'type' => "text", 'note' => "", 'default' => '993', - ), - 'users_imap_email' => array( + ], + 'users_imap_email' => [ 'label' => "LDAP User E-Mail Address", 'type' => "text", 'note' => "If empty the login is used.<br />Otherwise all %login% is replaced with the login name, and the result used as the email address.<br />Please remember to include the @ sign", 'default' => "%login%@redhat.com", - ), - ); + ], + ]; } } diff --git a/auth/ldap/auth.php b/auth/ldap/auth.php index b0e599f..709e5e7 100755 --- a/auth/ldap/auth.php +++ b/auth/ldap/auth.php @@ -9,6 +9,7 @@ * required setup */ namespace Bitweaver\Users; + use Bitweaver\KernelTools; if (file_exists(UTIL_PKG_INCLUDE_PATH."pear/Auth/Auth.php")) { @@ -76,7 +77,7 @@ class LDAPAuth extends BaseAuth { $success = $a->storage->fetchData($user_utf8, $pass, false); if ($success == false) { - $this->mErrors['login'] = isset($a->storage->options['status']) ? $a->storage->options['status'] : 'Not authenticated'; + $this->mErrors['login'] = $a->storage->options['status'] ?? 'Not authenticated'; return PASSWORD_INCORRECT; } } @@ -124,18 +125,18 @@ class LDAPAuth extends BaseAuth { global $gBitDb; // set additional attributes here if (empty($userattr["email"])) { - $userattr["email"] = $gBitDb->getOne("select `email` from `".BIT_DB_PREFIX."users_users` where `login`=?", array($userattr["login"])); + $userattr["email"] = $gBitDb->getOne("select `email` from `".BIT_DB_PREFIX."users_users` where `login`=?", [$userattr["login"]]); } // set the Auth options $a = new \Auth("LDAP", $this->mConfig); // check if the login correct if ($a->addUser($userattr["login"], $userattr["password"], $userattr) === true) { return true; - } else { + } // otherwise use the error status given back $this->mErrors['create'] = $a->getStatus(); return false; - } + } function canManageAuth() { diff --git a/auth/locate/auth.php b/auth/locate/auth.php index 2d6bf14..77197f5 100755 --- a/auth/locate/auth.php +++ b/auth/locate/auth.php @@ -15,7 +15,6 @@ * @subpackage auth */ namespace Bitweaver\Users; -use Bitweaver\KernelTools; class LocateAuth extends BaseAuth { @@ -39,7 +38,7 @@ class LocateAuth extends BaseAuth { $loginCol = ' UPPER(`'.(strpos( $user, '@' ) ? 'email' : 'login').'`)'; // first verify that the user exists $query = "select `email`, `login`, `user_id`, `user_password` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?"; - $result = $gBitDb->query( $query, array( $loginVal ) ); + $result = $gBitDb->query( $query, [ $loginVal ] ); if( !$result->numRows() ) { $this->mErrors['login'] = 'User not found'; } else { @@ -53,7 +52,7 @@ class LocateAuth extends BaseAuth { // TODO - this needs cleaning up - wolff_borg if( !$gBitSystem->isFeatureActive( 'feature_challenge' ) || empty($response) ) { $query = "select `user_id`, `content_id`, `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ? and (`hash`=? or `hash`=?)"; - if ( $row = $gBitDb->getRow( $query, array( $loginVal, $hash, $hash2 ) ) ) { + if ( $row = $gBitDb->getRow( $query, [ $loginVal, $hash, $hash2 ] ) ) { // auto-update old hashes with simple and standard md5( password ) $hashUpdate = ''; if( $row['hash'] == $hash ) { @@ -90,7 +89,7 @@ class LocateAuth extends BaseAuth { } else { // Use challenge-reponse method // Compare pass against md5(user,challenge,hash) - $hash = $gBitDb->getOne("select `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?", array( $user ) ); + $hash = $gBitDb->getOne("select `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?", [ $user ] ); if (!isset($_SESSION["challenge"])) { $this->mErrors[] = 'Invalid challenge'; $ret=PASSWORD_INCORRECT; @@ -118,18 +117,18 @@ class LocateAuth extends BaseAuth { global $gBitSystem; if( $gBitSystem->isPackageActive( 'contact' ) ) { return TRUE; - } else { - return FALSE; } + return FALSE; + } function isSupported() { global $gBitSystem; if( $gBitSystem->isPackageActive( 'contact' ) ) { return TRUE; - } else { - return FALSE; } + return FALSE; + } function createUser( &$pUserHash ) { diff --git a/auth/multisites/auth.php b/auth/multisites/auth.php index 680f4e4..cf44c0d 100755 --- a/auth/multisites/auth.php +++ b/auth/multisites/auth.php @@ -12,7 +12,6 @@ * @subpackage auth */ namespace Bitweaver\Users; -use Bitweaver\KernelTools; class MultisitesAuth extends BaseAuth { @@ -36,7 +35,7 @@ class MultisitesAuth extends BaseAuth { $loginCol = ' UPPER(`'.(strpos( $user, '@' ) ? 'email' : 'login').'`)'; // first verify that the user exists $query = "select `email`, `login`, `user_id`, `user_password` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?"; - $result = $gBitDb->query( $query, array( $loginVal ) ); + $result = $gBitDb->query( $query, [ $loginVal ] ); if( !$result->numRows() ) { $this->mErrors['login'] = 'User not found'; } else { @@ -50,7 +49,7 @@ class MultisitesAuth extends BaseAuth { // TODO - this needs cleaning up - wolff_borg if( !$gBitSystem->isFeatureActive( 'feature_challenge' ) || empty($response) ) { $query = "select `user_id`, `content_id`, `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ? and (`hash`=? or `hash`=?)"; - if ( $row = $gBitDb->getRow( $query, array( $loginVal, $hash, $hash2 ) ) ) { + if ( $row = $gBitDb->getRow( $query, [ $loginVal, $hash, $hash2 ] ) ) { // auto-update old hashes with simple and standard md5( password ) $hashUpdate = ''; if( $row['hash'] == $hash ) { @@ -62,7 +61,7 @@ class MultisitesAuth extends BaseAuth { $query = "update `".BIT_DB_PREFIX."users_users` set $hashUpdate `last_login`=`current_login`, `current_login`=? where `user_id`=?"; $result = $gBitDb->query($query, $bindVars ); $query = "select `multisite_id` from `".BIT_DB_PREFIX."multisite_content` where `content_id` = ?"; - $sites = $gBitDb->getAll($query, array( $row['content_id'] ) ); + $sites = $gBitDb->getAll($query, [ $row['content_id'] ] ); if ( !$sites ) { $ret=USER_VALID; } else { @@ -85,7 +84,7 @@ class MultisitesAuth extends BaseAuth { } else { // Use challenge-reponse method // Compare pass against md5(user,challenge,hash) - $hash = $gBitDb->getOne("select `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?", array( $user ) ); + $hash = $gBitDb->getOne("select `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?", [ $user ] ); if (!isset($_SESSION["challenge"])) { $this->mErrors[] = 'Invalid challenge'; $ret=PASSWORD_INCORRECT; @@ -113,18 +112,18 @@ class MultisitesAuth extends BaseAuth { global $gBitSystem; if( $gBitSystem->isPackageActive( 'multisites' ) ) { return TRUE; - } else { - return FALSE; } + return FALSE; + } function isSupported() { global $gBitSystem; if( $gBitSystem->isPackageActive( 'multisites' ) ) { return TRUE; - } else { - return FALSE; } + return FALSE; + } function createUser( &$pUserHash ) { diff --git a/bookmark.php b/bookmark.php index cc78ed3..a03df36 100755 --- a/bookmark.php +++ b/bookmark.php @@ -24,8 +24,8 @@ if( $gBitUser->isRegistered() ){ if( $gContent->hasViewPermission() ){ if( $gContent->hasService( CONTENT_SERVICE_USERS_FAVS ) ){ // default action is to add the favorite - $_REQUEST['action'] = empty( $_REQUEST['action'] )?'add':$_REQUEST['action']; - // add or remove + $_REQUEST['action'] = empty( $_REQUEST['action'] )?'add':$_REQUEST['action']; + // add or remove switch( $_REQUEST['action'] ){ case 'add': $gBitUser->storeFavorite( $_REQUEST['content_id'] ); @@ -61,4 +61,4 @@ $gBitSmarty->assign( 'statusCode', $statusCode ); $gBitSmarty->assign( 'error', $error ); $gBitSmarty->assign( 'msg', $msg ); $gBitThemes->setFormatHeader( 'json' ); -$gBitSystem->display('bitpackage:users/edit_user_fav_json.tpl', null, array( 'format' => 'center_only', 'display_mode' => 'edit' )); +$gBitSystem->display('bitpackage:users/edit_user_fav_json.tpl', null, [ 'format' => 'center_only', 'display_mode' => 'edit' ]); diff --git a/change_password.php b/change_password.php index 97472a8..2f69c38 100755 --- a/change_password.php +++ b/change_password.php @@ -32,7 +32,7 @@ $gBitSmarty->assign( 'login', $_REQUEST['login'] ); $gBitSmarty->assign( 'oldpass', $_REQUEST["oldpass"] ); $gBitSmarty->assign( 'provpass', $_REQUEST["provpass"] ); -$userInfo = $gBitUser->getUserInfo( array( 'user_id' => $_REQUEST['user_id'] )); +$userInfo = $gBitUser->getUserInfo( [ 'user_id' => $_REQUEST['user_id'] ]); $gBitSmarty->assign( 'userInfo', $userInfo ); if( isset( $_REQUEST["change"] )) { @@ -75,4 +75,4 @@ if( isset( $_REQUEST["change"] )) { } // Display the template -$gBitSystem->display( 'bitpackage:users/change_password.tpl', 'Change Password' , array( 'display_mode' => 'display' )); +$gBitSystem->display( 'bitpackage:users/change_password.tpl', 'Change Password' , [ 'display_mode' => 'display' ]); diff --git a/custom_home.php b/custom_home.php index a53f3cb..d923a20 100755 --- a/custom_home.php +++ b/custom_home.php @@ -30,5 +30,5 @@ print_r($b); */ $gBitSystem->verifyFeature( 'users_custom_home' ); // Display the template -$gBitSystem->display( 'bitpackage:users/custom_home_2.tpl', null, array( 'display_mode' => 'display' )); +$gBitSystem->display( 'bitpackage:users/custom_home_2.tpl', null, [ 'display_mode' => 'display' ]); ?> diff --git a/edit_personal_page.php b/edit_personal_page.php index dfcf321..a9a045a 100755 --- a/edit_personal_page.php +++ b/edit_personal_page.php @@ -42,10 +42,10 @@ if(isset($_REQUEST["preview"])) { } $gBitUser->mInfo['data'] = $_REQUEST["edit"]; - $parseHash = array( - 'data' => $_REQUEST["edit"], + $parseHash = [ + 'data' => $_REQUEST["edit"], 'format' => BitBase::getParameter( $_REQUEST, 'format_guid', $gBitUser->getField( 'format_guid', 'tikiwiki' ) ), - ); + ]; $parsed = LibertyContent::parseDataHash( $parseHash ); $gBitUser->mInfo['parsed_data'] = $parsed; @@ -64,5 +64,5 @@ $gBitSmarty->assign( 'gContent', $gBitUser ); $gBitSmarty->assign( 'show_page_bar', 'y' ); $gBitSystem->setConfig( 'wiki_description', 'n' ); -$gBitSystem->display( 'bitpackage:users/edit_personal_page.tpl', null, array( 'display_mode' => 'edit' ) ); +$gBitSystem->display( 'bitpackage:users/edit_personal_page.tpl', null, [ 'display_mode' => 'edit' ] ); ?> diff --git a/freecap/.ht_freecap_font1.gdf b/freecap/.ht_freecap_font1.gdf Binary files differindex 6f44158..6f44158 100644..100755 --- a/freecap/.ht_freecap_font1.gdf +++ b/freecap/.ht_freecap_font1.gdf diff --git a/freecap/.ht_freecap_font2.gdf b/freecap/.ht_freecap_font2.gdf Binary files differindex 0f549c2..0f549c2 100644..100755 --- a/freecap/.ht_freecap_font2.gdf +++ b/freecap/.ht_freecap_font2.gdf diff --git a/freecap/.ht_freecap_font3.gdf b/freecap/.ht_freecap_font3.gdf Binary files differindex fbea123..fbea123 100644..100755 --- a/freecap/.ht_freecap_font3.gdf +++ b/freecap/.ht_freecap_font3.gdf diff --git a/freecap/.ht_freecap_font4.gdf b/freecap/.ht_freecap_font4.gdf Binary files differindex f9f4b6a..f9f4b6a 100644..100755 --- a/freecap/.ht_freecap_font4.gdf +++ b/freecap/.ht_freecap_font4.gdf diff --git a/freecap/.ht_freecap_font5.gdf b/freecap/.ht_freecap_font5.gdf Binary files differindex fe123f8..fe123f8 100644..100755 --- a/freecap/.ht_freecap_font5.gdf +++ b/freecap/.ht_freecap_font5.gdf diff --git a/freecap/.ht_freecap_im1.jpg b/freecap/.ht_freecap_im1.jpg Binary files differindex 823678e..823678e 100644..100755 --- a/freecap/.ht_freecap_im1.jpg +++ b/freecap/.ht_freecap_im1.jpg diff --git a/freecap/.ht_freecap_im2.jpg b/freecap/.ht_freecap_im2.jpg Binary files differindex e9ad645..e9ad645 100644..100755 --- a/freecap/.ht_freecap_im2.jpg +++ b/freecap/.ht_freecap_im2.jpg diff --git a/freecap/.ht_freecap_im3.jpg b/freecap/.ht_freecap_im3.jpg Binary files differindex 7e3b65d..7e3b65d 100644..100755 --- a/freecap/.ht_freecap_im3.jpg +++ b/freecap/.ht_freecap_im3.jpg diff --git a/freecap/.ht_freecap_im4.jpg b/freecap/.ht_freecap_im4.jpg Binary files differindex f96821c..f96821c 100644..100755 --- a/freecap/.ht_freecap_im4.jpg +++ b/freecap/.ht_freecap_im4.jpg diff --git a/freecap/.ht_freecap_im5.jpg b/freecap/.ht_freecap_im5.jpg Binary files differindex a2800ed..a2800ed 100644..100755 --- a/freecap/.ht_freecap_im5.jpg +++ b/freecap/.ht_freecap_im5.jpg diff --git a/freecap/.ht_freecap_words b/freecap/.ht_freecap_words index b1e1312..b1e1312 100644..100755 --- a/freecap/.ht_freecap_words +++ b/freecap/.ht_freecap_words diff --git a/freecap/COPYING.txt b/freecap/COPYING.txt index 45645b4..45645b4 100644..100755 --- a/freecap/COPYING.txt +++ b/freecap/COPYING.txt diff --git a/freecap/freecap.php b/freecap/freecap.php index 2d99aa8..a4763fb 100755 --- a/freecap/freecap.php +++ b/freecap/freecap.php @@ -112,7 +112,7 @@ $max_attempts = 100; // the fonts included with freeCap *only* include lowercase alphabetic characters // so are not suitable for most other uses // to increase security, you really should add other fonts -$font_locations = Array("./.ht_freecap_font1.gdf","./.ht_freecap_font2.gdf","./.ht_freecap_font3.gdf","./.ht_freecap_font4.gdf","./.ht_freecap_font5.gdf"); +$font_locations = ["./.ht_freecap_font1.gdf","./.ht_freecap_font2.gdf","./.ht_freecap_font3.gdf","./.ht_freecap_font4.gdf","./.ht_freecap_font5.gdf"]; // background: // 0=transparent (if jpg, white) @@ -127,7 +127,7 @@ $bg_type = 2; $blur_bg = true; // for bg_type 3, which images should we use? // if you add your own, make sure they're fairly 'busy' images (ie a lot of shapes in them) -$bg_images = Array("./.ht_freecap_im1.jpg","./.ht_freecap_im2.jpg","./.ht_freecap_im3.jpg","./.ht_freecap_im4.jpg","./.ht_freecap_im5.jpg"); +$bg_images = ["./.ht_freecap_im1.jpg","./.ht_freecap_im2.jpg","./.ht_freecap_im3.jpg","./.ht_freecap_im4.jpg","./.ht_freecap_im5.jpg"]; // for non-transparent backgrounds only: // if 0, merges CAPTCHA with bg // if 1, write CAPTCHA over bg @@ -139,8 +139,6 @@ $bg_images = Array("./.ht_freecap_im1.jpg","./.ht_freecap_im2.jpg","./.ht_freeca // have fun, and email me with ideas, or improvements to the code (very interested in speed improvements) // hope this script saves some spam :-) - - ////////////////////////////////////////////////////// ////// Create Images + initialise a few things ////////////////////////////////////////////////////// @@ -169,7 +167,7 @@ switch($bg_type) $bg_fade_pct += $rand_func(-2,2); // read each font and get font character widths -$font_widths = Array(); +$font_widths = []; for($i=0 ; $i<sizeof($font_locations) ; $i++) { $handle = fopen($font_locations[$i],"r"); @@ -187,8 +185,6 @@ $height = !empty( $_REQUEST['height'] ) ? $_REQUEST['height'] : 75; $im = ImageCreate($width, $height); $im2 = ImageCreate($width, $height); - - ////////////////////////////////////////////////////// ////// Avoid Brute Force Attacks: ////////////////////////////////////////////////////// @@ -225,17 +221,13 @@ if(empty($_SESSION['freecap_attempts'])) } } - - - - ////////////////////////////////////////////////////// ////// Functions: ////////////////////////////////////////////////////// function make_seed() { // from http://php.net/srand - list($usec, $sec) = explode(' ', microtime()); - return (float) $sec + ((float) $usec * 100000); + list($usec, $sec) = explode(' ', microtime()); + return (float) $sec + ((float) $usec * 100000); } function rand_color() { @@ -244,9 +236,9 @@ function rand_color() { { // needs darker colour.. return $rand_func(10,100); - } else { - return $rand_func(60,170); } + return $rand_func(60,170); + } function myImageBlur($im) @@ -316,9 +308,6 @@ function sendImage($pic) exit(); } - - - ////////////////////////////////////////////////////// ////// Choose Word: ////////////////////////////////////////////////////// @@ -368,9 +357,6 @@ if($use_dict==1) // (though most hashes are easy to brute force for simple strings) $_SESSION['captcha'] = $hash_func($word); - - - ////////////////////////////////////////////////////// ////// Fill BGs and Allocate Colours: ////////////////////////////////////////////////////// @@ -463,7 +449,7 @@ if($bg_type!=0) $text_b = $rand_func(100,150); $text_colour3 = ImageColorAllocate($temp_bg, $text_r, $text_g, $text_b); - $points = Array(); + $points = []; // draw random squiggle for each character // the longer the loop, the more complex the squiggle // keep random so OCR can't say "if found shape has 10 points, ignore it" @@ -475,7 +461,7 @@ if($bg_type!=0) $points[] = $rand_func(30,$height+30); } - ImagePolygon($temp_bg,$points,intval(sizeof($points)/2),$text_colour3); + ImagePolygon($temp_bg,$points,(int) (sizeof($points)/2),$text_colour3); } } else if($bg_type==3) { @@ -561,9 +547,6 @@ if($bg_type!=0) // for debug: //sendImage($im3); - - - ////////////////////////////////////////////////////// ////// Write Word ////////////////////////////////////////////////////// @@ -602,10 +585,6 @@ $font_pixelwidth = $font_widths[$j]; // for debug: //sendImage($im2); - - - - ////////////////////////////////////////////////////// ////// Morph Image: ////////////////////////////////////////////////////// @@ -701,10 +680,6 @@ if($output!="jpg" && $bg_type==0) ImageColorTransparent($im,$bg); } - - - - ////////////////////////////////////////////////////// ////// Try to avoid 'free p*rn' style CAPTCHA re-use ////////////////////////////////////////////////////// @@ -724,12 +699,12 @@ if(is_array($site_tags)) if($tag_pos==0 || $tag_pos==2) { // write at top - ImageString($im2, 2, intval($width/2)-intval($tag_width/2), (10*$i), $site_tags[$i], $site_tag_col2); + ImageString($im2, 2, (int) ($width/2)-(int) ($tag_width/2), (10*$i), $site_tags[$i], $site_tag_col2); } if($tag_pos==1 || $tag_pos==2) { // write at bottom - ImageString($im2, 2, intval($width/2)-intval($tag_width/2), ($height-34+($i*10)), $site_tags[$i], $site_tag_col2); + ImageString($im2, 2, (int) ($width/2)-(int) ($tag_width/2), ($height-34+($i*10)), $site_tags[$i], $site_tag_col2); } } } @@ -738,9 +713,6 @@ ImageCopy($im,$im2,0,0,0,0,$width,$height); // for debug: //sendImage($im); - - - ////////////////////////////////////////////////////// ////// Merge with obfuscated background ////////////////////////////////////////////////////// @@ -779,7 +751,6 @@ if($bg_type!=0) // for debug: //sendImage($im); - ////////////////////////////////////////////////////// ////// Write tags, remove variables and output! ////////////////////////////////////////////////////// @@ -820,7 +791,6 @@ unset($col_type); unset($max_attempts); unset($font_locations); - // output final image :-) sendImage($im); // (sendImage also destroys all used images) diff --git a/freecap/freecap_wrap.php b/freecap/freecap_wrap.php index 5a0f89b..763ad83 100644 --- a/freecap/freecap_wrap.php +++ b/freecap/freecap_wrap.php @@ -21,8 +21,8 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
-\************************************************************/
-
+\************************************************************/ + // this is the 'form' side of the script.
// I suggest making the user fill in the main form
// then take them here and update the information with a 'freecap_passed' flag if they enter the
@@ -31,14 +31,14 @@ // also, if someone is spamming you, you've got a log of all the failed attempts
// which might prove useful for legal action or just for amusement, plus you'll be able to see
// if you're stopping spammers or if the majority of failed registrations are valid users who
-// just can't read the word properly...
-
+// just can't read the word properly... + // To avoid blocking out partially sighted users, I'd suggest having a 'submit without entering word'
// button, which sends the info to you for manual verification. It's a lot simpler than trying to
-// implement a secure audio-captcha.
-
-session_start();
-
+// implement a secure audio-captcha. + +session_start(); + if(!empty($_SESSION['freecap_word_hash']) && !empty($_POST['word']))
{
// all freeCap words are lowercase.
@@ -49,12 +49,10 @@ if(!empty($_SESSION['freecap_word_hash']) && !empty($_POST['word'])) // cannot stress enough how important it is to do this
// defeats re-use of known image with spoofed session id
$_SESSION['freecap_attempts'] = 0;
- $_SESSION['freecap_word_hash'] = false;
-
-
- // now process form
-
-
+ $_SESSION['freecap_word_hash'] = false; + + // now process form + // now go somewhere else
// header("Location: somewhere.php");
$word_ok = "yes";
diff --git a/hauth/Hybrid/Auth.php b/hauth/Hybrid/Auth.php index aa0a610..fb30ef9 100644 --- a/hauth/Hybrid/Auth.php +++ b/hauth/Hybrid/Auth.php @@ -1,11 +1,11 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2017, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_Auth class
*
@@ -13,34 +13,34 @@ *
* Generally, Hybrid_Auth is the only class you should instanciate and use throughout your application.
*/
-class Hybrid_Auth {
-
- public static $version = "2.14.0";
-
+class Hybrid_Auth { + + public static $version = "2.14.0"; + /**
* Configuration array
* @var array
*/
- public static $config = array();
-
+ public static $config = []; + /**
* Auth cache
* @var Hybrid_Storage
*/
- public static $store = null;
-
+ public static $store = null; + /**
* Error pool
* @var Hybrid_Error
*/
- public static $error = null;
-
+ public static $error = null; + /**
* Logger
* @var Hybrid_Logger
*/
- public static $logger = null;
-
+ public static $logger = null; + /**
* Try to start a new session of none then initialize Hybrid_Auth
*
@@ -53,8 +53,8 @@ class Hybrid_Auth { */
function __construct($config) {
Hybrid_Auth::initialize($config);
- }
-
+ } + /**
* Try to initialize Hybrid_Auth with given $config hash or file
*
@@ -64,115 +64,114 @@ class Hybrid_Auth { */
public static function initialize($config) {
if (!is_array($config) && !file_exists($config)) {
- throw new Exception("Hybriauth config does not exist on the given path.", 1);
- }
-
+ throw new Exception("Hybriauth config does not exist on the given path.", 1); + } + if (!is_array($config)) {
$config = include $config;
- }
-
+ } + // build some need'd paths
$config["path_base"] = realpath(dirname(__FILE__)) . "/";
$config["path_libraries"] = $config["path_base"] . "thirdparty/";
$config["path_resources"] = $config["path_base"] . "resources/";
- $config["path_providers"] = $config["path_base"] . "Providers/";
-
+ $config["path_providers"] = $config["path_base"] . "Providers/"; + // reset debug mode
if (!isset($config["debug_mode"])) {
$config["debug_mode"] = false;
$config["debug_file"] = null;
- }
-
+ } + # load hybridauth required files, a autoload is on the way...
require_once $config["path_base"] . "Error.php";
require_once $config["path_base"] . "Exception.php";
- require_once $config["path_base"] . "Logger.php";
-
- require_once $config["path_base"] . "Provider_Adapter.php";
-
+ require_once $config["path_base"] . "Logger.php"; + + require_once $config["path_base"] . "Provider_Adapter.php"; + require_once $config["path_base"] . "Provider_Model.php";
require_once $config["path_base"] . "Provider_Model_OpenID.php";
require_once $config["path_base"] . "Provider_Model_OAuth1.php";
- require_once $config["path_base"] . "Provider_Model_OAuth2.php";
-
+ require_once $config["path_base"] . "Provider_Model_OAuth2.php"; + require_once $config["path_base"] . "User.php";
require_once $config["path_base"] . "User_Profile.php";
require_once $config["path_base"] . "User_Contact.php";
- require_once $config["path_base"] . "User_Activity.php";
-
+ require_once $config["path_base"] . "User_Activity.php"; + if (!class_exists("Hybrid_Storage", false)) {
require_once $config["path_base"] . "Storage.php";
- }
-
+ } + // hash given config
- Hybrid_Auth::$config = $config;
-
+ Hybrid_Auth::$config = $config; + // instance of log mng
- Hybrid_Auth::$logger = new Hybrid_Logger();
-
+ Hybrid_Auth::$logger = new Hybrid_Logger(); + // instance of errors mng
- Hybrid_Auth::$error = new Hybrid_Error();
-
+ Hybrid_Auth::$error = new Hybrid_Error(); + // start session storage mng
- Hybrid_Auth::$store = new Hybrid_Storage();
-
+ Hybrid_Auth::$store = new Hybrid_Storage(); + Hybrid_Logger::info("Enter Hybrid_Auth::initialize()");
Hybrid_Logger::info("Hybrid_Auth::initialize(). PHP version: " . PHP_VERSION);
Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth version: " . Hybrid_Auth::$version);
- Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl());
-
+ Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl()); + // PHP Curl extension [http://www.php.net/manual/en/intro.curl.php]
if (!function_exists('curl_init')) {
Hybrid_Logger::error('Hybridauth Library needs the CURL PHP extension.');
- throw new Exception('Hybridauth Library needs the CURL PHP extension.');
- }
-
+ throw new Exception('Hybridauth Library needs the CURL PHP extension.'); + } + // PHP JSON extension [http://php.net/manual/en/book.json.php]
if (!function_exists('json_decode')) {
Hybrid_Logger::error('Hybridauth Library needs the JSON PHP extension.');
- throw new Exception('Hybridauth Library needs the JSON PHP extension.');
- }
-
+ throw new Exception('Hybridauth Library needs the JSON PHP extension.'); + } + // session.name
if (session_name() != "PHPSESSID") {
Hybrid_Logger::info('PHP session.name diff from default PHPSESSID. http://php.net/manual/en/session.configuration.php#ini.session.name.');
- }
-
+ } + // safe_mode is on
if (ini_get('safe_mode')) {
Hybrid_Logger::info('PHP safe_mode is on. http://php.net/safe-mode.');
- }
-
+ } + // open basedir is on
if (ini_get('open_basedir')) {
Hybrid_Logger::info('PHP open_basedir is on. http://php.net/open-basedir.');
- }
-
+ } + Hybrid_Logger::debug("Hybrid_Auth initialize. dump used config: ", serialize($config));
Hybrid_Logger::debug("Hybrid_Auth initialize. dump current session: ", Hybrid_Auth::storage()->getSessionData());
- Hybrid_Logger::info("Hybrid_Auth initialize: check if any error is stored on the endpoint...");
-
+ Hybrid_Logger::info("Hybrid_Auth initialize: check if any error is stored on the endpoint..."); + if (Hybrid_Error::hasError()) {
$m = Hybrid_Error::getErrorMessage();
$c = Hybrid_Error::getErrorCode();
- $p = Hybrid_Error::getErrorPrevious();
-
- Hybrid_Logger::error("Hybrid_Auth initialize: A stored Error found, Throw an new Exception and delete it from the store: Error#$c, '$m'");
-
- Hybrid_Error::clearError();
-
+ $p = Hybrid_Error::getErrorPrevious(); + + Hybrid_Logger::error("Hybrid_Auth initialize: A stored Error found, Throw an new Exception and delete it from the store: Error#$c, '$m'"); + + Hybrid_Error::clearError(); + // try to provide the previous if any
// Exception::getPrevious (PHP 5 >= 5.3.0) http://php.net/manual/en/exception.getprevious.php
if (version_compare(PHP_VERSION, '5.3.0', '>=') && ($p instanceof Exception)) {
- throw new Exception($m, $c, $p);
- } else {
- throw new Exception($m, $c);
+ throw new Exception($m, $c, $p); }
- }
-
+ throw new Exception($m, $c); + } + Hybrid_Logger::info("Hybrid_Auth initialize: no error found. initialization succeed.");
- }
-
+ } + /**
* Hybrid storage system accessor
*
@@ -184,16 +183,16 @@ class Hybrid_Auth { */
public static function storage() {
return Hybrid_Auth::$store;
- }
-
+ } + /**
* Get hybridauth session data
* @return string|null
*/
function getSessionData() {
return Hybrid_Auth::storage()->getSessionData();
- }
-
+ } + /**
* Restore hybridauth session data
*
@@ -202,8 +201,8 @@ class Hybrid_Auth { */
function restoreSessionData($sessiondata = null) {
Hybrid_Auth::storage()->restoreSessionData($sessiondata);
- }
-
+ } + /**
* Try to authenticate the user with a given provider.
*
@@ -221,8 +220,8 @@ class Hybrid_Auth { * @return
*/
public static function authenticate($providerId, $params = null) {
- Hybrid_Logger::info("Enter Hybrid_Auth::authenticate( $providerId )");
-
+ Hybrid_Logger::info("Enter Hybrid_Auth::authenticate( $providerId )"); + if (!Hybrid_Auth::storage()->get("hauth_session.$providerId.is_logged_in")) {
// if user not connected to $providerId then try setup a new adapter and start the login process for this provider
Hybrid_Logger::info("Hybrid_Auth::authenticate( $providerId ), User not connected to the provider. Try to authenticate..");
@@ -233,8 +232,8 @@ class Hybrid_Auth { Hybrid_Logger::info("Hybrid_Auth::authenticate( $providerId ), User is already connected to this provider. Return the adapter instance.");
return Hybrid_Auth::getAdapter($providerId);
}
- }
-
+ } + /**
* Return the adapter instance for an authenticated provider
*
@@ -244,8 +243,8 @@ class Hybrid_Auth { public static function getAdapter($providerId = null) {
Hybrid_Logger::info("Enter Hybrid_Auth::getAdapter( $providerId )");
return Hybrid_Auth::setup($providerId);
- }
-
+ } + /**
* Setup an adapter for a given provider
*
@@ -254,30 +253,30 @@ class Hybrid_Auth { * @return Hybrid_Provider_Adapter
*/
public static function setup($providerId, $params = null) {
- Hybrid_Logger::debug("Enter Hybrid_Auth::setup( $providerId )", $params);
-
+ Hybrid_Logger::debug("Enter Hybrid_Auth::setup( $providerId )", $params); + if (!$params) {
- $params = Hybrid_Auth::storage()->get("hauth_session.$providerId.id_provider_params");
-
+ $params = Hybrid_Auth::storage()->get("hauth_session.$providerId.id_provider_params"); + Hybrid_Logger::debug("Hybrid_Auth::setup( $providerId ), no params given. Trying to get the stored for this provider.", $params);
- }
-
+ } + if (!$params) {
- $params = array();
+ $params = [];
Hybrid_Logger::info("Hybrid_Auth::setup( $providerId ), no stored params found for this provider. Initialize a new one for new session");
- }
-
+ } + if (is_array($params) && !isset($params["hauth_return_to"])) {
$params["hauth_return_to"] = Hybrid_Auth::getCurrentUrl();
Hybrid_Logger::debug("Hybrid_Auth::setup( $providerId ). HybridAuth Callback URL set to: ", $params["hauth_return_to"]);
- }
-
+ } + # instantiate a new IDProvider Adapter
$provider = new Hybrid_Provider_Adapter();
$provider->factory($providerId, $params);
return $provider;
- }
-
+ } + /**
* Check if the current user is connected to a given provider
*
@@ -286,24 +285,24 @@ class Hybrid_Auth { */
public static function isConnectedWith($providerId) {
return (bool) Hybrid_Auth::storage()->get("hauth_session.{$providerId}.is_logged_in");
- }
-
+ } + /**
* Return array listing all authenticated providers
* @return array
*/
public static function getConnectedProviders() {
- $idps = array();
-
+ $idps = []; + foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
if (Hybrid_Auth::isConnectedWith($idpid)) {
$idps[] = $idpid;
}
- }
-
+ } + return $idps;
- }
-
+ } + /**
* Return array listing all enabled providers as well as a flag if you are connected
*
@@ -317,34 +316,34 @@ class Hybrid_Auth { * @return array
*/
public static function getProviders() {
- $idps = array();
-
+ $idps = []; + foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
if ($params['enabled']) {
- $idps[$idpid] = array('connected' => false);
-
+ $idps[$idpid] = ['connected' => false]; + if (Hybrid_Auth::isConnectedWith($idpid)) {
$idps[$idpid]['connected'] = true;
}
}
- }
-
+ } + return $idps;
- }
-
+ } + /**
* A generic function to logout all connected provider at once
* @return void
*/
public static function logoutAllProviders() {
- $idps = Hybrid_Auth::getConnectedProviders();
-
+ $idps = Hybrid_Auth::getConnectedProviders(); + foreach ($idps as $idp) {
$adapter = Hybrid_Auth::getAdapter($idp);
$adapter->logout();
}
- }
-
+ } + /**
* Utility function, redirect to a given URL with php header or using javascript location.href
*
@@ -355,13 +354,13 @@ class Hybrid_Auth { if(!$mode){
$mode = 'PHP';
}
- Hybrid_Logger::info("Enter Hybrid_Auth::redirect( $url, $mode )");
-
+ Hybrid_Logger::info("Enter Hybrid_Auth::redirect( $url, $mode )"); + // Ensure session is saved before sending response, see https://github.com/symfony/symfony/pull/12341
if ((PHP_VERSION_ID >= 50400 && PHP_SESSION_ACTIVE === session_status()) || (PHP_VERSION_ID < 50400 && isset($_SESSION) && session_id())) {
session_write_close();
- }
-
+ } + if ($mode == "PHP") {
header("Location: $url");
} elseif ($mode == "JS") {
@@ -375,11 +374,11 @@ class Hybrid_Auth { echo 'Redirecting, please wait...';
echo '</body>';
echo '</html>';
- }
-
+ } + die();
- }
-
+ } + /**
* Utility function, return the current url
*
@@ -389,18 +388,18 @@ class Hybrid_Auth { public static function getCurrentUrl($request_uri = true) {
if (php_sapi_name() == 'cli') {
return '';
- }
-
- $protocol = 'http://';
-
+ } + + $protocol = 'http://'; + if ((isset($_SERVER['HTTPS']) && ( $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 ))
|| (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
$protocol = 'https://';
- }
-
- $url = $protocol . $_SERVER['HTTP_HOST'];
-
+ } + + $url = $protocol . $_SERVER['HTTP_HOST']; + if ($request_uri) {
// If $_SERVER['REQUEST_URI'] is already a FQDN, use it
if (stripos($_SERVER['REQUEST_URI'], $url) === 0) {
@@ -410,10 +409,10 @@ class Hybrid_Auth { }
} else {
$url .= $_SERVER['PHP_SELF'];
- }
-
+ } + // return current url
return $url;
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/Endpoint.php b/hauth/Hybrid/Endpoint.php index 7813fee..de03601 100644 --- a/hauth/Hybrid/Endpoint.php +++ b/hauth/Hybrid/Endpoint.php @@ -90,7 +90,7 @@ class Hybrid_Endpoint { header("Content-Type: application/xrds+xml"); $output = str_replace("{RETURN_TO_URL}", str_replace( - array("<", ">", "\"", "'", "&"), array("<", ">", """, "'", "&"), Hybrid_Auth::getCurrentUrl(false) + ["<", ">", "\"", "'", "&"], ["<", ">", """, "'", "&"], Hybrid_Auth::getCurrentUrl(false), ), file_get_contents(dirname(__FILE__) . "/resources/openid_xrds.xml")); print $output; die(); @@ -103,7 +103,7 @@ class Hybrid_Endpoint { protected function processOpenidRealm() { $output = str_replace("{X_XRDS_LOCATION}", htmlentities(Hybrid_Auth::getCurrentUrl(false), ENT_QUOTES, 'UTF-8') . "?get=openid_xrds&v=" - . Hybrid_Auth::$version, file_get_contents(dirname(__FILE__) . "/resources/openid_realm.html")); + . Hybrid_Auth::$version, file_get_contents(dirname(__FILE__) . "/resources/openid_realm.html"), ); print $output; die(); } diff --git a/hauth/Hybrid/Error.php b/hauth/Hybrid/Error.php index 7013b49..d1dc496 100644 --- a/hauth/Hybrid/Error.php +++ b/hauth/Hybrid/Error.php @@ -1,18 +1,18 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Errors manager
*
* HybridAuth errors are stored in Hybrid::storage() and not displayed directly to the end user
*/
-class Hybrid_Error {
-
+class Hybrid_Error { + /**
* Store error in session
*
@@ -22,67 +22,67 @@ class Hybrid_Error { * @param string $previous Previous exception
*/
public static function setError($message, $code = null, $trace = null, $previous = null) {
- Hybrid_Logger::info("Enter Hybrid_Error::setError( $message )");
-
+ Hybrid_Logger::info("Enter Hybrid_Error::setError( $message )"); + Hybrid_Auth::storage()->set("hauth_session.error.status", 1);
Hybrid_Auth::storage()->set("hauth_session.error.message", $message);
Hybrid_Auth::storage()->set("hauth_session.error.code", $code);
Hybrid_Auth::storage()->set("hauth_session.error.trace", $trace);
Hybrid_Auth::storage()->set("hauth_session.error.previous", $previous);
- }
-
+ } + /**
* Clear the last error
* @return void
*/
public static function clearError() {
- Hybrid_Logger::info("Enter Hybrid_Error::clearError()");
-
+ Hybrid_Logger::info("Enter Hybrid_Error::clearError()"); + Hybrid_Auth::storage()->delete("hauth_session.error.status");
Hybrid_Auth::storage()->delete("hauth_session.error.message");
Hybrid_Auth::storage()->delete("hauth_session.error.code");
Hybrid_Auth::storage()->delete("hauth_session.error.trace");
Hybrid_Auth::storage()->delete("hauth_session.error.previous");
- }
-
+ } + /**
* Checks to see if there is a an error.
* @return boolean true if there is an error.
*/
public static function hasError() {
return (bool) Hybrid_Auth::storage()->get("hauth_session.error.status");
- }
-
+ } + /**
* Return error message
* @return string
*/
public static function getErrorMessage() {
return Hybrid_Auth::storage()->get("hauth_session.error.message");
- }
-
+ } + /**
* Return error code
* @return int
*/
public static function getErrorCode() {
return Hybrid_Auth::storage()->get("hauth_session.error.code");
- }
-
+ } + /**
* Return string detailed error backtrace as string
* @return string
*/
public static function getErrorTrace() {
return Hybrid_Auth::storage()->get("hauth_session.error.trace");
- }
-
+ } + /**
* Detailed error backtrace as string
* @return string
*/
public static function getErrorPrevious() {
return Hybrid_Auth::storage()->get("hauth_session.error.previous");
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/Exception.php b/hauth/Hybrid/Exception.php index 8c8c2d1..8c8c2d1 100644..100755 --- a/hauth/Hybrid/Exception.php +++ b/hauth/Hybrid/Exception.php diff --git a/hauth/Hybrid/Logger.php b/hauth/Hybrid/Logger.php index f948913..e6a769a 100644 --- a/hauth/Hybrid/Logger.php +++ b/hauth/Hybrid/Logger.php @@ -1,16 +1,16 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Debugging and Logging manager
*/
-class Hybrid_Logger {
-
+class Hybrid_Logger { + /**
* Constructor
*/
@@ -18,17 +18,17 @@ class Hybrid_Logger { // if debug mode is set to true, then check for the writable log file
if (Hybrid_Auth::$config["debug_mode"]) {
if (!isset(Hybrid_Auth::$config["debug_file"])) {
- throw new Exception("'debug_mode' is set to 'true' but no log file path 'debug_file' is set.", 1);
+ throw new Exception("'debug_mode' is set to 'true' but no log file path 'debug_file' is set.", 1); } elseif (!file_exists(Hybrid_Auth::$config["debug_file"]) && !is_writable(Hybrid_Auth::$config["debug_file"])) {
if (!touch(Hybrid_Auth::$config["debug_file"])) {
- throw new Exception("'debug_mode' is set to 'true', but the file " . Hybrid_Auth::$config['debug_file'] . " in 'debug_file' can not be created.", 1);
+ throw new Exception("'debug_mode' is set to 'true', but the file " . Hybrid_Auth::$config['debug_file'] . " in 'debug_file' can not be created.", 1); }
} elseif (!is_writable(Hybrid_Auth::$config["debug_file"])) {
- throw new Exception("'debug_mode' is set to 'true', but the given log file path 'debug_file' is not a writable file.", 1);
+ throw new Exception("'debug_mode' is set to 'true', but the given log file path 'debug_file' is not a writable file.", 1); }
}
- }
-
+ } + /**
* Logs a debug message with an object dump
*
@@ -38,18 +38,18 @@ class Hybrid_Logger { */
public static function debug($message, $object = null) {
if (Hybrid_Auth::$config["debug_mode"] === true) {
- $dt = new DateTime('now', new DateTimeZone( 'UTC' ));
- file_put_contents(Hybrid_Auth::$config["debug_file"], implode(' -- ', array(
+ $dt = new DateTime('now', new DateTimeZone( 'UTC' ));
+ file_put_contents(Hybrid_Auth::$config["debug_file"], implode(' -- ', [
"DEBUG",
$_SERVER['REMOTE_ADDR'],
$dt->format(DATE_ATOM),
$message,
print_r($object, true) . PHP_EOL,
- )), FILE_APPEND
+ ]), FILE_APPEND,
);
}
- }
-
+ } + /**
* Logs an info message
*
@@ -57,17 +57,17 @@ class Hybrid_Logger { * @return void
*/
public static function info($message) {
- if (in_array(Hybrid_Auth::$config["debug_mode"], array(true, 'info'), true)) {
- $dt = new DateTime('now', new DateTimeZone( 'UTC' ));
- file_put_contents(Hybrid_Auth::$config["debug_file"], implode(' -- ', array(
+ if (in_array(Hybrid_Auth::$config["debug_mode"], [true, 'info'], true)) {
+ $dt = new DateTime('now', new DateTimeZone( 'UTC' ));
+ file_put_contents(Hybrid_Auth::$config["debug_file"], implode(' -- ', [
"INFO",
$_SERVER['REMOTE_ADDR'],
$dt->format(DATE_ATOM),
$message . PHP_EOL,
- )), FILE_APPEND);
+ ]), FILE_APPEND);
}
- }
-
+ } + /**
* Logs an error message with an object dump
*
@@ -76,27 +76,27 @@ class Hybrid_Logger { * @return void
*/
public static function error($message, $object = null) {
- if (isset(Hybrid_Auth::$config["debug_mode"]) && in_array(Hybrid_Auth::$config["debug_mode"], array(true, 'info', 'error'), true)) {
- $dt = new DateTime('now', new DateTimeZone( 'UTC' ));
- file_put_contents(Hybrid_Auth::$config["debug_file"], implode(' -- ', array(
+ if (isset(Hybrid_Auth::$config["debug_mode"]) && in_array(Hybrid_Auth::$config["debug_mode"], [true, 'info', 'error'], true)) {
+ $dt = new DateTime('now', new DateTimeZone( 'UTC' ));
+ file_put_contents(Hybrid_Auth::$config["debug_file"], implode(' -- ', [
'ERROR',
$_SERVER['REMOTE_ADDR'],
$dt->format(DATE_ATOM),
$message,
- print_r($object, true) . PHP_EOL
- )), FILE_APPEND);
+ print_r($object, true) . PHP_EOL,
+ ]), FILE_APPEND);
}
- }
-
- /**
- * Dumps the data in the way suitable to be output in log files for debug purposes
- *
- * @param mixed $data
- *
- * @return string
- */
- public static function dumpData($data) {
+ } + + /**
+ * Dumps the data in the way suitable to be output in log files for debug purposes
+ *
+ * @param mixed $data
+ *
+ * @return string
+ */
+ public static function dumpData($data) {
return var_export($data, true);
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/Provider_Adapter.php b/hauth/Hybrid/Provider_Adapter.php index f96a500..e440aec 100644 --- a/hauth/Hybrid/Provider_Adapter.php +++ b/hauth/Hybrid/Provider_Adapter.php @@ -1,11 +1,11 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_Provider_Adapter is the basic class which Hybrid_Auth will use
* to connect users to a given provider.
@@ -16,38 +16,38 @@ * Hybrid_Auth will automatically load Hybrid_Provider_Adapter and create
* an instance of it for each authenticated provider.
*/
-class Hybrid_Provider_Adapter {
-
+class Hybrid_Provider_Adapter { + /**
* Provider ID (or unique name)
* @var mixed
*/
- public $id = null;
-
+ public $id = null; + /**
* Provider adapter specific config
* @var array
*/
- public $config = null;
-
+ public $config = null; + /**
* Provider adapter extra parameters
* @var array
*/
- public $params = array();
-
+ public $params = []; + /**
* Provider adapter wrapper path
* @var string
*/
- public $wrapper = null;
-
+ public $wrapper = null; + /**
* Provider adapter instance
* @var Hybrid_Provider_Model
*/
- public $adapter = null;
-
+ public $adapter = null; + /**
* Create a new adapter switch IDp name or ID
*
@@ -56,53 +56,53 @@ class Hybrid_Provider_Adapter { * @return Hybrid_Provider_Adapter
* @throws Exception
*/
- function factory($id, $params = array()) {
- Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::factory( $id )");
-
+ function factory($id, $params = []) {
+ Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::factory( $id )"); + # init the adapter config and params
$this->id = $id;
$this->params = $params;
$this->id = $this->getProviderCiId($this->id);
- $this->config = $this->getConfigById($this->id);
-
+ $this->config = $this->getConfigById($this->id); + # check the IDp id
if (!$this->id) {
- throw new Exception("No provider ID specified.", 2);
- }
-
+ throw new Exception("No provider ID specified.", 2); + } + # check the IDp config
if (!$this->config) {
- throw new Exception("Unknown Provider ID, check your configuration file.", 3);
- }
-
+ throw new Exception("Unknown Provider ID, check your configuration file.", 3); + } + # check the IDp adapter is enabled
if (!$this->config["enabled"]) {
- throw new Exception("The provider '{$this->id}' is not enabled.", 3);
- }
-
+ throw new Exception("The provider '{$this->id}' is not enabled.", 3); + } + # include the adapter wrapper
if (isset($this->config["wrapper"]) && is_array($this->config["wrapper"])) {
if (isset($this->config["wrapper"]["path"])) {
require_once $this->config["wrapper"]["path"];
- }
-
+ } + if (!class_exists($this->config["wrapper"]["class"])) {
- throw new Exception("Unable to load the adapter class.", 3);
- }
-
+ throw new Exception("Unable to load the adapter class.", 3); + } + $this->wrapper = $this->config["wrapper"]["class"];
} else {
- require_once Hybrid_Auth::$config["path_providers"] . $this->id . ".php";
-
+ require_once Hybrid_Auth::$config["path_providers"] . $this->id . ".php"; + $this->wrapper = "Hybrid_Providers_" . $this->id;
- }
-
+ } + # create the adapter instance, and pass the current params and config
- $this->adapter = new $this->wrapper($this->id, $this->config, $this->params);
-
+ $this->adapter = new $this->wrapper($this->id, $this->config, $this->params); + return $this;
- }
-
+ } + /**
* Hybrid_Provider_Adapter::login(), prepare the user session and the authentication request
* for index.php
@@ -110,22 +110,22 @@ class Hybrid_Provider_Adapter { * @throw Exception
*/
function login() {
- Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::login( {$this->id} ) ");
-
+ Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::login( {$this->id} ) "); + if (!$this->adapter) {
- throw new Exception("Hybrid_Provider_Adapter::login() should not directly used.");
- }
-
+ throw new Exception("Hybrid_Provider_Adapter::login() should not directly used."); + } + // clear all unneeded params
foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
Hybrid_Auth::storage()->delete("hauth_session.{$idpid}.hauth_return_to");
Hybrid_Auth::storage()->delete("hauth_session.{$idpid}.hauth_endpoint");
Hybrid_Auth::storage()->delete("hauth_session.{$idpid}.id_provider_params");
- }
-
+ } + // make a fresh start
- $this->logout();
-
+ $this->logout(); + # get hybridauth base url
if (empty(Hybrid_Auth::$config["base_url"])) {
// the base url wasn't provide, so we must use the current
@@ -136,86 +136,86 @@ class Hybrid_Provider_Adapter { $HYBRID_AUTH_URL_BASE = $url;
} else {
$HYBRID_AUTH_URL_BASE = Hybrid_Auth::$config["base_url"];
- }
-
+ } + // make sure params is array
if (!is_array($this->params)) {
- $this->params = array();
- }
-
+ $this->params = [];
+ } + # we make use of session_id() as storage hash to identify the current user
# using session_regenerate_id() will be a problem, but ..
- $this->params["hauth_token"] = session_id();
-
+ $this->params["hauth_token"] = session_id(); + # set request timestamp
- $this->params["hauth_time"] = time();
-
+ $this->params["hauth_time"] = time(); + # for default HybridAuth endpoint url hauth_login_start_url
# auth.start required the IDp ID
# auth.time optional login request timestamp
if (!isset($this->params["login_start"]) ) {
$this->params["login_start"] = $HYBRID_AUTH_URL_BASE . ( strpos($HYBRID_AUTH_URL_BASE, '?') ? '&' : '?' ) . "hauth.start={$this->id}&hauth.time={$this->params["hauth_time"]}";
- }
-
+ } + # for default HybridAuth endpoint url hauth_login_done_url
# auth.done required the IDp ID
if (!isset($this->params["login_done"]) ) {
$this->params["login_done"] = $HYBRID_AUTH_URL_BASE . ( strpos($HYBRID_AUTH_URL_BASE, '?') ? '&' : '?' ) . "hauth.done={$this->id}";
- }
-
+ } + # workaround to solve windows live authentication since microsoft disallowed redirect urls to contain any parameters
# http://mywebsite.com/path_to_hybridauth/?hauth.done=Live will not work
- if ($this->id=="Live") {
- $this->params["login_done"] = $HYBRID_AUTH_URL_BASE."live.php";
- }
-
+ if ($this->id=="Live") {
+ $this->params["login_done"] = $HYBRID_AUTH_URL_BASE."live.php";
+ } + # Workaround to fix broken callback urls for the Facebook OAuth client
if ($this->adapter->useSafeUrls) {
$this->params['login_done'] = str_replace('hauth.done', 'hauth_done', $this->params['login_done']);
- }
-
+ } + if (isset($this->params["hauth_return_to"])) {
Hybrid_Auth::storage()->set("hauth_session.{$this->id}.hauth_return_to", $this->params["hauth_return_to"]);
}
if (isset($this->params["login_done"])) {
Hybrid_Auth::storage()->set("hauth_session.{$this->id}.hauth_endpoint", $this->params["login_done"]);
}
- Hybrid_Auth::storage()->set("hauth_session.{$this->id}.id_provider_params", $this->params);
-
+ Hybrid_Auth::storage()->set("hauth_session.{$this->id}.id_provider_params", $this->params); + // store config to be used by the end point
- Hybrid_Auth::storage()->config("CONFIG", Hybrid_Auth::$config);
-
+ Hybrid_Auth::storage()->config("CONFIG", Hybrid_Auth::$config); + // move on
- Hybrid_Logger::debug("Hybrid_Provider_Adapter::login( {$this->id} ), redirect the user to login_start URL.");
-
+ Hybrid_Logger::debug("Hybrid_Provider_Adapter::login( {$this->id} ), redirect the user to login_start URL."); + // redirect
if (empty($this->params["redirect_mode"])) {
- Hybrid_Auth::redirect($this->params["login_start"]);
+ Hybrid_Auth::redirect($this->params["login_start"]);
} else {
Hybrid_Auth::redirect($this->params["login_start"],$this->params["redirect_mode"]);
}
- }
-
+ } + /**
* Let hybridauth forget all about the user for the current provider
* @return bool
*/
function logout() {
$this->adapter->logout();
- }
-
- // --------------------------------------------------------------------
-
+ } + + // -------------------------------------------------------------------- + /**
* Return true if the user is connected to the current provider
* @return bool
*/
public function isUserConnected() {
return $this->adapter->isUserConnected();
- }
-
- // --------------------------------------------------------------------
-
+ } + + // -------------------------------------------------------------------- + /**
* Call adapter methods defined in the adapter model:
* getUserProfile()
@@ -229,19 +229,19 @@ class Hybrid_Provider_Adapter { * @throws Exception
*/
public function __call($name, $arguments) {
- Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::$name(), Provider: {$this->id}");
-
+ Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::$name(), Provider: {$this->id}"); + if (!$this->isUserConnected()) {
- throw new Exception("User not connected to the provider {$this->id}.", 7);
- }
-
+ throw new Exception("User not connected to the provider {$this->id}.", 7); + } + if (!method_exists($this->adapter, $name)) {
- throw new Exception("Call to undefined function Hybrid_Providers_{$this->id}::$name().");
- }
-
- return call_user_func_array(array($this->adapter, $name), $arguments);
- }
-
+ throw new Exception("Call to undefined function Hybrid_Providers_{$this->id}::$name()."); + } + + return call_user_func_array([$this->adapter, $name], $arguments);
+ } + /**
* If the user is connected, then return the access_token and access_token_secret
* if the provider api use oauth
@@ -260,18 +260,18 @@ class Hybrid_Provider_Adapter { public function getAccessToken() {
if (!$this->adapter->isUserConnected()) {
Hybrid_Logger::error("User not connected to the provider.");
- throw new Exception("User not connected to the provider.", 7);
- }
-
- return array(
+ throw new Exception("User not connected to the provider.", 7); + } + + return [
"access_token" => $this->adapter->token("access_token"), // OAuth access token
"access_token_secret" => $this->adapter->token("access_token_secret"), // OAuth access token secret
"refresh_token" => $this->adapter->token("refresh_token"), // OAuth refresh token
"expires_in" => $this->adapter->token("expires_in"), // OPTIONAL. The duration in seconds of the access token lifetime
"expires_at" => $this->adapter->token("expires_at"), // OPTIONAL. Timestamp when the access_token expire. if not provided by the social api, then it should be calculated: expires_at = now + expires_in
- );
- }
-
+ ];
+ } + /**
* Naive getter of the current connected IDp API client
* @return stdClass
@@ -279,36 +279,36 @@ class Hybrid_Provider_Adapter { */
function api() {
if (!$this->adapter->isUserConnected()) {
- Hybrid_Logger::error("User not connected to the provider.");
-
- throw new Exception("User not connected to the provider.", 7);
+ Hybrid_Logger::error("User not connected to the provider."); + + throw new Exception("User not connected to the provider.", 7); }
return $this->adapter->api;
- }
-
+ } + /**
* Redirect the user to hauth_return_to (the callback url)
* @return void
*/
function returnToCallbackUrl() {
// get the stored callback url
- $callback_url = Hybrid_Auth::storage()->get("hauth_session.{$this->id}.hauth_return_to");
-
+ $callback_url = Hybrid_Auth::storage()->get("hauth_session.{$this->id}.hauth_return_to"); + // if the user presses the back button in the browser and we already deleted the hauth_return_to from
// the session in the previous request, we will redirect to '/' instead of displaying a blank page.
if (!$callback_url) {
$callback_url = '/';
- }
-
+ } + // remove some unneeded stored data
Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_return_to");
Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_endpoint");
- Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.id_provider_params");
-
+ Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.id_provider_params"); + // back to home
Hybrid_Auth::redirect($callback_url);
- }
-
+ } + /**
* Return the provider config by id
*
@@ -320,8 +320,8 @@ class Hybrid_Provider_Adapter { return Hybrid_Auth::$config["providers"][$id];
}
return null;
- }
-
+ } + /**
* Return the provider config by id; case insensitive
*
@@ -335,6 +335,6 @@ class Hybrid_Provider_Adapter { }
}
return null;
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/Provider_Model.php b/hauth/Hybrid/Provider_Model.php index cd72f54..5364542 100644 --- a/hauth/Hybrid/Provider_Model.php +++ b/hauth/Hybrid/Provider_Model.php @@ -1,11 +1,11 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_Provider_Model provide a common interface for supported IDps on HybridAuth.
*
@@ -20,56 +20,56 @@ * Class Hybrid_Provider_Model_OAuth1 for providers that uses the OAuth 1 protocol.
* Class Hybrid_Provider_Model_OAuth2 for providers that uses the OAuth 2 protocol.
*/
-abstract class Hybrid_Provider_Model {
-
+abstract class Hybrid_Provider_Model { + /**
* IDp ID (or unique name)
* @var mixed
*/
- public $providerId = null;
-
+ public $providerId = null; + /**
* Specific provider adapter config
* @var array
*/
- public $config = null;
-
+ public $config = null; + /**
* Provider extra parameters
* @var array
*/
- public $params = null;
-
+ public $params = null; + /**
* Endpoint URL for that provider
* @var string
*/
- public $endpoint = null;
-
+ public $endpoint = null; + /**
* Hybrid_User obj, represents the current loggedin user
* @var Hybrid_User
*/
- public $user = null;
-
+ public $user = null; + /**
* The provider api client (optional)
* @var stdClass
*/
- public $api = null;
-
+ public $api = null; + /**
* Model should use "gzip,deflate" for CURLOPT_ENCODING
* @var stdClass
*/
- public $compressed = false;
-
+ public $compressed = false; + /**
* Enable this to replace '.' with '_' characters in the callback urls
* @var bool $useSafeUrls
*/
- public $useSafeUrls = false;
-
+ public $useSafeUrls = false; + /**
* Common providers adapter constructor
*
@@ -78,32 +78,32 @@ abstract class Hybrid_Provider_Model { * @param array $params Provider extra params
*/
function __construct($providerId, $config, $params = null) {
- # init the IDp adapter parameters, get them from the cache if possible
- if (!$params) {
- $this->params = Hybrid_Auth::storage()->get("hauth_session.$providerId.id_provider_params");
- } else {
- $this->params = $params;
- }
-
- // idp id
- $this->providerId = $providerId;
-
- // set HybridAuth endpoint for this provider
- $this->endpoint = Hybrid_Auth::storage()->get("hauth_session.$providerId.hauth_endpoint");
-
- // idp config
- $this->config = $config;
-
- // new user instance
- $this->user = new Hybrid_User();
- $this->user->providerId = $providerId;
-
- // initialize the current provider adapter
- $this->initialize();
-
- Hybrid_Logger::debug("Hybrid_Provider_Model::__construct( $providerId ) initialized. dump current adapter instance: ", serialize($this));
- }
-
+ # init the IDp adapter parameters, get them from the cache if possible
+ if (!$params) {
+ $this->params = Hybrid_Auth::storage()->get("hauth_session.$providerId.id_provider_params");
+ } else {
+ $this->params = $params;
+ } + + // idp id
+ $this->providerId = $providerId; + + // set HybridAuth endpoint for this provider
+ $this->endpoint = Hybrid_Auth::storage()->get("hauth_session.$providerId.hauth_endpoint"); + + // idp config
+ $this->config = $config; + + // new user instance
+ $this->user = new Hybrid_User();
+ $this->user->providerId = $providerId; + + // initialize the current provider adapter
+ $this->initialize(); + + Hybrid_Logger::debug("Hybrid_Provider_Model::__construct( $providerId ) initialized. dump current adapter instance: ", serialize($this));
+ } + /**
* IDp wrappers initializer
*
@@ -116,157 +116,156 @@ abstract class Hybrid_Provider_Model { * @return void
* @throws Exception
*/
- abstract protected function initialize();
-
+ abstract protected function initialize(); + /**
* Begin login
*
* @return void
* @throws Exception
*/
- abstract public function loginBegin();
-
+ abstract public function loginBegin(); + /**
* Finish login
* @return void
* @throws Exception
*/
- abstract public function loginFinish();
-
-
+ abstract public function loginFinish(); + /**
* Require autoload.php for 3rd party libraries
*/
protected function autoLoaderInit() {
- // Check if there is SDK in thirdparty/[providerId].
- $filename = Hybrid_Auth::$config["path_libraries"] . "{$this->providerId}/autoload.php";
- if (file_exists($filename)) {
- require_once $filename;
- }
- else {
- // If Composer install was executed, try to find autoload.php.
- $vendorDir = dirname(Hybrid_Auth::$config['path_base']);
- do {
- if (file_exists($vendorDir . "/vendor/autoload.php")) {
- require_once $vendorDir . "/vendor/autoload.php";
- break;
- }
- } while (($vendorDir = dirname($vendorDir)) !== '/');
- }
- }
-
+ // Check if there is SDK in thirdparty/[providerId].
+ $filename = Hybrid_Auth::$config["path_libraries"] . "{$this->providerId}/autoload.php";
+ if (file_exists($filename)) {
+ require_once $filename;
+ }
+ else {
+ // If Composer install was executed, try to find autoload.php.
+ $vendorDir = dirname(Hybrid_Auth::$config['path_base']);
+ do {
+ if (file_exists($vendorDir . "/vendor/autoload.php")) {
+ require_once $vendorDir . "/vendor/autoload.php";
+ break;
+ }
+ } while (($vendorDir = dirname($vendorDir)) !== '/');
+ }
+ } + /**
* Generic logout, just erase current provider adapter stored data to let Hybrid_Auth all forget about it
* @return bool
*/
function logout() {
- Hybrid_Logger::info("Enter [{$this->providerId}]::logout()");
- $this->clearTokens();
- return true;
- }
-
+ Hybrid_Logger::info("Enter [{$this->providerId}]::logout()");
+ $this->clearTokens();
+ return true;
+ } + /**
* Grab the user profile from the IDp api client
* @return Hybrid_User_Profile
* @throws Exception
*/
function getUserProfile() {
- Hybrid_Logger::error("HybridAuth do not provide users contacts list for {$this->providerId} yet.");
- throw new Exception("Provider does not support this feature.", 8);
- }
-
+ Hybrid_Logger::error("HybridAuth do not provide users contacts list for {$this->providerId} yet.");
+ throw new Exception("Provider does not support this feature.", 8); + } + /**
* Load the current logged in user contacts list from the IDp api client
* @return Hybrid_User_Contact[]
* @throws Exception
*/
function getUserContacts() {
- Hybrid_Logger::error("HybridAuth do not provide users contacts list for {$this->providerId} yet.");
- throw new Exception("Provider does not support this feature.", 8);
- }
-
+ Hybrid_Logger::error("HybridAuth do not provide users contacts list for {$this->providerId} yet.");
+ throw new Exception("Provider does not support this feature.", 8); + } + /**
* Return the user activity stream
* @return Hybrid_User_Activity[]
* @throws Exception
*/
function getUserActivity($stream) {
- Hybrid_Logger::error("HybridAuth do not provide user's activity stream for {$this->providerId} yet.");
- throw new Exception("Provider does not support this feature.", 8);
- }
-
+ Hybrid_Logger::error("HybridAuth do not provide user's activity stream for {$this->providerId} yet.");
+ throw new Exception("Provider does not support this feature.", 8); + } + /**
* Set user status
* @return mixed Provider response
* @throws Exception
*/
function setUserStatus($status) {
- Hybrid_Logger::error("HybridAuth do not provide user's activity stream for {$this->providerId} yet.");
- throw new Exception("Provider does not support this feature.", 8);
- }
-
+ Hybrid_Logger::error("HybridAuth do not provide user's activity stream for {$this->providerId} yet.");
+ throw new Exception("Provider does not support this feature.", 8); + } + /**
* Return the user status
* @return mixed Provider response
* @throws Exception
*/
function getUserStatus($statusid) {
- Hybrid_Logger::error("HybridAuth do not provide user's status for {$this->providerId} yet.");
- throw new Exception("Provider does not support this feature.", 8);
- }
-
+ Hybrid_Logger::error("HybridAuth do not provide user's status for {$this->providerId} yet.");
+ throw new Exception("Provider does not support this feature.", 8); + } + /**
* Return true if the user is connected to the current provider
* @return bool
*/
public function isUserConnected() {
- return (bool) Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.is_logged_in");
- }
-
+ return (bool) Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.is_logged_in");
+ } + /**
* Set user to connected
* @return void
*/
public function setUserConnected() {
- Hybrid_Logger::info("Enter [{$this->providerId}]::setUserConnected()");
- Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.is_logged_in", 1);
- }
-
+ Hybrid_Logger::info("Enter [{$this->providerId}]::setUserConnected()");
+ Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.is_logged_in", 1);
+ } + /**
* Set user to unconnected
* @return void
*/
public function setUserUnconnected() {
- Hybrid_Logger::info("Enter [{$this->providerId}]::setUserUnconnected()");
- Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.is_logged_in", 0);
- }
-
+ Hybrid_Logger::info("Enter [{$this->providerId}]::setUserUnconnected()");
+ Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.is_logged_in", 0);
+ } + /**
* Get or set a token
* @return string
*/
public function token($token, $value = null) {
- if ($value === null) {
- return Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.token.$token");
- } else {
- Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.token.$token", $value);
- }
- }
-
+ if ($value === null) {
+ return Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.token.$token");
+ }
+ Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.token.$token", $value); + + } + /**
* Delete a stored token
* @return void
*/
public function deleteToken($token) {
- Hybrid_Auth::storage()->delete("hauth_session.{$this->providerId}.token.$token");
- }
-
+ Hybrid_Auth::storage()->delete("hauth_session.{$this->providerId}.token.$token");
+ } + /**
* Clear all existent tokens for this provider
* @return void
*/
public function clearTokens() {
- Hybrid_Auth::storage()->deleteMatch("hauth_session.{$this->providerId}.");
- }
-
-}
+ Hybrid_Auth::storage()->deleteMatch("hauth_session.{$this->providerId}.");
+ } + +} diff --git a/hauth/Hybrid/Provider_Model_OAuth1.php b/hauth/Hybrid/Provider_Model_OAuth1.php index 23fd2d3..f14ec4d 100644 --- a/hauth/Hybrid/Provider_Model_OAuth1.php +++ b/hauth/Hybrid/Provider_Model_OAuth1.php @@ -1,11 +1,11 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* To implement an OAuth 1 based service provider, Hybrid_Provider_Model_OAuth1
* can be used to save the hassle of the authentication flow.
@@ -18,26 +18,26 @@ * Hybrid_Provider_Model_OAuth1 use OAuth1Client v0.1 which can be found on
* Hybrid/thirdparty/OAuth/OAuth1Client.php
*/
-class Hybrid_Provider_Model_OAuth1 extends Hybrid_Provider_Model {
-
+class Hybrid_Provider_Model_OAuth1 extends Hybrid_Provider_Model { + /**
* Provider API client
* @var OAuth1Client
*/
- public $api = null;
-
+ public $api = null; + /**
* Request_tokens as received from provider
* @var stdClas
*/
- public $request_tokens_raw = null;
-
+ public $request_tokens_raw = null; + /**
* Access_tokens as received from provider
* @var stdClass
*/
- public $access_tokens_raw = null;
-
+ public $access_tokens_raw = null; + /**
* Try to get the error message from provider api
*
@@ -45,7 +45,7 @@ class Hybrid_Provider_Model_OAuth1 extends Hybrid_Provider_Model { * @return string
*/
function errorMessageByStatus($code = null) {
- $http_status_codes = array(
+ $http_status_codes = [
200 => "OK: Success!",
304 => "Not Modified: There was no new data to return.",
400 => "Bad Request: The request was invalid.",
@@ -55,120 +55,120 @@ class Hybrid_Provider_Model_OAuth1 extends Hybrid_Provider_Model { 406 => "Not Acceptable.",
500 => "Internal Server Error: Something is broken.",
502 => "Bad Gateway.",
- 503 => "Service Unavailable."
- );
-
+ 503 => "Service Unavailable.",
+ ]; + if (!$code && $this->api) {
$code = $this->api->http_code;
- }
-
+ } + if (isset($http_status_codes[$code])) {
return $code . " " . $http_status_codes[$code];
}
- }
-
+ } + /**
* {@inheritdoc}
*/
function initialize() {
// 1 - check application credentials
if (!$this->config["keys"]["key"] || !$this->config["keys"]["secret"]) {
- throw new Exception("Your application key and secret are required in order to connect to {$this->providerId}.", 4);
- }
-
+ throw new Exception("Your application key and secret are required in order to connect to {$this->providerId}.", 4); + } + // 2 - include OAuth lib and client
if (! class_exists('OAuthConsumer') ) {
- require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth.php";
- }
- require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth1Client.php";
-
+ require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth.php";
+ }
+ require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth1Client.php"; + // 3.1 - setup access_token if any stored
if ($this->token("access_token")) {
$this->api = new OAuth1Client(
- $this->config["keys"]["key"], $this->config["keys"]["secret"], $this->token("access_token"), $this->token("access_token_secret")
+ $this->config["keys"]["key"], $this->config["keys"]["secret"], $this->token("access_token"), $this->token("access_token_secret"),
);
- }
-
+ } + // 3.2 - setup request_token if any stored, in order to exchange with an access token
elseif ($this->token("request_token")) {
$this->api = new OAuth1Client(
- $this->config["keys"]["key"], $this->config["keys"]["secret"], $this->token("request_token"), $this->token("request_token_secret")
+ $this->config["keys"]["key"], $this->config["keys"]["secret"], $this->token("request_token"), $this->token("request_token_secret"),
);
- }
-
+ } + // 3.3 - instanciate OAuth client with client credentials
else {
$this->api = new OAuth1Client($this->config["keys"]["key"], $this->config["keys"]["secret"]);
- }
-
+ } + // Set curl proxy if exist
if (isset(Hybrid_Auth::$config["proxy"])) {
$this->api->curl_proxy = Hybrid_Auth::$config["proxy"];
}
- }
-
+ } + /**
* {@inheritdoc}
*/
function loginBegin() {
- $tokens = $this->api->requestToken($this->endpoint);
-
+ $tokens = $this->api->requestToken($this->endpoint); + // request tokens as received from provider
- $this->request_tokens_raw = $tokens;
-
+ $this->request_tokens_raw = $tokens; + // check the last HTTP status code returned
if ($this->api->http_code != 200) {
- throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
- }
-
+ throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5); + } + if (!isset($tokens["oauth_token"])) {
- throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth token.", 5);
- }
-
+ throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth token.", 5); + } + $this->token("request_token", $tokens["oauth_token"]);
- $this->token("request_token_secret", $tokens["oauth_token_secret"]);
-
+ $this->token("request_token_secret", $tokens["oauth_token_secret"]); + # redirect the user to the provider authentication url
Hybrid_Auth::redirect($this->api->authorizeUrl($tokens));
- }
-
+ } + /**
* {@inheritdoc}
*/
function loginFinish() {
$oauth_token = (array_key_exists('oauth_token', $_REQUEST)) ? $_REQUEST['oauth_token'] : "";
- $oauth_verifier = (array_key_exists('oauth_verifier', $_REQUEST)) ? $_REQUEST['oauth_verifier'] : "";
-
+ $oauth_verifier = (array_key_exists('oauth_verifier', $_REQUEST)) ? $_REQUEST['oauth_verifier'] : ""; + if (!$oauth_token || !$oauth_verifier) {
- throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth verifier.", 5);
- }
-
+ throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth verifier.", 5); + } + // request an access token
- $tokens = $this->api->accessToken($oauth_verifier);
-
+ $tokens = $this->api->accessToken($oauth_verifier); + // access tokens as received from provider
- $this->access_tokens_raw = $tokens;
-
+ $this->access_tokens_raw = $tokens; + // check the last HTTP status code returned
if ($this->api->http_code != 200) {
- throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
- }
-
+ throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5); + } + // we should have an access_token, or else, something has gone wrong
if (!isset($tokens["oauth_token"])) {
- throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
- }
-
+ throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5); + } + // we no more need to store request tokens
$this->deleteToken("request_token");
- $this->deleteToken("request_token_secret");
-
+ $this->deleteToken("request_token_secret"); + // store access_token for later user
$this->token("access_token", $tokens['oauth_token']);
- $this->token("access_token_secret", $tokens['oauth_token_secret']);
-
+ $this->token("access_token_secret", $tokens['oauth_token_secret']); + // set user as logged in to the current provider
$this->setUserConnected();
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/Provider_Model_OAuth2.php b/hauth/Hybrid/Provider_Model_OAuth2.php index b9de4e2..d0825a5 100644 --- a/hauth/Hybrid/Provider_Model_OAuth2.php +++ b/hauth/Hybrid/Provider_Model_OAuth2.php @@ -1,11 +1,11 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* To implement an OAuth 2 based service provider, Hybrid_Provider_Model_OAuth2
* can be used to save the hassle of the authentication flow.
@@ -18,20 +18,20 @@ * Hybrid_Provider_Model_OAuth2 use OAuth2Client v0.1 which can be found on
* Hybrid/thirdparty/OAuth/OAuth2Client.php
*/
-class Hybrid_Provider_Model_OAuth2 extends Hybrid_Provider_Model {
-
+class Hybrid_Provider_Model_OAuth2 extends Hybrid_Provider_Model { + /**
* Default permissions
* @var string
*/
- public $scope = "";
-
+ public $scope = ""; + /**
* Provider API wrapper
* @var OAuth2Client
*/
- public $api = null;
-
+ public $api = null; + /**
* Try to get the error message from provider api
*
@@ -39,146 +39,146 @@ class Hybrid_Provider_Model_OAuth2 extends Hybrid_Provider_Model { * @return string
*/
function errorMessageByStatus($code = null) {
- $http_status_codes = array(
- 200 => "OK: Success!",
- 304 => "Not Modified: There was no new data to return.",
- 400 => "Bad Request: The request was invalid.",
- 401 => "Unauthorized.",
- 403 => "Forbidden: The request is understood, but it has been refused.",
- 404 => "Not Found: The URI requested is invalid or the resource requested does not exists.",
- 406 => "Not Acceptable.",
- 500 => "Internal Server Error: Something is broken.",
- 502 => "Bad Gateway.",
- 503 => "Service Unavailable."
- );
-
- if (!$code && $this->api) {
- $code = $this->api->http_code;
- }
-
- if (isset($http_status_codes[$code])) {
- return $code . " " . $http_status_codes[$code];
- }
- }
-
+ $http_status_codes = [
+ 200 => "OK: Success!",
+ 304 => "Not Modified: There was no new data to return.",
+ 400 => "Bad Request: The request was invalid.",
+ 401 => "Unauthorized.",
+ 403 => "Forbidden: The request is understood, but it has been refused.",
+ 404 => "Not Found: The URI requested is invalid or the resource requested does not exists.",
+ 406 => "Not Acceptable.",
+ 500 => "Internal Server Error: Something is broken.",
+ 502 => "Bad Gateway.",
+ 503 => "Service Unavailable.",
+ ]; + + if (!$code && $this->api) {
+ $code = $this->api->http_code;
+ } + + if (isset($http_status_codes[$code])) {
+ return $code . " " . $http_status_codes[$code];
+ }
+ } + /**
* Adapter initializer
*/
function initialize() {
- if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) {
- throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4);
- }
-
- // override requested scope
- if (isset($this->config["scope"]) && !empty($this->config["scope"])) {
- $this->scope = $this->config["scope"];
- }
-
- // include OAuth2 client
- require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth2Client.php";
-
- // create a new OAuth2 client instance
- $this->api = new OAuth2Client($this->config["keys"]["id"], $this->config["keys"]["secret"], $this->endpoint, $this->compressed);
-
- // If we have an access token, set it
- if ($this->token("access_token")) {
- $this->api->access_token = $this->token("access_token");
- $this->api->refresh_token = $this->token("refresh_token");
- $this->api->access_token_expires_in = $this->token("expires_in");
- $this->api->access_token_expires_at = $this->token("expires_at");
- }
-
- // Set curl proxy if exist
- if (isset(Hybrid_Auth::$config["proxy"])) {
- $this->api->curl_proxy = Hybrid_Auth::$config["proxy"];
- }
- }
-
+ if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) {
+ throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4); + } + + // override requested scope
+ if (isset($this->config["scope"]) && !empty($this->config["scope"])) {
+ $this->scope = $this->config["scope"];
+ } + + // include OAuth2 client
+ require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth2Client.php"; + + // create a new OAuth2 client instance
+ $this->api = new OAuth2Client($this->config["keys"]["id"], $this->config["keys"]["secret"], $this->endpoint, $this->compressed); + + // If we have an access token, set it
+ if ($this->token("access_token")) {
+ $this->api->access_token = $this->token("access_token");
+ $this->api->refresh_token = $this->token("refresh_token");
+ $this->api->access_token_expires_in = $this->token("expires_in");
+ $this->api->access_token_expires_at = $this->token("expires_at");
+ } + + // Set curl proxy if exist
+ if (isset(Hybrid_Auth::$config["proxy"])) {
+ $this->api->curl_proxy = Hybrid_Auth::$config["proxy"];
+ }
+ } + /**
* {@inheritdoc}
*/
function loginBegin() {
- // redirect the user to the provider authentication url
- Hybrid_Auth::redirect($this->api->authorizeUrl(array("scope" => $this->scope)));
- }
-
+ // redirect the user to the provider authentication url
+ Hybrid_Auth::redirect($this->api->authorizeUrl(["scope" => $this->scope]));
+ } + /**
* {@inheritdoc}
*/
function loginFinish() {
- $error = (array_key_exists('error', $_REQUEST)) ? $_REQUEST['error'] : "";
-
- // check for errors
- if ($error) {
- throw new Exception("Authentication failed! {$this->providerId} returned an error: $error", 5);
- }
-
- // try to authenticate user
- $code = (array_key_exists('code', $_REQUEST)) ? $_REQUEST['code'] : "";
-
- try {
- $this->api->authenticate($code);
- } catch (Exception $e) {
- throw new Exception("User profile request failed! {$this->providerId} returned an error: " . $e->getMessage(), 6);
- }
-
- // check if authenticated
- if (!$this->api->access_token) {
- throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
- }
-
- // store tokens
- $this->token("access_token", $this->api->access_token);
- $this->token("refresh_token", $this->api->refresh_token);
- $this->token("expires_in", $this->api->access_token_expires_in);
- $this->token("expires_at", $this->api->access_token_expires_at);
-
- // set user connected locally
- $this->setUserConnected();
- }
-
+ $error = (array_key_exists('error', $_REQUEST)) ? $_REQUEST['error'] : ""; + + // check for errors
+ if ($error) {
+ throw new Exception("Authentication failed! {$this->providerId} returned an error: $error", 5); + } + + // try to authenticate user
+ $code = (array_key_exists('code', $_REQUEST)) ? $_REQUEST['code'] : ""; + + try {
+ $this->api->authenticate($code);
+ } catch (Exception $e) {
+ throw new Exception("User profile request failed! {$this->providerId} returned an error: " . $e->getMessage(), 6); + } + + // check if authenticated
+ if (!$this->api->access_token) {
+ throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5); + } + + // store tokens
+ $this->token("access_token", $this->api->access_token);
+ $this->token("refresh_token", $this->api->refresh_token);
+ $this->token("expires_in", $this->api->access_token_expires_in);
+ $this->token("expires_at", $this->api->access_token_expires_at); + + // set user connected locally
+ $this->setUserConnected();
+ } + /**
* {@inheritdoc}
*/
function refreshToken() {
- // have an access token?
- if ($this->api->access_token) {
-
- // have to refresh?
- if ($this->api->refresh_token && $this->api->access_token_expires_at) {
-
- // expired?
- if ($this->api->access_token_expires_at <= time()) {
- $response = $this->api->refreshToken(array("refresh_token" => $this->api->refresh_token));
-
- if (!isset($response->access_token) || !$response->access_token) {
- // set the user as disconnected at this point and throw an exception
- $this->setUserUnconnected();
-
- throw new Exception("The Authorization Service has return an invalid response while requesting a new access token. " . (string) $response->error);
- }
-
- // set new access_token
- $this->api->access_token = $response->access_token;
-
- if (isset($response->refresh_token))
- $this->api->refresh_token = $response->refresh_token;
-
- if (isset($response->expires_in)) {
- $this->api->access_token_expires_in = $response->expires_in;
-
- // even given by some idp, we should calculate this
- $this->api->access_token_expires_at = time() + $response->expires_in;
- }
- }
- }
-
- // re store tokens
- $this->token("access_token", $this->api->access_token);
- $this->token("refresh_token", $this->api->refresh_token);
- $this->token("expires_in", $this->api->access_token_expires_in);
- $this->token("expires_at", $this->api->access_token_expires_at);
- }
- }
-
-}
+ // have an access token?
+ if ($this->api->access_token) { + + // have to refresh?
+ if ($this->api->refresh_token && $this->api->access_token_expires_at) { + + // expired?
+ if ($this->api->access_token_expires_at <= time()) {
+ $response = $this->api->refreshToken(["refresh_token" => $this->api->refresh_token]); + + if (!isset($response->access_token) || !$response->access_token) {
+ // set the user as disconnected at this point and throw an exception
+ $this->setUserUnconnected(); + + throw new Exception("The Authorization Service has return an invalid response while requesting a new access token. " . (string) $response->error); + } + + // set new access_token
+ $this->api->access_token = $response->access_token; + + if (isset($response->refresh_token))
+ $this->api->refresh_token = $response->refresh_token; + + if (isset($response->expires_in)) {
+ $this->api->access_token_expires_in = $response->expires_in; + + // even given by some idp, we should calculate this
+ $this->api->access_token_expires_at = time() + $response->expires_in;
+ }
+ }
+ } + + // re store tokens
+ $this->token("access_token", $this->api->access_token);
+ $this->token("refresh_token", $this->api->refresh_token);
+ $this->token("expires_in", $this->api->access_token_expires_in);
+ $this->token("expires_at", $this->api->access_token_expires_at);
+ }
+ } + +} diff --git a/hauth/Hybrid/Provider_Model_OpenID.php b/hauth/Hybrid/Provider_Model_OpenID.php index 08fa36c..a30e9ee 100644 --- a/hauth/Hybrid/Provider_Model_OpenID.php +++ b/hauth/Hybrid/Provider_Model_OpenID.php @@ -1,11 +1,11 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* To implement an OpenID based service provider, Hybrid_Provider_Model_OpenID
* can be used to save the hassle of the authentication flow.
@@ -16,56 +16,56 @@ * Hybrid_Provider_Model_OpenID use LightOpenID lib which can be found on
* Hybrid/thirdparty/OpenID/LightOpenID.php
*/
-class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model {
-
+class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model { + /**
* Provider API client
* @var LightOpenID
*/
- public $api = null;
-
+ public $api = null; + /**
* Openid provider identifier
* @var string
*/
- public $openidIdentifier = "";
-
+ public $openidIdentifier = ""; + /**
* {@inheritdoc}
*/
function initialize() {
if (isset($this->params["openid_identifier"])) {
$this->openidIdentifier = $this->params["openid_identifier"];
- }
-
+ } + // include LightOpenID lib
- require_once Hybrid_Auth::$config["path_libraries"] . "OpenID/LightOpenID.php";
-
+ require_once Hybrid_Auth::$config["path_libraries"] . "OpenID/LightOpenID.php"; + // An error was occurring when proxy wasn't set. Not sure where proxy was meant to be set/initialized.
- Hybrid_Auth::$config['proxy'] = isset(Hybrid_Auth::$config['proxy']) ? Hybrid_Auth::$config['proxy'] : '';
-
+ Hybrid_Auth::$config['proxy'] = Hybrid_Auth::$config['proxy'] ?? ''; + $hostPort = parse_url(Hybrid_Auth::$config["base_url"], PHP_URL_PORT);
- $hostUrl = parse_url(Hybrid_Auth::$config["base_url"], PHP_URL_HOST);
-
+ $hostUrl = parse_url(Hybrid_Auth::$config["base_url"], PHP_URL_HOST); + // Check for port on url
if ($hostPort) {
$hostUrl .= ':' . $hostPort;
- }
-
+ } + $this->api = new LightOpenID($hostUrl, Hybrid_Auth::$config["proxy"]);
- }
-
+ } + /**
* {@inheritdoc}
*/
function loginBegin() {
if (empty($this->openidIdentifier)) {
- throw new Exception("OpenID adapter require the identity provider identifier 'openid_identifier' as an extra parameter.", 4);
- }
-
+ throw new Exception("OpenID adapter require the identity provider identifier 'openid_identifier' as an extra parameter.", 4); + } + $this->api->identity = $this->openidIdentifier;
$this->api->returnUrl = $this->endpoint;
- $this->api->required = array(
+ $this->api->required = [
'namePerson/first',
'namePerson/last',
'namePerson/friendly',
@@ -81,32 +81,32 @@ class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model { 'contact/city/home',
'contact/country/home',
'media/image/default',
- );
-
+ ]; + # redirect the user to the provider authentication url
Hybrid_Auth::redirect($this->api->authUrl());
- }
-
+ } + /**
* {@inheritdoc}
*/
function loginFinish() {
# if user don't grant access of their data to your site, halt with an Exception
if ($this->api->mode == 'cancel') {
- throw new Exception("Authentication failed! User has canceled authentication!", 5);
- }
-
+ throw new Exception("Authentication failed! User has canceled authentication!", 5); + } + # if something goes wrong
if (!$this->api->validate()) {
- throw new Exception("Authentication failed. Invalid request received!", 5);
- }
-
+ throw new Exception("Authentication failed. Invalid request received!", 5); + } + # fetch received user data
- $response = $this->api->getAttributes();
-
+ $response = $this->api->getAttributes(); + # store the user profile
- $this->user->profile->identifier = $this->api->identity;
-
+ $this->user->profile->identifier = $this->api->identity; + $this->user->profile->firstName = (array_key_exists("namePerson/first", $response)) ? $response["namePerson/first"] : "";
$this->user->profile->lastName = (array_key_exists("namePerson/last", $response)) ? $response["namePerson/last"] : "";
$this->user->profile->displayName = (array_key_exists("namePerson", $response)) ? $response["namePerson"] : "";
@@ -115,56 +115,56 @@ class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model { $this->user->profile->country = (array_key_exists("contact/country/home", $response)) ? $response["contact/country/home"] : "";
$this->user->profile->zip = (array_key_exists("contact/postalCode/home", $response)) ? $response["contact/postalCode/home"] : "";
$this->user->profile->gender = (array_key_exists("person/gender", $response)) ? $response["person/gender"] : "";
- $this->user->profile->photoURL = (array_key_exists("media/image/default", $response)) ? $response["media/image/default"] : "";
-
+ $this->user->profile->photoURL = (array_key_exists("media/image/default", $response)) ? $response["media/image/default"] : ""; + $this->user->profile->birthDay = (array_key_exists("birthDate/birthDay", $response)) ? $response["birthDate/birthDay"] : "";
$this->user->profile->birthMonth = (array_key_exists("birthDate/birthMonth", $response)) ? $response["birthDate/birthMonth"] : "";
- $this->user->profile->birthYear = (array_key_exists("birthDate/birthDate", $response)) ? $response["birthDate/birthDate"] : "";
-
+ $this->user->profile->birthYear = (array_key_exists("birthDate/birthDate", $response)) ? $response["birthDate/birthDate"] : ""; + if (isset($response['namePerson/friendly']) && !empty($response['namePerson/friendly']) && !$this->user->profile->displayName) {
$this->user->profile->displayName = $response["namePerson/friendly"];
- }
-
+ } + if (isset($response['birthDate']) && !empty($response['birthDate']) && !$this->user->profile->birthDay) {
- list( $birthday_year, $birthday_month, $birthday_day ) = $response['birthDate'];
-
+ list( $birthday_year, $birthday_month, $birthday_day ) = $response['birthDate']; + $this->user->profile->birthDay = (int) $birthday_day;
$this->user->profile->birthMonth = (int) $birthday_month;
$this->user->profile->birthYear = (int) $birthday_year;
- }
-
+ } + if (!$this->user->profile->displayName) {
$this->user->profile->displayName = trim($this->user->profile->firstName . " " . $this->user->profile->lastName);
- }
-
+ } + if ($this->user->profile->gender == "f") {
$this->user->profile->gender = "female";
- }
-
+ } + if ($this->user->profile->gender == "m") {
$this->user->profile->gender = "male";
- }
-
+ } + // set user as logged in
- $this->setUserConnected();
-
+ $this->setUserConnected(); + // with openid providers we get the user profile only once, so store it
Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.user", $this->user);
- }
-
+ } + /**
* {@inheritdoc}
*/
function getUserProfile() {
// try to get the user profile from stored data
- $this->user = Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.user");
-
+ $this->user = Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.user"); + // if not found
if (!is_object($this->user)) {
- throw new Exception("User profile request failed! User is not connected to {$this->providerId} or his session has expired.", 6);
- }
-
+ throw new Exception("User profile request failed! User is not connected to {$this->providerId} or his session has expired.", 6); + } + return $this->user->profile;
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/Providers/AOL.php b/hauth/Hybrid/Providers/AOL.php index 19028c0..bb34d02 100644 --- a/hauth/Hybrid/Providers/AOL.php +++ b/hauth/Hybrid/Providers/AOL.php @@ -1,18 +1,18 @@ <?php
-
+ /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_Providers_AOL provider adapter based on OpenID protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_AOL.html
*/
-class Hybrid_Providers_AOL extends Hybrid_Provider_Model_OpenID {
-
- var $openidIdentifier = "http://openid.aol.com/";
-
-}
+class Hybrid_Providers_AOL extends Hybrid_Provider_Model_OpenID { + + var $openidIdentifier = "http://openid.aol.com/"; + +} diff --git a/hauth/Hybrid/Providers/Amazon.php b/hauth/Hybrid/Providers/Amazon.php index cc7d14c..f8a10de 100644 --- a/hauth/Hybrid/Providers/Amazon.php +++ b/hauth/Hybrid/Providers/Amazon.php @@ -48,7 +48,7 @@ class Hybrid_Providers_Amazon extends Hybrid_Provider_Model_OAuth2 { $this->api->authorize_url = 'https://www.amazon.com/ap/oa'; $this->api->token_url = 'https://api.amazon.com/auth/o2/token'; - $this->api->curl_header = array( 'Content-Type: application/x-www-form-urlencoded' ); + $this->api->curl_header = [ 'Content-Type: application/x-www-form-urlencoded' ]; // If we have an access token, set it if ( $this->token( 'access_token' ) ) { diff --git a/hauth/Hybrid/Providers/Dropbox.php b/hauth/Hybrid/Providers/Dropbox.php index cc072ab..f903d94 100644 --- a/hauth/Hybrid/Providers/Dropbox.php +++ b/hauth/Hybrid/Providers/Dropbox.php @@ -12,18 +12,18 @@ */ class Hybrid_Providers_Dropbox extends Hybrid_Provider_Model_OAuth2 -{ +{ /** * IDp wrappers initializer */ - function initialize() + function initialize() { parent::initialize(); // Provider apis end-points $this->api->api_base_url = "https://api.dropbox.com/1/"; $this->api->authorize_url = "https://www.dropbox.com/1/oauth2/authorize"; - $this->api->token_url = "https://api.dropbox.com/1/oauth2/token"; + $this->api->token_url = "https://api.dropbox.com/1/oauth2/token"; } /** @@ -31,7 +31,7 @@ class Hybrid_Providers_Dropbox extends Hybrid_Provider_Model_OAuth2 */ function getUserProfile() { - // refresh tokens if needed + // refresh tokens if needed $this->refreshToken(); try{ @@ -49,7 +49,7 @@ class Hybrid_Providers_Dropbox extends Hybrid_Provider_Model_OAuth2 if ( ! is_object( $response ) || ! isset( $response->uid ) ){ throw new Exception( "User profile request failed! {$this->providerId} api returned an invalid response.", 6 ); } - # store the user profile. + # store the user profile. $this->user->profile->identifier = (property_exists($response,'uid'))?$response->uid:""; $this->user->profile->profileURL = ""; $this->user->profile->webSiteURL = ""; diff --git a/hauth/Hybrid/Providers/Facebook.php b/hauth/Hybrid/Providers/Facebook.php index ab48370..c5c74e2 100644 --- a/hauth/Hybrid/Providers/Facebook.php +++ b/hauth/Hybrid/Providers/Facebook.php @@ -1,402 +1,401 @@ <?php
-
-use Facebook\Exceptions\FacebookSDKException;
-use Facebook\Facebook as FacebookSDK;
-
+ +use Facebook\Exceptions\FacebookSDKException; +use Facebook\Facebook as FacebookSDK; + /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_Providers_Facebook provider adapter based on OAuth2 protocol
* Hybrid_Providers_Facebook use the Facebook PHP SDK created by Facebook
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Facebook.html
*/
-class Hybrid_Providers_Facebook extends Hybrid_Provider_Model {
-
- /**
- * Default permissions, and a lot of them. You can change them from the configuration by setting the scope to what you want/need.
- * For a complete list see: https://developers.facebook.com/docs/facebook-login/permissions
- *
- * @link https://developers.facebook.com/docs/facebook-login/permissions
- * @var array $scope
- */
- public $scope = array('email', 'public_profile');
-
- /**
- * Provider API client
- *
- * @var \Facebook\Facebook
- */
- public $api;
-
- public $useSafeUrls = true;
-
- /**
- * {@inheritdoc}
- */
- function initialize() {
- if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) {
- throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4);
- }
-
- if (isset($this->config['scope'])) {
- $scope = $this->config['scope'];
- if (is_string($scope)) {
- $scope = explode(",", $scope);
- }
- $scope = array_map('trim', $scope);
- $this->scope = $scope;
- }
-
- $trustForwarded = isset($this->config['trustForwarded']) ? (bool)$this->config['trustForwarded'] : false;
-
- // Include 3rd-party SDK.
- $this->autoLoaderInit();
-
- $this->api = new FacebookSDK([
- 'app_id' => $this->config["keys"]["id"],
- 'app_secret' => $this->config["keys"]["secret"],
- 'default_graph_version' => !empty($this->config['default_graph_version']) ? $this->config['default_graph_version'] : 'v2.12',
- 'trustForwarded' => $trustForwarded,
- ]);
- }
-
- /**
- * {@inheritdoc}
- */
- function loginBegin() {
-
- $this->endpoint = $this->params['login_done'];
- $helper = $this->api->getRedirectLoginHelper();
-
- // Use re-request, because this will trigger permissions window if not all permissions are granted.
- $url = $helper->getReRequestUrl($this->endpoint, $this->scope);
-
- // Redirect to Facebook
- Hybrid_Auth::redirect($url);
- }
-
- /**
- * {@inheritdoc}
- */
- function loginFinish() {
-
- $helper = $this->api->getRedirectLoginHelper();
- if (isset($_GET['state'])) {
- $helper->getPersistentDataHandler()->set('state', $_GET['state']);
- }
- try {
- $accessToken = $helper->getAccessToken($this->params['login_done']);
- } catch (Facebook\Exceptions\FacebookResponseException $e) {
- throw new Hybrid_Exception('Facebook Graph returned an error: ' . $e->getMessage());
- } catch (Facebook\Exceptions\FacebookSDKException $e) {
- throw new Hybrid_Exception('Facebook SDK returned an error: ' . $e->getMessage());
- }
-
- if (!isset($accessToken)) {
- if ($helper->getError()) {
- throw new Hybrid_Exception(sprintf("Could not authorize user, reason: %s (%d)", $helper->getErrorDescription(), $helper->getErrorCode()));
- } else {
- throw new Hybrid_Exception("Could not authorize user. Bad request");
- }
- }
-
- try {
- // Validate token
- $oAuth2Client = $this->api->getOAuth2Client();
- $tokenMetadata = $oAuth2Client->debugToken($accessToken);
- $tokenMetadata->validateAppId($this->config["keys"]["id"]);
- $tokenMetadata->validateExpiration();
-
- // Exchanges a short-lived access token for a long-lived one
- if (!$accessToken->isLongLived()) {
- $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
- }
- } catch (FacebookSDKException $e) {
- throw new Hybrid_Exception($e->getMessage(), 0, $e);
- }
-
- $this->setUserConnected();
- $this->token("access_token", $accessToken->getValue());
- }
-
- /**
- * {@inheritdoc}
- */
- function logout() {
- parent::logout();
- }
-
- /**
- * Update user status
- *
- * @param mixed $status An array describing the status, or string
- * @param string $pageid (optional) User page id
- * @return array
- * @throw Exception
- */
- function setUserStatus($status, $pageid = null) {
-
- if (!is_array($status)) {
- $status = array('message' => $status);
- }
-
- $access_token = null;
-
- if (is_null($pageid)) {
- $pageid = 'me';
- $access_token = $this->token('access_token');
-
- // if post on page, get access_token page
- } else {
-
- foreach ($this->getUserPages(true) as $p) {
- if (isset($p['id']) && intval($p['id']) == intval($pageid)) {
- $access_token = $p['access_token'];
- break;
- }
- }
-
- if (is_null($access_token)) {
- throw new Exception("Update user page failed, page not found or not writable!");
- }
- }
-
- try {
- $response = $this->api->post('/' . $pageid . '/feed', $status, $access_token);
- } catch (FacebookSDKException $e) {
- throw new Exception("Update user status failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
- }
-
- return $response;
- }
-
- /**
- * {@inheridoc}
- */
+class Hybrid_Providers_Facebook extends Hybrid_Provider_Model { + + /**
+ * Default permissions, and a lot of them. You can change them from the configuration by setting the scope to what you want/need.
+ * For a complete list see: https://developers.facebook.com/docs/facebook-login/permissions
+ *
+ * @link https://developers.facebook.com/docs/facebook-login/permissions
+ * @var array $scope
+ */
+ public $scope = ['email', 'public_profile']; + + /**
+ * Provider API client
+ *
+ * @var \Facebook\Facebook
+ */
+ public $api; + + public $useSafeUrls = true; + + /**
+ * {@inheritdoc}
+ */
+ function initialize() {
+ if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) {
+ throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4); + } + + if (isset($this->config['scope'])) {
+ $scope = $this->config['scope'];
+ if (is_string($scope)) {
+ $scope = explode(",", $scope);
+ }
+ $scope = array_map('trim', $scope);
+ $this->scope = $scope;
+ } + + $trustForwarded = isset($this->config['trustForwarded']) ? (bool)$this->config['trustForwarded'] : false; + + // Include 3rd-party SDK.
+ $this->autoLoaderInit(); + + $this->api = new FacebookSDK([
+ 'app_id' => $this->config["keys"]["id"],
+ 'app_secret' => $this->config["keys"]["secret"],
+ 'default_graph_version' => !empty($this->config['default_graph_version']) ? $this->config['default_graph_version'] : 'v2.12',
+ 'trustForwarded' => $trustForwarded,
+ ]);
+ } + + /**
+ * {@inheritdoc}
+ */
+ function loginBegin() { + + $this->endpoint = $this->params['login_done'];
+ $helper = $this->api->getRedirectLoginHelper(); + + // Use re-request, because this will trigger permissions window if not all permissions are granted.
+ $url = $helper->getReRequestUrl($this->endpoint, $this->scope); + + // Redirect to Facebook
+ Hybrid_Auth::redirect($url);
+ } + + /**
+ * {@inheritdoc}
+ */
+ function loginFinish() { + + $helper = $this->api->getRedirectLoginHelper();
+ if (isset($_GET['state'])) {
+ $helper->getPersistentDataHandler()->set('state', $_GET['state']);
+ }
+ try {
+ $accessToken = $helper->getAccessToken($this->params['login_done']);
+ } catch (Facebook\Exceptions\FacebookResponseException $e) {
+ throw new Hybrid_Exception('Facebook Graph returned an error: ' . $e->getMessage()); + } catch (Facebook\Exceptions\FacebookSDKException $e) {
+ throw new Hybrid_Exception('Facebook SDK returned an error: ' . $e->getMessage()); + } + + if (!isset($accessToken)) {
+ if ($helper->getError()) {
+ throw new Hybrid_Exception(sprintf("Could not authorize user, reason: %s (%d)", $helper->getErrorDescription(), $helper->getErrorCode())); + }
+ throw new Hybrid_Exception("Could not authorize user. Bad request"); + } + + try {
+ // Validate token
+ $oAuth2Client = $this->api->getOAuth2Client();
+ $tokenMetadata = $oAuth2Client->debugToken($accessToken);
+ $tokenMetadata->validateAppId($this->config["keys"]["id"]);
+ $tokenMetadata->validateExpiration(); + + // Exchanges a short-lived access token for a long-lived one
+ if (!$accessToken->isLongLived()) {
+ $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
+ }
+ } catch (FacebookSDKException $e) {
+ throw new Hybrid_Exception($e->getMessage(), 0, $e); + } + + $this->setUserConnected();
+ $this->token("access_token", $accessToken->getValue());
+ } + + /**
+ * {@inheritdoc}
+ */
+ function logout() {
+ parent::logout();
+ } + + /**
+ * Update user status
+ *
+ * @param mixed $status An array describing the status, or string
+ * @param string $pageid (optional) User page id
+ * @return array
+ * @throw Exception
+ */
+ function setUserStatus($status, $pageid = null) { + + if (!is_array($status)) {
+ $status = ['message' => $status];
+ } + + $access_token = null; + + if (is_null($pageid)) {
+ $pageid = 'me';
+ $access_token = $this->token('access_token'); + + // if post on page, get access_token page
+ } else { + + foreach ($this->getUserPages(true) as $p) {
+ if (isset($p['id']) && (int) ($p['id']) == (int) $pageid) {
+ $access_token = $p['access_token'];
+ break;
+ }
+ } + + if (is_null($access_token)) {
+ throw new Exception("Update user page failed, page not found or not writable!"); + }
+ } + + try {
+ $response = $this->api->post('/' . $pageid . '/feed', $status, $access_token);
+ } catch (FacebookSDKException $e) {
+ throw new Exception("Update user status failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e); + } + + return $response;
+ } + + /**
+ * {@inheridoc}
+ */
function getUserPages($writableonly = false) {
- if (!in_array('manage_pages', $this->scope)) {
- throw new Exception("Get user pages requires manage_page permission!");
- }
-
- try {
- $pages = $this->api->get("/me/accounts", $this->token('access_token'));
- $pages = $pages->getDecodedBody();
- } catch (FacebookApiException $e) {
- throw new Exception("Cannot retrieve user pages! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
- }
-
- if (!isset($pages['data'])) {
- return array();
- }
-
- if (!$writableonly) {
- return $pages['data'];
- }
-
- $wrpages = array();
- foreach ($pages['data'] as $p) {
- if (isset($p['perms']) && in_array('CREATE_CONTENT', $p['perms'])) {
- $wrpages[] = $p;
- }
- }
-
- return $wrpages;
- }
-
- /**
- * {@inheritdoc}
- */
- function getUserProfile() {
- try {
- $fields = array(
- 'id',
- 'name',
- 'first_name',
- 'last_name',
- 'link',
- 'website',
- 'gender',
- 'locale',
- 'about',
- 'email',
- 'hometown',
- 'location',
- 'birthday'
- );
- $response = $this->api->get('/me?fields=' . implode(',', $fields), $this->token('access_token'));
- $data = $response->getDecodedBody();
- } catch (FacebookSDKException $e) {
- throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e);
- }
-
- // Store the user profile.
- $this->user->profile->identifier = (array_key_exists('id', $data)) ? $data['id'] : "";
- $this->user->profile->displayName = (array_key_exists('name', $data)) ? $data['name'] : "";
- $this->user->profile->firstName = (array_key_exists('first_name', $data)) ? $data['first_name'] : "";
- $this->user->profile->lastName = (array_key_exists('last_name', $data)) ? $data['last_name'] : "";
- $this->user->profile->photoURL = $this->getUserPhoto($this->user->profile->identifier);
- $this->user->profile->profileURL = (array_key_exists('link', $data)) ? $data['link'] : "";
- $this->user->profile->webSiteURL = (array_key_exists('website', $data)) ? $data['website'] : "";
- $this->user->profile->gender = (array_key_exists('gender', $data)) ? $data['gender'] : "";
- $this->user->profile->language = (array_key_exists('locale', $data)) ? $data['locale'] : "";
- $this->user->profile->description = (array_key_exists('about', $data)) ? $data['about'] : "";
- $this->user->profile->email = (array_key_exists('email', $data)) ? $data['email'] : "";
- $this->user->profile->emailVerified = (array_key_exists('email', $data)) ? $data['email'] : "";
- $this->user->profile->region = (array_key_exists("location", $data) && array_key_exists("name", $data['location'])) ? $data['location']["name"] : "";
-
- if (!empty($this->user->profile->region)) {
- $regionArr = explode(',', $this->user->profile->region);
- if (count($regionArr) > 1) {
- $this->user->profile->city = trim($regionArr[0]);
- $this->user->profile->country = trim(end($regionArr));
- }
- }
-
- if (array_key_exists('birthday', $data)) {
- $birtydayPieces = explode('/', $data['birthday']);
-
- if (count($birtydayPieces) == 1) {
- $this->user->profile->birthYear = (int)$birtydayPieces[0];
- } elseif (count($birtydayPieces) == 2) {
- $this->user->profile->birthMonth = (int)$birtydayPieces[0];
- $this->user->profile->birthDay = (int)$birtydayPieces[1];
- } elseif (count($birtydayPieces) == 3) {
- $this->user->profile->birthMonth = (int)$birtydayPieces[0];
- $this->user->profile->birthDay = (int)$birtydayPieces[1];
- $this->user->profile->birthYear = (int)$birtydayPieces[2];
- }
- }
-
- return $this->user->profile;
- }
-
- /**
- * Since the Graph API 2.0, the /friends endpoint only returns friend that also use your Facebook app.
- * {@inheritdoc}
- */
- function getUserContacts() {
- if (!in_array('user_friends', $this->scope)) {
- throw new Exception("Get user contacts requires user_friends permission!");
- }
-
- $apiCall = '?fields=link,name';
- $returnedContacts = array();
- $pagedList = true;
-
- while ($pagedList) {
- try {
- $response = $this->api->get('/me/friends' . $apiCall, $this->token('access_token'));
- $response = $response->getDecodedBody();
- } catch (FacebookSDKException $e) {
- throw new Hybrid_Exception("User contacts request failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
- }
-
- // Prepare the next call if paging links have been returned
- if (array_key_exists('paging', $response) && array_key_exists('next', $response['paging'])) {
- $pagedList = true;
- $next_page = explode('friends', $response['paging']['next']);
- $apiCall = $next_page[1];
- } else {
- $pagedList = false;
- }
-
- // Add the new page contacts
- $returnedContacts = array_merge($returnedContacts, $response['data']);
- }
-
- $contacts = array();
- foreach ($returnedContacts as $item) {
-
- $uc = new Hybrid_User_Contact();
- $uc->identifier = (array_key_exists("id", $item)) ? $item["id"] : "";
- $uc->displayName = (array_key_exists("name", $item)) ? $item["name"] : "";
- $uc->profileURL = (array_key_exists("link", $item)) ? $item["link"] : "https://www.facebook.com/profile.php?id=" . $uc->identifier;
- $uc->photoURL = $this->getUserPhoto($uc->identifier);
-
- $contacts[] = $uc;
- }
-
- return $contacts;
- }
-
- /**
- * Load the user latest activity, needs 'read_stream' permission
- *
- * @param string $stream Which activity to fetch:
- * - timeline : all the stream
- * - me : the user activity only
- * {@inheritdoc}
- */
- function getUserActivity($stream = 'timeline') {
- try {
- if ($stream == "me") {
- $response = $this->api->get('/me/feed', $this->token('access_token'));
- } else {
- $response = $this->api->get('/me/home', $this->token('access_token'));
- }
- $response = $response->getDecodedBody();
- } catch (FacebookSDKException $e) {
- throw new Hybrid_Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
- }
-
- if (!$response || !count($response['data'])) {
- return array();
- }
-
- $activities = array();
- foreach ($response['data'] as $item) {
-
- $ua = new Hybrid_User_Activity();
-
- $ua->id = (array_key_exists("id", $item)) ? $item["id"] : "";
- $ua->date = (array_key_exists("created_time", $item)) ? strtotime($item["created_time"]) : "";
-
- if ($item["type"] == "video") {
- $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
- }
-
- if ($item["type"] == "link") {
- $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
- }
-
- if (empty($ua->text) && isset($item["story"])) {
- $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
- }
-
- if (empty($ua->text) && isset($item["message"])) {
- $ua->text = (array_key_exists("message", $item)) ? $item["message"] : "";
- }
-
- if (!empty($ua->text)) {
- $ua->user->identifier = (array_key_exists("id", $item["from"])) ? $item["from"]["id"] : "";
- $ua->user->displayName = (array_key_exists("name", $item["from"])) ? $item["from"]["name"] : "";
- $ua->user->profileURL = "https://www.facebook.com/profile.php?id=" . $ua->user->identifier;
- $ua->user->photoURL = $this->getUserPhoto($ua->user->identifier);
-
- $activities[] = $ua;
- }
- }
-
- return $activities;
- }
-
- /**
- * Returns a photo URL for give user.
- *
- * @param string $id
- * The User ID.
- *
- * @return string
- * A photo URL.
- */
- function getUserPhoto($id) {
- $photo_size = isset($this->config['photo_size']) ? $this->config['photo_size'] : 150;
-
- return "https://graph.facebook.com/{$id}/picture?width={$photo_size}&height={$photo_size}";
- }
-
-}
+ if (!in_array('manage_pages', $this->scope)) {
+ throw new Exception("Get user pages requires manage_page permission!"); + } + + try {
+ $pages = $this->api->get("/me/accounts", $this->token('access_token'));
+ $pages = $pages->getDecodedBody();
+ } catch (FacebookApiException $e) {
+ throw new Exception("Cannot retrieve user pages! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e); + } + + if (!isset($pages['data'])) {
+ return [];
+ } + + if (!$writableonly) {
+ return $pages['data'];
+ } + + $wrpages = [];
+ foreach ($pages['data'] as $p) {
+ if (isset($p['perms']) && in_array('CREATE_CONTENT', $p['perms'])) {
+ $wrpages[] = $p;
+ }
+ } + + return $wrpages;
+ } + + /**
+ * {@inheritdoc}
+ */
+ function getUserProfile() {
+ try {
+ $fields = [
+ 'id',
+ 'name',
+ 'first_name',
+ 'last_name',
+ 'link',
+ 'website',
+ 'gender',
+ 'locale',
+ 'about',
+ 'email',
+ 'hometown',
+ 'location',
+ 'birthday',
+ ];
+ $response = $this->api->get('/me?fields=' . implode(',', $fields), $this->token('access_token'));
+ $data = $response->getDecodedBody();
+ } catch (FacebookSDKException $e) {
+ throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e); + } + + // Store the user profile.
+ $this->user->profile->identifier = (array_key_exists('id', $data)) ? $data['id'] : "";
+ $this->user->profile->displayName = (array_key_exists('name', $data)) ? $data['name'] : "";
+ $this->user->profile->firstName = (array_key_exists('first_name', $data)) ? $data['first_name'] : "";
+ $this->user->profile->lastName = (array_key_exists('last_name', $data)) ? $data['last_name'] : "";
+ $this->user->profile->photoURL = $this->getUserPhoto($this->user->profile->identifier);
+ $this->user->profile->profileURL = (array_key_exists('link', $data)) ? $data['link'] : "";
+ $this->user->profile->webSiteURL = (array_key_exists('website', $data)) ? $data['website'] : "";
+ $this->user->profile->gender = (array_key_exists('gender', $data)) ? $data['gender'] : "";
+ $this->user->profile->language = (array_key_exists('locale', $data)) ? $data['locale'] : "";
+ $this->user->profile->description = (array_key_exists('about', $data)) ? $data['about'] : "";
+ $this->user->profile->email = (array_key_exists('email', $data)) ? $data['email'] : "";
+ $this->user->profile->emailVerified = (array_key_exists('email', $data)) ? $data['email'] : "";
+ $this->user->profile->region = (array_key_exists("location", $data) && array_key_exists("name", $data['location'])) ? $data['location']["name"] : ""; + + if (!empty($this->user->profile->region)) {
+ $regionArr = explode(',', $this->user->profile->region);
+ if (count($regionArr) > 1) {
+ $this->user->profile->city = trim($regionArr[0]);
+ $this->user->profile->country = trim(end($regionArr));
+ }
+ } + + if (array_key_exists('birthday', $data)) {
+ $birtydayPieces = explode('/', $data['birthday']); + + if (count($birtydayPieces) == 1) {
+ $this->user->profile->birthYear = (int)$birtydayPieces[0];
+ } elseif (count($birtydayPieces) == 2) {
+ $this->user->profile->birthMonth = (int)$birtydayPieces[0];
+ $this->user->profile->birthDay = (int)$birtydayPieces[1];
+ } elseif (count($birtydayPieces) == 3) {
+ $this->user->profile->birthMonth = (int)$birtydayPieces[0];
+ $this->user->profile->birthDay = (int)$birtydayPieces[1];
+ $this->user->profile->birthYear = (int)$birtydayPieces[2];
+ }
+ } + + return $this->user->profile;
+ } + + /**
+ * Since the Graph API 2.0, the /friends endpoint only returns friend that also use your Facebook app.
+ * {@inheritdoc}
+ */
+ function getUserContacts() {
+ if (!in_array('user_friends', $this->scope)) {
+ throw new Exception("Get user contacts requires user_friends permission!"); + } + + $apiCall = '?fields=link,name';
+ $returnedContacts = [];
+ $pagedList = true; + + while ($pagedList) {
+ try {
+ $response = $this->api->get('/me/friends' . $apiCall, $this->token('access_token'));
+ $response = $response->getDecodedBody();
+ } catch (FacebookSDKException $e) {
+ throw new Hybrid_Exception("User contacts request failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e); + } + + // Prepare the next call if paging links have been returned
+ if (array_key_exists('paging', $response) && array_key_exists('next', $response['paging'])) {
+ $pagedList = true;
+ $next_page = explode('friends', $response['paging']['next']);
+ $apiCall = $next_page[1];
+ } else {
+ $pagedList = false;
+ } + + // Add the new page contacts
+ $returnedContacts = array_merge($returnedContacts, $response['data']);
+ } + + $contacts = [];
+ foreach ($returnedContacts as $item) { + + $uc = new Hybrid_User_Contact();
+ $uc->identifier = (array_key_exists("id", $item)) ? $item["id"] : "";
+ $uc->displayName = (array_key_exists("name", $item)) ? $item["name"] : "";
+ $uc->profileURL = (array_key_exists("link", $item)) ? $item["link"] : "https://www.facebook.com/profile.php?id=" . $uc->identifier;
+ $uc->photoURL = $this->getUserPhoto($uc->identifier); + + $contacts[] = $uc;
+ } + + return $contacts;
+ } + + /**
+ * Load the user latest activity, needs 'read_stream' permission
+ *
+ * @param string $stream Which activity to fetch:
+ * - timeline : all the stream
+ * - me : the user activity only
+ * {@inheritdoc}
+ */
+ function getUserActivity($stream = 'timeline') {
+ try {
+ if ($stream == "me") {
+ $response = $this->api->get('/me/feed', $this->token('access_token'));
+ } else {
+ $response = $this->api->get('/me/home', $this->token('access_token'));
+ }
+ $response = $response->getDecodedBody();
+ } catch (FacebookSDKException $e) {
+ throw new Hybrid_Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e); + } + + if (!$response || !count($response['data'])) {
+ return [];
+ } + + $activities = [];
+ foreach ($response['data'] as $item) { + + $ua = new Hybrid_User_Activity(); + + $ua->id = (array_key_exists("id", $item)) ? $item["id"] : "";
+ $ua->date = (array_key_exists("created_time", $item)) ? strtotime($item["created_time"]) : ""; + + if ($item["type"] == "video") {
+ $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
+ } + + if ($item["type"] == "link") {
+ $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
+ } + + if (empty($ua->text) && isset($item["story"])) {
+ $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
+ } + + if (empty($ua->text) && isset($item["message"])) {
+ $ua->text = (array_key_exists("message", $item)) ? $item["message"] : "";
+ } + + if (!empty($ua->text)) {
+ $ua->user->identifier = (array_key_exists("id", $item["from"])) ? $item["from"]["id"] : "";
+ $ua->user->displayName = (array_key_exists("name", $item["from"])) ? $item["from"]["name"] : "";
+ $ua->user->profileURL = "https://www.facebook.com/profile.php?id=" . $ua->user->identifier;
+ $ua->user->photoURL = $this->getUserPhoto($ua->user->identifier); + + $activities[] = $ua;
+ }
+ } + + return $activities;
+ } + + /**
+ * Returns a photo URL for give user.
+ *
+ * @param string $id
+ * The User ID.
+ *
+ * @return string
+ * A photo URL.
+ */
+ function getUserPhoto($id) {
+ $photo_size = $this->config['photo_size'] ?? 150; + + return "https://graph.facebook.com/{$id}/picture?width={$photo_size}&height={$photo_size}";
+ } + +} diff --git a/hauth/Hybrid/Providers/Foursquare.php b/hauth/Hybrid/Providers/Foursquare.php index 5c64e96..1a290fe 100644 --- a/hauth/Hybrid/Providers/Foursquare.php +++ b/hauth/Hybrid/Providers/Foursquare.php @@ -1,17 +1,17 @@ <?php
-
+ /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_Providers_Foursquare provider adapter based on OAuth2 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Foursquare.html
- */
-
+ */ + /**
* Howto define profile photo size:
* - add params key into hybridauth config
@@ -25,37 +25,37 @@ * - list of valid photo_size values is described here https://developer.foursquare.com/docs/responses/photo.html
* - default photo_size is 100x100
*/
-class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2 {
-
- private static $apiVersion = array("v" => "20120610");
- private static $defPhotoSize = "100x100";
-
+class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2 { + + private static $apiVersion = ["v" => "20120610"];
+ private static $defPhotoSize = "100x100"; + /**
* {@inheritdoc}
*/
function initialize() {
- parent::initialize();
-
+ parent::initialize(); + // Provider apis end-points
$this->api->api_base_url = "https://api.foursquare.com/v2/";
$this->api->authorize_url = "https://foursquare.com/oauth2/authenticate";
- $this->api->token_url = "https://foursquare.com/oauth2/access_token";
-
+ $this->api->token_url = "https://foursquare.com/oauth2/access_token"; + $this->api->sign_token_name = "oauth_token";
- }
-
+ } + /**
* {@inheritdoc}
*/
function getUserProfile() {
- $data = $this->api->api("users/self", "GET", Hybrid_Providers_Foursquare::$apiVersion);
-
+ $data = $this->api->api("users/self", "GET", Hybrid_Providers_Foursquare::$apiVersion); + if (!isset($data->response->user->id)) {
- throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $data ), 6);
- }
-
- $data = $data->response->user;
-
+ throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $data ), 6); + } + + $data = $data->response->user; + $this->user->profile->identifier = $data->id;
$this->user->profile->firstName = $data->firstName;
$this->user->profile->lastName = $data->lastName;
@@ -65,27 +65,27 @@ class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2 { $this->user->profile->gender = $data->gender;
$this->user->profile->city = $data->homeCity;
$this->user->profile->email = $data->contact->email;
- $this->user->profile->emailVerified = $data->contact->email;
-
+ $this->user->profile->emailVerified = $data->contact->email; + return $this->user->profile;
- }
-
+ } + /**
* {@inheritdoc}
*/
function getUserContacts() {
// refresh tokens if needed
- $this->refreshToken();
-
+ $this->refreshToken(); + //
- $response = array();
- $contacts = array();
+ $response = [];
+ $contacts = [];
try {
$response = $this->api->api("users/self/friends", "GET", Hybrid_Providers_Foursquare::$apiVersion);
} catch (Exception $e) {
- throw new Exception("User contacts request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
- }
-
+ throw new Exception("User contacts request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e); + } + if (isset($response) && $response->meta->code == 200) {
foreach ($response->response->friends->items as $contact) {
$uc = new Hybrid_User_Contact();
@@ -102,20 +102,20 @@ class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2 { }
}
return $contacts;
- }
-
+ } + /**
* {@inheritdoc}
*/
private function buildDisplayName($firstName, $lastName) {
return trim($firstName . " " . $lastName);
- }
-
+ } + private function buildPhotoURL($prefix, $suffix) {
if (isset($prefix) && isset($suffix)) {
return $prefix . ((isset($this->config["params"]["photo_size"])) ? ($this->config["params"]["photo_size"]) : (Hybrid_Providers_Foursquare::$defPhotoSize)) . $suffix;
}
return ("");
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/Providers/Google.php b/hauth/Hybrid/Providers/Google.php index bcafa94..bdc3959 100644 --- a/hauth/Hybrid/Providers/Google.php +++ b/hauth/Hybrid/Providers/Google.php @@ -1,54 +1,54 @@ <?php
-
+ /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_Providers_Google provider adapter based on OAuth2 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Google.html
*/
-class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 {
-
+class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 { + /**
* > more infos on google APIs: http://developer.google.com (official site)
* or here: http://discovery-check.appspot.com/ (unofficial but up to date)
* default permissions
* {@inheritdoc}
*/
- public $scope = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds/";
-
+ public $scope = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds/"; + /**
* {@inheritdoc}
*/
function initialize() {
- parent::initialize();
-
+ parent::initialize(); + // Provider api end-points
$this->api->authorize_url = "https://accounts.google.com/o/oauth2/auth";
$this->api->token_url = "https://accounts.google.com/o/oauth2/token";
- $this->api->token_info_url = "https://www.googleapis.com/oauth2/v2/tokeninfo";
-
+ $this->api->token_info_url = "https://www.googleapis.com/oauth2/v2/tokeninfo"; + // Google POST methods require an access_token in the header
- $this->api->curl_header = array("Authorization: OAuth " . $this->api->access_token);
-
+ $this->api->curl_header = ["Authorization: OAuth " . $this->api->access_token]; + // Override the redirect uri when it's set in the config parameters. This way we prevent
// redirect uri mismatches when authenticating with Google.
if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
$this->api->redirect_uri = $this->config['redirect_uri'];
}
- }
-
+ } + /**
* {@inheritdoc}
*/
function loginBegin() {
- $parameters = array("scope" => $this->scope, "access_type" => "offline");
- $optionals = array("scope", "access_type", "redirect_uri", "approval_prompt", "hd", "state");
-
+ $parameters = ["scope" => $this->scope, "access_type" => "offline"];
+ $optionals = ["scope", "access_type", "redirect_uri", "approval_prompt", "hd", "state"]; + foreach ($optionals as $parameter) {
if (isset($this->config[$parameter]) && !empty($this->config[$parameter])) {
$parameters[$parameter] = $this->config[$parameter];
@@ -56,27 +56,27 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 { if (isset($this->config["scope"]) && !empty($this->config["scope"])) {
$this->scope = $this->config["scope"];
}
- }
-
+ } + if (isset($this->config['force']) && $this->config['force'] === true) {
$parameters['approval_prompt'] = 'force';
- }
-
+ } + Hybrid_Auth::redirect($this->api->authorizeUrl($parameters));
- }
-
+ } + /**
* {@inheritdoc}
*/
function getUserProfile() {
// refresh tokens if needed
- $this->refreshToken();
-
+ $this->refreshToken(); + $response = $this->api->api("https://www.googleapis.com/oauth2/v3/userinfo");
if (!isset($response->sub) || isset($response->error)) {
- throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $response ), 6);
- }
-
+ throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $response ), 6); + } + $this->user->profile->identifier = (property_exists($response, 'sub')) ? $response->sub : "";
$this->user->profile->firstName = (property_exists($response, 'given_name')) ? $response->given_name : "";
$this->user->profile->lastName = (property_exists($response, 'family_name')) ? $response->family_name : "";
@@ -86,33 +86,33 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 { $this->user->profile->gender = (property_exists($response, 'gender')) ? $response->gender : "";
$this->user->profile->language = (property_exists($response, 'locale')) ? $response->locale : "";
$this->user->profile->email = (property_exists($response, 'email')) ? $response->email : "";
- $this->user->profile->emailVerified = (property_exists($response, 'email_verified')) ? ($response->email_verified === true || $response->email_verified === 1 ? $response->email : "") : "";
-
+ $this->user->profile->emailVerified = (property_exists($response, 'email_verified')) ? ($response->email_verified === true || $response->email_verified === 1 ? $response->email : "") : ""; + return $this->user->profile;
- }
-
+ } + /**
* {@inheritdoc}
*/
function getUserContacts() {
// refresh tokens if needed
- $this->refreshToken();
-
- $contacts = array();
+ $this->refreshToken(); + + $contacts = [];
if (!isset($this->config['contacts_param'])) {
- $this->config['contacts_param'] = array("max-results" => 500);
- }
-
+ $this->config['contacts_param'] = ["max-results" => 500];
+ } + // Google Gmail and Android contacts
- if (strpos($this->scope, '/m8/feeds/') !== false) {
-
+ if (strpos($this->scope, '/m8/feeds/') !== false) { + $response = $this->api->api("https://www.google.com/m8/feeds/contacts/default/full?"
- . http_build_query(array_merge(array('alt' => 'json'), $this->config['contacts_param'])));
-
+ . http_build_query(array_merge(['alt' => 'json'], $this->config['contacts_param'])), ); + if (!$response) {
- return array();
- }
-
+ return [];
+ } + if (isset($response->feed->entry)) {
foreach ($response->feed->entry as $idx => $entry) {
$uc = new Hybrid_User_Contact();
@@ -127,9 +127,9 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 { if (is_array($entry->link)) {
foreach ($entry->link as $l) {
if (property_exists($l, 'gd$etag') && $l->type == "image/*") {
- $uc->photoURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token));
+ $uc->photoURL = $this->addUrlParam($l->href, ['access_token' => $this->api->access_token]);
} else if ($l->type == "self") {
- $uc->profileURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token));
+ $uc->profileURL = $this->addUrlParam($l->href, ['access_token' => $this->api->access_token]);
}
}
}
@@ -147,16 +147,16 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 { }
} else {
$uc->webSiteURL = '';
- }
-
+ } + $contacts[] = $uc;
}
}
- }
-
+ } + return $contacts;
- }
-
+ } + /**
* Add query parameters to the $url
*
@@ -164,9 +164,9 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 { * @param array $params Parameters to add
* @return string
*/
- function addUrlParam($url, array $params){
- $query = parse_url($url, PHP_URL_QUERY);
-
+ function addUrlParam($url, array $params){
+ $query = parse_url($url, PHP_URL_QUERY); + // Returns the URL string with new parameters
if ($query) {
$url .= '&' . http_build_query($params);
@@ -174,7 +174,7 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 { $url .= '?' . http_build_query($params);
}
return $url;
- }
-
-}
-
+ } + +} + diff --git a/hauth/Hybrid/Providers/Instagram.php b/hauth/Hybrid/Providers/Instagram.php index 3f958a0..d18f887 100644 --- a/hauth/Hybrid/Providers/Instagram.php +++ b/hauth/Hybrid/Providers/Instagram.php @@ -9,9 +9,9 @@ * Hybrid_Providers_Instagram (By Sebastian Lasse - https://github.com/sebilasse) */ class Hybrid_Providers_Instagram extends Hybrid_Provider_Model_OAuth2 -{ - // default permissions - public $scope = "basic"; +{ + // default permissions + public $scope = "basic"; /** * IDp wrappers initializer @@ -29,21 +29,21 @@ class Hybrid_Providers_Instagram extends Hybrid_Provider_Model_OAuth2 /** * load the user profile from the IDp api client */ - function getUserProfile(){ - $data = $this->api->api("users/self/" ); + function getUserProfile(){ + $data = $this->api->api("users/self/" ); if ( $data->meta->code != 200 ){ throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 ); } - $this->user->profile->identifier = $data->data->id; - $this->user->profile->displayName = $data->data->full_name ? $data->data->full_name : $data->data->username; + $this->user->profile->identifier = $data->data->id; + $this->user->profile->displayName = $data->data->full_name ? $data->data->full_name : $data->data->username; $this->user->profile->description = $data->data->bio; $this->user->profile->photoURL = $data->data->profile_picture; - $this->user->profile->webSiteURL = $data->data->website; - - $this->user->profile->username = $data->data->username; + $this->user->profile->webSiteURL = $data->data->website; + + $this->user->profile->username = $data->data->username; return $this->user->profile; } @@ -55,24 +55,24 @@ class Hybrid_Providers_Instagram extends Hybrid_Provider_Model_OAuth2 $this->refreshToken(); // - $response = array(); - $contacts = array(); - $profile = ( ( isset( $this->user->profile->identifier ) )?( $this->user->profile ):( $this->getUserProfile() ) ); + $response = []; + $contacts = []; + $profile = ( ( isset( $this->user->profile->identifier ) )?( $this->user->profile ):( $this->getUserProfile() ) ); try { - $response = $this->api->api( "users/{$this->user->profile->identifier}/follows" ); - } catch (Exception $e) { - throw new Exception("User contacts request failed! {$this->providerId} returned an error: $e"); - } - // + $response = $this->api->api( "users/{$this->user->profile->identifier}/follows" ); + } catch (Exception $e) { + throw new Exception("User contacts request failed! {$this->providerId} returned an error: $e"); + } + // if ( isset( $response ) && $response->meta->code == 200 ) { foreach ($response->data as $contact) { - try { - $contactInfo = $this->api->api( "users/".$contact->id ); - } catch (Exception $e) { - throw new Exception("Contact info request failed for user {$contact->username}! {$this->providerId} returned an error: $e"); - } - // + try { + $contactInfo = $this->api->api( "users/".$contact->id ); + } catch (Exception $e) { + throw new Exception("Contact info request failed for user {$contact->username}! {$this->providerId} returned an error: $e"); + } + // $uc = new Hybrid_User_Contact(); // $uc->identifier = $contact->id; diff --git a/hauth/Hybrid/Providers/LinkedIn.php b/hauth/Hybrid/Providers/LinkedIn.php index 4631b52..e327a1a 100644 --- a/hauth/Hybrid/Providers/LinkedIn.php +++ b/hauth/Hybrid/Providers/LinkedIn.php @@ -1,178 +1,178 @@ <?php
-
+ /* !
* Hybridauth
* https://hybridauth.github.io/hybridauth | https://github.com/hybridauth/hybridauth
* (c) 2017 Hybridauth authors | https://hybridauth.github.io/license.html
- */
-
+ */ + /**
* Hybrid_Providers_LinkedIn OAuth2 provider adapter.
*/
-class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model_OAuth2 {
-
- /**
- * {@inheritdoc}
- */
- public $scope = "r_basicprofile r_emailaddress";
-
- /**
- * {@inheritdoc}
- */
- function initialize() {
- parent::initialize();
-
- // Provider api end-points.
- $this->api->api_base_url = "https://api.linkedin.com/v1/";
- $this->api->authorize_url = "https://www.linkedin.com/oauth/v2/authorization";
- $this->api->token_url = "https://www.linkedin.com/oauth/v2/accessToken";
- }
-
- /**
- * {@inheritdoc}
- */
- function loginBegin() {
- if (is_array($this->scope)) {
- $this->scope = implode(" ", $this->scope);
- }
- if (isset($this->scope)) {
- $extra_params['scope'] = $this->scope;
- }
- if (!isset($this->state)) {
- $this->state = hash("sha256",(uniqid(rand(), TRUE)));
- }
- $extra_params['state'] = $this->state;
- Hybrid_Auth::redirect($this->api->authorizeUrl($extra_params));
- }
-
- /**
- * {@inheritdoc}
- *
- * @see https://developer.linkedin.com/docs/rest-api
- */
- function getUserProfile() {
- // Refresh tokens if needed.
- $this->setHeaders("token");
- $this->refreshToken();
-
- // https://developer.linkedin.com/docs/fields.
- $fields = isset($this->config["fields"]) ? $this->config["fields"] : array(
- "id",
- "email-address",
- "first-name",
- "last-name",
- "headline",
- "location",
- "industry",
- "picture-url",
- "public-profile-url",
- );
-
- $this->setHeaders();
- $response = $this->api->get(
- "people/~:(" . implode(",", $fields) . ")",
- array(
- "format" => "json",
- )
- );
-
- if (!isset($response->id)) {
- throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response), 6);
- }
-
- $this->user->profile->identifier = isset($response->id) ? $response->id : "";
- $this->user->profile->firstName = isset($response->firstName) ? $response->firstName : "";
- $this->user->profile->lastName = isset($response->lastName) ? $response->lastName : "";
- $this->user->profile->photoURL = isset($response->pictureUrl) ? $response->pictureUrl : "";
- $this->user->profile->profileURL = isset($response->publicProfileUrl) ? $response->publicProfileUrl : "";
- $this->user->profile->email = isset($response->emailAddress) ? $response->emailAddress : "";
- $this->user->profile->description = isset($response->headline) ? $response->headline : "";
- $this->user->profile->country = isset($response->location) ? $response->location->name : "";
- $this->user->profile->emailVerified = $this->user->profile->email;
- $this->user->profile->displayName = trim($this->user->profile->firstName . " " . $this->user->profile->lastName);
-
- return $this->user->profile;
- }
-
- /**
- * {@inheritdoc}
- *
- * @param array $status
- * An associative array containing:
- * - content: A collection of fields describing the shared content.
- * - comment: A comment by the member to associated with the share.
- * - visibility: A collection of visibility information about the share.
- * @param string $companyId (optional) User company id
- *
- * @return object
- * An object containing:
- * - updateKey - A unique ID for the shared content posting that was just created.
- * - updateUrl - A direct link to the newly shared content on LinkedIn.com that you can direct the user's web browser to.
- * @throws Exception
- * @see https://developer.linkedin.com/docs/share-on-linkedin
- */
- function setUserStatus($status, $companyId = null) {
- // Refresh tokens if needed.
- $this->setHeaders("token");
- $this->refreshToken();
-
- try {
- // Define default visibility.
- if (!isset($status["visibility"])) {
- $status["visibility"]["code"] = "anyone";
- }
-
- $this->setHeaders("share");
- $url = $companyId ? "companies/{$companyId}/shares?format=json" : "people/~/shares?format=json";
- $response = $this->api->post($url,
- array(
- "body" => $status,
- )
- );
- } catch (Exception $e) {
- throw new Exception("Update user status failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
- }
-
- if (!isset($response->updateKey)) {
- throw new Exception("Update user status failed! {$this->providerId} returned an error: {$response->message}", $response->errorCode);
- }
-
- return $response;
- }
-
- /**
- * Set correct request headers.
- *
- * @param string $api_type
- * (optional) Specify api type.
- *
- * @return void
- */
- private function setHeaders($api_type = null) {
- $this->api->curl_header = array(
- "Authorization: Bearer {$this->api->access_token}",
- );
-
- switch ($api_type) {
- case "share":
- $this->api->curl_header = array_merge(
- $this->api->curl_header,
- array(
- "Content-Type: application/json",
- "x-li-format: json",
- )
- );
- break;
-
- case "token":
- $this->api->curl_header = array_merge(
- $this->api->curl_header,
- array(
- "Content-Type: application/x-www-form-urlencoded",
- )
- );
- break;
- }
- }
-
-}
+class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model_OAuth2 { + + /**
+ * {@inheritdoc}
+ */
+ public $scope = "r_basicprofile r_emailaddress"; + + /**
+ * {@inheritdoc}
+ */
+ function initialize() {
+ parent::initialize(); + + // Provider api end-points.
+ $this->api->api_base_url = "https://api.linkedin.com/v1/";
+ $this->api->authorize_url = "https://www.linkedin.com/oauth/v2/authorization";
+ $this->api->token_url = "https://www.linkedin.com/oauth/v2/accessToken";
+ } + + /**
+ * {@inheritdoc}
+ */
+ function loginBegin() {
+ if (is_array($this->scope)) {
+ $this->scope = implode(" ", $this->scope);
+ }
+ if (isset($this->scope)) {
+ $extra_params['scope'] = $this->scope;
+ }
+ if (!isset($this->state)) {
+ $this->state = hash("sha256",(uniqid(rand(), TRUE)));
+ }
+ $extra_params['state'] = $this->state;
+ Hybrid_Auth::redirect($this->api->authorizeUrl($extra_params));
+ } + + /**
+ * {@inheritdoc}
+ *
+ * @see https://developer.linkedin.com/docs/rest-api
+ */
+ function getUserProfile() {
+ // Refresh tokens if needed.
+ $this->setHeaders("token");
+ $this->refreshToken(); + + // https://developer.linkedin.com/docs/fields.
+ $fields = $this->config["fields"] ?? [
+ "id",
+ "email-address",
+ "first-name",
+ "last-name",
+ "headline",
+ "location",
+ "industry",
+ "picture-url",
+ "public-profile-url",
+ ]; + + $this->setHeaders();
+ $response = $this->api->get(
+ "people/~:(" . implode(",", $fields) . ")",
+ [
+ "format" => "json",
+ ],
+ ); + + if (!isset($response->id)) {
+ throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response), 6); + } + + $this->user->profile->identifier = $response->id ?? "";
+ $this->user->profile->firstName = $response->firstName ?? "";
+ $this->user->profile->lastName = $response->lastName ?? "";
+ $this->user->profile->photoURL = $response->pictureUrl ?? "";
+ $this->user->profile->profileURL = $response->publicProfileUrl ?? "";
+ $this->user->profile->email = $response->emailAddress ?? "";
+ $this->user->profile->description = $response->headline ?? "";
+ $this->user->profile->country = isset($response->location) ? $response->location->name : "";
+ $this->user->profile->emailVerified = $this->user->profile->email;
+ $this->user->profile->displayName = trim($this->user->profile->firstName . " " . $this->user->profile->lastName); + + return $this->user->profile;
+ } + + /**
+ * {@inheritdoc}
+ *
+ * @param array $status
+ * An associative array containing:
+ * - content: A collection of fields describing the shared content.
+ * - comment: A comment by the member to associated with the share.
+ * - visibility: A collection of visibility information about the share.
+ * @param string $companyId (optional) User company id
+ *
+ * @return object
+ * An object containing:
+ * - updateKey - A unique ID for the shared content posting that was just created.
+ * - updateUrl - A direct link to the newly shared content on LinkedIn.com that you can direct the user's web browser to.
+ * @throws Exception
+ * @see https://developer.linkedin.com/docs/share-on-linkedin
+ */
+ function setUserStatus($status, $companyId = null) {
+ // Refresh tokens if needed.
+ $this->setHeaders("token");
+ $this->refreshToken(); + + try {
+ // Define default visibility.
+ if (!isset($status["visibility"])) {
+ $status["visibility"]["code"] = "anyone";
+ } + + $this->setHeaders("share");
+ $url = $companyId ? "companies/{$companyId}/shares?format=json" : "people/~/shares?format=json";
+ $response = $this->api->post($url,
+ [
+ "body" => $status,
+ ],
+ );
+ } catch (Exception $e) {
+ throw new Exception("Update user status failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e); + } + + if (!isset($response->updateKey)) {
+ throw new Exception("Update user status failed! {$this->providerId} returned an error: {$response->message}", $response->errorCode); + } + + return $response;
+ } + + /**
+ * Set correct request headers.
+ *
+ * @param string $api_type
+ * (optional) Specify api type.
+ *
+ * @return void
+ */
+ private function setHeaders($api_type = null) {
+ $this->api->curl_header = [
+ "Authorization: Bearer {$this->api->access_token}",
+ ]; + + switch ($api_type) {
+ case "share":
+ $this->api->curl_header = array_merge(
+ $this->api->curl_header,
+ [
+ "Content-Type: application/json",
+ "x-li-format: json",
+ ],
+ );
+ break; + + case "token":
+ $this->api->curl_header = array_merge(
+ $this->api->curl_header,
+ [
+ "Content-Type: application/x-www-form-urlencoded",
+ ],
+ );
+ break;
+ }
+ } + +} diff --git a/hauth/Hybrid/Providers/Live.php b/hauth/Hybrid/Providers/Live.php index 0cc2951..34c05a7 100644 --- a/hauth/Hybrid/Providers/Live.php +++ b/hauth/Hybrid/Providers/Live.php @@ -1,11 +1,11 @@ <?php
-
+ /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Windows Live OAuth2 Class
*
@@ -13,88 +13,88 @@ * @author Lukasz Koprowski <azram19@gmail.com>
* @version 0.2
* @license BSD License
- */
-
+ */ + /**
* Hybrid_Providers_Live - Windows Live provider adapter based on OAuth2 protocol
*/
-class Hybrid_Providers_Live extends Hybrid_Provider_Model_OAuth2 {
-
+class Hybrid_Providers_Live extends Hybrid_Provider_Model_OAuth2 { + /**
* {@inheritdoc}
*/
- public $scope = 'wl.basic wl.contacts_emails wl.emails wl.signin wl.share wl.birthday';
-
+ public $scope = 'wl.basic wl.contacts_emails wl.emails wl.signin wl.share wl.birthday'; + /**
* {@inheritdoc}
*/
function initialize() {
- parent::initialize();
-
+ parent::initialize(); + // Provider api end-points
$this->api->api_base_url = 'https://apis.live.net/v5.0/';
$this->api->authorize_url = 'https://login.live.com/oauth20_authorize.srf';
$this->api->token_url = 'https://login.live.com/oauth20_token.srf';
- }
-
+ } + /**
* {@inheritdoc}
*/
function getUserProfile() {
- $data = $this->api->get("me");
-
+ $data = $this->api->get("me"); + if (!isset($data->id)) {
- throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $data ), 6);
- }
-
+ throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $data ), 6); + } + $this->user->profile->identifier = (property_exists($data, 'id')) ? $data->id : "";
$this->user->profile->firstName = (property_exists($data, 'first_name')) ? $data->first_name : "";
$this->user->profile->lastName = (property_exists($data, 'last_name')) ? $data->last_name : "";
$this->user->profile->displayName = (property_exists($data, 'name')) ? trim($data->name) : "";
- $this->user->profile->gender = (property_exists($data, 'gender')) ? $data->gender : "";
-
+ $this->user->profile->gender = (property_exists($data, 'gender')) ? $data->gender : ""; + //wl.basic
- $this->user->profile->profileURL = (property_exists($data, 'link')) ? $data->link : "";
-
+ $this->user->profile->profileURL = (property_exists($data, 'link')) ? $data->link : ""; + //wl.emails
$this->user->profile->email = (property_exists($data, 'emails')) ? $data->emails->preferred : "";
- $this->user->profile->emailVerified = (property_exists($data, 'emails')) ? $data->emails->account : "";
-
+ $this->user->profile->emailVerified = (property_exists($data, 'emails')) ? $data->emails->account : ""; + //wl.birthday
$this->user->profile->birthDay = (property_exists($data, 'birth_day')) ? $data->birth_day : "";
$this->user->profile->birthMonth = (property_exists($data, 'birth_month')) ? $data->birth_month : "";
- $this->user->profile->birthYear = (property_exists($data, 'birth_year')) ? $data->birth_year : "";
-
+ $this->user->profile->birthYear = (property_exists($data, 'birth_year')) ? $data->birth_year : ""; + return $this->user->profile;
- }
-
+ } + /**
* Windows Live api does not support retrieval of email addresses (only hashes :/)
* {@inheritdoc}
*/
function getUserContacts() {
- $response = $this->api->get('me/contacts');
-
+ $response = $this->api->get('me/contacts'); + if ($this->api->http_code != 200) {
- throw new Exception('User contacts request failed! ' . $this->providerId . ' returned an error: ' . $this->errorMessageByStatus($this->api->http_code));
- }
-
+ throw new Exception('User contacts request failed! ' . $this->providerId . ' returned an error: ' . $this->errorMessageByStatus($this->api->http_code)); + } + if (!isset($response->data) || ( isset($response->errcode) && $response->errcode != 0 )) {
- return array();
- }
-
- $contacts = array();
-
+ return [];
+ } + + $contacts = []; + foreach ($response->data as $item) {
- $uc = new Hybrid_User_Contact();
-
+ $uc = new Hybrid_User_Contact(); + $uc->identifier = (property_exists($item, 'id')) ? $item->id : "";
$uc->displayName = (property_exists($item, 'name')) ? $item->name : "";
$uc->email = (property_exists($item, 'emails')) ? $item->emails->preferred : "";
$contacts[] = $uc;
- }
-
+ } + return $contacts;
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/Providers/OpenID.php b/hauth/Hybrid/Providers/OpenID.php index 8f7903c..823f857 100644 --- a/hauth/Hybrid/Providers/OpenID.php +++ b/hauth/Hybrid/Providers/OpenID.php @@ -1,16 +1,16 @@ <?php
-
+ /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_Providers_OpenID provider adapter for any idp openid based
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_OpenID.html
*/
-class Hybrid_Providers_OpenID extends Hybrid_Provider_Model_OpenID {
-
-}
+class Hybrid_Providers_OpenID extends Hybrid_Provider_Model_OpenID { + +} diff --git a/hauth/Hybrid/Providers/Paypal.php b/hauth/Hybrid/Providers/Paypal.php index be0a64b..480c4e7 100644 --- a/hauth/Hybrid/Providers/Paypal.php +++ b/hauth/Hybrid/Providers/Paypal.php @@ -28,184 +28,184 @@ use PayPal\Rest\ApiContext; class Hybrid_Providers_Paypal extends Hybrid_Provider_Model { - /** - * The access privileges that you are requesting for - * from the user. Pass empty array for all scopes. - * - * @var array $scope - * @see https://developer.paypal.com/docs/integration/direct/identity/attributes - */ - public $scope = array(); + /** + * The access privileges that you are requesting for + * from the user. Pass empty array for all scopes. + * + * @var array $scope + * @see https://developer.paypal.com/docs/integration/direct/identity/attributes + */ + public $scope = []; - /** - * The provider api client - * - * @var ApiContext $api - */ - public $api; + /** + * The provider api client + * + * @var ApiContext $api + */ + public $api; - /** - * TRUE if sandbox mode is ON otherwise FALSE - * - * @var bool $sandbox - */ - public $sandbox = true; + /** + * TRUE if sandbox mode is ON otherwise FALSE + * + * @var bool $sandbox + */ + public $sandbox = true; - /** - * {@inheritdoc} - */ - function initialize() - { - if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) { - throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4); - } + /** + * {@inheritdoc} + */ + function initialize() + { + if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) { + throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4); + } - // Set scope from config. - if (isset($this->config["scope"])) { - $scope = $this->config["scope"]; - if (is_string($scope)) { - $scope = explode(" ", $scope); - } - $scope = array_map("trim", $scope); - $this->scope = $scope; - } + // Set scope from config. + if (isset($this->config["scope"])) { + $scope = $this->config["scope"]; + if (is_string($scope)) { + $scope = explode(" ", $scope); + } + $scope = array_map("trim", $scope); + $this->scope = $scope; + } - // Set sandbox from config. - if (isset($this->config["sandbox"]) && is_bool($this->config["sandbox"])) { - $this->sandbox = $this->config["sandbox"]; - } + // Set sandbox from config. + if (isset($this->config["sandbox"]) && is_bool($this->config["sandbox"])) { + $this->sandbox = $this->config["sandbox"]; + } - // Include 3rd-party SDK. - $this->autoLoaderInit(); + // Include 3rd-party SDK. + $this->autoLoaderInit(); - // Set up ApiContext. - $this->api = new ApiContext( - new OAuthTokenCredential( - $this->config["keys"]["id"], - $this->config["keys"]["secret"] - ) - ); + // Set up ApiContext. + $this->api = new ApiContext( + new OAuthTokenCredential( + $this->config["keys"]["id"], + $this->config["keys"]["secret"], + ), + ); - // Set up config. - $this->api->setConfig(array( - "log.LogEnabled" => Hybrid_Auth::$config["debug_mode"], - "log.FileName" => Hybrid_Auth::$config["debug_file"], - "log.LogLevel" => "DEBUG", - "http.CURLOPT_SSLVERSION" => CURL_SSLVERSION_TLSv1, - "mode" => $this->sandbox ? "sandbox" : "live", - )); - } + // Set up config. + $this->api->setConfig([ + "log.LogEnabled" => Hybrid_Auth::$config["debug_mode"], + "log.FileName" => Hybrid_Auth::$config["debug_file"], + "log.LogLevel" => "DEBUG", + "http.CURLOPT_SSLVERSION" => CURL_SSLVERSION_TLSv1, + "mode" => $this->sandbox ? "sandbox" : "live", + ]); + } - /** - * {@inheritdoc} - */ - function loginBegin() - { - $url = OpenIdSession::getAuthorizationUrl( - $this->endpoint, - $this->scope, - null, - null, - null, - $this->api - ); - // Redirect to PayPal. - Hybrid_Auth::redirect($url); - } + /** + * {@inheritdoc} + */ + function loginBegin() + { + $url = OpenIdSession::getAuthorizationUrl( + $this->endpoint, + $this->scope, + null, + null, + null, + $this->api, + ); + // Redirect to PayPal. + Hybrid_Auth::redirect($url); + } - /** - * {@inheritdoc} - */ - function loginFinish() - { - if (!isset($_GET["code"])) { - throw new Exception("Authentication failed! User has canceled authentication!", 5); - } + /** + * {@inheritdoc} + */ + function loginFinish() + { + if (!isset($_GET["code"])) { + throw new Exception("Authentication failed! User has canceled authentication!", 5); + } - $code = $_GET["code"]; - try { - // Obtain Authorization Code from Code, Client ID and Client Secret - $accessToken = OpenIdTokeninfo::createFromAuthorizationCode(array("code" => $code), null, null, $this->api); - if ($accessToken) { - $this->setUserConnected(); + $code = $_GET["code"]; + try { + // Obtain Authorization Code from Code, Client ID and Client Secret + $accessToken = OpenIdTokeninfo::createFromAuthorizationCode(["code" => $code], null, null, $this->api); + if ($accessToken) { + $this->setUserConnected(); - // Store tokens. - $this->token("id_token", $accessToken->getIdToken()); - $this->token("access_token", $accessToken->getAccessToken()); - $this->token("refresh_token", $accessToken->getRefreshToken()); - } - } catch (PayPalConnectionException $e) { - throw new Hybrid_Exception($e->getMessage(), $e->getCode(), $e); - } - } + // Store tokens. + $this->token("id_token", $accessToken->getIdToken()); + $this->token("access_token", $accessToken->getAccessToken()); + $this->token("refresh_token", $accessToken->getRefreshToken()); + } + } catch (PayPalConnectionException $e) { + throw new Hybrid_Exception($e->getMessage(), $e->getCode(), $e); + } + } - /** - * {@inheritdoc} - */ - function logout() - { - parent::logout(); - if ($idToken = $this->token("id_token")) { - $url = OpenIdSession::getLogoutUrl( - $this->params["hauth_return_to"], - $idToken, - $this->api - ); - // Redirect to PayPal. - Hybrid_Auth::redirect($url); - } - } + /** + * {@inheritdoc} + */ + function logout() + { + parent::logout(); + if ($idToken = $this->token("id_token")) { + $url = OpenIdSession::getLogoutUrl( + $this->params["hauth_return_to"], + $idToken, + $this->api, + ); + // Redirect to PayPal. + Hybrid_Auth::redirect($url); + } + } - /** - * {@inheritdoc} - */ - function getUserProfile() - { - try { - $params = array("access_token" => $this->token("access_token")); - $userInfo = OpenIdUserinfo::getUserinfo($params, $this->api); + /** + * {@inheritdoc} + */ + function getUserProfile() + { + try { + $params = ["access_token" => $this->token("access_token")]; + $userInfo = OpenIdUserinfo::getUserinfo($params, $this->api); - $profile = new Hybrid_User_Profile(); + $profile = new Hybrid_User_Profile(); - $profile->identifier = $userInfo->getUserId(); - $profile->firstName = $userInfo->getGivenName(); - $profile->lastName = $userInfo->getFamilyName(); - $profile->displayName = $userInfo->getName(); - $profile->photoURL = $userInfo->getPicture(); - $profile->gender = $userInfo->getGender(); - $profile->email = $userInfo->getEmail(); - $profile->emailVerified = $userInfo->getEmailVerified(); - $profile->language = $userInfo->getLocale(); - $profile->phone = $userInfo->getPhoneNumber(); - if ($address = $userInfo->getAddress()) { - $profile->address = $address->getStreetAddress(); - $profile->city = $address->getLocality(); - $profile->zip = $address->getPostalCode(); - $profile->country = $address->getCountry(); - $profile->region = $address->getRegion(); - } + $profile->identifier = $userInfo->getUserId(); + $profile->firstName = $userInfo->getGivenName(); + $profile->lastName = $userInfo->getFamilyName(); + $profile->displayName = $userInfo->getName(); + $profile->photoURL = $userInfo->getPicture(); + $profile->gender = $userInfo->getGender(); + $profile->email = $userInfo->getEmail(); + $profile->emailVerified = $userInfo->getEmailVerified(); + $profile->language = $userInfo->getLocale(); + $profile->phone = $userInfo->getPhoneNumber(); + if ($address = $userInfo->getAddress()) { + $profile->address = $address->getStreetAddress(); + $profile->city = $address->getLocality(); + $profile->zip = $address->getPostalCode(); + $profile->country = $address->getCountry(); + $profile->region = $address->getRegion(); + } - if ($birthdate = $userInfo->getBirthday()) { - if (strpos($birthdate, "-") === FALSE) { - if ($birthdate !== "0000") { - $profile->birthYear = (int)$birthdate; - } - } else { - list($birthday_year, $birthday_month, $birthday_day) = explode("-", $birthdate); + if ($birthdate = $userInfo->getBirthday()) { + if (strpos($birthdate, "-") === FALSE) { + if ($birthdate !== "0000") { + $profile->birthYear = (int)$birthdate; + } + } else { + list($birthday_year, $birthday_month, $birthday_day) = explode("-", $birthdate); - $profile->birthDay = (int) $birthday_day; - $profile->birthMonth = (int) $birthday_month; - if ($birthday_year !== "0000") { - $profile->birthYear = (int) $birthday_year; - } - } - } + $profile->birthDay = (int) $birthday_day; + $profile->birthMonth = (int) $birthday_month; + if ($birthday_year !== "0000") { + $profile->birthYear = (int) $birthday_year; + } + } + } - $this->user->profile = $profile; + $this->user->profile = $profile; - return $this->user->profile; - } catch (Exception $e) { - throw new Hybrid_Exception($e->getMessage(), $e->getCode(), $e); - } - } + return $this->user->profile; + } catch (Exception $e) { + throw new Hybrid_Exception($e->getMessage(), $e->getCode(), $e); + } + } } diff --git a/hauth/Hybrid/Providers/PaypalOpenID.php b/hauth/Hybrid/Providers/PaypalOpenID.php index 6d4b9eb..b53ffba 100644 --- a/hauth/Hybrid/Providers/PaypalOpenID.php +++ b/hauth/Hybrid/Providers/PaypalOpenID.php @@ -10,7 +10,7 @@ */ class Hybrid_Providers_PaypalOpenID extends Hybrid_Provider_Model_OpenID { - var $openidIdentifier = "https://www.sandbox.paypal.com/webapps/auth/server"; + var $openidIdentifier = "https://www.sandbox.paypal.com/webapps/auth/server"; /** * begin login step @@ -23,7 +23,7 @@ class Hybrid_Providers_PaypalOpenID extends Hybrid_Provider_Model_OpenID $this->api->identity = $this->openidIdentifier; $this->api->returnUrl = $this->endpoint; - $this->api->required = ARRAY( + $this->api->required = [ /*'namePerson/first' , 'namePerson/last' , 'namePerson/friendly' , @@ -43,139 +43,139 @@ class Hybrid_Providers_PaypalOpenID extends Hybrid_Provider_Model_OpenID 'contact/city/home' , 'contact/country/home' , - 'media/image/default' ,*/ + 'media/image/default' ,*/ - 'namePerson/prefix', - 'namePerson/first', - 'namePerson/last', - 'namePerson/middle', - 'namePerson/suffix', - 'namePerson/friendly', - 'person/guid', - 'birthDate/birthYear', - 'birthDate/birthMonth', - 'birthDate/birthday', - 'gender', - 'language/pref', - 'contact/phone/default', - 'contact/phone/home', - 'contact/phone/business', - 'contact/phone/cell', - 'contact/phone/fax', - 'contact/postaladdress/home', - 'contact/postaladdressadditional/home', - 'contact/city/home', - 'contact/state/home', - 'contact/country/home', - 'contact/postalcode/home', - 'contact/postaladdress/business', - 'contact/postaladdressadditional/business', - 'contact/city/business', - 'contact/state/business', - 'contact/country/business', - 'contact/postalcode/business', - /*'contact/IM/default', - 'contact/IM/AIM', - 'contact/IM/ICQ', - 'contact/IM/MSN', - 'contact/IM/Yahoo', - 'contact/IM/Jabber', - 'contact/IM/Skype', - 'contact/internet/email', - 'contact/web/default', - 'contact/web/blog', - 'contact/web/Linkedin', - 'contact/web/Amazon', - 'contact/web/Flickr', - 'contact/web/Delicious',*/ - 'company/name', - 'company/title', - /*'media/spokenname', - 'media/greeting/audio', - 'media/greeting/video', - 'media/biography', - 'media/image', - 'media/image/16x16', - 'media/image/32x32', - 'media/image/48x48', - 'media/image/64x64', - 'media/image/80x80', - 'media/image/128x128', - 'media/image/160x120', - 'media/image/320x240', - 'media/image/640x480', - 'media/image/120x160', - 'media/image/240x320', - 'media/image/480x640', - 'media/image/favicon', - 'timezone',*/ - ); - $this->api->optional = array();ARRAY( - 'namePerson/prefix', - 'namePerson/first', - 'namePerson/last', - 'namePerson/middle', - 'namePerson/suffix', - 'namePerson/friendly', - 'person/guid', - 'birthDate/birthYear', - 'birthDate/birthMonth', - 'birthDate/birthday', - 'gender', - 'language/pref', - 'contact/phone/default', - 'contact/phone/home', - 'contact/phone/business', - 'contact/phone/cell', - 'contact/phone/fax', - 'contact/postaladdress/home', - 'contact/postaladdressadditional/home', - 'contact/city/home', - 'contact/state/home', - 'contact/country/home', - 'contact/postalcode/home', - 'contact/postaladdress/business', - 'contact/postaladdressadditional/business', - 'contact/city/business', - 'contact/state/business', - 'contact/country/business', - 'contact/postalcode/business', - /*'contact/IM/default', - 'contact/IM/AIM', - 'contact/IM/ICQ', - 'contact/IM/MSN', - 'contact/IM/Yahoo', - 'contact/IM/Jabber', - 'contact/IM/Skype', - 'contact/internet/email', - 'contact/web/default', - 'contact/web/blog', - 'contact/web/Linkedin', - 'contact/web/Amazon', - 'contact/web/Flickr', - 'contact/web/Delicious',*/ - 'company/name', - 'company/title', - /*'media/spokenname', - 'media/greeting/audio', - 'media/greeting/video', - 'media/biography', - 'media/image', - 'media/image/16x16', - 'media/image/32x32', - 'media/image/48x48', - 'media/image/64x64', - 'media/image/80x80', - 'media/image/128x128', - 'media/image/160x120', - 'media/image/320x240', - 'media/image/640x480', - 'media/image/120x160', - 'media/image/240x320', - 'media/image/480x640', - 'media/image/favicon', - 'timezone',*/ - ); + 'namePerson/prefix', + 'namePerson/first', + 'namePerson/last', + 'namePerson/middle', + 'namePerson/suffix', + 'namePerson/friendly', + 'person/guid', + 'birthDate/birthYear', + 'birthDate/birthMonth', + 'birthDate/birthday', + 'gender', + 'language/pref', + 'contact/phone/default', + 'contact/phone/home', + 'contact/phone/business', + 'contact/phone/cell', + 'contact/phone/fax', + 'contact/postaladdress/home', + 'contact/postaladdressadditional/home', + 'contact/city/home', + 'contact/state/home', + 'contact/country/home', + 'contact/postalcode/home', + 'contact/postaladdress/business', + 'contact/postaladdressadditional/business', + 'contact/city/business', + 'contact/state/business', + 'contact/country/business', + 'contact/postalcode/business', + /*'contact/IM/default', + 'contact/IM/AIM', + 'contact/IM/ICQ', + 'contact/IM/MSN', + 'contact/IM/Yahoo', + 'contact/IM/Jabber', + 'contact/IM/Skype', + 'contact/internet/email', + 'contact/web/default', + 'contact/web/blog', + 'contact/web/Linkedin', + 'contact/web/Amazon', + 'contact/web/Flickr', + 'contact/web/Delicious',*/ + 'company/name', + 'company/title', + /*'media/spokenname', + 'media/greeting/audio', + 'media/greeting/video', + 'media/biography', + 'media/image', + 'media/image/16x16', + 'media/image/32x32', + 'media/image/48x48', + 'media/image/64x64', + 'media/image/80x80', + 'media/image/128x128', + 'media/image/160x120', + 'media/image/320x240', + 'media/image/640x480', + 'media/image/120x160', + 'media/image/240x320', + 'media/image/480x640', + 'media/image/favicon', + 'timezone',*/ + ]; + $this->api->optional = [];[ + 'namePerson/prefix', + 'namePerson/first', + 'namePerson/last', + 'namePerson/middle', + 'namePerson/suffix', + 'namePerson/friendly', + 'person/guid', + 'birthDate/birthYear', + 'birthDate/birthMonth', + 'birthDate/birthday', + 'gender', + 'language/pref', + 'contact/phone/default', + 'contact/phone/home', + 'contact/phone/business', + 'contact/phone/cell', + 'contact/phone/fax', + 'contact/postaladdress/home', + 'contact/postaladdressadditional/home', + 'contact/city/home', + 'contact/state/home', + 'contact/country/home', + 'contact/postalcode/home', + 'contact/postaladdress/business', + 'contact/postaladdressadditional/business', + 'contact/city/business', + 'contact/state/business', + 'contact/country/business', + 'contact/postalcode/business', + /*'contact/IM/default', + 'contact/IM/AIM', + 'contact/IM/ICQ', + 'contact/IM/MSN', + 'contact/IM/Yahoo', + 'contact/IM/Jabber', + 'contact/IM/Skype', + 'contact/internet/email', + 'contact/web/default', + 'contact/web/blog', + 'contact/web/Linkedin', + 'contact/web/Amazon', + 'contact/web/Flickr', + 'contact/web/Delicious',*/ + 'company/name', + 'company/title', + /*'media/spokenname', + 'media/greeting/audio', + 'media/greeting/video', + 'media/biography', + 'media/image', + 'media/image/16x16', + 'media/image/32x32', + 'media/image/48x48', + 'media/image/64x64', + 'media/image/80x80', + 'media/image/128x128', + 'media/image/160x120', + 'media/image/320x240', + 'media/image/640x480', + 'media/image/120x160', + 'media/image/240x320', + 'media/image/480x640', + 'media/image/favicon', + 'timezone',*/ + ]; # redirect the user to the provider authentication url Hybrid_Auth::redirect( $this->api->authUrl() ); diff --git a/hauth/Hybrid/Providers/Twitter.php b/hauth/Hybrid/Providers/Twitter.php index 6ea6231..107ff86 100644 --- a/hauth/Hybrid/Providers/Twitter.php +++ b/hauth/Hybrid/Providers/Twitter.php @@ -1,81 +1,81 @@ <?php
-
+ /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_Providers_Twitter provider adapter based on OAuth1 protocol
*/
-class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 {
-
+class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 { + /**
* {@inheritdoc}
*/
function initialize() {
- parent::initialize();
-
- // Provider api end-points
+ parent::initialize(); + + // Provider api end-points
$this->api->api_base_url = "https://api.twitter.com/1.1/";
$this->api->authorize_url = "https://api.twitter.com/oauth/authenticate";
$this->api->request_token_url = "https://api.twitter.com/oauth/request_token";
- $this->api->access_token_url = "https://api.twitter.com/oauth/access_token";
-
+ $this->api->access_token_url = "https://api.twitter.com/oauth/access_token"; + if (isset($this->config['api_version']) && $this->config['api_version']) {
$this->api->api_base_url = "https://api.twitter.com/{$this->config['api_version']}/";
- }
-
+ } + if (isset($this->config['authorize']) && $this->config['authorize']) {
$this->api->authorize_url = "https://api.twitter.com/oauth/authorize";
- }
-
+ } + $this->api->curl_auth_header = false;
- }
-
+ } + /**
* {@inheritdoc}
*/
function loginBegin() {
// Initiate the Reverse Auth flow; cf. https://dev.twitter.com/docs/ios/using-reverse-auth
if (isset($_REQUEST['reverse_auth']) && ($_REQUEST['reverse_auth'] == 'yes')) {
- $stage1 = $this->api->signedRequest($this->api->request_token_url, 'POST', array('x_auth_mode' => 'reverse_auth'));
+ $stage1 = $this->api->signedRequest($this->api->request_token_url, 'POST', ['x_auth_mode' => 'reverse_auth']);
if ($this->api->http_code != 200) {
- throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
+ throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5); }
- $responseObj = array('x_reverse_auth_parameters' => $stage1, 'x_reverse_auth_target' => $this->config["keys"]["key"]);
+ $responseObj = ['x_reverse_auth_parameters' => $stage1, 'x_reverse_auth_target' => $this->config["keys"]["key"]];
$response = json_encode($responseObj);
header("Content-Type: application/json", true, 200);
echo $response;
die();
}
- $tokens = $this->api->requestToken($this->endpoint);
-
+ $tokens = $this->api->requestToken($this->endpoint); + // request tokens as received from provider
- $this->request_tokens_raw = $tokens;
-
+ $this->request_tokens_raw = $tokens; + // check the last HTTP status code returned
if ($this->api->http_code != 200) {
- throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
- }
-
+ throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5); + } + if (!isset($tokens["oauth_token"])) {
- throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth token.", 5);
- }
-
+ throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth token.", 5); + } + $this->token("request_token", $tokens["oauth_token"]);
- $this->token("request_token_secret", $tokens["oauth_token_secret"]);
-
+ $this->token("request_token_secret", $tokens["oauth_token_secret"]); + // redirect the user to the provider authentication url with force_login
if (( isset($this->config['force_login']) && $this->config['force_login'] ) || ( isset($this->config['force']) && $this->config['force'] === true )) {
- Hybrid_Auth::redirect($this->api->authorizeUrl($tokens, array('force_login' => true)));
- }
-
+ Hybrid_Auth::redirect($this->api->authorizeUrl($tokens, ['force_login' => true]));
+ } + // else, redirect the user to the provider authentication url
Hybrid_Auth::redirect($this->api->authorizeUrl($tokens));
- }
-
+ } + /**
* {@inheritdoc}
*/
@@ -83,45 +83,45 @@ class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 { // in case we are completing a Reverse Auth flow; cf. https://dev.twitter.com/docs/ios/using-reverse-auth
if (isset($_REQUEST['oauth_token_secret'])) {
$tokens = $_REQUEST;
- $this->access_tokens_raw = $tokens;
-
+ $this->access_tokens_raw = $tokens; + // we should have an access_token unless something has gone wrong
if (!isset($tokens["oauth_token"])) {
- throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
- }
-
+ throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5); + } + // Get rid of tokens we don't need
$this->deleteToken("request_token");
- $this->deleteToken("request_token_secret");
-
+ $this->deleteToken("request_token_secret"); + // Store access_token and secret for later use
$this->token("access_token", $tokens['oauth_token']);
- $this->token("access_token_secret", $tokens['oauth_token_secret']);
-
+ $this->token("access_token_secret", $tokens['oauth_token_secret']); + // set user as logged in to the current provider
$this->setUserConnected();
return;
}
parent::loginFinish();
- }
-
+ } + /**
* {@inheritdoc}
*/
function getUserProfile() {
$includeEmail = isset($this->config['includeEmail']) ? (bool) $this->config['includeEmail'] : false;
- $response = $this->api->get('account/verify_credentials.json'. ($includeEmail ? '?include_email=true' : ''));
-
+ $response = $this->api->get('account/verify_credentials.json'. ($includeEmail ? '?include_email=true' : '')); + // check the last HTTP status code returned
if ($this->api->http_code != 200) {
- throw new Exception("User profile request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 6);
- }
-
+ throw new Exception("User profile request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 6); + } + if (!is_object($response) || !isset($response->id)) {
- throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6);
- }
-
- # store the user profile.
+ throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6); + } + + # store the user profile.
$this->user->profile->identifier = (property_exists($response, 'id')) ? $response->id : "";
$this->user->profile->displayName = (property_exists($response, 'screen_name')) ? $response->screen_name : "";
$this->user->profile->description = (property_exists($response, 'description')) ? $response->description : "";
@@ -131,92 +131,92 @@ class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 { $this->user->profile->webSiteURL = (property_exists($response, 'url')) ? $response->url : "";
$this->user->profile->region = (property_exists($response, 'location')) ? $response->location : "";
if($includeEmail) $this->user->profile->email = (property_exists($response, 'email')) ? $response->email : "";
- if($includeEmail) $this->user->profile->emailVerified = (property_exists($response, 'email')) ? $response->email : "";
-
+ if($includeEmail) $this->user->profile->emailVerified = (property_exists($response, 'email')) ? $response->email : ""; + return $this->user->profile;
- }
-
+ } + /**
* {@inheritdoc}
*/
function getUserContacts() {
- $parameters = array('cursor' => '-1');
- $response = $this->api->get('friends/ids.json', $parameters);
-
+ $parameters = ['cursor' => '-1'];
+ $response = $this->api->get('friends/ids.json', $parameters); + // check the last HTTP status code returned
if ($this->api->http_code != 200) {
- throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
- }
-
+ throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code)); + } + if (!$response || !count($response->ids)) {
- return array();
- }
-
+ return [];
+ } + // 75 id per time should be okey
- $contactsids = array_chunk($response->ids, 75);
-
- $contacts = array();
-
+ $contactsids = array_chunk($response->ids, 75); + + $contacts = []; + foreach ($contactsids as $chunk) {
- $parameters = array('user_id' => implode(",", $chunk));
- $response = $this->api->get('users/lookup.json', $parameters);
-
+ $parameters = ['user_id' => implode(",", $chunk)];
+ $response = $this->api->get('users/lookup.json', $parameters); + // check the last HTTP status code returned
if ($this->api->http_code != 200) {
- throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
- }
-
+ throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code)); + } + if ($response && count($response)) {
foreach ($response as $item) {
- $uc = new Hybrid_User_Contact();
-
+ $uc = new Hybrid_User_Contact(); + $uc->identifier = (property_exists($item, 'id')) ? $item->id : "";
$uc->displayName = (property_exists($item, 'name')) ? $item->name : "";
$uc->profileURL = (property_exists($item, 'screen_name')) ? ("http://twitter.com/" . $item->screen_name) : "";
$uc->photoURL = (property_exists($item, 'profile_image_url')) ? $item->profile_image_url : "";
- $uc->description = (property_exists($item, 'description')) ? $item->description : "";
-
+ $uc->description = (property_exists($item, 'description')) ? $item->description : ""; + $contacts[] = $uc;
}
}
- }
-
+ } + return $contacts;
- }
-
+ } + /**
* {@inheritdoc}
*/
- function setUserStatus($status) {
-
+ function setUserStatus($status) { + if (is_array($status) && isset($status['message']) && isset($status['picture'])) {
- $response = $this->api->post('statuses/update_with_media.json', array('status' => $status['message'], 'media[]' => file_get_contents($status['picture'])), null, null, true);
+ $response = $this->api->post('statuses/update_with_media.json', ['status' => $status['message'], 'media[]' => file_get_contents($status['picture'])], null, null, true);
} else {
- $response = $this->api->post('statuses/update.json', array('status' => $status));
- }
-
+ $response = $this->api->post('statuses/update.json', ['status' => $status]);
+ } + // check the last HTTP status code returned
if ($this->api->http_code != 200) {
- throw new Exception("Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
- }
-
+ throw new Exception("Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code)); + } + return $response;
- }
-
+ } + /**
* {@inheritdoc}
*/
function getUserStatus($tweetid) {
- $info = $this->api->get('statuses/show.json?id=' . $tweetid . '&include_entities=true');
-
+ $info = $this->api->get('statuses/show.json?id=' . $tweetid . '&include_entities=true'); + // check the last HTTP status code returned
if ($this->api->http_code != 200 || !isset($info->id)) {
- throw new Exception("Cannot retrieve user status! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
- }
-
+ throw new Exception("Cannot retrieve user status! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code)); + } + return $info;
- }
-
+ } + /**
* load the user latest activity
* - timeline : all the stream
@@ -230,35 +230,35 @@ class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 { $response = $this->api->get('statuses/user_timeline.json');
} else {
$response = $this->api->get('statuses/home_timeline.json');
- }
-
+ } + // check the last HTTP status code returned
if ($this->api->http_code != 200) {
- throw new Exception("User activity stream request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
- }
-
+ throw new Exception("User activity stream request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code)); + } + if (!$response) {
- return array();
- }
-
- $activities = array();
-
+ return [];
+ } + + $activities = []; + foreach ($response as $item) {
- $ua = new Hybrid_User_Activity();
-
+ $ua = new Hybrid_User_Activity(); + $ua->id = (property_exists($item, 'id')) ? $item->id : "";
$ua->date = (property_exists($item, 'created_at')) ? strtotime($item->created_at) : "";
- $ua->text = (property_exists($item, 'text')) ? $item->text : "";
-
+ $ua->text = (property_exists($item, 'text')) ? $item->text : ""; + $ua->user->identifier = (property_exists($item->user, 'id')) ? $item->user->id : "";
$ua->user->displayName = (property_exists($item->user, 'name')) ? $item->user->name : "";
$ua->user->profileURL = (property_exists($item->user, 'screen_name')) ? ("http://twitter.com/" . $item->user->screen_name) : "";
- $ua->user->photoURL = (property_exists($item->user, 'profile_image_url')) ? $item->user->profile_image_url : "";
-
+ $ua->user->photoURL = (property_exists($item->user, 'profile_image_url')) ? $item->user->profile_image_url : ""; + $activities[] = $ua;
- }
-
+ } + return $activities;
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/Providers/Yahoo.php b/hauth/Hybrid/Providers/Yahoo.php index 82e3972..cd23270 100644 --- a/hauth/Hybrid/Providers/Yahoo.php +++ b/hauth/Hybrid/Providers/Yahoo.php @@ -1,11 +1,11 @@ <?php
-
+ /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Yahoo OAuth Class.
*
@@ -14,256 +14,256 @@ * @author Oleg Kuzava <olegkuzava@gmail.com>
* @version 1.0
* @license BSD License
- */
-
+ */ + /**
* Hybrid_Providers_Yahoo - Yahoo provider adapter based on OAuth2 protocol.
*/
-class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth2 {
-
- /**
- * Define Yahoo scopes.
- *
- * @var array $scope
- * If empty will be used YDN App scopes.
- * @see https://developer.yahoo.com/oauth2/guide/yahoo_scopes.
- */
- public $scope = array();
-
- /**
- * {@inheritdoc}
- */
- function initialize() {
- parent::initialize();
-
- // Provider api end-points.
- $this->api->api_base_url = "https://social.yahooapis.com/v1/";
- $this->api->authorize_url = "https://api.login.yahoo.com/oauth2/request_auth";
- $this->api->token_url = "https://api.login.yahoo.com/oauth2/get_token";
-
- // Set token headers.
- $this->setAuthorizationHeaders("basic");
- }
-
- /**
- * {@inheritdoc}
- */
- function loginBegin() {
- if (is_array($this->scope)) {
- $this->scope = implode(",", $this->scope);
- }
- parent::loginBegin();
- }
-
- /**
- * {@inheritdoc}
- */
- function getUserProfile() {
- $userId = $this->getCurrentUserId();
-
- $response = $this->api->get("user/{$userId}/profile", array(
- "format" => "json",
- ));
-
- if (!isset($response->profile)) {
- throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response), 6);
- }
-
- $data = $response->profile;
-
- $this->user->profile->identifier = isset($data->guid) ? $data->guid : "";
- $this->user->profile->firstName = isset($data->givenName) ? $data->givenName : "";
- $this->user->profile->lastName = isset($data->familyName) ? $data->familyName : "";
- $this->user->profile->displayName = isset($data->nickname) ? trim($data->nickname) : "";
- $this->user->profile->profileURL = isset($data->profileUrl) ? $data->profileUrl : "";
- $this->user->profile->gender = isset($data->gender) ? $data->gender : "";
-
- if ($this->user->profile->gender === "F") {
- $this->user->profile->gender = "female";
- }
- elseif ($this->user->profile->gender === "M") {
- $this->user->profile->gender = "male";
- }
-
- if (isset($data->emails)) {
- $email = "";
- foreach ($data->emails as $v) {
- if (isset($v->primary) && $v->primary) {
- $email = isset($v->handle) ? $v->handle : "";
- break;
- }
- }
- $this->user->profile->email = $email;
- $this->user->profile->emailVerified = $email;
- }
-
- $this->user->profile->age = isset($data->displayAge) ? $data->displayAge : "";
- $this->user->profile->photoURL = isset($data->image) ? $data->image->imageUrl : "";
-
- $this->user->profile->address = isset($data->location) ? $data->location : "";
- $this->user->profile->language = isset($data->lang) ? $data->lang : "";
-
- return $this->user->profile;
- }
-
- /**
- * {@inheritdoc}
- */
- function getUserContacts() {
- $userId = $this->getCurrentUserId();
-
- $response = $this->api->get("user/{$userId}/contacts", array(
- "format" => "json",
- "count" => "max",
- ));
-
- if ($this->api->http_code != 200) {
- throw new Exception("User contacts request failed! {$this->providerId} returned an error: " . $this->errorMessageByStatus());
- }
-
- if (!isset($response->contacts) || !isset($response->contacts->contact) || (isset($response->errcode) && $response->errcode != 0)) {
- return array();
- }
-
- $contacts = array();
- foreach ($response->contacts->contact as $item) {
- $uc = new Hybrid_User_Contact();
-
- $uc->identifier = isset($item->id) ? $item->id : "";
- $uc->email = $this->selectEmail($item->fields);
- $uc->displayName = $this->selectName($item->fields);
- $uc->photoURL = $this->selectPhoto($item->fields);
-
- $contacts[] = $uc;
- }
-
- return $contacts;
- }
-
- /**
- * Returns current user id.
- *
- * @return string
- * Current user ID.
- * @throws Exception
- */
- function getCurrentUserId() {
- // Set headers to get refresh token.
- $this->setAuthorizationHeaders("basic");
-
- // Refresh tokens if needed.
- $this->refreshToken();
-
- // Set headers to make api call.
- $this->setAuthorizationHeaders("bearer");
-
- $response = $this->api->get("me/guid", array(
- "format" => "json",
- ));
-
- if (!isset($response->guid->value)) {
- throw new Exception("User id request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response));
- }
-
- return $response->guid->value;
- }
-
- /**
- * Utility function for returning values from XML-like objects.
- *
- * @param stdClass $vs
- * Object.
- * @param string $t
- * Property name.
- * @return mixed
- */
- private function select($vs, $t) {
- foreach ($vs as $v) {
- if ($v->type == $t) {
- return $v;
- }
- }
-
- return null;
- }
-
- /**
- * Parses user name.
- *
- * @param stdClass $v
- * Object.
- * @return string
- * User name.
- */
- private function selectName($v) {
- $s = $this->select($v, "name");
- if (!$s) {
- $s = $this->select($v, "nickname");
- return isset($s->value) ? $s->value : "";
- }
- return isset($s->value) ? "{$s->value->givenName} {$s->value->familyName}" : "";
- }
-
- /**
- * Parses photo URL.
- *
- * @param stdClass $v
- * Object.
- * @return string
- * Photo URL.
- */
- private function selectPhoto($v) {
- $s = $this->select($v, "image");
-
- return isset($s->value) ? $s->value->imageUrl : "";
- }
-
- /**
- * Parses email.
- *
- * @param stdClass $v
- * Object
- * @return string
- * An email address.
- */
- private function selectEmail($v) {
- $s = $this->select($v, "email");
- if (empty($s)) {
- $s = $this->select($v, "yahooid");
- if (isset($s->value) && strpos($s->value, "@") === FALSE) {
- $s->value .= "@yahoo.com";
- }
- }
-
- return isset($s->value) ? $s->value : "";
- }
-
- /**
- * Set correct Authorization headers.
- *
- * @param string $token_type
- * Specify token type.
- *
- * @return void
- */
- private function setAuthorizationHeaders($token_type) {
- switch ($token_type) {
- case "basic":
- // The /get_token requires authorization header.
- $token = base64_encode("{$this->config["keys"]["id"]}:{$this->config["keys"]["secret"]}");
- $this->api->curl_header = array(
- "Authorization: Basic {$token}",
- "Content-Type: application/x-www-form-urlencoded",
- );
- break;
-
- case "bearer":
- // Yahoo API requires the token to be passed as a Bearer within the authorization header.
- $this->api->curl_header = array(
- "Authorization: Bearer {$this->api->access_token}",
- );
- break;
- }
- }
-
-}
+class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth2 { + + /**
+ * Define Yahoo scopes.
+ *
+ * @var array $scope
+ * If empty will be used YDN App scopes.
+ * @see https://developer.yahoo.com/oauth2/guide/yahoo_scopes.
+ */
+ public $scope = []; + + /**
+ * {@inheritdoc}
+ */
+ function initialize() {
+ parent::initialize(); + + // Provider api end-points.
+ $this->api->api_base_url = "https://social.yahooapis.com/v1/";
+ $this->api->authorize_url = "https://api.login.yahoo.com/oauth2/request_auth";
+ $this->api->token_url = "https://api.login.yahoo.com/oauth2/get_token"; + + // Set token headers.
+ $this->setAuthorizationHeaders("basic");
+ } + + /**
+ * {@inheritdoc}
+ */
+ function loginBegin() {
+ if (is_array($this->scope)) {
+ $this->scope = implode(",", $this->scope);
+ }
+ parent::loginBegin();
+ } + + /**
+ * {@inheritdoc}
+ */
+ function getUserProfile() {
+ $userId = $this->getCurrentUserId(); + + $response = $this->api->get("user/{$userId}/profile", [
+ "format" => "json",
+ ]); + + if (!isset($response->profile)) {
+ throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response), 6); + } + + $data = $response->profile; + + $this->user->profile->identifier = $data->guid ?? "";
+ $this->user->profile->firstName = $data->givenName ?? "";
+ $this->user->profile->lastName = $data->familyName ?? "";
+ $this->user->profile->displayName = isset($data->nickname) ? trim($data->nickname) : "";
+ $this->user->profile->profileURL = $data->profileUrl ?? "";
+ $this->user->profile->gender = $data->gender ?? ""; + + if ($this->user->profile->gender === "F") {
+ $this->user->profile->gender = "female";
+ }
+ elseif ($this->user->profile->gender === "M") {
+ $this->user->profile->gender = "male";
+ } + + if (isset($data->emails)) {
+ $email = "";
+ foreach ($data->emails as $v) {
+ if (isset($v->primary) && $v->primary) {
+ $email = $v->handle ?? "";
+ break;
+ }
+ }
+ $this->user->profile->email = $email;
+ $this->user->profile->emailVerified = $email;
+ } + + $this->user->profile->age = $data->displayAge ?? "";
+ $this->user->profile->photoURL = isset($data->image) ? $data->image->imageUrl : ""; + + $this->user->profile->address = $data->location ?? "";
+ $this->user->profile->language = $data->lang ?? ""; + + return $this->user->profile;
+ } + + /**
+ * {@inheritdoc}
+ */
+ function getUserContacts() {
+ $userId = $this->getCurrentUserId(); + + $response = $this->api->get("user/{$userId}/contacts", [
+ "format" => "json",
+ "count" => "max",
+ ]); + + if ($this->api->http_code != 200) {
+ throw new Exception("User contacts request failed! {$this->providerId} returned an error: " . $this->errorMessageByStatus()); + } + + if (!isset($response->contacts) || !isset($response->contacts->contact) || (isset($response->errcode) && $response->errcode != 0)) {
+ return [];
+ } + + $contacts = [];
+ foreach ($response->contacts->contact as $item) {
+ $uc = new Hybrid_User_Contact(); + + $uc->identifier = $item->id ?? "";
+ $uc->email = $this->selectEmail($item->fields);
+ $uc->displayName = $this->selectName($item->fields);
+ $uc->photoURL = $this->selectPhoto($item->fields); + + $contacts[] = $uc;
+ } + + return $contacts;
+ } + + /**
+ * Returns current user id.
+ *
+ * @return string
+ * Current user ID.
+ * @throws Exception
+ */
+ function getCurrentUserId() {
+ // Set headers to get refresh token.
+ $this->setAuthorizationHeaders("basic"); + + // Refresh tokens if needed.
+ $this->refreshToken(); + + // Set headers to make api call.
+ $this->setAuthorizationHeaders("bearer"); + + $response = $this->api->get("me/guid", [
+ "format" => "json",
+ ]); + + if (!isset($response->guid->value)) {
+ throw new Exception("User id request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response)); + } + + return $response->guid->value;
+ } + + /**
+ * Utility function for returning values from XML-like objects.
+ *
+ * @param stdClass $vs
+ * Object.
+ * @param string $t
+ * Property name.
+ * @return mixed
+ */
+ private function select($vs, $t) {
+ foreach ($vs as $v) {
+ if ($v->type == $t) {
+ return $v;
+ }
+ } + + return null;
+ } + + /**
+ * Parses user name.
+ *
+ * @param stdClass $v
+ * Object.
+ * @return string
+ * User name.
+ */
+ private function selectName($v) {
+ $s = $this->select($v, "name");
+ if (!$s) {
+ $s = $this->select($v, "nickname");
+ return $s->value ?? "";
+ }
+ return isset($s->value) ? "{$s->value->givenName} {$s->value->familyName}" : "";
+ } + + /**
+ * Parses photo URL.
+ *
+ * @param stdClass $v
+ * Object.
+ * @return string
+ * Photo URL.
+ */
+ private function selectPhoto($v) {
+ $s = $this->select($v, "image"); + + return isset($s->value) ? $s->value->imageUrl : "";
+ } + + /**
+ * Parses email.
+ *
+ * @param stdClass $v
+ * Object
+ * @return string
+ * An email address.
+ */
+ private function selectEmail($v) {
+ $s = $this->select($v, "email");
+ if (empty($s)) {
+ $s = $this->select($v, "yahooid");
+ if (isset($s->value) && strpos($s->value, "@") === FALSE) {
+ $s->value .= "@yahoo.com";
+ }
+ } + + return $s->value ?? "";
+ } + + /**
+ * Set correct Authorization headers.
+ *
+ * @param string $token_type
+ * Specify token type.
+ *
+ * @return void
+ */
+ private function setAuthorizationHeaders($token_type) {
+ switch ($token_type) {
+ case "basic":
+ // The /get_token requires authorization header.
+ $token = base64_encode("{$this->config["keys"]["id"]}:{$this->config["keys"]["secret"]}");
+ $this->api->curl_header = [
+ "Authorization: Basic {$token}",
+ "Content-Type: application/x-www-form-urlencoded",
+ ];
+ break; + + case "bearer":
+ // Yahoo API requires the token to be passed as a Bearer within the authorization header.
+ $this->api->curl_header = [
+ "Authorization: Bearer {$this->api->access_token}",
+ ];
+ break;
+ }
+ } + +} diff --git a/hauth/Hybrid/Storage.php b/hauth/Hybrid/Storage.php index d82b4af..b9fa366 100644 --- a/hauth/Hybrid/Storage.php +++ b/hauth/Hybrid/Storage.php @@ -1,31 +1,31 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
-require_once realpath(dirname(__FILE__)) . "/StorageInterface.php";
-
+require_once realpath(dirname(__FILE__)) . "/StorageInterface.php"; + /**
* HybridAuth storage manager
*/
-class Hybrid_Storage implements Hybrid_Storage_Interface {
-
+class Hybrid_Storage implements Hybrid_Storage_Interface { + /**
* Constructor
*/
function __construct() {
if (!session_id()) {
if (!session_start()) {
- throw new Exception("Hybridauth requires the use of 'session_start()' at the start of your script, which appears to be disabled.", 1);
+ throw new Exception("Hybridauth requires the use of 'session_start()' at the start of your script, which appears to be disabled.", 1); }
- }
-
+ } + $this->config("php_session_id", session_id());
$this->config("version", Hybrid_Auth::$version);
- }
-
+ } + /**
* Saves a value in the config storage, or returns config if value is null
*
@@ -34,17 +34,17 @@ class Hybrid_Storage implements Hybrid_Storage_Interface { * @return array|null
*/
public function config($key, $value = null) {
- $key = strtolower($key);
-
+ $key = strtolower($key); + if ($value) {
$_SESSION["HA::CONFIG"][$key] = serialize($value);
} elseif (isset($_SESSION["HA::CONFIG"][$key])) {
return unserialize($_SESSION["HA::CONFIG"][$key]);
- }
-
+ } + return null;
- }
-
+ } + /**
* Returns value from session storage
*
@@ -52,15 +52,15 @@ class Hybrid_Storage implements Hybrid_Storage_Interface { * @return string|null
*/
public function get($key) {
- $key = strtolower($key);
-
+ $key = strtolower($key); + if (isset($_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key])) {
return unserialize($_SESSION["HA::STORE"][$key]);
- }
-
+ } + return null;
- }
-
+ } + /**
* Saves a key value pair to the session storage
*
@@ -71,16 +71,16 @@ class Hybrid_Storage implements Hybrid_Storage_Interface { public function set($key, $value) {
$key = strtolower($key);
$_SESSION["HA::STORE"][$key] = serialize($value);
- }
-
+ } + /**
* Clear session storage
* @return void
*/
function clear() {
- $_SESSION["HA::STORE"] = array();
- }
-
+ $_SESSION["HA::STORE"] = [];
+ } + /**
* Delete a specific key from session storage
*
@@ -88,15 +88,15 @@ class Hybrid_Storage implements Hybrid_Storage_Interface { * @return void
*/
function delete($key) {
- $key = strtolower($key);
-
+ $key = strtolower($key); + if (isset($_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key])) {
$f = $_SESSION['HA::STORE'];
unset($f[$key]);
$_SESSION["HA::STORE"] = $f;
}
- }
-
+ } + /**
* Delete all keys recursively from session storage
*
@@ -104,8 +104,8 @@ class Hybrid_Storage implements Hybrid_Storage_Interface { * @retun void
*/
function deleteMatch($key) {
- $key = strtolower($key);
-
+ $key = strtolower($key); + if (isset($_SESSION["HA::STORE"]) && count($_SESSION["HA::STORE"])) {
$f = $_SESSION['HA::STORE'];
foreach ($f as $k => $v) {
@@ -115,8 +115,8 @@ class Hybrid_Storage implements Hybrid_Storage_Interface { }
$_SESSION["HA::STORE"] = $f;
}
- }
-
+ } + /**
* Returns session storage as a serialized string
* @return string|null
@@ -126,8 +126,8 @@ class Hybrid_Storage implements Hybrid_Storage_Interface { return serialize($_SESSION["HA::STORE"]);
}
return null;
- }
-
+ } + /**
* Restores the session from serialized session data
*
@@ -136,6 +136,6 @@ class Hybrid_Storage implements Hybrid_Storage_Interface { */
function restoreSessionData($sessiondata = null) {
$_SESSION["HA::STORE"] = unserialize($sessiondata);
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/StorageInterface.php b/hauth/Hybrid/StorageInterface.php index 5b171ec..5b171ec 100644..100755 --- a/hauth/Hybrid/StorageInterface.php +++ b/hauth/Hybrid/StorageInterface.php diff --git a/hauth/Hybrid/User.php b/hauth/Hybrid/User.php index 6461671..6668aca 100644 --- a/hauth/Hybrid/User.php +++ b/hauth/Hybrid/User.php @@ -1,40 +1,40 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* The Hybrid_User class represents the current logged in user
*/
-class Hybrid_User {
-
+class Hybrid_User { + /**
* The ID (name) of the connected provider
* @var mixed
*/
- public $providerId = null;
-
+ public $providerId = null; + /**
* Timestamp connection to the provider
* @var int
*/
- public $timestamp = null;
-
+ public $timestamp = null; + /**
* User profile, contains the list of fields available in the normalized user profile structure used by HybridAuth
* @var Hybrid_User_Profile
*/
- public $profile = null;
-
+ public $profile = null; + /**
* Initialize the user object
*/
function __construct() {
$this->timestamp = time();
$this->profile = new Hybrid_User_Profile();
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/User_Activity.php b/hauth/Hybrid/User_Activity.php index 4a57e16..7dc9376 100644 --- a/hauth/Hybrid/User_Activity.php +++ b/hauth/Hybrid/User_Activity.php @@ -1,11 +1,11 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_User_Activity
*
@@ -13,43 +13,43 @@ *
* http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Activity.html
*/
-class Hybrid_User_Activity {
-
+class Hybrid_User_Activity { + /**
* Activity id on the provider side, usually given as integer
* @var mixed
*/
- public $id = null;
-
+ public $id = null; + /**
* Activity date of creation
* @var int
*/
- public $date = null;
-
+ public $date = null; + /**
* Activity content as a string
* @var string
*/
- public $text = null;
-
+ public $text = null; + /**
* User who created the activity
* @var stdClass
*/
- public $user = null;
-
+ public $user = null; + /**
* Constructor
*/
public function __construct() {
- $this->user = new stdClass();
-
+ $this->user = new stdClass(); + // typically, we should have a few information about the user who created the event from social apis
$this->user->identifier = null;
$this->user->displayName = null;
$this->user->profileURL = null;
$this->user->photoURL = null;
- }
-
-}
+ } + +} diff --git a/hauth/Hybrid/User_Contact.php b/hauth/Hybrid/User_Contact.php index facbfc4..33a7fc8 100644 --- a/hauth/Hybrid/User_Contact.php +++ b/hauth/Hybrid/User_Contact.php @@ -1,11 +1,11 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_User_Contact
*
@@ -13,48 +13,48 @@ *
* http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Contacts.html
*/
-class Hybrid_User_Contact {
-
+class Hybrid_User_Contact { + /**
* The Unique contact user ID
* @var mixed
*/
- public $identifier = null;
-
+ public $identifier = null; + /**
* User website, blog, web page
* @var string
*/
- public $webSiteURL = null;
-
+ public $webSiteURL = null; + /**
* URL link to profile page on the IDp web site
* @var string
*/
- public $profileURL = null;
-
+ public $profileURL = null; + /**
* URL link to user photo or avatar
* @var string
*/
- public $photoURL = null;
-
+ public $photoURL = null; + /**
* User displayName provided by the IDp or a concatenation of first and last name
* @var string
*/
- public $displayName = null;
-
+ public $displayName = null; + /**
* A short about_me
* @var string
*/
- public $description = null;
-
+ public $description = null; + /**
* User email. Not all of IDp grant access to the user email
* @var string
*/
- public $email = null;
-
-}
+ public $email = null; + +} diff --git a/hauth/Hybrid/User_Profile.php b/hauth/Hybrid/User_Profile.php index 403be89..0cf299c 100644 --- a/hauth/Hybrid/User_Profile.php +++ b/hauth/Hybrid/User_Profile.php @@ -1,11 +1,11 @@ <?php
-
+ /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
- */
-
+ */ + /**
* Hybrid_User_Profile object represents the current logged in user profile.
* The list of fields available in the normalized user profile structure used by HybridAuth.
@@ -15,149 +15,149 @@ *
* http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Profile.html
*/
-class Hybrid_User_Profile {
-
+class Hybrid_User_Profile { + /**
* The Unique user's ID on the connected provider
* @var mixed
*/
- public $identifier = null;
-
+ public $identifier = null; + /**
* User website, blog, web page
* @var string
*/
- public $webSiteURL = null;
-
+ public $webSiteURL = null; + /**
* URL link to profile page on the IDp web site
* @var string
*/
- public $profileURL = null;
-
+ public $profileURL = null; + /**
* URL link to user photo or avatar
* @var string
*/
- public $photoURL = null;
-
+ public $photoURL = null; + /**
* User displayName provided by the IDp or a concatenation of first and last name.
* @var string
*/
- public $displayName = null;
-
+ public $displayName = null; + /**
* A short about_me
* @var string
*/
- public $description = null;
-
+ public $description = null; + /**
* User's first name
* @var string
*/
- public $firstName = null;
-
+ public $firstName = null; + /**
* User's last name
* @var string
*/
- public $lastName = null;
-
+ public $lastName = null; + /**
* Male or female
* @var string
*/
- public $gender = null;
-
+ public $gender = null; + /**
* Language
* @var string
*/
- public $language = null;
-
+ public $language = null; + /**
* User age, we don't calculate it. we return it as is if the IDp provide it.
* @var int
*/
- public $age = null;
-
+ public $age = null; + /**
* User birth Day
* @var int
*/
- public $birthDay = null;
-
+ public $birthDay = null; + /**
* User birth Month
* @var int
*/
- public $birthMonth = null;
-
+ public $birthMonth = null; + /**
* User birth Year
* @var int
*/
- public $birthYear = null;
-
+ public $birthYear = null; + /**
* User email. Note: not all of IDp grant access to the user email
* @var string
*/
- public $email = null;
-
+ public $email = null; + /**
* Verified user email. Note: not all of IDp grant access to verified user email
* @var string
*/
- public $emailVerified = null;
-
+ public $emailVerified = null; + /**
* Phone number
* @var string
*/
- public $phone = null;
-
+ public $phone = null; + /**
* Complete user address
* @var string
*/
- public $address = null;
-
+ public $address = null; + /**
* User country
* @var string
*/
- public $country = null;
-
+ public $country = null; + /**
* Region
* @var string
*/
- public $region = null;
-
+ public $region = null; + /**
* City
* @var string
*/
- public $city = null;
-
+ public $city = null; + /**
* Postal code
* @var string
*/
- public $zip = null;
-
+ public $zip = null; + /**
* Job title
* @var string
*/
- public $job_title = null;
-
+ public $job_title = null; + /**
* Organization name
* @var string
*/
public $organization_name = null;
-}
+} diff --git a/hauth/Hybrid/index.html b/hauth/Hybrid/index.html index 065d2da..065d2da 100644..100755 --- a/hauth/Hybrid/index.html +++ b/hauth/Hybrid/index.html diff --git a/hauth/Hybrid/resources/index.html b/hauth/Hybrid/resources/index.html index 065d2da..065d2da 100644..100755 --- a/hauth/Hybrid/resources/index.html +++ b/hauth/Hybrid/resources/index.html diff --git a/hauth/Hybrid/resources/openid_policy.html b/hauth/Hybrid/resources/openid_policy.html index bf5c52c..bf5c52c 100644..100755 --- a/hauth/Hybrid/resources/openid_policy.html +++ b/hauth/Hybrid/resources/openid_policy.html diff --git a/hauth/Hybrid/resources/openid_realm.html b/hauth/Hybrid/resources/openid_realm.html index e26a5a1..e26a5a1 100644..100755 --- a/hauth/Hybrid/resources/openid_realm.html +++ b/hauth/Hybrid/resources/openid_realm.html diff --git a/hauth/Hybrid/resources/openid_xrds.xml b/hauth/Hybrid/resources/openid_xrds.xml index 9d50170..9d50170 100644..100755 --- a/hauth/Hybrid/resources/openid_xrds.xml +++ b/hauth/Hybrid/resources/openid_xrds.xml diff --git a/hauth/Hybrid/thirdparty/Amazon/AmazonOAuth2Client.php b/hauth/Hybrid/thirdparty/Amazon/AmazonOAuth2Client.php index 9c8a363..723dbdb 100644 --- a/hauth/Hybrid/thirdparty/Amazon/AmazonOAuth2Client.php +++ b/hauth/Hybrid/thirdparty/Amazon/AmazonOAuth2Client.php @@ -25,13 +25,13 @@ class AmazonOAuth2Client extends OAuth2Client { public function authenticate( $code ) { - $params = array( + $params = [ "client_id" => $this->client_id, "client_secret" => $this->client_secret, "grant_type" => 'authorization_code', "redirect_uri" => $this->redirect_uri, "code" => $code, - ); + ]; $response = $this->request( $this->token_url, http_build_query($params), $this->curl_authenticate_method ); @@ -62,7 +62,7 @@ class AmazonOAuth2Client extends OAuth2Client { $url = $url . ( strpos( $url, '?' ) ? '&' : '?' ) . http_build_query($params, '', '&'); } - $this->http_info = array(); + $this->http_info = []; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL , $url ); diff --git a/hauth/Hybrid/thirdparty/OAuth/OAuth.php b/hauth/Hybrid/thirdparty/OAuth/OAuth.php index 4d06837..9f82cb8 100755 --- a/hauth/Hybrid/thirdparty/OAuth/OAuth.php +++ b/hauth/Hybrid/thirdparty/OAuth/OAuth.php @@ -1,62 +1,62 @@ <?php
// http://oauth.googlecode.com/svn/code/php/OAuth.php
-// rev 1276, July 4, 2014
-
-// vim: foldmethod=marker
-
+// rev 1276, July 4, 2014 + +// vim: foldmethod=marker + /* Generic exception class
*/
if (!class_exists('OAuthException', false)) {
class OAuthException extends Exception {
- // pass
+ // pass
}
-}
-
+} + class OAuthConsumer {
public $key;
- public $secret;
-
+ public $secret; + function __construct($key, $secret, $callback_url=null) {
- $this->key = $key;
- $this->secret = $secret;
- $this->callback_url = $callback_url;
- }
-
+ $this->key = $key;
+ $this->secret = $secret;
+ $this->callback_url = $callback_url;
+ } + function __toString() {
- return "OAuthConsumer[key=$this->key,secret=$this->secret]";
+ return "OAuthConsumer[key=$this->key,secret=$this->secret]";
}
-}
-
+} + class OAuthToken {
// access tokens and request tokens
public $key;
- public $secret;
-
+ public $secret; + /**
* key = the token
* secret = the token secret
*/
function __construct($key, $secret) {
- $this->key = $key;
- $this->secret = $secret;
- }
-
+ $this->key = $key;
+ $this->secret = $secret;
+ } + /**
* generates the basic string serialization of a token that a server
* would respond to request_token and access_token calls with
*/
function to_string() {
- return "oauth_token=" .
- OAuthUtil::urlencode_rfc3986($this->key) .
- "&oauth_token_secret=" .
- OAuthUtil::urlencode_rfc3986($this->secret);
- }
-
+ return "oauth_token=" .
+ OAuthUtil::urlencode_rfc3986($this->key) .
+ "&oauth_token_secret=" .
+ OAuthUtil::urlencode_rfc3986($this->secret);
+ } + function __toString() {
- return $this->to_string();
+ return $this->to_string();
}
-}
-
+} + /**
* A class for implementing a Signature Method
* See section 9 ("Signing Requests") in the spec
@@ -66,8 +66,8 @@ abstract class OAuthSignatureMethod { * Needs to return the name of the Signature Method (ie HMAC-SHA1)
* @return string
*/
- abstract public function get_name();
-
+ abstract public function get_name(); + /**
* Build up the signature
* NOTE: The output of this function MUST NOT be urlencoded.
@@ -78,8 +78,8 @@ abstract class OAuthSignatureMethod { * @param OAuthToken $token
* @return string
*/
- abstract public function build_signature($request, $consumer, $token);
-
+ abstract public function build_signature($request, $consumer, $token); + /**
* Verifies that a given signature is correct
* @param OAuthRequest $request
@@ -89,27 +89,27 @@ abstract class OAuthSignatureMethod { * @return bool
*/
public function check_signature($request, $consumer, $token, $signature) {
- $built = $this->build_signature($request, $consumer, $token);
-
- // Check for zero length, although unlikely here
- if (strlen($built) == 0 || strlen($signature) == 0) {
- return false;
- }
-
- if (strlen($built) != strlen($signature)) {
- return false;
- }
-
- // Avoid a timing leak with a (hopefully) time insensitive compare
- $result = 0;
- for ($i = 0; $i < strlen($signature); $i++) {
- $result |= ord($built[$i]) ^ ord($signature[$i]);
- }
-
- return $result == 0;
+ $built = $this->build_signature($request, $consumer, $token); + + // Check for zero length, although unlikely here
+ if (strlen($built) == 0 || strlen($signature) == 0) {
+ return false;
+ } + + if (strlen($built) != strlen($signature)) {
+ return false;
+ } + + // Avoid a timing leak with a (hopefully) time insensitive compare
+ $result = 0;
+ for ($i = 0; $i < strlen($signature); $i++) {
+ $result |= ord($built[$i]) ^ ord($signature[$i]);
+ } + + return $result == 0;
}
-}
-
+} + /**
* The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
* where the Signature Base String is the text and the key is the concatenated values (each first
@@ -119,25 +119,25 @@ abstract class OAuthSignatureMethod { */
class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
function get_name() {
- return "HMAC-SHA1";
- }
-
+ return "HMAC-SHA1";
+ } + public function build_signature($request, $consumer, $token) {
- $base_string = $request->get_signature_base_string();
- $request->base_string = $base_string;
-
- $key_parts = array(
- $consumer->secret,
- ($token) ? $token->secret : ""
- );
-
- $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
- $key = implode('&', $key_parts);
-
- return base64_encode(hash_hmac('sha1', $base_string, $key, true));
+ $base_string = $request->get_signature_base_string();
+ $request->base_string = $base_string; + + $key_parts = [
+ $consumer->secret,
+ ($token) ? $token->secret : "",
+ ]; + + $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
+ $key = implode('&', $key_parts); + + return base64_encode(hash_hmac('sha1', $base_string, $key, true));
}
-}
-
+} + /**
* The PLAINTEXT method does not provide any security protection and SHOULD only be used
* over a secure channel such as HTTPS. It does not use the Signature Base String.
@@ -145,9 +145,9 @@ class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod { */
class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
public function get_name() {
- return "PLAINTEXT";
- }
-
+ return "PLAINTEXT";
+ } + /**
* oauth_signature is set to the concatenated encoded values of the Consumer Secret and
* Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
@@ -158,19 +158,19 @@ class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod { * OAuthRequest handles this!
*/
public function build_signature($request, $consumer, $token) {
- $key_parts = array(
- $consumer->secret,
- ($token) ? $token->secret : ""
- );
-
- $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
- $key = implode('&', $key_parts);
- $request->base_string = $key;
-
- return $key;
+ $key_parts = [
+ $consumer->secret,
+ ($token) ? $token->secret : "",
+ ]; + + $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
+ $key = implode('&', $key_parts);
+ $request->base_string = $key; + + return $key;
}
-}
-
+} + /**
* The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
* [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
@@ -181,63 +181,63 @@ class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod { */
abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
public function get_name() {
- return "RSA-SHA1";
- }
-
+ return "RSA-SHA1";
+ } + // Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
// (2) fetch via http using a url provided by the requester
// (3) some sort of specific discovery code based on request
//
// Either way should return a string representation of the certificate
- protected abstract function fetch_public_cert(&$request);
-
+ protected abstract function fetch_public_cert(&$request); + // Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
//
// Either way should return a string representation of the certificate
- protected abstract function fetch_private_cert(&$request);
-
+ protected abstract function fetch_private_cert(&$request); + public function build_signature($request, $consumer, $token) {
- $base_string = $request->get_signature_base_string();
- $request->base_string = $base_string;
-
- // Fetch the private key cert based on the request
- $cert = $this->fetch_private_cert($request);
-
- // Pull the private key ID from the certificate
- $privatekeyid = openssl_get_privatekey($cert);
-
- // Sign using the key
- $ok = openssl_sign($base_string, $signature, $privatekeyid);
-
- // Release the key resource
- openssl_free_key($privatekeyid);
-
- return base64_encode($signature);
- }
-
+ $base_string = $request->get_signature_base_string();
+ $request->base_string = $base_string; + + // Fetch the private key cert based on the request
+ $cert = $this->fetch_private_cert($request); + + // Pull the private key ID from the certificate
+ $privatekeyid = openssl_get_privatekey($cert); + + // Sign using the key
+ $ok = openssl_sign($base_string, $signature, $privatekeyid); + + // Release the key resource
+ openssl_free_key($privatekeyid); + + return base64_encode($signature);
+ } + public function check_signature($request, $consumer, $token, $signature) {
- $decoded_sig = base64_decode($signature);
-
- $base_string = $request->get_signature_base_string();
-
- // Fetch the public key cert based on the request
- $cert = $this->fetch_public_cert($request);
-
- // Pull the public key ID from the certificate
- $publickeyid = openssl_get_publickey($cert);
-
- // Check the computed signature against the one passed in the query
- $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
-
- // Release the key resource
- openssl_free_key($publickeyid);
-
- return $ok == 1;
+ $decoded_sig = base64_decode($signature); + + $base_string = $request->get_signature_base_string(); + + // Fetch the public key cert based on the request
+ $cert = $this->fetch_public_cert($request); + + // Pull the public key ID from the certificate
+ $publickeyid = openssl_get_publickey($cert); + + // Check the computed signature against the one passed in the query
+ $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); + + // Release the key resource
+ openssl_free_key($publickeyid); + + return $ok == 1;
}
-}
-
+} + class OAuthRequest {
protected $parameters;
protected $http_method;
@@ -245,133 +245,132 @@ class OAuthRequest { // for debug purposes
public $base_string;
public static $version = '1.0';
- public static $POST_INPUT = 'php://input';
-
+ public static $POST_INPUT = 'php://input'; + function __construct($http_method, $http_url, $parameters=null) {
- $parameters = ($parameters) ? $parameters : array();
- $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
- $this->parameters = $parameters;
- $this->http_method = $http_method;
- $this->http_url = $http_url;
- }
-
-
+ $parameters = ($parameters) ? $parameters : [];
+ $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
+ $this->parameters = $parameters;
+ $this->http_method = $http_method;
+ $this->http_url = $http_url;
+ } + /**
* attempt to build up a request from what was passed to the server
*/
public static function from_request($http_method=null, $http_url=null, $parameters=null) {
- $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
- ? 'http'
- : 'https';
- if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
- $scheme = $_SERVER['HTTP_X_FORWARDED_PROTO'];
- }
- $http_url = ($http_url) ? $http_url : $scheme .
- '://' . $_SERVER['SERVER_NAME'] .
- ':' .
- $_SERVER['SERVER_PORT'] .
- $_SERVER['REQUEST_URI'];
- $http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD'];
-
- // We weren't handed any parameters, so let's find the ones relevant to
- // this request.
- // If you run XML-RPC or similar you should use this to provide your own
- // parsed parameter-list
- if (!$parameters) {
- // Find request headers
- $request_headers = OAuthUtil::get_headers();
-
- // Parse the query-string to find GET parameters
- $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
-
- // It's a POST request of the proper content-type, so parse POST
- // parameters and add those overriding any duplicates from GET
- if ($http_method == "POST"
- && isset($request_headers['Content-Type'])
- && strstr($request_headers['Content-Type'],
- 'application/x-www-form-urlencoded')
- ) {
- $post_data = OAuthUtil::parse_parameters(
- file_get_contents(self::$POST_INPUT)
- );
- $parameters = array_merge($parameters, $post_data);
- }
-
- // We have a Authorization-header with OAuth data. Parse the header
- // and add those overriding any duplicates from GET or POST
- if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') {
- $header_parameters = OAuthUtil::split_header(
- $request_headers['Authorization']
- );
- $parameters = array_merge($parameters, $header_parameters);
- }
-
- }
-
- return new OAuthRequest($http_method, $http_url, $parameters);
- }
-
+ $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
+ ? 'http'
+ : 'https';
+ if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
+ $scheme = $_SERVER['HTTP_X_FORWARDED_PROTO'];
+ }
+ $http_url = ($http_url) ? $http_url : $scheme .
+ '://' . $_SERVER['SERVER_NAME'] .
+ ':' .
+ $_SERVER['SERVER_PORT'] .
+ $_SERVER['REQUEST_URI'];
+ $http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD']; + + // We weren't handed any parameters, so let's find the ones relevant to
+ // this request.
+ // If you run XML-RPC or similar you should use this to provide your own
+ // parsed parameter-list
+ if (!$parameters) {
+ // Find request headers
+ $request_headers = OAuthUtil::get_headers(); + + // Parse the query-string to find GET parameters
+ $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']); + + // It's a POST request of the proper content-type, so parse POST
+ // parameters and add those overriding any duplicates from GET
+ if ($http_method == "POST"
+ && isset($request_headers['Content-Type'])
+ && strstr($request_headers['Content-Type'],
+ 'application/x-www-form-urlencoded', )
+ ) {
+ $post_data = OAuthUtil::parse_parameters(
+ file_get_contents(self::$POST_INPUT),
+ );
+ $parameters = array_merge($parameters, $post_data);
+ } + + // We have a Authorization-header with OAuth data. Parse the header
+ // and add those overriding any duplicates from GET or POST
+ if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') {
+ $header_parameters = OAuthUtil::split_header(
+ $request_headers['Authorization'],
+ );
+ $parameters = array_merge($parameters, $header_parameters);
+ } + + } + + return new OAuthRequest($http_method, $http_url, $parameters);
+ } + /**
* pretty much a helper function to set up the request
*/
public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=null) {
- $parameters = ($parameters) ? $parameters : array();
- $defaults = array("oauth_version" => OAuthRequest::$version,
- "oauth_nonce" => OAuthRequest::generate_nonce(),
- "oauth_timestamp" => OAuthRequest::generate_timestamp(),
- "oauth_consumer_key" => $consumer->key);
- if ($token)
- $defaults['oauth_token'] = $token->key;
-
- $parameters = array_merge($defaults, $parameters);
-
- return new OAuthRequest($http_method, $http_url, $parameters);
- }
-
+ $parameters = ($parameters) ? $parameters : [];
+ $defaults = ["oauth_version" => OAuthRequest::$version,
+ "oauth_nonce" => OAuthRequest::generate_nonce(),
+ "oauth_timestamp" => OAuthRequest::generate_timestamp(),
+ "oauth_consumer_key" => $consumer->key, ];
+ if ($token)
+ $defaults['oauth_token'] = $token->key; + + $parameters = array_merge($defaults, $parameters); + + return new OAuthRequest($http_method, $http_url, $parameters);
+ } + public function set_parameter($name, $value, $allow_duplicates = true) {
- if ($allow_duplicates && isset($this->parameters[$name])) {
- // We have already added parameter(s) with this name, so add to the list
- if (is_scalar($this->parameters[$name])) {
- // This is the first duplicate, so transform scalar (string)
- // into an array so we can add the duplicates
- $this->parameters[$name] = array($this->parameters[$name]);
- }
-
- $this->parameters[$name][] = $value;
- } else {
- $this->parameters[$name] = $value;
- }
- }
-
+ if ($allow_duplicates && isset($this->parameters[$name])) {
+ // We have already added parameter(s) with this name, so add to the list
+ if (is_scalar($this->parameters[$name])) {
+ // This is the first duplicate, so transform scalar (string)
+ // into an array so we can add the duplicates
+ $this->parameters[$name] = [$this->parameters[$name]];
+ } + + $this->parameters[$name][] = $value;
+ } else {
+ $this->parameters[$name] = $value;
+ }
+ } + public function get_parameter($name) {
- return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
- }
-
+ return $this->parameters[$name] ?? null;
+ } + public function get_parameters() {
- return $this->parameters;
- }
-
+ return $this->parameters;
+ } + public function unset_parameter($name) {
- unset($this->parameters[$name]);
- }
-
+ unset($this->parameters[$name]);
+ } + /**
* The request parameters, sorted and concatenated into a normalized string.
* @return string
*/
public function get_signable_parameters() {
- // Grab all parameters
- $params = $this->parameters;
-
- // Remove oauth_signature if present
- // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
- if (isset($params['oauth_signature'])) {
- unset($params['oauth_signature']);
- }
-
- return OAuthUtil::build_http_query($params);
- }
-
+ // Grab all parameters
+ $params = $this->parameters; + + // Remove oauth_signature if present
+ // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
+ if (isset($params['oauth_signature'])) {
+ unset($params['oauth_signature']);
+ } + + return OAuthUtil::build_http_query($params);
+ } + /**
* Returns the base string of this request
*
@@ -380,522 +379,520 @@ class OAuthRequest { * and the concated with &.
*/
public function get_signature_base_string() {
- $parts = array(
- $this->get_normalized_http_method(),
- $this->get_normalized_http_url(),
- $this->get_signable_parameters()
- );
-
- $parts = OAuthUtil::urlencode_rfc3986($parts);
-
- return implode('&', $parts);
- }
-
+ $parts = [
+ $this->get_normalized_http_method(),
+ $this->get_normalized_http_url(),
+ $this->get_signable_parameters(),
+ ]; + + $parts = OAuthUtil::urlencode_rfc3986($parts); + + return implode('&', $parts);
+ } + /**
* just uppercases the http method
*/
public function get_normalized_http_method() {
- return strtoupper($this->http_method);
- }
-
+ return strtoupper($this->http_method);
+ } + /**
* parses the url and rebuilds it to be
* scheme://host/path
*/
public function get_normalized_http_url() {
- $parts = parse_url($this->http_url);
-
- $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
- $port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80');
- $host = (isset($parts['host'])) ? strtolower($parts['host']) : '';
- $path = (isset($parts['path'])) ? $parts['path'] : '';
-
- if (($scheme == 'https' && $port != '443')
- || ($scheme == 'http' && $port != '80')) {
- $host = "$host:$port";
- }
- return "$scheme://$host$path";
- }
-
+ $parts = parse_url($this->http_url); + + $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
+ $port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80');
+ $host = (isset($parts['host'])) ? strtolower($parts['host']) : '';
+ $path = (isset($parts['path'])) ? $parts['path'] : ''; + + if (($scheme == 'https' && $port != '443')
+ || ($scheme == 'http' && $port != '80')) {
+ $host = "$host:$port";
+ }
+ return "$scheme://$host$path";
+ } + /**
* builds a url usable for a GET request
*/
public function to_url() {
- $post_data = $this->to_postdata();
- $out = $this->get_normalized_http_url();
- if ($post_data) {
- $out .= '?'.$post_data;
- }
- return $out;
- }
-
+ $post_data = $this->to_postdata();
+ $out = $this->get_normalized_http_url();
+ if ($post_data) {
+ $out .= '?'.$post_data;
+ }
+ return $out;
+ } + /**
* builds the data one would send in a POST request
*/
public function to_postdata() {
- return OAuthUtil::build_http_query($this->parameters);
- }
-
+ return OAuthUtil::build_http_query($this->parameters);
+ } + /**
* builds the Authorization: header
*/
public function to_header($realm=null) {
- $first = true;
+ $first = true;
if($realm) {
- $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
- $first = false;
- } else
- $out = 'Authorization: OAuth';
-
- $total = array();
- foreach ($this->parameters as $k => $v) {
- if (substr($k, 0, 5) != "oauth") continue;
- if (is_array($v)) {
- throw new OAuthException('arrays not supported in headers');
- }
- $out .= ($first) ? ' ' : ',';
- $out .= OAuthUtil::urlencode_rfc3986($k) .
- '="' .
- OAuthUtil::urlencode_rfc3986($v) .
- '"';
- $first = false;
- }
- return $out;
- }
-
+ $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
+ $first = false;
+ } else
+ $out = 'Authorization: OAuth'; + + $total = [];
+ foreach ($this->parameters as $k => $v) {
+ if (substr($k, 0, 5) != "oauth") continue;
+ if (is_array($v)) {
+ throw new OAuthException('arrays not supported in headers'); + }
+ $out .= ($first) ? ' ' : ',';
+ $out .= OAuthUtil::urlencode_rfc3986($k) .
+ '="' .
+ OAuthUtil::urlencode_rfc3986($v) .
+ '"';
+ $first = false;
+ }
+ return $out;
+ } + public function __toString() {
- return $this->to_url();
- }
-
-
+ return $this->to_url();
+ } + public function sign_request($signature_method, $consumer, $token) {
- $this->set_parameter(
- "oauth_signature_method",
- $signature_method->get_name(),
- false
- );
- $signature = $this->build_signature($signature_method, $consumer, $token);
- $this->set_parameter("oauth_signature", $signature, false);
- }
-
+ $this->set_parameter(
+ "oauth_signature_method",
+ $signature_method->get_name(),
+ false,
+ );
+ $signature = $this->build_signature($signature_method, $consumer, $token);
+ $this->set_parameter("oauth_signature", $signature, false);
+ } + public function build_signature($signature_method, $consumer, $token) {
- $signature = $signature_method->build_signature($this, $consumer, $token);
- return $signature;
- }
-
+ $signature = $signature_method->build_signature($this, $consumer, $token);
+ return $signature;
+ } + /**
* util function: current timestamp
*/
private static function generate_timestamp() {
- return time();
- }
-
+ return time();
+ } + /**
* util function: current nonce
*/
private static function generate_nonce() {
- $mt = microtime();
- $rand = mt_rand();
-
- return md5($mt . $rand); // md5s look nicer than numbers
+ $mt = microtime();
+ $rand = mt_rand(); + + return md5($mt . $rand); // md5s look nicer than numbers
}
-}
-
+} + class OAuthServer {
protected $timestamp_threshold = 300; // in seconds, five minutes
protected $version = '1.0'; // hi blaine
- protected $signature_methods = array();
-
- protected $data_store;
-
+ protected $signature_methods = []; + + protected $data_store; + function __construct($data_store) {
- $this->data_store = $data_store;
- }
-
+ $this->data_store = $data_store;
+ } + public function add_signature_method($signature_method) {
- $this->signature_methods[$signature_method->get_name()] =
- $signature_method;
- }
-
- // high level functions
-
+ $this->signature_methods[$signature_method->get_name()] =
+ $signature_method;
+ } + + // high level functions + /**
* process a request_token request
* returns the request token on success
*/
public function fetch_request_token(&$request) {
- $this->get_version($request);
-
- $consumer = $this->get_consumer($request);
-
- // no token required for the initial token request
- $token = null;
-
- $this->check_signature($request, $consumer, $token);
-
- // Rev A change
- $callback = $request->get_parameter('oauth_callback');
- $new_token = $this->data_store->new_request_token($consumer, $callback);
-
- return $new_token;
- }
-
+ $this->get_version($request); + + $consumer = $this->get_consumer($request); + + // no token required for the initial token request
+ $token = null; + + $this->check_signature($request, $consumer, $token); + + // Rev A change
+ $callback = $request->get_parameter('oauth_callback');
+ $new_token = $this->data_store->new_request_token($consumer, $callback); + + return $new_token;
+ } + /**
* process an access_token request
* returns the access token on success
*/
public function fetch_access_token(&$request) {
- $this->get_version($request);
-
- $consumer = $this->get_consumer($request);
-
- // requires authorized request token
- $token = $this->get_token($request, $consumer, "request");
-
- $this->check_signature($request, $consumer, $token);
-
- // Rev A change
- $verifier = $request->get_parameter('oauth_verifier');
- $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
-
- return $new_token;
- }
-
+ $this->get_version($request); + + $consumer = $this->get_consumer($request); + + // requires authorized request token
+ $token = $this->get_token($request, $consumer, "request"); + + $this->check_signature($request, $consumer, $token); + + // Rev A change
+ $verifier = $request->get_parameter('oauth_verifier');
+ $new_token = $this->data_store->new_access_token($token, $consumer, $verifier); + + return $new_token;
+ } + /**
* verify an api call, checks all the parameters
*/
public function verify_request(&$request) {
- $this->get_version($request);
- $consumer = $this->get_consumer($request);
- $token = $this->get_token($request, $consumer, "access");
- $this->check_signature($request, $consumer, $token);
- return array($consumer, $token);
- }
-
+ $this->get_version($request);
+ $consumer = $this->get_consumer($request);
+ $token = $this->get_token($request, $consumer, "access");
+ $this->check_signature($request, $consumer, $token);
+ return [$consumer, $token];
+ } + // Internals from here
/**
* version 1
*/
private function get_version(&$request) {
- $version = $request->get_parameter("oauth_version");
- if (!$version) {
- // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
- // Chapter 7.0 ("Accessing Protected Ressources")
- $version = '1.0';
- }
- if ($version !== $this->version) {
- throw new OAuthException("OAuth version '$version' not supported");
- }
- return $version;
- }
-
+ $version = $request->get_parameter("oauth_version");
+ if (!$version) {
+ // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
+ // Chapter 7.0 ("Accessing Protected Ressources")
+ $version = '1.0';
+ }
+ if ($version !== $this->version) {
+ throw new OAuthException("OAuth version '$version' not supported"); + }
+ return $version;
+ } + /**
* figure out the signature with some defaults
*/
private function get_signature_method($request) {
- $signature_method = $request instanceof OAuthRequest
- ? $request->get_parameter("oauth_signature_method")
- : null;
-
- if (!$signature_method) {
- // According to chapter 7 ("Accessing Protected Ressources") the signature-method
- // parameter is required, and we can't just fallback to PLAINTEXT
- throw new OAuthException('No signature method parameter. This parameter is required');
- }
-
- if (!in_array($signature_method,
- array_keys($this->signature_methods))) {
- throw new OAuthException(
- "Signature method '$signature_method' not supported " .
- "try one of the following: " .
- implode(", ", array_keys($this->signature_methods))
- );
- }
- return $this->signature_methods[$signature_method];
- }
-
+ $signature_method = $request instanceof OAuthRequest
+ ? $request->get_parameter("oauth_signature_method")
+ : null; + + if (!$signature_method) {
+ // According to chapter 7 ("Accessing Protected Ressources") the signature-method
+ // parameter is required, and we can't just fallback to PLAINTEXT
+ throw new OAuthException('No signature method parameter. This parameter is required'); + } + + if (!in_array($signature_method,
+ array_keys($this->signature_methods), )) {
+ throw new OAuthException( + "Signature method '$signature_method' not supported " .
+ "try one of the following: " .
+ implode(", ", array_keys($this->signature_methods)),
+ );
+ }
+ return $this->signature_methods[$signature_method];
+ } + /**
* try to find the consumer for the provided request's consumer key
*/
private function get_consumer($request) {
- $consumer_key = $request instanceof OAuthRequest
- ? $request->get_parameter("oauth_consumer_key")
- : null;
-
- if (!$consumer_key) {
- throw new OAuthException("Invalid consumer key");
- }
-
- $consumer = $this->data_store->lookup_consumer($consumer_key);
- if (!$consumer) {
- throw new OAuthException("Invalid consumer");
- }
-
- return $consumer;
- }
-
+ $consumer_key = $request instanceof OAuthRequest
+ ? $request->get_parameter("oauth_consumer_key")
+ : null; + + if (!$consumer_key) {
+ throw new OAuthException("Invalid consumer key"); + } + + $consumer = $this->data_store->lookup_consumer($consumer_key);
+ if (!$consumer) {
+ throw new OAuthException("Invalid consumer"); + } + + return $consumer;
+ } + /**
* try to find the token for the provided request's token key
*/
private function get_token($request, $consumer, $token_type="access") {
- $token_field = $request instanceof OAuthRequest
- ? $request->get_parameter('oauth_token')
- : null;
-
- $token = $this->data_store->lookup_token(
- $consumer, $token_type, $token_field
- );
- if (!$token) {
- throw new OAuthException("Invalid $token_type token: $token_field");
- }
- return $token;
- }
-
+ $token_field = $request instanceof OAuthRequest
+ ? $request->get_parameter('oauth_token')
+ : null; + + $token = $this->data_store->lookup_token(
+ $consumer, $token_type, $token_field,
+ );
+ if (!$token) {
+ throw new OAuthException("Invalid $token_type token: $token_field"); + }
+ return $token;
+ } + /**
* all-in-one function to check the signature on a request
* should guess the signature method appropriately
*/
private function check_signature($request, $consumer, $token) {
- // this should probably be in a different method
- $timestamp = $request instanceof OAuthRequest
- ? $request->get_parameter('oauth_timestamp')
- : null;
- $nonce = $request instanceof OAuthRequest
- ? $request->get_parameter('oauth_nonce')
- : null;
-
- $this->check_timestamp($timestamp);
- $this->check_nonce($consumer, $token, $nonce, $timestamp);
-
- $signature_method = $this->get_signature_method($request);
-
- $signature = $request->get_parameter('oauth_signature');
- $valid_sig = $signature_method->check_signature(
- $request,
- $consumer,
- $token,
- $signature
- );
-
- if (!$valid_sig) {
- throw new OAuthException("Invalid signature");
- }
- }
-
+ // this should probably be in a different method
+ $timestamp = $request instanceof OAuthRequest
+ ? $request->get_parameter('oauth_timestamp')
+ : null;
+ $nonce = $request instanceof OAuthRequest
+ ? $request->get_parameter('oauth_nonce')
+ : null; + + $this->check_timestamp($timestamp);
+ $this->check_nonce($consumer, $token, $nonce, $timestamp); + + $signature_method = $this->get_signature_method($request); + + $signature = $request->get_parameter('oauth_signature');
+ $valid_sig = $signature_method->check_signature(
+ $request,
+ $consumer,
+ $token,
+ $signature,
+ ); + + if (!$valid_sig) {
+ throw new OAuthException("Invalid signature"); + }
+ } + /**
* check that the timestamp is new enough
*/
private function check_timestamp($timestamp) {
- if( ! $timestamp )
- throw new OAuthException(
- 'Missing timestamp parameter. The parameter is required'
- );
-
- // verify that timestamp is recentish
- $now = time();
- if (abs($now - $timestamp) > $this->timestamp_threshold) {
- throw new OAuthException(
- "Expired timestamp, yours $timestamp, ours $now"
- );
- }
- }
-
+ if( ! $timestamp )
+ throw new OAuthException(
+ 'Missing timestamp parameter. The parameter is required',
+ ); + + // verify that timestamp is recentish
+ $now = time();
+ if (abs($now - $timestamp) > $this->timestamp_threshold) {
+ throw new OAuthException( + "Expired timestamp, yours $timestamp, ours $now",
+ );
+ }
+ } + /**
* check that the nonce is not repeated
*/
private function check_nonce($consumer, $token, $nonce, $timestamp) {
- if( ! $nonce )
- throw new OAuthException(
- 'Missing nonce parameter. The parameter is required'
- );
-
- // verify that the nonce is uniqueish
- $found = $this->data_store->lookup_nonce(
- $consumer,
- $token,
- $nonce,
- $timestamp
- );
- if ($found) {
- throw new OAuthException("Nonce already used: $nonce");
- }
- }
-
-}
-
+ if( ! $nonce )
+ throw new OAuthException(
+ 'Missing nonce parameter. The parameter is required',
+ ); + + // verify that the nonce is uniqueish
+ $found = $this->data_store->lookup_nonce(
+ $consumer,
+ $token,
+ $nonce,
+ $timestamp,
+ );
+ if ($found) {
+ throw new OAuthException("Nonce already used: $nonce"); + }
+ } + +} + class OAuthDataStore {
function lookup_consumer($consumer_key) {
- // implement me
- }
-
+ // implement me
+ } + function lookup_token($consumer, $token_type, $token) {
- // implement me
- }
-
+ // implement me
+ } + function lookup_nonce($consumer, $token, $nonce, $timestamp) {
- // implement me
- }
-
+ // implement me
+ } + function new_request_token($consumer, $callback = null) {
- // return a new token attached to this consumer
- }
-
+ // return a new token attached to this consumer
+ } + function new_access_token($token, $consumer, $verifier = null) {
- // return a new access token attached to this consumer
- // for the user associated with this token if the request token
- // is authorized
- // should also invalidate the request token
- }
-
-}
-
+ // return a new access token attached to this consumer
+ // for the user associated with this token if the request token
+ // is authorized
+ // should also invalidate the request token
+ } + +} + class OAuthUtil {
public static function urlencode_rfc3986($input) {
if (is_array($input)) {
- return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
+ return array_map(['OAuthUtil', 'urlencode_rfc3986'], $input);
} else if (is_scalar($input)) {
- return str_replace(
- '+',
- ' ',
- str_replace('%7E', '~', rawurlencode($input))
- );
+ return str_replace(
+ '+',
+ ' ',
+ str_replace('%7E', '~', rawurlencode($input)),
+ );
} else {
- return '';
+ return '';
}
-}
-
-
+} + // This decode function isn't taking into consideration the above
// modifications to the encoding process. However, this method doesn't
// seem to be used anywhere so leaving it as is.
public static function urldecode_rfc3986($string) {
- return urldecode($string);
- }
-
+ return urldecode($string);
+ } + // Utility function for turning the Authorization: header into
// parameters, has to do some unescaping
// Can filter out any non-oauth parameters if needed (default behaviour)
// May 28th, 2010 - method updated to tjerk.meesters for a speed improvement.
// see http://code.google.com/p/oauth/issues/detail?id=163
public static function split_header($header, $only_allow_oauth_parameters = true) {
- $params = array();
- if (preg_match_all('/('.($only_allow_oauth_parameters ? 'oauth_' : '').'[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches)) {
- foreach ($matches[1] as $i => $h) {
- $params[$h] = OAuthUtil::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]);
- }
- if (isset($params['realm'])) {
- unset($params['realm']);
- }
- }
- return $params;
- }
-
+ $params = [];
+ if (preg_match_all('/('.($only_allow_oauth_parameters ? 'oauth_' : '').'[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches)) {
+ foreach ($matches[1] as $i => $h) {
+ $params[$h] = OAuthUtil::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]);
+ }
+ if (isset($params['realm'])) {
+ unset($params['realm']);
+ }
+ }
+ return $params;
+ } + // helper to try to sort out headers for people who aren't running apache
public static function get_headers() {
- if (function_exists('apache_request_headers')) {
- // we need this to get the actual Authorization: header
- // because apache tends to tell us it doesn't exist
- $headers = apache_request_headers();
-
- // sanitize the output of apache_request_headers because
- // we always want the keys to be Cased-Like-This and arh()
- // returns the headers in the same case as they are in the
- // request
- $out = array();
- foreach ($headers AS $key => $value) {
- $key = str_replace(
- " ",
- "-",
- ucwords(strtolower(str_replace("-", " ", $key)))
- );
- $out[$key] = $value;
- }
- } else {
- // otherwise we don't have apache and are just going to have to hope
- // that $_SERVER actually contains what we need
- $out = array();
- if( isset($_SERVER['CONTENT_TYPE']) )
- $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
- if( isset($_ENV['CONTENT_TYPE']) )
- $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
-
- foreach ($_SERVER as $key => $value) {
- if (substr($key, 0, 5) == "HTTP_") {
- // this is chaos, basically it is just there to capitalize the first
- // letter of every word that is not an initial HTTP and strip HTTP
- // code from przemek
- $key = str_replace(
- " ",
- "-",
- ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
- );
- $out[$key] = $value;
- }
- }
- }
- return $out;
- }
-
+ if (function_exists('apache_request_headers')) {
+ // we need this to get the actual Authorization: header
+ // because apache tends to tell us it doesn't exist
+ $headers = apache_request_headers(); + + // sanitize the output of apache_request_headers because
+ // we always want the keys to be Cased-Like-This and arh()
+ // returns the headers in the same case as they are in the
+ // request
+ $out = [];
+ foreach ($headers AS $key => $value) {
+ $key = str_replace(
+ " ",
+ "-",
+ ucwords(strtolower(str_replace("-", " ", $key))),
+ );
+ $out[$key] = $value;
+ }
+ } else {
+ // otherwise we don't have apache and are just going to have to hope
+ // that $_SERVER actually contains what we need
+ $out = [];
+ if( isset($_SERVER['CONTENT_TYPE']) )
+ $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
+ if( isset($_ENV['CONTENT_TYPE']) )
+ $out['Content-Type'] = $_ENV['CONTENT_TYPE']; + + foreach ($_SERVER as $key => $value) {
+ if (substr($key, 0, 5) == "HTTP_") {
+ // this is chaos, basically it is just there to capitalize the first
+ // letter of every word that is not an initial HTTP and strip HTTP
+ // code from przemek
+ $key = str_replace(
+ " ",
+ "-",
+ ucwords(strtolower(str_replace("_", " ", substr($key, 5)))),
+ );
+ $out[$key] = $value;
+ }
+ }
+ }
+ return $out;
+ } + // This function takes a input like a=b&a=c&d=e and returns the parsed
// parameters like this
// array('a' => array('b','c'), 'd' => 'e')
public static function parse_parameters( $input ) {
- if (!isset($input) || !$input) return array();
-
- $pairs = explode('&', $input);
-
- $parsed_parameters = array();
- foreach ($pairs as $pair) {
- $split = explode('=', $pair, 2);
- $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
- $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
-
- if (isset($parsed_parameters[$parameter])) {
- // We have already recieved parameter(s) with this name, so add to the list
- // of parameters with this name
-
- if (is_scalar($parsed_parameters[$parameter])) {
- // This is the first duplicate, so transform scalar (string) into an array
- // so we can add the duplicates
- $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
- }
-
- $parsed_parameters[$parameter][] = $value;
- } else {
- $parsed_parameters[$parameter] = $value;
- }
- }
- return $parsed_parameters;
- }
-
+ if (!isset($input) || !$input) return []; + + $pairs = explode('&', $input); + + $parsed_parameters = [];
+ foreach ($pairs as $pair) {
+ $split = explode('=', $pair, 2);
+ $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
+ $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : ''; + + if (isset($parsed_parameters[$parameter])) {
+ // We have already recieved parameter(s) with this name, so add to the list
+ // of parameters with this name + + if (is_scalar($parsed_parameters[$parameter])) {
+ // This is the first duplicate, so transform scalar (string) into an array
+ // so we can add the duplicates
+ $parsed_parameters[$parameter] = [$parsed_parameters[$parameter]];
+ } + + $parsed_parameters[$parameter][] = $value;
+ } else {
+ $parsed_parameters[$parameter] = $value;
+ }
+ }
+ return $parsed_parameters;
+ } + public static function build_http_query($params) {
- if (!$params) return '';
-
- // Urlencode both keys and values
- $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
- $values = OAuthUtil::urlencode_rfc3986(array_values($params));
- $params = array_combine($keys, $values);
-
- // Parameters are sorted by name, using lexicographical byte value ordering.
- // Ref: Spec: 9.1.1 (1)
- uksort($params, 'strcmp');
-
- $pairs = array();
- foreach ($params as $parameter => $value) {
- if (is_array($value)) {
- // If two or more parameters share the same name, they are sorted by their value
- // Ref: Spec: 9.1.1 (1)
- // June 12th, 2010 - changed to sort because of issue 164 by hidetaka
- sort($value, SORT_STRING);
- foreach ($value as $duplicate_value) {
- $pairs[] = $parameter . '=' . $duplicate_value;
- }
- } else {
- $pairs[] = $parameter . '=' . $value;
- }
- }
- // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
- // Each name-value pair is separated by an '&' character (ASCII code 38)
- return implode('&', $pairs);
+ if (!$params) return ''; + + // Urlencode both keys and values
+ $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
+ $values = OAuthUtil::urlencode_rfc3986(array_values($params));
+ $params = array_combine($keys, $values); + + // Parameters are sorted by name, using lexicographical byte value ordering.
+ // Ref: Spec: 9.1.1 (1)
+ uksort($params, 'strcmp'); + + $pairs = [];
+ foreach ($params as $parameter => $value) {
+ if (is_array($value)) {
+ // If two or more parameters share the same name, they are sorted by their value
+ // Ref: Spec: 9.1.1 (1)
+ // June 12th, 2010 - changed to sort because of issue 164 by hidetaka
+ sort($value, SORT_STRING);
+ foreach ($value as $duplicate_value) {
+ $pairs[] = $parameter . '=' . $duplicate_value;
+ }
+ } else {
+ $pairs[] = $parameter . '=' . $value;
+ }
+ }
+ // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
+ // Each name-value pair is separated by an '&' character (ASCII code 38)
+ return implode('&', $pairs);
}
-}
+} diff --git a/hauth/Hybrid/thirdparty/OAuth/OAuth1Client.php b/hauth/Hybrid/thirdparty/OAuth/OAuth1Client.php index 64c03c8..2cdf249 100644 --- a/hauth/Hybrid/thirdparty/OAuth/OAuth1Client.php +++ b/hauth/Hybrid/thirdparty/OAuth/OAuth1Client.php @@ -52,20 +52,20 @@ class OAuth1Client{ * * @return string */ - function authorizeUrl( $token, $extras =array() ) + function authorizeUrl( $token, $extras =[] ) { if ( is_array( $token ) ){ $token = $token['oauth_token']; } - $parameters = array( "oauth_token" => $token ); + $parameters = [ "oauth_token" => $token ]; if( count($extras) ) foreach( $extras as $k=>$v ) $parameters[$k] = $v; return $this->authorize_url . "?" . http_build_query( $parameters ); - } + } /** * Get a request_token from provider @@ -74,7 +74,7 @@ class OAuth1Client{ */ function requestToken( $callback = null ) { - $parameters = array(); + $parameters = []; if ( $callback ) { $this->redirect_uri = $parameters['oauth_callback'] = $callback; @@ -94,7 +94,7 @@ class OAuth1Client{ */ function accessToken( $oauth_verifier = false, $oauth_token = false ) { - $parameters = array(); + $parameters = []; // 1.0a if ( $oauth_verifier ) { @@ -111,7 +111,7 @@ class OAuth1Client{ /** * GET wrapper for provider apis request */ - function get($url, $parameters = array(), $content_type = null) + function get($url, $parameters = [], $content_type = null) { return $this->api($url, 'GET', $parameters, null, $content_type); } @@ -119,7 +119,7 @@ class OAuth1Client{ /** * POST wrapper for provider apis request */ - function post($url, $parameters = array(), $body = null, $content_type = null, $multipart = false) + function post($url, $parameters = [], $body = null, $content_type = null, $multipart = false) { return $this->api($url, 'POST', $parameters, $body, $content_type, $multipart ); } @@ -127,7 +127,7 @@ class OAuth1Client{ /** * Format and sign an oauth for provider api */ - function api( $url, $method = 'GET', $parameters = array(), $body = null, $content_type = null, $multipart = false ) + function api( $url, $method = 'GET', $parameters = [], $body = null, $content_type = null, $multipart = false ) { if ( strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0 ) { $url = $this->api_base_url . $url; @@ -149,7 +149,7 @@ class OAuth1Client{ */ public function getResponse() { - return $this->response; + return $this->response; } /** @@ -158,14 +158,14 @@ class OAuth1Client{ function signedRequest( $url, $method, $parameters, $body = null, $content_type = null, $multipart = false ) { - $signature_parameters = array(); + $signature_parameters = []; - // when making a multipart request, use only oauth_* keys for signature - foreach( $parameters AS $key => $value ){ - if( !$multipart || strpos( $key, 'oauth_' ) === 0 ){ - $signature_parameters[$key] = $value; - } - } + // when making a multipart request, use only oauth_* keys for signature + foreach( $parameters AS $key => $value ){ + if( !$multipart || strpos( $key, 'oauth_' ) === 0 ){ + $signature_parameters[$key] = $value; + } + } $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $signature_parameters); $request->sign_request($this->sha1_method, $this->consumer, $this->token); @@ -174,7 +174,7 @@ class OAuth1Client{ default : if ($body) return $this->request( $request->to_url(), $method, $body, $request->to_header(), $content_type ); - else + return $this->request( $request->get_normalized_http_url(), $method, ($multipart ? $parameters : $request->to_postdata()), $request->to_header(), $content_type, $multipart ) ; } } @@ -187,7 +187,7 @@ class OAuth1Client{ Hybrid_Logger::info( "Enter OAuth1Client::request( $method, $url )" ); Hybrid_Logger::debug( "OAuth1Client::request(). dump post fields: ", serialize( $postfields ) ); - $this->http_info = array(); + $this->http_info = []; $ci = curl_init(); /* Curl settings */ @@ -195,16 +195,16 @@ class OAuth1Client{ curl_setopt( $ci, CURLOPT_CONNECTTIMEOUT, $this->curl_connect_time_out ); curl_setopt( $ci, CURLOPT_TIMEOUT , $this->curl_time_out ); curl_setopt( $ci, CURLOPT_RETURNTRANSFER, true ); - curl_setopt( $ci, CURLOPT_HTTPHEADER , array('Expect:') ); + curl_setopt( $ci, CURLOPT_HTTPHEADER , ['Expect:'] ); curl_setopt( $ci, CURLOPT_SSL_VERIFYPEER, $this->curl_ssl_verifypeer ); - curl_setopt( $ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader') ); + curl_setopt( $ci, CURLOPT_HEADERFUNCTION, [$this, 'getHeader'] ); curl_setopt( $ci, CURLOPT_HEADER , false ); - if( $multipart ){ - curl_setopt( $ci, CURLOPT_HTTPHEADER, array( 'Expect:', $auth_header ) ); + if( $multipart ){ + curl_setopt( $ci, CURLOPT_HTTPHEADER, [ 'Expect:', $auth_header ] ); - }elseif ($content_type) - curl_setopt( $ci, CURLOPT_HTTPHEADER, array('Expect:', "Content-Type: $content_type") ); + }elseif ($content_type) + curl_setopt( $ci, CURLOPT_HTTPHEADER, ['Expect:', "Content-Type: $content_type"] ); if($this->curl_proxy){ curl_setopt( $ci, CURLOPT_PROXY , $this->curl_proxy); @@ -219,7 +219,7 @@ class OAuth1Client{ } if ( !empty($auth_header) && $this->curl_auth_header && !$multipart ){ - curl_setopt( $ci, CURLOPT_HTTPHEADER, array( 'Content-Type: application/atom+xml', $auth_header ) ); + curl_setopt( $ci, CURLOPT_HTTPHEADER, [ 'Content-Type: application/atom+xml', $auth_header ] ); } break; case 'DELETE': @@ -235,7 +235,6 @@ class OAuth1Client{ Hybrid_Logger::error( "OAuth1Client::request(). curl_exec error: ", curl_error($ci) ); } - Hybrid_Logger::debug( "OAuth1Client::request(). dump request info: ", serialize( curl_getinfo($ci) ) ); Hybrid_Logger::debug( "OAuth1Client::request(). dump request result: ", serialize( $response ) ); diff --git a/hauth/Hybrid/thirdparty/OAuth/OAuth2Client.php b/hauth/Hybrid/thirdparty/OAuth/OAuth2Client.php index 0046d2c..568232d 100644 --- a/hauth/Hybrid/thirdparty/OAuth/OAuth2Client.php +++ b/hauth/Hybrid/thirdparty/OAuth/OAuth2Client.php @@ -30,7 +30,7 @@ class OAuth2Client public $curl_connect_time_out = 30; public $curl_ssl_verifypeer = false; public $curl_ssl_verifyhost = false; - public $curl_header = array(); + public $curl_header = []; public $curl_useragent = "OAuth/2 Simple PHP Client v0.1.1; HybridAuth http://hybridauth.sourceforge.net/"; public $curl_authenticate_method = "POST"; public $curl_proxy = null; @@ -45,108 +45,108 @@ class OAuth2Client public function __construct( $client_id = false, $client_secret = false, $redirect_uri='', $compressed = false ) { - $this->client_id = $client_id; - $this->client_secret = $client_secret; - $this->redirect_uri = $redirect_uri; - $this->curl_compressed = $compressed; + $this->client_id = $client_id; + $this->client_secret = $client_secret; + $this->redirect_uri = $redirect_uri; + $this->curl_compressed = $compressed; } - public function authorizeUrl( $extras = array() ) + public function authorizeUrl( $extras = [] ) { - $params = array( - "client_id" => $this->client_id, - "redirect_uri" => $this->redirect_uri, - "response_type" => "code" - ); + $params = [ + "client_id" => $this->client_id, + "redirect_uri" => $this->redirect_uri, + "response_type" => "code", + ]; - if( count($extras) ) - foreach( $extras as $k=>$v ) - $params[$k] = $v; + if( count($extras) ) + foreach( $extras as $k=>$v ) + $params[$k] = $v; - return $this->authorize_url . "?" . http_build_query($params, '', '&'); + return $this->authorize_url . "?" . http_build_query($params, '', '&'); } public function authenticate( $code ) { - $params = array( - "client_id" => $this->client_id, - "client_secret" => $this->client_secret, - "grant_type" => "authorization_code", - "redirect_uri" => $this->redirect_uri, - "code" => $code - ); + $params = [ + "client_id" => $this->client_id, + "client_secret" => $this->client_secret, + "grant_type" => "authorization_code", + "redirect_uri" => $this->redirect_uri, + "code" => $code, + ]; - $response = $this->request( $this->token_url, $params, $this->curl_authenticate_method ); + $response = $this->request( $this->token_url, $params, $this->curl_authenticate_method ); - $response = $this->parseRequestResult( $response ); + $response = $this->parseRequestResult( $response ); - if( ! $response || ! isset( $response->access_token ) ){ - throw new Exception( "The Authorization Service has return: " . $response->error ); - } + if( ! $response || ! isset( $response->access_token ) ){ + throw new Exception( "The Authorization Service has return: " . $response->error ); + } - if( isset( $response->access_token ) ) $this->access_token = $response->access_token; - if( isset( $response->refresh_token ) ) $this->refresh_token = $response->refresh_token; - if( isset( $response->expires_in ) ) $this->access_token_expires_in = $response->expires_in; + if( isset( $response->access_token ) ) $this->access_token = $response->access_token; + if( isset( $response->refresh_token ) ) $this->refresh_token = $response->refresh_token; + if( isset( $response->expires_in ) ) $this->access_token_expires_in = $response->expires_in; - // calculate when the access token expire - if( isset($response->expires_in)) { - $this->access_token_expires_at = time() + $response->expires_in; - } + // calculate when the access token expire + if( isset($response->expires_in)) { + $this->access_token_expires_at = time() + $response->expires_in; + } - return $response; + return $response; } public function authenticated() { - if ( $this->access_token ){ - if ( $this->token_info_url && $this->refresh_token ){ - // check if this access token has expired, - $tokeninfo = $this->tokenInfo( $this->access_token ); + if ( $this->access_token ){ + if ( $this->token_info_url && $this->refresh_token ){ + // check if this access token has expired, + $tokeninfo = $this->tokenInfo( $this->access_token ); - // if yes, access_token has expired, then ask for a new one - if( $tokeninfo && isset( $tokeninfo->error ) ){ - $response = $this->refreshToken( $this->refresh_token ); + // if yes, access_token has expired, then ask for a new one + if( $tokeninfo && isset( $tokeninfo->error ) ){ + $response = $this->refreshToken( $this->refresh_token ); - // if wrong response - if( ! isset( $response->access_token ) || ! $response->access_token ){ - throw new Exception( "The Authorization Service has return an invalid response while requesting a new access token. given up!" ); - } + // if wrong response + if( ! isset( $response->access_token ) || ! $response->access_token ){ + throw new Exception( "The Authorization Service has return an invalid response while requesting a new access token. given up!" ); + } - // set new access_token - $this->access_token = $response->access_token; - } - } + // set new access_token + $this->access_token = $response->access_token; + } + } - return true; - } + return true; + } - return false; + return false; } /** * Format and sign an oauth for provider api */ - public function api( $url, $method = "GET", $parameters = array(), $decode_json = true ) + public function api( $url, $method = "GET", $parameters = [], $decode_json = true ) { - if ( strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0 ) { - $url = $this->api_base_url . $url; - } + if ( strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0 ) { + $url = $this->api_base_url . $url; + } - $parameters[$this->sign_token_name] = $this->access_token; - $response = null; + $parameters[$this->sign_token_name] = $this->access_token; + $response = null; - switch( $method ){ - case 'GET' : $response = $this->request( $url, $parameters, "GET" ); break; - case 'POST' : $response = $this->request( $url, $parameters, "POST" ); break; - case 'DELETE' : $response = $this->request( $url, $parameters, "DELETE" ); break; - case 'PATCH' : $response = $this->request( $url, $parameters, "PATCH" ); break; - } + switch( $method ){ + case 'GET' : $response = $this->request( $url, $parameters, "GET" ); break; + case 'POST' : $response = $this->request( $url, $parameters, "POST" ); break; + case 'DELETE' : $response = $this->request( $url, $parameters, "DELETE" ); break; + case 'PATCH' : $response = $this->request( $url, $parameters, "PATCH" ); break; + } - if( $response && $decode_json ){ - return $this->response = json_decode( $response ); - } + if( $response && $decode_json ){ + return $this->response = json_decode( $response ); + } - return $this->response = $response; + return $this->response = $response; } /** @@ -156,147 +156,147 @@ class OAuth2Client */ public function getResponse() { - return $this->response; + return $this->response; } /** * GET wrapper for provider apis request */ - function get( $url, $parameters = array(), $decode_json = true ) + function get( $url, $parameters = [], $decode_json = true ) { - return $this->api( $url, 'GET', $parameters, $decode_json ); + return $this->api( $url, 'GET', $parameters, $decode_json ); } /** * POST wrapper for provider apis request */ - function post( $url, $parameters = array(), $decode_json = true ) + function post( $url, $parameters = [], $decode_json = true ) { - return $this->api( $url, 'POST', $parameters, $decode_json ); + return $this->api( $url, 'POST', $parameters, $decode_json ); } // -- tokens public function tokenInfo($accesstoken) { - $params['access_token'] = $this->access_token; - $response = $this->request( $this->token_info_url, $params ); - return $this->parseRequestResult( $response ); + $params['access_token'] = $this->access_token; + $response = $this->request( $this->token_info_url, $params ); + return $this->parseRequestResult( $response ); } - public function refreshToken( $parameters = array() ) + public function refreshToken( $parameters = [] ) { - $params = array( - "client_id" => $this->client_id, - "client_secret" => $this->client_secret, - "grant_type" => "refresh_token" - ); + $params = [ + "client_id" => $this->client_id, + "client_secret" => $this->client_secret, + "grant_type" => "refresh_token", + ]; - foreach($parameters as $k=>$v ){ - $params[$k] = $v; - } + foreach($parameters as $k=>$v ){ + $params[$k] = $v; + } - $response = $this->request( $this->token_url, $params, "POST" ); - return $this->parseRequestResult( $response ); + $response = $this->request( $this->token_url, $params, "POST" ); + return $this->parseRequestResult( $response ); } // -- utilities private function request( $url, $params=false, $type="GET" ) { - Hybrid_Logger::info( "Enter OAuth2Client::request( $url )" ); - Hybrid_Logger::debug( "OAuth2Client::request(). dump request params: ", serialize( $params ) ); + Hybrid_Logger::info( "Enter OAuth2Client::request( $url )" ); + Hybrid_Logger::debug( "OAuth2Client::request(). dump request params: ", serialize( $params ) ); $urlEncodedParams = http_build_query($params, '', '&'); - if( $type == "GET" ){ - $url = $url . ( strpos( $url, '?' ) ? '&' : '?' ) . $urlEncodedParams; - } + if( $type == "GET" ){ + $url = $url . ( strpos( $url, '?' ) ? '&' : '?' ) . $urlEncodedParams; + } - $this->http_info = array(); - $ch = curl_init(); + $this->http_info = []; + $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL , $url ); - curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1 ); - curl_setopt($ch, CURLOPT_TIMEOUT , $this->curl_time_out ); - curl_setopt($ch, CURLOPT_USERAGENT , $this->curl_useragent ); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , $this->curl_connect_time_out ); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , $this->curl_ssl_verifypeer ); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , $this->curl_ssl_verifyhost ); - curl_setopt($ch, CURLOPT_HTTPHEADER , $this->curl_header ); + curl_setopt($ch, CURLOPT_URL , $url ); + curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1 ); + curl_setopt($ch, CURLOPT_TIMEOUT , $this->curl_time_out ); + curl_setopt($ch, CURLOPT_USERAGENT , $this->curl_useragent ); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , $this->curl_connect_time_out ); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , $this->curl_ssl_verifypeer ); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , $this->curl_ssl_verifyhost ); + curl_setopt($ch, CURLOPT_HTTPHEADER , $this->curl_header ); - if ($this->curl_compressed){ - curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate"); - } + if ($this->curl_compressed){ + curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate"); + } - if($this->curl_proxy){ - curl_setopt( $ch, CURLOPT_PROXY , $this->curl_proxy); - } + if($this->curl_proxy){ + curl_setopt( $ch, CURLOPT_PROXY , $this->curl_proxy); + } - if ($type == "POST") { - curl_setopt($ch, CURLOPT_POST, 1); + if ($type == "POST") { + curl_setopt($ch, CURLOPT_POST, 1); - // If request body exists then encode it for "application/json". - if (isset($params['body'])) { - $urlEncodedParams = json_encode($params['body']); - } + // If request body exists then encode it for "application/json". + if (isset($params['body'])) { + $urlEncodedParams = json_encode($params['body']); + } - // Using URL encoded params here instead of a more convenient array - // cURL will set a wrong HTTP Content-Type header if using an array (cf. http://www.php.net/manual/en/function.curl-setopt.php, Notes section for "CURLOPT_POSTFIELDS") - // OAuth requires application/x-www-form-urlencoded Content-Type (cf. https://tools.ietf.org/html/rfc6749#section-2.3.1) - if ($params) { - curl_setopt($ch, CURLOPT_POSTFIELDS, $urlEncodedParams); - } - } + // Using URL encoded params here instead of a more convenient array + // cURL will set a wrong HTTP Content-Type header if using an array (cf. http://www.php.net/manual/en/function.curl-setopt.php, Notes section for "CURLOPT_POSTFIELDS") + // OAuth requires application/x-www-form-urlencoded Content-Type (cf. https://tools.ietf.org/html/rfc6749#section-2.3.1) + if ($params) { + curl_setopt($ch, CURLOPT_POSTFIELDS, $urlEncodedParams); + } + } - if( $type == "DELETE" ){ - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); - } - if( $type == "PATCH" ){ - curl_setopt($ch, CURLOPT_POST, 1); - if($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, $params ); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); - } - $response = curl_exec($ch); - if( $response === false ) { - Hybrid_Logger::error( "OAuth2Client::request(). curl_exec error: ", curl_error($ch) ); - } - Hybrid_Logger::debug( "OAuth2Client::request(). dump request info: ", serialize( curl_getinfo($ch) ) ); - Hybrid_Logger::debug( "OAuth2Client::request(). dump request result: ", serialize( $response ) ); + if( $type == "DELETE" ){ + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); + } + if( $type == "PATCH" ){ + curl_setopt($ch, CURLOPT_POST, 1); + if($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, $params ); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); + } + $response = curl_exec($ch); + if( $response === false ) { + Hybrid_Logger::error( "OAuth2Client::request(). curl_exec error: ", curl_error($ch) ); + } + Hybrid_Logger::debug( "OAuth2Client::request(). dump request info: ", serialize( curl_getinfo($ch) ) ); + Hybrid_Logger::debug( "OAuth2Client::request(). dump request result: ", serialize( $response ) ); - $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $this->http_info = array_merge($this->http_info, curl_getinfo($ch)); + $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $this->http_info = array_merge($this->http_info, curl_getinfo($ch)); - curl_close ($ch); + curl_close ($ch); - return $response; + return $response; } private function parseRequestResult( $result ) { - if( json_decode( $result ) ) return json_decode( $result ); + if( json_decode( $result ) ) return json_decode( $result ); - parse_str( $result, $output ); + parse_str( $result, $output ); - $result = new StdClass(); + $result = new StdClass(); - foreach( $output as $k => $v ) - $result->$k = $v; + foreach( $output as $k => $v ) + $result->$k = $v; - return $result; + return $result; } /** * DELETE wrapper for provider apis request */ - function delete( $url, $parameters = array() ) + function delete( $url, $parameters = [] ) { return $this->api( $url, 'DELETE', $parameters ); } /** * PATCH wrapper for provider apis request */ - function patch( $url, $parameters = array() ) + function patch( $url, $parameters = [] ) { - return $this->api( $url, 'PATCH', $parameters ); + return $this->api( $url, 'PATCH', $parameters ); } } diff --git a/hauth/Hybrid/thirdparty/OpenID/LightOpenID.php b/hauth/Hybrid/thirdparty/OpenID/LightOpenID.php index a257d6c..9e0a5e6 100644 --- a/hauth/Hybrid/thirdparty/OpenID/LightOpenID.php +++ b/hauth/Hybrid/thirdparty/OpenID/LightOpenID.php @@ -13,1039 +13,1037 @@ */
class LightOpenID
{
- public $returnUrl
- , $required = array()
- , $optional = array()
- , $verify_peer = null
- , $capath = null
- , $cainfo = null
- , $cnmatch = null
- , $data
- , $oauth = array()
- , $curl_time_out = 30
- , $curl_connect_time_out = 30;
- private $identity, $claimed_id;
- protected $server, $version, $trustRoot, $aliases, $identifier_select = false
- , $ax = false, $sreg = false, $setup_url = null, $headers = array()
- , $proxy = null, $user_agent = 'LightOpenID'
- , $xrds_override_pattern = null, $xrds_override_replacement = null;
- static protected $ax_to_sreg = array(
- 'namePerson/friendly' => 'nickname',
- 'contact/email' => 'email',
- 'namePerson' => 'fullname',
- 'birthDate' => 'dob',
- 'person/gender' => 'gender',
- 'contact/postalCode/home' => 'postcode',
- 'contact/country/home' => 'country',
- 'pref/language' => 'language',
- 'pref/timezone' => 'timezone',
- );
-
- function __construct($host, $proxy = null)
- {
- $this->set_realm($host);
- $this->set_proxy($proxy);
-
- $uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?');
- $this->returnUrl = $this->trustRoot . $uri;
-
- $this->data = ($_SERVER['REQUEST_METHOD'] === 'POST') ? $_POST : $_GET;
-
- if(!function_exists('curl_init') && !in_array('https', stream_get_wrappers())) {
- throw new ErrorException('You must have either https wrappers or curl enabled.');
- }
- }
-
- function __isset($name)
- {
- return in_array($name, array('identity', 'trustRoot', 'realm', 'xrdsOverride', 'mode'));
- }
-
- function __set($name, $value)
- {
- switch ($name) {
- case 'identity':
- if (strlen($value = trim((String) $value))) {
- if (preg_match('#^xri:/*#i', $value, $m)) {
- $value = substr($value, strlen($m[0]));
- } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) {
- $value = "http://$value";
- }
- if (preg_match('#^https?://[^/]+$#i', $value, $m)) {
- $value .= '/';
- }
- }
- $this->$name = $this->claimed_id = $value;
- break;
- case 'trustRoot':
- case 'realm':
- $this->trustRoot = trim($value);
- break;
- case 'xrdsOverride':
- if (is_array($value)) {
- list($pattern, $replacement) = $value;
- $this->xrds_override_pattern = $pattern;
- $this->xrds_override_replacement = $replacement;
- } else {
- trigger_error('Invalid value specified for "xrdsOverride".', E_USER_ERROR);
- }
- break;
- }
- }
-
- function __get($name)
- {
- switch ($name) {
- case 'identity':
- # We return claimed_id instead of identity,
- # because the developer should see the claimed identifier,
- # i.e. what he set as identity, not the op-local identifier (which is what we verify)
- return $this->claimed_id;
- case 'trustRoot':
- case 'realm':
- return $this->trustRoot;
- case 'mode':
- return empty($this->data['openid_mode']) ? null : $this->data['openid_mode'];
- }
- }
-
- function set_proxy($proxy)
- {
- if (!empty($proxy)) {
- // When the proxy is a string - try to parse it.
- if (!is_array($proxy)) {
- $proxy = parse_url($proxy);
- }
-
- // Check if $proxy is valid after the parsing.
- if ($proxy && !empty($proxy['host'])) {
- // Make sure that a valid port number is specified.
- if (array_key_exists('port', $proxy)) {
- if (!is_int($proxy['port'])) {
- $proxy['port'] = is_numeric($proxy['port']) ? intval($proxy['port']) : 0;
- }
-
- if ($proxy['port'] <= 0) {
- throw new ErrorException('The specified proxy port number is invalid.');
- }
- }
-
- $this->proxy = $proxy;
- }
- }
- }
-
- /**
- * Checks if the server specified in the url exists.
- *
- * @param $url url to check
- * @return true, if the server exists; false otherwise
- */
- function hostExists($url)
- {
- if (strpos($url, '/') === false) {
- $server = $url;
- } else {
- $server = @parse_url($url, PHP_URL_HOST);
- }
-
- if (!$server) {
- return false;
- }
-
- return !!gethostbynamel($server);
- }
-
- protected function set_realm($uri)
- {
- $realm = '';
-
- # Set a protocol, if not specified.
- $realm .= (($offset = strpos($uri, '://')) === false) ? $this->get_realm_protocol() : '';
-
- # Set the offset properly.
- $offset = (($offset !== false) ? $offset + 3 : 0);
-
- # Get only the root, without the path.
- $realm .= (($end = strpos($uri, '/', $offset)) === false) ? $uri : substr($uri, 0, $end);
-
- $this->trustRoot = $realm;
- }
-
- protected function get_realm_protocol()
- {
- if (!empty($_SERVER['HTTPS'])) {
- $use_secure_protocol = ($_SERVER['HTTPS'] != 'off');
- } else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
- $use_secure_protocol = ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
- } else {
- $use_secure_protocol = false;
- }
-
- return $use_secure_protocol ? 'https://' : 'http://';
- }
-
- protected function request_curl($url, $method='GET', $params=array(), $update_claimed_id)
- {
- $params = http_build_query($params, '', '&');
- $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : ''));
- curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_time_out);
- curl_setopt($curl, CURLOPT_CONNECTTIMEOUT , $this->curl_connect_time_out);
-
-
- if ($method == 'POST') {
- curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
- } else {
- curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*'));
- }
-
- if (!empty($this->proxy)) {
- curl_setopt($curl, CURLOPT_PROXY, $this->proxy['host']);
-
- if (!empty($this->proxy['port'])) {
- curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy['port']);
- }
-
- if (!empty($this->proxy['user'])) {
- curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']);
- }
- }
-
- if($this->verify_peer !== null) {
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer);
- if($this->capath) {
- curl_setopt($curl, CURLOPT_CAPATH, $this->capath);
- }
-
- if($this->cainfo) {
- curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo);
- }
- }
-
- if ($method == 'POST') {
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
- } elseif ($method == 'HEAD') {
- curl_setopt($curl, CURLOPT_HEADER, true);
- curl_setopt($curl, CURLOPT_NOBODY, true);
- } else {
- curl_setopt($curl, CURLOPT_HEADER, true);
- curl_setopt($curl, CURLOPT_HTTPGET, true);
- }
- $response = curl_exec($curl);
-
- if($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) {
- curl_setopt($curl, CURLOPT_HTTPGET, true);
- $response = curl_exec($curl);
- $response = substr($response, 0, strpos($response, "\r\n\r\n"));
- }
-
- if($method == 'HEAD' || $method == 'GET') {
- $header_response = $response;
-
- # If it's a GET request, we want to only parse the header part.
- if($method == 'GET') {
- $header_response = substr($response, 0, strpos($response, "\r\n\r\n"));
- }
-
- $headers = array();
- foreach(explode("\n", $header_response) as $header) {
- $pos = strpos($header,':');
- if ($pos !== false) {
- $name = strtolower(trim(substr($header, 0, $pos)));
- $headers[$name] = trim(substr($header, $pos+1));
- }
- }
-
- if($update_claimed_id) {
- # Update the claimed_id value in case of redirections.
- $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
- # Ignore the fragment (some cURL versions don't handle it well).
- if (strtok($effective_url, '#') != strtok($url, '#')) {
- $this->identity = $this->claimed_id = $effective_url;
- }
- }
-
- if($method == 'HEAD') {
- return $headers;
- } else {
- $this->headers = $headers;
- }
- }
-
- if (curl_errno($curl)) {
- throw new ErrorException(curl_error($curl), curl_errno($curl));
- }
-
- return $response;
- }
-
- protected function parse_header_array($array, $update_claimed_id)
- {
- $headers = array();
- foreach($array as $header) {
- $pos = strpos($header,':');
- if ($pos !== false) {
- $name = strtolower(trim(substr($header, 0, $pos)));
- $headers[$name] = trim(substr($header, $pos+1));
-
- # Following possible redirections. The point is just to have
- # claimed_id change with them, because the redirections
- # are followed automatically.
- # We ignore redirections with relative paths.
- # If any known provider uses them, file a bug report.
- if($name == 'location' && $update_claimed_id) {
- if(strpos($headers[$name], 'http') === 0) {
- $this->identity = $this->claimed_id = $headers[$name];
- } elseif($headers[$name][0] == '/') {
- $parsed_url = parse_url($this->claimed_id);
- $this->identity =
- $this->claimed_id = $parsed_url['scheme'] . '://'
- . $parsed_url['host']
- . $headers[$name];
- }
- }
- }
- }
- return $headers;
- }
-
- protected function request_streams($url, $method='GET', $params=array(), $update_claimed_id)
- {
- if(!$this->hostExists($url)) {
- throw new ErrorException("Could not connect to $url.", 404);
- }
-
- if (empty($this->cnmatch)) {
- $this->cnmatch = parse_url($url, PHP_URL_HOST);
- }
-
- $params = http_build_query($params, '', '&');
- switch($method) {
- case 'GET':
- $opts = array(
- 'http' => array(
- 'method' => 'GET',
- 'header' => 'Accept: application/xrds+xml, */*',
- 'user_agent' => $this->user_agent,
- 'ignore_errors' => true,
- ),
- 'ssl' => array(
- 'CN_match' => $this->cnmatch
- )
- );
- $url = $url . ($params ? '?' . $params : '');
- if (!empty($this->proxy)) {
- $opts['http']['proxy'] = $this->proxy_url();
- }
- break;
- case 'POST':
- $opts = array(
- 'http' => array(
- 'method' => 'POST',
- 'header' => 'Content-type: application/x-www-form-urlencoded',
- 'user_agent' => $this->user_agent,
- 'content' => $params,
- 'ignore_errors' => true,
- ),
- 'ssl' => array(
- 'CN_match' => $this->cnmatch
- )
- );
- if (!empty($this->proxy)) {
- $opts['http']['proxy'] = $this->proxy_url();
- }
- break;
- case 'HEAD':
- // We want to send a HEAD request, but since get_headers() doesn't
- // accept $context parameter, we have to change the defaults.
- $default = stream_context_get_options(stream_context_get_default());
-
- // PHP does not reset all options. Instead, it just sets the options
- // available in the passed array, therefore set the defaults manually.
- $default += array(
- 'http' => array(),
- 'ssl' => array()
- );
- $default['http'] += array(
- 'method' => 'GET',
- 'header' => '',
- 'user_agent' => '',
- 'ignore_errors' => false
- );
- $default['ssl'] += array(
- 'CN_match' => ''
- );
-
- $opts = array(
- 'http' => array(
- 'method' => 'HEAD',
- 'header' => 'Accept: application/xrds+xml, */*',
- 'user_agent' => $this->user_agent,
- 'ignore_errors' => true,
- ),
- 'ssl' => array(
- 'CN_match' => $this->cnmatch
- )
- );
-
- // Enable validation of the SSL certificates.
- if ($this->verify_peer) {
- $default['ssl'] += array(
- 'verify_peer' => false,
- 'capath' => '',
- 'cafile' => ''
- );
- $opts['ssl'] += array(
- 'verify_peer' => true,
- 'capath' => $this->capath,
- 'cafile' => $this->cainfo
- );
- }
-
- // Change the stream context options.
- stream_context_get_default($opts);
-
- $headers = get_headers($url . ($params ? '?' . $params : ''));
-
- // Restore the stream context options.
- stream_context_get_default($default);
-
- if (!empty($headers)) {
- if (intval(substr($headers[0], strlen('HTTP/1.1 '))) == 405) {
- // The server doesn't support HEAD - emulate it with a GET.
- $args = func_get_args();
- $args[1] = 'GET';
- call_user_func_array(array($this, 'request_streams'), $args);
- $headers = $this->headers;
- } else {
- $headers = $this->parse_header_array($headers, $update_claimed_id);
- }
- } else {
- $headers = array();
- }
-
- return $headers;
- }
-
- if ($this->verify_peer) {
- $opts['ssl'] += array(
- 'verify_peer' => true,
- 'capath' => $this->capath,
- 'cafile' => $this->cainfo
- );
- }
-
- $context = stream_context_create ($opts);
- $data = file_get_contents($url, false, $context);
- # This is a hack for providers who don't support HEAD requests.
- # It just creates the headers array for the last request in $this->headers.
- if(isset($http_response_header)) {
- $this->headers = $this->parse_header_array($http_response_header, $update_claimed_id);
- }
-
- return $data;
- }
-
- protected function request($url, $method='GET', $params=array(), $update_claimed_id=false)
- {
- $use_curl = false;
-
- if (function_exists('curl_init')) {
- if (!$use_curl) {
- # When allow_url_fopen is disabled, PHP streams will not work.
- $use_curl = !ini_get('allow_url_fopen');
- }
-
- if (!$use_curl) {
- # When there is no HTTPS wrapper, PHP streams cannott be used.
- $use_curl = !in_array('https', stream_get_wrappers());
- }
-
- if (!$use_curl) {
- # With open_basedir or safe_mode set, cURL can't follow redirects.
- $use_curl = !(ini_get('safe_mode') || ini_get('open_basedir'));
- }
- }
-
- return
- $use_curl
- ? $this->request_curl($url, $method, $params, $update_claimed_id)
- : $this->request_streams($url, $method, $params, $update_claimed_id);
- }
-
- protected function proxy_url()
- {
- $result = '';
-
- if (!empty($this->proxy)) {
- $result = $this->proxy['host'];
-
- if (!empty($this->proxy['port'])) {
- $result = $result . ':' . $this->proxy['port'];
- }
-
- if (!empty($this->proxy['user'])) {
- $result = $this->proxy['user'] . ':' . $this->proxy['pass'] . '@' . $result;
- }
-
- $result = 'http://' . $result;
- }
-
- return $result;
- }
-
- protected function build_url($url, $parts)
- {
- if (isset($url['query'], $parts['query'])) {
- $parts['query'] = $url['query'] . '&' . $parts['query'];
- }
-
- $url = $parts + $url;
- $url = $url['scheme'] . '://'
- . (empty($url['username'])?''
- :(empty($url['password'])? "{$url['username']}@"
- :"{$url['username']}:{$url['password']}@"))
- . $url['host']
- . (empty($url['port'])?'':":{$url['port']}")
- . (empty($url['path'])?'':$url['path'])
- . (empty($url['query'])?'':"?{$url['query']}")
- . (empty($url['fragment'])?'':"#{$url['fragment']}");
- return $url;
- }
-
- /**
- * Helper function used to scan for <meta>/<link> tags and extract information
- * from them
- */
- protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
- {
- preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
- preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2);
-
- $result = array_merge($matches1[1], $matches2[1]);
- return empty($result)?false:$result[0];
- }
-
- /**
- * Performs Yadis and HTML discovery. Normally not used.
- * @param $url Identity URL.
- * @return String OP Endpoint (i.e. OpenID provider address).
- * @throws ErrorException
- */
- function discover($url)
- {
- if (!$url) throw new ErrorException('No identity supplied.');
- # Use xri.net proxy to resolve i-name identities
- if (!preg_match('#^https?:#', $url)) {
- $url = "https://xri.net/$url";
- }
-
- # We save the original url in case of Yadis discovery failure.
- # It can happen when we'll be lead to an XRDS document
- # which does not have any OpenID2 services.
- $originalUrl = $url;
-
- # A flag to disable yadis discovery in case of failure in headers.
- $yadis = true;
-
- # Allows optional regex replacement of the URL, e.g. to use Google Apps
- # as an OpenID provider without setting up XRDS on the domain hosting.
- if (!is_null($this->xrds_override_pattern) && !is_null($this->xrds_override_replacement)) {
- $url = preg_replace($this->xrds_override_pattern, $this->xrds_override_replacement, $url);
- }
-
- # We'll jump a maximum of 5 times, to avoid endless redirections.
- for ($i = 0; $i < 5; $i ++) {
- if ($yadis) {
- $headers = $this->request($url, 'HEAD', array(), true);
-
- $next = false;
- if (isset($headers['x-xrds-location'])) {
- $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location'])));
- $next = true;
- }
-
- if (isset($headers['content-type']) && $this->is_allowed_type($headers['content-type'])) {
- # Found an XRDS document, now let's find the server, and optionally delegate.
- $content = $this->request($url, 'GET');
-
- preg_match_all('#<Service.*?>(.*?)</Service>#s', $content, $m);
- foreach($m[1] as $content) {
- $content = ' ' . $content; # The space is added, so that strpos doesn't return 0.
-
- # OpenID 2
- $ns = preg_quote('http://specs.openid.net/auth/2.0/', '#');
- if(preg_match('#<Type>\s*'.$ns.'(server|signon)\s*</Type>#s', $content, $type)) {
- if ($type[1] == 'server') $this->identifier_select = true;
-
- preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
- preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
- if (empty($server)) {
- return false;
- }
- # Does the server advertise support for either AX or SREG?
- $this->ax = (bool) strpos($content, '<Type>http://openid.net/srv/ax/1.0</Type>');
- $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
- || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
-
- $server = $server[1];
- if (isset($delegate[2])) $this->identity = trim($delegate[2]);
- $this->version = 2;
-
- $this->server = $server;
- return $server;
- }
-
- # OpenID 1.1
- $ns = preg_quote('http://openid.net/signon/1.1', '#');
- if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) {
-
- preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
- preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
- if (empty($server)) {
- return false;
- }
- # AX can be used only with OpenID 2.0, so checking only SREG
- $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
- || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
-
- $server = $server[1];
- if (isset($delegate[1])) $this->identity = $delegate[1];
- $this->version = 1;
-
- $this->server = $server;
- return $server;
- }
- }
-
- $next = true;
- $yadis = false;
- $url = $originalUrl;
- $content = null;
- break;
- }
- if ($next) continue;
-
- # There are no relevant information in headers, so we search the body.
- $content = $this->request($url, 'GET', array(), true);
-
- if (isset($this->headers['x-xrds-location'])) {
- $url = $this->build_url(parse_url($url), parse_url(trim($this->headers['x-xrds-location'])));
- continue;
- }
-
- $location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content');
- if ($location) {
- $url = $this->build_url(parse_url($url), parse_url($location));
- continue;
- }
- }
-
- if (!$content) $content = $this->request($url, 'GET');
-
- # At this point, the YADIS Discovery has failed, so we'll switch
- # to openid2 HTML discovery, then fallback to openid 1.1 discovery.
- $server = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href');
- $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href');
- $this->version = 2;
-
- if (!$server) {
- # The same with openid 1.1
- $server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href');
- $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href');
- $this->version = 1;
- }
-
- if ($server) {
- # We found an OpenID2 OP Endpoint
- if ($delegate) {
- # We have also found an OP-Local ID.
- $this->identity = $delegate;
- }
- $this->server = $server;
- return $server;
- }
-
- throw new ErrorException("No OpenID Server found at $url", 404);
- }
- throw new ErrorException('Endless redirection!', 500);
- }
-
- protected function is_allowed_type($content_type) {
- # Apparently, some providers return XRDS documents as text/html.
- # While it is against the spec, allowing this here shouldn't break
- # compatibility with anything.
- $allowed_types = array('application/xrds+xml', 'text/html', 'text/xml');
-
- foreach ($allowed_types as $type) {
- if (strpos($content_type, $type) !== false) {
- return true;
- }
- }
-
- return false;
- }
-
- protected function sregParams()
- {
- $params = array();
- # We always use SREG 1.1, even if the server is advertising only support for 1.0.
- # That's because it's fully backwards compatibile with 1.0, and some providers
- # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com
- $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1';
- if ($this->required) {
- $params['openid.sreg.required'] = array();
- foreach ($this->required as $required) {
- if (!isset(self::$ax_to_sreg[$required])) continue;
- $params['openid.sreg.required'][] = self::$ax_to_sreg[$required];
- }
- $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']);
- }
-
- if ($this->optional) {
- $params['openid.sreg.optional'] = array();
- foreach ($this->optional as $optional) {
- if (!isset(self::$ax_to_sreg[$optional])) continue;
- $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional];
- }
- $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']);
- }
- return $params;
- }
-
- protected function axParams()
- {
- $params = array();
- if ($this->required || $this->optional) {
- $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
- $params['openid.ax.mode'] = 'fetch_request';
- $this->aliases = array();
- $counts = array();
- $required = array();
- $optional = array();
- foreach (array('required','optional') as $type) {
- foreach ($this->$type as $alias => $field) {
- if (is_int($alias)) $alias = strtr($field, '/', '_');
- $this->aliases[$alias] = 'http://axschema.org/' . $field;
- if (empty($counts[$alias])) $counts[$alias] = 0;
- $counts[$alias] += 1;
- ${$type}[] = $alias;
- }
- }
- foreach ($this->aliases as $alias => $ns) {
- $params['openid.ax.type.' . $alias] = $ns;
- }
- foreach ($counts as $alias => $count) {
- if ($count == 1) continue;
- $params['openid.ax.count.' . $alias] = $count;
- }
-
- # Don't send empty ax.requied and ax.if_available.
- # Google and possibly other providers refuse to support ax when one of these is empty.
- if($required) {
- $params['openid.ax.required'] = implode(',', $required);
- }
- if($optional) {
- $params['openid.ax.if_available'] = implode(',', $optional);
- }
- }
- return $params;
- }
-
- protected function authUrl_v1($immediate)
- {
- $returnUrl = $this->returnUrl;
- # If we have an openid.delegate that is different from our claimed id,
- # we need to somehow preserve the claimed id between requests.
- # The simplest way is to just send it along with the return_to url.
- if($this->identity != $this->claimed_id) {
- $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id;
- }
-
- $params = array(
- 'openid.return_to' => $returnUrl,
- 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup',
- 'openid.identity' => $this->identity,
- 'openid.trust_root' => $this->trustRoot,
- ) + $this->sregParams();
-
- return $this->build_url(parse_url($this->server)
- , array('query' => http_build_query($params, '', '&')));
- }
-
- protected function authUrl_v2($immediate)
- {
- $params = array(
- 'openid.ns' => 'http://specs.openid.net/auth/2.0',
- 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup',
- 'openid.return_to' => $this->returnUrl,
- 'openid.realm' => $this->trustRoot,
- );
-
- if ($this->ax) {
- $params += $this->axParams();
- }
-
- if ($this->sreg) {
- $params += $this->sregParams();
- }
-
- if (!$this->ax && !$this->sreg) {
- # If OP doesn't advertise either SREG, nor AX, let's send them both
- # in worst case we don't get anything in return.
- $params += $this->axParams() + $this->sregParams();
- }
-
- if (!empty($this->oauth) && is_array($this->oauth)) {
- $params['openid.ns.oauth'] = 'http://specs.openid.net/extensions/oauth/1.0';
- $params['openid.oauth.consumer'] = str_replace(array('http://', 'https://'), '', $this->trustRoot);
- $params['openid.oauth.scope'] = implode(' ', $this->oauth);
- }
-
- if ($this->identifier_select) {
- $params['openid.identity'] = $params['openid.claimed_id']
- = 'http://specs.openid.net/auth/2.0/identifier_select';
- } else {
- $params['openid.identity'] = $this->identity;
- $params['openid.claimed_id'] = $this->claimed_id;
- }
-
- return $this->build_url(parse_url($this->server)
- , array('query' => http_build_query($params, '', '&')));
- }
-
- /**
- * Returns authentication url. Usually, you want to redirect your user to it.
- * @return String The authentication url.
- * @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1.
- * @throws ErrorException
- */
- function authUrl($immediate = false)
- {
- if ($this->setup_url && !$immediate) return $this->setup_url;
- if (!$this->server) $this->discover($this->identity);
-
- if ($this->version == 2) {
- return $this->authUrl_v2($immediate);
- }
- return $this->authUrl_v1($immediate);
- }
-
- /**
- * Performs OpenID verification with the OP.
- * @return Bool Whether the verification was successful.
- * @throws ErrorException
- */
- function validate()
- {
- # If the request was using immediate mode, a failure may be reported
- # by presenting user_setup_url (for 1.1) or reporting
- # mode 'setup_needed' (for 2.0). Also catching all modes other than
- # id_res, in order to avoid throwing errors.
- if(isset($this->data['openid_user_setup_url'])) {
- $this->setup_url = $this->data['openid_user_setup_url'];
- return false;
- }
- if($this->mode != 'id_res') {
- return false;
- }
-
- $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity'];
- $params = array(
- 'openid.assoc_handle' => $this->data['openid_assoc_handle'],
- 'openid.signed' => $this->data['openid_signed'],
- 'openid.sig' => $this->data['openid_sig'],
- );
-
- if (isset($this->data['openid_ns'])) {
- # We're dealing with an OpenID 2.0 server, so let's set an ns
- # Even though we should know location of the endpoint,
- # we still need to verify it by discovery, so $server is not set here
- $params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
- } elseif (isset($this->data['openid_claimed_id'])
- && $this->data['openid_claimed_id'] != $this->data['openid_identity']
- ) {
- # If it's an OpenID 1 provider, and we've got claimed_id,
- # we have to append it to the returnUrl, like authUrl_v1 does.
- $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?')
- . 'openid.claimed_id=' . $this->claimed_id;
- }
-
- if ($this->data['openid_return_to'] != $this->returnUrl) {
- # The return_to url must match the url of current request.
- # I'm assuing that noone will set the returnUrl to something that doesn't make sense.
- return false;
- }
-
- $server = $this->discover($this->claimed_id);
-
- foreach (explode(',', $this->data['openid_signed']) as $item) {
- # Checking whether magic_quotes_gpc is turned on, because
- # the function may fail if it is. For example, when fetching
- # AX namePerson, it might containg an apostrophe, which will be escaped.
- # In such case, validation would fail, since we'd send different data than OP
- # wants to verify. stripslashes() should solve that problem, but we can't
- # use it when magic_quotes is off.
- $value = $this->data['openid_' . str_replace('.','_',$item)];
- $params['openid.' . $item] = function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() ? stripslashes($value) : $value;
-
- }
-
- $params['openid.mode'] = 'check_authentication';
-
- $response = $this->request($server, 'POST', $params);
-
- return preg_match('/is_valid\s*:\s*true/i', $response);
- }
-
- protected function getAxAttributes()
- {
- $result = array();
-
- if ($alias = $this->getNamespaceAlias('http://openid.net/srv/ax/1.0', 'ax')) {
- $prefix = 'openid_' . $alias;
- $length = strlen('http://axschema.org/');
-
- foreach (explode(',', $this->data['openid_signed']) as $key) {
- $keyMatch = $alias . '.type.';
-
- if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) {
- continue;
- }
-
- $key = substr($key, strlen($keyMatch));
- $idv = $prefix . '_value_' . $key;
- $idc = $prefix . '_count_' . $key;
- $key = substr($this->getItem($prefix . '_type_' . $key), $length);
-
- if (!empty($key)) {
- if (($count = intval($this->getItem($idc))) > 0) {
- $value = array();
-
- for ($i = 1; $i <= $count; $i++) {
- $value[] = $this->getItem($idv . '_' . $i);
- }
-
- $value = ($count == 1) ? reset($value) : $value;
- } else {
- $value = $this->getItem($idv);
- }
-
- if (!is_null($value)) {
- $result[$key] = $value;
- }
- }
- }
- } else {
- // No alias for the AX schema has been found,
- // so there is no AX data in the OP's response.
- }
-
- return $result;
- }
-
- protected function getSregAttributes()
- {
- $attributes = array();
- $sreg_to_ax = array_flip(self::$ax_to_sreg);
- foreach (explode(',', $this->data['openid_signed']) as $key) {
- $keyMatch = 'sreg.';
- if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) {
- continue;
- }
- $key = substr($key, strlen($keyMatch));
- if (!isset($sreg_to_ax[$key])) {
- # The field name isn't part of the SREG spec, so we ignore it.
- continue;
- }
- $attributes[$sreg_to_ax[$key]] = $this->data['openid_sreg_' . $key];
- }
- return $attributes;
- }
-
- /**
- * Gets AX/SREG attributes provided by OP. should be used only after successful validaton.
- * Note that it does not guarantee that any of the required/optional parameters will be present,
- * or that there will be no other attributes besides those specified.
- * In other words. OP may provide whatever information it wants to.
- * * SREG names will be mapped to AX names.
- * * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email'
- * @see http://www.axschema.org/types/
- */
- function getAttributes()
- {
- if (isset($this->data['openid_ns'])
- && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0'
- ) { # OpenID 2.0
- # We search for both AX and SREG attributes, with AX taking precedence.
- return $this->getAxAttributes() + $this->getSregAttributes();
- }
- return $this->getSregAttributes();
- }
-
- /**
- * Gets an OAuth request token if the OpenID+OAuth hybrid protocol has been used.
- *
- * In order to use the OpenID+OAuth hybrid protocol, you need to add at least one
- * scope to the $openid->oauth array before you get the call to getAuthUrl(), e.g.:
- * $openid->oauth[] = 'https://www.googleapis.com/auth/plus.me';
- *
- * Furthermore the registered consumer name must fit the OpenID realm.
- * To register an OpenID consumer at Google use: https://www.google.com/accounts/ManageDomains
- *
- * @return string|bool OAuth request token on success, FALSE if no token was provided.
- */
- function getOAuthRequestToken()
- {
- $alias = $this->getNamespaceAlias('http://specs.openid.net/extensions/oauth/1.0');
-
- return !empty($alias) ? $this->data['openid_' . $alias . '_request_token'] : false;
- }
-
- /**
- * Gets the alias for the specified namespace, if it's present.
- *
- * @param string $namespace The namespace for which an alias is needed.
- * @param string $hint Common alias of this namespace, used for optimization.
- * @return string|null The namespace alias if found, otherwise - NULL.
- */
- private function getNamespaceAlias($namespace, $hint = null)
- {
- $result = null;
-
- if (empty($hint) || $this->getItem('openid_ns_' . $hint) != $namespace) {
- // The common alias is either undefined or points to
- // some other extension - search for another alias..
- $prefix = 'openid_ns_';
- $length = strlen($prefix);
-
- foreach ($this->data as $key => $val) {
- if (strncmp($key, $prefix, $length) === 0 && $val === $namespace) {
- $result = trim(substr($key, $length));
- break;
- }
- }
- } else {
- $result = $hint;
- }
-
- return $result;
- }
-
- /**
- * Gets an item from the $data array by the specified id.
- *
- * @param string $id The id of the desired item.
- * @return string|null The item if found, otherwise - NULL.
- */
- private function getItem($id)
- {
- return isset($this->data[$id]) ? $this->data[$id] : null;
- }
-}
+ public $returnUrl
+ , $required = []
+ , $optional = []
+ , $verify_peer = null
+ , $capath = null
+ , $cainfo = null
+ , $cnmatch = null
+ , $data
+ , $oauth = []
+ , $curl_time_out = 30
+ , $curl_connect_time_out = 30;
+ private $identity, $claimed_id;
+ protected $server, $version, $trustRoot, $aliases, $identifier_select = false
+ , $ax = false, $sreg = false, $setup_url = null, $headers = []
+ , $proxy = null, $user_agent = 'LightOpenID'
+ , $xrds_override_pattern = null, $xrds_override_replacement = null;
+ static protected $ax_to_sreg = [
+ 'namePerson/friendly' => 'nickname',
+ 'contact/email' => 'email',
+ 'namePerson' => 'fullname',
+ 'birthDate' => 'dob',
+ 'person/gender' => 'gender',
+ 'contact/postalCode/home' => 'postcode',
+ 'contact/country/home' => 'country',
+ 'pref/language' => 'language',
+ 'pref/timezone' => 'timezone',
+ ]; + + function __construct($host, $proxy = null)
+ {
+ $this->set_realm($host);
+ $this->set_proxy($proxy); + + $uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?');
+ $this->returnUrl = $this->trustRoot . $uri; + + $this->data = ($_SERVER['REQUEST_METHOD'] === 'POST') ? $_POST : $_GET; + + if(!function_exists('curl_init') && !in_array('https', stream_get_wrappers())) {
+ throw new ErrorException('You must have either https wrappers or curl enabled.'); + }
+ } + + function __isset($name)
+ {
+ return in_array($name, ['identity', 'trustRoot', 'realm', 'xrdsOverride', 'mode']);
+ } + + function __set($name, $value)
+ {
+ switch ($name) {
+ case 'identity':
+ if (strlen($value = trim((String) $value))) {
+ if (preg_match('#^xri:/*#i', $value, $m)) {
+ $value = substr($value, strlen($m[0]));
+ } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) {
+ $value = "http://$value";
+ }
+ if (preg_match('#^https?://[^/]+$#i', $value, $m)) {
+ $value .= '/';
+ }
+ }
+ $this->$name = $this->claimed_id = $value;
+ break;
+ case 'trustRoot':
+ case 'realm':
+ $this->trustRoot = trim($value);
+ break;
+ case 'xrdsOverride':
+ if (is_array($value)) {
+ list($pattern, $replacement) = $value;
+ $this->xrds_override_pattern = $pattern;
+ $this->xrds_override_replacement = $replacement;
+ } else {
+ trigger_error('Invalid value specified for "xrdsOverride".', E_USER_ERROR);
+ }
+ break;
+ }
+ } + + function __get($name)
+ {
+ switch ($name) {
+ case 'identity':
+ # We return claimed_id instead of identity,
+ # because the developer should see the claimed identifier,
+ # i.e. what he set as identity, not the op-local identifier (which is what we verify)
+ return $this->claimed_id;
+ case 'trustRoot':
+ case 'realm':
+ return $this->trustRoot;
+ case 'mode':
+ return empty($this->data['openid_mode']) ? null : $this->data['openid_mode'];
+ }
+ } + + function set_proxy($proxy)
+ {
+ if (!empty($proxy)) {
+ // When the proxy is a string - try to parse it.
+ if (!is_array($proxy)) {
+ $proxy = parse_url($proxy);
+ } + + // Check if $proxy is valid after the parsing.
+ if ($proxy && !empty($proxy['host'])) {
+ // Make sure that a valid port number is specified.
+ if (array_key_exists('port', $proxy)) {
+ if (!is_int($proxy['port'])) {
+ $proxy['port'] = is_numeric($proxy['port']) ? (int) ($proxy['port']) : 0;
+ } + + if ($proxy['port'] <= 0) {
+ throw new ErrorException('The specified proxy port number is invalid.'); + }
+ } + + $this->proxy = $proxy;
+ }
+ }
+ } + + /**
+ * Checks if the server specified in the url exists.
+ *
+ * @param $url url to check
+ * @return true, if the server exists; false otherwise
+ */
+ function hostExists($url)
+ {
+ if (strpos($url, '/') === false) {
+ $server = $url;
+ } else {
+ $server = @parse_url($url, PHP_URL_HOST);
+ } + + if (!$server) {
+ return false;
+ } + + return !!gethostbynamel($server);
+ } + + protected function set_realm($uri)
+ {
+ $realm = ''; + + # Set a protocol, if not specified.
+ $realm .= (($offset = strpos($uri, '://')) === false) ? $this->get_realm_protocol() : ''; + + # Set the offset properly.
+ $offset = (($offset !== false) ? $offset + 3 : 0); + + # Get only the root, without the path.
+ $realm .= (($end = strpos($uri, '/', $offset)) === false) ? $uri : substr($uri, 0, $end); + + $this->trustRoot = $realm;
+ } + + protected function get_realm_protocol()
+ {
+ if (!empty($_SERVER['HTTPS'])) {
+ $use_secure_protocol = ($_SERVER['HTTPS'] != 'off');
+ } else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
+ $use_secure_protocol = ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
+ } else {
+ $use_secure_protocol = false;
+ } + + return $use_secure_protocol ? 'https://' : 'http://';
+ } + + protected function request_curl($url, $method='GET', $params=[], $update_claimed_id)
+ {
+ $params = http_build_query($params, '', '&');
+ $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : ''));
+ curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($curl, CURLOPT_HEADER, false);
+ curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_time_out);
+ curl_setopt($curl, CURLOPT_CONNECTTIMEOUT , $this->curl_connect_time_out); + + if ($method == 'POST') {
+ curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/x-www-form-urlencoded']);
+ } else {
+ curl_setopt($curl, CURLOPT_HTTPHEADER, ['Accept: application/xrds+xml, */*']);
+ } + + if (!empty($this->proxy)) {
+ curl_setopt($curl, CURLOPT_PROXY, $this->proxy['host']); + + if (!empty($this->proxy['port'])) {
+ curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy['port']);
+ } + + if (!empty($this->proxy['user'])) {
+ curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']);
+ }
+ } + + if($this->verify_peer !== null) {
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer);
+ if($this->capath) {
+ curl_setopt($curl, CURLOPT_CAPATH, $this->capath);
+ } + + if($this->cainfo) {
+ curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo);
+ }
+ } + + if ($method == 'POST') {
+ curl_setopt($curl, CURLOPT_POST, true);
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
+ } elseif ($method == 'HEAD') {
+ curl_setopt($curl, CURLOPT_HEADER, true);
+ curl_setopt($curl, CURLOPT_NOBODY, true);
+ } else {
+ curl_setopt($curl, CURLOPT_HEADER, true);
+ curl_setopt($curl, CURLOPT_HTTPGET, true);
+ }
+ $response = curl_exec($curl); + + if($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) {
+ curl_setopt($curl, CURLOPT_HTTPGET, true);
+ $response = curl_exec($curl);
+ $response = substr($response, 0, strpos($response, "\r\n\r\n"));
+ } + + if($method == 'HEAD' || $method == 'GET') {
+ $header_response = $response; + + # If it's a GET request, we want to only parse the header part.
+ if($method == 'GET') {
+ $header_response = substr($response, 0, strpos($response, "\r\n\r\n"));
+ } + + $headers = [];
+ foreach(explode("\n", $header_response) as $header) {
+ $pos = strpos($header,':');
+ if ($pos !== false) {
+ $name = strtolower(trim(substr($header, 0, $pos)));
+ $headers[$name] = trim(substr($header, $pos+1));
+ }
+ } + + if($update_claimed_id) {
+ # Update the claimed_id value in case of redirections.
+ $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
+ # Ignore the fragment (some cURL versions don't handle it well).
+ if (strtok($effective_url, '#') != strtok($url, '#')) {
+ $this->identity = $this->claimed_id = $effective_url;
+ }
+ } + + if($method == 'HEAD') {
+ return $headers;
+ }
+ $this->headers = $headers; + + } + + if (curl_errno($curl)) {
+ throw new ErrorException(curl_error($curl), curl_errno($curl)); + } + + return $response;
+ } + + protected function parse_header_array($array, $update_claimed_id)
+ {
+ $headers = [];
+ foreach($array as $header) {
+ $pos = strpos($header,':');
+ if ($pos !== false) {
+ $name = strtolower(trim(substr($header, 0, $pos)));
+ $headers[$name] = trim(substr($header, $pos+1)); + + # Following possible redirections. The point is just to have
+ # claimed_id change with them, because the redirections
+ # are followed automatically.
+ # We ignore redirections with relative paths.
+ # If any known provider uses them, file a bug report.
+ if($name == 'location' && $update_claimed_id) {
+ if(strpos($headers[$name], 'http') === 0) {
+ $this->identity = $this->claimed_id = $headers[$name];
+ } elseif($headers[$name][0] == '/') {
+ $parsed_url = parse_url($this->claimed_id);
+ $this->identity =
+ $this->claimed_id = $parsed_url['scheme'] . '://'
+ . $parsed_url['host']
+ . $headers[$name];
+ }
+ }
+ }
+ }
+ return $headers;
+ } + + protected function request_streams($url, $method='GET', $params=[], $update_claimed_id)
+ {
+ if(!$this->hostExists($url)) {
+ throw new ErrorException("Could not connect to $url.", 404); + } + + if (empty($this->cnmatch)) {
+ $this->cnmatch = parse_url($url, PHP_URL_HOST);
+ } + + $params = http_build_query($params, '', '&');
+ switch($method) {
+ case 'GET':
+ $opts = [
+ 'http' => [
+ 'method' => 'GET',
+ 'header' => 'Accept: application/xrds+xml, */*',
+ 'user_agent' => $this->user_agent,
+ 'ignore_errors' => true,
+ ],
+ 'ssl' => [
+ 'CN_match' => $this->cnmatch,
+ ],
+ ];
+ $url = $url . ($params ? '?' . $params : '');
+ if (!empty($this->proxy)) {
+ $opts['http']['proxy'] = $this->proxy_url();
+ }
+ break;
+ case 'POST':
+ $opts = [
+ 'http' => [
+ 'method' => 'POST',
+ 'header' => 'Content-type: application/x-www-form-urlencoded',
+ 'user_agent' => $this->user_agent,
+ 'content' => $params,
+ 'ignore_errors' => true,
+ ],
+ 'ssl' => [
+ 'CN_match' => $this->cnmatch,
+ ],
+ ];
+ if (!empty($this->proxy)) {
+ $opts['http']['proxy'] = $this->proxy_url();
+ }
+ break;
+ case 'HEAD':
+ // We want to send a HEAD request, but since get_headers() doesn't
+ // accept $context parameter, we have to change the defaults.
+ $default = stream_context_get_options(stream_context_get_default()); + + // PHP does not reset all options. Instead, it just sets the options
+ // available in the passed array, therefore set the defaults manually.
+ $default += [
+ 'http' => [],
+ 'ssl' => [],
+ ];
+ $default['http'] += [
+ 'method' => 'GET',
+ 'header' => '',
+ 'user_agent' => '',
+ 'ignore_errors' => false,
+ ];
+ $default['ssl'] += [
+ 'CN_match' => '',
+ ]; + + $opts = [
+ 'http' => [
+ 'method' => 'HEAD',
+ 'header' => 'Accept: application/xrds+xml, */*',
+ 'user_agent' => $this->user_agent,
+ 'ignore_errors' => true,
+ ],
+ 'ssl' => [
+ 'CN_match' => $this->cnmatch,
+ ],
+ ]; + + // Enable validation of the SSL certificates.
+ if ($this->verify_peer) {
+ $default['ssl'] += [
+ 'verify_peer' => false,
+ 'capath' => '',
+ 'cafile' => '',
+ ];
+ $opts['ssl'] += [
+ 'verify_peer' => true,
+ 'capath' => $this->capath,
+ 'cafile' => $this->cainfo,
+ ];
+ } + + // Change the stream context options.
+ stream_context_get_default($opts); + + $headers = get_headers($url . ($params ? '?' . $params : '')); + + // Restore the stream context options.
+ stream_context_get_default($default); + + if (!empty($headers)) {
+ if ((int) (substr($headers[0], strlen('HTTP/1.1 '))) == 405) {
+ // The server doesn't support HEAD - emulate it with a GET.
+ $args = func_get_args();
+ $args[1] = 'GET';
+ call_user_func_array([$this, 'request_streams'], $args);
+ $headers = $this->headers;
+ } else {
+ $headers = $this->parse_header_array($headers, $update_claimed_id);
+ }
+ } else {
+ $headers = [];
+ } + + return $headers;
+ } + + if ($this->verify_peer) {
+ $opts['ssl'] += [
+ 'verify_peer' => true,
+ 'capath' => $this->capath,
+ 'cafile' => $this->cainfo,
+ ];
+ } + + $context = stream_context_create ($opts);
+ $data = file_get_contents($url, false, $context);
+ # This is a hack for providers who don't support HEAD requests.
+ # It just creates the headers array for the last request in $this->headers.
+ if(isset($http_response_header)) {
+ $this->headers = $this->parse_header_array($http_response_header, $update_claimed_id);
+ } + + return $data;
+ } + + protected function request($url, $method='GET', $params=[], $update_claimed_id=false)
+ {
+ $use_curl = false; + + if (function_exists('curl_init')) {
+ if (!$use_curl) {
+ # When allow_url_fopen is disabled, PHP streams will not work.
+ $use_curl = !ini_get('allow_url_fopen');
+ } + + if (!$use_curl) {
+ # When there is no HTTPS wrapper, PHP streams cannott be used.
+ $use_curl = !in_array('https', stream_get_wrappers());
+ } + + if (!$use_curl) {
+ # With open_basedir or safe_mode set, cURL can't follow redirects.
+ $use_curl = !(ini_get('safe_mode') || ini_get('open_basedir'));
+ }
+ } + + return
+ $use_curl
+ ? $this->request_curl($url, $method, $params, $update_claimed_id)
+ : $this->request_streams($url, $method, $params, $update_claimed_id);
+ } + + protected function proxy_url()
+ {
+ $result = ''; + + if (!empty($this->proxy)) {
+ $result = $this->proxy['host']; + + if (!empty($this->proxy['port'])) {
+ $result = $result . ':' . $this->proxy['port'];
+ } + + if (!empty($this->proxy['user'])) {
+ $result = $this->proxy['user'] . ':' . $this->proxy['pass'] . '@' . $result;
+ } + + $result = 'http://' . $result;
+ } + + return $result;
+ } + + protected function build_url($url, $parts)
+ {
+ if (isset($url['query'], $parts['query'])) {
+ $parts['query'] = $url['query'] . '&' . $parts['query'];
+ } + + $url = $parts + $url;
+ $url = $url['scheme'] . '://'
+ . (empty($url['username'])?''
+ :(empty($url['password'])? "{$url['username']}@"
+ :"{$url['username']}:{$url['password']}@"))
+ . $url['host']
+ . (empty($url['port'])?'':":{$url['port']}")
+ . (empty($url['path'])?'':$url['path'])
+ . (empty($url['query'])?'':"?{$url['query']}")
+ . (empty($url['fragment'])?'':"#{$url['fragment']}");
+ return $url;
+ } + + /**
+ * Helper function used to scan for <meta>/<link> tags and extract information
+ * from them
+ */
+ protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
+ {
+ preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
+ preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2); + + $result = array_merge($matches1[1], $matches2[1]);
+ return empty($result)?false:$result[0];
+ } + + /**
+ * Performs Yadis and HTML discovery. Normally not used.
+ * @param $url Identity URL.
+ * @return String OP Endpoint (i.e. OpenID provider address).
+ * @throws ErrorException
+ */
+ function discover($url)
+ {
+ if (!$url) throw new ErrorException('No identity supplied.');
+ # Use xri.net proxy to resolve i-name identities
+ if (!preg_match('#^https?:#', $url)) {
+ $url = "https://xri.net/$url";
+ } + + # We save the original url in case of Yadis discovery failure.
+ # It can happen when we'll be lead to an XRDS document
+ # which does not have any OpenID2 services.
+ $originalUrl = $url; + + # A flag to disable yadis discovery in case of failure in headers.
+ $yadis = true; + + # Allows optional regex replacement of the URL, e.g. to use Google Apps
+ # as an OpenID provider without setting up XRDS on the domain hosting.
+ if (!is_null($this->xrds_override_pattern) && !is_null($this->xrds_override_replacement)) {
+ $url = preg_replace($this->xrds_override_pattern, $this->xrds_override_replacement, $url);
+ } + + # We'll jump a maximum of 5 times, to avoid endless redirections.
+ for ($i = 0; $i < 5; $i ++) {
+ if ($yadis) {
+ $headers = $this->request($url, 'HEAD', [], true); + + $next = false;
+ if (isset($headers['x-xrds-location'])) {
+ $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location'])));
+ $next = true;
+ } + + if (isset($headers['content-type']) && $this->is_allowed_type($headers['content-type'])) {
+ # Found an XRDS document, now let's find the server, and optionally delegate.
+ $content = $this->request($url, 'GET'); + + preg_match_all('#<Service.*?>(.*?)</Service>#s', $content, $m);
+ foreach($m[1] as $content) {
+ $content = ' ' . $content; # The space is added, so that strpos doesn't return 0. + + # OpenID 2
+ $ns = preg_quote('http://specs.openid.net/auth/2.0/', '#');
+ if(preg_match('#<Type>\s*'.$ns.'(server|signon)\s*</Type>#s', $content, $type)) {
+ if ($type[1] == 'server') $this->identifier_select = true; + + preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
+ preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
+ if (empty($server)) {
+ return false;
+ }
+ # Does the server advertise support for either AX or SREG?
+ $this->ax = (bool) strpos($content, '<Type>http://openid.net/srv/ax/1.0</Type>');
+ $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
+ || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>'); + + $server = $server[1];
+ if (isset($delegate[2])) $this->identity = trim($delegate[2]);
+ $this->version = 2; + + $this->server = $server;
+ return $server;
+ } + + # OpenID 1.1
+ $ns = preg_quote('http://openid.net/signon/1.1', '#');
+ if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) { + + preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
+ preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
+ if (empty($server)) {
+ return false;
+ }
+ # AX can be used only with OpenID 2.0, so checking only SREG
+ $this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
+ || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>'); + + $server = $server[1];
+ if (isset($delegate[1])) $this->identity = $delegate[1];
+ $this->version = 1; + + $this->server = $server;
+ return $server;
+ }
+ } + + $next = true;
+ $yadis = false;
+ $url = $originalUrl;
+ $content = null;
+ break;
+ }
+ if ($next) continue; + + # There are no relevant information in headers, so we search the body.
+ $content = $this->request($url, 'GET', [], true); + + if (isset($this->headers['x-xrds-location'])) {
+ $url = $this->build_url(parse_url($url), parse_url(trim($this->headers['x-xrds-location'])));
+ continue;
+ } + + $location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content');
+ if ($location) {
+ $url = $this->build_url(parse_url($url), parse_url($location));
+ continue;
+ }
+ } + + if (!$content) $content = $this->request($url, 'GET'); + + # At this point, the YADIS Discovery has failed, so we'll switch
+ # to openid2 HTML discovery, then fallback to openid 1.1 discovery.
+ $server = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href');
+ $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href');
+ $this->version = 2; + + if (!$server) {
+ # The same with openid 1.1
+ $server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href');
+ $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href');
+ $this->version = 1;
+ } + + if ($server) {
+ # We found an OpenID2 OP Endpoint
+ if ($delegate) {
+ # We have also found an OP-Local ID.
+ $this->identity = $delegate;
+ }
+ $this->server = $server;
+ return $server;
+ } + + throw new ErrorException("No OpenID Server found at $url", 404); + }
+ throw new ErrorException('Endless redirection!', 500); + } + + protected function is_allowed_type($content_type) {
+ # Apparently, some providers return XRDS documents as text/html.
+ # While it is against the spec, allowing this here shouldn't break
+ # compatibility with anything.
+ $allowed_types = ['application/xrds+xml', 'text/html', 'text/xml']; + + foreach ($allowed_types as $type) {
+ if (strpos($content_type, $type) !== false) {
+ return true;
+ }
+ } + + return false;
+ } + + protected function sregParams()
+ {
+ $params = [];
+ # We always use SREG 1.1, even if the server is advertising only support for 1.0.
+ # That's because it's fully backwards compatibile with 1.0, and some providers
+ # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com
+ $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1';
+ if ($this->required) {
+ $params['openid.sreg.required'] = [];
+ foreach ($this->required as $required) {
+ if (!isset(self::$ax_to_sreg[$required])) continue;
+ $params['openid.sreg.required'][] = self::$ax_to_sreg[$required];
+ }
+ $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']);
+ } + + if ($this->optional) {
+ $params['openid.sreg.optional'] = [];
+ foreach ($this->optional as $optional) {
+ if (!isset(self::$ax_to_sreg[$optional])) continue;
+ $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional];
+ }
+ $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']);
+ }
+ return $params;
+ } + + protected function axParams()
+ {
+ $params = [];
+ if ($this->required || $this->optional) {
+ $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
+ $params['openid.ax.mode'] = 'fetch_request';
+ $this->aliases = [];
+ $counts = [];
+ $required = [];
+ $optional = [];
+ foreach (['required','optional'] as $type) {
+ foreach ($this->$type as $alias => $field) {
+ if (is_int($alias)) $alias = strtr($field, '/', '_');
+ $this->aliases[$alias] = 'http://axschema.org/' . $field;
+ if (empty($counts[$alias])) $counts[$alias] = 0;
+ $counts[$alias] += 1;
+ ${$type}[] = $alias;
+ }
+ }
+ foreach ($this->aliases as $alias => $ns) {
+ $params['openid.ax.type.' . $alias] = $ns;
+ }
+ foreach ($counts as $alias => $count) {
+ if ($count == 1) continue;
+ $params['openid.ax.count.' . $alias] = $count;
+ } + + # Don't send empty ax.requied and ax.if_available.
+ # Google and possibly other providers refuse to support ax when one of these is empty.
+ if($required) {
+ $params['openid.ax.required'] = implode(',', $required);
+ }
+ if($optional) {
+ $params['openid.ax.if_available'] = implode(',', $optional);
+ }
+ }
+ return $params;
+ } + + protected function authUrl_v1($immediate)
+ {
+ $returnUrl = $this->returnUrl;
+ # If we have an openid.delegate that is different from our claimed id,
+ # we need to somehow preserve the claimed id between requests.
+ # The simplest way is to just send it along with the return_to url.
+ if($this->identity != $this->claimed_id) {
+ $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id;
+ } + + $params = [
+ 'openid.return_to' => $returnUrl,
+ 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup',
+ 'openid.identity' => $this->identity,
+ 'openid.trust_root' => $this->trustRoot,
+ ] + $this->sregParams(); + + return $this->build_url(parse_url($this->server)
+ , ['query' => http_build_query($params, '', '&')], );
+ } + + protected function authUrl_v2($immediate)
+ {
+ $params = [
+ 'openid.ns' => 'http://specs.openid.net/auth/2.0',
+ 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup',
+ 'openid.return_to' => $this->returnUrl,
+ 'openid.realm' => $this->trustRoot,
+ ]; + + if ($this->ax) {
+ $params += $this->axParams();
+ } + + if ($this->sreg) {
+ $params += $this->sregParams();
+ } + + if (!$this->ax && !$this->sreg) {
+ # If OP doesn't advertise either SREG, nor AX, let's send them both
+ # in worst case we don't get anything in return.
+ $params += $this->axParams() + $this->sregParams();
+ } + + if (!empty($this->oauth) && is_array($this->oauth)) {
+ $params['openid.ns.oauth'] = 'http://specs.openid.net/extensions/oauth/1.0';
+ $params['openid.oauth.consumer'] = str_replace(['http://', 'https://'], '', $this->trustRoot);
+ $params['openid.oauth.scope'] = implode(' ', $this->oauth);
+ } + + if ($this->identifier_select) {
+ $params['openid.identity'] = $params['openid.claimed_id']
+ = 'http://specs.openid.net/auth/2.0/identifier_select';
+ } else {
+ $params['openid.identity'] = $this->identity;
+ $params['openid.claimed_id'] = $this->claimed_id;
+ } + + return $this->build_url(parse_url($this->server)
+ , ['query' => http_build_query($params, '', '&')], );
+ } + + /**
+ * Returns authentication url. Usually, you want to redirect your user to it.
+ * @return String The authentication url.
+ * @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1.
+ * @throws ErrorException
+ */
+ function authUrl($immediate = false)
+ {
+ if ($this->setup_url && !$immediate) return $this->setup_url;
+ if (!$this->server) $this->discover($this->identity); + + if ($this->version == 2) {
+ return $this->authUrl_v2($immediate);
+ }
+ return $this->authUrl_v1($immediate);
+ } + + /**
+ * Performs OpenID verification with the OP.
+ * @return Bool Whether the verification was successful.
+ * @throws ErrorException
+ */
+ function validate()
+ {
+ # If the request was using immediate mode, a failure may be reported
+ # by presenting user_setup_url (for 1.1) or reporting
+ # mode 'setup_needed' (for 2.0). Also catching all modes other than
+ # id_res, in order to avoid throwing errors.
+ if(isset($this->data['openid_user_setup_url'])) {
+ $this->setup_url = $this->data['openid_user_setup_url'];
+ return false;
+ }
+ if($this->mode != 'id_res') {
+ return false;
+ } + + $this->claimed_id = $this->data['openid_claimed_id']??$this->data['openid_identity'];
+ $params = [
+ 'openid.assoc_handle' => $this->data['openid_assoc_handle'],
+ 'openid.signed' => $this->data['openid_signed'],
+ 'openid.sig' => $this->data['openid_sig'],
+ ]; + + if (isset($this->data['openid_ns'])) {
+ # We're dealing with an OpenID 2.0 server, so let's set an ns
+ # Even though we should know location of the endpoint,
+ # we still need to verify it by discovery, so $server is not set here
+ $params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
+ } elseif (isset($this->data['openid_claimed_id'])
+ && $this->data['openid_claimed_id'] != $this->data['openid_identity']
+ ) {
+ # If it's an OpenID 1 provider, and we've got claimed_id,
+ # we have to append it to the returnUrl, like authUrl_v1 does.
+ $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?')
+ . 'openid.claimed_id=' . $this->claimed_id;
+ } + + if ($this->data['openid_return_to'] != $this->returnUrl) {
+ # The return_to url must match the url of current request.
+ # I'm assuing that noone will set the returnUrl to something that doesn't make sense.
+ return false;
+ } + + $server = $this->discover($this->claimed_id); + + foreach (explode(',', $this->data['openid_signed']) as $item) {
+ # Checking whether magic_quotes_gpc is turned on, because
+ # the function may fail if it is. For example, when fetching
+ # AX namePerson, it might containg an apostrophe, which will be escaped.
+ # In such case, validation would fail, since we'd send different data than OP
+ # wants to verify. stripslashes() should solve that problem, but we can't
+ # use it when magic_quotes is off.
+ $value = $this->data['openid_' . str_replace('.','_',$item)];
+ $params['openid.' . $item] = function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() ? stripslashes($value) : $value; + + } + + $params['openid.mode'] = 'check_authentication'; + + $response = $this->request($server, 'POST', $params); + + return preg_match('/is_valid\s*:\s*true/i', $response);
+ } + + protected function getAxAttributes()
+ {
+ $result = []; + + if ($alias = $this->getNamespaceAlias('http://openid.net/srv/ax/1.0', 'ax')) {
+ $prefix = 'openid_' . $alias;
+ $length = strlen('http://axschema.org/'); + + foreach (explode(',', $this->data['openid_signed']) as $key) {
+ $keyMatch = $alias . '.type.'; + + if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) {
+ continue;
+ } + + $key = substr($key, strlen($keyMatch));
+ $idv = $prefix . '_value_' . $key;
+ $idc = $prefix . '_count_' . $key;
+ $key = substr($this->getItem($prefix . '_type_' . $key), $length); + + if (!empty($key)) {
+ if (($count = (int) ($this->getItem($idc))) > 0) {
+ $value = []; + + for ($i = 1; $i <= $count; $i++) {
+ $value[] = $this->getItem($idv . '_' . $i);
+ } + + $value = ($count == 1) ? reset($value) : $value;
+ } else {
+ $value = $this->getItem($idv);
+ } + + if (!is_null($value)) {
+ $result[$key] = $value;
+ }
+ }
+ }
+ }
+ // No alias for the AX schema has been found,
+ // so there is no AX data in the OP's response. + + return $result;
+ } + + protected function getSregAttributes()
+ {
+ $attributes = [];
+ $sreg_to_ax = array_flip(self::$ax_to_sreg);
+ foreach (explode(',', $this->data['openid_signed']) as $key) {
+ $keyMatch = 'sreg.';
+ if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) {
+ continue;
+ }
+ $key = substr($key, strlen($keyMatch));
+ if (!isset($sreg_to_ax[$key])) {
+ # The field name isn't part of the SREG spec, so we ignore it.
+ continue;
+ }
+ $attributes[$sreg_to_ax[$key]] = $this->data['openid_sreg_' . $key];
+ }
+ return $attributes;
+ } + + /**
+ * Gets AX/SREG attributes provided by OP. should be used only after successful validaton.
+ * Note that it does not guarantee that any of the required/optional parameters will be present,
+ * or that there will be no other attributes besides those specified.
+ * In other words. OP may provide whatever information it wants to.
+ * * SREG names will be mapped to AX names.
+ * * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email'
+ * @see http://www.axschema.org/types/
+ */
+ function getAttributes()
+ {
+ if (isset($this->data['openid_ns'])
+ && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0'
+ ) { # OpenID 2.0
+ # We search for both AX and SREG attributes, with AX taking precedence.
+ return $this->getAxAttributes() + $this->getSregAttributes();
+ }
+ return $this->getSregAttributes();
+ } + + /**
+ * Gets an OAuth request token if the OpenID+OAuth hybrid protocol has been used.
+ *
+ * In order to use the OpenID+OAuth hybrid protocol, you need to add at least one
+ * scope to the $openid->oauth array before you get the call to getAuthUrl(), e.g.:
+ * $openid->oauth[] = 'https://www.googleapis.com/auth/plus.me';
+ *
+ * Furthermore the registered consumer name must fit the OpenID realm.
+ * To register an OpenID consumer at Google use: https://www.google.com/accounts/ManageDomains
+ *
+ * @return string|bool OAuth request token on success, FALSE if no token was provided.
+ */
+ function getOAuthRequestToken()
+ {
+ $alias = $this->getNamespaceAlias('http://specs.openid.net/extensions/oauth/1.0'); + + return !empty($alias) ? $this->data['openid_' . $alias . '_request_token'] : false;
+ } + + /**
+ * Gets the alias for the specified namespace, if it's present.
+ *
+ * @param string $namespace The namespace for which an alias is needed.
+ * @param string $hint Common alias of this namespace, used for optimization.
+ * @return string|null The namespace alias if found, otherwise - NULL.
+ */
+ private function getNamespaceAlias($namespace, $hint = null)
+ {
+ $result = null; + + if (empty($hint) || $this->getItem('openid_ns_' . $hint) != $namespace) {
+ // The common alias is either undefined or points to
+ // some other extension - search for another alias..
+ $prefix = 'openid_ns_';
+ $length = strlen($prefix); + + foreach ($this->data as $key => $val) {
+ if (strncmp($key, $prefix, $length) === 0 && $val === $namespace) {
+ $result = trim(substr($key, $length));
+ break;
+ }
+ }
+ } else {
+ $result = $hint;
+ } + + return $result;
+ } + + /**
+ * Gets an item from the $data array by the specified id.
+ *
+ * @param string $id The id of the desired item.
+ * @return string|null The item if found, otherwise - NULL.
+ */
+ private function getItem($id)
+ {
+ return $this->data[$id] ?? null;
+ }
+} diff --git a/hauth/Hybrid/thirdparty/index.html b/hauth/Hybrid/thirdparty/index.html index 065d2da..065d2da 100644..100755 --- a/hauth/Hybrid/thirdparty/index.html +++ b/hauth/Hybrid/thirdparty/index.html diff --git a/hauth/disconnect.php b/hauth/disconnect.php index 8efd2ca..3db74d8 100644 --- a/hauth/disconnect.php +++ b/hauth/disconnect.php @@ -6,7 +6,7 @@ // | This source file is subject to version 2.0 of the GPL license | // +--------------------------------------------------------------------+ // | Portions Copyright (c) 2003 The zen-cart developers | -// | Portions Copyright (c) 2003 osCommerce | +// | Portions Copyright (c) 2003 osCommerce | // +--------------------------------------------------------------------+ // diff --git a/hauth/images/google.png b/hauth/images/google.png Binary files differindex c1e2c5c..c1e2c5c 100644..100755 --- a/hauth/images/google.png +++ b/hauth/images/google.png diff --git a/hauth/index.php b/hauth/index.php index 29e76db..1386c84 100644 --- a/hauth/index.php +++ b/hauth/index.php @@ -3,19 +3,19 @@ * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
-*/
-
+*/ + // ------------------------------------------------------------------------
// HybridAuth End Point
// ------------------------------------------------------------------------
require_once( '../../kernel/includes/setup_inc.php' );
-require_once( EXTERNAL_LIBS_PATH . 'facebook/src/Facebook/autoload.php' );
-
+require_once( EXTERNAL_LIBS_PATH . 'facebook/src/Facebook/autoload.php' ); + require_once( "Hybrid/Auth.php" );
-require_once( "Hybrid/Endpoint.php" );
-
+require_once( "Hybrid/Endpoint.php" ); + try {
Hybrid_Endpoint::process();
} catch( Exception $e ) {
$gBitSystem->fatalError( $e->getMessage(), NULL, NULL, HttpStatusCodes::HTTP_UNAUTHORIZED );
-}
+} diff --git a/icons/flags/Afghanistan,_Islamic_State_of.gif b/icons/flags/Afghanistan,_Islamic_State_of.gif Binary files differindex 9889408..9889408 100644..100755 --- a/icons/flags/Afghanistan,_Islamic_State_of.gif +++ b/icons/flags/Afghanistan,_Islamic_State_of.gif diff --git a/icons/flags/Albania.gif b/icons/flags/Albania.gif Binary files differindex c44fe0a..c44fe0a 100644..100755 --- a/icons/flags/Albania.gif +++ b/icons/flags/Albania.gif diff --git a/icons/flags/Algeria.gif b/icons/flags/Algeria.gif Binary files differindex ed580a7..ed580a7 100644..100755 --- a/icons/flags/Algeria.gif +++ b/icons/flags/Algeria.gif diff --git a/icons/flags/American_Samoa.gif b/icons/flags/American_Samoa.gif Binary files differindex d776ec2..d776ec2 100644..100755 --- a/icons/flags/American_Samoa.gif +++ b/icons/flags/American_Samoa.gif diff --git a/icons/flags/Andorra,_Principality_of.gif b/icons/flags/Andorra,_Principality_of.gif Binary files differindex 57b4997..57b4997 100644..100755 --- a/icons/flags/Andorra,_Principality_of.gif +++ b/icons/flags/Andorra,_Principality_of.gif diff --git a/icons/flags/Angola.gif b/icons/flags/Angola.gif Binary files differindex 3011b19..3011b19 100644..100755 --- a/icons/flags/Angola.gif +++ b/icons/flags/Angola.gif diff --git a/icons/flags/Anguilla.gif b/icons/flags/Anguilla.gif Binary files differindex 1cbc579..1cbc579 100644..100755 --- a/icons/flags/Anguilla.gif +++ b/icons/flags/Anguilla.gif diff --git a/icons/flags/Antigua_and_Barbuda.gif b/icons/flags/Antigua_and_Barbuda.gif Binary files differindex 48f8e7b..48f8e7b 100644..100755 --- a/icons/flags/Antigua_and_Barbuda.gif +++ b/icons/flags/Antigua_and_Barbuda.gif diff --git a/icons/flags/Arab_League.gif b/icons/flags/Arab_League.gif Binary files differindex 95a557c..95a557c 100644..100755 --- a/icons/flags/Arab_League.gif +++ b/icons/flags/Arab_League.gif diff --git a/icons/flags/Argentina.gif b/icons/flags/Argentina.gif Binary files differindex a9f71f7..a9f71f7 100644..100755 --- a/icons/flags/Argentina.gif +++ b/icons/flags/Argentina.gif diff --git a/icons/flags/Armenia.gif b/icons/flags/Armenia.gif Binary files differindex 2915e30..2915e30 100644..100755 --- a/icons/flags/Armenia.gif +++ b/icons/flags/Armenia.gif diff --git a/icons/flags/Aruba.gif b/icons/flags/Aruba.gif Binary files differindex 27fdb4d..27fdb4d 100644..100755 --- a/icons/flags/Aruba.gif +++ b/icons/flags/Aruba.gif diff --git a/icons/flags/Australia.gif b/icons/flags/Australia.gif Binary files differindex 5269c6a..5269c6a 100644..100755 --- a/icons/flags/Australia.gif +++ b/icons/flags/Australia.gif diff --git a/icons/flags/Austria.gif b/icons/flags/Austria.gif Binary files differindex 87e1217..87e1217 100644..100755 --- a/icons/flags/Austria.gif +++ b/icons/flags/Austria.gif diff --git a/icons/flags/Azerbaidjan.gif b/icons/flags/Azerbaidjan.gif Binary files differindex d771618..d771618 100644..100755 --- a/icons/flags/Azerbaidjan.gif +++ b/icons/flags/Azerbaidjan.gif diff --git a/icons/flags/Bahamas.gif b/icons/flags/Bahamas.gif Binary files differindex c0a741e..c0a741e 100644..100755 --- a/icons/flags/Bahamas.gif +++ b/icons/flags/Bahamas.gif diff --git a/icons/flags/Bahrain.gif b/icons/flags/Bahrain.gif Binary files differindex 56aa72b..56aa72b 100644..100755 --- a/icons/flags/Bahrain.gif +++ b/icons/flags/Bahrain.gif diff --git a/icons/flags/Bangladesh.gif b/icons/flags/Bangladesh.gif Binary files differindex 0fd27ec..0fd27ec 100644..100755 --- a/icons/flags/Bangladesh.gif +++ b/icons/flags/Bangladesh.gif diff --git a/icons/flags/Barbados.gif b/icons/flags/Barbados.gif Binary files differindex b7d08e5..b7d08e5 100644..100755 --- a/icons/flags/Barbados.gif +++ b/icons/flags/Barbados.gif diff --git a/icons/flags/Belarus.gif b/icons/flags/Belarus.gif Binary files differindex 43ffcd4..43ffcd4 100644..100755 --- a/icons/flags/Belarus.gif +++ b/icons/flags/Belarus.gif diff --git a/icons/flags/Belgium.gif b/icons/flags/Belgium.gif Binary files differindex ae09bfb..ae09bfb 100644..100755 --- a/icons/flags/Belgium.gif +++ b/icons/flags/Belgium.gif diff --git a/icons/flags/Belize.gif b/icons/flags/Belize.gif Binary files differindex 791737f..791737f 100644..100755 --- a/icons/flags/Belize.gif +++ b/icons/flags/Belize.gif diff --git a/icons/flags/Benin.gif b/icons/flags/Benin.gif Binary files differindex e676116..e676116 100644..100755 --- a/icons/flags/Benin.gif +++ b/icons/flags/Benin.gif diff --git a/icons/flags/Bermuda.gif b/icons/flags/Bermuda.gif Binary files differindex 9feb87b..9feb87b 100644..100755 --- a/icons/flags/Bermuda.gif +++ b/icons/flags/Bermuda.gif diff --git a/icons/flags/Bhutan.gif b/icons/flags/Bhutan.gif Binary files differindex abe2f3c..abe2f3c 100644..100755 --- a/icons/flags/Bhutan.gif +++ b/icons/flags/Bhutan.gif diff --git a/icons/flags/Bolivia.gif b/icons/flags/Bolivia.gif Binary files differindex 4844f85..4844f85 100644..100755 --- a/icons/flags/Bolivia.gif +++ b/icons/flags/Bolivia.gif diff --git a/icons/flags/Bosnia-Herzegovina.gif b/icons/flags/Bosnia-Herzegovina.gif Binary files differindex 9bf5f0a..9bf5f0a 100644..100755 --- a/icons/flags/Bosnia-Herzegovina.gif +++ b/icons/flags/Bosnia-Herzegovina.gif diff --git a/icons/flags/Botswana.gif b/icons/flags/Botswana.gif Binary files differindex 986ab63..986ab63 100644..100755 --- a/icons/flags/Botswana.gif +++ b/icons/flags/Botswana.gif diff --git a/icons/flags/Bouvet_Island.gif b/icons/flags/Bouvet_Island.gif Binary files differindex 6202d1f..6202d1f 100644..100755 --- a/icons/flags/Bouvet_Island.gif +++ b/icons/flags/Bouvet_Island.gif diff --git a/icons/flags/Brazil.gif b/icons/flags/Brazil.gif Binary files differindex 8c86616..8c86616 100644..100755 --- a/icons/flags/Brazil.gif +++ b/icons/flags/Brazil.gif diff --git a/icons/flags/British_Indian_Ocean_Territory.gif b/icons/flags/British_Indian_Ocean_Territory.gif Binary files differindex de7e7ab..de7e7ab 100644..100755 --- a/icons/flags/British_Indian_Ocean_Territory.gif +++ b/icons/flags/British_Indian_Ocean_Territory.gif diff --git a/icons/flags/Brunei_Darussalam.gif b/icons/flags/Brunei_Darussalam.gif Binary files differindex b7b6b0f..b7b6b0f 100644..100755 --- a/icons/flags/Brunei_Darussalam.gif +++ b/icons/flags/Brunei_Darussalam.gif diff --git a/icons/flags/Bulgaria.gif b/icons/flags/Bulgaria.gif Binary files differindex 11cf8ff..11cf8ff 100644..100755 --- a/icons/flags/Bulgaria.gif +++ b/icons/flags/Bulgaria.gif diff --git a/icons/flags/Burkina_Faso.gif b/icons/flags/Burkina_Faso.gif Binary files differindex 9d6772c..9d6772c 100644..100755 --- a/icons/flags/Burkina_Faso.gif +++ b/icons/flags/Burkina_Faso.gif diff --git a/icons/flags/Burundi.gif b/icons/flags/Burundi.gif Binary files differindex 6e2cbe1..6e2cbe1 100644..100755 --- a/icons/flags/Burundi.gif +++ b/icons/flags/Burundi.gif diff --git a/icons/flags/Cambodia,_Kingdom_of.gif b/icons/flags/Cambodia,_Kingdom_of.gif Binary files differindex 30a1831..30a1831 100644..100755 --- a/icons/flags/Cambodia,_Kingdom_of.gif +++ b/icons/flags/Cambodia,_Kingdom_of.gif diff --git a/icons/flags/Cameroon.gif b/icons/flags/Cameroon.gif Binary files differindex 1fb102b..1fb102b 100644..100755 --- a/icons/flags/Cameroon.gif +++ b/icons/flags/Cameroon.gif diff --git a/icons/flags/Canada.gif b/icons/flags/Canada.gif Binary files differindex 457d966..457d966 100644..100755 --- a/icons/flags/Canada.gif +++ b/icons/flags/Canada.gif diff --git a/icons/flags/Cape_Verde.gif b/icons/flags/Cape_Verde.gif Binary files differindex 43c6c6c..43c6c6c 100644..100755 --- a/icons/flags/Cape_Verde.gif +++ b/icons/flags/Cape_Verde.gif diff --git a/icons/flags/Cayman_Islands.gif b/icons/flags/Cayman_Islands.gif Binary files differindex d3d02ee..d3d02ee 100644..100755 --- a/icons/flags/Cayman_Islands.gif +++ b/icons/flags/Cayman_Islands.gif diff --git a/icons/flags/Central_African_Republic.gif b/icons/flags/Central_African_Republic.gif Binary files differindex 35787ca..35787ca 100644..100755 --- a/icons/flags/Central_African_Republic.gif +++ b/icons/flags/Central_African_Republic.gif diff --git a/icons/flags/Chad.gif b/icons/flags/Chad.gif Binary files differindex 7aa8a10..7aa8a10 100644..100755 --- a/icons/flags/Chad.gif +++ b/icons/flags/Chad.gif diff --git a/icons/flags/Chile.gif b/icons/flags/Chile.gif Binary files differindex cbc370e..cbc370e 100644..100755 --- a/icons/flags/Chile.gif +++ b/icons/flags/Chile.gif diff --git a/icons/flags/China.gif b/icons/flags/China.gif Binary files differindex b052530..b052530 100644..100755 --- a/icons/flags/China.gif +++ b/icons/flags/China.gif diff --git a/icons/flags/Christmas_Island.gif b/icons/flags/Christmas_Island.gif Binary files differindex a5b4308..a5b4308 100644..100755 --- a/icons/flags/Christmas_Island.gif +++ b/icons/flags/Christmas_Island.gif diff --git a/icons/flags/Cocos_Islands.gif b/icons/flags/Cocos_Islands.gif Binary files differindex 3f78327..3f78327 100644..100755 --- a/icons/flags/Cocos_Islands.gif +++ b/icons/flags/Cocos_Islands.gif diff --git a/icons/flags/Colombia.gif b/icons/flags/Colombia.gif Binary files differindex d0e15ca..d0e15ca 100644..100755 --- a/icons/flags/Colombia.gif +++ b/icons/flags/Colombia.gif diff --git a/icons/flags/Comoros.gif b/icons/flags/Comoros.gif Binary files differindex 5859595..5859595 100644..100755 --- a/icons/flags/Comoros.gif +++ b/icons/flags/Comoros.gif diff --git a/icons/flags/Congo,_The_Democratic_Republic_of_the.gif b/icons/flags/Congo,_The_Democratic_Republic_of_the.gif Binary files differindex 1afa9d4..1afa9d4 100644..100755 --- a/icons/flags/Congo,_The_Democratic_Republic_of_the.gif +++ b/icons/flags/Congo,_The_Democratic_Republic_of_the.gif diff --git a/icons/flags/Cook_Islands.gif b/icons/flags/Cook_Islands.gif Binary files differindex 2edb739..2edb739 100644..100755 --- a/icons/flags/Cook_Islands.gif +++ b/icons/flags/Cook_Islands.gif diff --git a/icons/flags/Costa_Rica.gif b/icons/flags/Costa_Rica.gif Binary files differindex 0728dd6..0728dd6 100644..100755 --- a/icons/flags/Costa_Rica.gif +++ b/icons/flags/Costa_Rica.gif diff --git a/icons/flags/Croatia.gif b/icons/flags/Croatia.gif Binary files differindex 557c660..557c660 100644..100755 --- a/icons/flags/Croatia.gif +++ b/icons/flags/Croatia.gif diff --git a/icons/flags/Cuba.gif b/icons/flags/Cuba.gif Binary files differindex 291255c..291255c 100644..100755 --- a/icons/flags/Cuba.gif +++ b/icons/flags/Cuba.gif diff --git a/icons/flags/Cyprus.gif b/icons/flags/Cyprus.gif Binary files differindex 35c661e..35c661e 100644..100755 --- a/icons/flags/Cyprus.gif +++ b/icons/flags/Cyprus.gif diff --git a/icons/flags/Czech_Republic.gif b/icons/flags/Czech_Republic.gif Binary files differindex 0a605e5..0a605e5 100644..100755 --- a/icons/flags/Czech_Republic.gif +++ b/icons/flags/Czech_Republic.gif diff --git a/icons/flags/Denmark.gif b/icons/flags/Denmark.gif Binary files differindex 03e75bd..03e75bd 100644..100755 --- a/icons/flags/Denmark.gif +++ b/icons/flags/Denmark.gif diff --git a/icons/flags/Djibouti.gif b/icons/flags/Djibouti.gif Binary files differindex 212406d..212406d 100644..100755 --- a/icons/flags/Djibouti.gif +++ b/icons/flags/Djibouti.gif diff --git a/icons/flags/Dominica.gif b/icons/flags/Dominica.gif Binary files differindex 2f87f3c..2f87f3c 100644..100755 --- a/icons/flags/Dominica.gif +++ b/icons/flags/Dominica.gif diff --git a/icons/flags/Dominican_Republic.gif b/icons/flags/Dominican_Republic.gif Binary files differindex f7d0bad..f7d0bad 100644..100755 --- a/icons/flags/Dominican_Republic.gif +++ b/icons/flags/Dominican_Republic.gif diff --git a/icons/flags/Ecuador.gif b/icons/flags/Ecuador.gif Binary files differindex 9e41e0e..9e41e0e 100644..100755 --- a/icons/flags/Ecuador.gif +++ b/icons/flags/Ecuador.gif diff --git a/icons/flags/Egypt.gif b/icons/flags/Egypt.gif Binary files differindex 6857c7d..6857c7d 100644..100755 --- a/icons/flags/Egypt.gif +++ b/icons/flags/Egypt.gif diff --git a/icons/flags/El_Salvador.gif b/icons/flags/El_Salvador.gif Binary files differindex 2d7b159..2d7b159 100644..100755 --- a/icons/flags/El_Salvador.gif +++ b/icons/flags/El_Salvador.gif diff --git a/icons/flags/England.gif b/icons/flags/England.gif Binary files differindex 933a4f0..933a4f0 100644..100755 --- a/icons/flags/England.gif +++ b/icons/flags/England.gif diff --git a/icons/flags/Equatorial_Guinea.gif b/icons/flags/Equatorial_Guinea.gif Binary files differindex 8b4e0cc..8b4e0cc 100644..100755 --- a/icons/flags/Equatorial_Guinea.gif +++ b/icons/flags/Equatorial_Guinea.gif diff --git a/icons/flags/Eritrea.gif b/icons/flags/Eritrea.gif Binary files differindex 3d4d612..3d4d612 100644..100755 --- a/icons/flags/Eritrea.gif +++ b/icons/flags/Eritrea.gif diff --git a/icons/flags/Estonia.gif b/icons/flags/Estonia.gif Binary files differindex 9397a2d..9397a2d 100644..100755 --- a/icons/flags/Estonia.gif +++ b/icons/flags/Estonia.gif diff --git a/icons/flags/Ethiopia.gif b/icons/flags/Ethiopia.gif Binary files differindex f77995d..f77995d 100644..100755 --- a/icons/flags/Ethiopia.gif +++ b/icons/flags/Ethiopia.gif diff --git a/icons/flags/Falkland_Islands.gif b/icons/flags/Falkland_Islands.gif Binary files differindex 37b5ecf..37b5ecf 100644..100755 --- a/icons/flags/Falkland_Islands.gif +++ b/icons/flags/Falkland_Islands.gif diff --git a/icons/flags/Faroe_Islands.gif b/icons/flags/Faroe_Islands.gif Binary files differindex 4a90fc0..4a90fc0 100644..100755 --- a/icons/flags/Faroe_Islands.gif +++ b/icons/flags/Faroe_Islands.gif diff --git a/icons/flags/Federated_States_of_Micronesia.gif b/icons/flags/Federated_States_of_Micronesia.gif Binary files differindex bbd1cc8..bbd1cc8 100644..100755 --- a/icons/flags/Federated_States_of_Micronesia.gif +++ b/icons/flags/Federated_States_of_Micronesia.gif diff --git a/icons/flags/Fiji.gif b/icons/flags/Fiji.gif Binary files differindex 486151c..486151c 100644..100755 --- a/icons/flags/Fiji.gif +++ b/icons/flags/Fiji.gif diff --git a/icons/flags/Finland.gif b/icons/flags/Finland.gif Binary files differindex 8d3a191..8d3a191 100644..100755 --- a/icons/flags/Finland.gif +++ b/icons/flags/Finland.gif diff --git a/icons/flags/Former_Czechoslovakia.gif b/icons/flags/Former_Czechoslovakia.gif Binary files differindex 101db64..101db64 100644..100755 --- a/icons/flags/Former_Czechoslovakia.gif +++ b/icons/flags/Former_Czechoslovakia.gif diff --git a/icons/flags/France.gif b/icons/flags/France.gif Binary files differindex 43d0b80..43d0b80 100644..100755 --- a/icons/flags/France.gif +++ b/icons/flags/France.gif diff --git a/icons/flags/French_Polynesia.gif b/icons/flags/French_Polynesia.gif Binary files differindex 479ff10..479ff10 100644..100755 --- a/icons/flags/French_Polynesia.gif +++ b/icons/flags/French_Polynesia.gif diff --git a/icons/flags/French_Southern_Territories.gif b/icons/flags/French_Southern_Territories.gif Binary files differindex 51a4325..51a4325 100644..100755 --- a/icons/flags/French_Southern_Territories.gif +++ b/icons/flags/French_Southern_Territories.gif diff --git a/icons/flags/Gabon.gif b/icons/flags/Gabon.gif Binary files differindex 23fd5f0..23fd5f0 100644..100755 --- a/icons/flags/Gabon.gif +++ b/icons/flags/Gabon.gif diff --git a/icons/flags/Gambia.gif b/icons/flags/Gambia.gif Binary files differindex 6847c5a..6847c5a 100644..100755 --- a/icons/flags/Gambia.gif +++ b/icons/flags/Gambia.gif diff --git a/icons/flags/Georgia.gif b/icons/flags/Georgia.gif Binary files differindex faa7f12..faa7f12 100644..100755 --- a/icons/flags/Georgia.gif +++ b/icons/flags/Georgia.gif diff --git a/icons/flags/Germany.gif b/icons/flags/Germany.gif Binary files differindex 75728dd..75728dd 100644..100755 --- a/icons/flags/Germany.gif +++ b/icons/flags/Germany.gif diff --git a/icons/flags/Ghana.gif b/icons/flags/Ghana.gif Binary files differindex 273fb7d..273fb7d 100644..100755 --- a/icons/flags/Ghana.gif +++ b/icons/flags/Ghana.gif diff --git a/icons/flags/Gibraltar.gif b/icons/flags/Gibraltar.gif Binary files differindex 7b1984b..7b1984b 100644..100755 --- a/icons/flags/Gibraltar.gif +++ b/icons/flags/Gibraltar.gif diff --git a/icons/flags/Great_Britain.gif b/icons/flags/Great_Britain.gif Binary files differindex 3e16ff8..3e16ff8 100644..100755 --- a/icons/flags/Great_Britain.gif +++ b/icons/flags/Great_Britain.gif diff --git a/icons/flags/Greece.gif b/icons/flags/Greece.gif Binary files differindex b4c8c04..b4c8c04 100644..100755 --- a/icons/flags/Greece.gif +++ b/icons/flags/Greece.gif diff --git a/icons/flags/Greenland.gif b/icons/flags/Greenland.gif Binary files differindex ef445be..ef445be 100644..100755 --- a/icons/flags/Greenland.gif +++ b/icons/flags/Greenland.gif diff --git a/icons/flags/Grenada.gif b/icons/flags/Grenada.gif Binary files differindex 25ea312..25ea312 100644..100755 --- a/icons/flags/Grenada.gif +++ b/icons/flags/Grenada.gif diff --git a/icons/flags/Guadeloupe.gif b/icons/flags/Guadeloupe.gif Binary files differindex 31166db..31166db 100644..100755 --- a/icons/flags/Guadeloupe.gif +++ b/icons/flags/Guadeloupe.gif diff --git a/icons/flags/Guam.gif b/icons/flags/Guam.gif Binary files differindex eafef68..eafef68 100644..100755 --- a/icons/flags/Guam.gif +++ b/icons/flags/Guam.gif diff --git a/icons/flags/Guatemala.gif b/icons/flags/Guatemala.gif Binary files differindex 7e94d1d..7e94d1d 100644..100755 --- a/icons/flags/Guatemala.gif +++ b/icons/flags/Guatemala.gif diff --git a/icons/flags/Guinea.gif b/icons/flags/Guinea.gif Binary files differindex a982ac6..a982ac6 100644..100755 --- a/icons/flags/Guinea.gif +++ b/icons/flags/Guinea.gif diff --git a/icons/flags/Guinea_Bissau.gif b/icons/flags/Guinea_Bissau.gif Binary files differindex 55f7571..55f7571 100644..100755 --- a/icons/flags/Guinea_Bissau.gif +++ b/icons/flags/Guinea_Bissau.gif diff --git a/icons/flags/Guyana.gif b/icons/flags/Guyana.gif Binary files differindex 1cb4cd7..1cb4cd7 100644..100755 --- a/icons/flags/Guyana.gif +++ b/icons/flags/Guyana.gif diff --git a/icons/flags/Haiti.gif b/icons/flags/Haiti.gif Binary files differindex 059604a..059604a 100644..100755 --- a/icons/flags/Haiti.gif +++ b/icons/flags/Haiti.gif diff --git a/icons/flags/Holy_See.gif b/icons/flags/Holy_See.gif Binary files differindex 2bd7446..2bd7446 100644..100755 --- a/icons/flags/Holy_See.gif +++ b/icons/flags/Holy_See.gif diff --git a/icons/flags/Honduras.gif b/icons/flags/Honduras.gif Binary files differindex 6c4ffe8..6c4ffe8 100644..100755 --- a/icons/flags/Honduras.gif +++ b/icons/flags/Honduras.gif diff --git a/icons/flags/Hong_Kong.gif b/icons/flags/Hong_Kong.gif Binary files differindex 798af96..798af96 100644..100755 --- a/icons/flags/Hong_Kong.gif +++ b/icons/flags/Hong_Kong.gif diff --git a/icons/flags/Hungary.gif b/icons/flags/Hungary.gif Binary files differindex 6142d86..6142d86 100644..100755 --- a/icons/flags/Hungary.gif +++ b/icons/flags/Hungary.gif diff --git a/icons/flags/Iceland.gif b/icons/flags/Iceland.gif Binary files differindex b42502d..b42502d 100644..100755 --- a/icons/flags/Iceland.gif +++ b/icons/flags/Iceland.gif diff --git a/icons/flags/India.gif b/icons/flags/India.gif Binary files differindex 1cd8027..1cd8027 100644..100755 --- a/icons/flags/India.gif +++ b/icons/flags/India.gif diff --git a/icons/flags/Indonesia.gif b/icons/flags/Indonesia.gif Binary files differindex 865161b..865161b 100644..100755 --- a/icons/flags/Indonesia.gif +++ b/icons/flags/Indonesia.gif diff --git a/icons/flags/Iran.gif b/icons/flags/Iran.gif Binary files differindex 156040f..156040f 100644..100755 --- a/icons/flags/Iran.gif +++ b/icons/flags/Iran.gif diff --git a/icons/flags/Iraq.gif b/icons/flags/Iraq.gif Binary files differindex c34fe3c..c34fe3c 100644..100755 --- a/icons/flags/Iraq.gif +++ b/icons/flags/Iraq.gif diff --git a/icons/flags/Ireland.gif b/icons/flags/Ireland.gif Binary files differindex 506ad28..506ad28 100644..100755 --- a/icons/flags/Ireland.gif +++ b/icons/flags/Ireland.gif diff --git a/icons/flags/Israel.gif b/icons/flags/Israel.gif Binary files differindex c8483ae..c8483ae 100644..100755 --- a/icons/flags/Israel.gif +++ b/icons/flags/Israel.gif diff --git a/icons/flags/Italy.gif b/icons/flags/Italy.gif Binary files differindex d79e90e..d79e90e 100644..100755 --- a/icons/flags/Italy.gif +++ b/icons/flags/Italy.gif diff --git a/icons/flags/Ivory_Coast.gif b/icons/flags/Ivory_Coast.gif Binary files differindex 844120a..844120a 100644..100755 --- a/icons/flags/Ivory_Coast.gif +++ b/icons/flags/Ivory_Coast.gif diff --git a/icons/flags/Jamaica.gif b/icons/flags/Jamaica.gif Binary files differindex 0bed67c..0bed67c 100644..100755 --- a/icons/flags/Jamaica.gif +++ b/icons/flags/Jamaica.gif diff --git a/icons/flags/Japan.gif b/icons/flags/Japan.gif Binary files differindex 444c1d0..444c1d0 100644..100755 --- a/icons/flags/Japan.gif +++ b/icons/flags/Japan.gif diff --git a/icons/flags/Jordan.gif b/icons/flags/Jordan.gif Binary files differindex 03daf8a..03daf8a 100644..100755 --- a/icons/flags/Jordan.gif +++ b/icons/flags/Jordan.gif diff --git a/icons/flags/Kazakhstan.gif b/icons/flags/Kazakhstan.gif Binary files differindex 24baebe..24baebe 100644..100755 --- a/icons/flags/Kazakhstan.gif +++ b/icons/flags/Kazakhstan.gif diff --git a/icons/flags/Kenya.gif b/icons/flags/Kenya.gif Binary files differindex c2b5d45..c2b5d45 100644..100755 --- a/icons/flags/Kenya.gif +++ b/icons/flags/Kenya.gif diff --git a/icons/flags/Kiribati.gif b/icons/flags/Kiribati.gif Binary files differindex 4a0751a..4a0751a 100644..100755 --- a/icons/flags/Kiribati.gif +++ b/icons/flags/Kiribati.gif diff --git a/icons/flags/Kuwait.gif b/icons/flags/Kuwait.gif Binary files differindex 1efc734..1efc734 100644..100755 --- a/icons/flags/Kuwait.gif +++ b/icons/flags/Kuwait.gif diff --git a/icons/flags/Kyrgyz_Republic.gif b/icons/flags/Kyrgyz_Republic.gif Binary files differindex 72a4d41..72a4d41 100644..100755 --- a/icons/flags/Kyrgyz_Republic.gif +++ b/icons/flags/Kyrgyz_Republic.gif diff --git a/icons/flags/Laos.gif b/icons/flags/Laos.gif Binary files differindex d14cf4d..d14cf4d 100644..100755 --- a/icons/flags/Laos.gif +++ b/icons/flags/Laos.gif diff --git a/icons/flags/Latvia.gif b/icons/flags/Latvia.gif Binary files differindex 17e71b7..17e71b7 100644..100755 --- a/icons/flags/Latvia.gif +++ b/icons/flags/Latvia.gif diff --git a/icons/flags/Lebanon.gif b/icons/flags/Lebanon.gif Binary files differindex 003d83a..003d83a 100644..100755 --- a/icons/flags/Lebanon.gif +++ b/icons/flags/Lebanon.gif diff --git a/icons/flags/Lesotho.gif b/icons/flags/Lesotho.gif Binary files differindex 427ae95..427ae95 100644..100755 --- a/icons/flags/Lesotho.gif +++ b/icons/flags/Lesotho.gif diff --git a/icons/flags/Liberia.gif b/icons/flags/Liberia.gif Binary files differindex 435af9e..435af9e 100644..100755 --- a/icons/flags/Liberia.gif +++ b/icons/flags/Liberia.gif diff --git a/icons/flags/Libya.gif b/icons/flags/Libya.gif Binary files differindex a654c30..a654c30 100644..100755 --- a/icons/flags/Libya.gif +++ b/icons/flags/Libya.gif diff --git a/icons/flags/Liechtenstein.gif b/icons/flags/Liechtenstein.gif Binary files differindex 713c58e..713c58e 100644..100755 --- a/icons/flags/Liechtenstein.gif +++ b/icons/flags/Liechtenstein.gif diff --git a/icons/flags/Lithuania.gif b/icons/flags/Lithuania.gif Binary files differindex dee9c60..dee9c60 100644..100755 --- a/icons/flags/Lithuania.gif +++ b/icons/flags/Lithuania.gif diff --git a/icons/flags/Luxembourg.gif b/icons/flags/Luxembourg.gif Binary files differindex 7d7293e..7d7293e 100644..100755 --- a/icons/flags/Luxembourg.gif +++ b/icons/flags/Luxembourg.gif diff --git a/icons/flags/Macau.gif b/icons/flags/Macau.gif Binary files differindex 66cf5b4..66cf5b4 100644..100755 --- a/icons/flags/Macau.gif +++ b/icons/flags/Macau.gif diff --git a/icons/flags/Macedonia.gif b/icons/flags/Macedonia.gif Binary files differindex 7aeb831..7aeb831 100644..100755 --- a/icons/flags/Macedonia.gif +++ b/icons/flags/Macedonia.gif diff --git a/icons/flags/Madagascar.gif b/icons/flags/Madagascar.gif Binary files differindex a91b577..a91b577 100644..100755 --- a/icons/flags/Madagascar.gif +++ b/icons/flags/Madagascar.gif diff --git a/icons/flags/Malawi.gif b/icons/flags/Malawi.gif Binary files differindex ad045a0..ad045a0 100644..100755 --- a/icons/flags/Malawi.gif +++ b/icons/flags/Malawi.gif diff --git a/icons/flags/Malaysia.gif b/icons/flags/Malaysia.gif Binary files differindex fc7d523..fc7d523 100644..100755 --- a/icons/flags/Malaysia.gif +++ b/icons/flags/Malaysia.gif diff --git a/icons/flags/Maldives.gif b/icons/flags/Maldives.gif Binary files differindex 46b6387..46b6387 100644..100755 --- a/icons/flags/Maldives.gif +++ b/icons/flags/Maldives.gif diff --git a/icons/flags/Mali.gif b/icons/flags/Mali.gif Binary files differindex 53d6f49..53d6f49 100644..100755 --- a/icons/flags/Mali.gif +++ b/icons/flags/Mali.gif diff --git a/icons/flags/Malta.gif b/icons/flags/Malta.gif Binary files differindex 45c709f..45c709f 100644..100755 --- a/icons/flags/Malta.gif +++ b/icons/flags/Malta.gif diff --git a/icons/flags/Marshall_Islands.gif b/icons/flags/Marshall_Islands.gif Binary files differindex 92f5f48..92f5f48 100644..100755 --- a/icons/flags/Marshall_Islands.gif +++ b/icons/flags/Marshall_Islands.gif diff --git a/icons/flags/Martinique.gif b/icons/flags/Martinique.gif Binary files differindex 570bc5d..570bc5d 100644..100755 --- a/icons/flags/Martinique.gif +++ b/icons/flags/Martinique.gif diff --git a/icons/flags/Mauritania.gif b/icons/flags/Mauritania.gif Binary files differindex f52fcf0..f52fcf0 100644..100755 --- a/icons/flags/Mauritania.gif +++ b/icons/flags/Mauritania.gif diff --git a/icons/flags/Mauritius.gif b/icons/flags/Mauritius.gif Binary files differindex 081ab45..081ab45 100644..100755 --- a/icons/flags/Mauritius.gif +++ b/icons/flags/Mauritius.gif diff --git a/icons/flags/Mayotte.gif b/icons/flags/Mayotte.gif Binary files differindex a2267c0..a2267c0 100644..100755 --- a/icons/flags/Mayotte.gif +++ b/icons/flags/Mayotte.gif diff --git a/icons/flags/Mexico.gif b/icons/flags/Mexico.gif Binary files differindex ddc75d0..ddc75d0 100644..100755 --- a/icons/flags/Mexico.gif +++ b/icons/flags/Mexico.gif diff --git a/icons/flags/Micronesia.gif b/icons/flags/Micronesia.gif Binary files differindex 7f8723b..7f8723b 100644..100755 --- a/icons/flags/Micronesia.gif +++ b/icons/flags/Micronesia.gif diff --git a/icons/flags/Moldavia.gif b/icons/flags/Moldavia.gif Binary files differindex e4b8a7e..e4b8a7e 100644..100755 --- a/icons/flags/Moldavia.gif +++ b/icons/flags/Moldavia.gif diff --git a/icons/flags/Monaco.gif b/icons/flags/Monaco.gif Binary files differindex 02a7c8e..02a7c8e 100644..100755 --- a/icons/flags/Monaco.gif +++ b/icons/flags/Monaco.gif diff --git a/icons/flags/Mongolia.gif b/icons/flags/Mongolia.gif Binary files differindex dff8ea5..dff8ea5 100644..100755 --- a/icons/flags/Mongolia.gif +++ b/icons/flags/Mongolia.gif diff --git a/icons/flags/Montserrat.gif b/icons/flags/Montserrat.gif Binary files differindex 5e5a67a..5e5a67a 100644..100755 --- a/icons/flags/Montserrat.gif +++ b/icons/flags/Montserrat.gif diff --git a/icons/flags/Morocco.gif b/icons/flags/Morocco.gif Binary files differindex fc78411..fc78411 100644..100755 --- a/icons/flags/Morocco.gif +++ b/icons/flags/Morocco.gif diff --git a/icons/flags/Mozambique.gif b/icons/flags/Mozambique.gif Binary files differindex 7d63508..7d63508 100644..100755 --- a/icons/flags/Mozambique.gif +++ b/icons/flags/Mozambique.gif diff --git a/icons/flags/Myanmar.gif b/icons/flags/Myanmar.gif Binary files differindex 9e0a275..9e0a275 100644..100755 --- a/icons/flags/Myanmar.gif +++ b/icons/flags/Myanmar.gif diff --git a/icons/flags/Namibia.gif b/icons/flags/Namibia.gif Binary files differindex c0babe7..c0babe7 100644..100755 --- a/icons/flags/Namibia.gif +++ b/icons/flags/Namibia.gif diff --git a/icons/flags/Nauru.gif b/icons/flags/Nauru.gif Binary files differindex 2e4c0c5..2e4c0c5 100644..100755 --- a/icons/flags/Nauru.gif +++ b/icons/flags/Nauru.gif diff --git a/icons/flags/Nepal.gif b/icons/flags/Nepal.gif Binary files differindex 1096893..1096893 100644..100755 --- a/icons/flags/Nepal.gif +++ b/icons/flags/Nepal.gif diff --git a/icons/flags/Netherlands.gif b/icons/flags/Netherlands.gif Binary files differindex c1c8f46..c1c8f46 100644..100755 --- a/icons/flags/Netherlands.gif +++ b/icons/flags/Netherlands.gif diff --git a/icons/flags/Netherlands_Antilles.gif b/icons/flags/Netherlands_Antilles.gif Binary files differindex cb570c6..cb570c6 100644..100755 --- a/icons/flags/Netherlands_Antilles.gif +++ b/icons/flags/Netherlands_Antilles.gif diff --git a/icons/flags/New_Caledonia.gif b/icons/flags/New_Caledonia.gif Binary files differindex b1e91b9..b1e91b9 100644..100755 --- a/icons/flags/New_Caledonia.gif +++ b/icons/flags/New_Caledonia.gif diff --git a/icons/flags/New_Zealand.gif b/icons/flags/New_Zealand.gif Binary files differindex 028a5dc..028a5dc 100644..100755 --- a/icons/flags/New_Zealand.gif +++ b/icons/flags/New_Zealand.gif diff --git a/icons/flags/Nicaragua.gif b/icons/flags/Nicaragua.gif Binary files differindex d05894d..d05894d 100644..100755 --- a/icons/flags/Nicaragua.gif +++ b/icons/flags/Nicaragua.gif diff --git a/icons/flags/Niger.gif b/icons/flags/Niger.gif Binary files differindex ff4eaf0..ff4eaf0 100644..100755 --- a/icons/flags/Niger.gif +++ b/icons/flags/Niger.gif diff --git a/icons/flags/Nigeria.gif b/icons/flags/Nigeria.gif Binary files differindex bdde7cb..bdde7cb 100644..100755 --- a/icons/flags/Nigeria.gif +++ b/icons/flags/Nigeria.gif diff --git a/icons/flags/Niue.gif b/icons/flags/Niue.gif Binary files differindex 618210a..618210a 100644..100755 --- a/icons/flags/Niue.gif +++ b/icons/flags/Niue.gif diff --git a/icons/flags/None.gif b/icons/flags/None.gif Binary files differindex 1ca9269..1ca9269 100644..100755 --- a/icons/flags/None.gif +++ b/icons/flags/None.gif diff --git a/icons/flags/Norfolk_Island.gif b/icons/flags/Norfolk_Island.gif Binary files differindex c83424c..c83424c 100644..100755 --- a/icons/flags/Norfolk_Island.gif +++ b/icons/flags/Norfolk_Island.gif diff --git a/icons/flags/North_Korea.gif b/icons/flags/North_Korea.gif Binary files differindex 6e0ca09..6e0ca09 100644..100755 --- a/icons/flags/North_Korea.gif +++ b/icons/flags/North_Korea.gif diff --git a/icons/flags/Northern_Mariana_Islands.gif b/icons/flags/Northern_Mariana_Islands.gif Binary files differindex 73b7147..73b7147 100644..100755 --- a/icons/flags/Northern_Mariana_Islands.gif +++ b/icons/flags/Northern_Mariana_Islands.gif diff --git a/icons/flags/Norway.gif b/icons/flags/Norway.gif Binary files differindex 6202d1f..6202d1f 100644..100755 --- a/icons/flags/Norway.gif +++ b/icons/flags/Norway.gif diff --git a/icons/flags/Oman.gif b/icons/flags/Oman.gif Binary files differindex 2b8c775..2b8c775 100644..100755 --- a/icons/flags/Oman.gif +++ b/icons/flags/Oman.gif diff --git a/icons/flags/Other.gif b/icons/flags/Other.gif Binary files differindex 1611258..1611258 100644..100755 --- a/icons/flags/Other.gif +++ b/icons/flags/Other.gif diff --git a/icons/flags/Pakistan.gif b/icons/flags/Pakistan.gif Binary files differindex f3f62c2..f3f62c2 100644..100755 --- a/icons/flags/Pakistan.gif +++ b/icons/flags/Pakistan.gif diff --git a/icons/flags/Palau.gif b/icons/flags/Palau.gif Binary files differindex 5854510..5854510 100644..100755 --- a/icons/flags/Palau.gif +++ b/icons/flags/Palau.gif diff --git a/icons/flags/Panama.gif b/icons/flags/Panama.gif Binary files differindex d518b2f..d518b2f 100644..100755 --- a/icons/flags/Panama.gif +++ b/icons/flags/Panama.gif diff --git a/icons/flags/Papua_New_Guinea.gif b/icons/flags/Papua_New_Guinea.gif Binary files differindex 2d20b07..2d20b07 100644..100755 --- a/icons/flags/Papua_New_Guinea.gif +++ b/icons/flags/Papua_New_Guinea.gif diff --git a/icons/flags/Paraguay.gif b/icons/flags/Paraguay.gif Binary files differindex f2e66af..f2e66af 100644..100755 --- a/icons/flags/Paraguay.gif +++ b/icons/flags/Paraguay.gif diff --git a/icons/flags/Peru.gif b/icons/flags/Peru.gif Binary files differindex 3bc7639..3bc7639 100644..100755 --- a/icons/flags/Peru.gif +++ b/icons/flags/Peru.gif diff --git a/icons/flags/Philippines.gif b/icons/flags/Philippines.gif Binary files differindex 12b380a..12b380a 100644..100755 --- a/icons/flags/Philippines.gif +++ b/icons/flags/Philippines.gif diff --git a/icons/flags/Pitcairn_Island.gif b/icons/flags/Pitcairn_Island.gif Binary files differindex 4bc86a1..4bc86a1 100644..100755 --- a/icons/flags/Pitcairn_Island.gif +++ b/icons/flags/Pitcairn_Island.gif diff --git a/icons/flags/Poland.gif b/icons/flags/Poland.gif Binary files differindex bf10646..bf10646 100644..100755 --- a/icons/flags/Poland.gif +++ b/icons/flags/Poland.gif diff --git a/icons/flags/Polynesia.gif b/icons/flags/Polynesia.gif Binary files differindex 849297a..849297a 100644..100755 --- a/icons/flags/Polynesia.gif +++ b/icons/flags/Polynesia.gif diff --git a/icons/flags/Portugal.gif b/icons/flags/Portugal.gif Binary files differindex e735f74..e735f74 100644..100755 --- a/icons/flags/Portugal.gif +++ b/icons/flags/Portugal.gif diff --git a/icons/flags/Puerto_Rico.gif b/icons/flags/Puerto_Rico.gif Binary files differindex 6d5d589..6d5d589 100644..100755 --- a/icons/flags/Puerto_Rico.gif +++ b/icons/flags/Puerto_Rico.gif diff --git a/icons/flags/Qatar.gif b/icons/flags/Qatar.gif Binary files differindex 2e843ff..2e843ff 100644..100755 --- a/icons/flags/Qatar.gif +++ b/icons/flags/Qatar.gif diff --git a/icons/flags/README b/icons/flags/README index b50d716..b50d716 100644..100755 --- a/icons/flags/README +++ b/icons/flags/README diff --git a/icons/flags/Romania.gif b/icons/flags/Romania.gif Binary files differindex f5d5f12..f5d5f12 100644..100755 --- a/icons/flags/Romania.gif +++ b/icons/flags/Romania.gif diff --git a/icons/flags/Russian_Federation.gif b/icons/flags/Russian_Federation.gif Binary files differindex b525c46..b525c46 100644..100755 --- a/icons/flags/Russian_Federation.gif +++ b/icons/flags/Russian_Federation.gif diff --git a/icons/flags/Rwanda.gif b/icons/flags/Rwanda.gif Binary files differindex 0d095f7..0d095f7 100644..100755 --- a/icons/flags/Rwanda.gif +++ b/icons/flags/Rwanda.gif diff --git a/icons/flags/S._Georgia_and_S._Sandwich_Isls..gif b/icons/flags/S._Georgia_and_S._Sandwich_Isls..gif Binary files differindex ccc96ec..ccc96ec 100644..100755 --- a/icons/flags/S._Georgia_and_S._Sandwich_Isls..gif +++ b/icons/flags/S._Georgia_and_S._Sandwich_Isls..gif diff --git a/icons/flags/Saint_Helena.gif b/icons/flags/Saint_Helena.gif Binary files differindex dcc7f3b..dcc7f3b 100644..100755 --- a/icons/flags/Saint_Helena.gif +++ b/icons/flags/Saint_Helena.gif diff --git a/icons/flags/Saint_Kitts_and_Nevis_Anguilla.gif b/icons/flags/Saint_Kitts_and_Nevis_Anguilla.gif Binary files differindex bb9cc34..bb9cc34 100644..100755 --- a/icons/flags/Saint_Kitts_and_Nevis_Anguilla.gif +++ b/icons/flags/Saint_Kitts_and_Nevis_Anguilla.gif diff --git a/icons/flags/Saint_Lucia.gif b/icons/flags/Saint_Lucia.gif Binary files differindex d06b955..d06b955 100644..100755 --- a/icons/flags/Saint_Lucia.gif +++ b/icons/flags/Saint_Lucia.gif diff --git a/icons/flags/Saint_Pierre_and_Miquelon.gif b/icons/flags/Saint_Pierre_and_Miquelon.gif Binary files differindex 99bf6fd..99bf6fd 100644..100755 --- a/icons/flags/Saint_Pierre_and_Miquelon.gif +++ b/icons/flags/Saint_Pierre_and_Miquelon.gif diff --git a/icons/flags/Saint_Tome_and_Principe.gif b/icons/flags/Saint_Tome_and_Principe.gif Binary files differindex 4f1e6e0..4f1e6e0 100644..100755 --- a/icons/flags/Saint_Tome_and_Principe.gif +++ b/icons/flags/Saint_Tome_and_Principe.gif diff --git a/icons/flags/Saint_Vincent_and_Grenadines.gif b/icons/flags/Saint_Vincent_and_Grenadines.gif Binary files differindex 4821381..4821381 100644..100755 --- a/icons/flags/Saint_Vincent_and_Grenadines.gif +++ b/icons/flags/Saint_Vincent_and_Grenadines.gif diff --git a/icons/flags/Samoa.gif b/icons/flags/Samoa.gif Binary files differindex a51f939..a51f939 100644..100755 --- a/icons/flags/Samoa.gif +++ b/icons/flags/Samoa.gif diff --git a/icons/flags/San_Marino.gif b/icons/flags/San_Marino.gif Binary files differindex 04d98de..04d98de 100644..100755 --- a/icons/flags/San_Marino.gif +++ b/icons/flags/San_Marino.gif diff --git a/icons/flags/Saudi_Arabia.gif b/icons/flags/Saudi_Arabia.gif Binary files differindex 179961b..179961b 100644..100755 --- a/icons/flags/Saudi_Arabia.gif +++ b/icons/flags/Saudi_Arabia.gif diff --git a/icons/flags/Scotland.gif b/icons/flags/Scotland.gif Binary files differindex 03f3f1d..03f3f1d 100644..100755 --- a/icons/flags/Scotland.gif +++ b/icons/flags/Scotland.gif diff --git a/icons/flags/Senegal.gif b/icons/flags/Senegal.gif Binary files differindex 6dac870..6dac870 100644..100755 --- a/icons/flags/Senegal.gif +++ b/icons/flags/Senegal.gif diff --git a/icons/flags/Seychelles.gif b/icons/flags/Seychelles.gif Binary files differindex 31b4767..31b4767 100644..100755 --- a/icons/flags/Seychelles.gif +++ b/icons/flags/Seychelles.gif diff --git a/icons/flags/Sierra_Leone.gif b/icons/flags/Sierra_Leone.gif Binary files differindex f0f3492..f0f3492 100644..100755 --- a/icons/flags/Sierra_Leone.gif +++ b/icons/flags/Sierra_Leone.gif diff --git a/icons/flags/Singapore.gif b/icons/flags/Singapore.gif Binary files differindex 5663d39..5663d39 100644..100755 --- a/icons/flags/Singapore.gif +++ b/icons/flags/Singapore.gif diff --git a/icons/flags/Slovak_Republic.gif b/icons/flags/Slovak_Republic.gif Binary files differindex 1b3f22b..1b3f22b 100644..100755 --- a/icons/flags/Slovak_Republic.gif +++ b/icons/flags/Slovak_Republic.gif diff --git a/icons/flags/Slovakia.gif b/icons/flags/Slovakia.gif Binary files differindex 8172d02..8172d02 100644..100755 --- a/icons/flags/Slovakia.gif +++ b/icons/flags/Slovakia.gif diff --git a/icons/flags/Slovenia.gif b/icons/flags/Slovenia.gif Binary files differindex 23852b5..23852b5 100644..100755 --- a/icons/flags/Slovenia.gif +++ b/icons/flags/Slovenia.gif diff --git a/icons/flags/Solomon_Islands.gif b/icons/flags/Solomon_Islands.gif Binary files differindex 8f5ff83..8f5ff83 100644..100755 --- a/icons/flags/Solomon_Islands.gif +++ b/icons/flags/Solomon_Islands.gif diff --git a/icons/flags/Somalia.gif b/icons/flags/Somalia.gif Binary files differindex f196169..f196169 100644..100755 --- a/icons/flags/Somalia.gif +++ b/icons/flags/Somalia.gif diff --git a/icons/flags/South_Africa.gif b/icons/flags/South_Africa.gif Binary files differindex ede5258..ede5258 100644..100755 --- a/icons/flags/South_Africa.gif +++ b/icons/flags/South_Africa.gif diff --git a/icons/flags/South_Korea.gif b/icons/flags/South_Korea.gif Binary files differindex 1cddbe7..1cddbe7 100644..100755 --- a/icons/flags/South_Korea.gif +++ b/icons/flags/South_Korea.gif diff --git a/icons/flags/Spain.gif b/icons/flags/Spain.gif Binary files differindex c27d65e..c27d65e 100644..100755 --- a/icons/flags/Spain.gif +++ b/icons/flags/Spain.gif diff --git a/icons/flags/Sri_Lanka.gif b/icons/flags/Sri_Lanka.gif Binary files differindex 1b3ee7f..1b3ee7f 100644..100755 --- a/icons/flags/Sri_Lanka.gif +++ b/icons/flags/Sri_Lanka.gif diff --git a/icons/flags/Sudan.gif b/icons/flags/Sudan.gif Binary files differindex 53ae214..53ae214 100644..100755 --- a/icons/flags/Sudan.gif +++ b/icons/flags/Sudan.gif diff --git a/icons/flags/Suriname.gif b/icons/flags/Suriname.gif Binary files differindex 0f7499a..0f7499a 100644..100755 --- a/icons/flags/Suriname.gif +++ b/icons/flags/Suriname.gif diff --git a/icons/flags/Swaziland.gif b/icons/flags/Swaziland.gif Binary files differindex f37aaf8..f37aaf8 100644..100755 --- a/icons/flags/Swaziland.gif +++ b/icons/flags/Swaziland.gif diff --git a/icons/flags/Sweden.gif b/icons/flags/Sweden.gif Binary files differindex 80f6285..80f6285 100644..100755 --- a/icons/flags/Sweden.gif +++ b/icons/flags/Sweden.gif diff --git a/icons/flags/Switzerland.gif b/icons/flags/Switzerland.gif Binary files differindex d5c0e5b..d5c0e5b 100644..100755 --- a/icons/flags/Switzerland.gif +++ b/icons/flags/Switzerland.gif diff --git a/icons/flags/Syria.gif b/icons/flags/Syria.gif Binary files differindex dc8bd50..dc8bd50 100644..100755 --- a/icons/flags/Syria.gif +++ b/icons/flags/Syria.gif diff --git a/icons/flags/Tadjikistan.gif b/icons/flags/Tadjikistan.gif Binary files differindex 2fe38d4..2fe38d4 100644..100755 --- a/icons/flags/Tadjikistan.gif +++ b/icons/flags/Tadjikistan.gif diff --git a/icons/flags/Taiwan.gif b/icons/flags/Taiwan.gif Binary files differindex cacfd9b..cacfd9b 100644..100755 --- a/icons/flags/Taiwan.gif +++ b/icons/flags/Taiwan.gif diff --git a/icons/flags/Tanzania.gif b/icons/flags/Tanzania.gif Binary files differindex 82b52ca..82b52ca 100644..100755 --- a/icons/flags/Tanzania.gif +++ b/icons/flags/Tanzania.gif diff --git a/icons/flags/Thailand.gif b/icons/flags/Thailand.gif Binary files differindex 0130792..0130792 100644..100755 --- a/icons/flags/Thailand.gif +++ b/icons/flags/Thailand.gif diff --git a/icons/flags/Togo.gif b/icons/flags/Togo.gif Binary files differindex ca6b4e7..ca6b4e7 100644..100755 --- a/icons/flags/Togo.gif +++ b/icons/flags/Togo.gif diff --git a/icons/flags/Tokelau.gif b/icons/flags/Tokelau.gif Binary files differindex 3d3a727..3d3a727 100644..100755 --- a/icons/flags/Tokelau.gif +++ b/icons/flags/Tokelau.gif diff --git a/icons/flags/Tonga.gif b/icons/flags/Tonga.gif Binary files differindex d7ed4d1..d7ed4d1 100644..100755 --- a/icons/flags/Tonga.gif +++ b/icons/flags/Tonga.gif diff --git a/icons/flags/Trinidad_and_Tobago.gif b/icons/flags/Trinidad_and_Tobago.gif Binary files differindex 47d3b80..47d3b80 100644..100755 --- a/icons/flags/Trinidad_and_Tobago.gif +++ b/icons/flags/Trinidad_and_Tobago.gif diff --git a/icons/flags/Tunisia.gif b/icons/flags/Tunisia.gif Binary files differindex 917d428..917d428 100644..100755 --- a/icons/flags/Tunisia.gif +++ b/icons/flags/Tunisia.gif diff --git a/icons/flags/Turkey.gif b/icons/flags/Turkey.gif Binary files differindex e407d55..e407d55 100644..100755 --- a/icons/flags/Turkey.gif +++ b/icons/flags/Turkey.gif diff --git a/icons/flags/Turkmenistan.gif b/icons/flags/Turkmenistan.gif Binary files differindex 36d0994..36d0994 100644..100755 --- a/icons/flags/Turkmenistan.gif +++ b/icons/flags/Turkmenistan.gif diff --git a/icons/flags/Turks_and_Caicos_Islands.gif b/icons/flags/Turks_and_Caicos_Islands.gif Binary files differindex 11a8c23..11a8c23 100644..100755 --- a/icons/flags/Turks_and_Caicos_Islands.gif +++ b/icons/flags/Turks_and_Caicos_Islands.gif diff --git a/icons/flags/Tuvalu.gif b/icons/flags/Tuvalu.gif Binary files differindex 3c33827..3c33827 100644..100755 --- a/icons/flags/Tuvalu.gif +++ b/icons/flags/Tuvalu.gif diff --git a/icons/flags/Uganda.gif b/icons/flags/Uganda.gif Binary files differindex 58b731a..58b731a 100644..100755 --- a/icons/flags/Uganda.gif +++ b/icons/flags/Uganda.gif diff --git a/icons/flags/Ukraine.gif b/icons/flags/Ukraine.gif Binary files differindex 5d6cd83..5d6cd83 100644..100755 --- a/icons/flags/Ukraine.gif +++ b/icons/flags/Ukraine.gif diff --git a/icons/flags/United_Arab_Emirates.gif b/icons/flags/United_Arab_Emirates.gif Binary files differindex 78d15b6..78d15b6 100644..100755 --- a/icons/flags/United_Arab_Emirates.gif +++ b/icons/flags/United_Arab_Emirates.gif diff --git a/icons/flags/United_Kingdom.gif b/icons/flags/United_Kingdom.gif Binary files differindex 3e16ff8..3e16ff8 100644..100755 --- a/icons/flags/United_Kingdom.gif +++ b/icons/flags/United_Kingdom.gif diff --git a/icons/flags/United_States.gif b/icons/flags/United_States.gif Binary files differindex 8f198f7..8f198f7 100644..100755 --- a/icons/flags/United_States.gif +++ b/icons/flags/United_States.gif diff --git a/icons/flags/Uruguay.gif b/icons/flags/Uruguay.gif Binary files differindex 12848c7..12848c7 100644..100755 --- a/icons/flags/Uruguay.gif +++ b/icons/flags/Uruguay.gif diff --git a/icons/flags/Uzbekistan.gif b/icons/flags/Uzbekistan.gif Binary files differindex dc9daec..dc9daec 100644..100755 --- a/icons/flags/Uzbekistan.gif +++ b/icons/flags/Uzbekistan.gif diff --git a/icons/flags/Vanuatu.gif b/icons/flags/Vanuatu.gif Binary files differindex 8a8b2b0..8a8b2b0 100644..100755 --- a/icons/flags/Vanuatu.gif +++ b/icons/flags/Vanuatu.gif diff --git a/icons/flags/Venezuela.gif b/icons/flags/Venezuela.gif Binary files differindex 19ce6c1..19ce6c1 100644..100755 --- a/icons/flags/Venezuela.gif +++ b/icons/flags/Venezuela.gif diff --git a/icons/flags/Vietnam.gif b/icons/flags/Vietnam.gif Binary files differindex f1e20c9..f1e20c9 100644..100755 --- a/icons/flags/Vietnam.gif +++ b/icons/flags/Vietnam.gif diff --git a/icons/flags/Virgin_Islands.gif b/icons/flags/Virgin_Islands.gif Binary files differindex 66f9e74..66f9e74 100644..100755 --- a/icons/flags/Virgin_Islands.gif +++ b/icons/flags/Virgin_Islands.gif diff --git a/icons/flags/Wales.gif b/icons/flags/Wales.gif Binary files differindex 901d175..901d175 100644..100755 --- a/icons/flags/Wales.gif +++ b/icons/flags/Wales.gif diff --git a/icons/flags/Wallis_and_Futuna_Islands.gif b/icons/flags/Wallis_and_Futuna_Islands.gif Binary files differindex eaa954b..eaa954b 100644..100755 --- a/icons/flags/Wallis_and_Futuna_Islands.gif +++ b/icons/flags/Wallis_and_Futuna_Islands.gif diff --git a/icons/flags/Western_Sahara.gif b/icons/flags/Western_Sahara.gif Binary files differindex dd0391c..dd0391c 100644..100755 --- a/icons/flags/Western_Sahara.gif +++ b/icons/flags/Western_Sahara.gif diff --git a/icons/flags/Yemen.gif b/icons/flags/Yemen.gif Binary files differindex 7b0183d..7b0183d 100644..100755 --- a/icons/flags/Yemen.gif +++ b/icons/flags/Yemen.gif diff --git a/icons/flags/Zambia.gif b/icons/flags/Zambia.gif Binary files differindex b2851d2..b2851d2 100644..100755 --- a/icons/flags/Zambia.gif +++ b/icons/flags/Zambia.gif diff --git a/icons/flags/Zimbabwe.gif b/icons/flags/Zimbabwe.gif Binary files differindex 02901f6..02901f6 100644..100755 --- a/icons/flags/Zimbabwe.gif +++ b/icons/flags/Zimbabwe.gif diff --git a/icons/flags/au.gif b/icons/flags/au.gif Binary files differindex 5269c6a..5269c6a 100644..100755 --- a/icons/flags/au.gif +++ b/icons/flags/au.gif diff --git a/icons/flags/ca.gif b/icons/flags/ca.gif Binary files differindex 457d966..457d966 100644..100755 --- a/icons/flags/ca.gif +++ b/icons/flags/ca.gif diff --git a/icons/flags/de.gif b/icons/flags/de.gif Binary files differindex 75728dd..75728dd 100644..100755 --- a/icons/flags/de.gif +++ b/icons/flags/de.gif diff --git a/icons/flags/index.php b/icons/flags/index.php index 3e305fe..c0437d0 100644 --- a/icons/flags/index.php +++ b/icons/flags/index.php @@ -1,4 +1,4 @@ -<?php +<?php // This is not a package. header ("location: ../index.php"); diff --git a/icons/flags/uk.gif b/icons/flags/uk.gif Binary files differindex 3e16ff8..3e16ff8 100644..100755 --- a/icons/flags/uk.gif +++ b/icons/flags/uk.gif diff --git a/icons/flags/us.gif b/icons/flags/us.gif Binary files differindex 8f198f7..8f198f7 100644..100755 --- a/icons/flags/us.gif +++ b/icons/flags/us.gif diff --git a/icons/groups.gif b/icons/groups.gif Binary files differindex 25176ba..25176ba 100644..100755 --- a/icons/groups.gif +++ b/icons/groups.gif diff --git a/icons/groups.png b/icons/groups.png Binary files differindex c976fbd..c976fbd 100644..100755 --- a/icons/groups.png +++ b/icons/groups.png diff --git a/icons/index.php b/icons/index.php index 3e305fe..c0437d0 100644 --- a/icons/index.php +++ b/icons/index.php @@ -1,4 +1,4 @@ -<?php +<?php // This is not a package. header ("location: ../index.php"); diff --git a/icons/pkg_users.gif b/icons/pkg_users.gif Binary files differindex 026add1..026add1 100644..100755 --- a/icons/pkg_users.gif +++ b/icons/pkg_users.gif diff --git a/icons/pkg_users.png b/icons/pkg_users.png Binary files differindex b1fd4eb..b1fd4eb 100644..100755 --- a/icons/pkg_users.png +++ b/icons/pkg_users.png diff --git a/icons/silhouette.png b/icons/silhouette.png Binary files differindex 992295f..992295f 100644..100755 --- a/icons/silhouette.png +++ b/icons/silhouette.png diff --git a/icons/silhouette_100.png b/icons/silhouette_100.png Binary files differindex d6391d5..d6391d5 100644..100755 --- a/icons/silhouette_100.png +++ b/icons/silhouette_100.png diff --git a/icons/unknown_user.jpg b/icons/unknown_user.jpg Binary files differindex c1cacc1..c1cacc1 100644..100755 --- a/icons/unknown_user.jpg +++ b/icons/unknown_user.jpg diff --git a/includes/bit_setup_inc.php b/includes/bit_setup_inc.php index 3760a3c..979ac5b 100755 --- a/includes/bit_setup_inc.php +++ b/includes/bit_setup_inc.php @@ -33,7 +33,7 @@ $gLibertySystem->registerService( CONTENT_SERVICE_USERS_FAVS, ], [ 'description' => KernelTools::tra( 'Provides a ajax service enabling users to bookmark any content as a favorite.' ), - ] + ], ); $gBitSystem->registerNotifyEvent( [ "user_registers" => KernelTools::tra( "A user registers" ) ] ); diff --git a/includes/classes/BitAuth.php b/includes/classes/BitAuth.php index ad2ecac..9ef9678 100755 --- a/includes/classes/BitAuth.php +++ b/includes/classes/BitAuth.php @@ -34,7 +34,7 @@ class BitAuth extends BaseAuth { $loginCol = ' UPPER(`'.(strpos( $user, '@' ) ? 'email' : 'login').'`)'; // first verify that the user exists $query = "select `email`, `login`, `user_id`, `user_password` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?"; - $result = $gBitDb->query( $query, array( $loginVal ) ); + $result = $gBitDb->query( $query, [ $loginVal ] ); if( !$result->numRows() ) { $this->mErrors['login'] = 'User not found'; } else { @@ -48,7 +48,7 @@ class BitAuth extends BaseAuth { // TODO - this needs cleaning up - wolff_borg if( !$gBitSystem->isFeatureActive( 'feature_challenge' ) || empty($response) ) { $query = "select `user_id`, `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ? and (`hash`=? or `hash`=?)"; - if ( $row = $gBitDb->getRow( $query, array( $loginVal, $hash, $hash2 ) ) ) { + if ( $row = $gBitDb->getRow( $query, [ $loginVal, $hash, $hash2 ] ) ) { // auto-update old hashes with simple and standard md5( password ) $hashUpdate = ''; if( $row['hash'] == $hash ) { @@ -67,7 +67,7 @@ class BitAuth extends BaseAuth { } else { // Use challenge-reponse method // Compare pass against md5(user,challenge,hash) - $hash = $gBitDb->getOne("select `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?", array( $user ) ); + $hash = $gBitDb->getOne("select `hash` from `".BIT_DB_PREFIX."users_users` where " . $gBitDb->convertBinary(). " $loginCol = ?", [ $user ] ); if (!isset($_SESSION["challenge"])) { $this->mErrors[] = 'Invalid challenge'; $ret=PASSWORD_INCORRECT; diff --git a/includes/classes/BitHybridAuthManager.php b/includes/classes/BitHybridAuthManager.php index fc9d853..7eba4bc 100755 --- a/includes/classes/BitHybridAuthManager.php +++ b/includes/classes/BitHybridAuthManager.php @@ -8,6 +8,7 @@ */ namespace Bitweaver\Users; + require_once USERS_PKG_PATH.'hauth/Hybrid/Auth.php'; if( file_exists( EXTERNAL_LIBS_PATH.'facebook/src/Facebook/autoload.php' ) ) { @@ -17,7 +18,7 @@ if( file_exists( EXTERNAL_LIBS_PATH.'facebook/src/Facebook/autoload.php' ) ) { class BitHybridAuthManager extends \Bitweaver\BitSingleton { private $mEnabledProviders = []; - + /** * Constructor * Loads user configuration and strategies. @@ -35,7 +36,7 @@ class BitHybridAuthManager extends \Bitweaver\BitSingleton { } public function __sleep() { - return array_merge( parent::__sleep(), array( 'mEnabledProviders' ) ); + return array_merge( parent::__sleep(), [ 'mEnabledProviders' ] ); } /** @@ -53,8 +54,8 @@ class BitHybridAuthManager extends \Bitweaver\BitSingleton { if( $authProfile = $authedProvider->getUserProfile() ) { $ret = $authProfile; $this->cacheUserProfile( $pProvider, $authProfile ); - if( ($userId = $this->mDb->getOne( "SELECT `user_id` FROM `".BIT_DB_PREFIX."users_auth_map` uam WHERE uam.`provider`=? AND uam.`provider_identifier`=?", array( $pProvider, $authProfile->identifier ) )) > ROOT_USER_ID ) { - } elseif( $authProfile->emailVerified && ($userId = $this->mDb->getOne( "SELECT uu.`user_id` FROM `".BIT_DB_PREFIX."users_users` uu WHERE uu.`email`=?", array( $authProfile->emailVerified ) )) > ROOT_USER_ID ) { + if( ($userId = $this->mDb->getOne( "SELECT `user_id` FROM `".BIT_DB_PREFIX."users_auth_map` uam WHERE uam.`provider`=? AND uam.`provider_identifier`=?", [ $pProvider, $authProfile->identifier ] )) > ROOT_USER_ID ) { + } elseif( $authProfile->emailVerified && ($userId = $this->mDb->getOne( "SELECT uu.`user_id` FROM `".BIT_DB_PREFIX."users_users` uu WHERE uu.`email`=?", [ $authProfile->emailVerified ] )) > ROOT_USER_ID ) { } else { $ret = $authProfile; } @@ -83,7 +84,7 @@ class BitHybridAuthManager extends \Bitweaver\BitSingleton { apc_delete( $cacheKey ); } $query = "DELETE FROM `".BIT_DB_PREFIX."users_auth_map` WHERE `user_id`=? AND `provider`=?"; - $result = $this->mDb->query( $query, array( $pUserId, $pProvider ) ); + $result = $this->mDb->query( $query, [ $pUserId, $pProvider ] ); } } @@ -91,12 +92,12 @@ class BitHybridAuthManager extends \Bitweaver\BitSingleton { if( \Bitweaver\BitBase::verifyId( $pUserId ) && !empty( $pProvider ) && !empty( $pIdentifier ) ) { $this->StartTrans(); $query = "DELETE FROM `".BIT_DB_PREFIX."users_auth_map` WHERE `user_id`=? AND `provider`=?"; - $result = $this->mDb->query( $query, array( $pUserId, $pProvider ) ); + $result = $this->mDb->query( $query, [ $pUserId, $pProvider ] ); if( !is_null( $pIdentifier ) ) { $profileHash = get_object_vars( $pAuthProfile ); ksort( $profileHash ); $query = "INSERT INTO `".BIT_DB_PREFIX."users_auth_map` (`user_id`,`provider`,`provider_identifier`,`last_login`,`profile_json`) VALUES(?, ?, ?, ?, ?)"; - $result = $this->mDb->query( $query, array( $pUserId, $pProvider, $pIdentifier, time(), json_encode( $profileHash ) ) ); + $result = $this->mDb->query( $query, [ $pUserId, $pProvider, $pIdentifier, time(), json_encode( $profileHash ) ] ); } $this->CompleteTrans(); } @@ -123,7 +124,7 @@ class BitHybridAuthManager extends \Bitweaver\BitSingleton { global $gBitUser; $pUserId = $gBitUser->mUserId; } - if( $ret = $this->mDb->getRow( "SELECT * FROM `".BIT_DB_PREFIX."users_auth_map` WHERE `user_id`=? AND `provider`=?", array( $pUserId, $pProvider ) ) ) { + if( $ret = $this->mDb->getRow( "SELECT * FROM `".BIT_DB_PREFIX."users_auth_map` WHERE `user_id`=? AND `provider`=?", [ $pUserId, $pProvider ] ) ) { $ret['profile_hash'] = json_decode( $ret['profile_json'], true ); } } catch( \Exception $e ) { @@ -133,15 +134,15 @@ class BitHybridAuthManager extends \Bitweaver\BitSingleton { } public function getHybridAuth() { - $config = array( + $config = [ // "base_url" the url that point to HybridAuth Endpoint (where the index.php and config.php are found) "base_url" => USERS_PKG_URI.'hauth/', "debug_mode" => true, "debug_file" => sys_get_temp_dir().'/hybridauth_log', - ); + ]; foreach( $this->mEnabledProviders as $providerKey => $providerHash ) { - $config['providers'][$providerHash['provider']] = array ( "enabled" => true ); + $config['providers'][$providerHash['provider']] = [ "enabled" => true ]; foreach( array_keys( $providerHash['keys'] ) as $configKey ) { $config['providers'][$providerHash['provider']]['keys'][$configKey] = $this->getProviderConfig( $providerKey, $configKey ); } @@ -218,29 +219,28 @@ class BitHybridAuthManager extends \Bitweaver\BitSingleton { public function scanProviders() { $ret = []; - if( $providerFiles = array_diff(scandir( $this->getProviderPath() ), array('..', '.')) ) { + if( $providerFiles = array_diff(scandir( $this->getProviderPath() ), ['..', '.']) ) { foreach( $providerFiles as $providerFile ) { require_once $this->getProviderFile( $provider ); } } } - public function getAllProviders() { - return array ( - 'google' => array( 'provider' => 'Google', 'icon' => 'icon-google-plus-sign', 'image' => USERS_PKG_URL.'hauth/images/google.png', 'keys' => array( 'id'=>'', 'secret'=> '' ) ), - 'amazon' => array( 'provider' => 'Amazon', 'icon' => 'icon-user', 'keys' => array( 'id'=>'', 'secret'=> '' ) ), - 'aol' => array( 'provider' => 'AOL', 'icon' => 'icon-user', 'keys' => array( 'id'=>'', 'secret'=> '' ) ), - 'facebook' => array( 'provider' => 'Facebook', 'icon' => 'icon-facebook-sign', 'keys' => array( 'id'=>'', 'secret'=> '' ), 'options' => array( 'scope'=>'Comma separated list of requested permissions. Default are: email, user_about_me, user_birthday, user_hometown, user_location, user_website, publish_actions, read_custom_friendlists' ) ), - 'foursquare' => array( 'provider' => 'Foursquare', 'icon' => 'icon-foursquare', 'keys' => array( 'id'=>'', 'secret'=> '' ) ), - 'instagram' => array( 'provider' => 'Instagram', 'icon' => 'icon-instagram', 'keys' => array( 'id'=>'', 'secret'=> '' ) ), - 'linkedin' => array( 'provider' => 'LinkedIn', 'icon' => 'icon-linkedin', 'keys' => array( 'key'=>'', 'secret'=> '' ) ), - 'live' => array( 'provider' => 'Live', 'icon' => 'icon-windows', 'keys' => array( 'id'=>'', 'secret'=> '' ) ), - 'openid' => array( 'provider' => 'OpenID', 'icon' => 'icon-user', 'keys' => array( 'id'=>'', 'secret'=> '' ) ), - 'paypal' => array( 'provider' => 'Paypal', 'icon' => 'icon-user', 'keys' => array( 'id'=>'', 'secret'=> '' ) ), - 'twitter' => array( 'provider' => 'Twitter', 'icon' => 'icon-twitter', 'keys' => array( 'key'=>'', 'secret'=> '' ) ), - 'yahoo' => array( 'provider' => 'Yahoo', 'icon' => 'icon-user', 'keys' => array( 'id'=>'', 'secret'=> '' ) ), - ); + return [ + 'google' => [ 'provider' => 'Google', 'icon' => 'icon-google-plus-sign', 'image' => USERS_PKG_URL.'hauth/images/google.png', 'keys' => [ 'id'=>'', 'secret'=> '' ] ], + 'amazon' => [ 'provider' => 'Amazon', 'icon' => 'icon-user', 'keys' => [ 'id'=>'', 'secret'=> '' ] ], + 'aol' => [ 'provider' => 'AOL', 'icon' => 'icon-user', 'keys' => [ 'id'=>'', 'secret'=> '' ] ], + 'facebook' => [ 'provider' => 'Facebook', 'icon' => 'icon-facebook-sign', 'keys' => [ 'id'=>'', 'secret'=> '' ], 'options' => [ 'scope'=>'Comma separated list of requested permissions. Default are: email, user_about_me, user_birthday, user_hometown, user_location, user_website, publish_actions, read_custom_friendlists' ] ], + 'foursquare' => [ 'provider' => 'Foursquare', 'icon' => 'icon-foursquare', 'keys' => [ 'id'=>'', 'secret'=> '' ] ], + 'instagram' => [ 'provider' => 'Instagram', 'icon' => 'icon-instagram', 'keys' => [ 'id'=>'', 'secret'=> '' ] ], + 'linkedin' => [ 'provider' => 'LinkedIn', 'icon' => 'icon-linkedin', 'keys' => [ 'key'=>'', 'secret'=> '' ] ], + 'live' => [ 'provider' => 'Live', 'icon' => 'icon-windows', 'keys' => [ 'id'=>'', 'secret'=> '' ] ], + 'openid' => [ 'provider' => 'OpenID', 'icon' => 'icon-user', 'keys' => [ 'id'=>'', 'secret'=> '' ] ], + 'paypal' => [ 'provider' => 'Paypal', 'icon' => 'icon-user', 'keys' => [ 'id'=>'', 'secret'=> '' ] ], + 'twitter' => [ 'provider' => 'Twitter', 'icon' => 'icon-twitter', 'keys' => [ 'key'=>'', 'secret'=> '' ] ], + 'yahoo' => [ 'provider' => 'Yahoo', 'icon' => 'icon-user', 'keys' => [ 'id'=>'', 'secret'=> '' ] ], + ]; } - + } diff --git a/includes/classes/BitPermUser.php b/includes/classes/BitPermUser.php index 16597d5..61738cb 100755 --- a/includes/classes/BitPermUser.php +++ b/includes/classes/BitPermUser.php @@ -51,7 +51,7 @@ class BitPermUser extends BitUser { } public function __sleep() { - return array_merge( parent::__sleep(), array( 'mPerms' ) ); + return array_merge( parent::__sleep(), [ 'mPerms' ] ); } public function __wakeup() { @@ -80,7 +80,7 @@ class BitPermUser extends BitUser { if( $assumeUser->isAdmin() ) { $this->mErrors['assume_user'] = KernelTools::tra( "User administrators cannot be assumed." ); } else { - $this->mDb->query( "UPDATE `".BIT_DB_PREFIX."users_cnxn` SET `user_id`=?, `assume_user_id`=? WHERE `cookie`=?", array( $pUserId, $gBitUser->mUserId, $_COOKIE[$this->getSiteCookieName()] ) ); + $this->mDb->query( "UPDATE `".BIT_DB_PREFIX."users_cnxn` SET `user_id`=?, `assume_user_id`=? WHERE `cookie`=?", [ $pUserId, $gBitUser->mUserId, $_COOKIE[$this->getSiteCookieName()] ] ); $ret = true; } } @@ -115,7 +115,7 @@ class BitPermUser extends BitUser { function sanitizeUserInfo() { if (!empty( $this->mInfo )) { - $unsanitary = array( 'provpass', 'hash', 'challenge', 'user_password' ); + $unsanitary = [ 'provpass', 'hash', 'challenge', 'user_password' ]; foreach ( array_keys( $this->mInfo ) as $key ) { if (in_array( $key, $unsanitary )) { unset( $this->mInfo[$key] ); @@ -141,11 +141,11 @@ class BitPermUser extends BitUser { $this->addUserToGroup( $this->mUserId, $defaultGroups ); if ($gBitSystem->isFeatureActive( 'users_eponymous_groups' )) { // Create a group just for this user, for permissions assignment. - $groupParams = array( + $groupParams = [ 'user_id' => $this->mUserId, 'name' => $pParamHash['user_store']['login'], - 'desc' => "Personal group for " . ( !empty( $pParamHash['user_store']['real_name'] ) ? $pParamHash['user_store']['real_name'] : $pParamHash['user_store']['login'] ) - ); + 'desc' => "Personal group for " . ( !empty( $pParamHash['user_store']['real_name'] ) ? $pParamHash['user_store']['real_name'] : $pParamHash['user_store']['login'] ), + ]; if ($this->storeGroup( $groupParams )) { $this->addUserToGroup( $this->mUserId, $groupParams['group_id'] ); } @@ -172,7 +172,7 @@ class BitPermUser extends BitUser { { static $sGroups = []; if (!isset( $sGroups[$pUserId][$pGroupName] )) { - $bindVars = array( $pGroupName ); + $bindVars = [ $pGroupName ]; $whereSql = ''; if ($pUserId != '*') { $whereSql = 'AND `user_id`=?'; @@ -212,22 +212,22 @@ class BitPermUser extends BitUser { $gBitSystem->fatalError( KernelTools::tra( 'You cannot delete yourself' ) ); } elseif ($this->mUserId != ANONYMOUS_USER_ID) { - $userTables = array( + $userTables = [ 'users_groups_map', - ); + ]; foreach ( $userTables as $table ) { $query = "DELETE FROM `" . BIT_DB_PREFIX . $table . "` WHERE `user_id` = ?"; - $result = $this->mDb->query( $query, array( $this->mUserId ) ); + $result = $this->mDb->query( $query, [ $this->mUserId ] ); } if ( parent::expunge() ) { $this->CompleteTrans(); return true; } - else { + $this->mDb->RollbackTrans(); - } + } else { $this->mDb->RollbackTrans(); @@ -342,7 +342,7 @@ class BitPermUser extends BitUser { while ( $row = $rs->fetchRow() ) { $groupId = $row['group_id']; $ret[$groupId] = $row; - $ret[$groupId]['perms'] = $this->getGroupPermissions( array( 'group_id' => $groupId ) ); + $ret[$groupId]['perms'] = $this->getGroupPermissions( [ 'group_id' => $groupId ] ); } } @@ -368,7 +368,7 @@ class BitPermUser extends BitUser { SELECT ug.`group_id` AS `hash_key`, ug.* FROM `" . BIT_DB_PREFIX . "users_groups` ug WHERE `user_id`=? ORDER BY ug.`group_name` ASC"; - return $this->mDb->getAssoc( $sql, array( $pUserId ) ); + return $this->mDb->getAssoc( $sql, [ $pUserId ] ); } /** @@ -383,11 +383,11 @@ class BitPermUser extends BitUser { // we cannot remove the anonymous group if ($pGroupId != ANONYMOUS_GROUP_ID) { $query = "DELETE FROM `" . BIT_DB_PREFIX . "users_groups_map` WHERE `group_id` = ?"; - $result = $this->mDb->query( $query, array( $pGroupId ) ); + $result = $this->mDb->query( $query, [ $pGroupId ] ); $query = "DELETE FROM `" . BIT_DB_PREFIX . "users_group_permissions` WHERE `group_id` = ?"; - $result = $this->mDb->query( $query, array( $pGroupId ) ); + $result = $this->mDb->query( $query, [ $pGroupId ] ); $query = "DELETE FROM `" . BIT_DB_PREFIX . "users_groups` WHERE `group_id` = ?"; - $result = $this->mDb->query( $query, array( $pGroupId ) ); + $result = $this->mDb->query( $query, [ $pGroupId ] ); return true; } } @@ -405,7 +405,7 @@ class BitPermUser extends BitUser { $whereSql = ''; if (\Bitweaver\BitBase::verifyId( $pGroupId )) { $whereSql = "AND `group_id`=? "; - $bindvars = array( $pGroupId ); + $bindvars = [ $pGroupId ]; } return $this->mDb->getAssoc( "SELECT `group_id`, `group_name` FROM `" . BIT_DB_PREFIX . "users_groups` WHERE `is_default` = 'y' $whereSql ", $bindvars ); } @@ -426,7 +426,7 @@ class BitPermUser extends BitUser { FROM `" . BIT_DB_PREFIX . "users_users` uu INNER JOIN `" . BIT_DB_PREFIX . "users_groups_map` ug ON (uu.`user_id`=ug.`user_id`) WHERE `group_id`=?"; - $ret = $this->mDb->getAssoc( $query, array( $pGroupId ) ); + $ret = $this->mDb->getAssoc( $query, [ $pGroupId ] ); } return $ret; } @@ -443,7 +443,7 @@ class BitPermUser extends BitUser { $ret = false; if (\Bitweaver\BitBase::verifyId( $pGroupId )) { $query = "SELECT `group_home` FROM `" . BIT_DB_PREFIX . "users_groups` WHERE `group_id`=?"; - $ret = $this->mDb->getOne( $query, array( $pGroupId ) ); + $ret = $this->mDb->getOne( $query, [ $pGroupId ] ); } return $ret; } @@ -510,7 +510,7 @@ class BitPermUser extends BitUser { * @return array group information */ public function getGroupInfo( $pGroupId ) :array - { + { if (\Bitweaver\BitBase::verifyId( $pGroupId )) { $sql = "SELECT * FROM `" . BIT_DB_PREFIX . "users_groups` WHERE `group_id` = ?"; $ret = $this->mDb->getRow( $sql, [ $pGroupId ] ); @@ -547,13 +547,13 @@ class BitPermUser extends BitUser { $addGroups = array_keys( $pGroupMixed ); } elseif (\Bitweaver\BitBase::verifyId( $pGroupMixed )) { - $addGroups = array( $pGroupMixed ); + $addGroups = [ $pGroupMixed ]; } $currentUserGroups = $this->getGroups( $pUserId ); foreach ( $addGroups as $groupId ) { - if (!$this->mDb->getOne( "SELECT group_id FROM `" . BIT_DB_PREFIX . "users_groups_map` WHERE `user_id` = ? AND `group_id` = ?", array( $pUserId, $groupId ) )) { + if (!$this->mDb->getOne( "SELECT group_id FROM `" . BIT_DB_PREFIX . "users_groups_map` WHERE `user_id` = ? AND `group_id` = ?", [ $pUserId, $groupId ] )) { $query = "INSERT INTO `" . BIT_DB_PREFIX . "users_groups_map` (`user_id`,`group_id`) VALUES(?,?)"; - $result = $this->mDb->query( $query, array( $pUserId, $groupId ) ); + $result = $this->mDb->query( $query, [ $pUserId, $groupId ] ); } } } @@ -635,9 +635,9 @@ class BitPermUser extends BitUser { } else { $sql = "SELECT COUNT(*) FROM `" . BIT_DB_PREFIX . "users_groups` WHERE `group_id` = ?"; - $groupExists = $this->mDb->getOne( $sql, array( $pParamHash['group_id'] ) ); + $groupExists = $this->mDb->getOne( $sql, [ $pParamHash['group_id'] ] ); if ($groupExists) { - $result = $this->mDb->associateUpdate( BIT_DB_PREFIX . 'users_groups', $pParamHash['group_store'], array( "group_id" => $pParamHash['group_id'] ) ); + $result = $this->mDb->associateUpdate( BIT_DB_PREFIX . 'users_groups', $pParamHash['group_store'], [ "group_id" => $pParamHash['group_id'] ] ); } else { // A group_id was specified but that group does not exist yet @@ -667,7 +667,7 @@ class BitPermUser extends BitUser { $ret = ''; if (static::verifyId( $pGroupId )) { global $gBitDb; - $ret = $gBitDb->getOne( "SELECT `group_name` FROM `" . BIT_DB_PREFIX . "users_groups` WHERE `group_id`=?", array( $pGroupId ) ); + $ret = $gBitDb->getOne( "SELECT `group_name` FROM `" . BIT_DB_PREFIX . "users_groups` WHERE `group_id`=?", [ $pGroupId ] ); } return $ret; } @@ -697,7 +697,7 @@ class BitPermUser extends BitUser { FROM `" . BIT_DB_PREFIX . "users_users` uu INNER JOIN `" . BIT_DB_PREFIX . "users_groups_map` ugm ON (uu.`user_id`=ugm.`user_id`) WHERE ugm.`group_id` = ?"; - $ret = $this->mDb->$exec( $query, array( $pGroupId ) ); + $ret = $this->mDb->$exec( $query, [ $pGroupId ] ); } return $ret; } @@ -721,7 +721,7 @@ class BitPermUser extends BitUser { INNER JOIN `" . BIT_DB_PREFIX . "users_groups` ug ON ( ug.`group_id`=ugp.`group_id` ) LEFT OUTER JOIN `" . BIT_DB_PREFIX . "users_groups_map` ugm ON ( ugm.`group_id`=ugp.`group_id` AND ugm.`user_id` = ? ) WHERE ug.`group_id`= " . ANONYMOUS_GROUP_ID . " OR ugm.`group_id`=ug.`group_id`"; - $this->mPerms = $this->mDb->getAssoc( $query, array( $this->mUserId ) ); + $this->mPerms = $this->mDb->getAssoc( $query, [ $this->mUserId ] ); // Add in override permissions if (!empty( $this->mPermsOverride )) { foreach ( $this->mPermsOverride as $key => $val ) { @@ -745,7 +745,7 @@ class BitPermUser extends BitUser { LEFT OUTER JOIN `" . BIT_DB_PREFIX . "users_group_permissions` ugp ON( up.`perm_name` = ugp.`perm_name` ) WHERE ugp.`group_id` IS null AND up.`perm_name` <> ? ORDER BY `package`, up.`perm_name` ASC"; - return $this->mDb->getAssoc( $query, array( '' ) ); + return $this->mDb->getAssoc( $query, [ '' ] ); } /** @@ -793,9 +793,9 @@ class BitPermUser extends BitUser { if (empty( $pPermission ) || $this->hasPermission( $pPermission )) { return; } - else { + $gBitSystem->fatalPermission( $pPermission, $pMsg ); - } + } /** @@ -874,7 +874,7 @@ class BitPermUser extends BitUser { function assignLevelPermissions( $pGroupId, $pLevel, $pPackage = null ) { if (\Bitweaver\BitBase::verifyId( $pGroupId ) && !empty( $pLevel )) { - $bindvars = array( $pLevel ); + $bindvars = [ $pLevel ]; $whereSql = ''; if (!empty( $pPackage )) { $whereSql = ' AND `package`=?'; @@ -911,9 +911,9 @@ class BitPermUser extends BitUser { function assignPermissionToGroup( $pPerm, $pGroupId ) { if( \Bitweaver\BitBase::verifyId( $pGroupId ) && !empty( $pPerm )) { $query = "DELETE FROM `".BIT_DB_PREFIX."users_group_permissions` WHERE `group_id` = ? AND `perm_name` = ?"; - $result = $this->mDb->query( $query, array( $pGroupId, $pPerm )); + $result = $this->mDb->query( $query, [ $pGroupId, $pPerm ]); $query = "INSERT INTO `".BIT_DB_PREFIX."users_group_permissions`(`group_id`, `perm_name`) VALUES(?, ?)"; - $result = $this->mDb->query( $query, array( $pGroupId, $pPerm )); + $result = $this->mDb->query( $query, [ $pGroupId, $pPerm ]); return true; } } @@ -929,7 +929,7 @@ class BitPermUser extends BitUser { function removePermissionFromGroup( $pPerm, $pGroupId ) { if( \Bitweaver\BitBase::verifyId( $pGroupId ) && !empty( $pPerm )) { $query = "DELETE FROM `".BIT_DB_PREFIX."users_group_permissions` WHERE `perm_name` = ? AND `group_id` = ?"; - $result = $this->mDb->query($query, array($pPerm, $pGroupId)); + $result = $this->mDb->query($query, [$pPerm, $pGroupId]); return true; } } diff --git a/includes/classes/BitUser.php b/includes/classes/BitUser.php index 32644fb..7b5d021 100755 --- a/includes/classes/BitUser.php +++ b/includes/classes/BitUser.php @@ -17,7 +17,7 @@ * required setup */ namespace Bitweaver\Users; -use Bitweaver\BitMailer; + use Bitweaver\KernelTools; use Bitweaver\Liberty\LibertyContent; @@ -64,28 +64,28 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { parent::__construct(); $this->mContentTypeGuid = BITUSER_CONTENT_TYPE_GUID; $this->registerContentType( - BITUSER_CONTENT_TYPE_GUID, array( + BITUSER_CONTENT_TYPE_GUID, [ 'content_type_guid' => BITUSER_CONTENT_TYPE_GUID, 'content_name' => 'User Information', 'content_name_plural' => 'User Information', 'handler_class' => 'BitUser', 'handler_package' => 'users', 'handler_file' => 'BitUser.php', - 'maintainer_url' => 'https://www.bitweaver.org' - ) + 'maintainer_url' => 'https://www.bitweaver.org', + ], ); $this->mUserId = ( @$this->verifyId( $pUserId ) ? $pUserId : null); $this->mContentId = $pContentId; } public function __sleep() { - return array_merge( parent::__sleep(), array( 'mUserId', 'mUsername', 'mGroups', 'mTicket', 'mAuth' ) ); + return array_merge( parent::__sleep(), [ 'mUserId', 'mUsername', 'mGroups', 'mTicket', 'mAuth' ] ); } public function getCacheKey() { $ret = $this->mUserId; $siteCookie = static::getSiteCookieName(); - if( $this->isRegistered() && !empty( $_COOKIE[$siteCookie] ) ) { + if( $this->isRegistered() && !empty( $_COOKIE[$siteCookie] ) ) { $ret .= $_COOKIE[$siteCookie]; } return $ret; @@ -128,13 +128,13 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $this->mInfo = null; if( isset( $this->mUserId ) ) { $whereSql = "WHERE uu.`user_id`=?"; - $bindVars = array( $this->mUserId ); + $bindVars = [ $this->mUserId ]; } elseif( isset( $this->mContentId ) ) { $whereSql = "WHERE uu.`content_id`=?"; - $bindVars = array( $this->mContentId ); + $bindVars = [ $this->mContentId ]; } elseif( !empty( $extraParams[1] ) ) { $whereSql = "WHERE uu.`login`=?"; - $bindVars = array( $extraParams[1] ); + $bindVars = [ $extraParams[1] ]; } if( isset( $whereSql ) ) { $fullSelect = ''; @@ -166,8 +166,8 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $this->mInfo['valid'] = @$this->verifyId( $this->mInfo['uu_user_id'] ); $this->mInfo['user_id'] = $this->mInfo['uu_user_id']; $this->mInfo['is_registered'] = $this->isRegistered(); - foreach( array( 'portrait', 'avatar', 'logo' ) as $img ) { - $this->mInfo[$img.'_path'] = $this->getSourceFile( array( 'user_id'=>$this->getField( 'user_id' ), 'package'=>\Bitweaver\Liberty\liberty_mime_get_storage_sub_dir_name( array( 'mime_type' => $this->getField( $img.'_mime_type' ), 'name' => $this->getField( $img.'_file_name' ) ) ), 'file_name' => basename( $this->mInfo[$img.'_file_name'] ?? '' ), 'sub_dir' => $this->getField( $img.'_attachment_id' ), 'mime_type' => $this->getField( $img.'_mime_type' ) ) ); + foreach( [ 'portrait', 'avatar', 'logo' ] as $img ) { + $this->mInfo[$img.'_path'] = $this->getSourceFile( [ 'user_id'=>$this->getField( 'user_id' ), 'package'=>\Bitweaver\Liberty\liberty_mime_get_storage_sub_dir_name( [ 'mime_type' => $this->getField( $img.'_mime_type' ), 'name' => $this->getField( $img.'_file_name' ) ] ), 'file_name' => basename( $this->mInfo[$img.'_file_name'] ?? '' ), 'sub_dir' => $this->getField( $img.'_attachment_id' ), 'mime_type' => $this->getField( $img.'_mime_type' ) ] ); $this->mInfo[$img.'_url'] = \Bitweaver\Liberty\liberty_fetch_thumbnail_url( [ 'source_file'=>$this->mInfo[$img.'_path'], 'size' => 'small', 'mime_image' => false ]); } @@ -250,7 +250,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $this->setPreference( 'site_display_timezone', 'UTC' ); } */ - if( !$this->getPreference( 'bitlanguage' ) ) { + if( !$this->getPreference( 'bitlanguage' ) ) { $this->setPreference( 'bitlanguage', $gBitLanguage->mLanguage ); } if( !$this->getPreference( 'theme' ) ) { @@ -280,7 +280,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( strlen( $pParamHash['login'] ) > 40 ) { $pParamHash['login'] = substr( $pParamHash['login'], 0, 40 ); } - if( $this->userExists( array( 'login' => $pParamHash['login'] ) ) ) { + if( $this->userExists( [ 'login' => $pParamHash['login'] ] ) ) { $this->mErrors['login'] = 'The username "'.$pParamHash['login'].'" is already in use'; } elseif( preg_match( '/[^A-Za-z0-9_.-]/', $pParamHash["login"] ) ) { $this->mErrors['login'] = KernelTools::tra( "Your username can only contain numbers, characters, underscores and hyphens." ); @@ -322,7 +322,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $loginBase = preg_replace( '/[^A-Za-z0-9_]/', '', substr( $pParamHash['email'], 0, strpos( $pParamHash['email'], '@' ) ) ); $login = $loginBase; do { - if( $loginTaken = $this->userExists( array( 'login' => $login ) ) ) { + if( $loginTaken = $this->userExists( [ 'login' => $login ] ) ) { $login = $loginBase.rand(100,999); } } while( $loginTaken ); @@ -354,9 +354,9 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { } if( isset( $pParamHash['password'] ) ) { - if( isset( $pParamHash["password2"] ) && $pParamHash["password"] != $pParamHash["password2"] ) { - $passwordErrors['password2'] = KernelTools::tra("The passwords didn't match"); - } + if( isset( $pParamHash["password2"] ) && $pParamHash["password"] != $pParamHash["password2"] ) { + $passwordErrors['password2'] = KernelTools::tra("The passwords didn't match"); + } if( ( !$this->isValid() || isset( $pParamHash['password'] ) ) && $error = $this->verifyPasswordFormat( $pParamHash['password'] ) ) { $passwordErrors['password'] = $error; } @@ -514,7 +514,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { global $gBitSystem; // check for existing user first, so root@localhost doesn't get attempted to re-register - if( !empty( $this ) && is_object( $this ) && $this->userExists( array( 'email' => $pEmail ) ) ) { + if( !empty( $this ) && is_object( $this ) && $this->userExists( [ 'email' => $pEmail ] ) ) { $pErrors['email'] = 'The email address "'.$pEmail.'" has already been registered.'; // during install we have some <user>@localhost as email address. we won't cause problems on those } elseif( $pEmail == 'root@localhost' || $pEmail == 'guest@localhost' ) { @@ -604,7 +604,6 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( $Connect ) { bitdebug( "Connection succeeded to {$host} SMTP." ); - stream_set_timeout( $Connect, 30 ); $out = $this->getSmtpResponse( $Connect ); @@ -641,10 +640,10 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { bit_error_log("INVALID EMAIL : ".$pEmail." SMTP FROM : ".$from." SMTP TO: ".$to); $ret = false; break; //break out of foreach and fall through to the end of function - }else{ + } $ret = true;//address has been verified by the server, no more checking necessary break; - } + } } elseif( preg_match ( "/^420/", $out ) ) { // Yahoo has a bad, bad habit of issuing 420's @@ -698,10 +697,10 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( $userId = $instance->createUser( $pParamHash )) { $this->mUserId = $userId; break; - } else { + } $this->mErrors = array_merge( $this->mErrors, $instance->mErrors ); return false; - } + } } @@ -782,16 +781,14 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { function verifyCaptcha( $pCaptcha = null ) { if( $this->hasPermission( 'p_users_bypass_captcha' ) || ( !empty( $_SESSION['captcha_verified'] ) && $_SESSION['captcha_verified'] === true ) ) { return true; - } else { + } if( empty( $pCaptcha ) || empty( $_SESSION['captcha'] ) || $_SESSION['captcha'] != md5( $pCaptcha ) ) { return false; - } else { + } $_SESSION['captcha_verified'] = true; return true; - } - } - } + } /** * store @@ -806,7 +803,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( !empty( $pParamHash['user_store'] ) && count( $pParamHash['user_store'] ) ) { if( $this->isValid() ) { - $userId = array ( "user_id" => $this->mUserId ); + $userId = [ "user_id" => $this->mUserId ]; $result = $this->mDb->associateUpdate( BIT_DB_PREFIX.'users_users', $pParamHash['user_store'], $userId ); } else { if( empty( $pParamHash['user_store']['user_id'] ) ) { @@ -825,7 +822,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( empty( $this->mInfo['content_id'] ) || ($pParamHash['content_id'] != $this->mInfo['content_id']) ) { $query = "UPDATE `".BIT_DB_PREFIX."users_users` SET `content_id`=? WHERE `user_id`=?"; - $result = $this->mDb->query( $query, array( $pParamHash['content_id'], $this->mUserId ) ); + $result = $this->mDb->query( $query, [ $pParamHash['content_id'], $this->mUserId ] ); $this->mInfo['content_id'] = $pParamHash['content_id']; } } @@ -860,7 +857,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $pParamHash['user_store']['default_group_id'] = key( $defaultGroups ); } if( $this->isValid() ) { - $userId = array ( "user_id" => $this->mUserId ); + $userId = [ "user_id" => $this->mUserId ]; $result = $this->mDb->associateUpdate( BIT_DB_PREFIX.'users_users', $pParamHash['user_store'], $userId ); } else { if( empty( $pParamHash['user_store']['user_id'] ) ) { @@ -880,7 +877,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( parent::store( $pParamHash )) { if( empty( $this->mInfo['content_id'] ) || $pParamHash['content_id'] != $this->mInfo['content_id'] ) { $query = "UPDATE `".BIT_DB_PREFIX."users_users` SET `content_id`=? WHERE `user_id`=?"; - $result = $this->mDb->query( $query, array( $pParamHash['content_id'], $this->mUserId ) ); + $result = $this->mDb->query( $query, [ $pParamHash['content_id'], $this->mUserId ] ); $this->mInfo['content_id'] = $pParamHash['content_id']; } } @@ -915,14 +912,14 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { // perhaps someone is importing users and *knows* what they are doing if( $this->verifyIdParameter( $pParamHash, 'user_id' ) ) { // only import user_id if it doesn't exist or overwrite is set. - if( !$this->userExists( array( 'user_id' => $pParamHash['user_id'] ) ) || !empty( $_REQUEST['overwrite'] ) ) { + if( !$this->userExists( [ 'user_id' => $pParamHash['user_id'] ] ) || !empty( $_REQUEST['overwrite'] ) ) { $pParamHash['user_store']['user_id'] = $pParamHash['user_id']; } else { unset( $pParamHash['user_id'] ); } } if( !empty( $pParamHash['login'] ) ) { - $ret = $this->userExists( array( 'login' => $pParamHash['login'] ) ); + $ret = $this->userExists( [ 'login' => $pParamHash['login'] ] ); if( !empty( $ret ) ) { // On batch import admin can overwrite existing user, so don't error if set // however, prevent overwrite of a mix of user records @@ -951,7 +948,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { // LOWER CASE all emails admin_verify_email $pParamHash['email'] = strtolower( $pParamHash['email'] ); if( validate_email_syntax( $pParamHash['email'] ) ) { - $ret = $this->userExists( array( 'email' => $pParamHash['email'] ) ); + $ret = $this->userExists( [ 'email' => $pParamHash['email'] ] ); if( !empty($ret) ) { if( !empty( $_REQUEST['overwrite'] ) && (!isset($pParamHash['user_store']['user_id']) || $pParamHash['user_store']['user_id'] == $ret ) ) { $pParamHash['user_id'] = $ret; @@ -978,7 +975,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { // check some new user requirements if( !$this->isRegistered() ) { if( isset($pParamHash['user_store']['user_id']) && !empty( $_REQUEST['overwrite'] ) ) { - $this->mUserId = $this->userExists( array( 'user_id' => $pParamHash['user_store']['user_id'] ) ); + $this->mUserId = $this->userExists( [ 'user_id' => $pParamHash['user_store']['user_id'] ] ); } if( empty( $pParamHash['registration_date'] ) ) { $pParamHash['registration_date'] = date( "U" ); @@ -1055,7 +1052,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( !empty( $this->pExpungeContent ) ) { if( $this->pExpungeContent == 'all' ) { - if( $userContent = $this->mDb->getAssoc( "SELECT content_id, content_type_guid FROM `".BIT_DB_PREFIX."liberty_content` WHERE `user_id`=? AND `content_type_guid` != 'bituser'", array( $this->mUserId ) ) ) { + if( $userContent = $this->mDb->getAssoc( "SELECT content_id, content_type_guid FROM `".BIT_DB_PREFIX."liberty_content` WHERE `user_id`=? AND `content_type_guid` != 'bituser'", [ $this->mUserId ] ) ) { foreach( $userContent as $contentId=>$contentTypeGuid ) { if( $delContent = static::getLibertyObject( $contentId, $contentTypeGuid ) ) { $delContent->expunge(); @@ -1070,16 +1067,16 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $this->purgeImage( 'portrait' ); $this->purgeImage( 'logo' ); $this->invokeServices( 'users_expunge_function' ); - $userTables = array( + $userTables = [ 'users_cnxn', 'users_watches', 'users_favorites_map', 'users_auth_map', 'users_users', - ); + ]; foreach( $userTables as $table ) { $query = "DELETE FROM `".BIT_DB_PREFIX.$table."` WHERE `user_id` = ?"; - $result = $this->mDb->query( $query, array( $this->mUserId ) ); + $result = $this->mDb->query( $query, [ $this->mUserId ] ); } parent::expunge(); @@ -1091,10 +1088,10 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $this->clearFromCache(); return true; - } else { + } $this->mDb->RollbackTrans(); $gBitSystem->fatalError( KernelTools::tra( 'The anonymous user cannot be deleted' ) ); - } + } return count( $this->mErrors ) === 0; } @@ -1115,7 +1112,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $update['current_view'] = $_SERVER['SCRIPT_NAME']; if( empty( $gLightWeightScan ) ) { - $row = $this->mDb->getRow( "SELECT `last_get`, `connect_time`, `get_count`, `user_agent`, `current_view` FROM `".BIT_DB_PREFIX."users_cnxn` WHERE `cookie`=? ", array( $pSessionId ) ); + $row = $this->mDb->getRow( "SELECT `last_get`, `connect_time`, `get_count`, `user_agent`, `current_view` FROM `".BIT_DB_PREFIX."users_cnxn` WHERE `cookie`=? ", [ $pSessionId ] ); if( $gBitUser->isRegistered() ) { $update['user_id'] = $gBitUser->mUserId; } @@ -1127,7 +1124,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $update['user_agent'] = (string)substr( $_SERVER['HTTP_USER_AGENT'], 0, 128 ); } $update['get_count'] = $row['get_count'] + 1; - $ret = $this->mDb->associateUpdate( BIT_DB_PREFIX.'users_cnxn', $update, array( 'cookie' => $pSessionId ) ); + $ret = $this->mDb->associateUpdate( BIT_DB_PREFIX.'users_cnxn', $update, [ 'cookie' => $pSessionId ] ); } else { if( $this->isRegistered() ) { $update['user_id'] = $this->mUserId; @@ -1146,7 +1143,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { // Default to 30 days history $oldy = $update['last_get'] - ($gBitSystem->getConfig( 'users_cnxn_history_days', 30 ) * 24 * 60 * 60); $query = "DELETE from `".BIT_DB_PREFIX."users_cnxn` where `connect_time` < ?"; - $result = $this->mDb->query($query, array($oldy)); + $result = $this->mDb->query($query, [$oldy]); } } return true; @@ -1198,7 +1195,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { } elseif( $pCookie==false ) { $pCookie = ''; // unset the cookie, eg logout if( !empty( $_COOKIE[$siteCookie] ) ) { - $this->mDb->query( "UPDATE `".BIT_DB_PREFIX."users_cnxn` SET `cookie`=null WHERE `cookie`=?", array( $_COOKIE[$siteCookie] ) ); + $this->mDb->query( "UPDATE `".BIT_DB_PREFIX."users_cnxn` SET `cookie`=null WHERE `cookie`=?", [ $_COOKIE[$siteCookie] ] ); unset( $_COOKIE[$siteCookie] ); } } @@ -1329,7 +1326,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $this->StartTrans(); // Verify user is valid if( $this->validate( $pLogin, $pPassword, $pChallenge, $pResponse )) { - $userInfo = $this->getUserInfo( array( $loginCol => $pLogin )); + $userInfo = $this->getUserInfo( [ $loginCol => $pLogin ]); // If the password is valid but it is due then force the user to change the password by // sending the user to the new password change screen without letting him use @@ -1353,7 +1350,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { } else { // before we give up lets see if the user exists and if the password is expired $query = "select `email`, `user_id`, `user_password` from `".BIT_DB_PREFIX."users_users` where " . $this->mDb->convertBinary(). " $loginCol = ?"; - $result = $this->mDb->getRow( $query, array( $pLogin ) ); + $result = $this->mDb->getRow( $query, [ $pLogin ] ); if( !empty( $result['user_id'] ) && $this->isPasswordDue( $result['user_id'] ) ) { // user needs email password reset so send it and let them know $url = USERS_PKG_URL.'remind_password.php?remind=y&required=y&username='.$pLogin; @@ -1406,7 +1403,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $indexType = 'group_home'; } - $url = isset($_SESSION['loginfrom']) ? $_SESSION['loginfrom'] : $gBitSystem->getIndexPage( $indexType ); + $url = $_SESSION['loginfrom'] ?? $gBitSystem->getIndexPage( $indexType ); unset( $_SESSION['loginfrom'] ); } return $url; @@ -1466,26 +1463,26 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $this->mUserId = $instance->mInfo['user_id']; //Is the user already in the database: - } elseif( $this->mDb->getOne( "SELECT COUNT(*) FROM `".BIT_DB_PREFIX."users_users` WHERE `login` = ?", array( $instance->mLogin )) > 0 ) { + } elseif( $this->mDb->getOne( "SELECT COUNT(*) FROM `".BIT_DB_PREFIX."users_users` WHERE `login` = ?", [ $instance->mLogin ]) > 0 ) { // Update Details - $authUserInfo = array( + $authUserInfo = [ 'login' => $instance->mInfo['login'], 'password' => $instance->mInfo['password'], 'real_name' => $instance->mInfo['real_name'], - 'email' => $instance->mInfo['email'] - ); - $userInfo = $this->getUserInfo( array( 'login' => $pUser )); + 'email' => $instance->mInfo['email'], + ]; + $userInfo = $this->getUserInfo( [ 'login' => $pUser ]); $this->mUserId = $userInfo['user_id']; $this->store( $authUserInfo ); $this->mErrors = []; } else { - $authUserInfo = array( + $authUserInfo = [ 'login' => $instance->mInfo['login'], 'password' => $instance->mInfo['password'], 'real_name' => $instance->mInfo['real_name'], - 'email' => $instance->mInfo['email'] - ); + 'email' => $instance->mInfo['email'], + ]; // TODO somehow, mUserId gets set to -1 at this point - no idea how // set to null to prevent overwriting Guest user - wolff_borg $this->mUserId = null; @@ -1545,7 +1542,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( @$this->verifyId( $pUserId ) ) { global $gBitSystem; $query = "UPDATE `".BIT_DB_PREFIX."users_users` SET `last_login` = `current_login`, `current_login` = ? WHERE `user_id` = ?"; - $result = $this->mDb->query( $query, array( $gBitSystem->getUTCTime(), $pUserId )); + $result = $this->mDb->query( $query, [ $gBitSystem->getUTCTime(), $pUserId ]); $ret = true; } return $ret; @@ -1564,7 +1561,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $query = " SELECT `user_id`, `provpass`, `user_password`, `login`, `email` FROM `".BIT_DB_PREFIX."users_users` WHERE `user_id`=? AND `provpass`=? AND ( `provpass_expires` IS null OR `provpass_expires` > ?)"; - return( $this->mDb->getRow( $query, array( (int)$pUserId, $pProvpass, $gBitSystem->getUTCTime() ))); + return( $this->mDb->getRow( $query, [ (int)$pUserId, $pProvpass, $gBitSystem->getUTCTime() ])); } /** @@ -1578,13 +1575,13 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { function changeUserEmail( $pUserId, $pEmail ) { if( !validate_email_syntax( $pEmail ) ) { $this->mErrors['bad_mail'] = KernelTools::tra( "The email address provided does not have recognised valid syntax." ); - } elseif( $this->userExists( array( 'email' => $pEmail ))) { + } elseif( $this->userExists( [ 'email' => $pEmail ])) { $this->mErrors['duplicate_mail'] = KernelTools::tra( "The email address you selected already exists." ); } else { $query = "UPDATE `".BIT_DB_PREFIX."users_users` SET `email`=? WHERE `user_id`=?"; - $result = $this->mDb->query( $query, array( $pEmail, $pUserId ) ); + $result = $this->mDb->query( $query, [ $pEmail, $pUserId ] ); $query = "UPDATE `".BIT_DB_PREFIX."users_watches` SET `email`=? WHERE `user_id`=?"; - $result = $this->mDb->query( $query, array( $pEmail, $pUserId ) ); + $result = $this->mDb->query( $query, [ $pEmail, $pUserId ] ); // update value in hash $this->mInfo['email'] = $pEmail; @@ -1613,7 +1610,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { // iHomepage is the 'login' of the user... $key = 'login'; } - $tmpUser = $this->getUserInfo( array( $key => $iHomepage )); + $tmpUser = $this->getUserInfo( [ $key => $iHomepage ]); if( @$this->verifyId( $tmpUser['user_id'] )) { $ret = $tmpUser['user_id']; } @@ -1637,7 +1634,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $query = " SELECT lcp.`pref_value` FROM `".BIT_DB_PREFIX."liberty_content_prefs` lcp INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON (lcp.`content_id`=uu.`content_id`) WHERE uu.`user_id` = ? AND lcp.`pref_name` = ?"; - if( !$ret = $gBitDb->getOne( $query, array( $pUserId, $pPrefName ))) { + if( !$ret = $gBitDb->getOne( $query, [ $pUserId, $pPrefName ])) { $ret = $pPrefDefault; } } @@ -1673,7 +1670,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { } if( !empty( $col ) ) { $query = "SELECT uu.* FROM `".BIT_DB_PREFIX."users_users` uu LEFT OUTER JOIN `".BIT_DB_PREFIX."liberty_content` lc ON (lc.`content_id`=uu.`content_id`) WHERE $col = ?"; - $ret = $gBitDb->getRow( $query, array( $val ), 600 ); + $ret = $gBitDb->getRow( $query, [ $val ], 600 ); } } } @@ -1707,7 +1704,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { */ function getUserIdFromCookieHash( $pParamHash ) { $query = "SELECT `user_id` FROM `".BIT_DB_PREFIX."users_cnxn` WHERE `cookie` = ?"; - return $this->mDb->getOne( $query, array( $pParamHash )); + return $this->mDb->getOne( $query, [ $pParamHash ]); } /** @@ -1729,7 +1726,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { SELECT `user_id`, `pass_due` FROM `".BIT_DB_PREFIX."users_users` WHERE `pass_due` IS NOT null AND `user_id`=? "; - $due = $this->mDb->getRow( $query, array( $pUserId ) ); + $due = $this->mDb->getRow( $query, [ $pUserId ] ); if( @$this->verifyId( $due['user_id'] ) && !empty( $due['pass_due'] ) ) { $ret = $due['pass_due'] <= $gBitSystem->getUTCTime(); } @@ -1747,7 +1744,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { */ function createTempPassword( $pLogin, $pPass ) { global $gBitSystem; - $ret = array( '', '' ); + $ret = [ '', '' ]; if( empty( $pLogin ) ) { $pLogin = $this->getField( 'email' ); @@ -1761,8 +1758,8 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { #temp passwords good for 3 days -- prob should be an config option $passDue = $gBitSystem->getUTCTime() + ( 60 * 60 * 24 * 3 ); $query = "UPDATE `".BIT_DB_PREFIX."users_users` SET `provpass` = ?, `provpass_expires` = ? WHERE `".$loginCol."` = ?"; - $result = $this->mDb->query( $query, array( $provpass, $passDue, $pLogin )); - $ret = array( $pass, $provpass ); + $result = $this->mDb->query( $query, [ $provpass, $passDue, $pLogin ]); + $ret = [ $pass, $provpass ]; } return $ret; } @@ -1796,7 +1793,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $pPass = null; $loginCol = strpos( $pLogin, '@' ) ? 'email' : 'login'; $query = "UPDATE `".BIT_DB_PREFIX."users_users` SET `provpass`= null, `provpass_expires` = null,`hash`=? ,`user_password`=? ,`pass_due`=? WHERE `".$loginCol."`=?"; - $result = $this->mDb->query( $query, array( $hash, $pPass, $passDue, $pLogin )); + $result = $this->mDb->query( $query, [ $hash, $pPass, $passDue, $pLogin ]); } return $ret; } @@ -1886,7 +1883,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { FROM `".BIT_DB_PREFIX."users_users` uu INNER JOIN `".BIT_DB_PREFIX."liberty_content_prefs` lcp ON( uu.`content_id` = lcp.`content_id` ) WHERE uu.`login` = ? AND lcp.`pref_name` = ?"; - $ret = $this->mDb->getRow( $sql, array( $pLogin, 'domain_style' ) ); + $ret = $this->mDb->getRow( $sql, [ $pLogin, 'domain_style' ] ); } return( $ret ); } @@ -1902,7 +1899,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $ret = []; if( $this->verifyId( $pContentId ) ) { $ret['content_id'] = $pContentId; - $ret['style'] = $this->mDb->getOne( "SELECT `pref_value` FROM `".BIT_DB_PREFIX."liberty_content_prefs` WHERE `content_id`=? AND `pref_name`=?", array( $pContentId, 'domain_style' )); + $ret['style'] = $this->mDb->getOne( "SELECT `pref_value` FROM `".BIT_DB_PREFIX."liberty_content_prefs` WHERE `content_id`=? AND `pref_name`=?", [ $pContentId, 'domain_style' ]); } return( $ret ); } @@ -1929,8 +1926,6 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { return( $this->hasPermission( 'p_tidbits_custom_home_layout' ) || $gBitSystem->getConfig( 'users_layouts' ) == 'y' || $gBitSystem->getConfig( 'users_layouts' ) == 'h' || $gBitSystem->getConfig( 'users_layouts' ) == 'u' ); } - - // {{{ ==================== image and file functions ==================== /** * getThumbnailUrl @@ -2063,7 +2058,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $file = $pStorageHash['upload_store']['files'][$pType]; if( empty( $this->mInfo["{$pType}_attachment_id"] ) || $this->mInfo["{$pType}_attachment_id"] != $file['attachment_id'] ) { $query = "UPDATE `".BIT_DB_PREFIX."users_users` SET `{$pType}_attachment_id` = ? WHERE `user_id`=?"; - $result = $this->mDb->query( $query, array( $file['attachment_id'], $this->mUserId ) ); + $result = $this->mDb->query( $query, [ $file['attachment_id'], $this->mUserId ] ); $this->mInfo["{$pType}_attachment_id"] = $file['attachment_id']; $pStorageHash["{$pType}_file_name"] = $file['upload']['dest_branch']; } @@ -2085,7 +2080,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( $this->isValid() && @$this->verifyId( $this->mInfo[$pType.'_attachment_id'] ) ) { $this->StartTrans(); $query = "UPDATE `".BIT_DB_PREFIX."users_users` SET `".$pType."_attachment_id` = null WHERE `user_id`=?"; - $result = $this->mDb->query( $query, array( $this->mUserId ) ); + $result = $this->mDb->query( $query, [ $this->mUserId ] ); if( $this->expungeAttachment( $this->getField( $pType.'_attachment_id' ) ) ) { unset( $this->mInfo[$pType.'_file_name'] ); unset( $this->mInfo[$pType.'_attachment_id'] ); @@ -2106,7 +2101,6 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { return $this->purgeImage( 'portrait' ); } - /** * purgeAvatar * @@ -2117,7 +2111,6 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { return $this->purgeImage( 'avatar' ); } - /** * purgeLogo * @@ -2147,9 +2140,9 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( $this->isValid() ) { $hash = md5( uniqid( '.' )); $query = "DELETE FROM `".BIT_DB_PREFIX."users_watches` WHERE `user_id`=? AND `event`=? AND `object`=?"; - $this->mDb->query($query,array( $this->mUserId, $pEvent, $pObject ) ); + $this->mDb->query($query,[ $this->mUserId, $pEvent, $pObject ] ); $query = "INSERT INTO `".BIT_DB_PREFIX."users_watches`(`user_id` ,`event` ,`object` , `email`, `hash`, `watch_type`, `title`, `url`) VALUES(?,?,?,?,?,?,?,?)"; - $this->mDb->query( $query, array( $this->mUserId, $pEvent, $pObject, $this->mInfo['email'], $hash, $pType, $pTitle, $pUrl ) ); + $this->mDb->query( $query, [ $this->mUserId, $pEvent, $pObject, $this->mInfo['email'], $hash, $pType, $pTitle, $pUrl ] ); return true; } } @@ -2165,7 +2158,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $ret = null; if( $this->isValid() ) { $mid = ''; - $bindvars=array( $this->mUserId ); + $bindvars=[ $this->mUserId ]; if ($pEvent) { $mid = " and `event`=? "; $bindvars[]=$pEvent; @@ -2194,7 +2187,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $ret = null; if( $this->isValid() ) { $query = "SELECT * FROM `".BIT_DB_PREFIX."users_watches` WHERE `user_id`=? AND `event`=? AND `object`=?"; - $result = $this->mDb->query($query,array( $this->mUserId, $pEvent, $pObject ) ); + $result = $this->mDb->query($query,[ $this->mUserId, $pEvent, $pObject ] ); if ( $result->numRows() ) { $ret = $result->fetchRow(); } @@ -2214,7 +2207,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $ret = []; $query = "select * from `".BIT_DB_PREFIX."users_watches` tw INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON ( tw.`user_id`=uu.`user_id` ) where `event`=? and `object`=?"; - $result = $this->mDb->query( $query,array( $pEvent,$pObject )); + $result = $this->mDb->query( $query,[ $pEvent,$pObject ]); if( !$result->numRows() ) { return $ret; @@ -2236,7 +2229,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { */ function remove_user_watch_by_hash( $pParamHash ) { $query = "DELETE FROM `".BIT_DB_PREFIX."users_watches` WHERE `hash`=?"; - $this->mDb->query( $query,array( $pParamHash )); + $this->mDb->query( $query,[ $pParamHash ]); } /** @@ -2250,7 +2243,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { function expungeWatch( $pEvent, $pObject ) { if( $this->isValid() ) { $query = "DELETE FROM `".BIT_DB_PREFIX."users_watches` WHERE `user_id`=? AND `event`=? AND `object`=?"; - $this->mDb->query( $query, array( $this->mUserId, $pEvent, $pObject )); + $this->mDb->query( $query, [ $this->mUserId, $pEvent, $pObject ]); } } @@ -2296,7 +2289,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { $ret = false; if( $this->isValid() && $this->verifyId( $pContentId )) { if( !$this->hasFavorite( $pContentId ) ){ - $this->mDb->query( "INSERT INTO `".BIT_DB_PREFIX."users_favorites_map` ( `user_id`, `favorite_content_id` ) VALUES (?,?)", array( $this->mUserId, $pContentId ) ); + $this->mDb->query( "INSERT INTO `".BIT_DB_PREFIX."users_favorites_map` ( `user_id`, `favorite_content_id` ) VALUES (?,?)", [ $this->mUserId, $pContentId ] ); } $ret = true; } @@ -2306,7 +2299,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { function expungeFavorite( $pContentId ) { $ret = false; if( $this->isValid() && $this->verifyId( $pContentId ) ) { - $this->mDb->query( "DELETE FROM `".BIT_DB_PREFIX."users_favorites_map` WHERE `user_id`=? AND `favorite_content_id`=?", array( $this->mUserId, $pContentId ) ); + $this->mDb->query( "DELETE FROM `".BIT_DB_PREFIX."users_favorites_map` WHERE `user_id`=? AND `favorite_content_id`=?", [ $this->mUserId, $pContentId ] ); $ret = true; } return( $ret ); @@ -2314,7 +2307,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { function hasFavorite( $pContentId ) { $ret = false; - $rslt = $this->mDb->getOne( "SELECT `favorite_content_id` FROM `".BIT_DB_PREFIX."users_favorites_map` WHERE `user_id`=? AND `favorite_content_id`=?", array( $this->mUserId, $pContentId ) ); + $rslt = $this->mDb->getOne( "SELECT `favorite_content_id` FROM `".BIT_DB_PREFIX."users_favorites_map` WHERE `user_id`=? AND `favorite_content_id`=?", [ $this->mUserId, $pContentId ] ); if( !is_null( $rslt ) ){ $ret = true; } @@ -2438,12 +2431,12 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { } if( empty( $pParamHash['users_information'] ) && !empty( $pParamHash['login'] ) ) { - $pParamHash['users_information'] = $gBitSystem->mDb->getOne( "SELECT pref_value FROM liberty_content_prefs lcp INNER JOIN users_users uu ON (lcp.content_id=uu.content_id) WHERE uu.login=? AND pref_name='users_information'", array( $pParamHash['login'] ), 1, null, 86400 ); + $pParamHash['users_information'] = $gBitSystem->mDb->getOne( "SELECT pref_value FROM liberty_content_prefs lcp INNER JOIN users_users uu ON (lcp.content_id=uu.content_id) WHERE uu.login=? AND pref_name='users_information'", [ $pParamHash['login'] ], 1, null, 86400 ); } $ret = ( $pUseLink && ( $gBitUser->hasPermission( 'p_users_view_user_homepage' ) || $pParamHash['users_information'] == 'public' ) ) ? '<a class="username" title="' . ( !empty( $pParamHash['link_title'] ) ? $pParamHash['link_title'] : KernelTools::tra( 'Profile for' ) . ' ' . htmlspecialchars( $displayName ) ) . '" href="' . BitUser::getDisplayUrlFromHash( $pParamHash ) . '">' - . htmlspecialchars( isset( $pParamHash['link_label'] ) ? $pParamHash['link_label'] : $displayName ) + . htmlspecialchars( $pParamHash['link_label'] ?? $displayName ) . '</a>' : htmlspecialchars( $displayName ); } else { @@ -2510,7 +2503,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { LibertyContent::prepGetList( $pParamHash ); $selectSql = $joinSql = $whereSql = ''; - $bindVars = array( 'bituser' ); + $bindVars = [ 'bituser' ]; $this->getServicesSql( 'content_list_sql_function', $selectSql, $joinSql, $whereSql, $bindVars, null, $pParamHash ); // limit search to users with a specific language @@ -2585,7 +2578,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { while( $res = $result->fetchRow() ) { // Used for pulling out dead/empty/spam accounts if( isset( $pParamHash['max_content_count'] ) && is_numeric( $pParamHash['max_content_count'] ) ) { - $contentCount = $this->mDb->getOne( "SELECT COUNT(*) FROM `".BIT_DB_PREFIX."liberty_content` lc INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON ( lc.`user_id`=uu.`user_id` ) WHERE uu.`user_id`=? AND `content_type_guid` != 'bituser'", array( $res['user_id'] ) ); + $contentCount = $this->mDb->getOne( "SELECT COUNT(*) FROM `".BIT_DB_PREFIX."liberty_content` lc INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON ( lc.`user_id`=uu.`user_id` ) WHERE uu.`user_id`=? AND `content_type_guid` != 'bituser'", [ $res['user_id'] ] ); if( $contentCount > $pParamHash['max_content_count'] ) { continue; } @@ -2593,7 +2586,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { // Used for pulling out non-idle accounts or pigs if( isset( $pParamHash['min_content_count'] ) && is_numeric( $pParamHash['min_content_count'] ) ) { - $contentCount = $this->mDb->getOne( "SELECT COUNT(*) FROM `".BIT_DB_PREFIX."liberty_content` lc INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON ( lc.`user_id`=uu.`user_id` ) WHERE uu.`user_id`=? AND `content_type_guid` != 'bituser'", array( $res['user_id'] ) ); + $contentCount = $this->mDb->getOne( "SELECT COUNT(*) FROM `".BIT_DB_PREFIX."liberty_content` lc INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON ( lc.`user_id`=uu.`user_id` ) WHERE uu.`user_id`=? AND `content_type_guid` != 'bituser'", [ $res['user_id'] ] ); if( $contentCount < $pParamHash['min_content_count'] ) { continue; } @@ -2605,13 +2598,13 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { } } if( !empty( $res['avatar_file_name'] )) { - $res['avatar_url'] = $this->getSourceUrl( array( 'attachment_id'=>$res['avatar_attachment_id'], 'mime_type'=>$res['avatar_mime_type'], 'file_name'=>$res['avatar_file_name'] ) ); - $res['thumbnail_url'] = \Bitweaver\Liberty\liberty_fetch_thumbnail_url( array( - 'source_file' => $this->getSourceFile( array( 'sub_dir'=>$res['avatar_attachment_id'], 'user_id' => $res['user_id'], 'file_name'=>$res['avatar_file_name'], 'mime_type'=>$res['avatar_mime_type'], 'package'=>\Bitweaver\Liberty\liberty_mime_get_storage_sub_dir_name( array( 'mime_type'=>$res['avatar_mime_type'], 'name'=>$res['avatar_file_name'] ) ) ) ), + $res['avatar_url'] = $this->getSourceUrl( [ 'attachment_id'=>$res['avatar_attachment_id'], 'mime_type'=>$res['avatar_mime_type'], 'file_name'=>$res['avatar_file_name'] ] ); + $res['thumbnail_url'] = \Bitweaver\Liberty\liberty_fetch_thumbnail_url( [ + 'source_file' => $this->getSourceFile( [ 'sub_dir'=>$res['avatar_attachment_id'], 'user_id' => $res['user_id'], 'file_name'=>$res['avatar_file_name'], 'mime_type'=>$res['avatar_mime_type'], 'package'=>\Bitweaver\Liberty\liberty_mime_get_storage_sub_dir_name( [ 'mime_type'=>$res['avatar_mime_type'], 'name'=>$res['avatar_file_name'] ] ) ] ), 'file_name' => $res['avatar_url'], // TODO: Make this a preference 'size' => 'avatar', - ) ); + ] ); } $res["groups"] = $this->getGroups( $res['user_id'] ); $ret[$res['user_id']] = $res; @@ -2644,21 +2637,21 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { SELECT ug.`group_id`, ug.`group_name`, ug.`user_id` as group_owner_user_id FROM `".BIT_DB_PREFIX."users_groups_map` ugm INNER JOIN `".BIT_DB_PREFIX."users_groups` ug ON (ug.`group_id`=ugm.`group_id`) WHERE ugm.`user_id`=? OR ugm.`group_id`=".ANONYMOUS_GROUP_ID; - $ret = $this->mDb->getAssoc( $query, array(( int )$pUserId )); + $ret = $this->mDb->getAssoc( $query, [( int )$pUserId ]); if( $ret ) { foreach( array_keys( $ret ) as $groupId ) { $res = []; foreach( $res as $key=>$val) { - $ret[$key] = array( 'group_name' => $val ); + $ret[$key] = [ 'group_name' => $val ]; } } } // cache it $this->cUserGroups[$pUserId] = $ret; return $ret; - } else { - return $this->cUserGroups[$pUserId]; } + return $this->cUserGroups[$pUserId]; + } /** @@ -2718,7 +2711,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if ($cur = current( $pUserMixed )) { $conditionSql = ( is_numeric( $cur ) ) ? " `" . key( $pUserMixed ) . "` " : " UPPER(`" . key( $pUserMixed ) . "`)"; $query = "SELECT `user_id` FROM `".BIT_DB_PREFIX."users_users` WHERE $conditionSql = ?"; - $ret = $this->mDb->getOne( $query, array( strtoupper( $cur ) ) ); + $ret = $this->mDb->getOne( $query, [ strtoupper( $cur ) ] ); } } return $ret; @@ -2777,7 +2770,7 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { if( \Bitweaver\BitBase::verifyId( $pInput['group_id'] ) ) { $pReturn['group_id'] = $pInput['group_id']; } - return; + } public static function getUserObject( $pUserId ) { @@ -2793,14 +2786,13 @@ class BitUser extends \Bitweaver\Liberty\LibertyMime { function get_user_content_count( $pUserId ) { global $gBitDb; if( \Bitweaver\BitBase::verifyId( $pUserId ) ) { - return $gBitDb->getOne( "SELECT COUNT(`content_id`) FROM `".BIT_DB_PREFIX."liberty_content` lc WHERE lc.`content_type_guid`!='bituser' AND lc.`user_id`=?", array( $pUserId ) ); + return $gBitDb->getOne( "SELECT COUNT(`content_id`) FROM `".BIT_DB_PREFIX."liberty_content` lc WHERE lc.`content_type_guid`!='bituser' AND lc.`user_id`=?", [ $pUserId ] ); } } - // {{{ ==================== Services ==================== function users_favs_content_list_sql( $pObject, $pParamHash=null ){ - $ret = []; + $ret = []; if( is_object( $pObject ) && !empty( $pParamHash['user_favs'] ) ){ // $ret['select_sql'] = ""; $ret['join_sql'] = " INNER JOIN `".BIT_DB_PREFIX."users_favorites_map` ufm ON ( ufm.`favorite_content_id`=lc.`content_id` )"; @@ -2811,7 +2803,7 @@ function users_favs_content_list_sql( $pObject, $pParamHash=null ){ } function users_collection_sql( &$pObject, $pParamHash=null ){ - $ret = []; + $ret = []; if( !empty( $pParamHash['group_id'] ) and \Bitweaver\BitBase::verifyId( $pParamHash['group_id'] ) ){ // $ret['select_sql'] = ""; $ret['join_sql'] = " INNER JOIN `".BIT_DB_PREFIX."users_groups_map` ugm ON (ugm.`user_id`=uu.`user_id`)"; diff --git a/includes/classes/CloudflareTurnstile.php b/includes/classes/CloudflareTurnstile.php index e2f75ce..4c4deb1 100644 --- a/includes/classes/CloudflareTurnstile.php +++ b/includes/classes/CloudflareTurnstile.php @@ -1,55 +1,55 @@ <?php class CloudflareTurnstileValidator { - private $secretKey; - private $verifyUrl = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; + private $secretKey; + private $verifyUrl = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; - public function __construct($secretKey) { - $this->secretKey = $secretKey; - } + public function __construct($secretKey) { + $this->secretKey = $secretKey; + } + + public function validate($responseToken, $remoteIp = null) { + // Prepare POST data + $data = [ + 'secret' => $this->secretKey, + 'response' => $responseToken, + ]; - public function validate($responseToken, $remoteIp = null) { - // Prepare POST data - $data = [ - 'secret' => $this->secretKey, - 'response' => $responseToken - ]; + if ($remoteIp) { + $data['remoteip'] = $remoteIp; + } - if ($remoteIp) { - $data['remoteip'] = $remoteIp; - } + // Initialize cURL + $ch = curl_init($this->verifyUrl); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_TIMEOUT, 10); - // Initialize cURL - $ch = curl_init($this->verifyUrl); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_TIMEOUT, 10); + // Execute request + $response = curl_exec($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - // Execute request - $response = curl_exec($ch); - $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - - curl_close($ch); + curl_close($ch); - $ret = array(); + $ret = []; - // Decode JSON response - $result = json_decode($response, true); + // Decode JSON response + $result = json_decode($response, true); - if (!$result) { - $ret = [ - 'success' => false, - 'error_codes' => array( 'Invalid response from verification server ('.$httpCode.')' ) - ]; - } else { + if (!$result) { + $ret = [ + 'success' => false, + 'error_codes' => [ 'Invalid response from verification server ('.$httpCode.')' ], + ]; + } else { $ret = [ 'success' => $result['success'], 'timestamp' => $result['challenge_ts'] ?? null, 'hostname' => $result['hostname'] ?? null, - 'error_codes' => $result['error-codes'] ?? [] + 'error_codes' => $result['error-codes'] ?? [], ]; - } + } return $ret; } @@ -61,8 +61,8 @@ $validator = new TurnstileValidator('YOUR_SECRET_KEY_HERE'); $result = $validator->validate($_POST['cf-turnstile-response'], $_SERVER['REMOTE_ADDR']); if ($result['success']) { - echo "Verification successful!"; + echo "Verification successful!"; } else { - echo "Verification failed: " . implode(', ', $result['error_codes']); + echo "Verification failed: " . implode(', ', $result['error_codes']); } */ diff --git a/includes/classes/RolePermUser.php b/includes/classes/RolePermUser.php index 0db1f81..ddee217 100755 --- a/includes/classes/RolePermUser.php +++ b/includes/classes/RolePermUser.php @@ -19,6 +19,7 @@ * required setup */ namespace Bitweaver\Users; + use Bitweaver\BitBase; use Bitweaver\KernelTools; use Bitweaver\Liberty\LibertyContent; @@ -145,7 +146,7 @@ class RolePermUser extends RoleUser { $roleParams = [ 'user_id' => $this->mUserId, 'name' => $pParamHash['user_store']['login'], - 'desc' => "Personal role for ".( !empty( $pParamHash['user_store']['real_name'] ) ? $pParamHash['user_store']['real_name'] : $pParamHash['user_store']['login'] ) + 'desc' => "Personal role for ".( !empty( $pParamHash['user_store']['real_name'] ) ? $pParamHash['user_store']['real_name'] : $pParamHash['user_store']['login'] ), ]; if( $this->storeRole( $roleParams ) ) { $this->addUserToRole( $this->mUserId, $roleParams['role_id'] ); @@ -359,7 +360,7 @@ class RolePermUser extends RoleUser { ORDER BY ur.`role_name` ASC"; return $this->mDb->getAssoc( $sql, [ $pUserId ] ); } - + public function getAllGroups( &$pListHash ) { return []; } @@ -759,9 +760,9 @@ class RolePermUser extends RoleUser { global $gBitSmarty, $gBitSystem, ${$pPermission}; if( empty( $pPermission ) || $this->hasPermission( $pPermission ) ) { return; - } else { - $gBitSystem->fatalPermission( $pPermission, $pMsg ); } + $gBitSystem->fatalPermission( $pPermission, $pMsg ); + } public function getGroupPermissions( $pParamHash = null ) { @@ -782,8 +783,8 @@ class RolePermUser extends RoleUser { $ret = $bindVars = []; $whereSql = $selectSql = $fromSql = ''; - $sortMode = !empty( $pParamHash['sort_mode'] ) - ? $this->mDb->convertSortmode( $pParamHash['sort_mode'] ) + $sortMode = !empty( $pParamHash['sort_mode'] ) + ? $this->mDb->convertSortmode( $pParamHash['sort_mode'] ) : 'up.`package`, up.`perm_name` ASC'; if( !empty( $pParamHash['package'] )) { diff --git a/includes/classes/RoleUser.php b/includes/classes/RoleUser.php index 99301a8..c627409 100755 --- a/includes/classes/RoleUser.php +++ b/includes/classes/RoleUser.php @@ -17,9 +17,9 @@ * required setup */ namespace Bitweaver\Users; + use Bitweaver\BitBase; use Bitweaver\BitSystem; -use Bitweaver\DateTime; use Bitweaver\Liberty\LibertyBase; use Bitweaver\Liberty\LibertyContent; use Bitweaver\KernelTools; @@ -78,7 +78,7 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { 'handler_package' => 'users', 'handler_file' => 'RoleUser.php', 'maintainer_url' => 'https://www.bitweaver.org', - ] + ], ); $this->mUserId = @$this->verifyId( $pUserId ) ? $pUserId : null; $this->mContentId = $pContentId; @@ -91,11 +91,11 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { public function getCacheKey() { $siteCookie = static::getSiteCookieName(); - if( $this->isRegistered() && !empty( $_COOKIE[$siteCookie] ) ) { + if( $this->isRegistered() && !empty( $_COOKIE[$siteCookie] ) ) { return $_COOKIE[$siteCookie]; - } else { - return ANONYMOUS_USER_ID; } + return ANONYMOUS_USER_ID; + } public static function isCacheableClass() { @@ -175,18 +175,18 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { $this->mInfo['user_id'] = $this->mInfo['uu_user_id']; $this->mInfo['is_registered'] = $this->isRegistered(); foreach( [ 'portrait', 'avatar', 'logo' ] as $img ) { - $this->mInfo[$img.'_path'] = $this->getSourceFile( [ + $this->mInfo[$img.'_path'] = $this->getSourceFile( [ 'user_id'=>$this->getField( 'user_id' ), - 'package'=>\Bitweaver\Liberty\liberty_mime_get_storage_sub_dir_name([ + 'package'=>\Bitweaver\Liberty\liberty_mime_get_storage_sub_dir_name([ 'mime_type' => $this->getField( $img.'_mime_type' ), - 'name' => $this->getField( $img.'_file_name' ) ] ), + 'name' => $this->getField( $img.'_file_name' ), ] ), 'file_name' => basename( $this->mInfo[$img.'_file_name'] ?? '' ), 'sub_dir' => $this->getField( $img.'_attachment_id' ), - 'mime_type' => $this->getField( $img.'_mime_type' ) ] ); + 'mime_type' => $this->getField( $img.'_mime_type' ), ] ); $this->mInfo[$img.'_url'] = \Bitweaver\Liberty\liberty_fetch_thumbnail_url( [ 'source_file'=>$this->mInfo[$img.'_path'], 'size' => 'small', - 'mime_image' => false ] ); + 'mime_image' => false, ] ); } // break the real name into first and last name using the last space as the beginning of the last name @@ -266,7 +266,7 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { $this->setPreference( 'site_display_timezone', 'UTC' ); } */ - if( !$this->getPreference( 'bitlanguage' ) ) { + if( !$this->getPreference( 'bitlanguage' ) ) { $this->setPreference( 'bitlanguage', $gBitLanguage->mLanguage ); } if( !$this->getPreference( 'theme' ) ) { @@ -369,9 +369,9 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { } if( isset( $pParamHash['password'] ) ) { - if( isset( $pParamHash["password2"] ) && $pParamHash["password"] != $pParamHash["password2"] ) { - $passwordErrors['password2'] = KernelTools::tra("The passwords didn't match"); - } + if( isset( $pParamHash["password2"] ) && $pParamHash["password"] != $pParamHash["password2"] ) { + $passwordErrors['password2'] = KernelTools::tra("The passwords didn't match"); + } if( ( !$this->isValid() || isset( $pParamHash['password'] ) ) && $error = $this->verifyPasswordFormat( $pParamHash['password'] ) ) { $passwordErrors['password'] = $error; } @@ -614,7 +614,6 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { if( $Connect ) { \Bitweaver\bitdebug( "Connection succeeded to {$host} SMTP." ); - stream_set_timeout( $Connect, 30 ); $out = $this->getSmtpResponse( $Connect ); @@ -651,10 +650,10 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { \Bitweaver\bit_error_log("INVALID EMAIL : ".$pEmail." SMTP FROM : ".$from." SMTP TO: ".$to); $ret = false; break; //break out of foreach and fall through to the end of function - }else{ + } $ret = true;//address has been verified by the server, no more checking necessary break; - } + } } elseif( preg_match ( "/^420/", $out ) ) { // Yahoo has a bad, bad habit of issuing 420's @@ -708,10 +707,10 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { if( $userId = $instance->createUser( $pParamHash )) { $this->mUserId = $userId; break; - } else { + } $this->mErrors = array_merge( $this->mErrors, $instance->mErrors ); return false; - } + } } @@ -792,16 +791,14 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { public function verifyCaptcha( $pCaptcha = null ) { if( $this->hasPermission( 'p_users_bypass_captcha' ) || ( !empty( $_SESSION['captcha_verified'] ) && $_SESSION['captcha_verified'] === true ) ) { return true; - } else { + } if( empty( $pCaptcha ) || empty( $_SESSION['captcha'] ) || $_SESSION['captcha'] != md5( $pCaptcha ) ) { return false; - } else { + } $_SESSION['captcha_verified'] = true; return true; - } - } - } + } /** * store @@ -1037,7 +1034,7 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { // renew password only next half year ;) $pParamHash['user_store']['pass_due'] = $now + 60 * 60 * 24 * $pParamHash['pass_due']; } - $pParamHash['user_store']['user_password'] = ($gBitSystem->isFeatureActive( 'users_clear_passwords' )) ? $pParamHash['password'] : ''; + $pParamHash['user_store']['user_password'] = ($gBitSystem->isFeatureActive( 'users_clear_passwords' )) ? $pParamHash['password'] : ''; if ( !empty( $pParamHash['hash'] )) $pParamHash['user_store']['hash'] = $pParamHash['hash']; $now = $gBitSystem->getUTCTime(); if( !isset( $pParamHash['pass_due'] ) && $gBitSystem->getConfig( 'users_pass_due' )) { @@ -1222,7 +1219,7 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { 'domain' => $cookieDomain, 'secure' => true, 'httponly' => true, - 'samesite' => 'Strict' + 'samesite' => 'Strict', ] ); $_COOKIE[$siteCookie] = $pCookie; } @@ -1272,12 +1269,12 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { $indexType = 'group_home'; } - $url = isset($_SESSION['loginfrom']) ? $_SESSION['loginfrom'] : $gBitSystem->getIndexPage( $indexType ); + $url = $_SESSION['loginfrom'] ?? $gBitSystem->getIndexPage( $indexType ); unset( $_SESSION['loginfrom'] ); } return $url; } - + // {{{ ==================== Banning ==================== /** * ban sets the user account status to -201 suspended @@ -1965,8 +1962,6 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { return $this->hasPermission( 'p_tidbits_custom_home_layout' ) || $gBitSystem->getConfig( 'users_layouts' ) == 'y' || $gBitSystem->getConfig( 'users_layouts' ) == 'h' || $gBitSystem->getConfig( 'users_layouts' ) == 'u'; } - - // {{{ ==================== image and file functions ==================== /** * getThumbnailUrl @@ -2143,7 +2138,6 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { return $this->purgeImage( 'portrait' ); } - /** * purgeAvatar * @@ -2154,7 +2148,6 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { return $this->purgeImage( 'avatar' ); } - /** * purgeLogo * @@ -2252,7 +2245,7 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { $ret = []; $query = "select * from `".BIT_DB_PREFIX."users_watches` tw INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON ( tw.`user_id`=uu.`user_id` ) where `event`=? and `object`=?"; - $result = $this->mDb->query( $query,array( $pEvent,$pObject )); + $result = $this->mDb->query( $query,[ $pEvent,$pObject ]); if( !$result->numRows() ) { return $ret; @@ -2481,7 +2474,7 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { if( $pUseLink && $gBitUser->hasPermission( 'p_users_view_user_homepage' ) && (empty( $pHash['users_information'] ) || $pHash['users_information'] == 'public') ) { $ret = '<a class="username" title="'.( !empty( $pHash['link_title'] ) ? $pHash['link_title'] : KernelTools::tra( 'Profile for' ).' '.htmlspecialchars( $displayName )) .'" href="'.RoleUser::getDisplayUrlFromHash( $pHash ).'">' - . htmlspecialchars( isset( $pHash['link_label'] ) ? $pHash['link_label'] : ( isset($displayName) ? $displayName : 'not set' ) ) + . htmlspecialchars( $pHash['link_label'] ?? ( $displayName ?? 'not set' ) ) .'</a>'; } else { $ret = htmlspecialchars( $displayName ); @@ -2706,9 +2699,9 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { // cache it $this->cUserRoles[$userId] = $ret; return $ret; - } else { - return $this->cUserRoles[$userId]; } + return $this->cUserRoles[$userId]; + } /** @@ -2824,7 +2817,7 @@ class RoleUser extends \Bitweaver\Liberty\LibertyMime { if( BitBase::verifyId( $pInput['role_id'] ?? 0 ) ) { $pReturn['role_id'] = $pInput['role_id']; } - return; + } public static function getUserObject( $pUserId ) { @@ -2844,10 +2837,9 @@ function get_user_content_count( $pUserId ) { } } - // {{{ ==================== Services ==================== function users_favs_content_list_sql( $pObject, $pParamHash=null ){ - $ret = []; + $ret = []; if( !empty( $pParamHash['user_favs'] ) ){ // $ret['select_sql'] = ""; $ret['join_sql'] = " INNER JOIN `".BIT_DB_PREFIX."users_favorites_map` ufm ON ( ufm.`favorite_content_id`=lc.`content_id` )"; @@ -2858,7 +2850,7 @@ function users_favs_content_list_sql( $pObject, $pParamHash=null ){ } function users_collection_sql( $pObject, $pParamHash=null ){ - $ret = []; + $ret = []; if( !empty( $pParamHash['role_id'] ) and BitBase::verifyId( $pParamHash['role_id'] ) ){ // $ret['select_sql'] = ""; $ret['join_sql'] = " INNER JOIN `".BIT_DB_PREFIX."users_roles_map` urm ON (ugm.`user_id`=uu.`user_id`)"; diff --git a/includes/display_bituser_inc.php b/includes/display_bituser_inc.php index 1e4e537..b5e65db 100755 --- a/includes/display_bituser_inc.php +++ b/includes/display_bituser_inc.php @@ -15,4 +15,4 @@ // this first version is a bit incomplete, but at least things work now. - spiderr include USERS_PKG_PATH.'templates/center_user_wiki_page.php'; - $gBitSystem->display( 'bitpackage:users/center_user_wiki_page.tpl' , null, array( 'display_mode' => 'display' )); + $gBitSystem->display( 'bitpackage:users/center_user_wiki_page.tpl' , null, [ 'display_mode' => 'display' ]); diff --git a/includes/lookup_user_inc.php b/includes/lookup_user_inc.php index 78e1f7b..727dfa1 100755 --- a/includes/lookup_user_inc.php +++ b/includes/lookup_user_inc.php @@ -7,6 +7,7 @@ */ namespace Bitweaver\Users; + use Bitweaver\BitBase; use Bitweaver\HttpStatusCodes; use Bitweaver\KernelTools; @@ -24,7 +25,7 @@ if( isset( $_REQUEST['fHomepage'] )) { $userInfo = $gBitUser->getUserInfo( [ 'content_id' => $_REQUEST['content_id'] ?? 0 ]); $_REQUEST['home'] = !empty( $userInfo['login'] ) ? $userInfo['login'] : null; } elseif( isset($_REQUEST['user_id']) && BitBase::verifyId( $_REQUEST['user_id'] )) { - $userInfo = $gBitUser->getUserInfo( array( 'user_id' => $_REQUEST['user_id'] )); + $userInfo = $gBitUser->getUserInfo( [ 'user_id' => $_REQUEST['user_id'] ]); $_REQUEST['home'] = !empty( $userInfo['login'] ) ? $userInfo['login'] : null; } diff --git a/includes/module_controls_inc.php b/includes/module_controls_inc.php index fef85ee..751bcdc 100755 --- a/includes/module_controls_inc.php +++ b/includes/module_controls_inc.php @@ -14,32 +14,32 @@ use Bitweaver\KernelTools; $check_req = (isset($_REQUEST["mc_unassign"]) - || isset($_REQUEST["mc_up"]) - || isset($_REQUEST["mc_down"]) - || isset($_REQUEST["mc_move"])); + || isset($_REQUEST["mc_up"]) + || isset($_REQUEST["mc_down"]) + || isset($_REQUEST["mc_move"])); if (!$gBitUser->hasPermission( 'p_tidbits_configure_modules' ) && $check_req) { $gBitSmarty->assign('msg', KernelTools::tra( "You dont have permission to use this feature" )); - $gBitSystem->display( 'error.tpl' , null, array( 'display_mode' => 'display' )); + $gBitSystem->display( 'error.tpl' , null, [ 'display_mode' => 'display' ]); die; } if ($site_user_assigned_modules != 'y' && $check_req) { $gBitSmarty->assign('msg', KernelTools::tra( "This feature is disabled").": site_user_assigned_modules" ); - $gBitSystem->display( 'error.tpl' , null, array( 'display_mode' => 'display' )); + $gBitSystem->display( 'error.tpl' , null, [ 'display_mode' => 'display' ]); die; } if ( !$gBitUser->isRegistered() && $check_req) { $gBitSmarty->assign('msg', KernelTools::tra( "You must log in to use this feature" )); - $gBitSystem->display( 'error.tpl' , null, array( 'display_mode' => 'display' )); + $gBitSystem->display( 'error.tpl' , null, [ 'display_mode' => 'display' ]); die; } $url = $_SERVER["REQUEST_URI"]; if ($check_req) { // global $debugger; // $debugger->msg('Module control clicked: '.$check_req); - // Make defaults if user still ot configure modules for himself - if (!$usermoduleslib->user_has_assigned_modules($user)) - $usermoduleslib->create_user_assigned_modules($user); - // Handle control icon click + // Make defaults if user still ot configure modules for himself + if (!$usermoduleslib->user_has_assigned_modules($user)) + $usermoduleslib->create_user_assigned_modules($user); + // Handle control icon click if (isset($_REQUEST["mc_up"])) $usermoduleslib->swap_up_user_module($_REQUEST["mc_up"], $user); elseif (isset($_REQUEST["mc_down"])) @@ -48,10 +48,10 @@ if ($check_req) { $usermoduleslib->move_module($_REQUEST["mc_move"], $user); else $usermoduleslib->unassign_user_module($_REQUEST["mc_unassign"], $user); - // Remove module movemet paramaters from an URL - // \todo What if 'mc_xxx' arg was not at the end? (if smbd fix URL by hands...) - // should I handle this very special (hack?) case? - $url = preg_replace('/(.*)(\?|&)[1](mc_up|mc_down|mc_move|mc_unassign)=[^&]*/','\1', $url); + // Remove module movemet paramaters from an URL + // \todo What if 'mc_xxx' arg was not at the end? (if smbd fix URL by hands...) + // should I handle this very special (hack?) case? + $url = preg_replace('/(.*)(\?|&)[1](mc_up|mc_down|mc_move|mc_unassign)=[^&]*/','\1', $url); } // Fix locaton if parameter was removed... if ($url != $_SERVER["REQUEST_URI"]) header('location: '.$url); diff --git a/includes/recaptcha/ReCaptcha/ReCaptcha.php b/includes/recaptcha/ReCaptcha/ReCaptcha.php index 6984d0a..3bd41f9 100755 --- a/includes/recaptcha/ReCaptcha/ReCaptcha.php +++ b/includes/recaptcha/ReCaptcha/ReCaptcha.php @@ -39,237 +39,237 @@ namespace ReCaptcha; */ class ReCaptcha { - /** - * Version of this client library. - * @const string - */ - public const VERSION = 'php_1.3.0'; + /** + * Version of this client library. + * @const string + */ + public const VERSION = 'php_1.3.0'; - /** - * URL for reCAPTCHA siteverify API - * @const string - */ - public const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'; + /** + * URL for reCAPTCHA siteverify API + * @const string + */ + public const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'; - /** - * Invalid JSON received - * @const string - */ - public const E_INVALID_JSON = 'invalid-json'; + /** + * Invalid JSON received + * @const string + */ + public const E_INVALID_JSON = 'invalid-json'; - /** - * Could not connect to service - * @const string - */ - public const E_CONNECTION_FAILED = 'connection-failed'; + /** + * Could not connect to service + * @const string + */ + public const E_CONNECTION_FAILED = 'connection-failed'; - /** - * Did not receive a 200 from the service - * @const string - */ - public const E_BAD_RESPONSE = 'bad-response'; + /** + * Did not receive a 200 from the service + * @const string + */ + public const E_BAD_RESPONSE = 'bad-response'; - /** - * Not a success, but no error codes received! - * @const string - */ - public const E_UNKNOWN_ERROR = 'unknown-error'; + /** + * Not a success, but no error codes received! + * @const string + */ + public const E_UNKNOWN_ERROR = 'unknown-error'; - /** - * ReCAPTCHA response not provided - * @const string - */ - public const E_MISSING_INPUT_RESPONSE = 'missing-input-response'; + /** + * ReCAPTCHA response not provided + * @const string + */ + public const E_MISSING_INPUT_RESPONSE = 'missing-input-response'; - /** - * Expected hostname did not match - * @const string - */ - public const E_HOSTNAME_MISMATCH = 'hostname-mismatch'; + /** + * Expected hostname did not match + * @const string + */ + public const E_HOSTNAME_MISMATCH = 'hostname-mismatch'; - /** - * Expected APK package name did not match - * @const string - */ - public const E_APK_PACKAGE_NAME_MISMATCH = 'apk_package_name-mismatch'; + /** + * Expected APK package name did not match + * @const string + */ + public const E_APK_PACKAGE_NAME_MISMATCH = 'apk_package_name-mismatch'; - /** - * Expected action did not match - * @const string - */ - public const E_ACTION_MISMATCH = 'action-mismatch'; + /** + * Expected action did not match + * @const string + */ + public const E_ACTION_MISMATCH = 'action-mismatch'; - /** - * Score threshold not met - * @const string - */ - public const E_SCORE_THRESHOLD_NOT_MET = 'score-threshold-not-met'; + /** + * Score threshold not met + * @const string + */ + public const E_SCORE_THRESHOLD_NOT_MET = 'score-threshold-not-met'; - /** - * Challenge timeout - * @const string - */ - public const E_CHALLENGE_TIMEOUT = 'challenge-timeout'; + /** + * Challenge timeout + * @const string + */ + public const E_CHALLENGE_TIMEOUT = 'challenge-timeout'; - /** - * Shared secret for the site. - * @var string - */ - private $secret; + /** + * Shared secret for the site. + * @var string + */ + private $secret; - /** - * Method used to communicate with service. Defaults to POST request. - * @var RequestMethod - */ - private $requestMethod; + /** + * Method used to communicate with service. Defaults to POST request. + * @var RequestMethod + */ + private $requestMethod; - private $hostname; - private $apkPackageName; - private $action; - private $threshold; - private $timeoutSeconds; + private $hostname; + private $apkPackageName; + private $action; + private $threshold; + private $timeoutSeconds; - /** - * Create a configured instance to use the reCAPTCHA service. - * - * @param string $secret The shared key between your site and reCAPTCHA. - * @param RequestMethod $requestMethod method used to send the request. Defaults to POST. - * @throws \RuntimeException if $secret is invalid - */ - public function __construct($secret, RequestMethod $requestMethod = null) - { - if (empty($secret)) { - throw new \RuntimeException('No secret provided'); - } + /** + * Create a configured instance to use the reCAPTCHA service. + * + * @param string $secret The shared key between your site and reCAPTCHA. + * @param RequestMethod $requestMethod method used to send the request. Defaults to POST. + * @throws \RuntimeException if $secret is invalid + */ + public function __construct($secret, RequestMethod $requestMethod = null) + { + if (empty($secret)) { + throw new \RuntimeException('No secret provided'); + } - if (!is_string($secret)) { - throw new \RuntimeException('The provided secret must be a string'); - } + if (!is_string($secret)) { + throw new \RuntimeException('The provided secret must be a string'); + } - $this->secret = $secret; - $this->requestMethod = (is_null($requestMethod)) ? new RequestMethod\Post() : $requestMethod; - } + $this->secret = $secret; + $this->requestMethod = (is_null($requestMethod)) ? new RequestMethod\Post() : $requestMethod; + } - /** - * Calls the reCAPTCHA siteverify API to verify whether the user passes - * CAPTCHA test and additionally runs any specified additional checks - * - * @param string $response The user response token provided by reCAPTCHA, verifying the user on your site. - * @param string $remoteIp The end user's IP address. - * @return Response Response from the service. - */ - public function verify($response, $remoteIp = null) - { - // Discard empty solution submissions - if (empty($response)) { - $recaptchaResponse = new Response(false, array(self::E_MISSING_INPUT_RESPONSE)); - return $recaptchaResponse; - } + /** + * Calls the reCAPTCHA siteverify API to verify whether the user passes + * CAPTCHA test and additionally runs any specified additional checks + * + * @param string $response The user response token provided by reCAPTCHA, verifying the user on your site. + * @param string $remoteIp The end user's IP address. + * @return Response Response from the service. + */ + public function verify($response, $remoteIp = null) + { + // Discard empty solution submissions + if (empty($response)) { + $recaptchaResponse = new Response(false, [self::E_MISSING_INPUT_RESPONSE]); + return $recaptchaResponse; + } - $params = new RequestParameters($this->secret, $response, $remoteIp, self::VERSION); - $rawResponse = $this->requestMethod->submit($params); - $initialResponse = Response::fromJson($rawResponse); - $validationErrors = []; + $params = new RequestParameters($this->secret, $response, $remoteIp, self::VERSION); + $rawResponse = $this->requestMethod->submit($params); + $initialResponse = Response::fromJson($rawResponse); + $validationErrors = []; - if (isset($this->hostname) && strcasecmp($this->hostname, $initialResponse->getHostname()) !== 0) { - $validationErrors[] = self::E_HOSTNAME_MISMATCH; - } + if (isset($this->hostname) && strcasecmp($this->hostname, $initialResponse->getHostname()) !== 0) { + $validationErrors[] = self::E_HOSTNAME_MISMATCH; + } - if (isset($this->apkPackageName) && strcasecmp($this->apkPackageName, $initialResponse->getApkPackageName()) !== 0) { - $validationErrors[] = self::E_APK_PACKAGE_NAME_MISMATCH; - } + if (isset($this->apkPackageName) && strcasecmp($this->apkPackageName, $initialResponse->getApkPackageName()) !== 0) { + $validationErrors[] = self::E_APK_PACKAGE_NAME_MISMATCH; + } - if (isset($this->action) && strcasecmp($this->action, $initialResponse->getAction()) !== 0) { - $validationErrors[] = self::E_ACTION_MISMATCH; - } + if (isset($this->action) && strcasecmp($this->action, $initialResponse->getAction()) !== 0) { + $validationErrors[] = self::E_ACTION_MISMATCH; + } - if (isset($this->threshold) && $this->threshold > $initialResponse->getScore()) { - $validationErrors[] = self::E_SCORE_THRESHOLD_NOT_MET; - } + if (isset($this->threshold) && $this->threshold > $initialResponse->getScore()) { + $validationErrors[] = self::E_SCORE_THRESHOLD_NOT_MET; + } - if (isset($this->timeoutSeconds)) { - $challengeTs = strtotime($initialResponse->getChallengeTs()); + if (isset($this->timeoutSeconds)) { + $challengeTs = strtotime($initialResponse->getChallengeTs()); - if ($challengeTs > 0 && time() - $challengeTs > $this->timeoutSeconds) { - $validationErrors[] = self::E_CHALLENGE_TIMEOUT; - } - } + if ($challengeTs > 0 && time() - $challengeTs > $this->timeoutSeconds) { + $validationErrors[] = self::E_CHALLENGE_TIMEOUT; + } + } - if (empty($validationErrors)) { - return $initialResponse; - } + if (empty($validationErrors)) { + return $initialResponse; + } - return new Response( - false, - array_merge($initialResponse->getErrorCodes(), $validationErrors), - $initialResponse->getHostname(), - $initialResponse->getChallengeTs(), - $initialResponse->getApkPackageName(), - $initialResponse->getScore(), - $initialResponse->getAction() - ); - } + return new Response( + false, + array_merge($initialResponse->getErrorCodes(), $validationErrors), + $initialResponse->getHostname(), + $initialResponse->getChallengeTs(), + $initialResponse->getApkPackageName(), + $initialResponse->getScore(), + $initialResponse->getAction(), + ); + } - /** - * Provide a hostname to match against in verify() - * This should be without a protocol or trailing slash, e.g. www.google.com - * - * @param string $hostname Expected hostname - * @return ReCaptcha Current instance for fluent interface - */ - public function setExpectedHostname($hostname) - { - $this->hostname = $hostname; - return $this; - } + /** + * Provide a hostname to match against in verify() + * This should be without a protocol or trailing slash, e.g. www.google.com + * + * @param string $hostname Expected hostname + * @return ReCaptcha Current instance for fluent interface + */ + public function setExpectedHostname($hostname) + { + $this->hostname = $hostname; + return $this; + } - /** - * Provide an APK package name to match against in verify() - * - * @param string $apkPackageName Expected APK package name - * @return ReCaptcha Current instance for fluent interface - */ - public function setExpectedApkPackageName($apkPackageName) - { - $this->apkPackageName = $apkPackageName; - return $this; - } + /** + * Provide an APK package name to match against in verify() + * + * @param string $apkPackageName Expected APK package name + * @return ReCaptcha Current instance for fluent interface + */ + public function setExpectedApkPackageName($apkPackageName) + { + $this->apkPackageName = $apkPackageName; + return $this; + } - /** - * Provide an action to match against in verify() - * This should be set per page. - * - * @param string $action Expected action - * @return ReCaptcha Current instance for fluent interface - */ - public function setExpectedAction($action) - { - $this->action = $action; - return $this; - } + /** + * Provide an action to match against in verify() + * This should be set per page. + * + * @param string $action Expected action + * @return ReCaptcha Current instance for fluent interface + */ + public function setExpectedAction($action) + { + $this->action = $action; + return $this; + } - /** - * Provide a threshold to meet or exceed in verify() - * Threshold should be a float between 0 and 1 which will be tested as response >= threshold. - * - * @param float $threshold Expected threshold - * @return ReCaptcha Current instance for fluent interface - */ - public function setScoreThreshold($threshold) - { - $this->threshold = floatval($threshold); - return $this; - } + /** + * Provide a threshold to meet or exceed in verify() + * Threshold should be a float between 0 and 1 which will be tested as response >= threshold. + * + * @param float $threshold Expected threshold + * @return ReCaptcha Current instance for fluent interface + */ + public function setScoreThreshold($threshold) + { + $this->threshold = (float) $threshold; + return $this; + } - /** - * Provide a timeout in seconds to test against the challenge timestamp in verify() - * - * @param int $timeoutSeconds Expected hostname - * @return ReCaptcha Current instance for fluent interface - */ - public function setChallengeTimeout($timeoutSeconds) - { - $this->timeoutSeconds = $timeoutSeconds; - return $this; - } + /** + * Provide a timeout in seconds to test against the challenge timestamp in verify() + * + * @param int $timeoutSeconds Expected hostname + * @return ReCaptcha Current instance for fluent interface + */ + public function setChallengeTimeout($timeoutSeconds) + { + $this->timeoutSeconds = $timeoutSeconds; + return $this; + } } diff --git a/includes/recaptcha/ReCaptcha/RequestMethod.php b/includes/recaptcha/ReCaptcha/RequestMethod.php index bd2a949..b80eb7f 100644 --- a/includes/recaptcha/ReCaptcha/RequestMethod.php +++ b/includes/recaptcha/ReCaptcha/RequestMethod.php @@ -39,11 +39,11 @@ namespace ReCaptcha; */ interface RequestMethod { - /** - * Submit the request with the specified parameters. - * - * @param RequestParameters $params Request parameters - * @return string Body of the reCAPTCHA response - */ - public function submit(RequestParameters $params); + /** + * Submit the request with the specified parameters. + * + * @param RequestParameters $params Request parameters + * @return string Body of the reCAPTCHA response + */ + public function submit(RequestParameters $params); } diff --git a/includes/recaptcha/ReCaptcha/RequestMethod/Curl.php b/includes/recaptcha/ReCaptcha/RequestMethod/Curl.php index 2d3b389..15c5df3 100644 --- a/includes/recaptcha/ReCaptcha/RequestMethod/Curl.php +++ b/includes/recaptcha/ReCaptcha/RequestMethod/Curl.php @@ -39,43 +39,43 @@ namespace ReCaptcha\RequestMethod; */ class Curl { - /** - * @see http://php.net/curl_init - * @param string $url - * @return resource cURL handle - */ - public function init($url = null) - { - return curl_init($url); - } + /** + * @see http://php.net/curl_init + * @param string $url + * @return resource cURL handle + */ + public function init($url = null) + { + return curl_init($url); + } - /** - * @see http://php.net/curl_setopt_array - * @param resource $ch - * @param array $options - * @return bool - */ - public function setoptArray($ch, array $options) - { - return curl_setopt_array($ch, $options); - } + /** + * @see http://php.net/curl_setopt_array + * @param resource $ch + * @param array $options + * @return bool + */ + public function setoptArray($ch, array $options) + { + return curl_setopt_array($ch, $options); + } - /** - * @see http://php.net/curl_exec - * @param resource $ch - * @return mixed - */ - public function exec($ch) - { - return curl_exec($ch); - } + /** + * @see http://php.net/curl_exec + * @param resource $ch + * @return mixed + */ + public function exec($ch) + { + return curl_exec($ch); + } - /** - * @see http://php.net/curl_close - * @param resource $ch - */ - public function close($ch) - { - curl_close($ch); - } + /** + * @see http://php.net/curl_close + * @param resource $ch + */ + public function close($ch) + { + curl_close($ch); + } } diff --git a/includes/recaptcha/ReCaptcha/RequestMethod/CurlPost.php b/includes/recaptcha/ReCaptcha/RequestMethod/CurlPost.php index 1bd7cce..fc993d8 100644 --- a/includes/recaptcha/ReCaptcha/RequestMethod/CurlPost.php +++ b/includes/recaptcha/ReCaptcha/RequestMethod/CurlPost.php @@ -45,60 +45,60 @@ use ReCaptcha\RequestParameters; */ class CurlPost implements RequestMethod { - /** - * Curl connection to the reCAPTCHA service - * @var Curl - */ - private $curl; + /** + * Curl connection to the reCAPTCHA service + * @var Curl + */ + private $curl; - /** - * URL for reCAPTCHA siteverify API - * @var string - */ - private $siteVerifyUrl; + /** + * URL for reCAPTCHA siteverify API + * @var string + */ + private $siteVerifyUrl; - /** - * Only needed if you want to override the defaults - * - * @param Curl $curl Curl resource - * @param string $siteVerifyUrl URL for reCAPTCHA siteverify API - */ - public function __construct(Curl $curl = null, $siteVerifyUrl = null) - { - $this->curl = (is_null($curl)) ? new Curl() : $curl; - $this->siteVerifyUrl = (is_null($siteVerifyUrl)) ? ReCaptcha::SITE_VERIFY_URL : $siteVerifyUrl; - } + /** + * Only needed if you want to override the defaults + * + * @param Curl $curl Curl resource + * @param string $siteVerifyUrl URL for reCAPTCHA siteverify API + */ + public function __construct(Curl $curl = null, $siteVerifyUrl = null) + { + $this->curl = (is_null($curl)) ? new Curl() : $curl; + $this->siteVerifyUrl = (is_null($siteVerifyUrl)) ? ReCaptcha::SITE_VERIFY_URL : $siteVerifyUrl; + } - /** - * Submit the cURL request with the specified parameters. - * - * @param RequestParameters $params Request parameters - * @return string Body of the reCAPTCHA response - */ - public function submit(RequestParameters $params) - { - $handle = $this->curl->init($this->siteVerifyUrl); + /** + * Submit the cURL request with the specified parameters. + * + * @param RequestParameters $params Request parameters + * @return string Body of the reCAPTCHA response + */ + public function submit(RequestParameters $params) + { + $handle = $this->curl->init($this->siteVerifyUrl); - $options = array( - CURLOPT_POST => true, - CURLOPT_POSTFIELDS => $params->toQueryString(), - CURLOPT_HTTPHEADER => array( - 'Content-Type: application/x-www-form-urlencoded' - ), - CURLINFO_HEADER_OUT => false, - CURLOPT_HEADER => false, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_SSL_VERIFYPEER => true - ); - $this->curl->setoptArray($handle, $options); + $options = [ + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $params->toQueryString(), + CURLOPT_HTTPHEADER => [ + 'Content-Type: application/x-www-form-urlencoded', + ], + CURLINFO_HEADER_OUT => false, + CURLOPT_HEADER => false, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_SSL_VERIFYPEER => true, + ]; + $this->curl->setoptArray($handle, $options); - $response = $this->curl->exec($handle); - $this->curl->close($handle); + $response = $this->curl->exec($handle); + $this->curl->close($handle); - if ($response !== false) { - return $response; - } + if ($response !== false) { + return $response; + } - return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}'; - } + return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}'; + } } diff --git a/includes/recaptcha/ReCaptcha/RequestMethod/Post.php b/includes/recaptcha/ReCaptcha/RequestMethod/Post.php index a4ff716..936da97 100644 --- a/includes/recaptcha/ReCaptcha/RequestMethod/Post.php +++ b/includes/recaptcha/ReCaptcha/RequestMethod/Post.php @@ -43,46 +43,46 @@ use ReCaptcha\RequestParameters; */ class Post implements RequestMethod { - /** - * URL for reCAPTCHA siteverify API - * @var string - */ - private $siteVerifyUrl; + /** + * URL for reCAPTCHA siteverify API + * @var string + */ + private $siteVerifyUrl; - /** - * Only needed if you want to override the defaults - * - * @param string $siteVerifyUrl URL for reCAPTCHA siteverify API - */ - public function __construct($siteVerifyUrl = null) - { - $this->siteVerifyUrl = (is_null($siteVerifyUrl)) ? ReCaptcha::SITE_VERIFY_URL : $siteVerifyUrl; - } + /** + * Only needed if you want to override the defaults + * + * @param string $siteVerifyUrl URL for reCAPTCHA siteverify API + */ + public function __construct($siteVerifyUrl = null) + { + $this->siteVerifyUrl = (is_null($siteVerifyUrl)) ? ReCaptcha::SITE_VERIFY_URL : $siteVerifyUrl; + } - /** - * Submit the POST request with the specified parameters. - * - * @param RequestParameters $params Request parameters - * @return string Body of the reCAPTCHA response - */ - public function submit(RequestParameters $params) - { - $options = array( - 'http' => array( - 'header' => "Content-type: application/x-www-form-urlencoded\r\n", - 'method' => 'POST', - 'content' => $params->toQueryString(), - // Force the peer to validate (not needed in 5.6.0+, but still works) - 'verify_peer' => true, - ), - ); - $context = stream_context_create($options); - $response = file_get_contents($this->siteVerifyUrl, false, $context); + /** + * Submit the POST request with the specified parameters. + * + * @param RequestParameters $params Request parameters + * @return string Body of the reCAPTCHA response + */ + public function submit(RequestParameters $params) + { + $options = [ + 'http' => [ + 'header' => "Content-type: application/x-www-form-urlencoded\r\n", + 'method' => 'POST', + 'content' => $params->toQueryString(), + // Force the peer to validate (not needed in 5.6.0+, but still works) + 'verify_peer' => true, + ], + ]; + $context = stream_context_create($options); + $response = file_get_contents($this->siteVerifyUrl, false, $context); - if ($response !== false) { - return $response; - } + if ($response !== false) { + return $response; + } - return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}'; - } + return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}'; + } } diff --git a/includes/recaptcha/ReCaptcha/RequestMethod/Socket.php b/includes/recaptcha/ReCaptcha/RequestMethod/Socket.php index 236bd5f..56c638e 100644 --- a/includes/recaptcha/ReCaptcha/RequestMethod/Socket.php +++ b/includes/recaptcha/ReCaptcha/RequestMethod/Socket.php @@ -40,73 +40,73 @@ namespace ReCaptcha\RequestMethod; */ class Socket { - private $handle = null; + private $handle = null; - /** - * fsockopen - * - * @see http://php.net/fsockopen - * @param string $hostname - * @param int $port - * @param int $errno - * @param string $errstr - * @param float $timeout - * @return resource - */ - public function fsockopen($hostname, $port = -1, &$errno = 0, &$errstr = '', $timeout = null) - { - $this->handle = fsockopen($hostname, $port, $errno, $errstr, (is_null($timeout) ? ini_get("default_socket_timeout") : $timeout)); + /** + * fsockopen + * + * @see http://php.net/fsockopen + * @param string $hostname + * @param int $port + * @param int $errno + * @param string $errstr + * @param float $timeout + * @return resource + */ + public function fsockopen($hostname, $port = -1, &$errno = 0, &$errstr = '', $timeout = null) + { + $this->handle = fsockopen($hostname, $port, $errno, $errstr, (is_null($timeout) ? ini_get("default_socket_timeout") : $timeout)); - if ($this->handle != false && $errno === 0 && $errstr === '') { - return $this->handle; - } - return false; - } + if ($this->handle != false && $errno === 0 && $errstr === '') { + return $this->handle; + } + return false; + } - /** - * fwrite - * - * @see http://php.net/fwrite - * @param string $string - * @param int $length - * @return int | bool - */ - public function fwrite($string, $length = null) - { - return fwrite($this->handle, $string, (is_null($length) ? strlen($string) : $length)); - } + /** + * fwrite + * + * @see http://php.net/fwrite + * @param string $string + * @param int $length + * @return int | bool + */ + public function fwrite($string, $length = null) + { + return fwrite($this->handle, $string, (is_null($length) ? strlen($string) : $length)); + } - /** - * fgets - * - * @see http://php.net/fgets - * @param int $length - * @return string - */ - public function fgets($length = null) - { - return fgets($this->handle, $length); - } + /** + * fgets + * + * @see http://php.net/fgets + * @param int $length + * @return string + */ + public function fgets($length = null) + { + return fgets($this->handle, $length); + } - /** - * feof - * - * @see http://php.net/feof - * @return bool - */ - public function feof() - { - return feof($this->handle); - } + /** + * feof + * + * @see http://php.net/feof + * @return bool + */ + public function feof() + { + return feof($this->handle); + } - /** - * fclose - * - * @see http://php.net/fclose - * @return bool - */ - public function fclose() - { - return fclose($this->handle); - } + /** + * fclose + * + * @see http://php.net/fclose + * @return bool + */ + public function fclose() + { + return fclose($this->handle); + } } diff --git a/includes/recaptcha/ReCaptcha/RequestMethod/SocketPost.php b/includes/recaptcha/ReCaptcha/RequestMethod/SocketPost.php index 19d50ab..0413af3 100644 --- a/includes/recaptcha/ReCaptcha/RequestMethod/SocketPost.php +++ b/includes/recaptcha/ReCaptcha/RequestMethod/SocketPost.php @@ -45,66 +45,66 @@ use ReCaptcha\RequestParameters; */ class SocketPost implements RequestMethod { - /** - * Socket to the reCAPTCHA service - * @var Socket - */ - private $socket; + /** + * Socket to the reCAPTCHA service + * @var Socket + */ + private $socket; - private $siteVerifyUrl; + private $siteVerifyUrl; - /** - * Only needed if you want to override the defaults - * - * @param \ReCaptcha\RequestMethod\Socket $socket optional socket, injectable for testing - * @param string $siteVerifyUrl URL for reCAPTCHA siteverify API - */ - public function __construct(Socket $socket = null, $siteVerifyUrl = null) - { - $this->socket = (is_null($socket)) ? new Socket() : $socket; - $this->siteVerifyUrl = (is_null($siteVerifyUrl)) ? ReCaptcha::SITE_VERIFY_URL : $siteVerifyUrl; - } + /** + * Only needed if you want to override the defaults + * + * @param \ReCaptcha\RequestMethod\Socket $socket optional socket, injectable for testing + * @param string $siteVerifyUrl URL for reCAPTCHA siteverify API + */ + public function __construct(Socket $socket = null, $siteVerifyUrl = null) + { + $this->socket = (is_null($socket)) ? new Socket() : $socket; + $this->siteVerifyUrl = (is_null($siteVerifyUrl)) ? ReCaptcha::SITE_VERIFY_URL : $siteVerifyUrl; + } - /** - * Submit the POST request with the specified parameters. - * - * @param RequestParameters $params Request parameters - * @return string Body of the reCAPTCHA response - */ - public function submit(RequestParameters $params) - { - $errno = 0; - $errstr = ''; - $urlParsed = parse_url($this->siteVerifyUrl); + /** + * Submit the POST request with the specified parameters. + * + * @param RequestParameters $params Request parameters + * @return string Body of the reCAPTCHA response + */ + public function submit(RequestParameters $params) + { + $errno = 0; + $errstr = ''; + $urlParsed = parse_url($this->siteVerifyUrl); - if (false === $this->socket->fsockopen('ssl://' . $urlParsed['host'], 443, $errno, $errstr, 30)) { - return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}'; - } + if (false === $this->socket->fsockopen('ssl://' . $urlParsed['host'], 443, $errno, $errstr, 30)) { + return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}'; + } - $content = $params->toQueryString(); + $content = $params->toQueryString(); - $request = "POST " . $urlParsed['path'] . " HTTP/1.0\r\n"; - $request .= "Host: " . $urlParsed['host'] . "\r\n"; - $request .= "Content-Type: application/x-www-form-urlencoded\r\n"; - $request .= "Content-length: " . strlen($content) . "\r\n"; - $request .= "Connection: close\r\n\r\n"; - $request .= $content . "\r\n\r\n"; + $request = "POST " . $urlParsed['path'] . " HTTP/1.0\r\n"; + $request .= "Host: " . $urlParsed['host'] . "\r\n"; + $request .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $request .= "Content-length: " . strlen($content) . "\r\n"; + $request .= "Connection: close\r\n\r\n"; + $request .= $content . "\r\n\r\n"; - $this->socket->fwrite($request); - $response = ''; + $this->socket->fwrite($request); + $response = ''; - while (!$this->socket->feof()) { - $response .= $this->socket->fgets(4096); - } + while (!$this->socket->feof()) { + $response .= $this->socket->fgets(4096); + } - $this->socket->fclose(); + $this->socket->fclose(); - if (0 !== strpos($response, 'HTTP/1.0 200 OK')) { - return '{"success": false, "error-codes": ["'.ReCaptcha::E_BAD_RESPONSE.'"]}'; - } + if (0 !== strpos($response, 'HTTP/1.0 200 OK')) { + return '{"success": false, "error-codes": ["'.ReCaptcha::E_BAD_RESPONSE.'"]}'; + } - $parts = preg_split("#\n\s*\n#Uis", $response); + $parts = preg_split("#\n\s*\n#Uis", $response); - return $parts[1]; - } + return $parts[1]; + } } diff --git a/includes/recaptcha/ReCaptcha/RequestParameters.php b/includes/recaptcha/ReCaptcha/RequestParameters.php index e9ba453..2d4eeb3 100644 --- a/includes/recaptcha/ReCaptcha/RequestParameters.php +++ b/includes/recaptcha/ReCaptcha/RequestParameters.php @@ -39,73 +39,73 @@ namespace ReCaptcha; */ class RequestParameters { - /** - * The shared key between your site and reCAPTCHA. - * @var string - */ - private $secret; + /** + * The shared key between your site and reCAPTCHA. + * @var string + */ + private $secret; - /** - * The user response token provided by reCAPTCHA, verifying the user on your site. - * @var string - */ - private $response; + /** + * The user response token provided by reCAPTCHA, verifying the user on your site. + * @var string + */ + private $response; - /** - * Remote user's IP address. - * @var string - */ - private $remoteIp; + /** + * Remote user's IP address. + * @var string + */ + private $remoteIp; - /** - * Client version. - * @var string - */ - private $version; + /** + * Client version. + * @var string + */ + private $version; - /** - * Initialise parameters. - * - * @param string $secret Site secret. - * @param string $response Value from g-captcha-response form field. - * @param string $remoteIp User's IP address. - * @param string $version Version of this client library. - */ - public function __construct($secret, $response, $remoteIp = null, $version = null) - { - $this->secret = $secret; - $this->response = $response; - $this->remoteIp = $remoteIp; - $this->version = $version; - } + /** + * Initialise parameters. + * + * @param string $secret Site secret. + * @param string $response Value from g-captcha-response form field. + * @param string $remoteIp User's IP address. + * @param string $version Version of this client library. + */ + public function __construct($secret, $response, $remoteIp = null, $version = null) + { + $this->secret = $secret; + $this->response = $response; + $this->remoteIp = $remoteIp; + $this->version = $version; + } - /** - * Array representation. - * - * @return array Array formatted parameters. - */ - public function toArray() - { - $params = array('secret' => $this->secret, 'response' => $this->response); + /** + * Array representation. + * + * @return array Array formatted parameters. + */ + public function toArray() + { + $params = ['secret' => $this->secret, 'response' => $this->response]; - if (!is_null($this->remoteIp)) { - $params['remoteip'] = $this->remoteIp; - } + if (!is_null($this->remoteIp)) { + $params['remoteip'] = $this->remoteIp; + } - if (!is_null($this->version)) { - $params['version'] = $this->version; - } + if (!is_null($this->version)) { + $params['version'] = $this->version; + } - return $params; - } + return $params; + } - /** - * Query string representation for HTTP request. - * - * @return string Query string formatted parameters. - */ - public function toQueryString() - { - return http_build_query($this->toArray(), '', '&'); - } + /** + * Query string representation for HTTP request. + * + * @return string Query string formatted parameters. + */ + public function toQueryString() + { + return http_build_query($this->toArray(), '', '&'); + } } diff --git a/includes/recaptcha/ReCaptcha/Response.php b/includes/recaptcha/ReCaptcha/Response.php index b73d71a..e00ff0e 100755 --- a/includes/recaptcha/ReCaptcha/Response.php +++ b/includes/recaptcha/ReCaptcha/Response.php @@ -39,180 +39,180 @@ namespace ReCaptcha; */ class Response { - /** - * Success or failure. - * @var boolean - */ - private $success = false; + /** + * Success or failure. + * @var boolean + */ + private $success = false; - /** - * Error code strings. - * @var array - */ - private $errorCodes = []; + /** + * Error code strings. + * @var array + */ + private $errorCodes = []; - /** - * The hostname of the site where the reCAPTCHA was solved. - * @var string - */ - private $hostname; + /** + * The hostname of the site where the reCAPTCHA was solved. + * @var string + */ + private $hostname; - /** - * Timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ) - * @var string - */ - private $challengeTs; + /** + * Timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ) + * @var string + */ + private $challengeTs; - /** - * APK package name - * @var string - */ - private $apkPackageName; + /** + * APK package name + * @var string + */ + private $apkPackageName; - /** - * Score assigned to the request - * @var float - */ - private $score; + /** + * Score assigned to the request + * @var float + */ + private $score; - /** - * Action as specified by the page - * @var string - */ - private $action; + /** + * Action as specified by the page + * @var string + */ + private $action; - /** - * Build the response from the expected JSON returned by the service. - * - * @param string $json - * @return \ReCaptcha\Response - */ - public static function fromJson($json) - { - $responseData = json_decode($json, true); + /** + * Build the response from the expected JSON returned by the service. + * + * @param string $json + * @return \ReCaptcha\Response + */ + public static function fromJson($json) + { + $responseData = json_decode($json, true); - if (!$responseData) { - return new Response(false, array(ReCaptcha::E_INVALID_JSON)); - } + if (!$responseData) { + return new Response(false, [ReCaptcha::E_INVALID_JSON]); + } - $hostname = isset($responseData['hostname']) ? $responseData['hostname'] : null; - $challengeTs = isset($responseData['challenge_ts']) ? $responseData['challenge_ts'] : null; - $apkPackageName = isset($responseData['apk_package_name']) ? $responseData['apk_package_name'] : null; - $score = isset($responseData['score']) ? floatval($responseData['score']) : null; - $action = isset($responseData['action']) ? $responseData['action'] : null; + $hostname = $responseData['hostname'] ?? null; + $challengeTs = $responseData['challenge_ts'] ?? null; + $apkPackageName = $responseData['apk_package_name'] ?? null; + $score = isset($responseData['score']) ? (float) ($responseData['score']) : null; + $action = $responseData['action'] ?? null; - if (isset($responseData['success']) && $responseData['success'] == true) { - return new Response(true, [], $hostname, $challengeTs, $apkPackageName, $score, $action); - } + if (isset($responseData['success']) && $responseData['success'] == true) { + return new Response(true, [], $hostname, $challengeTs, $apkPackageName, $score, $action); + } - if (isset($responseData['error-codes']) && is_array($responseData['error-codes'])) { - return new Response(false, $responseData['error-codes'], $hostname, $challengeTs, $apkPackageName, $score, $action); - } + if (isset($responseData['error-codes']) && is_array($responseData['error-codes'])) { + return new Response(false, $responseData['error-codes'], $hostname, $challengeTs, $apkPackageName, $score, $action); + } - return new Response(false, array(ReCaptcha::E_UNKNOWN_ERROR), $hostname, $challengeTs, $apkPackageName, $score, $action); - } + return new Response(false, [ReCaptcha::E_UNKNOWN_ERROR], $hostname, $challengeTs, $apkPackageName, $score, $action); + } - /** - * Constructor. - * - * @param boolean $success - * @param string $hostname - * @param string $challengeTs - * @param string $apkPackageName - * @param float $score - * @param string $action - * @param array $errorCodes - */ - public function __construct($success, array $errorCodes = [], $hostname = null, $challengeTs = null, $apkPackageName = null, $score = null, $action = null) - { - $this->success = $success; - $this->hostname = $hostname; - $this->challengeTs = $challengeTs; - $this->apkPackageName = $apkPackageName; - $this->score = $score; - $this->action = $action; - $this->errorCodes = $errorCodes; - } + /** + * Constructor. + * + * @param boolean $success + * @param string $hostname + * @param string $challengeTs + * @param string $apkPackageName + * @param float $score + * @param string $action + * @param array $errorCodes + */ + public function __construct($success, array $errorCodes = [], $hostname = null, $challengeTs = null, $apkPackageName = null, $score = null, $action = null) + { + $this->success = $success; + $this->hostname = $hostname; + $this->challengeTs = $challengeTs; + $this->apkPackageName = $apkPackageName; + $this->score = $score; + $this->action = $action; + $this->errorCodes = $errorCodes; + } - /** - * Is success? - * - * @return boolean - */ - public function isSuccess() - { - return $this->success; - } + /** + * Is success? + * + * @return boolean + */ + public function isSuccess() + { + return $this->success; + } - /** - * Get error codes. - * - * @return array - */ - public function getErrorCodes() - { - return $this->errorCodes; - } + /** + * Get error codes. + * + * @return array + */ + public function getErrorCodes() + { + return $this->errorCodes; + } - /** - * Get hostname. - * - * @return string - */ - public function getHostname() - { - return $this->hostname; - } + /** + * Get hostname. + * + * @return string + */ + public function getHostname() + { + return $this->hostname; + } - /** - * Get challenge timestamp - * - * @return string - */ - public function getChallengeTs() - { - return $this->challengeTs; - } + /** + * Get challenge timestamp + * + * @return string + */ + public function getChallengeTs() + { + return $this->challengeTs; + } - /** - * Get APK package name - * - * @return string - */ - public function getApkPackageName() - { - return $this->apkPackageName; - } - /** - * Get score - * - * @return float - */ - public function getScore() - { - return $this->score; - } + /** + * Get APK package name + * + * @return string + */ + public function getApkPackageName() + { + return $this->apkPackageName; + } + /** + * Get score + * + * @return float + */ + public function getScore() + { + return $this->score; + } - /** - * Get action - * - * @return string - */ - public function getAction() - { - return $this->action; - } + /** + * Get action + * + * @return string + */ + public function getAction() + { + return $this->action; + } - public function toArray() - { - return array( - 'success' => $this->isSuccess(), - 'hostname' => $this->getHostname(), - 'challenge_ts' => $this->getChallengeTs(), - 'apk_package_name' => $this->getApkPackageName(), - 'score' => $this->getScore(), - 'action' => $this->getAction(), - 'error-codes' => $this->getErrorCodes(), - ); - } + public function toArray() + { + return [ + 'success' => $this->isSuccess(), + 'hostname' => $this->getHostname(), + 'challenge_ts' => $this->getChallengeTs(), + 'apk_package_name' => $this->getApkPackageName(), + 'score' => $this->getScore(), + 'action' => $this->getAction(), + 'error-codes' => $this->getErrorCodes(), + ]; + } } diff --git a/includes/recaptcha/autoload.php b/includes/recaptcha/autoload.php index 7947a10..392bc64 100644 --- a/includes/recaptcha/autoload.php +++ b/includes/recaptcha/autoload.php @@ -35,35 +35,35 @@ */ spl_autoload_register(function ($class) { - if (substr($class, 0, 10) !== 'ReCaptcha\\') { - /* If the class does not lie under the "ReCaptcha" namespace, - * then we can exit immediately. - */ - return; - } + if (substr($class, 0, 10) !== 'ReCaptcha\\') { + /* If the class does not lie under the "ReCaptcha" namespace, + * then we can exit immediately. + */ + return; + } - /* All of the classes have names like "ReCaptcha\Foo", so we need - * to replace the backslashes with frontslashes if we want the - * name to map directly to a location in the filesystem. - */ - $class = str_replace('\\', '/', $class); + /* All of the classes have names like "ReCaptcha\Foo", so we need + * to replace the backslashes with frontslashes if we want the + * name to map directly to a location in the filesystem. + */ + $class = str_replace('\\', '/', $class); - /* First, check under the current directory. It is important that - * we look here first, so that we don't waste time searching for - * test classes in the common case. - */ - $path = dirname(__FILE__).'/'.$class.'.php'; - if (is_readable($path)) { - require_once $path; + /* First, check under the current directory. It is important that + * we look here first, so that we don't waste time searching for + * test classes in the common case. + */ + $path = dirname(__FILE__).'/'.$class.'.php'; + if (is_readable($path)) { + require_once $path; - return; - } + return; + } - /* If we didn't find what we're looking for already, maybe it's - * a test class? - */ - $path = dirname(__FILE__).'/../tests/'.$class.'.php'; - if (is_readable($path)) { - require_once $path; - } + /* If we didn't find what we're looking for already, maybe it's + * a test class? + */ + $path = dirname(__FILE__).'/../tests/'.$class.'.php'; + if (is_readable($path)) { + require_once $path; + } }); diff --git a/includes/register_inc.php b/includes/register_inc.php index 2b6b374..89f8324 100755 --- a/includes/register_inc.php +++ b/includes/register_inc.php @@ -1,11 +1,11 @@ <?php namespace Bitweaver\Users; + use Bitweaver\HttpStatusCodes; use Bitweaver\KernelTools; use Bitweaver\Wiki\BitPage; -use Bitweaver\Users\RolePermUser; - // Register the new user +// Register the new user $userClass = $gBitSystem->getConfig( 'user_class', 'RolePermUser' ); $newUser = new $userClass(); @@ -45,7 +45,7 @@ use Bitweaver\Users\RolePermUser; $newUser->storePreference('users_information','private'); } - // requires validation by email + // requires validation by email if( $gBitSystem->isFeatureActive( 'users_validate_user' ) ) { $gBitSmarty->assign('msg',KernelTools::tra('You will receive an email with information to login for the first time into this site')); $gBitSmarty->assign('showmsg','y'); @@ -63,7 +63,7 @@ use Bitweaver\Users\RolePermUser; // return to referring page if( !empty( $_SESSION['returnto'] ) ) { $url = $_SESSION['returnto']; - // forward to group post-registration page + // forward to group post-registration page } elseif ( !empty( $_REQUEST['group'] ) && !empty( $groupInfo['after_registration_page'] ) ) { if ( $newUser->verifyId( $groupInfo['after_registration_page'] ) ) { $url = BIT_ROOT_URI."index.php?content_id=".$groupInfo['after_registration_page']; diff --git a/includes/solvemedialib.php b/includes/solvemedialib.php index 51b4617..a33d62c 100755 --- a/includes/solvemedialib.php +++ b/includes/solvemedialib.php @@ -55,17 +55,15 @@ define("ADCOPY_SIGNUP", "http://api.solvemedia.com/public/signup"); * @return string - encoded request */ function _adcopy_qsencode ($data) { - $req = ""; - foreach ( $data as $key => $value ) - $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; + $req = ""; + foreach ( $data as $key => $value ) + $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; - // Cut the last '&' - $req=substr($req,0,strlen($req)-1); - return $req; + // Cut the last '&' + $req=substr($req,0,strlen($req)-1); + return $req; } - - /** * Submits an HTTP POST to a solvemedia server * @param string $host @@ -76,33 +74,31 @@ function _adcopy_qsencode ($data) { */ function _adcopy_http_post($host, $path, $data, $port = 80) { - $req = _adcopy_qsencode ($data); + $req = _adcopy_qsencode ($data); - $http_request = "POST $path HTTP/1.0\r\n"; - $http_request .= "Host: $host\r\n"; - $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; - $http_request .= "Content-Length: " . strlen($req) . "\r\n"; - $http_request .= "User-Agent: solvemedia/PHP\r\n"; - $http_request .= "\r\n"; - $http_request .= $req; + $http_request = "POST $path HTTP/1.0\r\n"; + $http_request .= "Host: $host\r\n"; + $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; + $http_request .= "Content-Length: " . strlen($req) . "\r\n"; + $http_request .= "User-Agent: solvemedia/PHP\r\n"; + $http_request .= "\r\n"; + $http_request .= $req; - $response = ''; - if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { - die ('Could not open socket'); - } + $response = ''; + if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { + die ('Could not open socket'); + } - fwrite($fs, $http_request); + fwrite($fs, $http_request); - while ( !feof($fs) ) - $response .= fgets($fs, 1024); // One TCP-IP packet [sic] - fclose($fs); - $response = explode("\r\n\r\n", $response, 2); + while ( !feof($fs) ) + $response .= fgets($fs, 1024); // One TCP-IP packet [sic] + fclose($fs); + $response = explode("\r\n\r\n", $response, 2); - return $response; + return $response; } - - /** * Gets the challenge HTML (javascript and non-javascript version). * This is called from the browser, and the resulting solvemedia HTML widget @@ -120,16 +116,16 @@ function solvemedia_get_html ($pubkey, $error = null, $use_ssl = false) } if ($use_ssl) { - $server = ADCOPY_API_SECURE_SERVER; - } else { - $server = ADCOPY_API_SERVER; - } + $server = ADCOPY_API_SECURE_SERVER; + } else { + $server = ADCOPY_API_SERVER; + } - $errorpart = ""; - if ($error) { - $errorpart = ";error=1"; - } - return '<script type="text/javascript" src="'. $server . '/papi/challenge.script?k=' . $pubkey . $errorpart . '"></script> + $errorpart = ""; + if ($error) { + $errorpart = ";error=1"; + } + return '<script type="text/javascript" src="'. $server . '/papi/challenge.script?k=' . $pubkey . $errorpart . '"></script> <noscript> <iframe src="'. $server . '/papi/challenge.noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/> @@ -138,18 +134,14 @@ function solvemedia_get_html ($pubkey, $error = null, $use_ssl = false) </noscript>'; } - - - /** * A SolveMediaResponse is returned from solvemedia_check_answer() */ class SolveMediaResponse { - var $is_valid; - var $error; + var $is_valid; + var $error; } - /** * Calls an HTTP POST function to verify if the user's guess was correct * @param string $privkey @@ -169,45 +161,45 @@ function solvemedia_check_answer ($privkey, $remoteip, $challenge, $response, $h die ("For security reasons, you must pass the remote ip to solvemedia"); } - //discard spam submissions - if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { - $adcopy_response = new SolveMediaResponse(); - $adcopy_response->is_valid = false; - $adcopy_response->error = 'incorrect-solution'; - return $adcopy_response; - } + //discard spam submissions + if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { + $adcopy_response = new SolveMediaResponse(); + $adcopy_response->is_valid = false; + $adcopy_response->error = 'incorrect-solution'; + return $adcopy_response; + } - $response = _adcopy_http_post (ADCOPY_VERIFY_SERVER, "/papi/verify", - array ( - 'privatekey' => $privkey, - 'remoteip' => $remoteip, - 'challenge' => $challenge, - 'response' => $response - ) - ); + $response = _adcopy_http_post (ADCOPY_VERIFY_SERVER, "/papi/verify", + [ + 'privatekey' => $privkey, + 'remoteip' => $remoteip, + 'challenge' => $challenge, + 'response' => $response, + ], + ); - $answers = explode ("\n", $response [1]); - $adcopy_response = new SolveMediaResponse(); + $answers = explode ("\n", $response [1]); + $adcopy_response = new SolveMediaResponse(); - if( strlen($hashkey) ){ - # validate message authenticator - $hash = sha1( $answers[0] . $challenge . $hashkey ); + if( strlen($hashkey) ){ + # validate message authenticator + $hash = sha1( $answers[0] . $challenge . $hashkey ); - if( $hash != $answers[2] ){ - $adcopy_response->is_valid = false; - $adcopy_response->error = 'hash-fail'; - return $adcopy_response; - } - } + if( $hash != $answers[2] ){ + $adcopy_response->is_valid = false; + $adcopy_response->error = 'hash-fail'; + return $adcopy_response; + } + } - if (trim ($answers [0]) == 'true') { - $adcopy_response->is_valid = true; - } - else { - $adcopy_response->is_valid = false; - $adcopy_response->error = $answers [1]; - } - return $adcopy_response; + if (trim ($answers [0]) == 'true') { + $adcopy_response->is_valid = true; + } + else { + $adcopy_response->is_valid = false; + $adcopy_response->error = $answers [1]; + } + return $adcopy_response; } @@ -219,10 +211,9 @@ function solvemedia_check_answer ($privkey, $remoteip, $challenge, $response, $h * @param string $appname The name of your application */ function solvemedia_get_signup_url ($domain = null, $appname = null) { - return ADCOPY_SIGNUP . "?" . _adcopy_qsencode (array ('domain' => $domain, 'app' => $appname)); + return ADCOPY_SIGNUP . "?" . _adcopy_qsencode ( ['domain' => $domain, 'app' => $appname]); } - /** * Calls an HTTP POST function to verify if the user's response was correct * @param string $privkey @@ -232,32 +223,32 @@ function solvemedia_get_signup_url ($domain = null, $appname = null) { function solvemedia_precheck_response ($privkey, $verifycode) { - //discard spam submissions - if ($verifycode == null || strlen($verifycode) == 0 ) { - $adcopy_response = new SolveMediaResponse(); - $adcopy_response->is_valid = false; - $adcopy_response->error = 'incorrect-solution'; - return $adcopy_response; - } + //discard spam submissions + if ($verifycode == null || strlen($verifycode) == 0 ) { + $adcopy_response = new SolveMediaResponse(); + $adcopy_response->is_valid = false; + $adcopy_response->error = 'incorrect-solution'; + return $adcopy_response; + } - $response = _adcopy_http_post (ADCOPY_VERIFY_SERVER, "/papi/verify.precheck.server", - array ( - 'privatekey' => $privkey, - 'verify_code' => $verifycode - ) - ); + $response = _adcopy_http_post (ADCOPY_VERIFY_SERVER, "/papi/verify.precheck.server", + [ + 'privatekey' => $privkey, + 'verify_code' => $verifycode, + ], + ); - $answers = explode ("\n", $response [1]); - $adcopy_response = new SolveMediaResponse(); + $answers = explode ("\n", $response [1]); + $adcopy_response = new SolveMediaResponse(); - if (trim ($answers [0]) == 'true') { - $adcopy_response->is_valid = true; - } - else { - $adcopy_response->is_valid = false; - $adcopy_response->error = $answers [1]; - } + if (trim ($answers [0]) == 'true') { + $adcopy_response->is_valid = true; + } + else { + $adcopy_response->is_valid = false; + $adcopy_response->error = $answers [1]; + } - return $adcopy_response; + return $adcopy_response; } diff --git a/includes/users_lib.php b/includes/users_lib.php index 90095f5..ed5b05f 100755 --- a/includes/users_lib.php +++ b/includes/users_lib.php @@ -37,9 +37,9 @@ function users_admin_email_user( &$pParamHash ) { mail( $pParamHash['email'], $siteName.' - '.KernelTools::tra( 'Your registration information' ),$mail_data,"From: ".$gBitSystem->getConfig( 'site_sender_email' )."\r\nContent-type: text/plain;charset=utf-8\r\n" ); $gBitSmarty->assign( 'showmsg', 'n' ); - $ret = array( - 'confirm' => 'Validation email sent to '.$pParamHash['email'].'.' - ); + $ret = [ + 'confirm' => 'Validation email sent to '.$pParamHash['email'].'.', + ]; } elseif( !empty( $pParamHash['password'] )) { // Send the welcome mail $gBitSmarty->assign( 'mailPassword',$pParamHash['password'] ); @@ -47,7 +47,7 @@ function users_admin_email_user( &$pParamHash ) { $mail_data = $gBitSmarty->fetch( 'bitpackage:users/admin_welcome_mail.tpl' ); mail( $pParamHash["email"], KernelTools::tra( 'Welcome to' ).' '.$siteName,$mail_data,"From: ".$gBitSystem->getConfig('site_sender_email')."\r\nContent-type: text/plain;charset=utf-8\r\n" ); $ret = [ - 'welcome' => 'Welcome email sent to ' . $pParamHash['email'] . '.' + 'welcome' => 'Welcome email sent to ' . $pParamHash['email'] . '.', ]; } return $ret; @@ -64,9 +64,9 @@ function users_admin_email_user( &$pParamHash ) { function scramble_email( $email, $method = 'unicode' ) { switch( $method ) { case 'strtr': - $trans = array( "@" => KernelTools::tra(" AT "), - "." => KernelTools::tra(" DOT ") - ); + $trans = [ "@" => KernelTools::tra(" AT "), + "." => KernelTools::tra(" DOT "), + ]; $ret = strtr($email, $trans); break; @@ -95,7 +95,6 @@ function scramble_email( $email, $method = 'unicode' ) { return $ret; } - function users_httpauth(){ global $gBitSystem, $gBitUser; // require ssl @@ -114,8 +113,8 @@ function users_httpauth(){ exit; } - $user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : false; - $pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : false; + $user = $_SERVER['PHP_AUTH_USER'] ?? false; + $pass = $_SERVER['PHP_AUTH_PW'] ?? false; $challenge = false; $response = false; // verify the user is valid first @@ -125,10 +124,10 @@ function users_httpauth(){ return true; } // require http auth - else{ + header('WWW-Authenticate: Basic realm="Test"'); header('HTTP/1.0 401 Unauthorized'); $gBitSystem->fatalError( KernelTools::tra('HTTP Authentication Canceled') ); exit; - } + } @@ -119,4 +119,4 @@ if( !empty( $_REQUEST['home'] ) ) { } $gBitSmarty->assign( 'gBitLanguage', $gBitLanguage ); -$gBitSystem->display( $centerDisplay, $browserTitle , array( 'display_mode' => 'display' )); +$gBitSystem->display( $centerDisplay, $browserTitle , [ 'display_mode' => 'display' ]); diff --git a/liberty_plugins/data.userlink.php b/liberty_plugins/data.userlink.php index 73a943d..c8bce63 100755 --- a/liberty_plugins/data.userlink.php +++ b/liberty_plugins/data.userlink.php @@ -1,5 +1,6 @@ <?php namespace Bitweaver\Liberty; + use Bitweaver\KernelTools; /** @@ -39,7 +40,7 @@ $pluginParams = [ 'description' => KernelTools::tra("Will show a link to the userpage for a given login name or email."), 'help_function' => 'data_userlink_help', 'syntax' => "{USERLINK login='bigwasp'}", - 'plugin_type' => DATA_PLUGIN + 'plugin_type' => DATA_PLUGIN, ]; $gLibertySystem->registerPlugin( PLUGIN_GUID_DATAUSERLINK, $pluginParams ); $gLibertySystem->registerDataTag( $pluginParams['tag'], PLUGIN_GUID_DATAUSERLINK ); @@ -47,24 +48,24 @@ $gLibertySystem->registerDataTag( $pluginParams['tag'], PLUGIN_GUID_DATAUSERLINK // Help Function function data_userlink_help() { $help = - '<table class="data help">' - .'<tr>' - .'<th>' . KernelTools::tra( "Key" ) . '</th>' + '<table class="data help">' + .'<tr>' + .'<th>' . KernelTools::tra( "Key" ) . '</th>' .'<th>' . KernelTools::tra( "Type" ) . '</th>' .'<th>' . KernelTools::tra( "Comments") . '</th>' .'</tr>' .'<tr class="odd">' - .'<td>login</td>' - .'<td>' . KernelTools::tra( "string" ) . '<br />' . KernelTools::tra( "(optional)") . '</td>' + .'<td>login</td>' + .'<td>' . KernelTools::tra( "string" ) . '<br />' . KernelTools::tra( "(optional)") . '</td>' .'<td>' . KernelTools::tra( "The login name to generate the link" ) . '</td>' .'</tr>' .'<tr class="even">' - .'<td>email</td>' + .'<td>email</td>' .'<td>' . KernelTools::tra( "string" ) . '<br />' . KernelTools::tra( "(optional)") . '</td>' .'<td>' . KernelTools::tra( "The e-mail address to generate the link" ) . '</td>' .'</tr>' .'<tr class="odd">' - .'<td>label</td>' + .'<td>label</td>' .'<td>' . KernelTools::tra( "string" ) . '<br />' . KernelTools::tra( "(optional)") . '</td>' .'<td>' . KernelTools::tra( "The label to show; default is user's name" ) . '</td>' .'</tr>' diff --git a/modules/help_mod_online_users.tpl b/modules/help_mod_online_users.tpl index f6c309e..f6c309e 100644..100755 --- a/modules/help_mod_online_users.tpl +++ b/modules/help_mod_online_users.tpl diff --git a/modules/help_mod_since_last_visit.tpl b/modules/help_mod_since_last_visit.tpl index 9e6db5d..9e6db5d 100644..100755 --- a/modules/help_mod_since_last_visit.tpl +++ b/modules/help_mod_since_last_visit.tpl diff --git a/modules/help_mod_user_pages.tpl b/modules/help_mod_user_pages.tpl index 6a8c5f5..6a8c5f5 100644..100755 --- a/modules/help_mod_user_pages.tpl +++ b/modules/help_mod_user_pages.tpl diff --git a/modules/help_mod_user_profile.tpl b/modules/help_mod_user_profile.tpl index 10ff215..10ff215 100644..100755 --- a/modules/help_mod_user_profile.tpl +++ b/modules/help_mod_user_profile.tpl diff --git a/modules/mod_online_users.php b/modules/mod_online_users.php index 076a036..34dc062 100755 --- a/modules/mod_online_users.php +++ b/modules/mod_online_users.php @@ -13,7 +13,7 @@ * @subpackage modules */ global $gBitUser, $module_params; -$listHash['online' ] = true; +$listHash['online' ] = true; $listHash['last_get'] = !empty( $module_params['time_buffer'] ) ? $module_params['time_buffer'] : 900; $online_users = $gBitUser->getUserActivity( $listHash ); $gBitSmarty->assign( 'online_users', $online_users); diff --git a/modules/mod_online_users.tpl b/modules/mod_online_users.tpl index 7e40f5d..7e40f5d 100644..100755 --- a/modules/mod_online_users.tpl +++ b/modules/mod_online_users.tpl diff --git a/modules/mod_since_last_visit.tpl b/modules/mod_since_last_visit.tpl index 46b07c9..46b07c9 100644..100755 --- a/modules/mod_since_last_visit.tpl +++ b/modules/mod_since_last_visit.tpl diff --git a/modules/mod_user_pages.php b/modules/mod_user_pages.php index 4bb6c4d..90afe28 100755 --- a/modules/mod_user_pages.php +++ b/modules/mod_user_pages.php @@ -12,7 +12,6 @@ use Bitweaver\KernelTools; global $gQueryUser, $gBitUser, $module_rows, $module_params, $gLibertySystem, $module_title; - $userId = $gBitUser->mUserId; if( !empty( $gQueryUser->mUserId ) ) { $userId = $gQueryUser->mUserId; @@ -33,13 +32,13 @@ if( !empty( $module_params['show_date'] ) ) { $gBitSmarty->assign( 'userShowDate', true ); } -$listHash = array( +$listHash = [ 'content_type_guid' => !empty( $module_params['content_type_guid'] ) ? $module_params['content_type_guid'] : null, 'offset' => 0, 'max_records' => $module_rows, 'sort_mode' => 'last_modified_desc', 'user_id' => $userId, -); +]; $modLastPages = $gBitUser->getContentList( $listHash ); $gBitSmarty->assign( 'modLastPages', $modLastPages ); ?> diff --git a/modules/mod_user_pages.tpl b/modules/mod_user_pages.tpl index 158549c..158549c 100644..100755 --- a/modules/mod_user_pages.tpl +++ b/modules/mod_user_pages.tpl diff --git a/modules/user_module.tpl b/modules/user_module.tpl index c9d4ce0..c9d4ce0 100644..100755 --- a/modules/user_module.tpl +++ b/modules/user_module.tpl @@ -55,6 +55,6 @@ if( $gBitSystem->isFeatureActive( 'display_users_content_list' ) ) { // end of content listing } -$gBitSystem->display( 'bitpackage:users/my_bitweaver.tpl', 'My '.$gBitSystem->getConfig( 'site_title' ) , array( 'display_mode' => 'display' )); +$gBitSystem->display( 'bitpackage:users/my_bitweaver.tpl', 'My '.$gBitSystem->getConfig( 'site_title' ) , [ 'display_mode' => 'display' ]); ?> diff --git a/my_groups.php b/my_groups.php index 341fc1b..58ac0be 100755 --- a/my_groups.php +++ b/my_groups.php @@ -27,18 +27,18 @@ if( !empty( $_REQUEST["cancel"] ) ) { if ( $gBitUser->hasPermission('p_users_create_personal_groups' ) ) { if( !empty( $_REQUEST['group_id'] ) ) { - $allPerms = $gBitUser->getGroupPermissions( array( 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : null )); + $allPerms = $gBitUser->getGroupPermissions( [ 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : null ]); // get grouplist separately from the $users stuff to avoid splitting of data due to pagination - $listHash = array( 'sort_mode' => 'group_name_asc' ); + $listHash = [ 'sort_mode' => 'group_name_asc' ]; $groupList = $gBitUser->getAllGroups( $listHash ); } else { // get grouplist separately from the $users stuff to avoid splitting of data due to pagination - $listHash = array( 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : 'group_name_asc' ); + $listHash = [ 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : 'group_name_asc' ]; $groupList = $gBitUser->getAllGroups( $listHash ); } // Remember a package limit if it is set. - $gBitSmarty->assign( 'package',isset( $_REQUEST['package'] ) ? $_REQUEST['package'] : 'all' ); + $gBitSmarty->assign( 'package',$_REQUEST['package'] ?? 'all' ); // Save the join if( isset($_REQUEST["save"] ) ) { @@ -52,7 +52,7 @@ if ( $gBitUser->hasPermission('p_users_create_personal_groups' ) ) { } // Update Permissions } elseif (isset($_REQUEST['updateperms'])) { - $listHash = array( 'group_id' => $_REQUEST['group_id'] ); + $listHash = [ 'group_id' => $_REQUEST['group_id'] ]; $updatePerms = $gBitUser->getgroupPermissions( $listHash ); foreach (array_keys($_REQUEST['perm']) as $per) { if( isset($_REQUEST['perm'][$per]) && !isset($updatePerms[$per]) ) { @@ -93,7 +93,7 @@ if ( $gBitUser->hasPermission('p_users_create_personal_groups' ) ) { } // Search for users to add } elseif (!empty($_REQUEST['submitUserSearch'])) { - $searchParams = array('find' => $_REQUEST['find']); + $searchParams = ['find' => $_REQUEST['find']]; $gBitUser->getList($searchParams); $foundUsers = $searchParams['data']; $mid = 'bitpackage:users/my_group_edit.tpl'; @@ -112,7 +112,7 @@ if ( $gBitUser->hasPermission('p_users_create_personal_groups' ) ) { // get pagination url // get grouplist separately from the $users stuff to avoid splitting of data due to pagination - $listHash = array( 'sort_mode' => 'group_name_asc' ); + $listHash = [ 'sort_mode' => 'group_name_asc' ]; $groupList = $gBitUser->getAllUserGroups(); if( !empty( $_REQUEST['group_id'] ) ) { @@ -125,7 +125,7 @@ if ( $gBitUser->hasPermission('p_users_create_personal_groups' ) ) { $gBitSmarty->assign('groupUsers', $groupUsers); $gBitSmarty->assign('groupInfo', $groupInfo); $gBitSmarty->assign( 'allPerms', $allPerms ); - $gBitSystem->setBrowserTitle( 'Admininster Group: '.$groupInfo['group_name'].' '.(isset( $_REQUEST['tab'] ) ? $_REQUEST['tab'] : '') ); + $gBitSystem->setBrowserTitle( 'Admininster Group: '.$groupInfo['group_name'].' '.($_REQUEST['tab'] ?? '') ); $mid = 'bitpackage:users/my_group_edit.tpl'; } @@ -164,10 +164,10 @@ if ( ( !empty( $_REQUEST['add_public_group'] ) || !empty( $_REQUEST['remove_publ /* Load up public groups and check if the user can join or leave them */ $systemGroups = $gBitUser->getGroups( $gBitUser->mUserId, true ); $gBitSmarty->assign( 'systemGroups', $systemGroups); -$listHash = array( +$listHash = [ 'is_public'=>'y', - 'sort_mode' => array( 'is_default_asc', 'group_desc_asc' ), -); + 'sort_mode' => [ 'is_default_asc', 'group_desc_asc' ], +]; $publicGroups = $gBitUser->getAllGroups( $listHash ); if( count( $publicGroups )) { foreach ( $systemGroups as $groupId=>$groupInfo ) { @@ -208,5 +208,5 @@ if (empty($mid)) { } // Display the template for group administration -$gBitSystem->display( $mid , null, array( 'display_mode' => 'display' )); +$gBitSystem->display( $mid , null, [ 'display_mode' => 'display' ]); ?> diff --git a/my_images.php b/my_images.php index 358fde1..36eebb1 100755 --- a/my_images.php +++ b/my_images.php @@ -48,4 +48,4 @@ if( !empty( $_REQUEST['store'] )) { // dunno why, but this fixes the bug. XOXO spiderr $gBitSmarty->assign( 'gQueryUser', $gQueryUser ); -$gBitSystem->display( 'bitpackage:users/my_images.tpl', KernelTools::tra( 'Personal Images' ), array( 'display_mode' => 'display' )); +$gBitSystem->display( 'bitpackage:users/my_images.tpl', KernelTools::tra( 'Personal Images' ), [ 'display_mode' => 'display' ]); diff --git a/my_roles.php b/my_roles.php index 8b37ade..0e9c9e1 100755 --- a/my_roles.php +++ b/my_roles.php @@ -38,9 +38,9 @@ if ( $gBitUser->hasPermission('p_users_create_personal_roles' ) ) { $listHash = [ 'sort_mode' => !empty( $_REQUEST['sort_mode'] ) ? $_REQUEST['sort_mode'] : 'role_name_asc' ]; $roleList = $gBitUser->getAllRoles( $listHash ); } - + // Remember a package limit if it is set. - $gBitSmarty->assign( 'package',isset( $_REQUEST['package'] ) ? $_REQUEST['package'] : 'all' ); + $gBitSmarty->assign( 'package',$_REQUEST['package'] ?? 'all' ); // Save the join if( isset($_REQUEST["save"] ) ) { @@ -116,7 +116,7 @@ if ( $gBitUser->hasPermission('p_users_create_personal_roles' ) ) { // get rolelist separately from the $users stuff to avoid splitting of data due to pagination $listHash = [ 'sort_mode' => 'role_name_asc' ]; $roleList = $gBitUser->getAllUserRoles(); - + if( !empty( $_REQUEST['role_id'] ) ) { // we don't want our own role listed when editing if( !empty( $roleList[$_REQUEST['role_id']] ) ) { @@ -127,9 +127,9 @@ if ( $gBitUser->hasPermission('p_users_create_personal_roles' ) ) { $gBitSmarty->assign('roleUsers', $roleUsers); $gBitSmarty->assign('roleInfo', $roleInfo); $gBitSmarty->assign( 'allPerms', $allPerms ); - $gBitSystem->setBrowserTitle( 'Admininster Role: '.$roleInfo['role_name'].' '.(isset( $_REQUEST['tab'] ) ? $_REQUEST['tab'] : '') ); + $gBitSystem->setBrowserTitle( 'Admininster Role: '.$roleInfo['role_name'].' '.($_REQUEST['tab'] ?? '') ); $mid = 'bitpackage:users/my_role_edit.tpl'; - } + } $gBitSmarty->assign('roles', $roleList); // $gBitSmarty->assign( (!empty( $_REQUEST['tab'] ) ? $_REQUEST['tab'] : 'edit').'TabSelect', 'tdefault' ); @@ -139,7 +139,7 @@ if ( $gBitUser->hasPermission('p_users_create_personal_roles' ) ) { if ( ( !empty( $_REQUEST['add_public_role'] ) || !empty( $_REQUEST['remove_public_role'] ) ) && !empty( $_REQUEST['public_role_id'] ) ) { $roleInfo = $gBitUser->getRoleInfo( $_REQUEST['public_role_id'] ); if ( empty($roleInfo) || $roleInfo['is_public'] != 'y' ) { - $errorMsg[] = ( empty( $_REQUEST['add_public_role'] ) ) ? KernelTools::tra( "You can't join this role." ) : KernelTools::tra( "You can't leave this role." ); + $errorMsg[] = ( empty( $_REQUEST['add_public_role'] ) ) ? KernelTools::tra( "You can't join this role." ) : KernelTools::tra( "You can't leave this role." ); } elseif ( !empty( $_REQUEST['add_public_role'] ) ) { $gBitUser->addUserToRole( $gBitUser->mUserId, $_REQUEST['public_role_id'] ); } elseif ( !empty( $_REQUEST['remove_public_role'] ) ) { @@ -166,7 +166,7 @@ $listHash = [ 'is_public' => 'y', 'sort_mode' => [ 'is_default_asc', 'role_desc_asc' ], ]; -$publicRoles = $gBitUser->getAllRoles( $listHash ); +$publicRoles = $gBitUser->getAllRoles( $listHash ); if( count( $publicRoles )) { foreach ( $systemRoles as $roleId=>$roleInfo ) { foreach ( $publicRoles as $key=>$publicRole) { @@ -192,7 +192,7 @@ if( count( $publicRoles )) { } } -// Remember error and success messages. +// Remember error and success messages. if (!empty($errorMsg)) { $gBitSmarty->assign('errorMsg',$errorMsg); } diff --git a/preferences.php b/preferences.php index 85cd2b5..d4f122c 100755 --- a/preferences.php +++ b/preferences.php @@ -1,7 +1,7 @@ <?php namespace Bitweaver\Users; + use Bitweaver\KernelTools; -use function Bitweaver\Users\scramble_email; /** * user preferences @@ -211,7 +211,6 @@ if( isset( $_REQUEST["chgpswd"] )) { } } - // this should go in tidbits if( isset( $_REQUEST['tasksprefs'] )) { $editUser->storePreference( 'tasks_max_records', $_REQUEST['tasks_max_records'] ); diff --git a/register.php b/register.php index c949b07..eb20ca4 100755 --- a/register.php +++ b/register.php @@ -14,7 +14,6 @@ use Bitweaver\KernelTools; * required setup */ // Avoid user hell -use Bitweaver\BitBase; use Bitweaver\HttpStatusCodes; use Bitweaver\Users\BitHybridAuthManager; @@ -34,7 +33,6 @@ $gBitSmarty->assign( 'hybridProviders', $gBitHybridAuthManager->getEnabledProvid // Everything below here is needed for registration use Bitweaver\Users\BaseAuth; -use Bitweaver\Users\RolePermUser; if( !empty( $_REQUEST['returnto'] ) ) { $_SESSION['returnto'] = $_REQUEST['returnto']; @@ -94,10 +92,10 @@ closedir( $h ); sort( $flags ); $gBitSmarty->assign('flags', $flags); -$listHash = array( +$listHash = [ 'is_public' => 'y', - 'sort_mode' => array( 'is_default_asc', 'group_desc_asc' ), -); + 'sort_mode' => [ 'is_default_asc', 'group_desc_asc' ], +]; $groupList = $gBitUser->getAllGroups( $listHash ); $gBitSmarty->assign( 'groupList', $groupList ); @@ -125,4 +123,4 @@ if( !empty( $_REQUEST['error'] ) ) { } $gBitSmarty->assign( 'metaKeywords', 'Login, Sign in, Registration, Register, Create new account' ); -$gBitSystem->display('bitpackage:users/register.tpl', 'Register' , array( 'display_mode' => 'display' ));
\ No newline at end of file +$gBitSystem->display('bitpackage:users/register.tpl', 'Register' , [ 'display_mode' => 'display' ]);
\ No newline at end of file diff --git a/remind_password.php b/remind_password.php index 92141af..9ea045d 100755 --- a/remind_password.php +++ b/remind_password.php @@ -26,7 +26,7 @@ if( $gBitUser->isRegistered() ) { $userInfo = ''; $_REQUEST["username"] = strip_tags( urldecode( $_REQUEST["username"]) ); $pLogin = trim( $_REQUEST["username"] ); - if ( strlen ( $pLogin ) ) { + if ( strlen ( $pLogin ) ) { $loginCol = strpos( $pLogin, '@' ) ? 'email' : 'login'; $userInfo = $gBitUser->getUserInfo( [ $loginCol => $pLogin ] ); } diff --git a/role_register.php b/role_register.php index 9f1a7d2..23af889 100755 --- a/role_register.php +++ b/role_register.php @@ -12,6 +12,7 @@ * required setup */ namespace Bitweaver\Liberty; + use Bitweaver\HttpStatusCodes; use Bitweaver\Users\BaseAuth; use Bitweaver\Wiki\BitPage; @@ -70,7 +71,7 @@ if( isset( $_REQUEST["register"] ) ) { $newUser->storePreference('users_information','private'); } - // requires validation by email + // requires validation by email if( $gBitSystem->isFeatureActive( 'users_validate_user' ) ) { $gBitSmarty->assign('msg',tra('You will receive an email with information to login for the first time into this site')); $gBitSmarty->assign('showmsg','y'); @@ -9,6 +9,7 @@ */ namespace Bitweaver\Liberty; + use Bitweaver\KernelTools; use Bitweaver\HttpStatusCodes; use Bitweaver\Users\BitHybridAuthManager; @@ -46,4 +47,4 @@ $gBitSmarty->assign( 'languages', $languages ); $gBitSmarty->assign( 'gBitLanguage', $gBitLanguage ); $gBitSmarty->assign( 'metaKeywords', 'Login, Sign in, Registration, Register, Create new account' ); -$gBitSystem->display( 'bitpackage:users/signin.tpl', $gBitSystem->getConfig( 'site_title' ).' Login' , array( 'display_mode' => 'display' )); +$gBitSystem->display( 'bitpackage:users/signin.tpl', $gBitSystem->getConfig( 'site_title' ).' Login' , [ 'display_mode' => 'display' ]); diff --git a/smartyplugins/function.captcha.php b/smartyplugins/function.captcha.php index c52cb46..b11d7d6 100644 --- a/smartyplugins/function.captcha.php +++ b/smartyplugins/function.captcha.php @@ -13,7 +13,7 @@ function smarty_function_captcha( $pParams, &$gBitSmarty ) { if( $gBitSystem->isFeatureActive('users_register_recaptcha') ) { require_once USERS_PKG_INCLUDE_PATH.'recaptcha/autoload.php'; - if( $recapKey = $gBitSystem->getConfig( 'users_register_recaptcha_secret_key' ) ) { + if( $recapKey = $gBitSystem->getConfig( 'users_register_recaptcha_secret_key' ) ) { $recaptcha = new \ReCaptcha\ReCaptcha( $recapKey ); } } diff --git a/templates/admin_group_edit.tpl b/templates/admin_group_edit.tpl index 45f8593..45f8593 100644..100755 --- a/templates/admin_group_edit.tpl +++ b/templates/admin_group_edit.tpl diff --git a/templates/admin_groups_list.tpl b/templates/admin_groups_list.tpl index bf1e3f3..bf1e3f3 100644..100755 --- a/templates/admin_groups_list.tpl +++ b/templates/admin_groups_list.tpl diff --git a/templates/admin_roles_list.tpl b/templates/admin_roles_list.tpl index 7e885a8..7e885a8 100644..100755 --- a/templates/admin_roles_list.tpl +++ b/templates/admin_roles_list.tpl diff --git a/templates/admin_validation_mail.tpl b/templates/admin_validation_mail.tpl index 38f297c..38f297c 100644..100755 --- a/templates/admin_validation_mail.tpl +++ b/templates/admin_validation_mail.tpl diff --git a/templates/admin_welcome_mail.tpl b/templates/admin_welcome_mail.tpl index 47a10e4..47a10e4 100644..100755 --- a/templates/admin_welcome_mail.tpl +++ b/templates/admin_welcome_mail.tpl diff --git a/templates/captcha.tpl b/templates/captcha.tpl index d67131d..d67131d 100644..100755 --- a/templates/captcha.tpl +++ b/templates/captcha.tpl diff --git a/templates/change_password.tpl b/templates/change_password.tpl index ba5d6a0..ba5d6a0 100644..100755 --- a/templates/change_password.tpl +++ b/templates/change_password.tpl diff --git a/templates/edit_user_fav_json.tpl b/templates/edit_user_fav_json.tpl index e6621ae..e6621ae 100644..100755 --- a/templates/edit_user_fav_json.tpl +++ b/templates/edit_user_fav_json.tpl diff --git a/templates/index.php b/templates/index.php index 3e305fe..c0437d0 100644 --- a/templates/index.php +++ b/templates/index.php @@ -1,4 +1,4 @@ -<?php +<?php // This is not a package. header ("location: ../index.php"); diff --git a/templates/index_list.tpl b/templates/index_list.tpl index d733d35..d733d35 100644..100755 --- a/templates/index_list.tpl +++ b/templates/index_list.tpl diff --git a/templates/menu_users_admin.tpl b/templates/menu_users_admin.tpl index f6e7a75..f6e7a75 100644..100755 --- a/templates/menu_users_admin.tpl +++ b/templates/menu_users_admin.tpl diff --git a/templates/my_bitweaver_bar.tpl b/templates/my_bitweaver_bar.tpl index 07c23e1..07c23e1 100644..100755 --- a/templates/my_bitweaver_bar.tpl +++ b/templates/my_bitweaver_bar.tpl diff --git a/templates/my_images.tpl b/templates/my_images.tpl index 1aca2ec..1aca2ec 100644..100755 --- a/templates/my_images.tpl +++ b/templates/my_images.tpl diff --git a/templates/new_user_notification.tpl b/templates/new_user_notification.tpl index 1c3bfed..1c3bfed 100644..100755 --- a/templates/new_user_notification.tpl +++ b/templates/new_user_notification.tpl diff --git a/templates/password_reminder.tpl b/templates/password_reminder.tpl index f33e4f4..f33e4f4 100644..100755 --- a/templates/password_reminder.tpl +++ b/templates/password_reminder.tpl diff --git a/templates/signin.tpl b/templates/signin.tpl index 5fc0da9..5fc0da9 100644..100755 --- a/templates/signin.tpl +++ b/templates/signin.tpl diff --git a/templates/user_activity.tpl b/templates/user_activity.tpl index 7df7864..7df7864 100644..100755 --- a/templates/user_activity.tpl +++ b/templates/user_activity.tpl diff --git a/templates/user_validation_mail.tpl b/templates/user_validation_mail.tpl index 3b0a277..3b0a277 100644..100755 --- a/templates/user_validation_mail.tpl +++ b/templates/user_validation_mail.tpl diff --git a/templates/user_watches.tpl b/templates/user_watches.tpl index 166eb89..166eb89 100644..100755 --- a/templates/user_watches.tpl +++ b/templates/user_watches.tpl diff --git a/templates/validate_auth.tpl b/templates/validate_auth.tpl index 691b728..691b728 100644..100755 --- a/templates/validate_auth.tpl +++ b/templates/validate_auth.tpl diff --git a/templates/welcome_mail.tpl b/templates/welcome_mail.tpl index 50f4190..50f4190 100644..100755 --- a/templates/welcome_mail.tpl +++ b/templates/welcome_mail.tpl diff --git a/users_rss.php b/users_rss.php index e56cc6f..fdd9a53 100755 --- a/users_rss.php +++ b/users_rss.php @@ -5,8 +5,6 @@ * @subpackage functions */ - - /** * Initialization */ @@ -31,10 +29,10 @@ if( !$gBitUser->hasPermission( 'p_users_view_user_list' ) ) { $cacheFile = TEMP_PKG_PATH.RSS_PKG_NAME.'/'.USERS_PKG_NAME.'/'.$cacheFileTail; $rss->useCached( $rss_version_name, $cacheFile, $gBitSystem->getConfig( 'rssfeed_cache_time' )); - $listHash = array( + $listHash = [ 'max_records' => $gBitSystem->getConfig( 'users_rss_max_records' ), 'sort_mode' => 'registration_date_desc', - ); + ]; $gBitUser->getList( $listHash ); $feeds = $listHash['data']; diff --git a/validate.php b/validate.php index cbe7dbd..dd91b29 100755 --- a/validate.php +++ b/validate.php @@ -8,12 +8,9 @@ * @subpackage functions */ - namespace Bitweaver; -use Bitweaver\KernelTools; + use Bitweaver\Users\BitHybridAuthManager; -use Bitweaver\Users\RolePermUser; -use Bitweaver\Users\UserRepository; /** * this is a dirty hack to allow admins to log in when we require a visit to the installer @@ -99,7 +96,7 @@ if( !empty( $_REQUEST['provider'] ) ) { $pRegisterHash['customers_dob'] = ($auth->birthYear ? $auth->birthYear : 1900).'-'.$auth->birthMonth.'-'.$auth->birthDay; } $prefId = $gBitHybridAuthManager->getConfigName( $_REQUEST['provider'], 'id' ); - $_SESSION['returnto'] = $_SERVER['SCRIPT_URI'].'?provider='.$_REQUEST['provider'].'&auth_login=1'; + $_SESSION['returnto'] = $_SERVER['SCRIPT_URI'].'?provider='.$_REQUEST['provider'].'&auth_login=1'; include USERS_PKG_INCLUDE_PATH.'register_inc.php'; } } @@ -129,7 +126,7 @@ if( !empty( $_REQUEST['provider'] ) ) { default: $authError = $e->getMessage(); break; } - + $gBitSmarty->assign( 'authError', $authError ); $gBitSmarty->assign( 'authExpection', $e ); bit_error_log( $authError ); @@ -152,7 +149,6 @@ if( !empty( $tpl ) ) { } elseif(( strpos( $redirectUrl, 'signin.php?' ) || strpos( $redirectUrl, 'remind_password.php' )) && strpos( $redirectUrl, 'signin.php?error=' ) == -1 ) { // but if we came from a login page, let's go home (except if we got an error when login in) $redirectUrl = $gBitUser->getPostLoginUrl(); -} else { } if( !empty( $redirectUrl ) ) { diff --git a/watches.php b/watches.php index 1a622ae..8b28432 100755 --- a/watches.php +++ b/watches.php @@ -17,18 +17,18 @@ use Bitweaver\KernelTools; $user = $gBitUser->mUserId; if (!$user) { $gBitSmarty->assign('msg', KernelTools::tra( "You must log in to use this feature" )); - $gBitSystem->display( 'error.tpl' , null, array( 'display_mode' => 'display' )); + $gBitSystem->display( 'error.tpl' , null, [ 'display_mode' => 'display' ]); die; } $gBitSystem->verifyFeature( 'users_watches' ); if (isset($_REQUEST['hash'])) { - + $gBitUser->remove_user_watch_by_hash($_REQUEST['hash']); } if (isset($_REQUEST['watch'])) { - + foreach (array_keys($_REQUEST["watch"])as $item) { $gBitUser->remove_user_watch_by_hash($item); } @@ -43,5 +43,5 @@ if (!isset($_REQUEST['event'])) $watches = $gBitUser->getWatches( $_REQUEST['event'] ); $gBitSmarty->assign('watches', $watches); -$gBitSystem->display( 'bitpackage:users/user_watches.tpl', null, array( 'display_mode' => 'display' )); +$gBitSystem->display( 'bitpackage:users/user_watches.tpl', null, [ 'display_mode' => 'display' ]); ?> |
