Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Updated to use new Facebook API, changes to how User saved in Session.

Many small optimizations and updates.
  • Loading branch information...
commit 9a764392e0469fe0b500d461d49f222ec73d4c01 1 parent 97fc4bb
@snytkine snytkine authored
Showing with 2,588 additions and 3,048 deletions.
  1. +32 −16 !inc.php
  2. +1 −1  lib/Lampcms/Acl/Acl.php
  3. +2 −1  lib/Lampcms/AnswerParser.php
  4. +5 −6 lib/Lampcms/Base.php
  5. +4 −3 lib/Lampcms/Bitly.php
  6. +4 −6 lib/Lampcms/CacheHeaders.php
  7. +3 −0  lib/Lampcms/Captcha.php
  8. +3 −1 lib/Lampcms/Controllers/Accept.php
  9. +2 −1  lib/Lampcms/Controllers/Connectblogger.php
  10. +4 −4 lib/Lampcms/Controllers/Connectfb.php
  11. +1 −1  lib/Lampcms/Controllers/Editapp.php
  12. +0 −2  lib/Lampcms/Controllers/Locale.php
  13. +0 −2  lib/Lampcms/Controllers/Loginlinkedin.php
  14. +20 −5 lib/Lampcms/Controllers/Logintwitter.php
  15. +7 −7 lib/Lampcms/Controllers/Logout.php
  16. +4 −4 lib/Lampcms/CookieAuth.php
  17. +4 −29 lib/Lampcms/DB.php
  18. +1 −1  lib/Lampcms/Event/Dispatcher.php
  19. +1 −1  lib/Lampcms/Event/Notification.php
  20. +5 −5 lib/Lampcms/Exception.php
  21. +1 −1  lib/Lampcms/ExternalAuth.php
  22. +0 −893 lib/Lampcms/ExternalAuthFb.php
  23. +0 −317 lib/Lampcms/Facebook.php
  24. +7 −1 lib/Lampcms/FollowManager.php
  25. +0 −1  lib/Lampcms/I18n/XliffCatalog.php
  26. +20 −10 lib/Lampcms/Locale/Locale.php
  27. +0 −2  lib/Lampcms/LoginForm.php
  28. +712 −0 lib/Lampcms/Modules/Facebook/Client.php
  29. +1,143 −0 lib/Lampcms/Modules/Facebook/SDK/base_facebook.php
  30. +93 −0 lib/Lampcms/Modules/Facebook/SDK/facebook.php
  31. +8 −8 lib/Lampcms/Modules/Linkedin/ApiClient.php
  32. +8 −42 lib/Lampcms/Modules/Observers/PostFacebook.php
  33. +0 −2  lib/Lampcms/Modules/Observers/Similars.php
  34. +1 −2  lib/Lampcms/Modules/Search/Factory.php
  35. +8 −8 lib/Lampcms/Modules/Search/IndexerMySQL.php
  36. +6 −7 lib/Lampcms/Modules/Search/MySQL.php
  37. +16 −11 lib/Lampcms/Modules/Tumblr/ApiClient.php
  38. +6 −7 lib/Lampcms/Modules/Tumblr/TumblrPostAdapter.php
  39. +5 −5 lib/Lampcms/Mongo/DB.php
  40. +24 −17 lib/Lampcms/Mongo/Doc.php
  41. +1 −1  lib/Lampcms/Object.php
  42. +48 −13 lib/Lampcms/ProfileDiv.php
  43. +1 −0  lib/Lampcms/QuestionParser.php
  44. +2 −0  lib/Lampcms/RegBlock.php
  45. +5 −2 lib/Lampcms/RegBlockTwitter.php
  46. +43 −2 lib/Lampcms/Registry.php
  47. +1 −1  lib/Lampcms/Request.php
  48. +19 −15 lib/Lampcms/Responder.php
  49. +1 −1  lib/Lampcms/ShowFollowers.php
  50. +1 −1  lib/Lampcms/SocialCheckboxes.php
  51. +1 −1  lib/Lampcms/SplClassLoader.php
  52. +1 −1  lib/Lampcms/Template/Fast.php
  53. +22 −11 lib/Lampcms/User.php
  54. +3 −3 lib/Lampcms/UserAuth.php
  55. +24 −12 lib/Lampcms/UserTags.php
  56. +5 −1 lib/Lampcms/Usertools.php
  57. +26 −92 lib/Lampcms/WebPage.php
  58. +17 −1 www/api/api.php
  59. +72 −34 www/index.php
  60. +0 −21 www/js/min/qa_03312011.js
  61. +0 −21 www/js/min/qa_04022011.js
  62. +0 −22 www/js/min/qa_04072011.js
  63. +0 −22 www/js/min/qa_04102011_2.js
  64. +0 −23 www/js/min/qa_04132011.js
  65. +0 −23 www/js/min/qa_04142011.js
  66. +0 −22 www/js/min/qa_04182011.js
  67. +0 −23 www/js/min/qa_04202011.js
  68. +0 −23 www/js/min/qa_042311.js
  69. +0 −23 www/js/min/qa_05042011.js
  70. +0 −23 www/js/min/qa_05082011.js
  71. +0 −261 www/js/min/qa_051020112.js
  72. +0 −256 www/js/min/qa_05112011.js
  73. +0 −268 www/js/min/qa_05122011.js
  74. +0 −257 www/js/min/qa_051220112.js
  75. +62 −57 www/js/min/{qa_05312011.js → qa_122411.js}
  76. +14 −60 www/js/qa.js
  77. +1 −1  www/style/1/www/tplAnswer.php
  78. +15 −3 www/style/1/www/tplFbJs.php
  79. +2 −1  www/style/1/www/tplU3.php
  80. +40 −16 www/twitter.php
View
48 !inc.php
@@ -73,16 +73,19 @@
}
function exception_handler($e){
-
- try {
- $err = Lampcms\Responder::makeErrorPage('<strong>Error:</strong> '.Lampcms\Exception::formatException($e));
- $extra = (isset($_SERVER)) ? ' $_SERVER: '.print_r($_SERVER, 1) : ' no extra';
- if(defined('LAMPCMS_DEVELOPER_EMAIL') && strlen(trim(constant('LAMPCMS_DEVELOPER_EMAIL'))) > 1){
- @mail(LAMPCMS_DEVELOPER_EMAIL, 'ErrorHandle in inc.php', $err.$extra);
+ if(!($e instanceof \OutOfBoundsException)){
+ try {
+ $err = Lampcms\Responder::makeErrorPage('<strong>Error:</strong> '.Lampcms\Exception::formatException($e));
+ $extra = (isset($_SERVER)) ? ' $_SERVER: '.print_r($_SERVER, 1) : ' no extra';
+ if(defined('LAMPCMS_DEVELOPER_EMAIL') && strlen(trim(constant('LAMPCMS_DEVELOPER_EMAIL'))) > 1){
+ @mail(LAMPCMS_DEVELOPER_EMAIL, 'ErrorHandle in inc.php', $err.$extra);
+ }
+ echo ($err);
+ } catch(\Exception $e) {
+ echo 'Error in Exception handler: : '.$e->getMessage().' line '.$e->getLine().$e->getTraceAsString();
}
- exit ($err);
- }catch(\Exception $e) {
- echo 'Error in Exception handler: : '.$e->getMessage().' line '.$e->getLine().$e->getTraceAsString();
+ } else {
+ d('Got exit signal in error_handler from '.$e->getTraceAtString());
}
}
@@ -118,11 +121,6 @@ function fastcgi_finish_request(){}
require $lampcmsClasses.'Registry.php';
require $lampcmsClasses.'Template'.DIRECTORY_SEPARATOR.'Fast.php';
-if(defined('IS_WWW')){
- if (true !== session_start()) {
- exit('session start error');
- }
-}
/**
* Points.php is in non-standard directory,
* in fact this file is not even included in distro
@@ -228,7 +226,7 @@ function LampcmsErrorHandler($errno, $errstr, $errfile, $errline)
}
} catch(Lampcms\IniException $e){
- exit($e->getMessage());
+ throw new \OutOfBoundsException($e->getMessage());
}
@@ -256,6 +254,24 @@ function LampcmsErrorHandler($errno, $errstr, $errfile, $errline)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('warn_plus_overloading', 1);
+ /**
+ * Turn on session garbage collection
+ * to be run at every session start
+ * to give us consistant behaviour
+ * in debug mode
+ * Session expiration is 5 minutes
+ * which means when logged in without
+ * using "remember me" option,
+ * you supposed to be logged out after 5 minutes
+ * of inactivity. The only way to test it
+ * is to login, then after 6-7 minutes access site
+ * with a different browser. Then go to the browser with logged
+ * in user and try to use any other link. User should not
+ * be logged in anymore at this time.
+ */
+ ini_set("session.gc_maxlifetime", "300");
+ ini_set('session.gc_probability', "1");
+ ini_set('session.gc_divisor', "1");
} else {
define('LAMPCMS_DEBUG', false);
error_reporting(E_ALL ^ E_WARNING);
@@ -286,7 +302,7 @@ function LampcmsErrorHandler($errno, $errstr, $errfile, $errline)
* has been defined
*/
function d($message){
- if(true === LAMPCMS_DEBUG){
+ if(defined('LAMPCMS_DEBUG') && true === LAMPCMS_DEBUG){
\Lampcms\Log::d($message, 2);
}
}
View
2  lib/Lampcms/Acl/Acl.php
@@ -157,7 +157,7 @@ public function __construct(){
$aGroupPermissions[$roleName]['deny'] = $deny;
}
- d('$aGroupPermissions: '.print_r($aGroupPermissions, 1));
+ //d('$aGroupPermissions: '.print_r($aGroupPermissions, 1));
} catch (\Exception $e){
throw new \Lampcms\DevException('Unable to add role to ACL. Original file: '.$e->getFile().' orig line: '.$e->getLine().' original message: '.$e->getMessage());
View
3  lib/Lampcms/AnswerParser.php
@@ -366,7 +366,8 @@ protected function updateQuestion(){
$this->Question->updateAnswerCount()
->addContributor($User)
->setLatestAnswer($User, $this->Answer)
- ->touch();
+ ->touch()
+ ->save();
return $this;
}
View
11 lib/Lampcms/Base.php
@@ -219,7 +219,7 @@ public function saveResourceLocation($resourceId = '', $ip = '', array $arrExtra
*/
public function checkAccessPermission($privilege = null, RoleInterface $role = null, $resource = null){
- d('$privilege: '.$privilege.' '.var_export($privilege, true));
+ //d('$privilege: '.$privilege.' '.var_export($privilege, true));
if(null === $privilege){
d('$privilege is null');
@@ -252,7 +252,7 @@ public function checkAccessPermission($privilege = null, RoleInterface $role = n
* reload operation does not require even a single sql select
*
*/
- d('role: '.$role. ' $this->Registry->Viewer: '.$this->Registry->Viewer);
+ //d('role: '.$role. ' $this->Registry->Viewer: '.$this->Registry->Viewer);
/**
* How not to reload the object?
@@ -279,9 +279,8 @@ public function checkAccessPermission($privilege = null, RoleInterface $role = n
*
*/
- $role = (null !== $role) ? $role : $this->Registry->Viewer->reload();
+ $role = (null !== $role) ? $role : $this->Registry->Viewer;
- d('role: '.$role);
/**
* oACL can be cached, which saves about 5-7 milliseconds
@@ -289,8 +288,8 @@ public function checkAccessPermission($privilege = null, RoleInterface $role = n
* edit acl.ini you must manually remove
* Acl key from cache. (from C_Cache collection)
*/
- //$oACL = $this->Registry->Cache->Acl;
- $oACL = $this->Registry->Acl;//new \Lampcms\Acl\Acl();
+
+ $oACL = $this->Registry->Acl;
$roleID = $role->getRoleId();
d('$roleID '.$roleID.' $privilege: '.$privilege);
View
7 lib/Lampcms/Bitly.php
@@ -115,18 +115,18 @@ public function getShortUrl($url){
$tplUrl = 'http://api.bitly.com/v3/shorten?login=%s&apiKey=%s&longUrl=%s&format=json';
if(!empty($this->config) && !empty($this->config['user']) && !empty($this->config['api_key'])){
$context = \stream_context_create($this->aStreamOptions);
- $res = \file_get_contents(sprintf($tplUrl, $this->config['user'], $this->config['api_key'], urlencode($url) ), false, $context);
+ $res = \file_get_contents(\sprintf($tplUrl, $this->config['user'], $this->config['api_key'], \urlencode($url) ), false, $context);
if(empty($res)){
d('did not get data back from bit.ly');
return false;
}
- if(false === $a = json_decode($res, true)){
+ if(false === $a = \json_decode($res, true)){
d('unable to json_decode data returned by bit.ly '.$res);
return false;
}
- d('bit.ly decoded json data: '.print_r($a, 1));
+ d('bit.ly decoded json data: '.\print_r($a, 1));
if(!empty($a)
&& !empty($a['status_code'])
@@ -139,6 +139,7 @@ public function getShortUrl($url){
}
d('no short url from bitly');
+
return false;
}
}
View
10 lib/Lampcms/CacheHeaders.php
@@ -291,16 +291,14 @@ public static function processCacheHeaders($etag = null, $lastModified = null, $
* we return 304 header but ONLY if request method is GET or HEAD,
* for all others return special code
*/
- if($noChangeByEtag || $noChangeByTimestamp)
- {
- if($noChangeByEtag && ('GET' !== $_SERVER['REQUEST_METHOD'] && 'HEAD' !== $_SERVER['REQUEST_METHOD']))
- {
+ if($noChangeByEtag || $noChangeByTimestamp){
+ if($noChangeByEtag && ('GET' !== $_SERVER['REQUEST_METHOD'] && 'HEAD' !== $_SERVER['REQUEST_METHOD'])){
header("HTTP/1.1 412 (Precondition Failed)");
- exit;
+ throw new \OutOfBoundsException;
}
header("HTTP/1.1 304 Not Modified");
- exit;
+ throw new \OutOfBoundsException;
}
return true;
View
3  lib/Lampcms/Captcha.php
@@ -70,6 +70,9 @@
* Class that generate a captcha-image with text and a form to fill in this text
* @author Horst Nogajski, (mail: horst@nogajski.de)
* @version 1.3
+ *
+ * @todo this class does not have to extend LampcmsObject
+ * and does not need Registry in constructor, only Ini
*
*/
class Captcha extends LampcmsObject
View
4 lib/Lampcms/Controllers/Accept.php
@@ -107,6 +107,8 @@ protected function main(){
->updateQuestion()
->updateUser()
->postEvent();
+
+ $this->Answer->save();
//} catch(\Exception $e){
// d('Accept not counted due to exception: '.$e->getMessage().' in '.$e->getFile().' line: '.$e->getLine());
//}
@@ -318,7 +320,7 @@ protected function updateQuestion(){
$this->rewardViewer();
}
- $this->Question->setBestAnswer($this->Answer);
+ $this->Question->setBestAnswer($this->Answer)->save();
return $this;
}
View
3  lib/Lampcms/Controllers/Connectblogger.php
@@ -341,7 +341,8 @@ protected function step2(){
d('User has more than one blog, generating "select blog" form');
$form = $this->makeBlogSelectionForm();
d('$form: '.$form);
- exit(Responder::makeErrorPage($form));
+ echo(Responder::makeErrorPage($form));
+ throw new \OutOfBoundsException;
} else {
d('User has one Blogger blog, using it now');
/**
View
8 lib/Lampcms/Controllers/Connectfb.php
@@ -52,10 +52,10 @@
namespace Lampcms\Controllers;
-use Lampcms\WebPage;
+use \Lampcms\WebPage;
use \Lampcms\Request;
use \Lampcms\Responder;
-use \Lampcms\ExternalAuthFb;
+//use \Lampcms\ExternalAuthFb;
/**
*
@@ -85,7 +85,7 @@ class Connectfb extends WebPage
protected function main(){
try{
d('cp');
- ExternalAuthFb::factory($this->Registry)->connect($this->Registry->Viewer);
+ $this->Registry->Facebook->connect($this->Registry->Viewer);
d('cp');
} catch (\Lampcms\FacebookAuthException $e ){
d('Caught FacebookAuthException');
@@ -99,7 +99,7 @@ protected function main(){
throw $e;
}
- e('Unable to connect Facebook account. '.$e->getMessage.' in file '.$e->getFile().' on line '.$e->getLine());
+ e('Unable to connect Facebook account. '.$e->getMessage().' in file '.$e->getFile().' on line '.$e->getLine());
throw new \Lampcms\Exception('Unable to connect Facebook account at this time');
}
View
2  lib/Lampcms/Controllers/Editapp.php
@@ -251,7 +251,7 @@ protected function save(){
$res = $this->oApi->insert();
}
} catch (\Exception $e){
- exit($e->getMessage());
+ throw new \OutOfBoundsException($e->getMessage());
}
d('$res: '.$res);
View
2  lib/Lampcms/Controllers/Locale.php
@@ -79,8 +79,6 @@ class Locale extends WebPage
protected function main(){
$locale = $this->Request->get('locale');
- /*echo __METHOD__.' '.__LINE__.'$locale: '.$locale;
- exit;*/
if(isset($_SESSION['guest_block'])){
unset($_SESSION['guest_block']);
View
2  lib/Lampcms/Controllers/Loginlinkedin.php
@@ -332,8 +332,6 @@ protected function createOrUpdate(){
throw new \Exception($e->getMessage());
}
- d('SESSION oViewer: '.print_r($_SESSION['oViewer']->getArrayCopy(), 1). 'isNew: '.$this->Registry->Viewer->isNewUser());
-
$this->Registry->Dispatcher->post( $this, 'onLinkedinLogin' );
return $this;
View
25 lib/Lampcms/Controllers/Logintwitter.php
@@ -403,8 +403,6 @@ protected function createOrUpdate(){
throw new \Exception($e->getMessage());
}
- d('SESSION oViewer: '.print_r($_SESSION['oViewer']->getArrayCopy(), 1). 'isNew: '.$this->Registry->Viewer->isNewUser());
-
$this->Registry->Dispatcher->post( $this, 'onTwitterLogin' );
if($this->isNewAccount){
@@ -507,13 +505,14 @@ protected function createNewUser(){
* and ask the user to provide email address but only
* during the same session
*/
- $this->User->setNewUser();
- d('isNewUser: '.$this->User->isNewUser());
+ //$this->User->setNewUser();
+ //d('isNewUser: '.$this->User->isNewUser());
$this->User->save();
\Lampcms\PostRegistration::createReferrerRecord($this->Registry, $this->User);
$this->Registry->Dispatcher->post($this->User, 'onNewUser');
+ $this->Registry->Dispatcher->post($this->User, 'onNewTwitterUser');
//exit(' new user: '.$this->User->isNewUser().' '.print_r($this->User->getArrayCopy(), 1));
@@ -540,6 +539,22 @@ protected function updateUser($bUpdateAvatar = true){
$avatarTwitter = $this->User['avatar_external'];
if(empty($avatarTwitter)){
$this->User['avatar_external'] = $this->aUserData['profile_image_url'];
+
+ $srcAvatar = \trim($this->User->offsetGet('avatar'));
+ /**
+ * If user also did not have any avatar
+ * then
+ * after this update we should also update
+ * the welcome block (removing it from SESSION will
+ * ensure that it updates on next page load) so that
+ * avatar on the welcome block will change to the
+ * external avatar
+ */
+ if(empty($srcAvatar)){
+ if(!empty($_SESSION) && !empty($_SESSION['welcome'])){
+ unset($_SESSION['welcome']);
+ }
+ }
}
$this->User->save();
@@ -732,7 +747,7 @@ protected function redirectToTwitter($url){
*/
protected function makeUsername(){
- $res = $this->Registry->Mongo->USERS->findOne(array('twitter_uid' => $this->aUserData['_id']));
+ $res = $this->Registry->Mongo->USERS->findOne(array('username_lc' => \mb_strtolower($this->aUserData['screen_name']) ));
$ret = (empty($res)) ? $this->aUserData['screen_name'] : '@'.$this->aUserData['screen_name'];
d('ret: '.$ret);
View
14 lib/Lampcms/Controllers/Logout.php
@@ -134,13 +134,13 @@ public function main(){
}
}
- d('logging out Facebook User');
- $aFB = $this->Registry->Ini->getSection('FACEBOOK');
- if(!empty($aFB) && !empty($aFB['APP_ID'])){
- $fb_cookie = 'fbs_'.$aFB['APP_ID'];
- d('deleting Facebook cookie '.$fb_cookie.' len: '.strlen($fb_cookie));
- $aDelete[] = $fb_cookie;
- }
+ //d('logging out Facebook User');
+ //$aFB = $this->Registry->Ini->getSection('FACEBOOK');
+ //if(!empty($aFB) && !empty($aFB['APP_ID'])){
+ // $fb_cookie = 'fbsr_'.$aFB['APP_ID'];
+ // d('deleting Facebook cookie '.$fb_cookie.' len: '.strlen($fb_cookie));
+ // $aDelete[] = $fb_cookie;
+ //}
d('Delete these cookies: '.print_r($aDelete, 1));
View
8 lib/Lampcms/CookieAuth.php
@@ -83,7 +83,7 @@ class CookieAuth extends UserAuth
public function authByCookie(){
- d('$_COOKIE: '.print_r($_COOKIE, 1));
+ //d('$_COOKIE: '.print_r($_COOKIE, 1));
$User = $this->checkRequiredCookies()
->validateCookieSalt()
@@ -165,7 +165,7 @@ protected function checkRequiredCookies(){
*/
protected function validateCookieSalt(){
parse_str($this->cookie, $a);
- d('parsed cookie: '.print_r($a, 1));
+ //d('parsed cookie: '.print_r($a, 1));
if(!is_array($a) || !array_key_exists('uid', $a) || !array_key_exists('s', $a)){
throw new CookieAuthException('Wrong value of uid cookie could not parse it');
@@ -306,11 +306,11 @@ protected function checkMultipleSidLoginErrors(){
d('$cur: '.gettype($cur).' found count: '.$cur->count());
$aLockParams = $this->Registry->Ini->getSection('LOGIN_ERROR_LOCK');
- d('$aLockParams: '.print_r($aLockParams, 1));
+ //d('$aLockParams: '.print_r($aLockParams, 1));
if ($cur->count() > (int)$aLockParams['max_errors']) {
$a1 = $cur->getNext();
- d('a1: '.print_r($a1, 1));
+ //d('a1: '.print_r($a1, 1));
$lastAttempt = ($now - $a1['i_ts']);
d('$lastAttempt: '.$lastAttempt);
View
33 lib/Lampcms/DB.php
@@ -61,9 +61,9 @@
* @author Dmitri Snytkine
*
*/
-class DB extends LampcmsObject
+class DB
{
- protected $Registry;
+ protected $Ini;
/**
* Instance of this object
@@ -107,36 +107,11 @@ class DB extends LampcmsObject
*
* @return object
*/
- public function __construct(Registry $Registry){
- $this->Registry = $Registry;
- $this->Ini = $Registry->Ini;
+ public function __construct(Ini $Ini){
+ $this->Ini = $Ini;
}
- /**
- * Release resource when this object terminates
- *
- * @todo keep an eye on the possible problems related to
- * this destructor.
- *
- * It may cause some problems that have to do with serializing
- * and unserializing an object, in which case this descructor
- * may be triggered, unsetting the dbh and since this object is singleton,
- * it may affect other objects that are still alive and need
- * and access to dbh through the instance of this class.
- *
- * This is complicated, this should not really happened, but
- * if there are any weired errors that are traced to call to
- * member function on non-object and it's traced to dbh
- * not being an object where it's supposed to be an object for sure,
- * then the problem is almost certainly due to this destructor
- *
- * @return void
- */
- public function __destruct(){
-
- }
-
protected function connect(){
$sDsn = $this->makeDsn();
View
2  lib/Lampcms/Event/Dispatcher.php
@@ -44,7 +44,7 @@
*
* @category Event
* @package Event_Dispatcher2
- * @author Dmitri Snytkine <d.snytkine@gmail.com>
+ * @author Dmitri Snytkine
* @author Bertrand Mansion <bmansion@mamasam.com>
* @author Stephan Schmidt <schst@php.net>
* @copyright 1997-2009 The PHP Group
View
2  lib/Lampcms/Event/Notification.php
@@ -53,7 +53,7 @@
*
* @category Event
* @package Event_Dispatcher2
- * @author Dmitri Snytkine <d.snytkine@gmail.com>
+ * @author Dmitri Snytkine
* @author Bertrand Mansion <bmansion@mamasam.com>
* @author Stephan Schmidt <schst@php.net>
* @copyright 1997-2009 The PHP Group
View
10 lib/Lampcms/Exception.php
@@ -217,7 +217,7 @@ public static function formatException(\Exception $e, $sMessage = '', \Lampcms\I
//$bHtml = ($e instanceof \Lampcms\Exception) ? $e->getHtmlFlag() : false;
if ($e instanceof Lampcms\DevException) {
- $sMessage = ( (defined('LAMPCMS_DEBUG')) && true === LAMPCMS_DEBUG) ? $e->getMessage() : 'Error occured';//$oTr->get('generic_error', 'exceptions');
+ $sMessage = ( (defined('LAMPCMS_DEBUG')) && true === LAMPCMS_DEBUG) ? $e->getMessage() : 'Error occured';//$oTr->get('generic_error', 'exceptions');
}
$sMessage = strip_tags($sMessage);
@@ -531,13 +531,13 @@ class RedirectException extends Exception
/**
* Constructor
*
- * @param str $strNewLocation must be a full url where
+ * @param string $newLocation must be a full url where
* the page can be found
*
- * @param int $intHttpCode HTTP response code
+ * @param int $httpCode HTTP response code
*/
- public function __construct($strNewLocation, $intHttpCode = 301, $boolHTML = true){
- parent::__construct($strNewLocation, null, $intHttpCode, $boolHTML);
+ public function __construct($newLocation, $httpCode = 301, $boolHTML = true){
+ parent::__construct($newLocation, null, $httpCode, $boolHTML);
}
}
View
2  lib/Lampcms/ExternalAuth.php
@@ -109,7 +109,7 @@ class ExternalAuth extends LampcmsObject
* Constructor
* @param Registry $Registry
*/
- protected function __construct(Registry $Registry){
+ public function __construct(Registry $Registry){
$this->Registry = $Registry;
}
View
893 lib/Lampcms/ExternalAuthFb.php
@@ -1,893 +0,0 @@
-<?php
-/**
- *
- * License, TERMS and CONDITIONS
- *
- * This software is lisensed under the GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
- * Please read the license here : http://www.gnu.org/licenses/lgpl-3.0.txt
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * ATTRIBUTION REQUIRED
- * 4. All web pages generated by the use of this software, or at least
- * the page that lists the recent questions (usually home page) must include
- * a link to the http://www.lampcms.com and text of the link must indicate that
- * the website's Questions/Answers functionality is powered by lampcms.com
- * An example of acceptable link would be "Powered by <a href="http://www.lampcms.com">LampCMS</a>"
- * The location of the link is not important, it can be in the footer of the page
- * but it must not be hidden by style attibutes
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * This product includes GeoLite data created by MaxMind,
- * available from http://www.maxmind.com/
- *
- *
- * @author Dmitri Snytkine <cms@lampcms.com>
- * @copyright 2005-2011 (or current year) ExamNotes.net inc.
- * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
- * @link http://www.lampcms.com Lampcms.com project
- * @version Release: @package_version@
- *
- *
- */
-
-
-namespace Lampcms;
-
-/**
- * Class to login or create new account (and then login)
- * the Facebook user
- *
- * @todo Do something if user with the same email already exists
- *
- * @todo post event on user creation, on user update
- * if just adding record to USERS_FACEBOOK for existing user
- * or if updating user data in any way.
- *
- * @todo
- * run post-registration post to wall if Admin set this in config
- *
- * @todo send out registration email after createNewUser() is run
- * send out special email that explains that user can login
- * with Facebook button as before OR directly with
- * new username/password
- * For this the sendRegistrationEmail() should be in some external
- * class that would accept email, body
- * Probably in Mailer class as static method
- *
- *@todo this class should extend Facebook so that we
- *may reuse removeFacebookConnect()
- *
- * @author Dmitri Snytkine
- *
- */
-class ExternalAuthFb extends Facebook
-{
-
- /**
- * Parsed facebook cookie
- *
- * @var array
- */
- protected $aCookieParams = array();
-
-
- /**
- * Array of data returned from Facebook server
- * @var array
- */
- protected $aFbUserData = array();
-
-
- /**
- * Indicates if post announcment of new
- * registation to user's FB Wall
- *
- * @var bool
- */
- protected $bToWall = false;
-
-
- /**
- * Auto generated password for the new user
- *
- * @todo must also check that curl has support for ssl
- * because oAuth2 uses ssl
- *
- * @param object $Registry
- * @param array $aFacebook array from !config.ini FACEBOOK section
- * @param array $aCookieParams
- */
- protected $tempPassword;
-
-
- protected function __construct(Registry $Registry, array $aFacebookConf, array $aCookieParams){
- if(!extension_loaded('curl')){
- throw new \Lampcms\Exception('Cannot use this class because php extension "curl" is not loaded');
- }
-
- parent::__construct($Registry);
- $Registry->Mongo->USERS->ensureIndex(array('fb_id' => 1));
-
- d('$this->User: '.get_class($this->User).' '.print_r($this->User->getArrayCopy(), 1));
- $this->sAccessToken = $aCookieParams['access_token'];
- $this->sAppId = $aFacebookConf['APP_ID'];
- $this->bToWall = (!empty($aFacebookConf['POST_TO_WALL'])) ? true : false;
- $this->aCookieParams = $aCookieParams;
- }
-
-
- /**
- * Get user data from Facebook, do whatever is necessary
- * and return either null or object of type UserFacebook
- * which extends User Object
- *
- * @param Registry $Registry
- *
- * @param bool $bIsConnect if set to true then this method
- * is called for the purpose of "Connecting" existing user to
- * the Facebook Account. This this case we check that Facebook
- * user with the same Facebook account does not already exist
- *
- * @return mixed null of failure or object UserFacebook
- *
- * @throws FacebookAuthException in case user does not have
- * fbs_ cookie or in case this site config does not have
- * necessary settings in [FACEBOOK] section
- * or in case something else goes wrong
- */
- public static function getUserObject(Registry $Registry){
-
- $aFacebookConf = $Registry->Ini->getSection('FACEBOOK');
- $aCookieParams = self::prepareFBCookies($aFacebookConf);
-
- /**
- * At this point we can try to get user
- * just by facebook uid which should be in fb cookie
- * If we can get uid by fbid and then userobject by uid
- * then we can defer calling FB api to later time,
- * but we can't just call fastcgi_finish_request now
- * because it would send out something to the browser now
- * and we still at early stage of page generation.
- *
- */
- if(!empty($aCookieParams['uid'])){
- d('going to try to get user object by fbu uid cookie: '.$aCookieParams['uid']);
- $Registry->Mongo->USERS->ensureIndex(array('fb_id' => 1));
- $aUser = $Registry->Mongo->USERS->findOne(array('fb_id' => (string)$aCookieParams['uid']));
- if(!empty($aUser)){
- /**
- * Should check if user still has FB fb_token?
- * If FB access was revoked why should be still
- * return this user object? It's OK, its still our valid
- * user
- */
- d('Found user by fb cookie in USERS');
- $User = UserFacebook::factory($Registry, $aUser);
- }
-
-
- /**
- * If we able to find our user by facebook user id
- * we will add the job of contacting facebook api
- * for possible update of data to be executed
- * later
- *
- * But if we did not get facebook user by facebook uid
- * that means it's a new user and we must finish
- * this method now in order to create a new user
- *
- */
- if(isset($User)){
- d('got FB user by fb uid from fbu cookie');
-
- $Registry->Viewer = $User;
- $oAuthFB = new self($Registry, $aFacebookConf, $aCookieParams);
- $callable = function() use ($oAuthFB){
- try{
- //d('before facebook auth post precessing $oAuthFB: '.$oAuthFB);
- $oAuthFB->getFbData()->getFacebookUserObject();
- //d('after facebook auth post precessing');
- } catch (Exception $e){
- //e('Unable to run post processing of FB data: '.$e->getFile().' '.$e->getLine().' '.$e->getMessage());
- }
- };
-
- d('cp before runLater');
- runLater($callable);
- d('after runLater');
-
- return $User;
- }
- }
-
- $oAuthFB = new self($Registry, $aFacebookConf, $aCookieParams);
-
- return $oAuthFB->getFbData()->getFacebookUserObject();
- }
-
-
- /**
- * Factory method
- *
- * @param Registry $Registry
- * @return object of this class
- * @throws FacebookAuthException in case Cookie that is supposed
- * to be set by Facebook JS was not or is not valid
- */
- public static function factory(Registry $Registry){
-
- $aFacebookConf = $Registry->Ini->getSection('FACEBOOK');
- $aCookieParams = self::prepareFBCookies($aFacebookConf);
-
- return new self($Registry, $aFacebookConf, $aCookieParams);
- }
-
-
- /**
- * Parse array $aFacebookConf
- * then get, parse and validate cookie set by Facebook JS API
- * If everhing looks good return array parsed cookie
- *
- * @param array $aFacebookConf
- * @throws FacebookAuthException if the required params
- * in !config.ini in 'FACEBOOK' section is not set
- * OR if Facebook cookie does not look valid
- *
- * @return array of parsed cookie
- */
- public static function prepareFBCookies(array $aFacebookConf){
-
- if(empty($aFacebookConf) || (is_array($aFacebookConf)
- && (empty($aFacebookConf['APP_ID']) || empty($aFacebookConf['APP_SECRET']) ) )){
- throw new FacebookAuthUserException('Administrator of this site has not enabled Facebook connect feature');
- }
-
- $sAppId = $aFacebookConf['APP_ID'];
- $sSecret = $aFacebookConf['APP_SECRET'];
-
- $cookieName = 'fbs_'.$sAppId;
- if(!isset($_COOKIE) || empty($_COOKIE[$cookieName])){
- throw new FacebookAuthException('No fbs_ cookie present');
- }
-
- $cookie = $_COOKIE[$cookieName];
-
- $aCookieParams = array();
- parse_str(trim($cookie, '\\"'), $aCookieParams);
-
- d('$aCookieParams: '.print_r($aCookieParams, 1));
-
- if(empty($aCookieParams)
- || empty($aCookieParams['sig'])
- || empty($aCookieParams['access_token'])
- ){
-
- throw new FacebookAuthException('Unable to parse fbs_ cookie: '.$cookie);
- }
-
- /**
- * Security check of fbs cookie
- */
- if($aCookieParams['sig'] !== self::generateSignature($aCookieParams, $sSecret)){
-
- throw new FacebookAuthException('Facebook signature violation. Potential security threat! '.print_r($aCookieParams, 1));
- }
-
- return $aCookieParams;
- }
-
-
- /**
- * Generate a signature for the given params and secret.
- *
- * @param Array $params the parameters to sign
- * @param String $secret the secret to sign with
- * @return String the generated signature
- */
- protected static function generateSignature(array $params, $secret) {
-
- ksort($params);
-
- $s = '';
- foreach($params as $key => $value) {
- if ($key != 'sig') {
- $s .= $key . '=' . $value;
- }
- }
-
- $s .= $secret;
-
- return hash('md5', $s);
- }
-
-
- /**
- * Return object of type FacebookUser
- * this is either the existing user or newly created
- * user
- *
- * @return object of type UserFacebook which extends User Object
- *
- * @throws FacebookAuthException in case something goes wrong
- */
- public function getFacebookUserObject(){
- d('cp');
-
- /**
- * First get userid by fb_id, via cache
- * even though this is usually less than 1 millisecond,
- * still avoiding mysql call is good.
- *
- */
- $aUser = $this->getUserArray($this->aFbUserData['id']);
- if(!empty($aUser)){
- $this->User = UserFacebook::factory($this->Registry, $aUser);
- d('existing user $this->User: '.print_r($this->User->getArrayCopy(), 1));
- $this->updateUser()->updateFbUserRecord();
- d('cp');
-
- return $this->User;
- }
-
-
- /**
- * See if we already have the user with the email
- * address provided by facebook.
- * In such case we just create the record in USERS_FACEBOOK
- * And possibly run updateUser()
- * And then.... append array of access_token, expires
- * to the object
- *
- * @todo potential problem:
- * someone registers bogus account with someone else's email
- * address.
- *
- * Then the real owner of that email registers via Facebook
- * We then associate some bogus account with this one
- *
- * The bogus account cannot be used by hacker because hacker does
- * not know the password so this is not a big problem.
- *
- *
- */
- if(!empty($this->aFbUserData['email'])){
- $aByEmail = $this->Registry->Mongo->EMAILS->findOne(array('email' => strtolower($this->aFbUserData['email']) ));
- d('$aByEmail: '.print_r($aByEmail, 1) );
- if(!empty($aByEmail) && !empty($aByEmail['i_uid'])){
- $uidByEmail = (int)$aByEmail['i_uid'];
- d('$uidByEmail: '.$uidByEmail);
- }
- }
-
-
- /**
- * This means this facebook user is not
- * registered on our site.
- * Not found either by facebook id or by
- * email address. We are confident that this is
- * NOT an existing Facebook user.
- */
- if(empty($uidByEmail)){
- d('cp empty uid');
- $this->createNewUser();
-
- return $this->User;
- }
-
- $aUser = $this->Registry->Mongo->USERS->findOne(array('_id' => $uidByEmail));
- d('aUser var type: '.gettype($aUser).' ' .print_r($aUser, 1));
-
- /**
- * Found existing user
- * If this is a Connect action then check if this is
- * not the same user as Viewer and throw exception
- * if this is the same uid as Viewer then just update
- * Viewer record, it's OK and actually in case Viwer had FB
- * access revoked before this will update their access back
- * to "active" FB user by adding valid FB token to User object
- */
- if(!empty($aUser)){
- $this->User = UserFacebook::factory($this->Registry, $aUser);
- d('existing user $this->User: '.print_r($this->User->getArrayCopy(), 1));
- $this->updateUser();
-
- /**
- * It's possible that this is not the new user
- * but also a new FACEBOOK user.
- * This is when we determined that user with this email
- * already exists in our database but
- * this user has never logged in as Facebook user
- * in this case we still have to create a new
- * record in USERS_FACEBOOK
- */
- $this->updateFbUserRecord();
- } else {
- /**
- * This is the case where we found $uid either is USERS_FACEBOOK
- * or in EMAILS but then were unable to find
- * this user in USERS collection.
- * This is a very unlikely situation, not sure how
- * this could be possible....
- */
- e('Very unlikely situation occured found uid: '.$uid.' but no user in USERS. ');
- d('cp need to create new user');
- $this->createNewUser();
- }
-
- return $this->User;
- }
-
-
- /**
- * Get JSON data from the server for this user
- * If timeout, then what? Then we will throw our own
- * Exception and user will see a message
- * that timeout has occured
- *
- * @return object $this
- */
- public function getFbData(){
- d('$this->User: '.get_class($this->User).' '.print_r($this->User->getArrayCopy(), 1));
- d('This is: '.gettype($this).(is_object($this)) ? get_class($this) : 'not object');
- $url = $this->graphUrl.$this->sAccessToken;
- d('url: '.$url);
-
- $oHTTP = new Curl();
-
- try{
- d('cp');
- $this->oResponse = $oHTTP->getDocument($url)->checkResponse();
- $json = $this->oResponse->getResponseBody();
-
- /**
- * retCode should be 200
- *
- */
- $retCode = $oHTTP->getHttpResponseCode();
- d('json '.$json.' http code: '.$retCode);
-
- /**
- * samle json data, can be used for mock object
- * in testing
- * {
- "id": "100000742465943",
- "name": "Dmitri Snytkine",
- "first_name": "Dmitri",
- "last_name": "Snytkine",
- "link": "http://www.facebook.com/profile.php?id=100000742465943",
- "gender": "male",
- "email": "d.snytkine\u0040gmail.com",
- "timezone": -4,
- "locale": "en_US",
- "verified": true,
- "updated_time": "2011-03-22T18:02:41+0000"
- }
- *
- */
-
- $this->aFbUserData = json_decode($json, true);
- d('$this->aFbUserData: '.print_r($this->aFbUserData, 1));
-
- if(empty($this->aFbUserData)
- || !is_array($this->aFbUserData)
- || !array_key_exists('id', $this->aFbUserData)
- || empty($this->aFbUserData['name'])){
-
- throw new FacebookAuthException('Invalid data returned by FriendConnect server: '.print_r($this->aFbUserData, 1));;
- }
-
- } catch (HttpTimeoutException $e ){
- d('Request to GFC server timedout');
-
- throw new FacebookAuthUserException('Request to Facebook server timed out. Please try again later');
- } catch (Http401Exception $e){
- d('Unauthorized to get data from Facebook, most likely user unjoined the site');
- $this->revokeFacebookConnect();
- Cookie::delete('fbs_'.$this->sAppId);
-
- throw new FacebookAuthUserException('Unauthorized with Facebook server');
-
- } catch(HttpResponseCodeException $e){
- e('LampcmsError Facebook response exception: '.$e->getHttpCode().' '.$e->getMessage());
- /**
- * The non-200 response code means there is some kind
- * of error, maybe authorization failed or something like that,
- * or maybe Facebook Connect server was acting up.
- * In this case it is better to delete fcauth cookies
- * so that we dont go through these steps again.
- * User will just have to re-do the login Facebook step
- */
- Cookie::delete('fbs_'.$this->sAppId);
- $this->revokeFacebookConnect();
-
- throw new FacebookAuthUserException('Error during authentication with Facebook server');
- }
-
- return $this;
- }
-
-
- /**
- * Update user data in USERS collection
- * by using $this->User object's save() method
- *
- * @return object $this
- */
- protected function updateUser($updateAvatar = true){
- d('cp');
-
- $this->User['fb_id'] = (string)$this->aFbUserData['id'];
- $this->User['fb_token'] = $this->aCookieParams['access_token'];
- $this->User['fn'] = $this->aFbUserData['first_name'];
- $this->User['ln'] = $this->aFbUserData['last_name'];
- $extAvatar = $this->User['avatar_external'];
-
- /**
- * Reason why not checking $updateAvatar anymore
- * is because if logged in with Twitter,
- * then added FB using Connect - the avatar is not
- * updated (good)
- * but then same user loggs in with FB and
- * at that time $updateAvatar = false not passed
- * and avatar is then just changed to FB!
- * Unexpected turn of events!
- */
- if(empty($extAvatar)){
- $this->User['avatar_external'] = 'http://graph.facebook.com/'.$this->aFbUserData['id'].'/picture';
- }
-
- if(!empty($this->aFbUserData['link'])){
- $this->User['fb_url'] = $this->aFbUserData['link'];
- }
-
- try{
- $this->User->save();
- d('cp');
-
- $this->Registry->Dispatcher->post($this->User, 'onUserUpdate');
- d('cp');
- } catch (\Exception $e){
- e('Error while saving user: '.$e->getMessage().' file: '.$e->getFile().' on line '.$e->getLine());
- }
-
-
- return $this;
- }
-
-
- /**
- * @todo
- * What if email address provided from Facebook
- * already belongs to some other user?
- *
- * This would mean that existing user is just
- * trying to signup with Facebook.
- *
- * In this case we should allow it but ONLY create
- * a record in the USERS_FACEBOOK table and use users_id
- * of use that we find by email address
- *
- * and then also insert avatar_external into USERS
- *
- * @todo create username for user based on Facebook username
- * Facebook does not really have username, so we can use fn_ln
- *
- */
- protected function createNewUser(){
- d('cp');
- $this->Registry->Mongo->USERS->ensureIndex(array('fb_id' => 1));
-
- /**
- * Time zone offset in seconds
- * @var int
- */
- $tzo = (array_key_exists('timezone', $this->aFbUserData)) ? $this->aFbUserData['timezone'] * 3600 : Cookie::get('tzo', 0);
-
- /**
- * User language
- * @var string
- */
- $lang = (!empty($this->aFbUserData['locale'])) ? \strtolower(\substr($this->aFbUserData['locale'], 0, 2)) : $this->Registry->getCurrentLang();
-
- /**
- * User locale
- * @var string
- */
- $locale = (!empty($this->aFbUserData['locale'])) ? $this->aFbUserData['locale'] : $this->Registry->Locale->getLocale();
-
- $this->tempPassword = String::makePasswd();
-
- /**
- * Sid value use existing cookie val
- * if possible, otherwise create a new one
- * @var string
- */
- $sid = (false === ($sid = Cookie::getSidCookie())) ? String::makeSid() : $sid;
-
- $displayName = (!empty($this->aFbUserData['name'])) ? $this->aFbUserData['name'] : $this->aFbUserData['first_name'].' '.$this->aFbUserData['last_name'];
- $username = $this->makeUsername($displayName);
-
- /**
- * Create new record in USERS table
- * do this first because we need uid from
- * newly created record
- */
- $aUser = array(
- 'username' => $username,
- 'username_lc' => \mb_strtolower($username, 'utf-8'),
- 'fn' => $this->aFbUserData['first_name'],
- 'ln' => $this->aFbUserData['last_name'],
- 'rs' => $sid,
- 'email' => Utf8String::factory($this->aFbUserData['email'])->toLowerCase()->valueOf(),
- 'fb_id' => (string)$this->aFbUserData['id'],
- 'fb_token' => $this->aCookieParams['access_token'],
- 'pwd' => String::hashPassword($this->tempPassword),
- 'avatar_external' => 'http://graph.facebook.com/'.$this->aFbUserData['id'].'/picture',
- 'i_reg_ts' => time(),
- 'date_reg' => date('r'),
- 'role' => 'external_auth',
- 'lang' => $lang,
- 'i_rep' => 1,
- 'tz' => TimeZone::getTZbyoffset($tzo),
- 'i_fv' => (false !== $intFv = Cookie::getSidCookie(true)) ? $intFv : time());
-
- if(!empty($this->aFbUserData['gender'])){
- $aUser['gender'] = ('male' === $this->aFbUserData['gender']) ? 'M' : 'F';
- }
-
- $aUser = \array_merge($this->Registry->Geo->Location->data, $aUser);
-
- if(!empty($this->aFbUserData['locale'])){
- $aUser['locale'] = $this->aFbUserData['locale'];
- }
-
- if(!empty($this->aFbUserData['link'])){
- $aUser['fb_url'] = $this->aFbUserData['link'];
- }
-
- d('aUser: '.print_r($aUser, 1));
-
- $this->User = UserFacebook::factory($this->Registry, $aUser);
- $this->User->insert();
- //$this->User->setNewUser();
-
-
- d('$this->User after insert: '.print_r($this->User->getArrayCopy(), 1));
- $this->Registry->Dispatcher->post($this->User, 'onNewUser');
- $this->Registry->Dispatcher->post($this->User, 'onNewFacebookUser');
- d('cp');
-
- $this->saveEmailAddress();
- d('cp');
-
- /**
- * Create new record in USERS_FACEBOOK
- */
- $this->updateFbUserRecord();
-
- PostRegistration::createReferrerRecord($this->Registry, $this->User);
-
- $this->postRegistrationToWall();
-
- return $this;
- }
-
-
- /**
- * Create new record in EMAILS table for this new user
- * but only if user has provided email address
- *
- * @return object $this
- */
- protected function saveEmailAddress(){
- if(!empty($this->aFbUserData['email'])){
- $coll = $this->Registry->Mongo->EMAILS;
- $coll->ensureIndex(array('email' => 1), array('unique' => true));
-
- $a = array(
- 'email' => \mb_strtolower($this->aFbUserData['email']),
- 'i_uid' => $this->User->getUid(),
- 'has_gravatar' => Gravatar::factory($this->aFbUserData['email'])->hasGravatar(),
- 'ehash' => hash('md5', $this->aFbUserData['email']));
- try{
- $o = \Lampcms\Mongo\Doc::factory($this->Registry, 'EMAILS', $a)->insert();
- } catch (\Exception $e){
- e('Unable to save email address from Facebook to our EMAILS: '.$e->getMessage().' in '.$e->getFile().' on '.$e->getLine());
- }
- }
-
- return $this;
- }
-
-
- /**
- * Create a new record in USERS_FACEBOOK table
- * or update an existing record
- *
- * @param bool $isUpdate
- *
- * @return object $this
- */
- protected function updateFbUserRecord(){
- d('cp');
-
- $uid = $this->User->getUid();
- d('uid '.$uid);
-
- $aFb = array(
- '_id' => (string)$this->aFbUserData['id'],
- 'i_uid' => $uid,
- 'access_token' => $this->aCookieParams['access_token'],
- 'token_expiration' => (array_key_exists('expires', $this->aCookieParams)) ? $this->aCookieParams['expires'] : 0,
- 'a_data' => $this->aFbUserData);
-
- d('aFb: '.print_r($aFb, 1));
-
- $this->Registry->Mongo->USERS_FACEBOOK->save($aFb, array('fsync' => true));
- d('cp');
-
- return $this;
- }
-
-
- /**
- * @todo translate strings
- *
- * @todo have site logo image in settings
- *
- * @todo unfinished. Must ask user permission
- * during registration to post something to the wall
- * like "I joined this cool site"
- *
- * Post to user wall
- *
- */
- protected function postRegistrationToWall(){
-
- return $this;
-
- d('bToWall: '.$this->bToWall);
- if($this->bToWall){
- $aData = array(
- 'access_token' => $this->aCookieParams['access_token'],
- 'message' => 'Joined this website',
- 'link' => $this->Registry->Ini->SITE_URL,
- 'caption' => 'Interesting stuff',
- 'name' => $this->Registry->Ini->SITE_TITLE,
- 'description' => '<b>Cool stuff </b>');
-
- }
-
- return $this;
- }
-
-
- /**
- * Add Facebook token and stuff to existing user
- *
- * Logic:
- * 1) If there is already another user with same
- * Facebook account - throw exception - must be unique
- *
- * 2) If this user is already connected to this same FB account -
- * this is OK, just update FB and User records
- *
- * 3) If Facebook's email address belongs to another user -?
- * It should not really be a problem in this case. This means
- * that someone (probably this same user) already has an account
- * on this site but it's a different account. So NOW this user is
- * connecting his second account to Facebook. This should not
- * cause any problems in the future.
- *
- *
- * @param User $User
- * @return object $this
- */
- public function connect(User $User){
- d('cp');
- $this->User = $User;
- if(!empty($this->aCookieParams['uid'])){
- d('cp');
- $this->checkUniqueAccount($this->getUserArray($this->aCookieParams['uid']));
- }
-
- $this->getFbData();
- d('cp');
-
- $this->checkUniqueAccount($this->getUserArray($this->aFbUserData['id']));
- d('cp');
- /**
- * Now we need to check again if
- * another user already uses this Facebook account
- *
- * If NOT then create new Facebook record
- * and add Facebook credentials to existing user
- * NOT going to create new user!
- */
- $this->updateUser(false)->updateFbUserRecord();
- d('cp');
-
- return $this;
- }
-
-
- /**
- *
- * Get array of data for user by the value
- * of fb_id in USERS collection
- *
- * @param mixed $fb_id
- * @return mixed null|array
- *
- */
- protected function getUserArray($fb_id){
- $fb_id = (string)$fb_id;
-
- return $this->Registry->Mongo->USERS->findOne(array('fb_id' => $fb_id));
- }
-
-
- /**
- *
- * Validation to check that user represented by
- * $aUser array is the same account as $this->User
- *
- * @param array $aUser
- * @throws \Lampcms\Exception is user from input array
- * is different from $this->User.
- *
- * @return object $this
- *
- */
- protected function checkUniqueAccount(array $aUser = null){
- if(!is_object($this->User) || (!$this->User instanceof \Lampcms\User)){
- d('$this->User now set yet');
-
- throw new DevException('$this->User now set yet');
- }
-
- if(!empty($aUser) && ((int)$aUser['_id'] !== $this->User->getUid())){
- d('Different user already exists');
-
- throw new Exception('This Facebook account is already connected to another user <strong>'.$aUser['fn']. ' '.$aUser['ln'].'</strong><br>
- <br>A Facebook account cannot be associated with more than one account on this site<br>');
- }
-
- d('cp');
-
- return $this;
- }
-
-
- /**
- * @todo sent a welcome email,
- * include temp password and explain to user
- * that user can keep logging in with facebook connect
- * OR using email address and password
- *
- * Enter description here ...
- */
- protected function sendWelcomeEmail(){
-
- }
-
-}
View
317 lib/Lampcms/Facebook.php
@@ -1,317 +0,0 @@
-<?php
-/**
- *
- * License, TERMS and CONDITIONS
- *
- * This software is lisensed under the GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
- * Please read the license here : http://www.gnu.org/licenses/lgpl-3.0.txt
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * ATTRIBUTION REQUIRED
- * 4. All web pages generated by the use of this software, or at least
- * the page that lists the recent questions (usually home page) must include
- * a link to the http://www.lampcms.com and text of the link must indicate that
- * the website's Questions/Answers functionality is powered by lampcms.com
- * An example of acceptable link would be "Powered by <a href="http://www.lampcms.com">LampCMS</a>"
- * The location of the link is not important, it can be in the footer of the page
- * but it must not be hidden by style attibutes
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * This product includes GeoLite data created by MaxMind,
- * available from http://www.maxmind.com/
- *
- *
- * @author Dmitri Snytkine <cms@lampcms.com>
- * @copyright 2005-2011 (or current year) ExamNotes.net inc.
- * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
- * @link http://www.lampcms.com Lampcms.com project
- * @version Release: @package_version@
- *
- *
- */
-
-
-
-namespace Lampcms;
-
-use \Lampcms\Interfaces\FacebookUser;
-
-/**
- * Class for working with Facebook REST Oauth based API
- * @author Dmitri Snytkine
- *
- *
- */
-class Facebook extends ExternalAuth
-{
- /**
- * Url of Facebook Graph API for posting message to wall
- * This is a template url. %s will be replaced with actual facebookID
- * of User
- *
- * This same url can also be used to get data from API, just
- * set method to GET instead of post
- * and can get the DATA from Facebook
- *
- * @var string
- */
- protected $wallUpdateUrl = 'https://graph.facebook.com/%s/feed';
-
-
- /**
- * Url of facebook API
- * @var string
- */
- protected $graphUrl = 'https://graph.facebook.com/me?access_token=';
-
-
- /**
- * Object User that we either found
- * or created new user
- *
- * @var object which extends User
- */
- protected $User;
-
-
- /**
- * access token we get from fb cookie
- *
- * @var string
- */
- protected $sAccessToken = null;
-
-
- /**
- * Facebook Application ID
- * You get this by setting up your own application on facebook
- * here: http://www.facebook.com/developers/
- *
- * @var string
- */
- protected $sAppId = null;
-
-
- /**
- * Object returned by \Lampcms\Curl
- *
- * @var object
- */
- protected $oResponse;
-
-
- /**
- * Object of type \Lampcms\Curl;
- * @var object
- */
- protected $oHTTP;
-
-
- /**
- * Array of data returned from Facebook server
- * @var array
- */
- protected $aFbUserData = array();
-
-
- /**
- * Constructor
- *
- * @param object $Registry
- * @param object $User
- */
- protected function __construct(Registry $Registry, FacebookUser $User = null){
- parent::__construct($Registry);
- $this->User = (null !== $User) ? $User : $Registry->Viewer;
- $this->initHttpObject();
- }
-
-
- /**
- * Instantiates (or resets) the
- * $this->oHTTP which is our instance of Curl class
- */
- protected function initHttpObject(){
- $this->oHTTP = new Curl();
-
- return $this;
- }
-
-
- /**
- * Setter for $this->User
- *
- * @param FacebookUser $User
- * @return object $this
- */
- public function setUser(FacebookUser $User){
- $this->User = $User;
-
- return $this;
- }
-
-
- /**
- * Post message to the wall of user
- *
- * @param array $aData must include at least 'message' key
- * with actual message to post some html allowed, some not.
- * It's up to facebook to decide which html is not allowed
- *
- * @param object $Registry Registry object
- * @param object $User user object or null
- * in case of null the currently logged in user is used
- *
- * @return mixed whatever is returned by postUpdate method
- * @see postUpdate()
- */
- public static function postToWall(Registry $Registry, $aData, FacebookUser $User = null){
- $o = new self($Registry, $User);
- return $o->postUpdate($aData);
- }
-
-
- /**
- * Post update to user Wall
- *
- *
- * @param mixed array $aData | string can provide just
- * a string it will be posted to Facebook User's Wall as a message
- * it can contain some html code - it's up to Facebook to allow
- * or disallow certain html tags
- *
- * @return mixed if successful post to Facebook API
- * then it will return the string returned by API
- * This could be raw string of json data - not json decoded yet
- * or false in case there were some errors
- *
- * @throws FacebookApiException in case of errors with
- * using API or more general \Lampcms\Exception in case there
- * were some other problems sowhere along the line like
- * in case with Curl object
- *
- */
- public function postUpdate($aData){
-
- if(!is_string($aData) && !is_array($aData)){
- throw new \InvalidArgumentException('Invalid data type of $aData: '.\gettype($aData));
- }
-
- $aData = \is_array($aData) ? $aData : array('message' => $aData);
-
- $facebookUid = $this->User->getFacebookUid();
- $facebookToken = $this->User->getFacebookToken();
- d('$facebookUid: '.$facebookUid.' $facebookToken: '.$facebookToken);
-
- if(empty($facebookUid) || empty($facebookToken)){
- d('User is not connected with Facebook');
-
- return false;
- }
-
- $aData['access_token'] = $this->User->getFacebookToken();
- d('$aData: '.print_r($aData, 1));
-
- $url = \sprintf($this->wallUpdateUrl, $facebookUid);
- d('cp url: '.$url);;
- try{
- $this->oHTTP->getDocument($url, null, null, array('formVars' => $aData))->checkResponse();
- $retCode = $this->oHTTP->getHttpResponseCode();
- $body = $this->oHTTP->getResponseBody();
- d('retCode: '.$retCode.' resp: '.$body);
- return $body;
- } catch(HttpTimeoutException $e ){
- d('Request to Facebook server timedout');
- throw new FacebookApiException('Request to Facebook server timed out. Please try again later');
- } catch(Http401Exception $e){
- d('Unauthorized to get data from Facebook, most likely user unjoined the site');
- $this->revokeFacebookConnect();
- throw new FacebookApiException('Anauthorized with Facebook');
- } catch(HttpResponseCodeException $e){
- e('LampcmsError Facebook response exception: '.$e->getHttpCode().' '.$e->getMessage().' body: '.$this->oHTTP->getResponseBody());
- /**
- * The non-200 response code means there is some kind
- * of error, maybe authorization failed or something like that,
- * or maybe Facebook server was acting up,
- * in this case it is better to delete cookies
- * so that we dont go through these steps again.
- * User will just have to re-do the login fir GFC step
- */
-
- throw new FacebookApiException('Error during authentication with Facebook server');
- }catch (\Exception $e){
- e('Unable to post: '.$e->getMessage().' code: '.$e->getCode());
- throw $e;
- }
-
- d('cp');
-
- return false;
- }
-
-
- /**
- * Validation to make sure data array
- * has required keys 'message'
- * @param unknown_type $aData
- */
- protected function validateData(array &$aData){
- if(empty($aData['message'])){
- throw new FacebookApiException('Array of data must contain key "message" and its value cannot be empty');
- }
-
- if(empty($aData['access_token'])){
- $aData['access_token'] = $this->User->getFacebookToken();
- }
- }
-
-
- /**
- * In case we got the 401 Error this means
- * user is no longer authorizing us to post
- * to wall
- *
- * What do we do?
- * We can delete from USERS_FACEBOOK
- * or just mark it or just remove the access token
- *
- * But what if user only remove one permission like
- * to post updates or to post while offline?
- *
- * but still authorizes us to do stuff like
- * get email address?
- *
- *@todo finish this
- */
- protected function revokeFacebookConnect(){
- /**
- * Why uid is 0?
- * This means user viewer is not logged in, but why?
- *
- */
- d('$this->User: '.get_class($this->User).' '.print_r($this->User->getArrayCopy(), 1));
-
- $this->User->revokeFacebookConnect();
-
- return $this;
- }
-}
View
8 lib/Lampcms/FollowManager.php
@@ -54,7 +54,13 @@
class FollowManager extends LampcmsObject
{
-
+ /**
+ * @todo instead
+ * should pass Mongo, Dispatcher objects
+ * And not extend LampcmsObject
+ *
+ * @param Registry $Registry
+ */
public function __construct(Registry $Registry){
$this->Registry = $Registry;
}
View
1  lib/Lampcms/I18n/XliffCatalog.php
@@ -122,7 +122,6 @@ protected function parseFile($file){
$current = libxml_use_internal_errors(true);
if (!@$oDom->load($file, LIBXML_COMPACT)) {
$err = implode("\n", $this->getXmlErrors());
- exit($err);
throw new \Lampcms\DevException($err);
}
View
30 lib/Lampcms/Locale/Locale.php
@@ -51,7 +51,17 @@
namespace Lampcms\Locale;
-
+/**
+ * Class for setting
+ * Locate value,
+ * and for settings SESSION['langs'] drop-down menu
+ *
+ * @todo Pass only Viewer and Ini to constructor, do not
+ * pass Registry and not necessary to extend LampcmsObject
+ *
+ * @author Dmitri Snytkine
+ *
+ */
class Locale extends \Lampcms\LampcmsObject
{
/**
@@ -95,7 +105,7 @@ public function init(){
* If Viewer is not a guest then
* get value of locale from Viewer object
*/
- if(is_object($this->Registry->Viewer) && !$this->Registry->Viewer->isGuest()){
+ if(!$this->Registry->Viewer->isGuest()){
$this->locale = $this->Registry->Viewer->offsetGet('locale');
} elseif (isset($_COOKIE) && !empty($_COOKIE['locale'])) {
$this->locale = $_COOKIE['locale'];
@@ -162,10 +172,10 @@ public function makeOptions(){
$tpl = '<select name="locale" class="locales" id="id_locale">%s</select>';
- $ret = sprintf($tpl, $ret);
+ $ret = \sprintf($tpl, $ret);
}
- return sprintf($tplWrapper, $ret);
+ return \sprintf($tplWrapper, $ret);
}
@@ -181,9 +191,9 @@ public function makeOptions(){
* @return string html fragment
*/
public function getOptions(){
- /*if(isset($_SESSION) && !empty($_SESSION['langs'])){
+ if(isset($_SESSION) && !empty($_SESSION['langs'])){
return $_SESSION['langs'];
- }*/
+ }
$langs = $this->makeOptions();
@@ -207,9 +217,9 @@ public function set($locale){
d(' $locale: '.$locale);
$res = false;
$locales = array(
- str_replace('_', '-', $locale),
- str_replace('-', '_', $locale),
- strtolower(substr($locale, 0, 2))
+ \str_replace('_', '-', $locale),
+ \str_replace('-', '_', $locale),
+ \strtolower(\substr($locale, 0, 2))
);
$this->locale = $locale;
@@ -240,6 +250,6 @@ public function getLocale(){
*
*/
public function setLocale(){
- return @setlocale(LC_ALL, $this->locale, str_replace('_', '-', $this->locale));
+ return @setlocale(LC_ALL, $this->locale, \str_replace('_', '-', $this->locale));
}
}
View
2  lib/Lampcms/LoginForm.php
@@ -127,8 +127,6 @@ public static function makeWelcomeMenu(Registry $Registry){
*/
protected static function forGuest(Registry $Registry){
- d('SESSION: '.print_r($_SESSION, 1));
-
if( empty($_SESSION['guest_block']) || !empty($_SESSION['login_error'])) {
$html = '';
View
712 lib/Lampcms/Modules/Facebook/Client.php
@@ -0,0 +1,712 @@
+<?php
+/**
+ *
+ * License, TERMS and CONDITIONS
+ *
+ * This software is lisensed under the GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
+ * Please read the license here : http://www.gnu.org/licenses/lgpl-3.0.txt
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * ATTRIBUTION REQUIRED
+ * 4. All web pages generated by the use of this software, or at least
+ * the page that lists the recent questions (usually home page) must include
+ * a link to the http://www.lampcms.com and text of the link must indicate that
+ * the website\'s Questions/Answers functionality is powered by lampcms.com
+ * An example of acceptable link would be "Powered by <a href="http://www.lampcms.com">LampCMS</a>"
+ * The location of the link is not important, it can be in the footer of the page
+ * but it must not be hidden by style attibutes
+ *