Alex Trofimov 12 лет назад
Родитель
Сommit
a545d693cd
100 измененных файлов с 4289 добавлено и 3616 удалено
  1. 21 21
      cmts.php
  2. 4 4
      get_rss_feed.php
  3. 2 2
      grid.php
  4. 2 3
      image_transcoder.php
  5. 14 9
      inc/classes/BxDol.php
  6. 63 45
      inc/classes/BxDolAccount.php
  7. 56 41
      inc/classes/BxDolAccountQuery.php
  8. 283 271
      inc/classes/BxDolAcl.php
  9. 69 54
      inc/classes/BxDolAclQuery.php
  10. 22 21
      inc/classes/BxDolAlerts.php
  11. 3 4
      inc/classes/BxDolCache.php
  12. 14 15
      inc/classes/BxDolCacheAPC.php
  13. 14 15
      inc/classes/BxDolCacheEAccelerator.php
  14. 17 18
      inc/classes/BxDolCacheFile.php
  15. 8 9
      inc/classes/BxDolCacheFileHtml.php
  16. 15 16
      inc/classes/BxDolCacheMemcache.php
  17. 0 1
      inc/classes/BxDolCacheUtilities.php
  18. 14 15
      inc/classes/BxDolCacheXCache.php
  19. 28 23
      inc/classes/BxDolCaptcha.php
  20. 8 5
      inc/classes/BxDolCaptchaQuery.php
  21. 266 268
      inc/classes/BxDolCmts.php
  22. 69 70
      inc/classes/BxDolCmtsQuery.php
  23. 10 11
      inc/classes/BxDolConfig.php
  24. 101 77
      inc/classes/BxDolConnection.php
  25. 43 24
      inc/classes/BxDolConnectionQuery.php
  26. 1 2
      inc/classes/BxDolCron.php
  27. 6 7
      inc/classes/BxDolCronPruning.php
  28. 2 2
      inc/classes/BxDolCronStorage.php
  29. 53 69
      inc/classes/BxDolDb.php
  30. 29 25
      inc/classes/BxDolEditor.php
  31. 8 5
      inc/classes/BxDolEditorQuery.php
  32. 32 27
      inc/classes/BxDolEmailTemplates.php
  33. 5 5
      inc/classes/BxDolEmailTemplatesQuery.php
  34. 46 33
      inc/classes/BxDolFile.php
  35. 210 180
      inc/classes/BxDolForm.php
  36. 9 8
      inc/classes/BxDolFormNested.php
  37. 24 19
      inc/classes/BxDolFormQuery.php
  38. 41 31
      inc/classes/BxDolFtp.php
  39. 101 91
      inc/classes/BxDolGrid.php
  40. 8 7
      inc/classes/BxDolGridConnections.php
  41. 11 8
      inc/classes/BxDolGridQuery.php
  42. 17 9
      inc/classes/BxDolGzip.php
  43. 1 1
      inc/classes/BxDolIO.php
  44. 69 77
      inc/classes/BxDolImageResize.php
  45. 107 83
      inc/classes/BxDolImageTranscoder.php
  46. 44 31
      inc/classes/BxDolImageTranscoderQuery.php
  47. 24 21
      inc/classes/BxDolInformer.php
  48. 1 1
      inc/classes/BxDolInstallerUtils.php
  49. 26 18
      inc/classes/BxDolKey.php
  50. 14 8
      inc/classes/BxDolKeyQuery.php
  51. 69 41
      inc/classes/BxDolLanguages.php
  52. 83 72
      inc/classes/BxDolLanguagesQuery.php
  53. 39 32
      inc/classes/BxDolMenu.php
  54. 16 10
      inc/classes/BxDolMenuQuery.php
  55. 19 10
      inc/classes/BxDolModule.php
  56. 24 13
      inc/classes/BxDolModuleConfig.php
  57. 9 7
      inc/classes/BxDolModuleDb.php
  58. 62 43
      inc/classes/BxDolModuleQuery.php
  59. 25 15
      inc/classes/BxDolModuleTemplate.php
  60. 25 23
      inc/classes/BxDolObject.php
  61. 33 27
      inc/classes/BxDolPage.php
  62. 17 11
      inc/classes/BxDolPageQuery.php
  63. 52 39
      inc/classes/BxDolPaginate.php
  64. 31 22
      inc/classes/BxDolPermalinks.php
  65. 47 44
      inc/classes/BxDolPrivacy.php
  66. 37 35
      inc/classes/BxDolPrivacyQuery.php
  67. 65 40
      inc/classes/BxDolProfile.php
  68. 9 7
      inc/classes/BxDolProfileForms.php
  69. 58 42
      inc/classes/BxDolProfileQuery.php
  70. 27 18
      inc/classes/BxDolProfileUndefined.php
  71. 43 31
      inc/classes/BxDolRequest.php
  72. 14 14
      inc/classes/BxDolRssFactory.php
  73. 53 59
      inc/classes/BxDolSearch.php
  74. 5 6
      inc/classes/BxDolService.php
  75. 34 21
      inc/classes/BxDolSession.php
  76. 14 8
      inc/classes/BxDolSessionQuery.php
  77. 131 126
      inc/classes/BxDolSocialSharing.php
  78. 30 28
      inc/classes/BxDolSocialSharingQuery.php
  79. 236 182
      inc/classes/BxDolStorage.php
  80. 23 21
      inc/classes/BxDolStorageLocal.php
  81. 80 52
      inc/classes/BxDolStorageQuery.php
  82. 34 30
      inc/classes/BxDolStorageS3.php
  83. 246 188
      inc/classes/BxDolTemplate.php
  84. 72 55
      inc/classes/BxDolUploader.php
  85. 8 5
      inc/classes/BxDolUploaderQuery.php
  86. 33 32
      inc/classes/BxDolView.php
  87. 9 8
      inc/classes/BxDolViewQuery.php
  88. 107 106
      inc/classes/BxDolVote.php
  89. 38 38
      inc/classes/BxDolVoteQuery.php
  90. 24 15
      inc/classes/BxDolXmlParser.php
  91. 17 13
      inc/design.inc.php
  92. 25 28
      inc/profiles.inc.php
  93. 134 98
      inc/utils.inc.php
  94. 4 6
      index.php
  95. 17 16
      install/classes/BxDolInstallController.php
  96. 9 6
      install/classes/BxDolInstallLang.php
  97. 24 20
      install/classes/BxDolInstallModulesTools.php
  98. 28 28
      install/classes/BxDolInstallSiteConfig.php
  99. 8 8
      install/classes/BxDolInstallView.php
  100. 7 7
      install/cmd.php

+ 21 - 21
cmts.php

@@ -21,25 +21,25 @@ bx_import('BxDolCmts');
 $oCmts = BxDolCmts::getObjectInstance($sSys, $iObjectId, true);
 
 if ($oCmts && $sSys && $iObjectId) {
-	if($sAction) {
-	    header('Content-Type: text/html; charset=utf-8');
-	    $sMethod = 'action' . $sAction;
-	    echo $oCmts->$sMethod();
-	    exit;
-	}
-
-	$iCmtId = bx_get('cmt_id');
-	if($iCmtId !== false) {
-		$sObjectTitle = $oCmts->getObjectTitle($iObjectId);
-
-		$sHeader = _t('_cmt_page_view_header', $sObjectTitle);
-		$sTitle = _t('_cmt_page_view_title', $oCmts->getBaseUrl(), $sObjectTitle);
-		$sContent = DesignBoxContent($sTitle, $oCmts->getCommentBlock($iCmtId), BX_DB_PADDING_DEF);
-
-		$oTemplate = BxDolTemplate::getInstance();
-		$oTemplate->setPageNameIndex(BX_PAGE_DEFAULT);
-		$oTemplate->setPageHeader($sHeader);
-		$oTemplate->setPageContent('page_main_code', $sContent);
-		$oTemplate->getPageCode();
-	}
+    if($sAction) {
+        header('Content-Type: text/html; charset=utf-8');
+        $sMethod = 'action' . $sAction;
+        echo $oCmts->$sMethod();
+        exit;
+    }
+
+    $iCmtId = bx_get('cmt_id');
+    if($iCmtId !== false) {
+        $sObjectTitle = $oCmts->getObjectTitle($iObjectId);
+
+        $sHeader = _t('_cmt_page_view_header', $sObjectTitle);
+        $sTitle = _t('_cmt_page_view_title', $oCmts->getBaseUrl(), $sObjectTitle);
+        $sContent = DesignBoxContent($sTitle, $oCmts->getCommentBlock($iCmtId), BX_DB_PADDING_DEF);
+
+        $oTemplate = BxDolTemplate::getInstance();
+        $oTemplate->setPageNameIndex(BX_PAGE_DEFAULT);
+        $oTemplate->setPageHeader($sHeader);
+        $oTemplate->setPageContent('page_main_code', $sContent);
+        $oTemplate->getPageCode();
+    }
 }

+ 4 - 4
get_rss_feed.php

@@ -13,11 +13,11 @@ $mixedBlockId = bx_process_input(bx_get('ID'));
 
 $aPredefinedRssFeeds = array (
     'boonex_news' => 'http://www.boonex.com/unity/blog/featured_posts/?rss=1',
-	'boonex_version' => 'http://rss.boonex.com/',
-	'boonex_unity_market' => 'http://www.boonex.com/unity/extensions/latest/?rss=1',
-	'boonex_unity_lang_files' => 'http://www.boonex.com/unity/extensions/tag/translations&rss=1',
+    'boonex_version' => 'http://rss.boonex.com/',
+    'boonex_unity_market' => 'http://www.boonex.com/unity/extensions/latest/?rss=1',
+    'boonex_unity_lang_files' => 'http://www.boonex.com/unity/extensions/tag/translations&rss=1',
     'boonex_unity_market_templates' => 'http://www.boonex.com/unity/extensions/tag/templates&rss=1',
-    'boonex_unity_market_featured' => 'http://www.boonex.com/unity/extensions/featured_posts?rss=1', 
+    'boonex_unity_market_featured' => 'http://www.boonex.com/unity/extensions/featured_posts?rss=1',
 );
 
 if (isset($aPredefinedRssFeeds[$mixedBlockId])) {

+ 2 - 2
grid.php

@@ -19,13 +19,13 @@ if (!$sObject)
 bx_import('BxDolGrid');
 $oGrid = BxDolGrid::getObjectInstance($sObject);
 if (!$oGrid) {
-    // no such grid object available    
+    // no such grid object available
     exit;
 }
 
 $sAction = 'performAction' . bx_gen_method_name(bx_process_input(bx_get('a')));
 if (method_exists($oGrid, $sAction)) {
     $oGrid->$sAction();
-} 
+}
 
 /** @} */

+ 2 - 3
image_transcoder.php

@@ -28,7 +28,7 @@ bx_import('BxDolImageTranscoder');
 $oTranscoder = BxDolImageTranscoder::getObjectInstance($sTranscoderObject);
 
 if (!$oTranscoder) {
-    ob_end_clean();    
+    ob_end_clean();
     bx_transcoder_error_occured();
     exit;
 }
@@ -50,7 +50,7 @@ header('HTTP/1.1 301 Moved Permanently');
 header('Location: ' . $sImageUrl);
 exit;
 
-function bx_transcoder_error_occured($sMethod = 'displayPageNotFound') 
+function bx_transcoder_error_occured($sMethod = 'displayPageNotFound')
 {
     require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
     bx_import('BxDolLanguages');
@@ -60,4 +60,3 @@ function bx_transcoder_error_occured($sMethod = 'displayPageNotFound')
 }
 
 /** @} */
-

+ 14 - 9
inc/classes/BxDol.php

@@ -7,9 +7,9 @@
  * @{
  */
 
-/** 
+/**
  * @page objects Objects
- * Classes which represents high level programming constructions to generate ready functionality, like Comments, Votings, Forms. 
+ * Classes which represents high level programming constructions to generate ready functionality, like Comments, Votings, Forms.
  */
 
 /**
@@ -20,35 +20,40 @@ $GLOBALS['bxDolClasses'] = array();
 /**
  * Base class for all Dolphin classes
  */
-class BxDol {
+class BxDol
+{
     public function BxDol () {}
 }
 
 /**
  * Singleton interface, for objects with one instance only
  */
-interface iBxDolSingleton {
+interface iBxDolSingleton
+{
     public static function getInstance();
 }
 
 /**
  * Factory interface for object instances, once instance per object name
  */
-interface iBxDolFactoryObject {
+interface iBxDolFactoryObject
+{
     static public function getObjectInstance($sObject);
 }
 
 /**
  * Replacable interface, class has an ability to replace markers somewhere
  */
-interface iBxDolReplaceable {
+interface iBxDolReplaceable
+{
     public function addMarkers ($a);
 }
 
 /**
  * Profile interface, class must implement basic profile methods to be compliant with Profile interface
  */
-interface iBxDolProfile {
+interface iBxDolProfile
+{
     public function id();
     public function getDisplayName();
     public function getUrl();
@@ -63,7 +68,8 @@ interface iBxDolProfile {
 /**
  * Profile services module interface, module class must implement basic profile services to be compliant with Profile interface
  */
-interface iBxDolProfileService {
+interface iBxDolProfileService
+{
     public function serviceProfileUnit ($iContentId);
     public function serviceProfileAvatar ($iContentId);
     public function serviceProfileThumb ($iContentId);
@@ -75,4 +81,3 @@ interface iBxDolProfileService {
 }
 
 /** @} */
-

+ 63 - 45
inc/classes/BxDolAccount.php

@@ -9,20 +9,21 @@
 
 bx_import('BxDolAccountQuery');
 
-class BxDolAccount extends BxDol {
-
+class BxDolAccount extends BxDol
+{
     protected $_iAccountID;
     protected $_oQuery;
 
     /**
      * Constructor
      */
-    protected function __construct ($iAccountId) {
+    protected function __construct ($iAccountId)
+    {
         $iAccountId = (int)$iAccountId;
         $sClass = get_class($this) . '_' . $iAccountId;
         if (isset($GLOBALS['bxDolClasses'][$sClass]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
-        
+
         parent::__construct();
 
         $this->_iAccountID = $iAccountId; // since constructor is protected $iAccountId is always valid
@@ -32,7 +33,8 @@ class BxDolAccount extends BxDol {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         $sClass = get_class($this) . '_' . $this->_iProfileID;
         if (isset($GLOBALS['bxDolClasses'][$sClass]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
@@ -41,8 +43,8 @@ class BxDolAccount extends BxDol {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance($mixedAccountId = false) {
-
+    public static function getInstance($mixedAccountId = false)
+    {
         if (!$mixedAccountId)
             $mixedAccountId = getLoggedId();
 
@@ -60,14 +62,16 @@ class BxDolAccount extends BxDol {
     /**
      * Get account id
      */
-    public function id() {
+    public function id()
+    {
         return $this->_oQuery->getIdById($this->_iAccountID);
     }
 
     /**
      * Check if account is confirmed, it is checked by email confirmation
      */
-    public function isConfirmed($iAccountId = false) {
+    public function isConfirmed($iAccountId = false)
+    {
         if (!getParam('sys_email_confirmation')) // if email_confirmation procedure is disabled, always return true
             return true;
         $a = $this->getInfo((int)$iAccountId);
@@ -76,11 +80,12 @@ class BxDolAccount extends BxDol {
 
     /**
      * Set account email to confirmed or unconfirmed
-     * @param int $isConfirmed - false: mark email as unconfirmed, true: as confirmed
-     * @param int $iAccountId - optional account id
+     * @param  int  $isConfirmed - false: mark email as unconfirmed, true: as confirmed
+     * @param  int  $iAccountId  - optional account id
      * @return true on success or false on error
      */
-    public function updateEmailConfirmed($isConfirmed, $isAutoSendConfrmationEmail = true, $iAccountId = false) {
+    public function updateEmailConfirmed($isConfirmed, $isAutoSendConfrmationEmail = true, $iAccountId = false)
+    {
         $iId = (int)$iAccountId ? (int)$iAccountId : $this->_iAccountID;
 
         if (!$isConfirmed && $isAutoSendConfrmationEmail && getParam('sys_email_confirmation')) // if email_confirmation procedure is enabled - send email confirmation letter
@@ -91,9 +96,10 @@ class BxDolAccount extends BxDol {
             return true;
         }
         return false;
-    }    
+    }
 
-    public function updateProfileContext($iSwitchToProfileId, $iAccountId = false) {
+    public function updateProfileContext($iSwitchToProfileId, $iAccountId = false)
+    {
         $iId = (int)$iAccountId ? (int)$iAccountId : $this->_iAccountID;
         $aInfo = $this->getInfo((int)$iId);
         if (!$aInfo)
@@ -115,7 +121,8 @@ class BxDolAccount extends BxDol {
     /**
      * Send "confirmation" email
      */
-    public function sendConfirmationEmail($iAccountId = false) {
+    public function sendConfirmationEmail($iAccountId = false)
+    {
         $sEmail = $this->getEmail($iAccountId);
 
         bx_import('BxDolKey');
@@ -139,14 +146,16 @@ class BxDolAccount extends BxDol {
     /**
      * Get account info
      */
-    public function getInfo($iAccountId = false) {
+    public function getInfo($iAccountId = false)
+    {
         return $this->_oQuery->getInfoById((int)$iAccountId ? (int)$iAccountId : $this->_iAccountID);
     }
 
     /**
      * Get account display name
      */
-    public function getDisplayName($iAccountId = false) {
+    public function getDisplayName($iAccountId = false)
+    {
         $aInfo = $this->getInfo($iAccountId);
         return $aInfo['name'];
     }
@@ -154,53 +163,60 @@ class BxDolAccount extends BxDol {
     /**
      * Get account url
      */
-    public function getUrl($iAccountId = false) {
+    public function getUrl($iAccountId = false)
+    {
         return 'javascript:void(0);';
     }
 
     /**
      * Get account url
      */
-    public function getUnit($iAccountId = false) {
+    public function getUnit($iAccountId = false)
+    {
         return '<div>' . $this->getDisplayName($iAccountId) . '</div>';
     }
 
     /**
      * Get avatar picture url
      */
-    public function getAvatar($iAccountId = false) {
+    public function getAvatar($iAccountId = false)
+    {
         return BxDolTemplate::getInstance()->getImageUrl('account-avatar.png');
     }
 
     /**
      * Get thumb picture url
      */
-    public function getThumb($iAccountId = false) {
+    public function getThumb($iAccountId = false)
+    {
         return BxDolTemplate::getInstance()->getImageUrl('account-thumb.png');
     }
 
     /**
      * Get icon picture url
      */
-    public function getIcon($iAccountId = false) {
+    public function getIcon($iAccountId = false)
+    {
         return BxDolTemplate::getInstance()->getImageUrl('account-icon.png');
     }
 
     /**
      * Get account email
      */
-    public function getEmail($iAccountId = false) {
+    public function getEmail($iAccountId = false)
+    {
         $iAccountId = (int)$iAccountId ? (int)$iAccountId : $this->_iAccountID;
         $aAccountInfo = $this->getInfo($iAccountId);
         return $aAccountInfo['email'];
     }
 
     /**
-     * Validate account. 
-     * @param $s - account identifier (id or email) 
+     * Validate account.
+     * @param $s - account identifier (id or email)
      * @return account id or false if account was not found
      */
-    static public function getID($s) {
+    static public function getID($s)
+    {
         $oQuery = BxDolAccountQuery::getInstance();
 
         if (preg_match("/^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$/i", $s)) {
@@ -215,8 +231,8 @@ class BxDolAccount extends BxDol {
     /**
      * Delete profile.
      */
-    function delete($iAccountId = false) {
-
+    function delete($iAccountId = false)
+    {
         $ID = (int)$iAccountId ? (int)$iAccountId : $this->_iAccountID;
 
         $aAccountInfo = $this->_oQuery->getInfoById($ID);
@@ -238,7 +254,7 @@ class BxDolAccount extends BxDol {
         foreach ($aProfiles as $iProfileId => $aRow) {
             $oProfile = BxDolProfile::getInstance($iProfileId);
             if (!$oProfile)
-                continue;            
+                continue;
             $oProfile->delete(false, true);
         }
 
@@ -252,7 +268,7 @@ class BxDolAccount extends BxDol {
         // unset class instance to prevent creating the instance again
         $this->_iAccountID = 0;
         $sClass = get_class($this) . '_' . $ID;
-        unset($GLOBALS['bxDolClasses'][$sClass]);        
+        unset($GLOBALS['bxDolClasses'][$sClass]);
 
         return true;
     }
@@ -260,7 +276,8 @@ class BxDolAccount extends BxDol {
     /**
      * Add permament messages.
      */
-    public function addInformerPermanentMessages ($oInformer) {
+    public function addInformerPermanentMessages ($oInformer)
+    {
         if (!$this->isConfirmed()) {
             bx_import('BxDolPermalinks');
             $sUrl = BxDolPermalinks::getInstance()->permalink('page.php?i=confirm-email') . '&resend=1';
@@ -272,8 +289,9 @@ class BxDolAccount extends BxDol {
     /**
      * Get unsubscribe link for the specified mesage type
      */
-    public function getUnsubscribeLink($iEmailType, $iAccountId = false) {
-        $iAccountId = (int)$iAccountId ? (int)$iAccountId : $this->_iAccountID; 
+    public function getUnsubscribeLink($iEmailType, $iAccountId = false)
+    {
+        $iAccountId = (int)$iAccountId ? (int)$iAccountId : $this->_iAccountID;
         bx_import('BxDolPermalinks');
         $sUrl = '';
         switch ($iEmailType) {
@@ -289,18 +307,18 @@ class BxDolAccount extends BxDol {
         return BxDolPermalinks::getInstance()->permalink($sUrl) . '&id=' . $iAccountId . '&code=' . $this->getEmailHash();
     }
 
-    public function getEmailHash($iAccountId = false) {
-        $iAccountId = (int)$iAccountId ? (int)$iAccountId : $this->_iAccountID; 
+    public function getEmailHash($iAccountId = false)
+    {
+        $iAccountId = (int)$iAccountId ? (int)$iAccountId : $this->_iAccountID;
         $a = $this->getInfo();
         return md5($a['email'] . $a['salt'] . BX_DOL_SECRET);
     }
 
-
-
     /**
-     * @return CHECK_ACTION_RESULT_ALLOWED if access is granted or error message if access is forbidden. 
+     * @return CHECK_ACTION_RESULT_ALLOWED if access is granted or error message if access is forbidden.
      */
-    static public function isAllowedCreate ($iProfileId, $isPerformAction = false) {
+    static public function isAllowedCreate ($iProfileId, $isPerformAction = false)
+    {
         $aCheck = checkActionModule($iProfileId, 'create account', 'system', $isPerformAction);
         if ($aCheck[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED)
             return MsgBox($aCheck[CHECK_ACTION_MESSAGE]);
@@ -308,10 +326,10 @@ class BxDolAccount extends BxDol {
     }
 
     /**
-     * @return CHECK_ACTION_RESULT_ALLOWED if access is granted or error message if access is forbidden. 
+     * @return CHECK_ACTION_RESULT_ALLOWED if access is granted or error message if access is forbidden.
      */
-    static public function isAllowedEdit ($iProfileId, $aContentInfo, $isPerformAction = false) {
-
+    static public function isAllowedEdit ($iProfileId, $aContentInfo, $isPerformAction = false)
+    {
         bx_import('BxDolProfile');
         $oProfile = BxDolProfile::getInstance($iProfileId);
         if (!$oProfile)
@@ -325,9 +343,10 @@ class BxDolAccount extends BxDol {
     }
 
     /**
-     * @return CHECK_ACTION_RESULT_ALLOWED if access is granted or error message if access is forbidden. 
+     * @return CHECK_ACTION_RESULT_ALLOWED if access is granted or error message if access is forbidden.
      */
-    static public function isAllowedDelete ($iProfileId, $aContentInfo, $isPerformAction = false) {
+    static public function isAllowedDelete ($iProfileId, $aContentInfo, $isPerformAction = false)
+    {
         $aCheck = checkActionModule($iProfileId, 'delete account', 'system', $isPerformAction);
         if ($aCheck[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED)
             return MsgBox($aCheck[CHECK_ACTION_MESSAGE]);
@@ -337,4 +356,3 @@ class BxDolAccount extends BxDol {
 }
 
 /** @} */
-

+ 56 - 41
inc/classes/BxDolAccountQuery.php

@@ -12,10 +12,10 @@ bx_import('BxDolDb');
 /**
  * All queries related to account
  */
-class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton {
-
-    public function __construct() {
-
+class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton
+{
+    public function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -25,7 +25,8 @@ class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -33,7 +34,8 @@ class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
+    public static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolAccountQuery();
 
@@ -44,53 +46,59 @@ class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton {
      * Get account by specified field name and value.
      * It is for internal usage only.
      * Use other funtions to get account info, like getInfoById, etc.
-     * @param string $sField database field name
-     * @param mixed $sValue database field value
-     * @return array with porfile info
+     * @param  string $sField database field name
+     * @param  mixed  $sValue database field value
+     * @return array  with porfile info
      */
-    protected function _getDataByField ($sField, $sValue) {
+    protected function _getDataByField ($sField, $sValue)
+    {
         $sSql = $this->prepare("SELECT * FROM `sys_accounts` WHERE `$sField` = ? LIMIT 1", $sValue);
         return $this->getRow($sSql);
     }
 
     /**
      * Get account info by id
-     * @param int $iID account id
+     * @param  int   $iID account id
      * @return array with account info
      */
-    public function getInfoById( $iID )    {
+    public function getInfoById( $iID )
+    {
         return $this->_getDataByField('id', (int)$iID);
     }
 
     /**
      * get account id by emial
      */
-    public function getIdByEmail($sEmail) {
+    public function getIdByEmail($sEmail)
+    {
         return (int)$this->_getFieldByField('id', 'email', $sEmail);
     }
 
     /**
      * get account id by id
      */
-    public function getIdById($iId) {
+    public function getIdById($iId)
+    {
         return (int)$this->_getFieldByField('id', 'id', $iId);
     }
 
     /**
      * Get account email by id
-     * @param string $s search account by this id
+     * @param  string  $s search account by this id
      * @return account email
      */
-    public function getEmail($iID) {
+    public function getEmail($iID)
+    {
         return $this->_getFieldByField('email', 'id', (int)$iID);
     }
 
     /**
      * Get account password by id
-     * @param string $s search account by this id
+     * @param  string  $s search account by this id
      * @return account password
      */
-    public function getPassword($iID) {
+    public function getPassword($iID)
+    {
         return $this->_getFieldByField('password', 'id', (int)$iID);
     }
 
@@ -101,46 +109,51 @@ class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton {
      * @param $iAccountId - account id to update password for
      * @return number of affected rows
      */
-    public function updatePassword($sPasswordHash, $sSalt, $iAccountId) {
+    public function updatePassword($sPasswordHash, $sSalt, $iAccountId)
+    {
         $sQuery = $this->prepare("UPDATE `sys_accounts` SET `password` = ?, `salt` = ? WHERE `id`= ?", $sPasswordHash, $sSalt, $iAccountId);
         return $this->query($sQuery);
     }
 
     /**
      * Update last logged in time
-     * @param int $iID account id
+     * @param  int    $iID account id
      * @return number of affected rows
      */
-    public function updateLoggedIn($iID) {
+    public function updateLoggedIn($iID)
+    {
         return $this->_updateField ($iID, 'logged', time());
     }
 
     /**
      * Update language
-     * @param int $iID account id
+     * @param  int    $iID account id
      * @return number of affected rows
      */
-    public function updateLanguage($iID, $iLangId) {
+    public function updateLanguage($iID, $iLangId)
+    {
         return $this->_updateField ($iID, 'lang_id', $iLangId);
     }
 
     /**
      * Update current profile id associated with account
-     * @param int $iID account id
-     * @param int $iProfileId set current profile id to this value
+     * @param  int    $iID        account id
+     * @param  int    $iProfileId set current profile id to this value
      * @return number of affected rows
      */
-    public function updateCurrentProfile($iID, $iProfileId) {
+    public function updateCurrentProfile($iID, $iProfileId)
+    {
         return $this->_updateField ($iID, 'profile_id', $iProfileId);
     }
 
     /**
      * Update 'email_confirmed' field.
-     * @param int $isConfirmed - 0: mark email as unconfirmed, 1: as confirmed
-     * @param int $iID - account id
+     * @param  int    $isConfirmed - 0: mark email as unconfirmed, 1: as confirmed
+     * @param  int    $iID         - account id
      * @return number of affected rows
      */
-    public function updateEmailConfirmed($isConfirmed, $iID) {
+    public function updateEmailConfirmed($isConfirmed, $iID)
+    {
         return $this->_updateField ($iID, 'email_confirmed', $isConfirmed ? 1 : 0);
     }
 
@@ -148,12 +161,13 @@ class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton {
      * Get account field by specified field name and value.
      * In most cases it is for internal usage only.
      * Use other funtions to get account info, like getIdByEmail, etc.
-     * @param string $sFieldRequested database field name to return
-     * @param string $sFieldSearch database field name to search for
-     * @param mixed $sValue database field value
+     * @param  string    $sFieldRequested database field name to return
+     * @param  string    $sFieldSearch    database field name to search for
+     * @param  mixed     $sValue          database field value
      * @return specified account field value
      */
-    protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue) {
+    protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue)
+    {
         $sSql = $this->prepare("SELECT `$sFieldRequested` FROM `sys_accounts` WHERE `$sFieldSearch` = ? LIMIT 1", $sValue);
         return $this->getOne($sSql);
     }
@@ -162,22 +176,24 @@ class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton {
      * Update some field by account id
      * In most cases it is for internal usage only.
      * Use other funtions to get account info, like updateLogged, etc.
-     * @param string $sFieldRequested database field name to return
-     * @param string $sFieldSearch database field name to search for
-     * @param mixed $sValue database field value
+     * @param  string    $sFieldRequested database field name to return
+     * @param  string    $sFieldSearch    database field name to search for
+     * @param  mixed     $sValue          database field value
      * @return specified account field value
      */
-    protected function _updateField ($iId, $sFieldForUpdate, $sValue) {
+    protected function _updateField ($iId, $sFieldForUpdate, $sValue)
+    {
         $sSql = $this->prepare("UPDATE `sys_accounts` SET `$sFieldForUpdate` = ? WHERE `id` = ? LIMIT 1", $sValue, $iId);
         return $this->query($sSql);
     }
 
     /**
      * Delete account info by id
-     * @param int $iID profile id
+     * @param  int      $iID profile id
      * @return affected rows
      */
-    public function delete($iID) {
+    public function delete($iID)
+    {
         $sSql = $this->prepare("DELETE FROM `sys_accounts` WHERE `id` = ? LIMIT 1", $iID);
         return $this->query($sSql);
     }
@@ -185,7 +201,7 @@ class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Search account profile by keyword
      */
-    public function searchByTerm($sTerm, $iLimit) 
+    public function searchByTerm($sTerm, $iLimit)
     {
         $aFieldsQuickSearch = array('name', 'email');
         $sWhere = '';
@@ -200,4 +216,3 @@ class BxDolAccountQuery extends BxDolDb implements iBxDolSingleton {
 }
 
 /** @} */
-

+ 283 - 271
inc/classes/BxDolAcl.php

@@ -12,7 +12,7 @@ bx_import('BxDolAclQuery');
 
 /**
  * Message constants passed to _t_ext() function by checkAction()
- * 
+ *
  * NOTE: checkAction() returns language dependent messages
  */
 define('CHECK_ACTION_MESSAGE_NOT_ALLOWED',			"_sys_acl_action_not_allowed");
@@ -65,8 +65,8 @@ define('CHECK_ACTION_RESULT_LIMIT_REACHED', 3);
 define('CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE', 4);
 define('CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER', 5);
 
-class BxDolAcl extends BxDol implements iBxDolSingleton {
-
+class BxDolAcl extends BxDol implements iBxDolSingleton
+{
     protected $oDb;
 
     protected $_aStandardMemberships = array(
@@ -77,7 +77,7 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
         MEMBERSHIP_ID_STANDARD => 1,
     );
 
-    protected $_aProfileStatus2LevelMap = array ( 
+    protected $_aProfileStatus2LevelMap = array (
         BX_PROFILE_STATUS_SUSPENDED => MEMBERSHIP_ID_SUSPENDED,
         BX_PROFILE_STATUS_PENDING => MEMBERSHIP_ID_PENDING,
     );
@@ -89,7 +89,8 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
         MEMBERSHIP_ID_SUSPENDED => '_sys_acl_action_suspended',
     );
 
-    protected function __construct() {
+    protected function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -101,7 +102,8 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -109,7 +111,8 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
+    public static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
             bx_import('BxTemplAcl');
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxTemplAcl();
@@ -124,7 +127,8 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
      * @param $iProfileId - profile to check, if it isn't provided or is false then currently logged in profile is used.
      * @return true if member has privided membership levels, or false if member hasn't.
      */
-    public function isMemberLevelInSet($iPermissions, $iProfileId = false) {
+    public function isMemberLevelInSet($iPermissions, $iProfileId = false)
+    {
         if (!$iPermissions)
             return false;
 
@@ -141,18 +145,18 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
         return ($iPermissions & pow(2, $aACL['id'] - 1));
     }
 
-	/**
+    /**
      * Checks if a given action is allowed for a given profile and updates action information if the
      * action is performed.
      *
-     * @param int $iProfileId ID of a profile that is going to perform an action
-     * @param int $iActionId ID of the action itself
-     * @param boolean $bPerformAction if true, then action information is updated, i.e. action is 'performed'
-     * @return array(	
-     * 				CHECK_ACTION_RESULT => CHECK_ACTION_RESULT_ constant,
-     * 				CHECK_ACTION_MESSAGE => CHECK_ACTION_MESSAGE_ constant,
-     * 				CHECK_ACTION_PARAMETER => additional action parameter (string)
-     * 			)
+     * @param  int     $iProfileId     ID of a profile that is going to perform an action
+     * @param  int     $iActionId      ID of the action itself
+     * @param  boolean $bPerformAction if true, then action information is updated, i.e. action is 'performed'
+     * @return array(
+     *                                CHECK_ACTION_RESULT => CHECK_ACTION_RESULT_ constant,
+     *                                CHECK_ACTION_MESSAGE => CHECK_ACTION_MESSAGE_ constant,
+     *                                CHECK_ACTION_PARAMETER => additional action parameter (string)
+     *                                )
      *
      * NOTES:
      *
@@ -189,188 +193,191 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
      * $aResult[CHECK_ACTION_PARAMETER] contains an additional parameter that can be considered
      * when performing the action (like the number of profiles to show in search result)
     */
-    function checkAction($iProfileId, $iActionId, $bPerformAction = false) {
-
-    	$aResult = array();
-    	$aLangFileParams = array();
-    
-    	$iProfileId = (int)$iProfileId;
-    	$iActionId = (int)$iActionId;
-    	$bPerformAction = $bPerformAction ? true : false;
-    
-    	$aMembership = $this->getMemberMembershipInfo($iProfileId); // get current profile's membership information
-    
-    	$aLangFileParams[CHECK_ACTION_LANG_FILE_MEMBERSHIP] = _t($aMembership['name']);
-    	$aLangFileParams[CHECK_ACTION_LANG_FILE_SITE_EMAIL] = getParam('site_email');
-
-    	$aAction = $this->oDb->getAction($aMembership['id'], $iActionId);
-    	if (!$aAction)
+    function checkAction($iProfileId, $iActionId, $bPerformAction = false)
+    {
+        $aResult = array();
+        $aLangFileParams = array();
+
+        $iProfileId = (int)$iProfileId;
+        $iActionId = (int)$iActionId;
+        $bPerformAction = $bPerformAction ? true : false;
+
+        $aMembership = $this->getMemberMembershipInfo($iProfileId); // get current profile's membership information
+
+        $aLangFileParams[CHECK_ACTION_LANG_FILE_MEMBERSHIP] = _t($aMembership['name']);
+        $aLangFileParams[CHECK_ACTION_LANG_FILE_SITE_EMAIL] = getParam('site_email');
+
+        $aAction = $this->oDb->getAction($aMembership['id'], $iActionId);
+        if (!$aAction)
             bx_trigger_error('Unknown action ID: ' . $iActionId, 2);
 
-    	$aResult[CHECK_ACTION_PARAMETER] = $aAction['additional_param_value'];
-    	$aLangFileParams[CHECK_ACTION_LANG_FILE_ACTION] = !empty($aAction['title']) ? _t($aAction['title']) : $aAction['name'];
+        $aResult[CHECK_ACTION_PARAMETER] = $aAction['additional_param_value'];
+        $aLangFileParams[CHECK_ACTION_LANG_FILE_ACTION] = !empty($aAction['title']) ? _t($aAction['title']) : $aAction['name'];
 
-    	/**
-    	 * Action is not allowed for the current membership
-    	 */
-    	if (is_null($aAction['id'])) {
+        /**
+         * Action is not allowed for the current membership
+         */
+        if (is_null($aAction['id'])) {
 
             $sLangKey = CHECK_ACTION_MESSAGE_NOT_ALLOWED;
             if (isset($this->_aLevel2MessageMap[$aMembership['id']]))
                 $sLangKey = $this->_aLevel2MessageMap[$aMembership['id']];
 
-    		$aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED;
-    		$aResult[CHECK_ACTION_MESSAGE] = _t_ext($sLangKey, $aLangFileParams);
-    		return $aResult;
-    	}
-
-    	/**
-    	 * Check fixed period limitations if present (also for non-members)
-    	 */
-    	if($aAction['allowed_period_start'] && time() < $aAction['allowed_period_start']) {
-    		$aLangFileParams[CHECK_ACTION_LANG_FILE_BEFORE] = bx_time_js($aAction['allowed_period_start'], BX_FORMAT_DATE_TIME);
-
-    		$aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE;
-    		$aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_BEFORE, $aLangFileParams);
-
-    		return $aResult;
-    	}
-
-    	if($aAction['allowed_period_end'] && time() > $aAction['allowed_period_end']) {
-    		$aLangFileParams[CHECK_ACTION_LANG_FILE_AFTER] = bx_time_js($aAction['allowed_period_end'], BX_FORMAT_DATE_TIME);
-
-    		$aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER;
-    		$aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_AFTER, $aLangFileParams);
-
-    		return $aResult;
-    	}
-
-    	/**
-    	 * if non-member, allow action without performing further checks
-    	 */
-    	if ($aMembership['id'] == MEMBERSHIP_ID_NON_MEMBER) {
-    		$aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
-    		return $aResult;
-    	}
-
-    	/**
-    	 * Check other limitations (for members only)
-    	 */
-    	$iAllowedCnt = (int)$aAction['allowed_count']; ///< Number of allowed actions. Unlimited if not specified or 0 
-    	$iPeriodLen = (int)$aAction['allowed_period_len']; ///< Period for AllowedCount in hours. If not specified, AllowedCount is treated as total number of actions permitted.
-
-    	if($iAllowedCnt > 0) {
-            $aActionTrack = $this->oDb->getActionTrack($iActionId, $iProfileId); 
-
-    		$iActionsLeft = $bPerformAction ? $iAllowedCnt - 1 : $iAllowedCnt;
-    		$iValidSince = time();
-
-    		/**
-    		 * Member is requesting/performing this action for the first time, 
-    		 * and there is no corresponding record in sys_acl_actions_track table.
-    		 */
-    		if(!$aActionTrack) {
+            $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED;
+            $aResult[CHECK_ACTION_MESSAGE] = _t_ext($sLangKey, $aLangFileParams);
+            return $aResult;
+        }
+
+        /**
+         * Check fixed period limitations if present (also for non-members)
+         */
+        if($aAction['allowed_period_start'] && time() < $aAction['allowed_period_start']) {
+            $aLangFileParams[CHECK_ACTION_LANG_FILE_BEFORE] = bx_time_js($aAction['allowed_period_start'], BX_FORMAT_DATE_TIME);
+
+            $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE;
+            $aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_BEFORE, $aLangFileParams);
+
+            return $aResult;
+        }
+
+        if($aAction['allowed_period_end'] && time() > $aAction['allowed_period_end']) {
+            $aLangFileParams[CHECK_ACTION_LANG_FILE_AFTER] = bx_time_js($aAction['allowed_period_end'], BX_FORMAT_DATE_TIME);
+
+            $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER;
+            $aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_AFTER, $aLangFileParams);
+
+            return $aResult;
+        }
+
+        /**
+         * if non-member, allow action without performing further checks
+         */
+        if ($aMembership['id'] == MEMBERSHIP_ID_NON_MEMBER) {
+            $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
+            return $aResult;
+        }
+
+        /**
+         * Check other limitations (for members only)
+         */
+        $iAllowedCnt = (int)$aAction['allowed_count']; ///< Number of allowed actions. Unlimited if not specified or 0
+        $iPeriodLen = (int)$aAction['allowed_period_len']; ///< Period for AllowedCount in hours. If not specified, AllowedCount is treated as total number of actions permitted.
+
+        if($iAllowedCnt > 0) {
+            $aActionTrack = $this->oDb->getActionTrack($iActionId, $iProfileId);
+
+            $iActionsLeft = $bPerformAction ? $iAllowedCnt - 1 : $iAllowedCnt;
+            $iValidSince = time();
+
+            /**
+             * Member is requesting/performing this action for the first time,
+             * and there is no corresponding record in sys_acl_actions_track table.
+             */
+            if(!$aActionTrack) {
                 $this->oDb->insertActionTarck($iActionId, $iProfileId, $iActionsLeft, $iValidSince);
 
-    			$aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
-    			return $aResult;
-    		}
-
-    		/**
-    		 * Action has been requested/performed at least once at this point and there is a corresponding record in sys_acl_actions_track table
-    		 * 
-    		 * Action record in sys_acl_actions_track table is out of date.
-    		 */
-    		$iPeriodEnd = (int)$aActionTrack['valid_since'] + $iPeriodLen * 3600; //ValidSince is in seconds, PeriodLen is in hours
-    		if($iPeriodLen > 0 && $iPeriodEnd < time()) {
+                $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
+                return $aResult;
+            }
+
+            /**
+             * Action has been requested/performed at least once at this point and there is a corresponding record in sys_acl_actions_track table
+             *
+             * Action record in sys_acl_actions_track table is out of date.
+             */
+            $iPeriodEnd = (int)$aActionTrack['valid_since'] + $iPeriodLen * 3600; //ValidSince is in seconds, PeriodLen is in hours
+            if($iPeriodLen > 0 && $iPeriodEnd < time()) {
                 $this->oDb->updateActionTrack($iActionId, $iProfileId, $iActionsLeft, $iValidSince);
-    
-    			$aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
-    			return $aResult;
-    		}
 
-    		$iActionsLeft = (int)$aActionTrack['actions_left']; ///< Action record is up to date
+                $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
+                return $aResult;
+            }
+
+            $iActionsLeft = (int)$aActionTrack['actions_left']; ///< Action record is up to date
 
             /**
              * Action limit reached for now
              */
-    		if($iActionsLeft <= 0){
-    			$aLangFileParams[CHECK_ACTION_LANG_FILE_LIMIT] = $iAllowedCnt;
-    			$aLangFileParams[CHECK_ACTION_LANG_FILE_PERIOD] = $iPeriodLen;
-    
-    			$aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_LIMIT_REACHED;
-    			$aResult[CHECK_ACTION_MESSAGE] = '<div style="width: 80%">' . _t_ext(CHECK_ACTION_MESSAGE_LIMIT_REACHED, $aLangFileParams) . ($iPeriodLen > 0 ? _t_ext(CHECK_ACTION_MESSAGE_MESSAGE_EVERY_PERIOD, $aLangFileParams) : '') . '.</div>';
-    
-    			return $aResult;
-    		}
-
-    		if($bPerformAction) {
-    			$iActionsLeft--;
-    			$this->oDb->updateActionTrack($iActionId, $iProfileId, $iActionsLeft);
-    		}
-    	}
-
-    	$aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
-    	return $aResult;
+            if($iActionsLeft <= 0){
+                $aLangFileParams[CHECK_ACTION_LANG_FILE_LIMIT] = $iAllowedCnt;
+                $aLangFileParams[CHECK_ACTION_LANG_FILE_PERIOD] = $iPeriodLen;
+
+                $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_LIMIT_REACHED;
+                $aResult[CHECK_ACTION_MESSAGE] = '<div style="width: 80%">' . _t_ext(CHECK_ACTION_MESSAGE_LIMIT_REACHED, $aLangFileParams) . ($iPeriodLen > 0 ? _t_ext(CHECK_ACTION_MESSAGE_MESSAGE_EVERY_PERIOD, $aLangFileParams) : '') . '.</div>';
+
+                return $aResult;
+            }
+
+            if($bPerformAction) {
+                $iActionsLeft--;
+                $this->oDb->updateActionTrack($iActionId, $iProfileId, $iActionsLeft);
+            }
+        }
+
+        $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED;
+        return $aResult;
     }
 
-	/**
+    /**
      * Get the list of existing memberships
      *
-     * @param bool $bPurchasableOnly	if true, fetches only purchasable memberships; 'purchasable' here means that:
-     * - MemLevels.Purchasable = 'yes'
-     * - MemLevels.Active = 'yes'
-     * - there is at least one pricing option for the membership
+     * @param  bool   $bPurchasableOnly if true, fetches only purchasable memberships; 'purchasable' here means that:
+     *                                  - MemLevels.Purchasable = 'yes'
+     *                                  - MemLevels.Active = 'yes'
+     *                                  - there is at least one pricing option for the membership
      * @return array( membershipID_1 => membershipName_1,  membershipID_2 => membershipName_2, ...) if no such memberships, then just array()
      */
-    function getMemberships($bPurchasableOnly = false, $bActiveOnly = false, $isTranslate = true) {
+    function getMemberships($bPurchasableOnly = false, $bActiveOnly = false, $isTranslate = true)
+    {
         $sType = 'all_pair';
         if($bPurchasableOnly)
             $sType = 'all_active_purchasble_pair';
         else if($bActiveOnly)
             $sType = 'all_active_pair';
 
-    	$aLevels = array();
-    	$this->oDb->getLevels(array('type' => $sType), $aLevels, false);
+        $aLevels = array();
+        $this->oDb->getLevels(array('type' => $sType), $aLevels, false);
         if ($isTranslate)
             foreach ($aLevels as $k => $s)
                 $aLevels[$k] = _t($s);
-    	return $aLevels;
+        return $aLevels;
     }
 
     /**
      * Get info about a given membership
      *
-     * @param int $iLevelId membership to get info about
+     * @param  int    $iLevelId membership to get info about
      * @return array(
-     * 				'id'					=>	ID, 
-     * 				'name'					=>	name,
-     * 				'icon'					=>	icon,
-     * 				'description'			=>	description, 
-     * 				'active'				=>	active, 
-     * 				'purchasable'			=>	purchasable, 
-     * 				'removable'				=>	removable
-     * 				'quota_size'			=>	quota size,
-     * 				'quota_number'			=>	quota number,
-     * 				'quota_max_file_size'	=>	quota max file size
-     * 			)
+     *                         'id'					=>	ID,
+     *                         'name'					=>	name,
+     *                         'icon'					=>	icon,
+     *                         'description'			=>	description,
+     *                         'active'				=>	active,
+     *                         'purchasable'			=>	purchasable,
+     *                         'removable'				=>	removable
+     *                         'quota_size'			=>	quota size,
+     *                         'quota_number'			=>	quota number,
+     *                         'quota_max_file_size'	=>	quota max file size
+     *                         )
      */
-    function getMembershipInfo($iLevelId) {
+    function getMembershipInfo($iLevelId)
+    {
         $aLevel = array();
-    	$this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false);
-    	return $aLevel;
+        $this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false);
+        return $aLevel;
     }
 
     /**
      * Get pricing options for the given membership
      *
-     * @param int $iLevelId membership to get prices for
+     * @param  int    $iLevelId membership to get prices for
      * @return array( days1 => price1, days2 => price2, ...) if no prices set, then just array()
      */
-    function getMembershipPrices($iLevelId) {
-    	$aPrice = array();
-    	$this->oDb->getPrices(array('type' => 'by_level_id_pair', 'value' => $iLevelId), $aPrice, false);
-    	return $aPrice;
+    function getMembershipPrices($iLevelId)
+    {
+        $aPrice = array();
+        $this->oDb->getPrices(array('type' => 'by_level_id_pair', 'value' => $iLevelId), $aPrice, false);
+        return $aPrice;
     }
 
     /**
@@ -391,93 +398,95 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
      * The Standard, Authenticated and Non-member memberships have their
      * DateStarts and DateExpires attributes set to NULL.
      *
-     * @param int $iProfileId ID of a profile to get info about
-     * @param int $time specifies the time to use when determining membership; if not specified, the function takes the current time
-     * @return array(	
-     * 				'id'			=> membership id,
-     * 				'name'			=> membership name,
-     * 				'date_starts'	=> (UNIX timestamp) date/time purchased,
-     * 				'date_expires'	=> (UNIX timestamp) date/time expires
-     * 			)
+     * @param  int    $iProfileId ID of a profile to get info about
+     * @param  int    $time       specifies the time to use when determining membership; if not specified, the function takes the current time
+     * @return array(
+     *                           'id'			=> membership id,
+     *                           'name'			=> membership name,
+     *                           'date_starts'	=> (UNIX timestamp) date/time purchased,
+     *                           'date_expires'	=> (UNIX timestamp) date/time expires
+     *                           )
      */
-    function getMemberMembershipInfo($iProfileId, $iTime = 0) {
-    	$aMembershipCurrent = $this->getMemberMembershipInfoCurrent($iProfileId, $iTime);
+    function getMemberMembershipInfo($iProfileId, $iTime = 0)
+    {
+        $aMembershipCurrent = $this->getMemberMembershipInfoCurrent($iProfileId, $iTime);
         if (isset($this->_aStandardMemberships[$aMembershipCurrent['id']]))
-    		return $aMembershipCurrent;
-    
-    	$aMembership = $aMembershipCurrent;
-    	do {
-    		$iDateStarts = $aMembership['date_starts'];
-    		$aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, ((int)$iDateStarts < 1 ? 0 : $iDateStarts - 1));
-    	}
-    	while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_starts']);
-
-    	$aMembership = $aMembershipCurrent;
-    	do {
-    		$iDateExpires = $aMembership['date_expires'];
-    		$aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, $iDateExpires);
-    	}
-    	while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_expires']);
-
-    	$aMembershipCurrent['date_starts'] = $iDateStarts;
-    	$aMembershipCurrent['date_expires'] = $iDateExpires;
-
-    	return $aMembershipCurrent;
+            return $aMembershipCurrent;
+
+        $aMembership = $aMembershipCurrent;
+        do {
+            $iDateStarts = $aMembership['date_starts'];
+            $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, ((int)$iDateStarts < 1 ? 0 : $iDateStarts - 1));
+        }
+        while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_starts']);
+
+        $aMembership = $aMembershipCurrent;
+        do {
+            $iDateExpires = $aMembership['date_expires'];
+            $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, $iDateExpires);
+        } while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_expires']);
+
+        $aMembershipCurrent['date_starts'] = $iDateStarts;
+        $aMembershipCurrent['date_expires'] = $iDateExpires;
+
+        return $aMembershipCurrent;
     }
 
     /**
      * Buy a membership for a profile
      *
-     * @param int $iProfileId profile that is going to get the membership
-     * @param int $iMembershipId bought membership
-     * @param int $sTransactionId internal key of the transaction (ID from Transactions table)
-     * @param boolean $bStartsNow if true, the membership will start immediately; if false, the membership will start after the current membership expires
+     * @param  int     $iProfileId     profile that is going to get the membership
+     * @param  int     $iMembershipId  bought membership
+     * @param  int     $sTransactionId internal key of the transaction (ID from Transactions table)
+     * @param  boolean $bStartsNow     if true, the membership will start immediately; if false, the membership will start after the current membership expires
      * @return boolean true in case of success, false in case of failure
      */
-    function buyMembership($iProfileId, $iPriceId, $sTransactionId, $bStartsNow = false) {
+    function buyMembership($iProfileId, $iPriceId, $sTransactionId, $bStartsNow = false)
+    {
         $aPrice = array();
         $this->oDb->getPrices(array('type' => 'by_id', 'value' => (int)$iPriceId), $aPrice, false);
-    	if(!is_array($aPrice) || empty($aPrice))
+        if(!is_array($aPrice) || empty($aPrice))
             return false;
 
         $aLevel = array();
-        $this->oDb->getLevels(array('type' => 'by_id', 'value' => $aPrice['level_id']), $aLevel, false); 
+        $this->oDb->getLevels(array('type' => 'by_id', 'value' => $aPrice['level_id']), $aLevel, false);
         if(!is_array($aLevel) || empty($aLevel))
             return false;
 
-    	$iLevelId = (int)$aLevel['id'];        
+        $iLevelId = (int)$aLevel['id'];
         if (isset($this->_aStandardMemberships[$iLevelId])) // check for predefined non-purchasable memberships
             return false;
 
-    	if($aLevel['active'] != 'yes' || $aLevel['purchasable'] != 'yes') // check if membership is active and purchasable 
+        if($aLevel['active'] != 'yes' || $aLevel['purchasable'] != 'yes') // check if membership is active and purchasable
             return false;
 
-    	return $this->setMembership((int)$iProfileId, $iLevelId, $aPrice['days'], $bStartsNow, $sTransactionId);
+        return $this->setMembership((int)$iProfileId, $iLevelId, $aPrice['days'], $bStartsNow, $sTransactionId);
     }
 
     /**
      * Set a membership for a profile
      *
-     * @param int $iProfileId profile that is going to get the membership
-     * @param int $iLevelId membership that is going to be assigned to the profile
-     * if $iLevelId == MEMBERSHIP_ID_STANDARD then $days and $bStartsNow parameters are not used, 
-     * so Standard membership is always set immediately and `forever`
-     * @param int $iDays number of days to set membership for if 0, then the membership is set forever
-     * @param boolean $bStartsNow if true, the membership will start immediately if false, the membership will start after the current membership expires
+     * @param  int     $iProfileId profile that is going to get the membership
+     * @param  int     $iLevelId   membership that is going to be assigned to the profile
+     *                             if $iLevelId == MEMBERSHIP_ID_STANDARD then $days and $bStartsNow parameters are not used,
+     *                             so Standard membership is always set immediately and `forever`
+     * @param  int     $iDays      number of days to set membership for if 0, then the membership is set forever
+     * @param  boolean $bStartsNow if true, the membership will start immediately if false, the membership will start after the current membership expires
      * @return boolean true in case of success, false in case of failure
      */
-    function setMembership($iProfileId, $iLevelId, $iDays = 0, $bStartsNow = false, $sTransactionId = '') {    
-    	$iProfileId = (int)$iProfileId;
-    	$iLevelId = (int)$iLevelId;
-    	$iDays = (int)$iDays;
-    	$bStartsNow = $bStartsNow ? true : false;
+    function setMembership($iProfileId, $iLevelId, $iDays = 0, $bStartsNow = false, $sTransactionId = '')
+    {
+        $iProfileId = (int)$iProfileId;
+        $iLevelId = (int)$iLevelId;
+        $iDays = (int)$iDays;
+        $bStartsNow = $bStartsNow ? true : false;
 
-    	$iSecInDay = 86400;
+        $iSecInDay = 86400;
 
-    	if (!$iProfileId)
-    		$iProfileId = -1;
+        if (!$iProfileId)
+            $iProfileId = -1;
 
-    	if (empty($sTransactionId)) 
+        if (empty($sTransactionId))
             $sTransactionId = 'NULL';
 
         // check if profile exists
@@ -485,58 +494,57 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
         if(($sProfileEmail = BxDolProfileQuery::getInstance()->getEmailById($iProfileId)) === false)
             return false;
 
-    	// check if membership exists
-    	$aLevel = array();
-    	$this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false);
-    	if(empty($aLevel) || !is_array($aLevel))
-    	    return false;            
+        // check if membership exists
+        $aLevel = array();
+        $this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false);
+        if(empty($aLevel) || !is_array($aLevel))
+            return false;
 
-    	if($iLevelId == MEMBERSHIP_ID_NON_MEMBER) 
+        if($iLevelId == MEMBERSHIP_ID_NON_MEMBER)
             return false;
 
-    	$aMembershipCurrent = $this->getMemberMembershipInfo($iProfileId);
-    	$aMembershipLatest = $this->getMemberMembershipInfoLatest($iProfileId);
+        $aMembershipCurrent = $this->getMemberMembershipInfo($iProfileId);
+        $aMembershipLatest = $this->getMemberMembershipInfoLatest($iProfileId);
 
-    	// setting Standard membership level 
-    	if ($iLevelId == MEMBERSHIP_ID_STANDARD) {
-    		if ($aMembershipCurrent['id'] == MEMBERSHIP_ID_STANDARD) 
+        // setting Standard membership level
+        if ($iLevelId == MEMBERSHIP_ID_STANDARD) {
+            if ($aMembershipCurrent['id'] == MEMBERSHIP_ID_STANDARD)
                 return true;
 
-    		// delete present and future memberships
-    		return $this->oDb->deleteLevelByProfileId($iProfileId);
-    	}
+            // delete present and future memberships
+            return $this->oDb->deleteLevelByProfileId($iProfileId);
+        }
 
-    	if ($iDays < 0) 
+        if ($iDays < 0)
             return false;
 
-    	$iDateStarts = time();
-    	if (!$bStartsNow) {
-    		// make the membership starts after the latest membership expires or return false if latest membership isn't Standard and is lifetime membership.
-    		if(!is_null($aMembershipLatest['date_expires']))
+        $iDateStarts = time();
+        if (!$bStartsNow) {
+            // make the membership starts after the latest membership expires or return false if latest membership isn't Standard and is lifetime membership.
+            if(!is_null($aMembershipLatest['date_expires']))
                 $iDateStarts = $aMembershipLatest['date_expires'];
-    		else if(is_null($aMembershipLatest['date_expires']) && $aMembershipLatest['id'] != MEMBERSHIP_ID_STANDARD)
+            else if(is_null($aMembershipLatest['date_expires']) && $aMembershipLatest['id'] != MEMBERSHIP_ID_STANDARD)
                 return false;
-    	}
-    	else
-    	    $this->oDb->deleteLevelByProfileId($iProfileId, true); ///< Delete any profile's membership level
+        } else
+            $this->oDb->deleteLevelByProfileId($iProfileId, true); ///< Delete any profile's membership level
 
         // set lifetime membership if 0 days is used.
         $iDateExpires = $iDays != 0 ? (int)$iDateStarts + $iDays * $iSecInDay : null;
-    	if(!$this->oDb->insertLevelByProfileId($iProfileId, $iLevelId, $iDateStarts, $iDateExpires, $sTransactionId))
-    	   return false;
-
-    	// raise membership alert
-    	bx_import('BxDolAlerts');
-    	$oZ = new BxDolAlerts('profile', 'set_membership', '', $iProfileId, array('mlevel'=> $iLevelId, 'days' => $iDays, 'starts_now' => $bStartsNow, 'txn_id' => $sTransactionId));
-    	$oZ->alert();
-    	
-    	// Send notification
-    	bx_import('BxDolEmailTemplates');
+        if(!$this->oDb->insertLevelByProfileId($iProfileId, $iLevelId, $iDateStarts, $iDateExpires, $sTransactionId))
+           return false;
+
+        // raise membership alert
+        bx_import('BxDolAlerts');
+        $oZ = new BxDolAlerts('profile', 'set_membership', '', $iProfileId, array('mlevel'=> $iLevelId, 'days' => $iDays, 'starts_now' => $bStartsNow, 'txn_id' => $sTransactionId));
+        $oZ->alert();
+
+        // Send notification
+        bx_import('BxDolEmailTemplates');
         $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_MemChanged', array('membership_level' => _t($aLevel['name'])), 0, $iProfileId);
         if ($aTemplate)
             sendMail($sProfileEmail, $aTemplate['Subject'], $aTemplate['Body']);
 
-    	return true;
+        return true;
     }
 
     /**
@@ -545,8 +553,8 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
      *
      * @param $aActions array of actions from sys_acl_actions table, with default array keys (starting from 0) and text values
      */
-    function defineMembershipActions($mixedActions, $sPrefix = 'BX_') {
-
+    function defineMembershipActions($mixedActions, $sPrefix = 'BX_')
+    {
         if (is_array($mixedActions))
             $aActions = $mixedActions;
         else
@@ -564,7 +572,7 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
         $this->oDb->getActions(array('type' => 'by_names', 'value' => $aNames), $aActions, false);
         foreach($aActions as $aAction)
             define($sPrefix . strtoupper(str_replace(' ', '_', $aAction['name'])), $aAction['id']);
-    }		
+    }
 
     /**
      * get action id by module and name
@@ -572,16 +580,17 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
      * @param $sModule module name
      * @param $aActions array of actions from sys_acl_actions table, with default array keys (starting from 0) and text values
      */
-    function getMembershipActionId($sAction, $sModule) {
-
+    function getMembershipActionId($sAction, $sModule)
+    {
         $this->oDb->getActions(array('type' => 'by_names_and_module', 'value' => $sAction, 'module' => $sModule), $aActions, false);
         if (count($aActions) > 1)
-            trigger_error('Duplicate action - name:' . $sAction . ', module:' . $sModule, E_USER_ERROR);        
+            trigger_error('Duplicate action - name:' . $sAction . ', module:' . $sModule, E_USER_ERROR);
         $aAction = array_pop($aActions);
         return $aAction['id'];
-    }		
+    }
 
-    function getExpirationLetter($iProfileId, $sLevelName, $iLevelExpireDays ) {
+    function getExpirationLetter($iProfileId, $sLevelName, $iLevelExpireDays )
+    {
         $iProfileId = (int)$iProfileId;
 
         if(!$iProfileId)
@@ -593,7 +602,7 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
 
         $aPlus = array(
             'membership_name' => $sLevelName,
-        	'expire_days' => $iLevelExpireDays
+            'expire_days' => $iLevelExpireDays
         );
 
         bx_import('BxDolEmailTemplates');
@@ -606,13 +615,14 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
     /**
      * clear expired membership levels
      */
-    public function maintenance () {
+    public function maintenance ()
+    {
         $iDaysToCleanMemLevels = (int) getParam("db_clean_mem_levels");
         return $this->oDb->maintenance ($iDaysToCleanMemLevels);
     }
 
-    protected function getMemberMembershipInfoCurrent($iProfileId, $iTime = 0) {
-
+    protected function getMemberMembershipInfoCurrent($iProfileId, $iTime = 0)
+    {
         $aMemLevel = false;
 
         // get profile status
@@ -621,14 +631,14 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
         $aProfileInfo = $oProfile ? $oProfile->getInfo() : false;
         $sProfileStatus = $aProfileInfo ? $aProfileInfo['status'] : false;
 
-    	// profile is not active, so return standard memberships according to profile status
+        // profile is not active, so return standard memberships according to profile status
         if (BX_PROFILE_STATUS_ACTIVE != $sProfileStatus) {
-        
+
             bx_import('BxDolAccount');
-            $oAccount = $aProfileInfo ? BxDolAccount::getInstance($aProfileInfo['account_id']) : false;            
-            if ($oAccount && !$oAccount->isConfirmed()) 
+            $oAccount = $aProfileInfo ? BxDolAccount::getInstance($aProfileInfo['account_id']) : false;
+            if ($oAccount && !$oAccount->isConfirmed())
                 $iLevelId = MEMBERSHIP_ID_UNCONFIRMED; // every account's profile is unconfirmed if account is unconfirmed
-            elseif (!isset($this->_aProfileStatus2LevelMap[$sProfileStatus])) 
+            elseif (!isset($this->_aProfileStatus2LevelMap[$sProfileStatus]))
                 $iLevelId = MEMBERSHIP_ID_NON_MEMBER; // if there is no profile status - then it isn't member
             else
                 $iLevelId = $this->_aProfileStatus2LevelMap[$sProfileStatus]; // get member level id which associated with every non-active status
@@ -640,24 +650,24 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
 
             return $aMemLevel;
 
-        } 
+        }
 
         // profile is active get memebr level from profile
-    	$aMemLevel = $this->oDb->getLevelCurrent((int)$iProfileId, $iTime);
+        $aMemLevel = $this->oDb->getLevelCurrent((int)$iProfileId, $iTime);
 
-    
-        // There are no purchased/assigned memberships for the profile or all of them have expired. 
+        // There are no purchased/assigned memberships for the profile or all of them have expired.
         // In this case the profile is assumed to have Standard membership.
-    	if (!$aMemLevel || is_null($aMemLevel['id'])) {
+        if (!$aMemLevel || is_null($aMemLevel['id'])) {
             $aMemLevel = $this->oDb->getLevelByIdCached(MEMBERSHIP_ID_STANDARD);
             if (!$aMemLevel)
                 trigger_error ('Standard member level is missing: ' . MEMBERSHIP_ID_NON_MEMBER, E_USER_ERROR);
-    	}
+        }
 
-    	return $aMemLevel;
+        return $aMemLevel;
     }
 
-    protected function getMemberMembershipInfoLatest($iProfileId, $iTime = 0) {
+    protected function getMemberMembershipInfoLatest($iProfileId, $iTime = 0)
+    {
         $aMembershipCurrent = $this->getMemberMembershipInfoCurrent($iProfileId, $iTime);
         if (isset($this->_aStandardMemberships[$aMembershipCurrent['id']]))
             return $aMembershipCurrent;
@@ -674,17 +684,19 @@ class BxDolAcl extends BxDol implements iBxDolSingleton {
         return $aMembershipLast;
     }
 
-    public function onProfileDelete ($iProfileId) {
+    public function onProfileDelete ($iProfileId)
+    {
         return $this->oDb->deleteLevelByProfileId($iProfileId, true);
     }
 }
 
-function checkAction($iProfileId, $iActionId, $bPerformAction = false) {
+function checkAction($iProfileId, $iActionId, $bPerformAction = false)
+{
     return BxDolAcl::getInstance()->checkAction($iProfileId, $iActionId, $bPerformAction);
 }
 
-function checkActionModule($iProfileId, $sActionName, $sModuleName, $bPerformAction = false) {
-
+function checkActionModule($iProfileId, $sActionName, $sModuleName, $bPerformAction = false)
+{
     $oACL = BxDolAcl::getInstance();
 
     $iActionId = $oACL->getMembershipActionId($sActionName, $sModuleName);

+ 69 - 54
inc/classes/BxDolAclQuery.php

@@ -13,8 +13,10 @@ bx_import('BxDolDb');
  * Database queries for ACL
  * @see BxDolAcl
  */
-class BxDolAclQuery extends BxDolDb implements iBxDolSingleton {
-    function __construct() {
+class BxDolAclQuery extends BxDolDb implements iBxDolSingleton
+{
+    function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -24,7 +26,8 @@ class BxDolAclQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -32,14 +35,16 @@ class BxDolAclQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    static function getInstance() {
+    static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolAclQuery();
 
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    function getLevels($aParams, &$aItems, $bReturnCount = true) {
+    function getLevels($aParams, &$aItems, $bReturnCount = true)
+    {
         $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
         $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
 
@@ -66,7 +71,7 @@ class BxDolAclQuery extends BxDolDb implements iBxDolSingleton {
                 $aMethod['params'][1] = 'id';
                 $aMethod['params'][2] = 'name';
                 $sWhereClause .= "AND `tal`.`Active`='yes'";
-                break;    
+                break;
             case 'all_pair':
                 $aMethod['name'] = "getPairs";
                 $aMethod['params'][1] = 'id';
@@ -101,7 +106,8 @@ class BxDolAclQuery extends BxDolDb implements iBxDolSingleton {
         return (int)$this->getOne("SELECT FOUND_ROWS()");
     }
 
-    function getActions($aParams, &$aItems, $bReturnCount = true) {
+    function getActions($aParams, &$aItems, $bReturnCount = true)
+    {
         $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
         $sSelectClause = $sJoinClause = $sWhereClause = $sGroupClause = $sOrderClause = $sLimitClause = "";
 
@@ -162,13 +168,14 @@ class BxDolAclQuery extends BxDolDb implements iBxDolSingleton {
     }
 
     /**
-	 * Fetch the last purchased/assigned membership that is still active for the given profile.
-	 * 
-	 * NOTE. Don't use cache here, because it's causing an error, if a number of memberrship levels are purchased at the same time.
-	 * 
-	 * fromMemory returns the same DateExpires because buyMembership function is called in cycle in the same session.
-	 */
-    function getLevelCurrent($iProfileId, $iTime = 0) {
+     * Fetch the last purchased/assigned membership that is still active for the given profile.
+     *
+     * NOTE. Don't use cache here, because it's causing an error, if a number of memberrship levels are purchased at the same time.
+     *
+     * fromMemory returns the same DateExpires because buyMembership function is called in cycle in the same session.
+     */
+    function getLevelCurrent($iProfileId, $iTime = 0)
+    {
         $iTime = $iTime == 0 ? time() : (int)$iTime;
 
         $sSql = $this->prepare("
@@ -182,61 +189,66 @@ class BxDolAclQuery extends BxDolDb implements iBxDolSingleton {
                     `sys_acl_levels_members`.`TransactionID` AS `transaction_id`,
                     `sys_profiles`.`status`
             FROM `sys_acl_levels_members`
-			RIGHT JOIN `sys_profiles` ON `sys_acl_levels_members`.IDMember = `sys_profiles`.`id` 
-				AND (`sys_acl_levels_members`.DateStarts IS NULL OR `sys_acl_levels_members`.DateStarts <= FROM_UNIXTIME(?))
-				AND (`sys_acl_levels_members`.DateExpires IS NULL OR `sys_acl_levels_members`.DateExpires > FROM_UNIXTIME(?))
-			LEFT JOIN `sys_acl_levels` ON `sys_acl_levels_members`.IDLevel = `sys_acl_levels`.ID
+            RIGHT JOIN `sys_profiles` ON `sys_acl_levels_members`.IDMember = `sys_profiles`.`id`
+                AND (`sys_acl_levels_members`.DateStarts IS NULL OR `sys_acl_levels_members`.DateStarts <= FROM_UNIXTIME(?))
+                AND (`sys_acl_levels_members`.DateExpires IS NULL OR `sys_acl_levels_members`.DateExpires > FROM_UNIXTIME(?))
+            LEFT JOIN `sys_acl_levels` ON `sys_acl_levels_members`.IDLevel = `sys_acl_levels`.ID
             WHERE `sys_profiles`.`id` = ?
             ORDER BY `sys_acl_levels_members`.DateStarts DESC
             LIMIT 1", $iTime, $iTime, $iProfileId);
 
-    	return $this->getRow($sSql);
+        return $this->getRow($sSql);
     }
 
-    function getLevelByIdCached($iLevel) {
-        $sQuery = $this->prepare("SELECT 
-            	`tal`.`ID` AS `id`, 
-            	`tal`.`Name` AS `name`, 
-            	`tal`.`QuotaSize` AS `quota_size`, 
-            	`tal`.`QuotaNumber` AS `quota_number`, 
-            	`tal`.`QuotaMaxFileSize` AS `quota_max_file_size` 
-        	FROM `sys_acl_levels` AS `tal`
-        	WHERE `tal`.`ID`=? 
-        	LIMIT 1", $iLevel);
+    function getLevelByIdCached($iLevel)
+    {
+        $sQuery = $this->prepare("SELECT
+                `tal`.`ID` AS `id`,
+                `tal`.`Name` AS `name`,
+                `tal`.`QuotaSize` AS `quota_size`,
+                `tal`.`QuotaNumber` AS `quota_number`,
+                `tal`.`QuotaMaxFileSize` AS `quota_max_file_size`
+            FROM `sys_acl_levels` AS `tal`
+            WHERE `tal`.`ID`=?
+            LIMIT 1", $iLevel);
         return $this->fromCache('sys_acl_levels' . $iLevel, 'getRow', $sQuery);
     }
 
-    function getAction($iMembershipId, $iActionId) {
+    function getAction($iMembershipId, $iActionId)
+    {
         $sQuery = $this->prepare("SELECT
-        		`tam`.`IDAction` AS `id`, 
-            	`taa`.`Name` AS `name`,  
+                `tam`.`IDAction` AS `id`,
+                `taa`.`Name` AS `name`,
                 `taa`.`Title` AS `title`,
-            	`tam`.`AllowedCount` AS `allowed_count`, 
-            	`tam`.`AllowedPeriodLen` AS `allowed_period_len`, 
-            	UNIX_TIMESTAMP(`tam`.`AllowedPeriodStart`) as `allowed_period_start`, 
-            	UNIX_TIMESTAMP(`tam`.`AllowedPeriodEnd`) as `allowed_period_end`, 
-            	`tam`.`AdditionalParamValue` AS `additional_param_value` 
-        	FROM `sys_acl_actions` AS `taa`
-        	LEFT JOIN `sys_acl_matrix` AS `tam` ON `tam`.`IDAction` = `taa`.`ID` AND `tam`.`IDLevel` = ?
-        	WHERE `taa`.`ID` = ?", $iMembershipId, $iActionId);
-    	return $this->getRow($sQuery);
+                `tam`.`AllowedCount` AS `allowed_count`,
+                `tam`.`AllowedPeriodLen` AS `allowed_period_len`,
+                UNIX_TIMESTAMP(`tam`.`AllowedPeriodStart`) as `allowed_period_start`,
+                UNIX_TIMESTAMP(`tam`.`AllowedPeriodEnd`) as `allowed_period_end`,
+                `tam`.`AdditionalParamValue` AS `additional_param_value`
+            FROM `sys_acl_actions` AS `taa`
+            LEFT JOIN `sys_acl_matrix` AS `tam` ON `tam`.`IDAction` = `taa`.`ID` AND `tam`.`IDLevel` = ?
+            WHERE `taa`.`ID` = ?", $iMembershipId, $iActionId);
+        return $this->getRow($sQuery);
     }
 
-    function getActionTrack($iActionId, $iProfileId) {
-        $sQuery = $this->prepare("SELECT 
-        		`taat`.`ActionsLeft` AS `actions_left`,
-        		UNIX_TIMESTAMP(`taat`.`ValidSince`) as `valid_since`
-        	FROM `sys_acl_actions_track` AS `taat`
-        	WHERE `taat`.`IDAction`=? AND `taat`.`IDMember`=?", $iActionId, $iProfileId);
-        return $this->getRow($sQuery); 
+    function getActionTrack($iActionId, $iProfileId)
+    {
+        $sQuery = $this->prepare("SELECT
+                `taat`.`ActionsLeft` AS `actions_left`,
+                UNIX_TIMESTAMP(`taat`.`ValidSince`) as `valid_since`
+            FROM `sys_acl_actions_track` AS `taat`
+            WHERE `taat`.`IDAction`=? AND `taat`.`IDMember`=?", $iActionId, $iProfileId);
+        return $this->getRow($sQuery);
     }
 
-    function insertActionTarck($iActionId, $iProfileId, $iActionsLeft, $iValidSince) {
+    function insertActionTarck($iActionId, $iProfileId, $iActionsLeft, $iValidSince)
+    {
         $sQuery = $this->prepare("INSERT INTO `sys_acl_actions_track`(`IDAction`, `IDMember`, `ActionsLeft`, `ValidSince`) VALUES (?, ?, ?, FROM_UNIXTIME(?))", $iActionId, $iProfileId, $iActionsLeft, $iValidSince);
         return (int)$this->query($sQuery) > 0;
     }
 
-    function updateActionTrack($iActionId, $iProfileId, $iActionsLeft, $iValidSince = 0) {
+    function updateActionTrack($iActionId, $iProfileId, $iActionsLeft, $iValidSince = 0)
+    {
         $sUpdateAddon = "";
         if($iValidSince != 0)
             $sUpdateAddon = $this->prepare(", ValidSince=FROM_UNIXTIME(?)", $iValidSince);
@@ -245,17 +257,20 @@ class BxDolAclQuery extends BxDolDb implements iBxDolSingleton {
         return (int)$this->query($sQuery) > 0;
     }
 
-    function insertLevelByProfileId($iProfileId, $iMembershipId, $iDateStarts, $iDateExpires, $sTransactionId) {
+    function insertLevelByProfileId($iProfileId, $iMembershipId, $iDateStarts, $iDateExpires, $sTransactionId)
+    {
         $sQuery = $this->prepare("INSERT `sys_acl_levels_members` (`IDMember`, `IDLevel`, `DateStarts`, `DateExpires`, `TransactionID`) VALUES (?, ?, FROM_UNIXTIME(?), FROM_UNIXTIME(?), ?)", $iProfileId, $iMembershipId, $iDateStarts, $iDateExpires, $sTransactionId);
-    	return (int)$this->query($sQuery) > 0;
+        return (int)$this->query($sQuery) > 0;
     }
 
-    function deleteLevelByProfileId($iProfileId, $bAll = false) {
+    function deleteLevelByProfileId($iProfileId, $bAll = false)
+    {
         $sQuery = $this->prepare("DELETE FROM `sys_acl_levels_members` WHERE `IDMember` = ? " . ($bAll ? "" : " AND (`DateExpires` IS NULL OR `DateExpires` > NOW())"), $iProfileId);
         return (int)$this->query($sQuery) > 0;
     }
 
-    function maintenance($iDaysToCleanMemLevels) {
+    function maintenance($iDaysToCleanMemLevels)
+    {
         $sQuery = $this->prepare("DELETE FROM `sys_acl_levels_members` WHERE `DateExpires` < NOW() - INTERVAL ? DAY", $iDaysToCleanMemLevels);
         if ($iDeleteMemLevels = $this->query($sQuery))
             $this->query("OPTIMIZE TABLE `sys_acl_levels_members`");

+ 22 - 21
inc/classes/BxDolAlerts.php

@@ -37,8 +37,8 @@ defined('BX_DOL') or die('hack attempt');
  * no alerts available
  *
  */
-class BxDolAlerts extends BxDol {
-
+class BxDolAlerts extends BxDol
+{
     public $sUnit;
     public $sAction;
     public $iObject;
@@ -50,12 +50,13 @@ class BxDolAlerts extends BxDol {
 
     /**
      * Constructor
-     * @param string $sType - system type
-     * @param string $sAction - system action
-     * @param int $iObjectId - object id
-     * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
+     * @param string $sType     - system type
+     * @param string $sAction   - system action
+     * @param int    $iObjectId - object id
+     * @param int    $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
      */
-    public function __construct($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array()) {
+    public function __construct($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
+    {
         parent::__construct();
 
         if (getParam('sys_db_cache_enable')) {
@@ -80,7 +81,7 @@ class BxDolAlerts extends BxDol {
 
         $this->sUnit = $sUnit;
         $this->sAction = $sAction;
-        $this->iObject = (int)$iObjectId;        
+        $this->iObject = (int)$iObjectId;
         $this->aExtras = $aExtras;
         if (false === $iSender) {
             bx_import('BxDolProfile');
@@ -91,15 +92,16 @@ class BxDolAlerts extends BxDol {
         }
     }
 
-    public static function cacheInvalidate() {
+    public static function cacheInvalidate()
+    {
         return BxDolDb::getInstance()->cleanCache ('sys_alerts');
     }
 
     /**
      * Notifies the necessary handlers about the alert.
      */
-    public function alert() {
-
+    public function alert()
+    {
         if (isset($this->_aAlerts[$this->sUnit]) && isset($this->_aAlerts[$this->sUnit][$this->sAction]))
             foreach($this->_aAlerts[$this->sUnit][$this->sAction] as $iHandlerId) {
                 $aHandler = $this->_aHandlers[$iHandlerId];
@@ -110,15 +112,14 @@ class BxDolAlerts extends BxDol {
 
                     $oHandler = new $aHandler['class']();
                     $oHandler->response($this);
-                } 
-                else if(!empty($aHandler['service_call']) && BxDolService::isSerializedService($aHandler['service_call'])) {
-                	$aService = unserialize($aHandler['service_call']);
+                } else if(!empty($aHandler['service_call']) && BxDolService::isSerializedService($aHandler['service_call'])) {
+                    $aService = unserialize($aHandler['service_call']);
 
-                	$aParams = array($this);
-                	if(isset($aService['params']) && is_array($aService['params']))
-                		$aParams = array_merge($aParams, $aService['params']);
+                    $aParams = array($this);
+                    if(isset($aService['params']) && is_array($aService['params']))
+                        $aParams = array_merge($aParams, $aService['params']);
 
-					BxDolService::call($aService['module'], $aService['method'], $aParams, isset($aService['class']) ? $aService['class'] : 'Module');
+                    BxDolService::call($aService['module'], $aService['method'], $aParams, isset($aService['class']) ? $aService['class'] : 'Module');
                 }
             }
     }
@@ -128,7 +129,8 @@ class BxDolAlerts extends BxDol {
      *
      * @return an array with all alerts and handlers.
      */
-    public function getAlertsData() {
+    public function getAlertsData()
+    {
         $oDb = BxDolDb::getInstance();
         $aResult = array('alerts' => array(), 'handlers' => array());
 
@@ -146,11 +148,10 @@ class BxDolAlerts extends BxDol {
 
 class BxDolAlertsResponse extends BxDol
 {
-    public function __construct() 
+    public function __construct()
     {
         parent::__construct();
     }
 
     public function response($oAlert) {}
 }
-

+ 3 - 4
inc/classes/BxDolCache.php

@@ -7,13 +7,13 @@
  * @{
  */
 
-class BxDolCache extends BxDol 
+class BxDolCache extends BxDol
 {
     /**
      * Is cache engine available?
      * @return boolean
      */
-    function isAvailable() 
+    function isAvailable()
     {
         return true;
     }
@@ -22,7 +22,7 @@ class BxDolCache extends BxDol
      * Are required php modules are installed for this cache engine ?
      * @return boolean
      */
-    function isInstalled() 
+    function isInstalled()
     {
         return true;
     }
@@ -35,4 +35,3 @@ class BxDolCache extends BxDol
 }
 
 /** @} */
-

+ 14 - 15
inc/classes/BxDolCacheAPC.php

@@ -9,18 +9,18 @@
 
 bx_import('BxDolCache');
 
-class BxDolCacheAPC extends BxDolCache 
+class BxDolCacheAPC extends BxDolCache
 {
     protected $iTTL = 3600;
 
     /**
      * Get data from shared memory cache
      *
-     * @param string $sKey - file name
-     * @param int $iTTL - time to live
-     * @return the data is got from cache.
+     * @param  string $sKey - file name
+     * @param  int    $iTTL - time to live
+     * @return the    data is got from cache.
      */
-    function getData($sKey, $iTTL = false) 
+    function getData($sKey, $iTTL = false)
     {
         $isSucess = false;
         $mixedData = apc_fetch ($sKey, $isSucess);
@@ -32,12 +32,12 @@ class BxDolCacheAPC extends BxDolCache
     /**
      * Save data in shared memory cache
      *
-     * @param string $sKey - file name
-     * @param mixed $mixedData - the data to be cached in the file
-     * @param int $iTTL - time to live
+     * @param  string  $sKey      - file name
+     * @param  mixed   $mixedData - the data to be cached in the file
+     * @param  int     $iTTL      - time to live
      * @return boolean result of operation.
      */
-    function setData($sKey, $mixedData, $iTTL = false) 
+    function setData($sKey, $mixedData, $iTTL = false)
     {
         return apc_store ($sKey, $mixedData, false === $iTTL ? $this->iTTL : $iTTL);
     }
@@ -45,10 +45,10 @@ class BxDolCacheAPC extends BxDolCache
     /**
      * Delete cache from shared memory
      *
-     * @param string $sKey - file name
+     * @param  string $sKey - file name
      * @return result of the operation
      */
-    function delData($sKey) 
+    function delData($sKey)
     {
         $isSucess = false;
         apc_fetch ($sKey, $isSucess);
@@ -62,7 +62,7 @@ class BxDolCacheAPC extends BxDolCache
      * Check if apc cache functions are available
      * @return boolean
      */
-    function isAvailable() 
+    function isAvailable()
     {
         return function_exists('apc_store');
     }
@@ -71,7 +71,7 @@ class BxDolCacheAPC extends BxDolCache
      * Check if apc extension is loaded
      * @return boolean
      */
-    function isInstalled() 
+    function isInstalled()
     {
         return extension_loaded('apc');
     }
@@ -80,7 +80,7 @@ class BxDolCacheAPC extends BxDolCache
      * remove all data from cache by key prefix
      * @return true on success
      */
-    function removeAllByPrefix ($s) 
+    function removeAllByPrefix ($s)
     {
         $l = strlen($s);
         $aKeys = apc_cache_info('user');
@@ -96,4 +96,3 @@ class BxDolCacheAPC extends BxDolCache
 }
 
 /** @} */
-

+ 14 - 15
inc/classes/BxDolCacheEAccelerator.php

@@ -9,18 +9,18 @@
 
 bx_import('BxDolCache');
 
-class BxDolCacheEAccelerator extends BxDolCache 
+class BxDolCacheEAccelerator extends BxDolCache
 {
     protected $iTTL = 3600;
 
     /**
      * Get data from shared memory cache
      *
-     * @param string $sKey - file name
-     * @param int $iTTL - time to live
-     * @return the data is got from cache.
+     * @param  string $sKey - file name
+     * @param  int    $iTTL - time to live
+     * @return the    data is got from cache.
      */
-    function getData($sKey, $iTTL = false) 
+    function getData($sKey, $iTTL = false)
     {
         $sData = eaccelerator_get($sKey);
         return null === $sData ? null : unserialize($sData);
@@ -29,12 +29,12 @@ class BxDolCacheEAccelerator extends BxDolCache
     /**
      * Save data in shared memory cache
      *
-     * @param string $sKey - file name
-     * @param mixed $mixedData - the data to be cached in the file
-     * @param int $iTTL - time to live
+     * @param  string  $sKey      - file name
+     * @param  mixed   $mixedData - the data to be cached in the file
+     * @param  int     $iTTL      - time to live
      * @return boolean result of operation.
      */
-    function setData($sKey, $mixedData, $iTTL = false) 
+    function setData($sKey, $mixedData, $iTTL = false)
     {
         $bResult = eaccelerator_put($sKey, serialize($mixedData), false === $iTTL ? $this->iTTL : $iTTL);
         return $bResult;
@@ -43,10 +43,10 @@ class BxDolCacheEAccelerator extends BxDolCache
     /**
      * Delete cache from shared memory
      *
-     * @param string $sKey - file name
+     * @param  string $sKey - file name
      * @return result of the operation
      */
-    function delData($sKey) 
+    function delData($sKey)
     {
         eaccelerator_lock($sKey);
 
@@ -61,7 +61,7 @@ class BxDolCacheEAccelerator extends BxDolCache
      * Check if eAccelerator is available
      * @return boolean
      */
-    function isAvailable() 
+    function isAvailable()
     {
         return function_exists('eaccelerator_put');
     }
@@ -70,7 +70,7 @@ class BxDolCacheEAccelerator extends BxDolCache
      * Check if eaccelerator extension is loaded
      * @return boolean
      */
-    function isInstalled() 
+    function isInstalled()
     {
         return extension_loaded('eaccelerator');
     }
@@ -79,7 +79,7 @@ class BxDolCacheEAccelerator extends BxDolCache
      * remove all data from cache by key prefix
      * @return true on success
      */
-    function removeAllByPrefix ($s) 
+    function removeAllByPrefix ($s)
     {
         $l = strlen($s);
         $aKeys = eaccelerator_list_keys();
@@ -94,4 +94,3 @@ class BxDolCacheEAccelerator extends BxDolCache
 }
 
 /** @} */
-

+ 17 - 18
inc/classes/BxDolCacheFile.php

@@ -9,14 +9,14 @@
 
 bx_import('BxDolCache');
 
-class BxDolCacheFile extends BxDolCache 
+class BxDolCacheFile extends BxDolCache
 {
     protected $sPath;
 
     /**
      * constructor
      */
-    function __construct() 
+    function __construct()
     {
         parent::__construct();
         $this->sPath = BX_DIRECTORY_PATH_CACHE;
@@ -25,11 +25,11 @@ class BxDolCacheFile extends BxDolCache
     /**
      * Get all data from the cache file.
      *
-     * @param string $sKey - file name
-     * @param int $iTTL - time to live
-     * @return the data is got from cache.
+     * @param  string $sKey - file name
+     * @param  int    $iTTL - time to live
+     * @return the    data is got from cache.
      */
-    function getData($sKey, $iTTL = false) 
+    function getData($sKey, $iTTL = false)
     {
         if (!file_exists($this->sPath . $sKey))
             return null;
@@ -44,12 +44,12 @@ class BxDolCacheFile extends BxDolCache
     /**
      * Save all data in cache file.
      *
-     * @param string $sKey - file name
-     * @param mixed $mixedData - the data to be cached in the file
-     * @param int $iTTL - time to live
+     * @param  string  $sKey      - file name
+     * @param  mixed   $mixedData - the data to be cached in the file
+     * @param  int     $iTTL      - time to live
      * @return boolean result of operation.
      */
-    function setData($sKey, $mixedData, $iTTL = false) 
+    function setData($sKey, $mixedData, $iTTL = false)
     {
         if(file_exists($this->sPath . $sKey) && !is_writable($this->sPath . $sKey))
            return false;
@@ -67,10 +67,10 @@ class BxDolCacheFile extends BxDolCache
     /**
      * Delete cache file.
      *
-     * @param string $sKey - file name
+     * @param  string $sKey - file name
      * @return result of the operation
      */
-    function delData($sKey) 
+    function delData($sKey)
     {
         $sFile = $this->sPath . $sKey;
         return !file_exists($sFile) || @unlink($sFile);
@@ -80,7 +80,7 @@ class BxDolCacheFile extends BxDolCache
      * remove all data from cache by key prefix
      * @return true on success
      */
-    function removeAllByPrefix ($s) 
+    function removeAllByPrefix ($s)
     {
         if (!($rHandler = opendir($this->sPath)))
             return false;
@@ -116,11 +116,11 @@ class BxDolCacheFile extends BxDolCache
 
     /**
      * remove file from dist if TTL expored
-     * @param string $sFile - full path to filename
-     * @param int $iTTL - time to live in seconds
-     * @return true if TTL is expired and file is deleted or false otherwise
+     * @param  string $sFile - full path to filename
+     * @param  int    $iTTL  - time to live in seconds
+     * @return true   if TTL is expired and file is deleted or false otherwise
      */
-    function _removeFileIfTtlExpired ($sFile, $iTTL) 
+    function _removeFileIfTtlExpired ($sFile, $iTTL)
     {
         $iTimeDiff = time() - filectime($sFile);
         if ($iTimeDiff > $iTTL) {
@@ -133,4 +133,3 @@ class BxDolCacheFile extends BxDolCache
 }
 
 /** @} */
-

+ 8 - 9
inc/classes/BxDolCacheFileHtml.php

@@ -14,9 +14,9 @@ class BxDolCacheFileHtml extends BxDolCacheFile
     /**
      * Get all data from the cache file.
      *
-     * @param string $sKey - file name
-     * @param int $iTTL - time to live
-     * @return the data is got from cache.
+     * @param  string $sKey - file name
+     * @param  int    $iTTL - time to live
+     * @return the    data is got from cache.
      */
     function getData($sKey, $iTTL = false)
     {
@@ -32,7 +32,7 @@ class BxDolCacheFileHtml extends BxDolCacheFile
     /**
      * Get full path to cache file
      */
-    function getDataFilePath($sKey, $iTTL = false) 
+    function getDataFilePath($sKey, $iTTL = false)
     {
         if (!file_exists($this->sPath . $sKey))
             return null;
@@ -46,12 +46,12 @@ class BxDolCacheFileHtml extends BxDolCacheFile
     /**
      * Save all data in cache file.
      *
-     * @param string $sKey - file name
-     * @param mixed $mixedData - the data to be cached in the file
-     * @param int $iTTL - time to live
+     * @param  string  $sKey      - file name
+     * @param  mixed   $mixedData - the data to be cached in the file
+     * @param  int     $iTTL      - time to live
      * @return boolean result of operation.
      */
-    function setData($sKey, $mixedData, $iTTL = false) 
+    function setData($sKey, $mixedData, $iTTL = false)
     {
         if(file_exists($this->sPath . $sKey) && !is_writable($this->sPath . $sKey))
            return false;
@@ -68,4 +68,3 @@ class BxDolCacheFileHtml extends BxDolCacheFile
 }
 
 /** @} */
-

+ 15 - 16
inc/classes/BxDolCacheMemcache.php

@@ -9,7 +9,7 @@
 
 bx_import('BxDolCache');
 
-class BxDolCacheMemcache extends BxDolCache 
+class BxDolCacheMemcache extends BxDolCache
 {
     protected $iTTL = 3600;
     protected $iStoreFlag = 0;
@@ -18,7 +18,7 @@ class BxDolCacheMemcache extends BxDolCache
     /**
      * constructor
      */
-    function __construct() 
+    function __construct()
     {
         parent::__construct();
         if (class_exists('Memcache')) {
@@ -31,11 +31,11 @@ class BxDolCacheMemcache extends BxDolCache
     /**
      * Get data from cache server
      *
-     * @param string $sKey - file name
-     * @param int $iTTL - time to live
-     * @return the data is got from cache.
+     * @param  string $sKey - file name
+     * @param  int    $iTTL - time to live
+     * @return the    data is got from cache.
      */
-    function getData($sKey, $iTTL = false) 
+    function getData($sKey, $iTTL = false)
     {
         $mixedData = $this->oMemcache->get($sKey);
         return false === $mixedData ? null : $mixedData;
@@ -44,12 +44,12 @@ class BxDolCacheMemcache extends BxDolCache
     /**
      * Save data in cache server
      *
-     * @param string $sKey - file name
-     * @param mixed $mixedData - the data to be cached in the file
-     * @param int $iTTL - time to live
+     * @param  string  $sKey      - file name
+     * @param  mixed   $mixedData - the data to be cached in the file
+     * @param  int     $iTTL      - time to live
      * @return boolean result of operation.
      */
-    function setData($sKey, $mixedData, $iTTL = false) 
+    function setData($sKey, $mixedData, $iTTL = false)
     {
         return $this->oMemcache->set($sKey, $mixedData, $this->iStoreFlag, false === $iTTL ? $this->iTTL : $iTTL);
     }
@@ -57,10 +57,10 @@ class BxDolCacheMemcache extends BxDolCache
     /**
      * Delete cache from cache server
      *
-     * @param string $sKey - file name
+     * @param  string $sKey - file name
      * @return result of the operation
      */
-    function delData($sKey) 
+    function delData($sKey)
     {
         $this->oMemcache->delete($sKey);
         return true;
@@ -70,7 +70,7 @@ class BxDolCacheMemcache extends BxDolCache
      * Check if memcache is available
      * @return boolean
      */
-    function isAvailable() 
+    function isAvailable()
     {
         return $this->oMemcache == null ? false : true;
     }
@@ -79,7 +79,7 @@ class BxDolCacheMemcache extends BxDolCache
      * Check if memcache extension is loaded
      * @return boolean
      */
-    function isInstalled() 
+    function isInstalled()
     {
         return extension_loaded('memcache');
     }
@@ -88,7 +88,7 @@ class BxDolCacheMemcache extends BxDolCache
      * remove all data from cache by key prefix
      * @return true on success
      */
-    function removeAllByPrefix ($s) 
+    function removeAllByPrefix ($s)
     {
         // not implemented for current cache
         return false;
@@ -96,4 +96,3 @@ class BxDolCacheMemcache extends BxDolCache
 }
 
 /** @} */
-

+ 0 - 1
inc/classes/BxDolCacheUtilities.php

@@ -134,4 +134,3 @@ class BxDolCacheUtilities extends BxDol
 }
 
 /** @} */
-

+ 14 - 15
inc/classes/BxDolCacheXCache.php

@@ -9,18 +9,18 @@
 
 bx_import('BxDolCache');
 
-class BxDolCacheXCache extends BxDolCache 
+class BxDolCacheXCache extends BxDolCache
 {
     protected $iTTL = 3600;
 
     /**
      * Get data from shared memory cache
      *
-     * @param string $sKey - file name
-     * @param int $iTTL - time to live
-     * @return the data is got from cache.
+     * @param  string $sKey - file name
+     * @param  int    $iTTL - time to live
+     * @return the    data is got from cache.
      */
-    function getData($sKey, $iTTL = false) 
+    function getData($sKey, $iTTL = false)
     {
         if (!xcache_isset($sKey))
             return null;
@@ -31,12 +31,12 @@ class BxDolCacheXCache extends BxDolCache
     /**
      * Save data in shared memory cache
      *
-     * @param string $sKey - file name
-     * @param mixed $mixedData - the data to be cached in the file
-     * @param int $iTTL - time to live
+     * @param  string  $sKey      - file name
+     * @param  mixed   $mixedData - the data to be cached in the file
+     * @param  int     $iTTL      - time to live
      * @return boolean result of operation.
      */
-    function setData($sKey, $mixedData, $iTTL = false) 
+    function setData($sKey, $mixedData, $iTTL = false)
     {
         $bResult = xcache_set($sKey, $mixedData, false === $iTTL ? $this->iTTL : $iTTL);
         return $bResult;
@@ -45,10 +45,10 @@ class BxDolCacheXCache extends BxDolCache
     /**
      * Delete cache from shared memory
      *
-     * @param string $sKey - file name
+     * @param  string $sKey - file name
      * @return result of the operation
      */
-    function delData($sKey) 
+    function delData($sKey)
     {
         if (!xcache_isset($sKey))
             return true;
@@ -60,7 +60,7 @@ class BxDolCacheXCache extends BxDolCache
      * Check if xcache functions are available
      * @return boolean
      */
-    function isAvailable() 
+    function isAvailable()
     {
         return extension_loaded('xcache');
     }
@@ -69,7 +69,7 @@ class BxDolCacheXCache extends BxDolCache
      * Check if xcache extension is loaded
      * @return boolean
      */
-    function isInstalled() 
+    function isInstalled()
     {
         return extension_loaded('xcache');
     }
@@ -78,11 +78,10 @@ class BxDolCacheXCache extends BxDolCache
      * remove all data from cache by key prefix
      * @return true on success
      */
-    function removeAllByPrefix ($s) 
+    function removeAllByPrefix ($s)
     {
         return xcache_unset_by_prefix ($s);
     }
 }
 
 /** @} */
-

+ 28 - 23
inc/classes/BxDolCaptcha.php

@@ -9,14 +9,14 @@
 
 bx_import('BxDolCaptchaQuery');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section captcha CAPTCHA
  * @ref BxDolCaptcha
  */
 
 /**
- * CAPTCHA objects. 
+ * CAPTCHA objects.
  *
  * Default captcha is stored in 'sys_captcha_default' setting option.
  *
@@ -25,36 +25,36 @@ bx_import('BxDolCaptchaQuery');
  *
  * Add record to 'sys_objects_captcha' table:
  *
- * - object: name of the captcha object, in the format: vendor prefix, underscore, module prefix, underscore, internal identifier or nothing; for example: bx_blogs - custom captcha in blogs module. 
+ * - object: name of the captcha object, in the format: vendor prefix, underscore, module prefix, underscore, internal identifier or nothing; for example: bx_blogs - custom captcha in blogs module.
  * - title: captcha title.
  * - override_class_name: user defined class name which is derived from one of base captcha classes.
  * - override_class_file: the location of the user defined class, leave it empty if class is located in system folders.
- * 
+ *
  *
  * @section example Example of usage
  *
  * Display captcha:
- * 
+ *
  * @code
  *  bx_import('BxDolCaptcha'); // import captcha class
  *  $oCaptcha = BxDolCaptcha::getObjectInstance(); // get default captcha object instance
  *  if ($oCaptcha) // check if captcha is available for using
  *      echo $oCaptcha->display (); // output HTML which will automatically show captcha
  * @endcode
- * 
+ *
  * Check captcha:
- * 
+ *
  * @code
  *  bx_import('BxDolCaptcha'); // import captcha class
  *  $oCaptcha = BxDolCaptcha::getObjectInstance(); // get default captcha object instance
  *  if ($oCaptcha && $oCaptcha->check ()) // check if captcha is correct
- *      echo 'captcha is OK'; 
+ *      echo 'captcha is OK';
  *  else
- *      echo 'captcha is incorrect'; // 
+ *      echo 'captcha is incorrect'; //
  * @endcode
  */
-class BxDolCaptcha extends BxDol implements iBxDolFactoryObject {
-
+class BxDolCaptcha extends BxDol implements iBxDolFactoryObject
+{
     protected $_sObject;
     protected $_aObject;
 
@@ -62,7 +62,8 @@ class BxDolCaptcha extends BxDol implements iBxDolFactoryObject {
      * Constructor
      * @param $aObject array of captcha options
      */
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
 
         $this->_sObject = $aObject['object'];
@@ -74,14 +75,14 @@ class BxDolCaptcha extends BxDol implements iBxDolFactoryObject {
      * @param $sObject object name
      * @return object instance or false on error
      */
-    static public function getObjectInstance($sObject = false) {
-
+    static public function getObjectInstance($sObject = false)
+    {
         if (!$sObject)
             $sObject = getParam('sys_captcha_default');
 
         if (isset($GLOBALS['bxDolClasses']['BxDolCaptcha!'.$sObject]))
             return $GLOBALS['bxDolClasses']['BxDolCaptcha!'.$sObject];
-        
+
         $aObject = BxDolCaptchaQuery::getCaptchaObject($sObject);
         if (!$aObject || !is_array($aObject))
             return false;
@@ -92,9 +93,9 @@ class BxDolCaptcha extends BxDol implements iBxDolFactoryObject {
         $sClass = $aObject['override_class_name'];
         if (!empty($aObject['override_class_file']))
             require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
-        else    
+        else
             bx_import($sClass);
-        
+
         $o = new $sClass($aObject);
         if (!$o->isAvailable())
             return false;
@@ -106,28 +107,32 @@ class BxDolCaptcha extends BxDol implements iBxDolFactoryObject {
      * Display captcha.
      * @param $bDynamicMode - is AJAX mode or not, if true then HTML code with captcha is loaded dynamically.
      */
-    public function display ($bDynamicMode = false) {
+    public function display ($bDynamicMode = false)
+    {
         // override this function in particular class
     }
-  
+
     /**
      * Check captcha.
      */
-    public function check () {
+    public function check ()
+    {
         // override this function in particular class
     }
 
     /**
      * Return text entered by user
      */
-    public function getUserResponse () {
+    public function getUserResponse ()
+    {
         // override this function in particular class
     }
 
     /**
      * Check if captcha is available, like all API keys are specified.
      */
-    public function isAvailable () {
+    public function isAvailable ()
+    {
         // override this function in particular class
     }
 }

+ 8 - 5
inc/classes/BxDolCaptchaQuery.php

@@ -13,21 +13,24 @@ bx_import('BxDolDb');
  * Database queries for captcha objects.
  * @see BxDolCaptcha
  */
-class BxDolCaptchaQuery extends BxDolDb {
+class BxDolCaptchaQuery extends BxDolDb
+{
     protected $_aObject;
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
     }
 
-    static public function getCaptchaObject ($sObject) {
+    static public function getCaptchaObject ($sObject)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_captcha` WHERE `object` = ?", $sObject);
         $aObject = $oDb->getRow($sQuery);
-        if (!$aObject || !is_array($aObject)) 
+        if (!$aObject || !is_array($aObject))
             return false;
-        
+
         return $aObject;
     }
 

+ 266 - 268
inc/classes/BxDolCmts.php

@@ -9,7 +9,7 @@
 
 bx_import('BxDolCmtsQuery');
 
-define('BX_CMT_OLD_VOTES', 365*86400); ///< comment votes older than this number of seconds will be deleted automatically 
+define('BX_CMT_OLD_VOTES', 365*86400); ///< comment votes older than this number of seconds will be deleted automatically
 
 define('BX_CMT_ACTION_POST', 'post');
 define('BX_CMT_ACTION_EDIT', 'edit');
@@ -38,9 +38,8 @@ define('BX_CMT_PFP_BOTTOM', 'bottom');
 define('BX_CMT_RATE_VALUE_PLUS', 1);
 define('BX_CMT_RATE_VALUE_MINUS', -1);
 
-
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section comments Comments
  * @ref BxDolCmts
  */
@@ -97,7 +96,7 @@ define('BX_CMT_RATE_VALUE_MINUS', -1);
  * @section acl Memberships/ACL:
  * - comments post
  * - comments edit own
- * - comments remove own 
+ * - comments remove own
  * - comments edit all
  *
  *
@@ -131,31 +130,31 @@ define('BX_CMT_RATE_VALUE_MINUS', -1);
  */
 class BxDolCmts extends BxDol implements iBxDolReplaceable
 {
-	protected $_oQuery = null;
+    protected $_oQuery = null;
 
-	protected $_sFormObject;
-	protected $_sFormDisplayPost;
-	protected $_sFormDisplayEdit;
+    protected $_sFormObject;
+    protected $_sFormDisplayPost;
+    protected $_sFormDisplayEdit;
 
-	protected $_sStorageObject;
-	protected $_sTranscoderPreview;
+    protected $_sStorageObject;
+    protected $_sTranscoderPreview;
 
-	protected $_sTableImages;
-	protected $_sTableImages2Entries;
+    protected $_sTableImages;
+    protected $_sTableImages2Entries;
 
-	protected $_aImageUploaders;
+    protected $_aImageUploaders;
 
-	protected $_sConnObjFriends;
-	protected $_sConnObjSubscriptions;
+    protected $_sConnObjFriends;
+    protected $_sConnObjSubscriptions;
 
-	protected $_sMenuObjManage;
-	protected $_sMenuObjActions;
+    protected $_sMenuObjManage;
+    protected $_sMenuObjActions;
 
-	protected $_sViewUrl = '';
-	protected $_sBaseUrl = '';
-	protected $_sListAnchor = '';
+    protected $_sViewUrl = '';
+    protected $_sBaseUrl = '';
+    protected $_sListAnchor = '';
 
-	protected $_sSystem = 'profile'; ///< current comment system name
+    protected $_sSystem = 'profile'; ///< current comment system name
     protected $_aSystem = array (); ///< current comments system array
     protected $_iId = 0; ///< obect id to be commented
 
@@ -168,7 +167,7 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
     protected $_sBrowseType = '';
     protected $_sBrowseFilter = '';
     protected $_sBpSessionKeyType = '';
-    protected $_sBpSessionKeyFilter = ''; 
+    protected $_sBpSessionKeyFilter = '';
     protected $_aOrder = array();
 
     protected $_iRememberTime = 2592000;
@@ -183,14 +182,14 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         parent::__construct();
 
         $this->_aSystems = $this->getSystems();
-		if(!isset($this->_aSystems[$sSystem]))
-			return;
+        if(!isset($this->_aSystems[$sSystem]))
+            return;
 
         $this->_sSystem = $sSystem;
         $this->_aSystem = $this->_aSystems[$sSystem];
 
-		$this->_aSystem['table_images'] = 'sys_cmts_images';
-		$this->_aSystem['table_images2entries'] = 'sys_cmts_images2entries';
+        $this->_aSystem['table_images'] = 'sys_cmts_images';
+        $this->_aSystem['table_images2entries'] = 'sys_cmts_images2entries';
 
         $this->_iDpMaxLevel = (int)$this->_aSystem['number_of_levels'];
         $this->_sDisplayType = $this->_iDpMaxLevel == 0 ? BX_CMT_DISPLAY_FLAT : BX_CMT_DISPLAY_THREADED;
@@ -201,55 +200,55 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         $this->_sBpSessionKeyType = 'bx_' . $this->_sSystem . '_bpt_';
         $this->_sBpSessionKeyFilter = 'bx_' . $this->_sSystem . '_bpf_';
         $this->_aOrder = array(
-        	'by' => BX_CMT_ORDER_BY_DATE, 
-        	'way' => BX_CMT_ORDER_WAY_ASC
+            'by' => BX_CMT_ORDER_BY_DATE,
+            'way' => BX_CMT_ORDER_WAY_ASC
         );
 
         list($mixedUserDp, $mixedUserBpType, $mixedUserBpFilter) = $this->_getUserChoice();
-		if(!empty($mixedUserDp))
-			$this->_sDisplayType = $mixedUserDp;
+        if(!empty($mixedUserDp))
+            $this->_sDisplayType = $mixedUserDp;
         if(!empty($mixedUserBpType))
-        	$this->_sBrowseType = $mixedUserBpType;
-		if(!empty($mixedUserBpFilter))
-        	$this->_sBrowseFilter = $mixedUserBpFilter;
+            $this->_sBrowseType = $mixedUserBpType;
+        if(!empty($mixedUserBpFilter))
+            $this->_sBrowseFilter = $mixedUserBpFilter;
 
         $this->_sViewUrl = BX_DOL_URL_ROOT . 'cmts.php';
         $this->_sBaseUrl = $this->_aSystem['base_url'];
         if(get_mb_substr($this->_sBaseUrl, 0, 4) != 'http')
-        	$this->_sBaseUrl = BX_DOL_URL_ROOT . $this->_sBaseUrl;
-		$this->_sListAnchor = "cmts-anchor-%s-%d";
+            $this->_sBaseUrl = BX_DOL_URL_ROOT . $this->_sBaseUrl;
+        $this->_sListAnchor = "cmts-anchor-%s-%d";
+
+        $this->_oQuery = new BxDolCmtsQuery($this);
 
-		$this->_oQuery = new BxDolCmtsQuery($this);
+        $this->_sFormObject = 'sys_comment';
+        $this->_sFormDisplayPost = 'sys_comment_post';
+        $this->_sFormDisplayEdit = 'sys_comment_edit';
 
-		$this->_sFormObject = 'sys_comment';
-		$this->_sFormDisplayPost = 'sys_comment_post';
-		$this->_sFormDisplayEdit = 'sys_comment_edit';
+        $this->_sStorageObject = 'sys_cmts_images';
+        $this->_sTranscoderPreview = 'sys_cmts_images_preview';
 
-		$this->_sStorageObject = 'sys_cmts_images';
-		$this->_sTranscoderPreview = 'sys_cmts_images_preview';
+        $this->_aImageUploaders = array('sys_cmts_simple');
 
-		$this->_aImageUploaders = array('sys_cmts_simple');
-		
-		$this->_sConnObjFriends = 'sys_profiles_friends';
-		$this->_sConnObjSubscriptions = 'sys_profiles_subscriptions';
+        $this->_sConnObjFriends = 'sys_profiles_friends';
+        $this->_sConnObjSubscriptions = 'sys_profiles_subscriptions';
+
+        $this->_sMenuObjManage = 'sys_cmts_item_manage';
+        $this->_sMenuObjActions = 'sys_cmts_item_actions';
 
-		$this->_sMenuObjManage = 'sys_cmts_item_manage';
-		$this->_sMenuObjActions = 'sys_cmts_item_actions';
-		
         if ($iInit)
             $this->init($iId);
     }
 
-	/**
+    /**
      * get comments object instanse
-     * @param $sSys comments object name 
+     * @param $sSys comments object name
      * @param $iId associated content id, where comments are postred in
      * @param $iInit perform initialization
      * @return null on error, or ready to use class instance
-     */ 
-    public static function getObjectInstance($sSys, $iId, $iInit = true) 
+     */
+    public static function getObjectInstance($sSys, $iId, $iInit = true)
     {
-    	if(isset($GLOBALS['bxDolClasses']['BxDolCmts!' . $sSys . $iId]))
+        if(isset($GLOBALS['bxDolClasses']['BxDolCmts!' . $sSys . $iId]))
             return $GLOBALS['bxDolClasses']['BxDolCmts!' . $sSys . $iId];
 
         $aSystems = self::getSystems();
@@ -259,8 +258,8 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         bx_import('BxTemplCmts');
         $sClassName = 'BxTemplCmts';
         if(!empty($aSystems[$sSys]['class_name'])) {
-        	$sClassName = $aSystems[$sSys]['class_name'];
-        	if(!empty($aSystems[$sSys]['class_file']))
+            $sClassName = $aSystems[$sSys]['class_name'];
+            if(!empty($aSystems[$sSys]['class_file']))
                 require_once(BX_DIRECTORY_PATH_ROOT . $aSystems[$sSys]['class_file']);
             else
                 bx_import($sClassName);
@@ -311,10 +310,10 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         if (empty($this->iId) && $iId)
             $this->setId($iId);
 
-		$this->addMarkers(array(
-			'object_id' => $this->getId(),
-			'user_id' => $this->_getAuthorId()
-		));
+        $this->addMarkers(array(
+            'object_id' => $this->getId(),
+            'user_id' => $this->_getAuthorId()
+        ));
     }
 
     public function getId ()
@@ -327,7 +326,7 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         return isset($this->_aSystem['is_on']) && $this->_aSystem['is_on'];
     }
 
-	public function getSystemId()
+    public function getSystemId()
     {
         return $this->_aSystem['system_id'];
     }
@@ -342,68 +341,68 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         return $this->_sStorageObject;
     }
 
-	public function getSystemInfo()
+    public function getSystemInfo()
     {
         return $this->_aSystem;
     }
 
-	public function getMaxLevel()
-	{
-		return $this->_iDpMaxLevel;
-	}
+    public function getMaxLevel()
+    {
+        return $this->_iDpMaxLevel;
+    }
 
     public function getOrder ()
     {
         return $this->_sOrder;
     }
 
-	public function getPerView ($iCmtParentId = 0)
+    public function getPerView ($iCmtParentId = 0)
     {
         return $iCmtParentId == 0 ? $this->_aSystem['per_view'] : $this->_aSystem['per_view_replies'];
     }
 
     public function getBaseUrl()
     {
-    	return $this->_replaceMarkers($this->_sBaseUrl);
+        return $this->_replaceMarkers($this->_sBaseUrl);
     }
 
     public function getListUrl()
     {
-    	return $this->getBaseUrl() . '#' . $this->getListAnchor();
+        return $this->getBaseUrl() . '#' . $this->getListAnchor();
     }
 
     public function getListAnchor()
     {
-    	return sprintf($this->_sListAnchor, str_replace('_', '-', $this->getSystemName()), $this->getId());
+        return sprintf($this->_sListAnchor, str_replace('_', '-', $this->getSystemName()), $this->getId());
     }
 
     public function getConnectionObject($sType)
     {
-    	$sResult = '';
+        $sResult = '';
 
-    	switch($sType) {
-    		case BX_CMT_FILTER_FRIENDS:
-    			$sResult = $this->_sConnObjFriends;
-    			break;
-    		case BX_CMT_FILTER_SUBSCRIPTIONS:
-    			$sResult = $this->_sConnObjSubscriptions;
-    			break;
-    	}
+        switch($sType) {
+            case BX_CMT_FILTER_FRIENDS:
+                $sResult = $this->_sConnObjFriends;
+                break;
+            case BX_CMT_FILTER_SUBSCRIPTIONS:
+                $sResult = $this->_sConnObjSubscriptions;
+                break;
+        }
 
-    	return $sResult;
+        return $sResult;
     }
 
-	public function getVoteObject($iId)
+    public function getVoteObject($iId)
     {
-    	if(empty($this->_aSystem['object_vote']))
-    		return false;
+        if(empty($this->_aSystem['object_vote']))
+            return false;
 
-    	bx_import('BxDolVote');
+        bx_import('BxDolVote');
         $oVote = BxDolVote::getObjectInstance($this->_aSystem['object_vote'], $iId);
-		if(!$oVote->isEnabled())
-			return false;
+        if(!$oVote->isEnabled())
+            return false;
 
-		return $oVote;
+        return $oVote;
     }
 
     public function isNl2br ()
@@ -418,7 +417,7 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
 
     public function isAttachImageEnabled()
     {
-    	return true;
+        return true;
     }
 
     /**
@@ -430,12 +429,12 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         $this->_iId = $iId;
     }
 
-	/**
+    /**
      * Add replace markers.
      * @param $a array of markers as key => value
      * @return true on success or false on error
      */
-    public function addMarkers ($a) 
+    public function addMarkers ($a)
     {
         if (empty($a) || !is_array($a))
             return false;
@@ -443,25 +442,25 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         return true;
     }
 
-    /** 
+    /**
      * Database functions
      */
-	public function getQueryObject ()
+    public function getQueryObject ()
     {
         return $this->_oQuery;
     }
 
-	public function getCommentsTableName ()
+    public function getCommentsTableName ()
     {
         return $this->_oQuery->getTableName ();
     }
 
     public function getObjectTitle ($iObjectId = 0)
     {
-    	return $this->_oQuery->getObjectTitle ($iObjectId ? $iObjectId : $this->getId());
+        return $this->_oQuery->getObjectTitle ($iObjectId ? $iObjectId : $this->getId());
     }
 
-	public function getCommentsCount ($iObjectId = 0, $iCmtVParentId = 0, $sFilter = '')
+    public function getCommentsCount ($iObjectId = 0, $iCmtVParentId = 0, $sFilter = '')
     {
         return $this->_oQuery->getCommentsCount ($iObjectId ? $iObjectId : $this->getId(), $iCmtVParentId, $this->_getAuthorId(), $sFilter);
     }
@@ -495,14 +494,14 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
     {
         bx_import('BxDolStorage');
         $aSystems = self::getSystems();
-    	foreach($aSystems as $sSystem => $aSystem) {
+        foreach($aSystems as $sSystem => $aSystem) {
             $o = self::getObjectInstance($sSystem, 0);
-            $oQuery = $o->getQueryObject();            
+            $oQuery = $o->getQueryObject();
 
             // delete comments
             $aFiles = array ();
             $oQuery->deleteAuthorComments($iAuthorId, $aFiles);
-            
+
             // delete files
             $oStorage = BxDolStorage::getObjectInstance($o->getStorageObjectName());
             if ($oStorage)
@@ -512,17 +511,17 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
     }
 
     public static function onModuleUninstall ($sModuleName, &$iFiles = null)
-    {        
+    {
         bx_import('BxDolStorage');
         $aSystems = self::getSystems();
-    	foreach($aSystems as $sSystem => $aSystem) {
+        foreach($aSystems as $sSystem => $aSystem) {
             if (0 != strncasecmp($sModuleName, $sSystem, strlen($sModuleName)))
                 continue;
 
             $o = self::getObjectInstance($sSystem, 0);
             $oQuery = $o->getQueryObject();
 
-            // delete comments            
+            // delete comments
             $aFiles = array ();
             $oQuery->deleteAll($aSystem['system_id'], $aFiles);
 
@@ -538,7 +537,7 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         return true;
     }
 
-    /** 
+    /**
      * Permissions functions
      */
     public function checkAction ($sAction, $isPerformAction = false)
@@ -557,21 +556,21 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
 
     public function isVoteAllowed ($aCmt, $isPerformAction = false)
     {
-    	if(!$this->isRatable())
-    		return false;
+        if(!$this->isRatable())
+            return false;
 
-		$oVote = $this->getVoteObject($aCmt['cmt_id']);
-    	if($oVote === false)
-    		return false;
+        $oVote = $this->getVoteObject($aCmt['cmt_id']);
+        if($oVote === false)
+            return false;
 
-    	$iUserId = (int)$this->_getAuthorId();
-    	if($iUserId == 0)
-    		return false;
+        $iUserId = (int)$this->_getAuthorId();
+        if($iUserId == 0)
+            return false;
 
-    	if(isAdmin())
-			return true;
+        if(isAdmin())
+            return true;
 
-        return $oVote->isAllowedVote($isPerformAction); 
+        return $oVote->isAllowedVote($isPerformAction);
     }
 
     public function isPostReplyAllowed ($isPerformAction = false)
@@ -586,11 +585,11 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
 
     public function isEditAllowed ($aCmt, $isPerformAction = false)
     {
-    	if(isAdmin())
-    		return true;
+        if(isAdmin())
+            return true;
 
-		if($aCmt['cmt_author_id'] == $this->_getAuthorId() && $this->checkAction ('comments edit own', $isPerformAction))
-			return true;
+        if($aCmt['cmt_author_id'] == $this->_getAuthorId() && $this->checkAction ('comments edit own', $isPerformAction))
+            return true;
 
         return $this->checkAction('comments edit all', $isPerformAction);
     }
@@ -602,11 +601,11 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
 
     public function isRemoveAllowed ($aCmt, $isPerformAction = false)
     {
-    	if(isAdmin())
-    		return true;
+        if(isAdmin())
+            return true;
 
-		if($aCmt['cmt_author_id'] == $this->_getAuthorId() && $this->checkAction ('comments remove own', $isPerformAction))
-			return true;
+        if($aCmt['cmt_author_id'] == $this->_getAuthorId() && $this->checkAction ('comments remove own', $isPerformAction))
+            return true;
 
         return $this->checkAction ('comments remove all', $isPerformAction);
     }
@@ -619,7 +618,7 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
     /**
      * Actions functions
      */
-    public function actionGetFormPost () 
+    public function actionGetFormPost ()
     {
         if (!$this->isEnabled())
             return '';
@@ -631,18 +630,18 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         return $this->getFormBoxPost(array('parent_id' => $iCmtParentId, 'type' => $sCmtBrowse), array('type' => $sCmtDisplay));
     }
 
-	public function actionGetFormEdit ()
+    public function actionGetFormEdit ()
     {
         if (!$this->isEnabled()){
-        	$this->_echoResultJson(array());
-        	return;
+            $this->_echoResultJson(array());
+            return;
         }
 
-		$iCmtId = bx_process_input(bx_get('Cmt'), BX_DATA_INT);
+        $iCmtId = bx_process_input(bx_get('Cmt'), BX_DATA_INT);
         $this->_echoResultJson($this->getFormEdit($iCmtId));
     }
 
-    public function actionGetCmt () 
+    public function actionGetCmt ()
     {
         if (!$this->isEnabled())
             return '';
@@ -653,13 +652,13 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
 
         $aCmt = $this->getCommentRow($iCmtId);
         $this->_echoResultJson(array(
-        	'parent_id' => $aCmt['cmt_parent_id'],
-        	'vparent_id' => $aCmt['cmt_vparent_id'],
-        	'content' => $this->getComment($aCmt, array('type' => $sCmtBrowse), array('type' => $sCmtDisplay))
+            'parent_id' => $aCmt['cmt_parent_id'],
+            'vparent_id' => $aCmt['cmt_vparent_id'],
+            'content' => $this->getComment($aCmt, array('type' => $sCmtBrowse), array('type' => $sCmtDisplay))
         ));
     }
 
-    public function actionGetCmts () 
+    public function actionGetCmts ()
     {
         if (!$this->isEnabled())
             return '';
@@ -674,39 +673,39 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         return $this->getComments(array('vparent_id' => $iCmtVParentId, 'start' => $iCmtStart, 'per_view' => $iCmtPerView, 'type' => $sCmtBrowse, 'filter' => $sCmtFilter), array('type' => $sCmtDisplay));
     }
 
-	public function actionGetImage ()
+    public function actionGetImage ()
     {
-    	if (!$this->isEnabled())
+        if (!$this->isEnabled())
            return '';
 
-		$iImgId = bx_process_input(bx_get('ImgId'), BX_DATA_INT);
+        $iImgId = bx_process_input(bx_get('ImgId'), BX_DATA_INT);
         return $this->getImage($iImgId);
     }
 
     public function actionSubmitPostForm()
     {
         if(!$this->isEnabled() || !$this->isPostReplyAllowed()) {
-        	$this->_echoResultJson(array());
-        	return;
+            $this->_echoResultJson(array());
+            return;
         }
 
         $iCmtParentId = 0;
         if(bx_get('cmt_parent_id') !== false)
-			$iCmtParentId = bx_process_input(bx_get('cmt_parent_id'), BX_DATA_INT);
+            $iCmtParentId = bx_process_input(bx_get('cmt_parent_id'), BX_DATA_INT);
 
-		$this->_echoResultJson($this->getFormPost($iCmtParentId));
+        $this->_echoResultJson($this->getFormPost($iCmtParentId));
     }
 
-	public function actionSubmitEditForm()
-	{
+    public function actionSubmitEditForm()
+    {
         if (!$this->isEnabled()) {
-        	$this->_echoResultJson(array());
-        	return;
+            $this->_echoResultJson(array());
+            return;
         };
 
         $iCmtId = 0;
         if(bx_get('cmt_id') !== false)
-			$iCmtId = bx_process_input(bx_get('cmt_id'), BX_DATA_INT);
+            $iCmtId = bx_process_input(bx_get('cmt_id'), BX_DATA_INT);
 
         $this->_echoResultJson($this->getFormEdit($iCmtId));
     }
@@ -714,57 +713,57 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
     public function actionRemove()
     {
         if (!$this->isEnabled()) {
-        	$this->_echoResultJson(array());
-        	return;
+            $this->_echoResultJson(array());
+            return;
         };
 
         $iCmtId = 0;
         if(bx_get('Cmt') !== false)
-        	$iCmtId = bx_process_input(bx_get('Cmt'), BX_DATA_INT);
+            $iCmtId = bx_process_input(bx_get('Cmt'), BX_DATA_INT);
 
         $aCmt = $this->_oQuery->getCommentSimple ($this->getId(), $iCmtId);
         if(!$aCmt) {
-        	$this->_echoResultJson(array('msg' => _t('_No such comment')));
-        	return;
+            $this->_echoResultJson(array('msg' => _t('_No such comment')));
+            return;
         }
 
         if ($aCmt['cmt_replies'] > 0) {
-        	$this->_echoResultJson(array('msg' => _t('_Can not delete comments with replies')));
-        	return;
+            $this->_echoResultJson(array('msg' => _t('_Can not delete comments with replies')));
+            return;
         }
 
         $iCmtAuthorId = $this->_getAuthorId();
         if(!$this->isRemoveAllowed($aCmt)) {
-        	$this->_echoResultJson(array('msg' => $aCmt['cmt_author_id'] == $iCmtAuthorId ? strip_tags($this->msgErrRemoveAllowed()) : _t('_Access denied')));
-        	return;
+            $this->_echoResultJson(array('msg' => $aCmt['cmt_author_id'] == $iCmtAuthorId ? strip_tags($this->msgErrRemoveAllowed()) : _t('_Access denied')));
+            return;
         }
 
         if($this->_oQuery->removeComment ($this->getId(), $aCmt['cmt_id'], $aCmt['cmt_parent_id'])) {
-        	$this->_triggerComment();
+            $this->_triggerComment();
 
-        	bx_import('BxDolStorage');
-			$oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
+            bx_import('BxDolStorage');
+            $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
 
-			$aImages = $this->_oQuery->getImages($this->_aSystem['system_id'], $aCmt['cmt_id']);
-			foreach($aImages as $aImage)
-				$oStorage->deleteFile($aImage['image_id']);
+            $aImages = $this->_oQuery->getImages($this->_aSystem['system_id'], $aCmt['cmt_id']);
+            foreach($aImages as $aImage)
+                $oStorage->deleteFile($aImage['image_id']);
 
-        	$this->_oQuery->deleteImages($this->_aSystem['system_id'], $aCmt['cmt_id']);
+            $this->_oQuery->deleteImages($this->_aSystem['system_id'], $aCmt['cmt_id']);
 
-			$this->isRemoveAllowed(true);
+            $this->isRemoveAllowed(true);
 
-	        bx_import('BxDolAlerts');
-	        $oZ = new BxDolAlerts($this->_sSystem, 'commentRemoved', $this->getId(), $iCmtAuthorId, array('comment_id' => $aCmt['cmt_id'], 'comment_author_id' => $aCmt['cmt_author_id']));
-	        $oZ->alert();
+            bx_import('BxDolAlerts');
+            $oZ = new BxDolAlerts($this->_sSystem, 'commentRemoved', $this->getId(), $iCmtAuthorId, array('comment_id' => $aCmt['cmt_id'], 'comment_author_id' => $aCmt['cmt_author_id']));
+            $oZ->alert();
 
-	        $this->_echoResultJson(array('id' => $iCmtId));
-	        return;
+            $this->_echoResultJson(array('id' => $iCmtId));
+            return;
         }
 
         $this->_echoResultJson(array('msg' => _t('_cmt_err_cannot_perform_action')));
     }
 
-    /** 
+    /**
      * Internal functions
      */
     protected function _getAuthorId ()
@@ -782,29 +781,29 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         return getVisitorIP();
     }
 
-    
-	protected function _getAuthorInfo($iAuthorId = 0)
+
+    protected function _getAuthorInfo($iAuthorId = 0)
     {
-    	$oProfile = $this->_getAuthorObject($iAuthorId);
+        $oProfile = $this->_getAuthorObject($iAuthorId);
 
-		return array(
-			$oProfile->getDisplayName(), 
-			$oProfile->getUrl(), 
-			$oProfile->getThumb(),
-			$oProfile->getUnit()
-		);
+        return array(
+            $oProfile->getDisplayName(),
+            $oProfile->getUrl(),
+            $oProfile->getThumb(),
+            $oProfile->getUnit()
+        );
     }
 
     protected function _getAuthorObject($iAuthorId = 0)
     {
-    	bx_import('BxDolProfile');
-		$oProfile = BxDolProfile::getInstance($iAuthorId);
-		if (!$oProfile) {
-			bx_import('BxDolProfileUndefined');
-			$oProfile = BxDolProfileUndefined::getInstance();
-		}
+        bx_import('BxDolProfile');
+        $oProfile = BxDolProfile::getInstance($iAuthorId);
+        if (!$oProfile) {
+            bx_import('BxDolProfileUndefined');
+            $oProfile = BxDolProfileUndefined::getInstance();
+        }
 
-		return $oProfile;
+        return $oProfile;
     }
 
     protected function _prepareTextForEdit ($s)
@@ -815,72 +814,72 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         return $s;
     }
 
-    protected function _prepareTextForSave ($s) 
+    protected function _prepareTextForSave ($s)
     {
-    	$iDataAction = $this->isNl2br() ? BX_DATA_TEXT_MULTILINE : BX_DATA_HTML;
-		return bx_process_input($s, $iDataAction);
+        $iDataAction = $this->isNl2br() ? BX_DATA_TEXT_MULTILINE : BX_DATA_HTML;
+        return bx_process_input($s, $iDataAction);
     }
 
     protected function _prepareTextForOutput ($s)
     {
-    	$sHttp = '';
-		$sPattern = "/((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*\.)+(aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|[a-z]{2})|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&amp;]*)?)?(#[a-z][a-z0-9_]*)?/";
-    	$aMatches = array();
-    	if(preg_match($sPattern, $s, $aMatches) && empty($aMatches[1]))
-    		$sHttp = 'http://';
+        $sHttp = '';
+        $sPattern = "/((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*\.)+(aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|[a-z]{2})|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&amp;]*)?)?(#[a-z][a-z0-9_]*)?/";
+        $aMatches = array();
+        if(preg_match($sPattern, $s, $aMatches) && empty($aMatches[1]))
+            $sHttp = 'http://';
 
-		$s = bx_process_output($s, BX_DATA_HTML);
-		$s = preg_replace($sPattern, '<a href="' . $sHttp . '$0" target="_blank">$0</a>', $s);
+        $s = bx_process_output($s, BX_DATA_HTML);
+        $s = preg_replace($sPattern, '<a href="' . $sHttp . '$0" target="_blank">$0</a>', $s);
 
-		return $s; 
+        return $s;
     }
 
-	protected function _prepareParams(&$aBp, &$aDp)
+    protected function _prepareParams(&$aBp, &$aDp)
     {
-    	$aBp['type'] = isset($aBp['type']) && !empty($aBp['type']) ? $aBp['type'] : $this->_sBrowseType;
-    	$aBp['filter'] = isset($aBp['filter']) && !empty($aBp['filter']) ? $aBp['filter'] : $this->_sBrowseFilter;
-    	$aBp['parent_id'] = isset($aBp['parent_id']) ? $aBp['parent_id'] : 0;
-    	$aBp['start'] = isset($aBp['start']) ? $aBp['start'] : -1;
-    	$aBp['per_view'] = isset($aBp['per_view']) ? $aBp['per_view'] : -1;
-    	$aBp['order']['by'] = isset($aBp['order_by']) ? $aBp['order_by'] : $this->_aOrder['by'];
-    	$aBp['order']['way'] = isset($aBp['order_way']) ? $aBp['order_way'] : $this->_aOrder['way'];
+        $aBp['type'] = isset($aBp['type']) && !empty($aBp['type']) ? $aBp['type'] : $this->_sBrowseType;
+        $aBp['filter'] = isset($aBp['filter']) && !empty($aBp['filter']) ? $aBp['filter'] : $this->_sBrowseFilter;
+        $aBp['parent_id'] = isset($aBp['parent_id']) ? $aBp['parent_id'] : 0;
+        $aBp['start'] = isset($aBp['start']) ? $aBp['start'] : -1;
+        $aBp['per_view'] = isset($aBp['per_view']) ? $aBp['per_view'] : -1;
+        $aBp['order']['by'] = isset($aBp['order_by']) ? $aBp['order_by'] : $this->_aOrder['by'];
+        $aBp['order']['way'] = isset($aBp['order_way']) ? $aBp['order_way'] : $this->_aOrder['way'];
 
-    	$aDp['type'] = isset($aDp['type']) && !empty($aDp['type']) ? $aDp['type'] : $this->_sDisplayType;
+        $aDp['type'] = isset($aDp['type']) && !empty($aDp['type']) ? $aDp['type'] : $this->_sDisplayType;
 
-		switch($aDp['type']) {
-			case BX_CMT_DISPLAY_FLAT:
-				$aBp['vparent_id'] = -1;
-				$aBp['per_view'] = $aBp['per_view'] != -1 ? $aBp['per_view'] : $this->getPerView(0);
-				break;
+        switch($aDp['type']) {
+            case BX_CMT_DISPLAY_FLAT:
+                $aBp['vparent_id'] = -1;
+                $aBp['per_view'] = $aBp['per_view'] != -1 ? $aBp['per_view'] : $this->getPerView(0);
+                break;
 
-			case BX_CMT_DISPLAY_THREADED:
-				$aBp['per_view'] = $aBp['per_view'] != -1 ? $aBp['per_view'] : $this->getPerView($aBp['vparent_id']);
-				break;
-		}
-
-		switch ($aBp['type']) {
-			case BX_CMT_BROWSE_POPULAR:
-				$aBp['order'] = array(
-					'by' => BX_CMT_ORDER_BY_POPULAR,
-					'way' => BX_CMT_ORDER_WAY_DESC
-				);
-				break;
-		}
+            case BX_CMT_DISPLAY_THREADED:
+                $aBp['per_view'] = $aBp['per_view'] != -1 ? $aBp['per_view'] : $this->getPerView($aBp['vparent_id']);
+                break;
+        }
 
-		$aBp['count'] = $this->getCommentsCount($this->_iId, $aBp['vparent_id'], $aBp['filter']);
-		if($aBp['start'] != -1)
-			return;
+        switch ($aBp['type']) {
+            case BX_CMT_BROWSE_POPULAR:
+                $aBp['order'] = array(
+                    'by' => BX_CMT_ORDER_BY_POPULAR,
+                    'way' => BX_CMT_ORDER_WAY_DESC
+                );
+                break;
+        }
 
-		$aBp['start'] = 0;
-		if($aBp['type'] == BX_CMT_BROWSE_TAIL) {
-			$aBp['start'] = $aBp['count'] - $aBp['per_view'];
-			if($aBp['start'] < 0) {
-    			$aBp['per_view'] += $aBp['start'];
-    			$aBp['start'] = 0;
-			}
-		}
+        $aBp['count'] = $this->getCommentsCount($this->_iId, $aBp['vparent_id'], $aBp['filter']);
+        if($aBp['start'] != -1)
+            return;
+
+        $aBp['start'] = 0;
+        if($aBp['type'] == BX_CMT_BROWSE_TAIL) {
+            $aBp['start'] = $aBp['count'] - $aBp['per_view'];
+            if($aBp['start'] < 0) {
+                $aBp['per_view'] += $aBp['start'];
+                $aBp['start'] = 0;
+            }
+        }
 
-		$this->_setUserChoice($aDp['type'], $aBp['type'], $aBp['filter']);
+        $this->_setUserChoice($aDp['type'], $aBp['type'], $aBp['filter']);
     }
 
     protected function _triggerComment()
@@ -896,66 +895,66 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
         return $this->_oQuery->updateTriggerTable($iId, $iCount);
     }
 
-	/**
+    /**
      * Replace provided markers in a string
      * @param $mixed string or array to replace markers in
      * @return string where all occured markers are replaced
-     */ 
-    protected function _replaceMarkers ($mixed) 
+     */
+    protected function _replaceMarkers ($mixed)
     {
         return bx_replace_markers($mixed, $this->_aMarkers);
     }
 
     protected function _getUserChoice()
     {
-    	$mixedDp = $mixedBpType = $mixedBpFilter = false;
-    	if(!isLogged())
-    		return array($mixedDp, $mixedBpType, $mixedBpFilter);
+        $mixedDp = $mixedBpType = $mixedBpFilter = false;
+        if(!isLogged())
+            return array($mixedDp, $mixedBpType, $mixedBpFilter);
 
-    	$iUserId = $this->_getAuthorId();
+        $iUserId = $this->_getAuthorId();
 
-    	bx_import('BxDolSession');
-    	$oSession = BxDolSession::getInstance();
+        bx_import('BxDolSession');
+        $oSession = BxDolSession::getInstance();
 
-    	$mixedDp = $oSession->getValue($this->_sDpSessionKey . $iUserId);
-    	$mixedBpType = $oSession->getValue($this->_sBpSessionKeyType . $iUserId);
-    	$mixedBpFilter = $oSession->getValue($this->_sBpSessionKeyFilter . $iUserId);
+        $mixedDp = $oSession->getValue($this->_sDpSessionKey . $iUserId);
+        $mixedBpType = $oSession->getValue($this->_sBpSessionKeyType . $iUserId);
+        $mixedBpFilter = $oSession->getValue($this->_sBpSessionKeyFilter . $iUserId);
 
-    	return array($mixedDp, $mixedBpType, $mixedBpFilter);
+        return array($mixedDp, $mixedBpType, $mixedBpFilter);
     }
 
     protected function _setUserChoice($sDp, $sBpType, $sBpFilter)
     {
-    	if(!isLogged())
-    		return;
+        if(!isLogged())
+            return;
+
+        $iUserId = $this->_getAuthorId();
 
-    	$iUserId = $this->_getAuthorId();
+        bx_import('BxDolSession');
+        $oSession = BxDolSession::getInstance();
 
-    	bx_import('BxDolSession');
-    	$oSession = BxDolSession::getInstance();
+        if(!empty($sDp))
+            $oSession->setValue($this->_sDpSessionKey . $iUserId, $sDp);
 
-    	if(!empty($sDp))
-    		$oSession->setValue($this->_sDpSessionKey . $iUserId, $sDp);
+        if(!empty($sBpType))
+            $oSession->setValue($this->_sBpSessionKeyType . $iUserId, $sBpType);
 
-    	if(!empty($sBpType))
-	    	$oSession->setValue($this->_sBpSessionKeyType . $iUserId, $sBpType);
-	    	
-	    if(!empty($sBpFilter))
-	    	$oSession->setValue($this->_sBpSessionKeyFilter . $iUserId, $sBpFilter);
+        if(!empty($sBpFilter))
+            $oSession->setValue($this->_sBpSessionKeyFilter . $iUserId, $sBpFilter);
     }
 
-	protected function _sendNotificationEmail($iCmtId, $iCmtParentId)
-	{
-		$aCmt = $this->getCommentRow($iCmtId);
-		$aCmtParent = $this->getCommentRow($iCmtParentId);
-		if(empty($aCmt) || !is_array($aCmt) || empty($aCmtParent) || !is_array($aCmtParent) || (int)$aCmt['cmt_author_id'] == (int)$aCmtParent['cmt_author_id'])
-			return;
+    protected function _sendNotificationEmail($iCmtId, $iCmtParentId)
+    {
+        $aCmt = $this->getCommentRow($iCmtId);
+        $aCmtParent = $this->getCommentRow($iCmtParentId);
+        if(empty($aCmt) || !is_array($aCmt) || empty($aCmtParent) || !is_array($aCmtParent) || (int)$aCmt['cmt_author_id'] == (int)$aCmtParent['cmt_author_id'])
+            return;
 
-		$oProfile = $this->_getAuthorObject($aCmtParent['cmt_author_id']);
+        $oProfile = $this->_getAuthorObject($aCmtParent['cmt_author_id']);
 
-		bx_import('BxDolAccount');
-		$iAccount = $oProfile->getAccountId();
-    	$aAccount = BxDolAccount::getInstance($iAccount)->getInfo();
+        bx_import('BxDolAccount');
+        $iAccount = $oProfile->getAccountId();
+        $aAccount = BxDolAccount::getInstance($iAccount)->getInfo();
 
         $aPlus = array();
         $aPlus['reply_text'] = bx_process_output($aCmt['cmt_text']);
@@ -968,4 +967,3 @@ class BxDolCmts extends BxDol implements iBxDolReplaceable
 }
 
 /** @} */
-

+ 69 - 70
inc/classes/BxDolCmtsQuery.php

@@ -14,7 +14,7 @@ bx_import('BxDolDb');
  */
 class BxDolCmtsQuery extends BxDolDb
 {
-	protected $_oMain;
+    protected $_oMain;
 
     protected $_sTable;
     protected $_sTriggerTable;
@@ -27,9 +27,9 @@ class BxDolCmtsQuery extends BxDolDb
 
     function __construct(&$oMain)
     {
-    	$this->_oMain = $oMain;
+        $this->_oMain = $oMain;
 
-    	$aSystem = $this->_oMain->getSystemInfo();
+        $aSystem = $this->_oMain->getSystemInfo();
         $this->_sTable = $aSystem['table'];
         $this->_sTriggerTable = $aSystem['trigger_table'];
         $this->_sTriggerFieldId = $aSystem['trigger_field_id'];
@@ -47,66 +47,67 @@ class BxDolCmtsQuery extends BxDolDb
         return $this->_sTable;
     }
 
-	function getCommentsCount ($iId, $iCmtVParentId = 0, $iAuthorId = 0, $sFilter = '') {
-		$sWhereParent = '';
+    function getCommentsCount ($iId, $iCmtVParentId = 0, $iAuthorId = 0, $sFilter = '')
+    {
+        $sWhereParent = '';
         if((int)$iCmtVParentId >= 0)
-        	$sWhereParent = $this->prepare(" AND `{$this->_sTable}`.`cmt_vparent_id` = ?", $iCmtVParentId);
+            $sWhereParent = $this->prepare(" AND `{$this->_sTable}`.`cmt_vparent_id` = ?", $iCmtVParentId);
 
         $sJoin = '';
-		if(in_array($sFilter, array(BX_CMT_FILTER_FRIENDS, BX_CMT_FILTER_SUBSCRIPTIONS))) {
-			bx_import('BxDolConnection');
-			$oConnection = BxDolConnection::getObjectInstance($this->_oMain->getConnectionObject($sFilter));
-			
-			$aQueryParts = $oConnection->getConnectedContentAsSQLParts($this->_sTable, 'cmt_author_id', $iAuthorId);
-			$sJoin .= ' ' . $aQueryParts['join'];
-		}
-
-		$sQuery = $this->prepare("SELECT 
-				COUNT(*) 
-			FROM `{$this->_sTable}`
-			$sJoin 
-			WHERE `{$this->_sTable}`.`cmt_object_id` = ?" . $sWhereParent, $iId);
-
-		return (int)$this->getOne($sQuery);
-	}
+        if(in_array($sFilter, array(BX_CMT_FILTER_FRIENDS, BX_CMT_FILTER_SUBSCRIPTIONS))) {
+            bx_import('BxDolConnection');
+            $oConnection = BxDolConnection::getObjectInstance($this->_oMain->getConnectionObject($sFilter));
+
+            $aQueryParts = $oConnection->getConnectedContentAsSQLParts($this->_sTable, 'cmt_author_id', $iAuthorId);
+            $sJoin .= ' ' . $aQueryParts['join'];
+        }
+
+        $sQuery = $this->prepare("SELECT
+                COUNT(*)
+            FROM `{$this->_sTable}`
+            $sJoin
+            WHERE `{$this->_sTable}`.`cmt_object_id` = ?" . $sWhereParent, $iId);
+
+        return (int)$this->getOne($sQuery);
+    }
 
     function getComments ($iId, $iCmtVParentId = 0, $iAuthorId = 0, $sFilter = '', $aOrder = array(), $iStart = 0, $iCount = -1)
     {
         $sFields = $sJoin = "";
 
-	    $oVote = $this->_oMain->getVoteObject(0);
+        $oVote = $this->_oMain->getVoteObject(0);
         if($oVote !== false) {
-        	$aSql = $oVote->getSqlParts($this->_sTable, 'cmt_id');
+            $aSql = $oVote->getSqlParts($this->_sTable, 'cmt_id');
 
-        	$sFields .= $aSql['fields'];
-        	$sJoin .= $aSql['join'];
+            $sFields .= $aSql['fields'];
+            $sJoin .= $aSql['join'];
         }
 
         $sWhereParent = '';
         if((int)$iCmtVParentId >= 0)
-        	$sWhereParent = $this->prepare(" AND `{$this->_sTable}`.`cmt_vparent_id` = ?", $iCmtVParentId);
+            $sWhereParent = $this->prepare(" AND `{$this->_sTable}`.`cmt_vparent_id` = ?", $iCmtVParentId);
 
-		if(in_array($sFilter, array(BX_CMT_FILTER_FRIENDS, BX_CMT_FILTER_SUBSCRIPTIONS))) {
-			bx_import('BxDolConnection');
-			$oConnection = BxDolConnection::getObjectInstance($this->_oMain->getConnectionObject($sFilter));
-			
-			$aQueryParts = $oConnection->getConnectedContentAsSQLParts($this->_sTable, 'cmt_author_id', $iAuthorId);
-			$sJoin .= ' ' . $aQueryParts['join'];
-		}
+        if(in_array($sFilter, array(BX_CMT_FILTER_FRIENDS, BX_CMT_FILTER_SUBSCRIPTIONS))) {
+            bx_import('BxDolConnection');
+            $oConnection = BxDolConnection::getObjectInstance($this->_oMain->getConnectionObject($sFilter));
+
+            $aQueryParts = $oConnection->getConnectedContentAsSQLParts($this->_sTable, 'cmt_author_id', $iAuthorId);
+            $sJoin .= ' ' . $aQueryParts['join'];
+        }
 
         $sOder = " ORDER BY `{$this->_sTable}`.`cmt_time` ASC";
         if(isset($aOrder['by']) && isset($aOrder['way'])) {
-        	$aOrder['way'] = strtoupper(in_array($aOrder['way'], array(BX_CMT_ORDER_WAY_ASC, BX_CMT_ORDER_WAY_DESC)) ? $aOrder['way'] : BX_CMT_ORDER_WAY_ASC);
+            $aOrder['way'] = strtoupper(in_array($aOrder['way'], array(BX_CMT_ORDER_WAY_ASC, BX_CMT_ORDER_WAY_DESC)) ? $aOrder['way'] : BX_CMT_ORDER_WAY_ASC);
 
-        	switch($aOrder['by']) {
-        		case BX_CMT_ORDER_BY_DATE:
-        			$sOder = " ORDER BY `{$this->_sTable}`.`cmt_time` " . $aOrder['way'];
-        			break;
+            switch($aOrder['by']) {
+                case BX_CMT_ORDER_BY_DATE:
+                    $sOder = " ORDER BY `{$this->_sTable}`.`cmt_time` " . $aOrder['way'];
+                    break;
 
-        		case BX_CMT_ORDER_BY_POPULAR:
-        			$sOder = " ORDER BY `{$this->_sTable}`.`cmt_rate` " . $aOrder['way'];
-        			break;
-	        }
+                case BX_CMT_ORDER_BY_POPULAR:
+                    $sOder = " ORDER BY `{$this->_sTable}`.`cmt_rate` " . $aOrder['way'];
+                    break;
+            }
         }
 
         $sLimit = $iCount != -1 ? $this->prepare(" LIMIT ?, ?", (int)$iStart, (int)$iCount) : '';
@@ -133,12 +134,12 @@ class BxDolCmtsQuery extends BxDolDb
     {
         $sFields = $sJoin = "";
 
-    	$oVote = $this->_oMain->getVoteObject($iCmtId);
+        $oVote = $this->_oMain->getVoteObject($iCmtId);
         if($oVote !== false) {
-        	$aSql = $oVote->getSqlParts($this->_sTable, 'cmt_id');
+            $aSql = $oVote->getSqlParts($this->_sTable, 'cmt_id');
 
-        	$sFields .= $aSql['fields'];
-        	$sJoin .= $aSql['join'];
+            $sFields .= $aSql['fields'];
+            $sJoin .= $aSql['join'];
         }
 
         $sQuery = $this->prepare("SELECT
@@ -171,17 +172,17 @@ class BxDolCmtsQuery extends BxDolDb
         if (!$this->query($sQuery))
             return false;
 
-		if($iCmtParentId) 
-        	$this->updateRepliesCount($iCmtParentId, -1);
+        if($iCmtParentId)
+            $this->updateRepliesCount($iCmtParentId, -1);
 
         return true;
     }
 
-	function saveImages($iSystemId, $iCmtId, $iImageId)
-	{
-		$sQuery = $this->prepare("INSERT IGNORE INTO `{$this->_sTableImages2Entries}` SET `system_id`=?, `cmt_id`=?, `image_id`=?", $iSystemId, $iCmtId, $iImageId);
-		return (int)$this->query($sQuery) > 0;
-	}
+    function saveImages($iSystemId, $iCmtId, $iImageId)
+    {
+        $sQuery = $this->prepare("INSERT IGNORE INTO `{$this->_sTableImages2Entries}` SET `system_id`=?, `cmt_id`=?, `image_id`=?", $iSystemId, $iCmtId, $iImageId);
+        return (int)$this->query($sQuery) > 0;
+    }
 
     function getImages($iSystemId, $iCmtId, $iId = false)
     {
@@ -195,38 +196,37 @@ class BxDolCmtsQuery extends BxDolDb
         if (false !== $iId) {
             $sWhere .= $this->prepare(" AND `c`.`cmt_object_id` = ?", $iId);
             $sJoin .= " INNER JOIN `{$this->_sTable}` AS `c` ON (`i`.`cmt_id` = `c`.`cmt_id`) ";
-        }        
+        }
 
-    	return $this->getAll("SELECT * FROM `{$this->_sTableImages2Entries}` AS `i` " . $sJoin . " WHERE 1 " . $sWhere);
+        return $this->getAll("SELECT * FROM `{$this->_sTableImages2Entries}` AS `i` " . $sJoin . " WHERE 1 " . $sWhere);
     }
 
-	function deleteImages($iSystemId, $iCmtId)
-	{
+    function deleteImages($iSystemId, $iCmtId)
+    {
         $sWhereAddon = '';
         if (false !== $iCmtId)
             $sWhereAddon = $this->prepare(" AND `cmt_id` = ? ", $iCmtId);
 
-		$sQuery = $this->prepare("DELETE FROM `{$this->_sTableImages2Entries}` WHERE `system_id` = ?", $iSystemId);
+        $sQuery = $this->prepare("DELETE FROM `{$this->_sTableImages2Entries}` WHERE `system_id` = ?", $iSystemId);
         $sQuery .= $sWhereAddon;
 
-    	return $this->query($sQuery);
-	}
+        return $this->query($sQuery);
+    }
 
     function updateRepliesCount($iCmtId, $iCount)
     {
-    	$sQuery = $this->prepare("UPDATE `{$this->_sTable}` SET `cmt_replies`=`cmt_replies`+? WHERE `cmt_id`=? LIMIT 1", $iCount, $iCmtId);
-		return $this->query($sQuery);
+        $sQuery = $this->prepare("UPDATE `{$this->_sTable}` SET `cmt_replies`=`cmt_replies`+? WHERE `cmt_id`=? LIMIT 1", $iCount, $iCmtId);
+        return $this->query($sQuery);
     }
 
     function deleteAuthorComments ($iAuthorId, &$aFiles = null)
     {
-    	$aSystem = $this->_oMain->getSystemInfo();
+        $aSystem = $this->_oMain->getSystemInfo();
 
         $isDelOccured = 0;
         $sQuery = $this->prepare("SELECT `cmt_id`, `cmt_parent_id` FROM {$this->_sTable} WHERE `cmt_author_id` = ? AND `cmt_replies` = 0", $iAuthorId);
         $a = $this->getAll ($sQuery);
-        for ( reset($a) ; list (, $r) = each ($a) ; )
-        {
+        for ( reset($a) ; list (, $r) = each ($a) ; ) {
             $sQuery = $this->prepare("DELETE FROM {$this->_sTable} WHERE `cmt_id` = ?", $r['cmt_id']);
             $this->query ($sQuery);
 
@@ -235,7 +235,7 @@ class BxDolCmtsQuery extends BxDolDb
 
             $aFilesMore = $this->convertImagesArray($this->getImages($aSystem['system_id'], $r['cmt_id']));
             $this->deleteImages($aSystem['system_id'], $r['cmt_id']);
-            if ($aFilesMore && null !== $aFiles) 
+            if ($aFilesMore && null !== $aFiles)
                 $aFiles = array_merge($aFiles, $aFilesMore);
 
             $isDelOccured = 1;
@@ -279,7 +279,7 @@ class BxDolCmtsQuery extends BxDolDb
         $this->query ($sQuery);
     }
 
-	function getObjectTitle($iId)
+    function getObjectTitle($iId)
     {
         $sQuery = $this->prepare("SELECT `{$this->_sTriggerFieldTitle}` FROM `{$this->_sTriggerTable}` WHERE `{$this->_sTriggerFieldId}` = ? LIMIT 1", $iId);
         return $this->getOne($sQuery);
@@ -291,7 +291,7 @@ class BxDolCmtsQuery extends BxDolDb
         return $this->query($sQuery);
     }
 
-    protected function convertImagesArray($a) 
+    protected function convertImagesArray($a)
     {
         if (!$a || !is_array($a))
             return array();
@@ -304,4 +304,3 @@ class BxDolCmtsQuery extends BxDolDb
 }
 
 /** @} */
-

+ 10 - 11
inc/classes/BxDolConfig.php

@@ -25,7 +25,7 @@ class BxDolConfig extends BxDol implements iBxDolSingleton
     /**
      * constructor
      */
-    protected function __construct() 
+    protected function __construct()
     {
         if(isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
@@ -44,7 +44,7 @@ class BxDolConfig extends BxDol implements iBxDolSingleton
     /**
      * Prevent cloning the instance
      */
-    public function __clone() 
+    public function __clone()
     {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
@@ -53,7 +53,7 @@ class BxDolConfig extends BxDol implements iBxDolSingleton
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() 
+    public static function getInstance()
     {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolConfig();
@@ -63,7 +63,7 @@ class BxDolConfig extends BxDol implements iBxDolSingleton
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    function init() 
+    function init()
     {
         $this->aUrlDynamic = array();
 
@@ -76,17 +76,17 @@ class BxDolConfig extends BxDol implements iBxDolSingleton
         );
     }
 
-    function get($sGroup, $sName) 
+    function get($sGroup, $sName)
     {
         return $this->{$this->getVarName($sGroup)}[$sName];
     }
 
-    function getGroup($sGroup) 
+    function getGroup($sGroup)
     {
         return $this->{$this->getVarName($sGroup)};
     }
 
-    function set($sGroup, $sName, $sValue, $bDefine = false) 
+    function set($sGroup, $sName, $sValue, $bDefine = false)
     {
         if($bDefine)
             define($this->getDefineName($sGroup, $sName), $sValue);
@@ -94,7 +94,7 @@ class BxDolConfig extends BxDol implements iBxDolSingleton
             $this->{$this->getVarName($sGroup)}[$sName] = $sValue;
     }
 
-    function setGroup($sGroup, $aValue, $bDefine = false) 
+    function setGroup($sGroup, $aValue, $bDefine = false)
     {
         if($bDefine)
             foreach($aValue as $sName => $sValue)
@@ -109,12 +109,12 @@ class BxDolConfig extends BxDol implements iBxDolSingleton
         }
     }
 
-    private function getVarName($sVar) 
+    private function getVarName($sVar)
     {
         return 'a' . bx_gen_method_name($sVar);
     }
 
-    private function getDefineName() 
+    private function getDefineName()
     {
         $aArgs = func_get_args();
         return 'BX_' . strtoupper(implode('_', $aArgs));
@@ -122,4 +122,3 @@ class BxDolConfig extends BxDol implements iBxDolSingleton
 }
 
 /** @} */
-

+ 101 - 77
inc/classes/BxDolConnection.php

@@ -9,16 +9,14 @@
 
 bx_import('BxDolConnectionQuery');
 
-
 /**
  * Default limit for connections lists
  */
 define('BX_CONNECTIONS_LIST_LIMIT', 1000);
 
-
 /**
  * Connections order: no order
- */ 
+ */
 define('BX_CONNECTIONS_ORDER_NONE', 0);
 
 /**
@@ -31,7 +29,6 @@ define('BX_CONNECTIONS_ORDER_ADDED_ASC', 1);
  */
 define('BX_CONNECTIONS_ORDER_ADDED_DESC', 2);
 
-
 /**
  * Connection type: one-way
  */
@@ -42,7 +39,6 @@ define('BX_CONNECTIONS_TYPE_ONE_WAY', 'one-way');
  */
 define('BX_CONNECTIONS_TYPE_MUTUAL', 'mutual');
 
-
 /**
  * Connections content type: content
  */
@@ -58,25 +54,25 @@ define('BX_CONNECTIONS_CONTENT_TYPE_INITIATORS', 'initiators');
  */
 define('BX_CONNECTIONS_CONTENT_TYPE_COMMON', 'common');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section connection Connection
  * @ref BxDolConnection
  */
 
 /**
- * Connection is usefull when you need to organize some sorts of connections between different content, 
+ * Connection is usefull when you need to organize some sorts of connections between different content,
  * for example: friends, contacts, favorites, block lists, subscriptions, etc.
- * 
- * Two types of connections are supported one way connections (block list, favourites) and mutual (friends). 
+ *
+ * Two types of connections are supported one way connections (block list, favourites) and mutual (friends).
  *
  * For automatic handling of connections (like, add/remove connection in frontend) refer to JS function: @see bx_conn_action()
- * 
+ *
  * @section connection_create Creating the Connection object:
  *
  * Step 1:
  * Add record to 'sys_objects_connection' table:
- * - object: name of the connection object, in the format: vendor prefix, underscore, module prefix, underscore, internal identifier or nothing; 
+ * - object: name of the connection object, in the format: vendor prefix, underscore, module prefix, underscore, internal identifier or nothing;
  *           for example: bx_blogs_favorites - favorite blogs for users in blogs module.
  * - table: table name with connections, see step 2
  * - type: 'one-way' or 'mutual'
@@ -90,7 +86,7 @@ define('BX_CONNECTIONS_CONTENT_TYPE_COMMON', 'common');
  *   `id` int(11) NOT NULL AUTO_INCREMENT,
  *   `initiator` int(11) NOT NULL,
  *   `content` int(11) NOT NULL,
- *   `mutual` tinyint(4) NOT NULL, -- can re removed for one-way connections 
+ *   `mutual` tinyint(4) NOT NULL, -- can re removed for one-way connections
  *   `added` int(10) unsigned NOT NULL,
  *   PRIMARY KEY (`id`),
  *   UNIQUE KEY `initiator` (`initiator`,`content`),
@@ -100,7 +96,7 @@ define('BX_CONNECTIONS_CONTENT_TYPE_COMMON', 'common');
  *
  *
  * @section example Example of usage
- * 
+ *
  * Check if two profiles are friends:
  * @code
  *   bx_import('BxDolConnection'); // import connection class
@@ -116,10 +112,10 @@ define('BX_CONNECTIONS_CONTENT_TYPE_COMMON', 'common');
  *   if ($oConnectionFriends) // check if connections is available for using
  *       print_r($oConnection->getConnectedContent(100, 1)); // print array of friends IDs of 100's profile
  * @endcode
- * 
+ *
  */
-class BxDolConnection extends BxDol implements iBxDolFactoryObject {
-
+class BxDolConnection extends BxDol implements iBxDolFactoryObject
+{
     protected $_sObject;
     protected $_aObject;
     protected $_oQuery;
@@ -129,7 +125,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * Constructor
      * @param $aObject array of connection options
      */
-    protected function __construct($aObject) {
+    protected function __construct($aObject)
+    {
         parent::__construct();
 
         $this->_sObject = $aObject['object'];
@@ -144,14 +141,14 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $sObject object name
      * @return object instance or false on error
      */
-    static public function getObjectInstance($sObject) {
-
+    static public function getObjectInstance($sObject)
+    {
         if (!$sObject)
             return false;
 
         if (isset($GLOBALS['bxDolClasses']['BxDolConnection!'.$sObject]))
             return $GLOBALS['bxDolClasses']['BxDolConnection!'.$sObject];
-        
+
         $aObject = BxDolConnectionQuery::getConnectionObject($sObject);
         if (!$aObject || !is_array($aObject))
             return false;
@@ -159,9 +156,9 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
         $sClass = empty($aObject['override_class_name']) ? 'BxDolConnection' : $aObject['override_class_name'];
         if (!empty($aObject['override_class_file']))
             require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
-        else    
+        else
             bx_import($sClass);
-        
+
         $o = new $sClass($aObject);
 
         return ($GLOBALS['bxDolClasses']['BxDolConnection!'.$sObject] = $o);
@@ -171,8 +168,9 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * Add new connection.
      * @param $iContent content to make connection to, in most cases some content id, or other profile id in case of friends
      * @return array
-     */ 
-    public function actionAdd ($iContent = 0) {
+     */
+    public function actionAdd ($iContent = 0)
+    {
         if (!$iContent)
             $iContent = bx_process_input($_POST['id'], BX_DATA_INT);
 
@@ -183,14 +181,15 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * Remove connection.
      * @param $iContent content to make connection to, in most cases some content id, or other profile id in case of friends
      * @return array
-     */ 
-    public function actionRemove ($iContent = 0) {
+     */
+    public function actionRemove ($iContent = 0)
+    {
         if (!$iContent)
             $iContent = bx_process_input($_POST['id'], BX_DATA_INT);
 
         $a = $this->actionReject($iContent);
         if (false == $a['err'])
-            return $a;     
+            return $a;
 
         return $this->_action (bx_get_logged_profile_id(), $iContent, 'removeConnection', '_sys_conn_err_connection_does_not_exists');
     }
@@ -199,15 +198,17 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * Reject connection request.
      * @param $iContent content to make connection to, in most cases some content id, or other profile id in case of friends
      * @return array
-     */ 
-    public function actionReject ($iContent = 0) {
+     */
+    public function actionReject ($iContent = 0)
+    {
         if (!$iContent)
             $iContent = bx_process_input($_POST['id'], BX_DATA_INT);
 
         return $this->_action ($iContent, bx_get_logged_profile_id(), 'removeConnection', '_sys_conn_err_connection_does_not_exists');
     }
 
-    protected function _action ($iInitiator, $iContent, $sMethod, $sErrorKey, $isMutual = false) {
+    protected function _action ($iInitiator, $iContent, $sMethod, $sErrorKey, $isMutual = false)
+    {
         bx_import('BxDolLanguages');
 
         if (!$iContent || !$iInitiator)
@@ -223,12 +224,13 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
         return array ('err' => false, 'msg' => _t('_sys_conn_msg_success'));
     }
 
-    public function outputActionResult ($mixed, $sFormat = 'json') {
+    public function outputActionResult ($mixed, $sFormat = 'json')
+    {
         switch ($sFormat) {
             case 'json':
             default:
                 header('Content-Type: application/json; charset=utf-8');
-                echo json_encode($mixed);  
+                echo json_encode($mixed);
         }
         exit;
     }
@@ -238,15 +240,16 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iInitiator initiator of the connection, in most cases some profile id
      * @param $iContent content to make connection to, in most cases some content id, or other profile id in case of friends
      * @return true - if connection was added, false - if connection already exists or error occured
-     */ 
-    public function addConnection ($iInitiator, $iContent) {
+     */
+    public function addConnection ($iInitiator, $iContent)
+    {
         $iMutual = 0;
         if (!$this->_oQuery->addConnection((int)$iInitiator, (int)$iContent, $iMutual))
-            return false; 
-    
+            return false;
+
         bx_alert($this->_sObject, 'connection_added', 0, getLoggedId(), array(
-            'initiator' => (int)$iInitiator, 
-            'content' => (int)$iContent, 
+            'initiator' => (int)$iInitiator,
+            'content' => (int)$iContent,
             'mutual' => (int)$iMutual,
             'object' => $this,
         ));
@@ -260,7 +263,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iContent connected content or other profile id in case of friends
      * @return true - if connection was removed, false - if connection isn't exist or error occured
      */
-    public function removeConnection ($iInitiator, $iContent) {
+    public function removeConnection ($iInitiator, $iContent)
+    {
         if (!($aConnection = $this->_oQuery->getConnection((int)$iInitiator, (int)$iContent))) // connection doesn't exist
             return false;
 
@@ -268,8 +272,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
             return false;
 
         bx_alert($this->_sObject, 'connection_removed', 0, getLoggedId(), array(
-            'initiator' => (int)$iInitiator, 
-            'content' => (int)$iContent, 
+            'initiator' => (int)$iInitiator,
+            'content' => (int)$iContent,
             'mutual' => isset($aConnection['mutual']) ? $aConnection['mutual'] : 0,
             'object' => $this,
         ));
@@ -284,7 +288,7 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iId2 second content or initiator only in case of BX_CONNECTIONS_CONTENT_TYPE_COMMON content type
      * @param $isMutual get mutual connections only
      * @return array of available connections
-     */    
+     */
     public function getConnectionsAsArray ($sContentType, $iId1, $iId2, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE)
     {
         if (BX_CONNECTIONS_CONTENT_TYPE_COMMON == $sContentType)
@@ -301,11 +305,12 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
     /**
      * Get common content IDs between two initiators
      * @param $iInitiator1 one initiator
-     * @param $iInitiator2 second initiator 
+     * @param $iInitiator2 second initiator
      * @param $isMutual get mutual connections only
      * @return array of available connections
-     */    
-    public function getCommonContent ($iInitiator1, $iInitiator2, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE) {
+     */
+    public function getCommonContent ($iInitiator1, $iInitiator2, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE)
+    {
         return $this->_oQuery->getCommonContent($iInitiator1, $iInitiator2, $isMutual, $iStart, $iLimit, $iOrder);
     }
 
@@ -314,8 +319,9 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iInitiator initiator of the connection
      * @param $isMutual get mutual connections only
      * @return array of available connections
-     */    
-    public function getConnectedContent ($iInitiator, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE) {
+     */
+    public function getConnectedContent ($iInitiator, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE)
+    {
         return $this->_oQuery->getConnectedContent($iInitiator, $isMutual, $iStart, $iLimit, $iOrder);
     }
 
@@ -324,15 +330,16 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iContent content of the connection
      * @param $isMutual get mutual connections only
      * @return array of available connections
-     */    
-    public function getConnectedInitiators ($iContent, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE) {
+     */
+    public function getConnectedInitiators ($iContent, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE)
+    {
         return $this->_oQuery->getConnectedInitiators($iContent, $isMutual, $iStart, $iLimit, $iOrder);
     }
 
     /**
      * Similar to getConnectionsAsArray, but for getCommonContentAsSQLParts, getConnectedContentAsSQLParts or getConnectedInitiatorsAsSQLParts methods
      * @see getConnectionsAsArray
-     */    
+     */
     public function getConnectionsAsSQLParts ($sContentType, $sContentTable, $sContentField, $iId1, $iId2, $isMutual = false)
     {
         if (BX_CONNECTIONS_CONTENT_TYPE_COMMON == $sContentType)
@@ -354,7 +361,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $isMutual get mutual connections only
      * @return array of SQL string parts, for now 'join' part only is returned
      */
-    public function getCommonContentAsSQLParts ($sContentTable, $sContentField, $iInitiator1, $iInitiator2, $isMutual = false) {
+    public function getCommonContentAsSQLParts ($sContentTable, $sContentField, $iInitiator1, $iInitiator2, $isMutual = false)
+    {
         return $this->_oQuery->getCommonContentSQLParts($sContentTable, $sContentField, $iInitiator1, $iInitiator2, $isMutual);
     }
 
@@ -366,7 +374,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $isMutual get mutual connections only
      * @return array of SQL string parts, for now 'join' part only is returned
      */
-    public function getConnectedContentAsSQLParts ($sContentTable, $sContentField, $iInitiator, $isMutual = false) {
+    public function getConnectedContentAsSQLParts ($sContentTable, $sContentField, $iInitiator, $isMutual = false)
+    {
         return $this->_oQuery->getConnectedContentSQLParts($sContentTable, $sContentField, $iInitiator, $isMutual);
     }
 
@@ -378,14 +387,15 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $isMutual get mutual connections only
      * @return array of SQL string parts, for now 'join' part only is returned
      */
-    public function getConnectedInitiatorsAsSQLParts ($sContentTable, $sContentField, $iContent, $isMutual = false) {
+    public function getConnectedInitiatorsAsSQLParts ($sContentTable, $sContentField, $iContent, $isMutual = false)
+    {
         return $this->_oQuery->getConnectedInitiatorsSQLParts($sContentTable, $sContentField, $iContent, $isMutual);
     }
 
     /**
      * Similar to getConnectionsAsArray, but for getCommonContentAsCondition, getConnectedContentAsCondition or getConnectedInitiatorsAsCondition methods
      * @see getConnectionsAsArray
-     */    
+     */
     public function getConnectionsAsCondition ($sContentType, $sContentField, $iId1, $iId2, $isMutual = false)
     {
         if (BX_CONNECTIONS_CONTENT_TYPE_COMMON == $sContentType)
@@ -406,7 +416,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iMutual get mutual connections only
      * @return array of conditions, for now with 'restriction' and 'join' parts
      */
-    public function getCommonContentAsCondition ($sContentField, $iInitiator1, $iInitiator2, $iMutual = false) {
+    public function getCommonContentAsCondition ($sContentField, $iInitiator1, $iInitiator2, $iMutual = false)
+    {
         return array(
 
             'restriction' => array (
@@ -466,7 +477,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iMutual get mutual connections only
      * @return array of conditions, for now with 'restriction' and 'join' parts
      */
-    public function getConnectedContentAsCondition ($sContentField, $iInitiator, $iMutual = false) {
+    public function getConnectedContentAsCondition ($sContentField, $iInitiator, $iMutual = false)
+    {
         return array(
 
             'restriction' => array (
@@ -481,7 +493,7 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
                     'field' => 'mutual',
                     'operator' => '=',
                     'table' => $this->_aObject['table'],
-                ),               
+                ),
             ),
 
             'join' => array (
@@ -504,7 +516,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iMutual get mutual connections only
      * @return array of conditions, for now with 'restriction' and 'join' parts
      */
-    public function getConnectedInitiatorsAsCondition ($sContentField, $iContent, $iMutual = false) {
+    public function getConnectedInitiatorsAsCondition ($sContentField, $iContent, $iMutual = false)
+    {
         return array(
 
             'restriction' => array (
@@ -519,7 +532,7 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
                     'field' => 'mutual',
                     'operator' => '=',
                     'table' => $this->_aObject['table'],
-                ),               
+                ),
             ),
 
             'join' => array (
@@ -532,17 +545,18 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
                 ),
             ),
 
-        );        
-    }    
+        );
+    }
 
     /**
-     * Check if initiator and content are connected. 
+     * Check if initiator and content are connected.
      * In case if friends this function in conjunction with isMutual parameter can be used to check pending friend requests.
      * @param $iInitiator initiator of the connection
      * @param $iContent connected content or other profile id in case of friends
      * @return true - if content and initiator are connected or false - in all other cases
-     */    
-    public function isConnected ($iInitiator, $iContent, $isMutual = false) {
+     */
+    public function isConnected ($iInitiator, $iContent, $isMutual = false)
+    {
         $oConnection = $this->_oQuery->getConnection ($iInitiator, $iContent);
         if (!$oConnection)
             return false;
@@ -550,13 +564,14 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
     }
 
     /**
-     * Check if initiator and content are connected but connetion is not mutual, for checking pending connection requests. 
+     * Check if initiator and content are connected but connetion is not mutual, for checking pending connection requests.
      * This method makes sense only when type of connection is mutual.
      * @param $iInitiator initiator of the connection
      * @param $iContent connected content or other profile id in case of friends
      * @return true - if content and initiator are connected but connection is not mutual or false in all other cases
-     */    
-    public function isConnectedNotMutual ($iInitiator, $iContent) {
+     */
+    public function isConnectedNotMutual ($iInitiator, $iContent)
+    {
         $oConnection = $this->_oQuery->getConnection ($iInitiator, $iContent);
         if (!$oConnection)
             return false;
@@ -569,7 +584,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iId which can be as conetnt ot initiator
      * @return true if some connections were deleted
      */
-    public function onDeleteInitiatorAndContent ($iId) {
+    public function onDeleteInitiatorAndContent ($iId)
+    {
         $b = $this->onDeleteInitiator ($iId);
         $b = $this->onDeleteContent ($iId) || $b;
         return $b;
@@ -580,7 +596,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iIdInitiator initiator id
      * @return true if some connections were deleted
      */
-    public function onDeleteInitiator ($iIdInitiator) {
+    public function onDeleteInitiator ($iIdInitiator)
+    {
         return $this->_oQuery->onDelete ($iIdInitiator, 'initiator');
     }
 
@@ -589,7 +606,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $iIdInitiator initiator id
      * @return true if some connections were deleted
      */
-    public function onDeleteContent ($iIdContent) {
+    public function onDeleteContent ($iIdContent)
+    {
         return $this->_oQuery->onDelete ($iIdContent, 'content');
     }
 
@@ -601,7 +619,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $sFieldId id field name which is associated with the connection
      * @return number of deleted connections
      */
-    public function onModuleDeleteInitiatorAndContent ($sTable, $sFieldId) {
+    public function onModuleDeleteInitiatorAndContent ($sTable, $sFieldId)
+    {
         $iAffected = $this->onModuleDeleteInitiator ($sTable, $sFieldId);
         $iAffected += $this->onModuleDeleteContent ($sTable, $sFieldId);
         return $iAffected;
@@ -614,7 +633,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $sFieldId id field name which is associated with the connection
      * @return number of deleted connections
      */
-    public function onModuleDeleteInitiator ($sTable, $sFieldId) {
+    public function onModuleDeleteInitiator ($sTable, $sFieldId)
+    {
         return $this->_oQuery->onModuleDelete ($sTable, $sFieldId, 'initiator');
     }
 
@@ -625,7 +645,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $sFieldId id field name which is associated with the connection
      * @return number of deleted connections
      */
-    public function onModuleDeleteContent ($sTable, $sFieldId) {
+    public function onModuleDeleteContent ($sTable, $sFieldId)
+    {
         return $this->_oQuery->onModuleDelete ($sTable, $sFieldId, 'content');
     }
 
@@ -636,7 +657,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $sModuleName module name to delete connections for
      * @return number of deleted connections
      */
-    public function onModuleProfileDeleteInitiatorAndContent ($sModuleName) {
+    public function onModuleProfileDeleteInitiatorAndContent ($sModuleName)
+    {
         $iAffected = $this->onModuleProfileDeleteInitiator ($sModuleName);
         $iAffected += $this->onModuleProfileDeleteContent ($sModuleName);
         return $iAffected;
@@ -648,7 +670,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $sModuleName module name to delete connections for
      * @return number of deleted connections
      */
-    public function onModuleProfileDeleteInitiator ($sModuleName) {
+    public function onModuleProfileDeleteInitiator ($sModuleName)
+    {
         return $this->_oQuery->onModuleProfileDelete ($sModuleName, 'initiator');
     }
 
@@ -658,7 +681,8 @@ class BxDolConnection extends BxDol implements iBxDolFactoryObject {
      * @param $sModuleName module name to delete connections for
      * @return number of deleted connections
      */
-    public function onModuleProfileDeleteContent ($sModuleName) {
+    public function onModuleProfileDeleteContent ($sModuleName)
+    {
         return $this->_oQuery->onModuleProfileDelete ($sModuleName, 'content');
     }
 }

+ 43 - 24
inc/classes/BxDolConnectionQuery.php

@@ -13,29 +13,33 @@ bx_import('BxDolDb');
  * Database queries for Connection objects.
  * @see BxDolConnection
  */
-class BxDolConnectionQuery extends BxDolDb {
+class BxDolConnectionQuery extends BxDolDb
+{
     protected $_aObject;
     protected $_sTable;
     protected $_sType;
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
         $this->_sTable = $aObject['table'];
         $this->_sType = $aObject['type'];
     }
 
-    static public function getConnectionObject ($sObject) {
+    static public function getConnectionObject ($sObject)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_connection` WHERE `object` = ?", $sObject);
         $aObject = $oDb->getRow($sQuery);
-        if (!$aObject || !is_array($aObject)) 
+        if (!$aObject || !is_array($aObject))
             return false;
-        
+
         return $aObject;
     }
 
-    public function getCommonContentSQLParts ($sContentTable, $sContentField, $iInitiator1, $iInitiator2, $isMutual = false) {
+    public function getCommonContentSQLParts ($sContentTable, $sContentField, $iInitiator1, $iInitiator2, $isMutual = false)
+    {
         $sWhereJoin1 = $this->prepare(" AND `c`.`initiator` = ?", $iInitiator1);
         $sWhereJoin2 = $this->prepare(" AND `c2`.`initiator` = ?", $iInitiator2);
         if (false !== $isMutual) {
@@ -49,7 +53,8 @@ class BxDolConnectionQuery extends BxDolDb {
         );
     }
 
-    public function getConnectedContentSQLParts ($sContentTable, $sContentField, $iInitiator, $isMutual = false) {
+    public function getConnectedContentSQLParts ($sContentTable, $sContentField, $iInitiator, $isMutual = false)
+    {
         $sWhere = $this->prepare(" AND `c`.`initiator` = ?", $iInitiator);
         if (false !== $isMutual)
             $sWhere .= $this->prepare(" AND `c`.`mutual` = ?", $isMutual);
@@ -58,7 +63,8 @@ class BxDolConnectionQuery extends BxDolDb {
         );
     }
 
-    public function getConnectedInitiatorsSQLParts ($sContentTable, $sContentField, $iInitiator, $isMutual = false) {
+    public function getConnectedInitiatorsSQLParts ($sContentTable, $sContentField, $iInitiator, $isMutual = false)
+    {
         $sWhere = $this->prepare(" AND `c`.`content` = ?", $iInitiator);
         if (false !== $isMutual)
             $sWhere .= $this->prepare(" AND `c`.`mutual` = ?", $isMutual);
@@ -67,7 +73,8 @@ class BxDolConnectionQuery extends BxDolDb {
         );
     }
 
-    public function getCommonContent($iInitiator1, $iInitiator2, $isMutual, $iStart, $iLimit, $iOrder) {        
+    public function getCommonContent($iInitiator1, $iInitiator2, $isMutual, $iStart, $iLimit, $iOrder)
+    {
         $sWhereJoin = (false !== $isMutual) ? $this->prepare(" AND `c2`.`mutual` = ?", $isMutual) : '';
         $sJoin = $this->prepare("INNER JOIN `" . $this->_sTable . "` AS `c2` ON (`c2`.`initiator` = ? AND `c`.`content` = `c2`.`content` $sWhereJoin)", $iInitiator2);
 
@@ -77,19 +84,22 @@ class BxDolConnectionQuery extends BxDolDb {
         return $this->getColumn($sQuery);
     }
 
-    public function getConnectedContent ($iInitiator, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE) {
+    public function getConnectedContent ($iInitiator, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE)
+    {
         $sWhere = $this->prepare(" AND `c`.`initiator` = ?", $iInitiator);
         $sQuery = $this->_getConnectionsQuery($sWhere, '', '`c`.`content`', $isMutual, $iStart, $iLimit, $iOrder);
         return $this->getColumn($sQuery);
     }
 
-    public function getConnectedInitiators ($iContent, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE) {
+    public function getConnectedInitiators ($iContent, $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE)
+    {
         $sWhere = $this->prepare(" AND `c`.`content` = ?", $iContent);
         $sQuery = $this->_getConnectionsQuery($sWhere, '', '`c`.`initiator`', $isMutual, $iStart, $iLimit, $iOrder);
         return $this->getColumn($sQuery);
     }
 
-    protected function _getConnectionsQuery ($sWhere, $sJoin = '', $sFields = '*', $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE) {
+    protected function _getConnectionsQuery ($sWhere, $sJoin = '', $sFields = '*', $isMutual = false, $iStart = 0, $iLimit = BX_CONNECTIONS_LIST_LIMIT, $iOrder = BX_CONNECTIONS_ORDER_NONE)
+    {
         $sOrder = $this->_getOrderClause($iOrder);
 
         $sWhere .= (false !== $isMutual) ? $this->prepare(" AND `c`.`mutual` = ?", $isMutual) : '';
@@ -97,27 +107,30 @@ class BxDolConnectionQuery extends BxDolDb {
         return $this->prepare("SELECT $sFields FROM `" . $this->_sTable . "` AS `c` $sJoin WHERE 1 $sWhere $sOrder LIMIT ?, ?", $iStart, $iLimit);
     }
 
-    protected function _getOrderClause ($iOrder = BX_CONNECTIONS_ORDER_NONE, $sTable = '') {
+    protected function _getOrderClause ($iOrder = BX_CONNECTIONS_ORDER_NONE, $sTable = '')
+    {
         if ($sTable)
             $sTable .= '.';
         $sOrder = '';
         switch ($iOrder) {
-        case BX_CONNECTIONS_ORDER_ADDED_ASC: 
+        case BX_CONNECTIONS_ORDER_ADDED_ASC:
             $sOrder = "ORDER BY {$sTable}`added` ASC";
             break;
-        case BX_CONNECTIONS_ORDER_ADDED_DESC: 
+        case BX_CONNECTIONS_ORDER_ADDED_DESC:
             $sOrder = "ORDER BY {$sTable}`added` DESC";
             break;
         }
         return $sOrder;
     }
 
-    public function getConnection ($iInitiator, $iContent) {
+    public function getConnection ($iInitiator, $iContent)
+    {
         $sQuery = $this->prepare("SELECT * FROM `" . $this->_sTable . "` WHERE `initiator` = ? AND `content` = ?", $iInitiator, $iContent);
         return $this->getRow($sQuery);
     }
 
-    public function addConnection ($iInitiator, $iContent, &$iMutualParam = null) {
+    public function addConnection ($iInitiator, $iContent, &$iMutualParam = null)
+    {
         if ($this->getConnection($iInitiator, $iContent)) // connection already exists
             return false;
 
@@ -127,7 +140,7 @@ class BxDolConnectionQuery extends BxDolDb {
             $aConnectionMutual = $this->getConnection($iContent, $iInitiator);
             $iMutual = $aConnectionMutual ? 1 : 0;
             $sMutualField = $this->prepare(", `mutual` = ?", $iMutual);
-        } 
+        }
 
         $sQuery = $this->prepare("INSERT INTO `" . $this->_sTable . "` SET `initiator` = ?, `content` = ?, `added` = ?", $iInitiator, $iContent, time());
         $sQuery .= $sMutualField;
@@ -143,12 +156,14 @@ class BxDolConnectionQuery extends BxDolDb {
         return true;
     }
 
-    public function updateConnectionMutual ($iInitiator, $iContent, $iMutual) {
+    public function updateConnectionMutual ($iInitiator, $iContent, $iMutual)
+    {
         $sQuery = $this->prepare("UPDATE `" . $this->_sTable . "` SET `mutual` = ? WHERE `initiator` = ? AND `content` = ?", $iMutual, $iInitiator, $iContent);
         return $this->query($sQuery);
     }
 
-    public function removeConnection ($iInitiator, $iContent) {
+    public function removeConnection ($iInitiator, $iContent)
+    {
         if (!($aConnection = $this->getConnection($iInitiator, $iContent))) // connection doesn't exist
             return false;
 
@@ -162,20 +177,24 @@ class BxDolConnectionQuery extends BxDolDb {
         return true;
     }
 
-    public function onDelete ($iId, $sField = 'initiator') {
+    public function onDelete ($iId, $sField = 'initiator')
+    {
         $sQuery = $this->prepare("DELETE FROM `{$this->_sTable}` WHERE `$sField` = ?", $iId);
         return $this->query($sQuery);
     }
 
-    public function onModuleDelete ($sTable, $sFieldId, $sField = 'initiator') {
+    public function onModuleDelete ($sTable, $sFieldId, $sField = 'initiator')
+    {
         return $this->onModuleDeleteCustom ($sTable, $sFieldId, $sField);
     }
 
-    public function onModuleProfileDelete ($sModuleName, $sField = 'initiator') {
+    public function onModuleProfileDelete ($sModuleName, $sField = 'initiator')
+    {
         return $this->onModuleDeleteCustom ('sys_profiles', 'id', $sField, $this->prepare(" AND `sys_profiles`.`type` = ? ", $sModuleName));
     }
 
-    protected function onModuleDeleteCustom ($sTable, $sFieldId, $sField = 'initiator', $sWhere = '') {
+    protected function onModuleDeleteCustom ($sTable, $sFieldId, $sField = 'initiator', $sWhere = '')
+    {
         $sQuery = "DELETE `" . $this->_sTable . "` FROM `" . $this->_sTable . "` INNER JOIN `{$sTable}` WHERE `" . $this->_sTable . "`.`$sField` = `{$sTable}`.`{$sFieldId}` " . $sWhere;
         return $this->query($sQuery);
     }

+ 1 - 2
inc/classes/BxDolCron.php

@@ -79,7 +79,7 @@
  * no alerts available
  *
  */
-class BxDolCron extends BxDol 
+class BxDolCron extends BxDol
 {
     public function __construct()
     {
@@ -90,4 +90,3 @@ class BxDolCron extends BxDol
 }
 
 /** @} */
-

+ 6 - 7
inc/classes/BxDolCronPruning.php

@@ -9,23 +9,23 @@
 
 bx_import('BxDolCron');
 
-class BxDolCronPruning extends BxDolCron 
+class BxDolCronPruning extends BxDolCron
 {
-    protected function start() 
+    protected function start()
     {
         set_time_limit(0);
         ignore_user_abort();
         ob_start();
     }
 
-    protected function finish() 
+    protected function finish()
     {
         bx_alert('system', 'pruning', 0);
 
         if (!($sOutput = ob_get_clean()))
             return;
 
-    	bx_import('BxDolEmailTemplates');
+        bx_import('BxDolEmailTemplates');
         $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_Pruning', array('pruning_output' => $sOutput, 'site_title' => getParam('site_title')), 0, 0);
         if ($aTemplate)
             sendMail(getParam('site_email'), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), BX_EMAIL_NOTIFY);
@@ -73,7 +73,7 @@ class BxDolCronPruning extends BxDolCron
     /**
      * Clean tmp folders (tmp, cache) by deleting old files (by default older than 1 month)
      */
-    protected function cleanTmpFolders() 
+    protected function cleanTmpFolders()
     {
         $iTmpFileLife = 2592000;  // one month
         $aDirsToClean = array(
@@ -104,7 +104,7 @@ class BxDolCronPruning extends BxDolCron
         echo _t('_sys_pruning_files', $iNumTmp, $iNumDel);
     }
 
-    public function processing()    
+    public function processing()
     {
         $this->start();
 
@@ -117,4 +117,3 @@ class BxDolCronPruning extends BxDolCron
 }
 
 /** @} */
-

+ 2 - 2
inc/classes/BxDolCronStorage.php

@@ -9,9 +9,9 @@
 
 bx_import('BxDolCron');
 
-class BxDolCronStorage extends BxDolCron 
+class BxDolCronStorage extends BxDolCron
 {
-    public function processing() 
+    public function processing()
     {
         set_time_limit(36000);
         ignore_user_abort();

+ 53 - 69
inc/classes/BxDolDb.php

@@ -7,7 +7,7 @@
  * @{
  */
 
-class BxDolDb extends BxDol implements iBxDolSingleton 
+class BxDolDb extends BxDol implements iBxDolSingleton
 {
     protected $_bErrorChecking = true;
     protected $_sErrorMessage;
@@ -22,7 +22,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
     /**
      * set database parameters and connect to it
      */
-    protected function __construct($aDbConf = false) 
+    protected function __construct($aDbConf = false)
     {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
@@ -60,7 +60,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
     /**
      * Prevent cloning the instance
      */
-    public function __clone() 
+    public function __clone()
     {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
@@ -69,7 +69,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance($aDbConf = false, &$sError = null) 
+    public static function getInstance($aDbConf = false, &$sError = null)
     {
         if (!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
             if (false === $aDbConf && !defined('BX_DATABASE_HOST'))
@@ -153,8 +153,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
             $arr_type = MYSQL_ASSOC;
         $res = $this->res ($query);
         $arr_res = array();
-        if($res && mysql_num_rows($res))
-        {
+        if($res && mysql_num_rows($res)) {
             $arr_res = mysql_fetch_array($res, $arr_type);
             mysql_free_result($res);
         }
@@ -164,7 +163,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
     /**
      * execute sql query and return a column as result
      */
-    function getColumn($sQuery) 
+    function getColumn($sQuery)
     {
         if(!$sQuery)
             return array();
@@ -224,8 +223,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
         $arr_res = mysql_fetch_array($this->_rCurrentRes, $this->_iCurrentResType);
         if($arr_res)
             return $arr_res;
-        else
-        {
+        else {
             mysql_free_result($this->_rCurrentRes);
             $this->_iCurrentResType = MYSQL_ASSOC;
             return array();
@@ -309,8 +307,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
 
         $res = $this->res ($query);
         $arr_res = array();
-        if($res)
-        {
+        if($res) {
             while($row = mysql_fetch_array($res, $arr_type))
                 $arr_res[] = $row;
             mysql_free_result($res);
@@ -347,10 +344,8 @@ class BxDolDb extends BxDol implements iBxDolSingleton
 
         $res = $this->res ($query);
         $arr_res = array();
-        if($res)
-        {
-            while($row = mysql_fetch_array($res, MYSQL_ASSOC))
-            {
+        if($res) {
+            while($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
                 $arr_res[$row[$sFieldKey]] = $row;
             }
             mysql_free_result($res);
@@ -368,10 +363,8 @@ class BxDolDb extends BxDol implements iBxDolSingleton
 
         $res = $this->res ($query);
         $arr_res = array();
-        if($res)
-        {
-            while($row = mysql_fetch_array($res, MYSQL_ASSOC))
-            {
+        if($res) {
+            while($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
                 $arr_res[$row[$sFieldKey]] = $row[$sFieldValue];
             }
             mysql_free_result($res);
@@ -384,7 +377,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
         return mysql_insert_id($this->_rLink);
     }
 
-    function getErrorMessage () 
+    function getErrorMessage ()
     {
         $s = mysql_error($this->_rLink);
         if ($s)
@@ -401,12 +394,12 @@ class BxDolDb extends BxDol implements iBxDolSingleton
             $this->log($text . ': ' . $this->getErrorMessage());
     }
 
-    protected function isParamInCache($sKey) 
+    protected function isParamInCache($sKey)
     {
         return isset($this->_aParams[$sKey]);
     }
 
-    protected function cacheParams($bForceCacheInvalidate = false) 
+    protected function cacheParams($bForceCacheInvalidate = false)
     {
         if ($bForceCacheInvalidate)
             $this->cacheParamsClear();
@@ -420,21 +413,21 @@ class BxDolDb extends BxDol implements iBxDolSingleton
         return true;
     }
 
-    public function cacheParamsClear() 
+    public function cacheParamsClear()
     {
         return $this->cleanCache($this->_sParamsCacheName);
     }
 
-    public function isParam($sKey, $bFromCache = true) 
+    public function isParam($sKey, $bFromCache = true)
     {
-    	if ($bFromCache && $this->isParamInCache($sKey))
-    	   return true;
+        if ($bFromCache && $this->isParamInCache($sKey))
+           return true;
 
         $sQuery = $this->prepare("SELECT `name` FROM `sys_options` WHERE `name` = ? LIMIT 1", $sKey);
         return $this->getOne($sQuery) == $sKey;
     }
 
-    function addParam($sName, $sValue, $iKateg, $sDesc, $sType) 
+    function addParam($sName, $sValue, $iKateg, $sDesc, $sType)
     {
         $sQuery = $this->prepare("INSERT INTO `sys_options` SET `category_id` = ?, `name` = ?, `caption` = ?, `value` = ?, `type` = ?", $iKateg, $sName, $sDesc, $sValue, $sType);
         $this->query($sQuery);
@@ -443,7 +436,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
         $this->cacheParams(true);
     }
 
-    function getParam($sKey, $bFromCache = true) 
+    function getParam($sKey, $bFromCache = true)
     {
         if (!$sKey)
             return false;
@@ -455,7 +448,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
         }
     }
 
-    function setParam($sKey, $mixedValue) 
+    function setParam($sKey, $mixedValue)
     {
         $sQuery = $this->prepare("UPDATE `sys_options` SET `value` = ? WHERE `name` = ? LIMIT 1", $mixedValue, $sKey);
         $this->query($sQuery);
@@ -464,12 +457,12 @@ class BxDolDb extends BxDol implements iBxDolSingleton
         $this->cacheParams(true);
     }
 
-    function listTables() 
+    function listTables()
     {
         return mysql_list_tables($GLOBALS['db']['db'], $this->_rLink);
     }
 
-    function getFields($sTable) 
+    function getFields($sTable)
     {
         $rFields = mysql_list_fields($this->_sDbname, $sTable, $this->_rLink);
         $iFields = mysql_num_fields($rFields);
@@ -484,18 +477,18 @@ class BxDolDb extends BxDol implements iBxDolSingleton
         return $aResult;
     }
 
-    function isFieldExists($sTable, $sFieldName) 
+    function isFieldExists($sTable, $sFieldName)
     {
         $aFields = $this->getFields($sTable);
         return in_array(strtoupper($sFieldName), $aFields['uppercase']);
     }
 
-    function getEncoding()  
+    function getEncoding()
     {
         return  mysql_client_encoding($this->_rLink) or $this->error('Database get encoding error');
     }
 
-    function genMySQLErr( $out, $query ='' ) 
+    function genMySQLErr( $out, $query ='' )
     {
         $sParamsOutput = false;
         $sFoundError = '';
@@ -503,14 +496,12 @@ class BxDolDb extends BxDol implements iBxDolSingleton
         $aBackTrace = debug_backtrace();
         unset( $aBackTrace[0] );
 
-        if( $query )
-        {
+        if( $query ) {
             //try help to find error
 
             $aFoundError = array();
 
-            foreach( $aBackTrace as $aCall )
-            {
+            foreach( $aBackTrace as $aCall ) {
 
                 // truncating global settings since it repeated many times and output it separately
                 if (isset($aCall['object']) && property_exists($aCall['object'], '_aParams')) {
@@ -519,12 +510,9 @@ class BxDolDb extends BxDol implements iBxDolSingleton
                     $aCall['object']->_aParams = '[truncated]';
                 }
 
-                if (isset($aCall['args']) && is_array($aCall['args']))
-                {
-                    foreach( $aCall['args'] as $argNum => $argVal )
-                    {
-                        if( is_string($argVal) and strcmp( $argVal, $query ) == 0 )
-                        {
+                if (isset($aCall['args']) && is_array($aCall['args'])) {
+                    foreach( $aCall['args'] as $argNum => $argVal ) {
+                        if( is_string($argVal) and strcmp( $argVal, $query ) == 0 ) {
                             $aFoundError['file']     = isset($aCall['file']) ? $aCall['file'] : (isset($aCall['class']) ? 'class: ' . $aCall['class'] : 'undefined');
                             $aFoundError['line']     = isset($aCall['line']) ? $aCall['line'] : 'undefined';
                             $aFoundError['function'] = $aCall['function'];
@@ -534,8 +522,7 @@ class BxDolDb extends BxDol implements iBxDolSingleton
                 }
             }
 
-            if( $aFoundError )
-            {
+            if( $aFoundError ) {
                 $sFoundError = <<<EOJ
 Found error in the file '<b>{$aFoundError['file']}</b>' at line <b>{$aFoundError['line']}</b>.<br />
 Called '<b>{$aFoundError['function']}</b>' function with erroneous argument #<b>{$aFoundError['arg']}</b>.<br /><br />
@@ -543,7 +530,6 @@ EOJ;
             }
         }
 
-
         bx_import('BxDolConfig');
         if (BxDolConfig::getInstance()->get('db', 'visual_processing')) {
             ?>
@@ -582,8 +568,7 @@ EOJ;
             ?>
                 </div>
             <?php
-        }
-        else
+        } else
             echo $out;
 
         if(BxDolConfig::getInstance()->get('db', 'error_remort_by_email')) {
@@ -616,12 +601,12 @@ EOJ;
         exit;
     }
 
-    function setErrorChecking ($b) 
+    function setErrorChecking ($b)
     {
         $this->_bErrorChecking = $b;
     }
 
-    function getDbCacheObject () 
+    function getDbCacheObject ()
     {
         if ($this->_oDbCacheObject != null) {
             return $this->_oDbCacheObject;
@@ -634,12 +619,12 @@ EOJ;
         }
     }
 
-    function genDbCacheKey ($sName) 
+    function genDbCacheKey ($sName)
     {
         return 'db_' . $sName . '_' . bx_site_hash() . '.php';
     }
 
-    function fromCache ($sName, $sFunc) 
+    function fromCache ($sName, $sFunc)
     {
         $aArgs = func_get_args();
         array_shift ($aArgs); // shift $sName
@@ -668,7 +653,7 @@ EOJ;
         return $mixedRet;
     }
 
-    function cleanCache ($sName) 
+    function cleanCache ($sName)
     {
         if (!$this->getParam('sys_db_cache_enable'))
             return true;
@@ -680,7 +665,7 @@ EOJ;
         return $oCache->delData($sKey);
     }
 
-    function & fromMemory ($sName, $sFunc) 
+    function & fromMemory ($sName, $sFunc)
     {
         if (array_key_exists($sName, $GLOBALS['gl_db_cache'])) {
             return $GLOBALS['gl_db_cache'][$sName];
@@ -695,7 +680,7 @@ EOJ;
         }
     }
 
-    function cleanMemory ($sName) 
+    function cleanMemory ($sName)
     {
         if (isset($GLOBALS['gl_db_cache'][$sName])) {
             unset($GLOBALS['gl_db_cache'][$sName]);
@@ -709,10 +694,10 @@ EOJ;
      * Try to use "prepare" function always (@see BxDolDb::prepare), use "escape" only if "prepare" function is not possible at all.
      * Also consider using "implode_escape" function (@see BxDolDb::implode_escape).
      *
-     * @param string $s string to escape
+     * @param  string  $s string to escape
      * @return escaped string whcich is ready to pass to SQL query.
      */
-    function escape ($s) 
+    function escape ($s)
     {
         return mysql_real_escape_string($s, $this->_rLink);
     }
@@ -729,7 +714,7 @@ EOJ;
      * @param $mixed array or parameters or just one paramter
      * @return string which is ready to pass to IN(...) SQL construction
      */
-    function implode_escape ($mixed) 
+    function implode_escape ($mixed)
     {
         if (is_array($mixed)) {
             $s = '';
@@ -746,7 +731,7 @@ EOJ;
     /**
      * @deprecated
      */
-    function unescape ($mixed) 
+    function unescape ($mixed)
     {
         if (is_array($mixed)) {
             foreach ($mixed as $k => $v)
@@ -768,11 +753,11 @@ EOJ;
      * $a = $oDb->getAll($sSql);
      * @endcode
      *
-     * @param string $sQuery SQL query, parameters for replacing are marked with ? symbol
-     * @param mixed $mixed any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
+     * @param  string $sQuery SQL query, parameters for replacing are marked with ? symbol
+     * @param  mixed  $mixed  any number if parameters to replace, number of parameters whould match number of ? symbols in SQL query
      * @return string with SQL query ready for execution
      */
-    function prepare ($sQuery) 
+    function prepare ($sQuery)
     {
         $aArgs = func_get_args();
         $sQuery = array_shift($aArgs);
@@ -799,7 +784,7 @@ EOJ;
      * @param $sDiv fields separator, by default it is ',', another useful value is ' AND '
      * @return part of SQL query string
      */
-    function arrayToSQL ($a, $sDiv = ',') 
+    function arrayToSQL ($a, $sDiv = ',')
     {
         $s = '';
         foreach ($a as $k => $v)
@@ -807,12 +792,12 @@ EOJ;
         return trim($s, $sDiv);
     }
 
-    function log ($s) 
+    function log ($s)
     {
         return file_put_contents(BX_DIRECTORY_PATH_ROOT . 'logs/db.err.log', date('Y-m-d H:i:s') . "\t" . $s . "\n", FILE_APPEND);
     }
 
-    function executeSQL($sPath, $aReplace = array (), $isBreakOnError = true) 
+    function executeSQL($sPath, $aReplace = array (), $isBreakOnError = true)
     {
         if(!file_exists($sPath) || !($rHandler = fopen($sPath, "r")))
             return array(array ('query' => "fopen($sPath, 'r')", 'error' => 'file not found or permission denied'));
@@ -858,15 +843,14 @@ EOJ;
     }
 }
 
-function getParam($sParamName, $bUseCache = true) 
+function getParam($sParamName, $bUseCache = true)
 {
     return BxDolDb::getInstance()->getParam($sParamName, $bUseCache);
 }
 
-function setParam($sParamName, $sParamVal) 
+function setParam($sParamName, $sParamVal)
 {
     return BxDolDb::getInstance()->setParam($sParamName, $sParamVal);
 }
 
 /** @} */
-

+ 29 - 25
inc/classes/BxDolEditor.php

@@ -13,7 +13,7 @@ bx_import('BxDolEditorQuery');
  * Standard WYSIWYG editor view.
  * @see BxDolEditor::attachEditor
  */
-define('BX_EDITOR_STANDARD', 1); 
+define('BX_EDITOR_STANDARD', 1);
 
 /**
  * Full WYSIWYG editor view. If not supported by editor, standard view is used.
@@ -27,16 +27,15 @@ define('BX_EDITOR_FULL', 2);
  */
 define('BX_EDITOR_MINI', 3);
 
-
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section editor Editor
  * @ref BxDolEditor
  */
 
 /**
- * WYSIWYG editors. 
- * 
+ * WYSIWYG editors.
+ *
  * Site owner can choose which visual editor can be user on the site.
  *
  * Default visual editor is stored in 'sys_editor_default' setting option.
@@ -46,17 +45,17 @@ define('BX_EDITOR_MINI', 3);
  *
  * Add record to 'sys_objects_editor' table:
  *
- * - object: name of the editor object, in the format: vendor prefix, underscore, module prefix, underscore, internal identifier or nothing; for example: bx_blogs - custom editor in blogs module. 
+ * - object: name of the editor object, in the format: vendor prefix, underscore, module prefix, underscore, internal identifier or nothing; for example: bx_blogs - custom editor in blogs module.
  * - title: title of the editor, displayed in the studio.
  * - skin: editor skin, if editor suports custom/multiple skins.
  * - override_class_name: user defined class name which is derived from one of base editor classes.
  * - override_class_file: the location of the user defined class, leave it empty if class is located in system folders.
- * 
+ *
  *
  * @section example Example of usage
  *
  * Apply visual editor to textarea:
- * 
+ *
  * @code
  *  echo '<textarea id="my_textarea" rows="20" cols="80">some text here</textarea>'; // print text area element
  *
@@ -65,10 +64,10 @@ define('BX_EDITOR_MINI', 3);
  *  if ($oEditor) // check if editor is available for using
  *      echo $oEditor->attachEditor ('#my_textarea', BX_EDITOR_STANDARD); // output HTML which will automatically apply editor to textarea element by its id
  * @endcode
- * 
+ *
  */
-class BxDolEditor extends BxDol implements iBxDolFactoryObject {
-
+class BxDolEditor extends BxDol implements iBxDolFactoryObject
+{
     protected $_sObject;
     protected $_aObject;
 
@@ -76,7 +75,8 @@ class BxDolEditor extends BxDol implements iBxDolFactoryObject {
      * Constructor
      * @param $aObject array of editor options
      */
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
 
         $this->_sObject = $aObject['object'];
@@ -88,14 +88,14 @@ class BxDolEditor extends BxDol implements iBxDolFactoryObject {
      * @param $sObject object name
      * @return object instance or false on error
      */
-    static public function getObjectInstance($sObject = false) {
-
+    static public function getObjectInstance($sObject = false)
+    {
         if (!$sObject)
             $sObject = getParam('sys_editor_default');
 
         if (isset($GLOBALS['bxDolClasses']['BxDolEditor!'.$sObject]))
             return $GLOBALS['bxDolClasses']['BxDolEditor!'.$sObject];
-        
+
         $aObject = BxDolEditorQuery::getEditorObject($sObject);
         if (!$aObject || !is_array($aObject))
             return false;
@@ -106,9 +106,9 @@ class BxDolEditor extends BxDol implements iBxDolFactoryObject {
         $sClass = $aObject['override_class_name'];
         if (!empty($aObject['override_class_file']))
             require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
-        else    
+        else
             bx_import($sClass);
-        
+
         $o = new $sClass($aObject);
 
         return ($GLOBALS['bxDolClasses']['BxDolEditor!'.$sObject] = $o);
@@ -117,7 +117,8 @@ class BxDolEditor extends BxDol implements iBxDolFactoryObject {
     /**
      * Get minimal width which is neede for editor for the provided view mode
      */
-    public function getWidth ($iViewMode) {
+    public function getWidth ($iViewMode)
+    {
         // override this function in particular editor class
     }
 
@@ -127,24 +128,27 @@ class BxDolEditor extends BxDol implements iBxDolFactoryObject {
      * @param $iViewMode - editor view mode: BX_EDITOR_STANDARD, BX_EDITOR_MINI, BX_EDITOR_FULL
      * @param $bDynamicMode - is AJAX mode or not, the HTML with editor area is loaded synamically.
      */
-    public function attachEditor ($sSelector, $iViewMode, $bDynamicMode = false) {
+    public function attachEditor ($sSelector, $iViewMode, $bDynamicMode = false)
+    {
         // override this function in particular editor class
     }
-  
+
     /**
      * Add css/js files which are needed for editor display and functionality.
      */
-    protected function _addJsCss ($bDynamicMode = false) {
+    protected function _addJsCss ($bDynamicMode = false)
+    {
         // override this function in particular editor class
     }
 
     /**
      * Replace provided markers string.
-     * @param $s - string to replace markers in 
+     * @param $s - string to replace markers in
      * @param $a - markers array
      * @return string with replaces markers
-     */ 
-    protected function _replaceMarkers ($s, $a) {
+     */
+    protected function _replaceMarkers ($s, $a)
+    {
         if (empty($s) || empty($a) || !is_array($a))
             return $s;
         return bx_replace_markers($s, $a);

+ 8 - 5
inc/classes/BxDolEditorQuery.php

@@ -13,21 +13,24 @@ bx_import('BxDolDb');
  * Database queries for editor objects.
  * @see BxDolEditor
  */
-class BxDolEditorQuery extends BxDolDb {
+class BxDolEditorQuery extends BxDolDb
+{
     protected $_aObject;
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
     }
 
-    static public function getEditorObject ($sObject) {
+    static public function getEditorObject ($sObject)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_editor` WHERE `object` = ?", $sObject);
         $aObject = $oDb->getRow($sQuery);
-        if (!$aObject || !is_array($aObject)) 
+        if (!$aObject || !is_array($aObject))
             return false;
-        
+
         return $aObject;
     }
 

+ 32 - 27
inc/classes/BxDolEmailTemplates.php

@@ -10,15 +10,15 @@
 bx_import('BxDolLanguagesQuery');
 bx_import('BxDolEmailTemplatesQuery');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section email_templates Email Templates
  * @ref BxDolEmailTemplates
  */
 
 /**
  * Email templates are used to send preformated messages.
- * 
+ *
  * Email templates are multilingual.
  *
  * User is sent email in language which is defined in their account, if account language is not set - then default site language is used.
@@ -30,20 +30,20 @@ bx_import('BxDolEmailTemplatesQuery');
  * 1-click unsubscribe link is added automatically to every email (except a few system emails, which is not supposed to unsubscribe from, like forgot password email).
  * Please note: make sure that {unsubscribe} marker is not removed, or unsubscribe link will not be added.
  *
- * 
+ *
  * @section example Example of usage
  *
  * Send an email using email templates:
- * 
+ *
  * @code
- *     
+ *
  *     // define custom template variables
  *     $aPlus = array();
  *     $aPlus['email'] = 'ktoto@example.com';
  *     $aPlus['conf_code'] = '123456';
  *     $aPlus['conf_link'] = BX_DOL_URL_ROOT . 'page.php?i=confirm-email&code=123456';
  *     $aPlus['conf_form_link'] = BX_DOL_URL_ROOT . 'page.php?i=confirm-email';
- *         
+ *
  *     bx_import('BxDolEmailTemplates'); // import class
  *     $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_Confirmation', $aPlus); // get class instance and parse template
  *
@@ -53,20 +53,21 @@ bx_import('BxDolEmailTemplatesQuery');
  *         echo 'email send failed';
  *
  * @endcode
- * 
+ *
  */
-class BxDolEmailTemplates extends BxDol implements iBxDolSingleton {
-
+class BxDolEmailTemplates extends BxDol implements iBxDolSingleton
+{
     protected $_oEmailTemplatesQuery;
 
     protected $iDefaultLangId;
     protected $iFallbackLangId;
-    protected $aDefaultKeys;    
+    protected $aDefaultKeys;
 
     /**
      * Class constructor.
      */
-    protected function __construct() {
+    protected function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -91,7 +92,8 @@ class BxDolEmailTemplates extends BxDol implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -99,7 +101,8 @@ class BxDolEmailTemplates extends BxDol implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    static function getInstance() {
+    static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolEmailTemplates();
 
@@ -109,12 +112,12 @@ class BxDolEmailTemplates extends BxDol implements iBxDolSingleton {
     /**
      * Function will return array of needed template ;
      *
-     * @param string $sTemplateName - name of necessary template.
-     * @param integer $iAccountId - account ID of registered member.
-     * @return array with template 'Subject' and 'Body'.
+     * @param  string  $sTemplateName - name of necessary template.
+     * @param  integer $iAccountId    - account ID of registered member.
+     * @return array   with template 'Subject' and 'Body'.
      */
-    function getTemplate($sTemplateName, $iAccountId = 0 ) {
-
+    function getTemplate($sTemplateName, $iAccountId = 0 )
+    {
         $iUseLang = $this->iDefaultLangId;
         if ($iAccountId) {
             bx_import('BxDolAccount');
@@ -123,7 +126,7 @@ class BxDolEmailTemplates extends BxDol implements iBxDolSingleton {
                 $aAccountInfo = $oAccount->getInfo();
                 $iUseLang = $aAccountInfo['lang_id'] ? $aAccountInfo['lang_id'] : $this->iDefaultLangId;
             }
-        } 
+        }
 
         return $this->_oEmailTemplatesQuery->getTemplate ($sTemplateName, $iUseLang, $this->iDefaultLangId, $this->iFallbackLangId);
     }
@@ -131,13 +134,14 @@ class BxDolEmailTemplates extends BxDol implements iBxDolSingleton {
     /**
      * Function will return array of needed template with neccessary markers replaced ;
      *
-     * @param string $sTemplateName - name of necessary template.
-     * @param string $aTemplatekeys - key ane value pairs to replace in subject and body.
-     * @param integer $iAccountId - account ID of registered member.
-     * @param integer $iProfileId - profile ID of registered member.
-     * @return array with template 'Subject' and 'Body'.
+     * @param  string  $sTemplateName - name of necessary template.
+     * @param  string  $aTemplatekeys - key ane value pairs to replace in subject and body.
+     * @param  integer $iAccountId    - account ID of registered member.
+     * @param  integer $iProfileId    - profile ID of registered member.
+     * @return array   with template 'Subject' and 'Body'.
      */
-    function parseTemplate($sTemplateName, $aTemplateKeys, $iAccountId = 0, $iProfileId = 0) {
+    function parseTemplate($sTemplateName, $aTemplateKeys, $iAccountId = 0, $iProfileId = 0)
+    {
         $aTemplate = $this->getTemplate($sTemplateName, $iAccountId);
         if (!$aTemplate)
             return false;
@@ -147,7 +151,8 @@ class BxDolEmailTemplates extends BxDol implements iBxDolSingleton {
         );
     }
 
-    function parseContent($sContent, $aKeys, $iAccountId = 0, $iProfileId = 0) {
+    function parseContent($sContent, $aKeys, $iAccountId = 0, $iProfileId = 0)
+    {
         $aResultKeys = $this->aDefaultKeys;
 
         if ($iAccountId) {

+ 5 - 5
inc/classes/BxDolEmailTemplatesQuery.php

@@ -13,9 +13,9 @@ bx_import('BxDolDb');
  * Database queries for BxDolEmailTemplates object.
  * @see BxDolEmailTemplates
  */
-class BxDolEmailTemplatesQuery extends BxDolDb implements iBxDolSingleton 
+class BxDolEmailTemplatesQuery extends BxDolDb implements iBxDolSingleton
 {
-    public static function getInstance() 
+    public static function getInstance()
     {
         if (!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
             $o = new BxDolEmailTemplatesQuery();
@@ -25,7 +25,7 @@ class BxDolEmailTemplatesQuery extends BxDolDb implements iBxDolSingleton
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    public function getTemplate ($sTemplateName, $iLangAccount, $iLangDefault, $iLangFallback) 
+    public function getTemplate ($sTemplateName, $iLangAccount, $iLangDefault, $iLangFallback)
     {
         // get email templates keys
         $sSql = $this->prepare("SELECT `Subject`, `Body` FROM `sys_email_templates` WHERE `Name`=? LIMIT 1", $sTemplateName);
@@ -33,7 +33,7 @@ class BxDolEmailTemplatesQuery extends BxDolDb implements iBxDolSingleton
         if (!$a)
             return false;
 
-        // build languages idsto search for translation in 
+        // build languages idsto search for translation in
         $aLangs = array ($iLangAccount);
         if ($iLangDefault != $iLangAccount)
             $aLangs[] = $iLangDefault;
@@ -60,7 +60,7 @@ class BxDolEmailTemplatesQuery extends BxDolDb implements iBxDolSingleton
         return array ('Subject' => $sSubject, 'Body' => $sBody);
     }
 
-    public function getLangTranslation ($sKey, $iLangId) 
+    public function getLangTranslation ($sKey, $iLangId)
     {
         $sSql = $this->prepare("SELECT `s`.`String` FROM `sys_localization_strings` as `s` INNER JOIN `sys_localization_keys` AS `k` ON (`s`.`IDKey` = `k`.`ID`) WHERE `k`.`Key` = ? AND `s`.`IDLanguage` = ? LIMIT 1", $sKey, $iLangId);
         return $this->getOne($sSql);

+ 46 - 33
inc/classes/BxDolFile.php

@@ -7,21 +7,24 @@
  * @{
  */
 
-class BxDolFile extends BxDol implements iBxDolSingleton {
+class BxDolFile extends BxDol implements iBxDolSingleton
+{
     protected $_sPathFrom;
     protected $_sPathTo;
 
-    function __construct() {
+    function __construct()
+    {
         parent::__construct();
 
         $this->_sPathFrom = BX_DIRECTORY_PATH_ROOT;
         $this->_sPathTo = BX_DIRECTORY_PATH_ROOT;
     }
 
-	/**
+    /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -29,35 +32,41 @@ class BxDolFile extends BxDol implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
+    public static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolFile();
 
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    function copy($sFilePathFrom, $sFilePathTo) {
+    function copy($sFilePathFrom, $sFilePathTo)
+    {
         $sFilePathFrom = $this->_sPathFrom . $sFilePathFrom;
         $sFilePathTo = $this->_sPathTo . $sFilePathTo;
         return $this->_copyFile($sFilePathFrom, $sFilePathTo);
     }
 
-    function delete($sPath) {
+    function delete($sPath)
+    {
         $sPath = $this->_sPathTo . $sPath;
         return $this->_deleteDirectory($sPath);
     }
 
-	function getPermissions($sPath) {
-    	$sPath = $this->_sPathTo . $sPath;
-    	return $this->_getPermissions($sPath);
+    function getPermissions($sPath)
+    {
+        $sPath = $this->_sPathTo . $sPath;
+        return $this->_getPermissions($sPath);
     }
 
-	function setPermissions($sPath, $sMode) {
-    	$sPath = $this->_sPathTo . $sPath;
-    	return $this->_setPermissions($sPath, $sMode);
+    function setPermissions($sPath, $sMode)
+    {
+        $sPath = $this->_sPathTo . $sPath;
+        return $this->_setPermissions($sPath, $sMode);
     }
 
-    protected function _copyFile($sFilePathFrom, $sFilePathTo) {
+    protected function _copyFile($sFilePathFrom, $sFilePathTo)
+    {
         if(file_exists($sFilePathTo))
             return true;
 
@@ -72,35 +81,33 @@ class BxDolFile extends BxDol implements iBxDolSingleton {
                     @mkdir($this->_rStream, $aFileParts[0]);
 
                 $bResult = @copy($sFilePathFrom, $sFilePathTo);
-            }
-            else if($this->_isDirectory($sFilePathTo)) {
+            } else if($this->_isDirectory($sFilePathTo)) {
                 @mkdir($sFilePathTo);
 
                 $aFileParts = $this->_parseFile($sFilePathFrom);
                 if(isset($aFileParts[1]))
                     $bResult = @copy($sFilePathFrom, $this->_validatePath($sFilePathTo) . $aFileParts[1]);
             }
-        }
-        else if(is_dir($sFilePathFrom) && $this->_isDirectory($sFilePathTo)) {
+        } else if(is_dir($sFilePathFrom) && $this->_isDirectory($sFilePathTo)) {
             @mkdir($sFilePathTo);
 
             $aInnerFiles = $this->_readDirectory($sFilePathFrom);
             foreach($aInnerFiles as $sFile)
                 $bResult = $this->_copyFile($this->_validatePath($sFilePathFrom) . $sFile, $this->_validatePath($sFilePathTo) . $sFile);
-        }
-        else
+        } else
             $bResult = false;
 
         return $bResult;
     }
 
-    protected function _readDirectory($sFilePath) {
+    protected function _readDirectory($sFilePath)
+    {
         if(!is_dir($sFilePath) || !($rSource = opendir($sFilePath)))
             return false;
 
         $aResult = array();
         while(($sFile = readdir($rSource)) !== false) {
-            if($sFile == '.' || $sFile =='..' || $sFile[0] == '.') 
+            if($sFile == '.' || $sFile =='..' || $sFile[0] == '.')
                 continue;
             $aResult[] = $sFile;
         }
@@ -109,7 +116,8 @@ class BxDolFile extends BxDol implements iBxDolSingleton {
         return $aResult;
     }
 
-    protected function _deleteDirectory($sPath) {
+    protected function _deleteDirectory($sPath)
+    {
         if(!file_exists($sPath))
             return true;
 
@@ -124,35 +132,39 @@ class BxDolFile extends BxDol implements iBxDolSingleton {
 
             if(!@rmdir($sPath))
                 return false;
-        }
-        else if(!@unlink($sPath))
+        } else if(!@unlink($sPath))
             return false;
 
         return true;
     }
 
-    protected function _validatePath($sPath) {
+    protected function _validatePath($sPath)
+    {
         if($sPath && substr($sPath, -1) != '/' && $this->_isDirectory($sPath))
             $sPath .= '/';
 
         return $sPath;
     }
 
-    protected function _parseFile($sFilePath) {
+    protected function _parseFile($sFilePath)
+    {
         $aParts = array();
         preg_match("/^([a-zA-Z0-9@~_\.\\\\\/:-]+[\\\\\/])([a-zA-Z0-9~_-]+\.[a-zA-Z]{2,8})$/", $sFilePath, $aParts) ? true : false;
         return count($aParts) > 1 ? array_slice($aParts, 1) : false;
     }
 
-    protected function _isFile($sFilePath) {
+    protected function _isFile($sFilePath)
+    {
         return preg_match("/^([a-zA-Z0-9@~_\.\\\\\/:-]+)\.([a-zA-Z]){2,8}$/", $sFilePath) ? true : false;
     }
 
-    protected function _isDirectory($sFilePath) {
+    protected function _isDirectory($sFilePath)
+    {
         return preg_match("/^([a-zA-Z0-9@~_\.\\\\\/:-]+)[\\\\\/]([a-zA-Z0-9~_-]+)[\\\\\/]?$/", $sFilePath) ? true : false;
     }
 
-	protected function _getPermissions($sPath) {
+    protected function _getPermissions($sPath)
+    {
         clearstatcache();
 
         $hPerms = @fileperms($sPath);
@@ -162,10 +174,11 @@ class BxDolFile extends BxDol implements iBxDolSingleton {
         return substr(decoct($hPerms), -3);
     }
 
-	protected function _setPermissions($sPath, $sMode) {
-		$aConvert = array('writable' => 0666, 'executable' => 0777);
+    protected function _setPermissions($sPath, $sMode)
+    {
+        $aConvert = array('writable' => 0666, 'executable' => 0777);
 
-		return chmod($sPath, $aConvert[$sMode]);
+        return chmod($sPath, $aConvert[$sMode]);
     }
 }
 

Разница между файлами не показана из-за своего большого размера
+ 210 - 180
inc/classes/BxDolForm.php


+ 9 - 8
inc/classes/BxDolFormNested.php

@@ -13,9 +13,9 @@ bx_import('BxTemplFormView');
  * Nested form. It is used in file uploaders to show uploaded file as nested form.
  * @see BxDolUploader
  * @see BxDolForm
- */ 
-class BxDolFormNested extends BxTemplFormView {
-
+ */
+class BxDolFormNested extends BxTemplFormView
+{
     /**
      * Constructor
      * @param $sName the name of form field from main form, where this nested form is inserted.
@@ -23,19 +23,19 @@ class BxDolFormNested extends BxTemplFormView {
      * @param $sSubmitName main form submit_name; field name of submit form input to determine if form is submitted or not.
      * @param $oTemplate optional template object
      */
-    function __construct($sName, $aForm, $sSubmitName = false, $oTemplate = false) {
-
+    function __construct($sName, $aForm, $sSubmitName = false, $oTemplate = false)
+    {
         if (!isset($aForm['params']['nested_form_template']) || !$aForm['params']['nested_form_template'])
             $aForm['params']['nested_form_template'] = 'uploader_nested_form_wrapper.html';
 
         $aForm['form_attrs']['id'] = $sName . '_{file_id}';
         $aForm['form_attrs']['method'] = 'specific';
         $aForm['params']['remove_form'] = true;
-        $aForm['params']['csrf']['disable'] = true;                
+        $aForm['params']['csrf']['disable'] = true;
         if ($sSubmitName)
             $aForm['params']['db']['submit_name'] = $sSubmitName;
         if (!isset($aForm['inputs'][$sName])) {
-            $aForm['inputs'][$sName] = array( 
+            $aForm['inputs'][$sName] = array(
                 'type' => 'hidden',
                 'name' => $sName . '[]',
                 'value' => '{file_id}',
@@ -45,7 +45,8 @@ class BxDolFormNested extends BxTemplFormView {
         parent::__construct($aForm, $oTemplate);
     }
 
-    function genForm() {
+    function genForm()
+    {
         $sNestedForm = parent::genForm();
         $a = array (
             'nested_form' => $sNestedForm,

+ 24 - 19
inc/classes/BxDolFormQuery.php

@@ -13,7 +13,8 @@ bx_import('BxDolDb');
  * Database queries for forms.
  * @see BxDolForm
  */
-class BxDolFormQuery extends BxDolDb {
+class BxDolFormQuery extends BxDolDb
+{
     protected $_aObject;
 
     protected static $TYPES_SET = array (
@@ -26,22 +27,24 @@ class BxDolFormQuery extends BxDolDb {
         'button' => 1,
     );
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
     }
 
-    static public function getFormArray ($sObject, $sDisplayName) {
+    static public function getFormArray ($sObject, $sDisplayName)
+    {
         $oDb = BxDolDb::getInstance();
 
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_form` WHERE `active` = 1 AND `object` = ?", $sObject);
-        $aObject = $oDb->getRow($sQuery);        
-        if (!$aObject || !is_array($aObject)) 
+        $aObject = $oDb->getRow($sQuery);
+        if (!$aObject || !is_array($aObject))
             return false;
 
         $sQuery = $oDb->prepare("SELECT * FROM `sys_form_displays` WHERE `object` = ? AND `display_name` = ?", $sObject, $sDisplayName);
-        $aDisplay = $oDb->getRow($sQuery);        
-        if (!$aDisplay || !is_array($aDisplay)) 
+        $aDisplay = $oDb->getRow($sQuery);
+        if (!$aDisplay || !is_array($aDisplay))
             return false;
 
         $aForm = array ();
@@ -60,10 +63,10 @@ class BxDolFormQuery extends BxDolDb {
 
         // form action
         if (!empty($aForm['form_attrs']['action']) && 0 != strncasecmp($aForm['form_attrs']['action'], 'http://', 7) && 0 != strncasecmp($aForm['form_attrs']['action'], 'https://', 8)) {
-        	bx_import('BxDolPermalinks');
+            bx_import('BxDolPermalinks');
             $aForm['form_attrs']['action'] = BX_DOL_URL_ROOT . BxDolPermalinks::getInstance()->permalink($aForm['form_attrs']['action']);
         }
-        
+
         // params
         if (!empty($aObject['params']))
             $aAddFormParams = unserialize($aObject['params']);
@@ -87,26 +90,26 @@ class BxDolFormQuery extends BxDolDb {
         $aInputs = $oDb->getAllWithKey($sQuery, 'name');
         $aForm['inputs'] = array();
         $aInputSets = array();
-        foreach ($aInputs as $a) {            
+        foreach ($aInputs as $a) {
 
             // main attributes
             $aInput = array (
-                'type' => $a['type'],                
+                'type' => $a['type'],
                 'name' => $a['name'],
                 'caption' => _t($a['caption']),
                 'info' => $a['info'] ? _t($a['info']) : '',
                 'required' => $a['required'] ? true : false,
                 'collapsed' => $a['collapsed'] ? true : false,
-                'html' => $a['html'],  
+                'html' => $a['html'],
                 'attrs' => $a['attrs'] ? unserialize($a['attrs']) : false,
                 'tr_attrs' => $a['attrs_tr'] ? unserialize($a['attrs_tr']) : false,
                 'attrs_wrapper' => $a['attrs_wrapper'] ? unserialize($a['attrs_wrapper']) : false,
                 'visible_for_levels' => $a['visible_for_levels'],
             );
-            
+
             // if type is input set stop to process other attribnutes
-            if ('input_set' == $a['type']) {            
-                $aForm['inputs'][$a['name']] = $aInput; 
+            if ('input_set' == $a['type']) {
+                $aForm['inputs'][$a['name']] = $aInput;
                 $aInputSets[] = $a['name'];
                 continue;
             }
@@ -134,7 +137,7 @@ class BxDolFormQuery extends BxDolDb {
                     $aChecker['params'] = unserialize($a['checker_params']);
                 $aInput['checker'] = $aChecker;
             }
-            
+
             // db processing options
             if (!empty($a['db_pass'])) {
                 $aDb = array ('pass' => $a['db_pass']);
@@ -162,7 +165,8 @@ class BxDolFormQuery extends BxDolDb {
         return $aForm;
     }
 
-    static public function getDataItems($sKey, $isUseForSet = false, $sUseValues = BX_DATA_VALUES_DEFAULT) {
+    static public function getDataItems($sKey, $isUseForSet = false, $sUseValues = BX_DATA_VALUES_DEFAULT)
+    {
         if ($sUseValues != BX_DATA_VALUES_DEFAULT && $sUseValues != BX_DATA_VALUES_ADDITIONAL)
             $sUseValues = BX_DATA_VALUES_DEFAULT;
 
@@ -174,7 +178,7 @@ class BxDolFormQuery extends BxDolDb {
         if ($isUseForSet)
             $iMaxValue = log(BX_DOL_INT_MAX, 2) + 1;
 
-        $aRet = array();    
+        $aRet = array();
         foreach ($a as $r) {
             if ($isUseForSet && (!is_numeric($r['Value']) || $r['Value'] < 1 || $r['Value'] > $iMaxValue))
                 continue;
@@ -184,7 +188,8 @@ class BxDolFormQuery extends BxDolDb {
         return $aRet;
     }
 
-    public function getFormInputs() {
+    public function getFormInputs()
+    {
         $sQuery = $this->prepare("SELECT * FROM `sys_form_inputs` WHERE `object` = ? ORDER BY `order` ASC", $this->_aObject['object']);
         return $this->getAll($sQuery);
     }

+ 41 - 31
inc/classes/BxDolFtp.php

@@ -9,37 +9,44 @@
 
 bx_import('BxDolFile');
 
-class BxDolFtp extends BxDolFile {
+class BxDolFtp extends BxDolFile
+{
     protected $_sHost;
     protected $_sLogin;
     protected $_sPassword;
     protected $_sPathTo;
     protected $_rStream;
 
-    function __construct($sHost, $sLogin, $sPassword, $sPath = '/') {
+    function __construct($sHost, $sLogin, $sPassword, $sPath = '/')
+    {
         parent::__construct();
         $this->_sHost = $sHost;
         $this->_sLogin = $sLogin;
         $this->_sPassword = $sPassword;
         $this->_sPathTo = $sPath . ('/' == substr($sPath, -1) ? '' : '/');
     }
-    function connect() {
+    function connect()
+    {
         $this->_rStream = ftp_connect($this->_sHost);
         return @ftp_login($this->_rStream, $this->_sLogin, $this->_sPassword);
     }
-    function isDolphin() {
+    function isDolphin()
+    {
         return @ftp_size($this->_rStream, $this->_sPathTo . 'inc/header.inc.php') > 0;
     }
-    function copy($sFilePathFrom, $sFilePathTo) {
+    function copy($sFilePathFrom, $sFilePathTo)
+    {
         $sFilePathTo = $this->_sPathTo . $sFilePathTo;
         return $this->_copyFile($sFilePathFrom, $sFilePathTo);
     }
-    function delete($sPath) {
+    function delete($sPath)
+    {
         $sPath = $this->_sPathTo . $sPath;
         return $this->_deleteDirectory($sPath);
     }
 
-    protected function _copyFile($sFilePathFrom, $sFilePathTo) {
+    protected function _copyFile($sFilePathFrom, $sFilePathTo)
+    {
         if(substr($sFilePathFrom, -1) == '*')
             $sFilePathFrom = substr($sFilePathFrom, 0, -1);
 
@@ -48,31 +55,29 @@ class BxDolFtp extends BxDolFile {
             if($this->_isFile($sFilePathTo)) {
                 $aFileParts = $this->_parseFile($sFilePathTo);
                 if(isset($aFileParts[0]))
-					$this->_ftpMkDirR($aFileParts[0]);
+                    $this->_ftpMkDirR($aFileParts[0]);
 
                 $bResult = @ftp_put($this->_rStream, $sFilePathTo, $sFilePathFrom, FTP_BINARY);
-            } 
-            else if($this->_isDirectory($sFilePathTo)) {
+            } else if($this->_isDirectory($sFilePathTo)) {
                 $this->_ftpMkDirR($sFilePathTo);
                 $aFileParts = $this->_parseFile($sFilePathFrom);
                 if(isset($aFileParts[1]))
                     $bResult = @ftp_put($this->_rStream, $this->_validatePath($sFilePathTo) . $aFileParts[1], $sFilePathFrom, FTP_BINARY);
             }
-        } 
-        else if(is_dir($sFilePathFrom) && $this->_isDirectory($sFilePathTo)) {
+        } else if(is_dir($sFilePathFrom) && $this->_isDirectory($sFilePathTo)) {
             $this->_ftpMkDirR($sFilePathTo);
 
             $aInnerFiles = $this->_readDirectory($sFilePathFrom);
             foreach($aInnerFiles as $sFile)
                 $bResult = $this->_copyFile($this->_validatePath($sFilePathFrom) . $sFile, $this->_validatePath($sFilePathTo) . $sFile);
-        }
-        else
+        } else
             $bResult = false;
 
         return $bResult;
     }
 
-    protected function _deleteDirectory($sPath) {
+    protected function _deleteDirectory($sPath)
+    {
         if($this->_isDirectory($sPath)) {
             if(substr($sPath, -1) != '/')
                 $sPath .= '/';
@@ -85,41 +90,46 @@ class BxDolFtp extends BxDolFile {
                 if(!@ftp_rmdir($this->_rStream, $sPath))
                     return false;
 
-        } 
-        else if(!@ftp_delete($this->_rStream, $sPath))
-			return false;
+        } else if(!@ftp_delete($this->_rStream, $sPath))
+            return false;
 
         return true;
     }
-    protected function _validatePath($sPath) {
+    protected function _validatePath($sPath)
+    {
         if($sPath && substr($sPath, -1) != '/' && $this->_isDirectory($sPath))
             $sPath .= '/';
 
         return $sPath;
     }
-    protected function _parseFile($sFilePath) {
+    protected function _parseFile($sFilePath)
+    {
         $aParts = array();
         preg_match("/^([a-zA-Z0-9@~_\.\\\\\/:-]+[\\\\\/])([a-zA-Z0-9~_-]+\.[a-zA-Z]{2,8})$/", $sFilePath, $aParts) ? true : false;
         return count($aParts) > 1 ? array_slice($aParts, 1) : false;
     }
-    protected function _isFile($sFilePath) {
+    protected function _isFile($sFilePath)
+    {
         return preg_match("/^([a-zA-Z0-9@~_\.\\\\\/:-]+)\.([a-zA-Z]){2,8}$/", $sFilePath) ? true : false;
     }
-    protected function _isDirectory($sFilePath) {
+    protected function _isDirectory($sFilePath)
+    {
         return preg_match("/^([a-zA-Z0-9@~_\.\\\\\/:-]+)[\\\\\/]([a-zA-Z0-9~_-]+)[\\\\\/]?$/", $sFilePath) ? true : false;
     }
-	protected function _setPermissions($sPath, $sMode) {
-		$aConvert = array(
-			'writable' => $this->_isDirectory($sPath) ? 0777 : 0666, 
-			'executable' => 0777
-		);
+    protected function _setPermissions($sPath, $sMode)
+    {
+        $aConvert = array(
+            'writable' => $this->_isDirectory($sPath) ? 0777 : 0666,
+            'executable' => 0777
+        );
 
-    	if(@ftp_chmod($this->_rStream, $aConvert[$sMode], $sPath) === false)
-    		return false;
+        if(@ftp_chmod($this->_rStream, $aConvert[$sMode], $sPath) === false)
+            return false;
 
-		return true;
+        return true;
     }
-    protected function _ftpMkDirR($sPath) {
+    protected function _ftpMkDirR($sPath)
+    {
         $sPwd = ftp_pwd ($this->_rStream);
         $aParts = explode("/", $sPath);
         $sPathFull = '';

+ 101 - 91
inc/classes/BxDolGrid.php

@@ -7,15 +7,14 @@
  * @{
  */
 
-
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section grid Grid
  * @ref BxDolGrid
  */
 
 /**
- * Grid for any content. 
+ * Grid for any content.
  *
  * It allows to display some data as grid with ready to use features:
  * - paginate
@@ -24,12 +23,12 @@
  * - search
  * - actions
  *
- * The advantages of the this system: 
+ * The advantages of the this system:
  * - Less code to write - so you can concentrate on the main functionality.
  * - Flexibility - you can turn on/off ready features or override it for the custom behavior.
  *
  * Grid is working together with Paginate to look through the data in the grid. @see BxDolPaginate
- * 
+ *
  * @section grid_create Creating the new Grid object:
  *
  * 1. add record to 'sys_objects_grid' table:
@@ -88,22 +87,22 @@
  *      - attr_cell: tag attributes for the data cell.
  *      - attr_head: tag attributes for the header cell.
  * - order: order of the field.
- * 
+ *
  * There are some fields which are always available, additionally to the provided set of fields:
- * 
- * - order: display column as dragable handle, it makes sense if you have data ordered by some field 
- *          and it is specified in field_order, field_id and table fields; reordering is not correctly 
- *          working with paginate, so make sure that paginate_per_page number is big enough to show all records; 
+ *
+ * - order: display column as dragable handle, it makes sense if you have data ordered by some field
+ *          and it is specified in field_order, field_id and table fields; reordering is not correctly
+ *          working with paginate, so make sure that paginate_per_page number is big enough to show all records;
  *          reordering is working with Sql source_type.
- * - checkbox: display column with checkboxes, so several records can be selected for bulk action; 
- *          you need to specify 'field_id' field, so every checkbox have unique row id; 
+ * - checkbox: display column with checkboxes, so several records can be selected for bulk action;
+ *          you need to specify 'field_id' field, so every checkbox have unique row id;
  *          you need to specify bulk actions separately in 'sys_grid_actions' table;
  *          you can override '_isCheckboxSelected' function to display checkbox as checked by default.
- * - actions: display column with single actions, displayed as buttons; you need to specify field_id field, 
+ * - actions: display column with single actions, displayed as buttons; you need to specify field_id field,
  *          so every action is provided with unique row id; you need to specify single actions separately in sys_grid_actions table.
- *  
+ *
  * 3. Add actions to sys_grid_actions table:
- * 
+ *
  * - object: name of the Grid object.
  * - type: action type, one of the following:
  *      - bulk: bulk action, to perform on the set of records, the action is usually displaed below the grid.
@@ -114,67 +113,67 @@
  * - icon: display action as icon, title need to be empty in this case.
  * - confirm: ask confirmation before performing the action, 0 or 1.
  * - order: order of the action in particular actions set by type.
- * 
+ *
  * Usually you need to handle actions manually, but there are several actions which are available by default:
- * 
+ *
  * - delete: delete the record, it works automatically when 'source_type' is 'Sql' and 'field_id', 'table' fields are specified.
  *
  *
  *
  * @section grid_display_custom_cell Displaying custom cell
- * 
- * Cell is displayed with default design. It is possible to easily customize its design by specifying custom attributes as 'attr_cell' in params field in sys_grid_fields table. 
  *
- * If it is not enough, you can customize it even more by adding the method to your custom class with the following format: 
+ * Cell is displayed with default design. It is possible to easily customize its design by specifying custom attributes as 'attr_cell' in params field in sys_grid_fields table.
+ *
+ * If it is not enough, you can customize it even more by adding the method to your custom class with the following format:
  * _getCell[field name]
- * where [field name] is the name of the field you want to have custom look with the capital first letter. 
+ * where [field name] is the name of the field you want to have custom look with the capital first letter.
  *
  * For example:
  *
  * @code
- * protected function _getCellStatus ($mixedValue, $sKey, $aField, $aRow) {        
- * 
+ * protected function _getCellStatus ($mixedValue, $sKey, $aField, $aRow) {
+ *
  *     $sAttr = $this->_convertAttrs(
  *         $aField, 'attr_cell',
- *         false, 
+ *         false,
  *         isset($aField['width']) ? 'width:' . $aField['width'] : false // add default styles
  *     );
  *     return '<td ' . $sAttr . '><span style="background-color:' . ('Active' == $mixedValue ? '#cfc' : '#fcc') . '">' . $mixedValue . '</span></td>';
- * } 
+ * }
  * @endcode
- *  
+ *
  * Above example is displaying user's status using different colors depending on the status value. Please note that you need to convert attributes by adding some default classes or styles if you need.
  *
  *
  *
  * @section grid_display_custom_header Displaying custom column header
- * 
+ *
  * This is working similar to displaying custom cell. It easily customize its design by specifying custom attributes as 'attr_head' in params field in sys_grid_fields table.
- * If it is not enough, you can customize it even more by adding the method to your custom class with the following format: 
+ * If it is not enough, you can customize it even more by adding the method to your custom class with the following format:
  * _getCellHeader[field name]
- * where [field name] is the name of the field you want to have custom look with the capital first letter. 
- * 
+ * where [field name] is the name of the field you want to have custom look with the capital first letter.
+ *
  * For example:
  *
  * @code
- * protected function _getCellHeaderStatus ($sKey, $aField) { 
+ * protected function _getCellHeaderStatus ($sKey, $aField) {
  *     $s = parent::_getCellHeaderDefault($sKey, $aField);
  *     return preg_replace ('/<th(.*?)>(.*?)<\/th>/', '<th$1><img src="' . BxDolTemplate::getInstance()->getIconUrl('user.png') . '"></th>', $s);
  * }
  * @endcode
- * 
- * The above example replaces column header text with the image. 
+ *
+ * The above example replaces column header text with the image.
  *
  *
  *
  * @section grid_display_custom_action Displaying custom action
- * 
+ *
  * All actions are displayed as buttons. Bulk and independent actions are displaed as big buttons and single actions are displayed as small buttons.
- * 
+ *
  * It is possible to completely customize it by adding the following method to your custom class:
  * _getAction[action name]
- * where [action name] is the action name with the capital first letter. 
- * 
+ * where [action name] is the action name with the capital first letter.
+ *
  * For example:
  *
  * @code
@@ -186,30 +185,30 @@
  *     return '<button ' . $sAttr . ' onclick="$(this).off(); alert(\'default behaviour is overrided, so the action is not performed\');">' . $a['title'] . '</button>';
  * }
  * @endcode
- * 
+ *
  * The above example disables default onclick event and just displays an alert. Please note that you need to convert attributes by adding some default classes or styles if you need.
  *
- * 
- * 
+ *
+ *
  * @section grid_add_action_handler Add action handler
  *
- * As it was mentioned earlier only several actions can be handled automatically, all other actions must be processed manually. 
- * To add action handler you need to add method to your custom class with the following format: 
+ * As it was mentioned earlier only several actions can be handled automatically, all other actions must be processed manually.
+ * To add action handler you need to add method to your custom class with the following format:
  * performAction[action name]
- * where [action name] is the action name with the capital first letter. 
+ * where [action name] is the action name with the capital first letter.
  *
  * For example:
  *
  * @code
  * public function performActionApprove() {
- * 
+ *
  *     $iAffected = 0;
  *     $aIds = bx_get('ids');
  *     if (!$aIds || !is_array($aIds)) {
  *         $this->_echoResultJson(array());
  *         exit;
  *     }
- * 
+ *
  *     $aIdsAffected = array ();
  *     foreach ($aIds as $mixedId) {
  *         if (!$this->_approve($mixedId))
@@ -217,14 +216,14 @@
  *         $aIdsAffected[] = $mixedId;
  *         $iAffected++;
  *     }
- * 
+ *
  *     $this->_echoResultJson(array(
- *         'msg' => $iAffected > 0 ? sprintf("%d profiles successfully activated", $iAffected) : "Profile(s) activation failed", 
+ *         'msg' => $iAffected > 0 ? sprintf("%d profiles successfully activated", $iAffected) : "Profile(s) activation failed",
  *         'grid' => $this->getCode(false),
  *         'blink' => $aIdsAffected,
  *     ));
  * }
- * 
+ *
  * protected function _approve ($mixedId) {
  *     $oDb = BxDolDb::getInstance();
  *     $sTable = $this->_aOptions['table'];
@@ -233,21 +232,21 @@
  *     return $oDb->query($sQuery);
  * }
  * @endcode
- * 
+ *
  * The action can be used as 'single' or 'bulk', in the case of 'single' action 'ids' array always has one element.
- * 
- * As the result, action must outputs JSON array, which is done by _echoResultJson function. 
+ *
+ * As the result, action must outputs JSON array, which is done by _echoResultJson function.
  * The defined indexes in the array determines behavior after action is performed, the following behaviors are supported:
- * 
+ *
  * - msg: display javascript alert message.
  * - grid: reload grid data with the provided HTML code.
  * - popup: display popup with the provided HTML code.
  * - blink: highlight(blink effect) the specified rows, by the ids.
- * 
+ *
  */
 
-class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable {
-
+class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
+{
     protected $_aMarkers = array ();
 
     protected $_sObject;
@@ -258,7 +257,8 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * Constructor
      * @param $aOptions array of grid options
      */
-    public function __construct($aOptions) {
+    public function __construct($aOptions)
+    {
         parent::__construct();
 
         $this->_sObject = $aOptions['object'];
@@ -270,8 +270,8 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * @param $sObject object name
      * @return object instance or false on error
      */
-    public static function getObjectInstance($sObject) {
-
+    public static function getObjectInstance($sObject)
+    {
         if (isset($GLOBALS['bxDolClasses']['BxDolGrid!'.$sObject]))
             return $GLOBALS['bxDolClasses']['BxDolGrid!'.$sObject];
 
@@ -281,24 +281,25 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
             return false;
 
         bx_import('BxTemplGrid');
-        $sClass = 'BxTemplGrid';        
+        $sClass = 'BxTemplGrid';
         if (!empty($aObject['override_class_name'])) {
             $sClass = $aObject['override_class_name'];
             if (!empty($aObject['override_class_file']))
                 require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
-            else    
+            else
                 bx_import($sClass);
         }
-        
+
         $o = new $sClass($aObject);
-        
+
         if (!$o->_isVisibleGrid($aObject))
             return false;
 
         return ($GLOBALS['bxDolClasses']['BxDolGrid!'.$sObject] = $o);
     }
 
-    public function getObject() {
+    public function getObject()
+    {
         return $this->_sObject;
     }
 
@@ -307,7 +308,8 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * @param $a array of markers as key => value
      * @return true on success or false on error
      */
-    public function addMarkers ($a) {
+    public function addMarkers ($a)
+    {
         if (empty($a) || !is_array($a))
             return false;
         $this->_aMarkers = array_merge ($this->_aMarkers, $a);
@@ -318,21 +320,24 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * Replace provided markers in form array
      * @param $a form description array
      * @return array where markes are replaced with real values
-     */ 
-    protected function _replaceMarkers () {
+     */
+    protected function _replaceMarkers ()
+    {
         $this->_aOptions['source'] = bx_replace_markers($this->_aOptions['source'], $this->_aMarkers);
     }
 
-    protected function _getData ($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage) {
+    protected function _getData ($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage)
+    {
         $sFunc = '_getData' . $this->_aOptions['source_type'];
         return $this->$sFunc($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage);
     }
 
-    protected function _getDataArray ($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage) {
+    protected function _getDataArray ($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage)
+    {
         if ($this->_aOptions['source'] && !is_array($this->_aOptions['source'])) {
             $this->_aOptions['source'] = unserialize($this->_aOptions['source']);
         }
-        
+
         // apply filter
         if ($sFilter && (!empty($this->_aOptions['filter_fields']) || !empty($this->_aOptions['filter_fields_translatable']))) {
             $aSource = array();
@@ -365,10 +370,10 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
         $sSortField = false;
         $iSortDir = 1;
         if ($sOrderField && !empty($this->_aOptions['sorting_fields']) && is_array($this->_aOptions['sorting_fields']) && in_array($sOrderField, $this->_aOptions['sorting_fields'])) { // explicit order
-            $sSortField = $sOrderField; 
+            $sSortField = $sOrderField;
             $iSortDir = 0 == strcasecmp($sOrderDir, 'desc') ? -1 : 1;
         } elseif (!empty($this->_aOptions['field_order'])) { // order by "order" field
-            $sSortField = $this->_aOptions['field_order']; 
+            $sSortField = $this->_aOptions['field_order'];
         }
 
         if ($sSortField) {
@@ -383,12 +388,13 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
         return array_slice($aSourceOrdered, $iStart, $iPerPage, true);
     }
 
-   protected function _getDataSql ($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage) {
+   protected function _getDataSql ($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage)
+   {
         $oDb = BxDolDb::getInstance();
         $sQuery = $this->_aOptions['source'];
 
         if (false === stripos($sQuery, ' WHERE '))
-            $sQuery .= " WHERE 1 ";        
+            $sQuery .= " WHERE 1 ";
 
         // add filter condition
         $sOrderByFilter = '';
@@ -410,7 +416,7 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
                 if (!empty($this->_aOptions['filter_fields_translatable'])) {
                     $sCondFields = '';
                     foreach ($this->_aOptions['filter_fields_translatable'] as $sField)
-                        $sCondFields .= "`k`.`Key` = `{$sField}` OR "; 
+                        $sCondFields .= "`k`.`Key` = `{$sField}` OR ";
 
                     $sCondFields = rtrim($sCondFields, ' OR ');
 
@@ -427,7 +433,7 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
 
                     $sCondFields = '';
                     foreach ($this->_aOptions['filter_fields'] as $sField)
-                        $sCondFields .= "`{$sField}`,"; 
+                        $sCondFields .= "`{$sField}`,";
 
                     $sCondFields = rtrim($sCondFields, ',');
 
@@ -458,31 +464,31 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
                 $sQuery .= ' AND (' . $sCond . ')';
         }
 
-        // add order 
+        // add order
         $sQuery .= $this->_getDataSqlOrderClause ($sOrderByFilter, $sOrderField, $sOrderDir);
-                
+
 
         $sQuery = $sQuery . $oDb->prepare(' LIMIT ?, ?', $iStart, $iPerPage);
         return $oDb->getAll($sQuery);
     }
 
-    protected function _getDataSqlOrderClause ($sOrderByFilter, $sOrderField, $sOrderDir) {
-
+    protected function _getDataSqlOrderClause ($sOrderByFilter, $sOrderField, $sOrderDir)
+    {
         $sOrderClause = '';
 
-        if ($sOrderField && is_array($this->_aOptions['sorting_fields']) && in_array($sOrderField, $this->_aOptions['sorting_fields'])) { // explicit order 
+        if ($sOrderField && is_array($this->_aOptions['sorting_fields']) && in_array($sOrderField, $this->_aOptions['sorting_fields'])) { // explicit order
 
             $sDir = (0 == strcasecmp($sOrderDir, 'desc') ? 'DESC' : 'ASC');
 
-            if (is_array($this->_aOptions['sorting_fields_translatable']) && in_array($sOrderField, $this->_aOptions['sorting_fields_translatable'])) { 
+            if (is_array($this->_aOptions['sorting_fields_translatable']) && in_array($sOrderField, $this->_aOptions['sorting_fields_translatable'])) {
 
-                // translatable fields            
+                // translatable fields
                 bx_import('BxDolLanguages');
                 $iLang = BxDolLanguages::getInstance()->getCurrentLangId();
                 $oDb = BxDolDb::getInstance();
                 $sOrderClause = $oDb->prepare("ORDER BY (SELECT `s`.`string` FROM `sys_localization_strings` AS `s` INNER JOIN `sys_localization_keys` AS `k` ON (`k`.`ID` = `s`.`IDKey`) WHERE `k`.`KEY` = `$sOrderField` AND `s`.`IDLanguage` = ? LIMIT 1) ", $iLang) . $sDir;
 
-            } else { 
+            } else {
 
                 // regular fields
                 $sOrderClause = " ORDER BY `$sOrderField` $sDir";
@@ -498,19 +504,20 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
             if (false == strpos($this->_aOptions['field_order'], ',')) {
                 $sOrderClause = " ORDER BY `" . $this->_aOptions['field_order'] . "` " . $this->_sDefaultSortingOrder;
             } else {
-                $a = explode(',', $this->_aOptions['field_order']);                
+                $a = explode(',', $this->_aOptions['field_order']);
                 foreach ($a as $sField)
                     $sOrderClause .= "`" . trim($sField) . "` " . $this->_sDefaultSortingOrder . ", ";
                 if ($sOrderClause)
                     $sOrderClause = " ORDER BY " . trim($sOrderClause, ', ');
             }
 
-        } 
+        }
 
         return $sOrderClause;
-    }    
+    }
 
-    protected function _getCellData($sKey, $aField, $aRow) {
+    protected function _getCellData($sKey, $aField, $aRow)
+    {
         if (isset($aRow[$sKey])) {
             if (!empty($aField['display'])) {
                 bx_import('BxDolForm');
@@ -525,16 +532,19 @@ class BxDolGrid extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
         }
     }
 
-    protected function _cmp ($r1, $r2) {        
+    protected function _cmp ($r1, $r2)
+    {
         $iRet = strcasecmp($r1[$this->_tmpOrderField], $r2[$this->_tmpOrderField]);
         return $iRet ? $this->_tmpOrderDir * $iRet : 0;
     }
 
-    protected function _genMethodName ($s) {
+    protected function _genMethodName ($s)
+    {
         return bx_gen_method_name($s);
     }
 
-    protected function _isVisibleGrid ($a) {
+    protected function _isVisibleGrid ($a)
+    {
         bx_import('BxDolAcl');
         if (!isset($a['visible_for_levels']))
             return true;

+ 8 - 7
inc/classes/BxDolGridConnections.php

@@ -11,19 +11,19 @@ require_once(BX_DIRECTORY_PATH_INC . "design.inc.php");
 
 bx_import('BxTemplGrid');
 
-class BxDolGridConnections extends BxTemplGrid 
+class BxDolGridConnections extends BxTemplGrid
 {
     protected $_bOwner = false;
     protected $_sContentModule = 'bx_persons';
     protected $_sObjectConnections = 'sys_profiles_friends';
 
-    public function __construct ($aOptions, $oTemplate = false) 
+    public function __construct ($aOptions, $oTemplate = false)
     {
         parent::__construct ($aOptions, $oTemplate);
         $this->_sDefaultSortingOrder = 'DESC';
 
         $iProfileId = bx_process_input(bx_get('profile_id'), BX_DATA_INT);
-        if (!$iProfileId) 
+        if (!$iProfileId)
             return;
 
         bx_import('BxDolProfile');
@@ -51,7 +51,7 @@ class BxDolGridConnections extends BxTemplGrid
     /**
      * 'accept' action handler
      */
-    public function performActionAccept() 
+    public function performActionAccept()
     {
         $iId = 0;
         $aIds = bx_get('ids');
@@ -76,12 +76,13 @@ class BxDolGridConnections extends BxTemplGrid
     /**
      * 'add friend' action handler
      */
-    public function performActionAddFriend() 
+    public function performActionAddFriend()
     {
         return $this->performActionAccept();
     }
 
-    protected function _delete ($mixedId) {
+    protected function _delete ($mixedId)
+    {
         bx_import('BxDolConnection');
         $oConn = BxDolConnection::getObjectInstance($this->_sObjectConnections);
 
@@ -99,7 +100,7 @@ class BxDolGridConnections extends BxTemplGrid
         $oProfile = BxDolProfile::getInstance($aRow['id']);
         if (!$oProfile)
             return _t('_sys_txt_error_occured');
-        
+
         return parent::_getCellDefault ($oProfile->getUnit(), $sKey, $aField, $aRow);
     }
 

+ 11 - 8
inc/classes/BxDolGridQuery.php

@@ -13,19 +13,22 @@ bx_import('BxDolDb');
  * Database queries for grid.
  * @see BxDolGrid
  */
-class BxDolGridQuery extends BxDolDb {
+class BxDolGridQuery extends BxDolDb
+{
     protected $_aObject;
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
     }
 
-    static public function getGridObject ($sObject) {
+    static public function getGridObject ($sObject)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_grid` WHERE `object` = ?", $sObject);
-        $aObject = $oDb->getRow($sQuery);        
-        if (!$aObject || !is_array($aObject)) 
+        $aObject = $oDb->getRow($sQuery);
+        if (!$aObject || !is_array($aObject))
             return false;
 
         // paginate
@@ -64,7 +67,7 @@ class BxDolGridQuery extends BxDolDb {
                 continue;
             $aAdd = unserialize($aRow['params']);
             if (!empty($aAdd) && is_array($aAdd))
-                $aObject['fields'][$sKey] = array_merge($aObject['fields'][$sKey], $aAdd); 
+                $aObject['fields'][$sKey] = array_merge($aObject['fields'][$sKey], $aAdd);
         }
         // get actions
         $a = array('bulk','single','independent');
@@ -73,12 +76,12 @@ class BxDolGridQuery extends BxDolDb {
             $aObject[$sActionField] = array();
             $sQuery = $oDb->prepare("SELECT * FROM `sys_grid_actions` WHERE `object` = ? AND `type` = ? ORDER BY `order`", $sObject, $sActionType);
             $aActions = $oDb->getAllWithKey($sQuery, 'name');
-            if (!$aActions || !is_array($aActions)) 
+            if (!$aActions || !is_array($aActions))
                 continue;
             foreach ($aActions as $sKey => $aRow)
                 $aObject[$sActionField][$sKey] = $aRow['title'] || $aRow['icon'] ? array('title' => _t($aRow['title']), 'icon' => $aRow['icon'], 'confirm' => $aRow['confirm']) : array();
         }
-        
+
         return $aObject;
     }
 

+ 17 - 9
inc/classes/BxDolGzip.php

@@ -7,7 +7,8 @@
  * @{
  */
 
-class BxDolGzip extends BxDol {
+class BxDolGzip extends BxDol
+{
     protected $_sType;
     protected $_bGzip;
     protected $_sEncoding;
@@ -19,7 +20,8 @@ class BxDolGzip extends BxDol {
     protected $_sOutContent;
     protected $_sOutContentZipped;
 
-    function __construct($sFile) {
+    function __construct($sFile)
+    {
         parent::__construct();
 
         $this->_iExpirationOffset = 3600 * 24 * 10;
@@ -44,7 +46,8 @@ class BxDolGzip extends BxDol {
         $this->_sOutContentZipped = "";
     }
 
-    static function load($sFile) {
+    static function load($sFile)
+    {
         $oLoader = new BxDolGzip($sFile);
 
         $oLoader->prepare();
@@ -52,7 +55,8 @@ class BxDolGzip extends BxDol {
         $oLoader->output();
     }
 
-    function prepare() {
+    function prepare()
+    {
         header("Content-type: text/" . $this->_sType);
         header("Vary: Accept-Encoding");
         header("Expires: " . gmdate("D, d M Y H:i:s", time() + $this->_iExpirationOffset) . " GMT");
@@ -67,14 +71,16 @@ class BxDolGzip extends BxDol {
         }
     }
 
-    function read() {
+    function read()
+    {
         if($this->_bGzip && file_exists($this->_sOutFile))
             $this->_sOutContentZipped = $this->getFileContents($this->_sOutFile);
         else
             $this->_sOutContent = $this->getFileContents($this->_sInFile);
     }
 
-    function output() {
+    function output()
+    {
         if(!$this->_bGzip) {
             echo $this->_sOutContent;
             return;
@@ -87,7 +93,7 @@ class BxDolGzip extends BxDol {
         }
 
         if (!$this->_sOutContent)
-            return;        
+            return;
 
         $this->_sOutContentZipped = gzencode($this->_sOutContent, 9, FORCE_GZIP);
         $this->putFileContents($this->_sOutFile, $this->_sOutContentZipped);
@@ -95,7 +101,8 @@ class BxDolGzip extends BxDol {
         echo $this->_sOutContentZipped;
     }
 
-    function getFileContents($sPath) {
+    function getFileContents($sPath)
+    {
         $sPath = realpath($sPath);
 
         if(!$sPath || !@is_file($sPath))
@@ -116,7 +123,8 @@ class BxDolGzip extends BxDol {
         return $sContent;
     }
 
-    function putFileContents($sPath, $sContent) {
+    function putFileContents($sPath, $sContent)
+    {
         if (function_exists("file_put_contents"))
             return @file_put_contents($sPath, $sContent);
 

+ 1 - 1
inc/classes/BxDolIO.php

@@ -9,7 +9,7 @@
 
 class BxDolIO extends BxDol
 {
-    function __construct() 
+    function __construct()
     {
         parent::__construct();
     }

+ 69 - 77
inc/classes/BxDolImageResize.php

@@ -22,7 +22,6 @@ define( 'IMAGE_ERROR_GD_WRITE_FAILED',       10 );
 define( 'IMAGE_ERROR_GD_TTF_NOT_SUPPORTED',  11 );
 define( 'IMAGE_ERROR_GD_FILTER_ERROR',       12 );
 
-
 // Image types for GD
 // NOTE: actually these constants exist in PHP >= 4.3.0, but they are included for
 //       back compatibility
@@ -30,8 +29,8 @@ define( 'IMAGE_TYPE_GIF',         1 );
 define( 'IMAGE_TYPE_JPG',         2 );
 define( 'IMAGE_TYPE_PNG',         3 );
 
-class BxDolImageResize extends BxDol implements iBxDolSingleton {
-
+class BxDolImageResize extends BxDol implements iBxDolSingleton
+{
     protected $w = 64, $h = 64; ///< size of destination image
     protected $_isCrop = false;
     protected $_isAutoCrop = false;
@@ -41,8 +40,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
     protected $_isSquareResize = false; ///< use smart resize, destination image will be exact Width x Height size
     protected $_isUseGD; ///< use GD library or command line ImagMagic utilites
 
-    function __construct() {
-
+    function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -54,7 +53,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -62,15 +62,16 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
+    public static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolImageResize();
 
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    function isAllowedImage ($sPath) {
-
+    function isAllowedImage ($sPath)
+    {
         if ($this->_isUseGD) {
             $aImage = getimagesize($sPath);
             if (!empty($aImage) && in_array($aImage[2], array(1, 2, 3)))
@@ -81,7 +82,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         return false;
     }
 
-    function resize ($mixedImage, $sDstImage = '') {
+    function resize ($mixedImage, $sDstImage = '')
+    {
         if (is_array($mixedImage)) {
             $aRet = array();
             foreach ($mixedImage as $s) {
@@ -93,7 +95,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         }
     }
 
-    function applyWatermark ($mixedImage, $sDstImage, $wtrFilename, $wtrTransparency) {
+    function applyWatermark ($mixedImage, $sDstImage, $wtrFilename, $wtrTransparency)
+    {
         if (is_array($mixedImage)) {
             $aRet = array();
             foreach ($mixedImage as $s) {
@@ -105,7 +108,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         }
     }
 
-    function grayscale ($mixedImage, $sDstImage = '') {
+    function grayscale ($mixedImage, $sDstImage = '')
+    {
         if (is_array($mixedImage)) {
             $aRet = array();
             foreach ($mixedImage as $s) {
@@ -117,17 +121,20 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         }
     }
 
-    function setSize ($w, $h) {
+    function setSize ($w, $h)
+    {
         $this->w = $w;
         $this->h = $h;
     }
 
-    function removeCropOptions () {
+    function removeCropOptions ()
+    {
         $this->_isCrop = false;
         $this->_isAutoCrop = false;
     }
 
-    function setCropOptions ($x, $y, $w, $h) {
+    function setCropOptions ($x, $y, $w, $h)
+    {
         $this->_isCrop = true;
         $this->_cropX = $x;
         $this->_cropY = $y;
@@ -138,38 +145,46 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
     /**
      * Crop image to destination size with filling whole area of destination size
      */
-    function setAutoCrop ($b) {
+    function setAutoCrop ($b)
+    {
         $this->_isAutoCrop = $b;
     }
 
-    function setJpegOutput ($b) {
+    function setJpegOutput ($b)
+    {
         $this->setOutputType($b ? IMAGE_TYPE_JPG : false);
     }
 
-    function setOutputType ($iType) {
+    function setOutputType ($iType)
+    {
         $this->_iForceOutputType = $iType;;
     }
 
-    function setJpegQuality ($i) {
+    function setJpegQuality ($i)
+    {
         $this->_iJpegQuality = $i;
     }
 
-    function setSquareResize ($b) {
+    function setSquareResize ($b)
+    {
         $this->_isSquareResize = ($b ? true : false);
     }
 
-    function isUsedGD () {
+    function isUsedGD ()
+    {
         return $this->_isUseGD;
     }
 
-    function getImageSize($sPath) {
+    function getImageSize($sPath)
+    {
         $aSize = getimagesize($sPath);
         return array ('w' => $aSize[0], 'h' => $aSize[1]);
     }
 
     // private functions are below -------------------------------
 
-    function _grayscale ($sSrcImage, $sDstImage = '') {
+    function _grayscale ($sSrcImage, $sDstImage = '')
+    {
         if (!file_exists($sSrcImage))
             return IMAGE_ERROR_SOURCE_NOT_EXISTS;
 
@@ -183,8 +198,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         return $this->_isUseGD ? $this->_grayscaleGD ($sSrcImage, $sDstImage) : $this->_grayscaleImageMagick ($sSrcImage, $sDstImage);
     }
 
-    function _grayscaleGD ($sSrcImage, $sDstImage) {
-
+    function _grayscaleGD ($sSrcImage, $sDstImage)
+    {
         $iErr = 0;
         $src_im =& $this->_createGDImage($sSrcImage, $size, $iErr);
 
@@ -193,7 +208,7 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         if (!$src_im)
             return IMAGE_ERROR_GD_OPEN_FAILED;
 
-        if (!imagefilter($src_im, IMG_FILTER_GRAYSCALE)) 
+        if (!imagefilter($src_im, IMG_FILTER_GRAYSCALE))
             return IMAGE_ERROR_GD_FILTER_ERROR;
 
         $writeResult = $this->_writeImageGD ($src_im, $sDstImage, $size[2]);
@@ -207,8 +222,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         return IMAGE_ERROR_GD_WRITE_FAILED;
     }
 
-    function _grayscaleImageMagick ($sSrcImage, $sDstImage) {
-
+    function _grayscaleImageMagick ($sSrcImage, $sDstImage)
+    {
         $cmd = "{$GLOBALS['CONVERT']} \"$sSrcImage\" -type Grayscale -quantize Gray \"$sDstImage\"";
         @exec( $cmd );
 
@@ -218,7 +233,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         return IMAGE_ERROR_IMAGEMAGICK_ERROR;
     }
 
-    function _resize ($sSrcImage, $sDstImage = '') {
+    function _resize ($sSrcImage, $sDstImage = '')
+    {
         if (!file_exists($sSrcImage))
             return IMAGE_ERROR_SOURCE_NOT_EXISTS;
 
@@ -232,8 +248,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         return $this->_isUseGD ? $this->_resizeGD ($sSrcImage, $sDstImage) : $this->_resizeImageMagick ($sSrcImage, $sDstImage);
     }
 
-    function _resizeGD ($sSrcImage, $sDstImage) {
-
+    function _resizeGD ($sSrcImage, $sDstImage)
+    {
         $iErr = 0;
         $src_im =& $this->_createGDImage($sSrcImage, $size, $iErr);
         $sizeOrig = $size;
@@ -310,29 +326,22 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         }
 
         // this is more qualitative function, but it doesn't exist in old GD and doesn't support GIF format
-        if ( function_exists( 'imagecreatetruecolor' ) && $size[2] != IMAGE_TYPE_GIF )
-        {
+        if ( function_exists( 'imagecreatetruecolor' ) && $size[2] != IMAGE_TYPE_GIF ) {
             // resize only if size is larger than needed
-            if ( $this->_isCrop || $sizeOrig[0] > $this->w || $sizeOrig[1] > $this->h )
-            {
+            if ( $this->_isCrop || $sizeOrig[0] > $this->w || $sizeOrig[1] > $this->h ) {
                 $dst_im = imagecreatetruecolor( $destW, $destH );
                 imagecolortransparent($dst_im, imagecolorallocate($dst_im, 0, 0, 0));
                 imagealphablending($dst_im, false);
                 imagesavealpha($dst_im, true);
                 $convertResult = imagecopyresampled( $dst_im, $src_im, $xd, $yd, $xs, $ys,
                     $destW, $destH, $size[0], $size[1] );
-            }
-            else
-            {
+            } else {
                 $dst_im = $src_im;
                 $convertResult = true;
             }
-        }
-        else // this is for old GD versions and for GIF images
-        {
+        } else { // this is for old GD versions and for GIF images
             // resize only if size is larger than needed
-            if ( $size[0] > $this->w || $size[1] > $this->h )
-            {
+            if ( $size[0] > $this->w || $size[1] > $this->h ) {
                 $dst_im = imagecreate( $destW, $destH );
                 if ($size[2] == IMAGE_TYPE_GIF) {
                     ImageColorTransparent( $dst_im, imagecolorallocate($dst_im, 0, 0, 0) );
@@ -340,9 +349,7 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
                 }
                 $convertResult = imagecopyresized( $dst_im, $src_im, $xd, $yd, $xs, $ys,
                     $destW, $destH, $size[0], $size[1] );
-            }
-            else
-            {
+            } else {
                 $dst_im = $src_im;
                 $convertResult = true;
             }
@@ -354,13 +361,10 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         $writeResult = $this->_writeImageGD ($dst_im, $sDstImage, $size[2]);
 
         // free memory
-        if ( $dst_im != $src_im )
-        {
+        if ( $dst_im != $src_im ) {
             imagedestroy( $src_im );
             imagedestroy( $dst_im );
-        }
-        else
-        {
+        } else {
             imagedestroy( $src_im );
         }
 
@@ -370,19 +374,16 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         return IMAGE_ERROR_GD_WRITE_FAILED;
     }
 
-    function _resizeImageMagick ($sSrcImage, $sDstImage) {
-
+    function _resizeImageMagick ($sSrcImage, $sDstImage)
+    {
         // TODO: $this->_isCrop and $this->_isSquareResize
-        if ( $sSrcImage == $sDstImage )
-        {
+        if ( $sSrcImage == $sDstImage ) {
             $cmd = "{$GLOBALS['MOGRIFY']} -geometry {$this->w}\">\"x{$this->h}\">\" \"$sSrcImage\"";
             @exec( $cmd );
             $nameWithoutExt = substr( $sSrcImage, 0, strrpos($sSrcImage, '.') );
             if ( file_exists( "{$nameWithoutExt}.mgk" ) )
                 rename( "{$nameWithoutExt}.mgk", $sSrcImage );
-        }
-        else
-        {
+        } else {
             $cmd = "{$GLOBALS['CONVERT']} \"$sSrcImage\" -geometry {$this->w}\">\"x{$this->h}\">\" \"$sDstImage\"";
             @exec( $cmd );
         }
@@ -393,7 +394,6 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         return IMAGE_ERROR_IMAGEMAGICK_ERROR;
     }
 
-
     function _applyWatermark( $srcFilename, $dstFilename, $wtrFilename, $wtrTransparency )
     {
         // TODO: watermard are not applied correctly, becuase images of different suzes are used, FIX IT
@@ -411,18 +411,15 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         if ( $srcFilename == $dstFilename )
             chmod( $dstFilename, 0666 );
 
-        if ( $this->_isUseGD )
-        {
+        if ( $this->_isUseGD ) {
             return $this->_applyWatermarkGD($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency);
-        }
-        else
-        {
+        } else {
             return $this->_applyWatermarkImageMagick($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency);
         }
     }
 
-    function _applyWatermarkGD($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency) {
-
+    function _applyWatermarkGD($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency)
+    {
         $iErr = 0;
 
         $src_im =& $this->_createGDImage($srcFilename, $size, $iErr);
@@ -450,7 +447,6 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         if (!$copyResult)
             return IMAGE_ERROR_GD_MERGE_ERROR;
 
-
         imagealphablending($wtr_im, false);
         imagesavealpha($wtr_im, true);
 
@@ -462,8 +458,7 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         if ( !$mergeResult )
             return IMAGE_ERROR_GD_MERGE_ERROR;
 
-        switch ( $size[2] )
-        {
+        switch ( $size[2] ) {
             case IMAGE_TYPE_GIF:
                 $writeResult = imagegif( $dst_im, $dstFilename );
                 break;
@@ -486,10 +481,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
             return IMAGE_ERROR_GD_WRITE_FAILED;
     }
 
-
-
-    function _applyWatermarkImageMagick($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency) {
-
+    function _applyWatermarkImageMagick($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency)
+    {
         $imgTransparency = 100 - $wtrTransparency;
         $cmd = "{$GLOBALS['COMPOSITE']} -gravity \"South\" -dissolve \"$imgTransparency\" \"$wtrFilename\" -dissolve $wtrTransparency \"$srcFilename\" \"$dstFilename\"";
         @exec( $cmd );
@@ -508,8 +501,7 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         $aSize = getimagesize($s);
 
         // only GIF, JPG and PNG allowed
-        switch ( $aSize[2] )
-        {
+        switch ( $aSize[2] ) {
             case IMAGE_TYPE_GIF:
                 if (!isset($this->gdInfoArray['GIF Read Support']) || !$this->gdInfoArray['GIF Read Support'] || !isset($this->gdInfoArray['GIF Create Support']) || !$this->gdInfoArray['GIF Create Support'])
                     return ($iErr = IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED);
@@ -530,8 +522,8 @@ class BxDolImageResize extends BxDol implements iBxDolSingleton {
         }
     }
 
-    function _writeImageGD ($src_im, $sDstImage, $iSrcImageType) {
-
+    function _writeImageGD ($src_im, $sDstImage, $iSrcImageType)
+    {
         $writeResult = false;
 
         switch ($this->_iForceOutputType){

+ 107 - 83
inc/classes/BxDolImageTranscoder.php

@@ -10,15 +10,15 @@
 bx_import('BxDolStorage');
 bx_import('BxDolImageTranscoderQuery');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section images_transcoder Images Transcoder
  * @ref BxDolImageTranscoder
  */
 
 /**
- * This class transcodes images on the fly. 
- * Transcoded image is saved in the specified storage engine and next time ready image is served. 
+ * This class transcodes images on the fly.
+ * Transcoded image is saved in the specified storage engine and next time ready image is served.
  *
  *
  * To add image transcoder object add record to 'sys_objects_transcoder_images' table:
@@ -33,28 +33,28 @@ bx_import('BxDolImageTranscoderQuery');
  * - atime_tracking - track last access time to the transcoded data, allowed values 0 - disables or 1 - enabled.
  * - atime_pruning - prune transcoded images by last access time, if last access time of the image is older than atime_pruning seconds - it is deleted, it works when atime_tracking is enabled
  * - ts - unix timestamp of the last change of transcoder parameters, if transcoded image is older than this value - image is deleted and transcoded again.
- * 
+ *
  *
  * Then you need to add image filters to 'sys_transcoder_images_filters' table:
  * - transcoder_object - name of the transcoded object to apply filter to.
  * - filter - filter name, please read futher for available filters.
  * - filter_params - serialized array of filter params, please read futher for particular filters params.
  * - order - if there are several filters for one object, they will be applied in this order.
- * 
- * 
+ *
+ *
  * 'Folder' source types:
  * This source type is some folder with original images for the transcoding, the identifier of the image (handler) is file name.
  * The params are the following:
  * - path - path to the folder with original images
  * This source type has some limitation:
  * - automatic detection of private files is not supported
- * - transcoded file is not automaticlaly deleted/renewed if original file is changed 
+ * - transcoded file is not automaticlaly deleted/renewed if original file is changed
  *
  *
  * 'Storage' source type:
  * The source of original files is Storage engine, the identifier of the image (handler) is file id.
  * The params are the following:
- * - object - name of the Storage object 
+ * - object - name of the Storage object
  *
  *
  * Available filters:
@@ -66,22 +66,22 @@ bx_import('BxDolImageTranscoderQuery');
  * - Grayscale - make image grayscale, there is no parameters for this filter
  *
  *
- * Automatic deletetion of associated data is supported - in the case if original or transcoded file is deleted, 
- * but you need to register alert handlers, just call registerHandlers () function to register handler (for example, during module installation) 
+ * Automatic deletetion of associated data is supported - in the case if original or transcoded file is deleted,
+ * but you need to register alert handlers, just call registerHandlers () function to register handler (for example, during module installation)
  * and call unregisterHandlers () function to unregister handlers (for example, during module uninstallation)
- * 
+ *
  *
  * Example of usage:
  * @code
  * bx_import('BxDolImageTranscoder');
  * $oTranscoder = BxDolImageTranscoder::getObjectInstance('bx_images_thumb'); // change images transcode object name to your own
- * $oTranscoder->registerHandlers(); // make sure to call it only once! before the first usage, no need to call it every time 
+ * $oTranscoder->registerHandlers(); // make sure to call it only once! before the first usage, no need to call it every time
  * $sTranscodedImageUrl = $oTranscoder->getImageUrl('my_dog.jpg'); // the name of file, in the case of 'Folder' storage type this is file name
  * echo 'My dog : <img src="' . $sUrl . '" />'; // transcoded(resized and/or grayscaled) image will be shown, according to the specified filters
  * @endcode
  *
  */
-class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject 
+class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
 {
     protected $_aObject; ///< object properties
     protected $_oStorage; ///< storage object, transcoded images are stored here
@@ -91,10 +91,11 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
     /**
      * constructor
      */
-    protected function __construct($aObject, $oStorage) {
+    protected function __construct($aObject, $oStorage)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
-        $this->_oStorage = $oStorage;        
+        $this->_oStorage = $oStorage;
         $this->_oDb = new BxDolImageTranscoderQuery($aObject);
     }
 
@@ -103,13 +104,13 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
      * @param $sObject - name of trancode object.
      * @return false on error or instance of BxDolImageTranscoder class.
      */
-    public static function getObjectInstance($sObject) {
-
+    public static function getObjectInstance($sObject)
+    {
         if (isset($GLOBALS['bxDolClasses']['BxDolImageTranscoder!'.$sObject]))
             return $GLOBALS['bxDolClasses']['BxDolImageTranscoder!'.$sObject];
- 
+
         // get transcode object
-        $aObject = BxDolImageTranscoderQuery::getTranscoderObject($sObject); 
+        $aObject = BxDolImageTranscoderQuery::getTranscoderObject($sObject);
         if (!$aObject || !is_array($aObject))
             return false;
 
@@ -131,10 +132,11 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
 
     /**
      * Delete outdated transcoed data from all transcoeeed objects, by last access time.
-     * It called on cron, usually every day. 
+     * It called on cron, usually every day.
      * @return total number of pruned/deleted files
      */
-    static public function pruning () {
+    static public function pruning ()
+    {
         $iCount = 0;
         $aObjects = BxDolImageTranscoderQuery::getTranscoderObjects ();
         foreach ($aObjects as $aObject) {
@@ -151,48 +153,53 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
     /**
      * Register handlers array
      * It can be called upon module enable event.
-     * @param $mixed array of transcoders objects, or just one object 
+     * @param $mixed array of transcoders objects, or just one object
      */
-    static public function registerHandlersArray ($mixed) {
+    static public function registerHandlersArray ($mixed)
+    {
         self::_callFuncForObjectsArray ($mixed, 'registerHandlers');
     }
 
     /**
      * Unregister handlers array
      * It can be called upon module disbale event.
-     * @param $mixed array of transcoders objects, or just one object 
+     * @param $mixed array of transcoders objects, or just one object
      */
-    static public function unregisterHandlersArray ($mixed) {
+    static public function unregisterHandlersArray ($mixed)
+    {
         self::_callFuncForObjectsArray ($mixed, 'unregisterHandlers');
     }
 
     /**
      * Cleanup (queue for deletion all resized files)
      * It can be called upon module disbale event.
-     * @param $mixed array of transcoders objects, or just one object 
+     * @param $mixed array of transcoders objects, or just one object
      */
-    static public function cleanupObjectsArray ($mixed) {
+    static public function cleanupObjectsArray ($mixed)
+    {
         self::_callFuncForObjectsArray ($mixed, 'cleanup');
     }
 
     /**
      * Called automatically, upon local(transcoded) file deletetion.
      */
-    static public function onAlertResponseFileDeleteLocal ($oAlert, $sObject) {
+    static public function onAlertResponseFileDeleteLocal ($oAlert, $sObject)
+    {
         $oTranscoder = BxDolImageTranscoder::getObjectInstance($sObject);
         if (!$oTranscoder)
             return;
 
         if ($oAlert->sAction != 'file_deleted')
             return;
-        
+
         $oTranscoder->onDeleteFileLocal($oAlert->iObject);
     }
 
     /**
      * Called automatically, upon original file deletetion.
      */
-    static public function onAlertResponseFileDeleteOrig ($oAlert, $sObject) {
+    static public function onAlertResponseFileDeleteOrig ($oAlert, $sObject)
+    {
         $oTranscoder = BxDolImageTranscoder::getObjectInstance($sObject);
         if (!$oTranscoder)
             return;
@@ -206,20 +213,22 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
     /**
      * Called automatically, upon local(transcoded) file deletetion.
      */
-    public function onDeleteFileLocal($iFileId) {
+    public function onDeleteFileLocal($iFileId)
+    {
         return $this->_oDb->deleteFileTraces($iFileId);
     }
 
     /**
      * Called automatically, upon original file deletetion.
      */
-    public function onDeleteFileOrig($mixedHandler) {
+    public function onDeleteFileOrig($mixedHandler)
+    {
         // delete main file
         $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
         if (!$iFileId)
             return false;
 
-        if (!$this->_oStorage->deleteFile($iFileId)) 
+        if (!$this->_oStorage->deleteFile($iFileId))
             return false;
 
         // delete retina file
@@ -234,7 +243,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
      * Register necessary alert handlers for automatic deletetion of transcoded data if source file is deleted.
      * Make sure that you call it once, before first usage, for example upon module installation.
      */
-    public function registerHandlers () {
+    public function registerHandlers ()
+    {
         if (!$this->_oDb->registerHandlers ())
             return false;
         return $this->clearCacheDB();
@@ -244,7 +254,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
      * Unregister alert handlers for automatic deletetion of transcoded data if source file is deleted.
      * Make sure that you call it once, for example upon module uninstallation.
      */
-    public function unregisterHandlers () {
+    public function unregisterHandlers ()
+    {
         if (!$this->_oDb->unregisterHandlers ())
             return false;
         return $this->clearCacheDB();
@@ -253,26 +264,28 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
     /**
      * Delete (queue for deletion) all resized files for the current object
      */
-    public function cleanup () {
+    public function cleanup ()
+    {
         return $this->_oStorage->queueFilesForDeletionFromObject();
     }
 
     /**
-     * Get storage object where transcoded data is stored    
+     * Get storage object where transcoded data is stored
      */
-    public function getStorage() {
+    public function getStorage()
+    {
         return $this->_oStorage;
     }
 
     /**
-     * Get transcoded image url. 
-     * If transcoded image is ready then direct url to this image is returned. 
+     * Get transcoded image url.
+     * If transcoded image is ready then direct url to this image is returned.
      * If there is no transcoded data available, then special url is returned, upon opening this url image is transcoded automatically and redirects to the ready transcoed image.
      * @params $mixedHandler - image handler
      * @return image url, or false on error.
      */
-    public function getImageUrl($mixedHandler) {
-
+    public function getImageUrl($mixedHandler)
+    {
         if ($this->isImageReady($mixedHandler)) {
 
             $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
@@ -298,27 +311,28 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
      * Check if transcoded data is available. No need to call it directly, it is called automatically when it is needed.
      * @params $mixedHandler - image handler
      * @params $isCheckOutdated - check if transcoded image outdated
-     * @return false if there is no ready transcoed image is available or it is outdated, true if image is ready 
+     * @return false if there is no ready transcoed image is available or it is outdated, true if image is ready
      */
-    public function isImageReady ($mixedHandler, $isCheckOutdated = true) {
+    public function isImageReady ($mixedHandler, $isCheckOutdated = true)
+    {
         $sMethodImageReady = 'isImageReady_' . $this->_aObject['source_type'];
         return $this->$sMethodImageReady($mixedHandler, $isCheckOutdated);
     }
 
-    /** 
+    /**
      * Transcode image, no need to call it directly, it is called automatically when it is needed.
      * @params $mixedHandler - image handler
      * @params $iProfileId - optional profile id, to assign transcoded image to, usually it is NOT assigned to any particular profile, so just leave it default
      * @return true on success, false on error
      */
-    public function transcode ($mixedHandler, $iProfileId = 0) {
-
+    public function transcode ($mixedHandler, $iProfileId = 0)
+    {
         $sExtChange = false;
 
-        // create tmp file locally 
+        // create tmp file locally
         $sMethodStoreFile = 'storeFileLocally_' . $this->_aObject['source_type'];
         $sTmpFile = $this->$sMethodStoreFile($mixedHandler);
-        if (!$sTmpFile) 
+        if (!$sTmpFile)
             return false;
 
         // appply filters to tmp file
@@ -348,7 +362,7 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
             }
         }
 
-        if ($sExtChange && false !== ($iDotPos = strrpos($sTmpFile, '.'))) {            
+        if ($sExtChange && false !== ($iDotPos = strrpos($sTmpFile, '.'))) {
             $sExtOld = substr($sTmpFile, $iDotPos+1);
             if ($sExtOld != $sExtChange) {
                 $sTmpFileOld = $sTmpFile;
@@ -369,7 +383,7 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         $iFileId = $this->_oStorage->storeFileFromPath ($sTmpFile, $isPrivate, $iProfileId);
         @unlink($sTmpFile);
         if (!$iFileId)
-            return false;                
+            return false;
 
         if (!$this->_oDb->updateHandler($iFileId, $mixedHandler)) {
             $this->_oStorage->deleteFile($iFileId);
@@ -380,14 +394,14 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
 
         return true;
     }
-    
 
     /**
      * Delete outdated files by last access time.
      * @return number of pruned/deleted files
      */
-    public function prune () {
-        $aFiles = $this->_oDb->getFilesForPruning();        
+    public function prune ()
+    {
+        $aFiles = $this->_oDb->getFilesForPruning();
         if (!$aFiles)
             return false;
         $iCount = 0;
@@ -396,7 +410,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         return $iCount;
     }
 
-    public function getDevicePixelRatio () {
+    public function getDevicePixelRatio ()
+    {
         if (isset($_COOKIE['devicePixelRatio']) && (!isset($this->_aObject['source_params']['disable_retina']) || !$this->_aObject['source_params']['disable_retina'])) {
             $iDevicePixelRatio = intval($_COOKIE['devicePixelRatio']);
             if ($iDevicePixelRatio >= 2)
@@ -407,8 +422,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
 
     // ---------------------------
 
-    protected function isImageReady_Folder ($mixedHandlerOrig, $isCheckOutdated = true) {
-
+    protected function isImageReady_Folder ($mixedHandlerOrig, $isCheckOutdated = true)
+    {
         $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
 
         $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
@@ -430,8 +445,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         return true;
     }
 
-    protected function isImageReady_Storage ($mixedHandlerOrig, $isCheckOutdated = true) {
-
+    protected function isImageReady_Storage ($mixedHandlerOrig, $isCheckOutdated = true)
+    {
         $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
 
         $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
@@ -446,31 +461,33 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
             $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
             if ($oStorageOriginal) {
                 $aFileOriginal = $oStorageOriginal->getFile($mixedHandlerOrig);
-                if (!$aFileOriginal || $aFileOriginal['modified'] > $aFile['modified'] || $this->_aObject['ts'] > $aFile['modified']) { // if original file was changed OR we changed transcoder object params 
+                if (!$aFileOriginal || $aFileOriginal['modified'] > $aFile['modified'] || $this->_aObject['ts'] > $aFile['modified']) { // if original file was changed OR we changed transcoder object params
                     // delete file, so it will be recreated next time
                     if ($this->_oStorage->deleteFile($aFile['id']))
                         return false;
-                } 
+                }
             }
         }
 
         return true;
     }
 
-    protected function isPrivate_Folder ($mixedHandler) {
+    protected function isPrivate_Folder ($mixedHandler)
+    {
         if ('no' == $this->_aObject['private'])
-            return false;                
+            return false;
         return true;
     }
 
-    protected function isPrivate_Storage ($mixedHandler) {
+    protected function isPrivate_Storage ($mixedHandler)
+    {
         switch ($this->_aObject['private']) {
             case 'no':
                 return false;
             case 'yes':
                 return true;
             default:
-            case 'auto':                
+            case 'auto':
                 $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
                 if (!$oStorageOriginal)
                     return true; // in case of error - make sure that file is not public accidentally
@@ -479,8 +496,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         }
     }
 
-    protected function getFilePath_Folder ($mixedHandler) {
-
+    protected function getFilePath_Folder ($mixedHandler)
+    {
         $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
         if (!file_exists($sPath))
             $sPath = BX_DIRECTORY_PATH_ROOT . $sPath;
@@ -491,8 +508,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         return $sPath;
     }
 
-    protected function storeFileLocally_Folder ($mixedHandler) {
-
+    protected function storeFileLocally_Folder ($mixedHandler)
+    {
         $sPath = $this->getFilePath_Folder($mixedHandler);
         if (!$sPath)
             return false;
@@ -504,8 +521,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         return $sTmpFile;
     }
 
-    protected function storeFileLocally_Storage ($mixedHandler) {
-
+    protected function storeFileLocally_Storage ($mixedHandler)
+    {
         $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
         if (!$oStorageOriginal)
             return false;
@@ -517,7 +534,6 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         $sUrl = $oStorageOriginal->getFileUrlById($mixedHandler);
         if (!$sUrl)
             return false;
-                
 
         $sFileData = bx_file_get_contents ($sUrl);
         if (false === $sFileData)
@@ -530,13 +546,15 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         return $sTmpFile;
     }
 
-    protected function getTmpFilename ($sOverrideName = false) {
+    protected function getTmpFilename ($sOverrideName = false)
+    {
         if ($sOverrideName)
             return BX_DIRECTORY_PATH_TMP . rand(10000, 99999) . $sOverrideName;
         return tempnam(BX_DIRECTORY_PATH_TMP, $this->_aObject['object']);
     }
 
-    protected function applyFilter_Grayscale ($sFile, $aParams) { 
+    protected function applyFilter_Grayscale ($sFile, $aParams)
+    {
         bx_import ('BxDolImageResize');
         $o = BxDolImageResize::getInstance();
         $o->removeCropOptions ();
@@ -549,7 +567,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         return false;
     }
 
-    protected function applyFilter_Resize ($sFile, $aParams) { 
+    protected function applyFilter_Resize ($sFile, $aParams)
+    {
         bx_import ('BxDolImageResize');
         $o = BxDolImageResize::getInstance();
         $o->removeCropOptions ();
@@ -573,7 +592,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         return false;
     }
 
-    protected function _checkForceType ($oImageProcessor, $aParams) { 
+    protected function _checkForceType ($oImageProcessor, $aParams)
+    {
         if (empty($aParams['force_type']))
             $aParams['force_type'] = false;
 
@@ -594,8 +614,8 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
         }
     }
 
-    protected function initFilters () {
-
+    protected function initFilters ()
+    {
         if (false !== $this->_aObject['filters']) // filters are already initilized
             return;
 
@@ -610,23 +630,27 @@ class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject
 
     }
 
-    protected function clearCacheDB() {
+    protected function clearCacheDB()
+    {
         $oCacheDb = $this->_oDb->getDbCacheObject();
         return $oCacheDb->removeAllByPrefix('db_');
     }
 
-    public function getDevicePixelRatioHandlerSuffix () {
+    public function getDevicePixelRatioHandlerSuffix ()
+    {
         $iDevicePixelRatio = $this->getDevicePixelRatio ();
         if ($iDevicePixelRatio >= 2)
             return $this->_sRetinaSuffix;
         return '';
     }
 
-    protected function processHandlerForRetinaDevice ($mixedHandler) {
+    protected function processHandlerForRetinaDevice ($mixedHandler)
+    {
         return '' . $mixedHandler . $this->getDevicePixelRatioHandlerSuffix ();
     }
 
-    static protected function _callFuncForObjectsArray ($mixed, $sFunc) {
+    static protected function _callFuncForObjectsArray ($mixed, $sFunc)
+    {
         if (!is_array($mixed))
             $mixed = array($mixed);
         foreach ($mixed as $sObject) {

+ 44 - 31
inc/classes/BxDolImageTranscoderQuery.php

@@ -12,68 +12,78 @@ bx_import('BxDolDb');
 /**
  * @see BxDolImageTranscoder
  */
-class BxDolImageTranscoderQuery extends BxDolDb {
+class BxDolImageTranscoderQuery extends BxDolDb
+{
     protected $_aObject;
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
     }
 
-    static public function getTranscoderObject ($sObject) {
+    static public function getTranscoderObject ($sObject)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_transcoder_images` WHERE `object` = ?", $sObject);
         return $oDb->getRow($sQuery);
     }
 
-    static public function getTranscoderObjects () {
+    static public function getTranscoderObjects ()
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_transcoder_images`");
         return $oDb->getAll($sQuery);
     }
 
-    public function getTranscoderFilters () {
+    public function getTranscoderFilters ()
+    {
         $sQuery = $this->prepare("SELECT * FROM `sys_transcoder_images_filters` WHERE `transcoder_object` = ? ORDER BY `order` ASC", $this->_aObject['object']);
         return $this->getAll($sQuery);
     }
 
-    public function updateHandler ($iFileId, $mixedHandler) {
+    public function updateHandler ($iFileId, $mixedHandler)
+    {
         $sUpdateATime = '';
         if ($this->_aObject['atime_tracking']) {
             $iTime = time();
             $sUpdateATime = $this->prepare(", `atime` = ?", $iTime);
         }
-        $sQuery = $this->prepare("INSERT INTO `sys_transcoder_images_files` SET `transcoder_object` = ?, `file_id` = ?, `handler` = ? $sUpdateATime 
+        $sQuery = $this->prepare("INSERT INTO `sys_transcoder_images_files` SET `transcoder_object` = ?, `file_id` = ?, `handler` = ? $sUpdateATime
             ON DUPLICATE KEY UPDATE `file_id` = ? $sUpdateATime", $this->_aObject['object'], $iFileId, $mixedHandler, $iFileId);
         return $this->res($sQuery);
     }
 
-    public function getFileIdByHandler ($mixedHandler) {
+    public function getFileIdByHandler ($mixedHandler)
+    {
         $sQuery = $this->prepare("SELECT `file_id` FROM `sys_transcoder_images_files` WHERE `transcoder_object` = ? AND `handler` = ?", $this->_aObject['object'], $mixedHandler);
         return $this->getOne($sQuery);
     }
 
-    public function updateAccessTime($mixedHandler) {
+    public function updateAccessTime($mixedHandler)
+    {
         $iTime = time();
         $sQuery = $this->prepare("UPDATE `sys_transcoder_images_files` SET `atime` = ? WHERE `transcoder_object` = ? AND `handler` = ?", $iTime, $this->_aObject['object'], $mixedHandler);
         return $this->res($sQuery);
     }
 
-    public function deleteFileTraces($iFileId) { 
+    public function deleteFileTraces($iFileId)
+    {
         $sQuery = $this->prepare("DELETE FROM `sys_transcoder_images_files` WHERE `transcoder_object` = ? AND `file_id` = ?", $this->_aObject['object'], $iFileId);
         return $this->res($sQuery);
-    }    
+    }
 
-    public function getFilesForPruning () {
+    public function getFilesForPruning ()
+    {
         if (!$this->_aObject['atime_tracking'] || !$this->_aObject['atime_pruning'])
             continue;
-    
+
         $sQuery = $this->prepare("SELECT * FROM `sys_transcoder_images_files` WHERE `transcoder_object` = ? AND `atime` != 0 AND `atime` < ?", $this->_aObject['object'], time() - $this->_aObject['atime_pruning']);
         return $this->getAll($sQuery);
     }
 
-    public function registerHandlers () {
-
+    public function registerHandlers ()
+    {
         if (!$this->registerHandler ('getAlertHandlerNameLocal', 'alert_response_file_delete_local', $this->_aObject['object'], $this->_aObject['storage_object']))
             return false;
 
@@ -85,8 +95,8 @@ class BxDolImageTranscoderQuery extends BxDolDb {
         return true;
     }
 
-    public function unregisterHandlers () {
-
+    public function unregisterHandlers ()
+    {
         if (!$this->unregisterHandler('getAlertHandlerNameLocal', $this->_aObject['storage_object']))
             return false;
 
@@ -94,22 +104,22 @@ class BxDolImageTranscoderQuery extends BxDolDb {
         if ('Storage' == $this->_aObject['source_type']) // if original storage is "Storage", not "Folder"
             if (!$this->unregisterHandler('getAlertHandlerNameOrig', $this->_aObject['source_params']['object']))
                 return false;
-        
-        return true;
-    }    
 
-    protected function registerHandler ($sHandlerNameFunc, $sServiceFunc, $sObject, $sUnit) {
+        return true;
+    }
 
+    protected function registerHandler ($sHandlerNameFunc, $sServiceFunc, $sObject, $sUnit)
+    {
         $sHandlerName = $this->$sHandlerNameFunc ();
         $iHandlerId = $this->getAlertHandlerId ($sHandlerName);
         if ($iHandlerId) // if handler already exists, do nothing
             return true;
 
         $sServiceCall = serialize(array(
-        	'module' => 'system',
-        	'method' => $sServiceFunc,
-        	'params' => array($sObject),
-        	'class' => 'TemplImageServices'
+            'module' => 'system',
+            'method' => $sServiceFunc,
+            'params' => array($sObject),
+            'class' => 'TemplImageServices'
         ));
         $sQuery = $this->prepare("INSERT INTO `sys_alerts_handlers` SET `name` = ?, `service_call` = ?", $sHandlerName, $sServiceCall);
         if (!$this->query($sQuery))
@@ -124,8 +134,8 @@ class BxDolImageTranscoderQuery extends BxDolDb {
         return true;
     }
 
-    protected function unregisterHandler ($sHandlerNameFunc, $sUnit) {
-
+    protected function unregisterHandler ($sHandlerNameFunc, $sUnit)
+    {
         $sHandlerName = $this->$sHandlerNameFunc ();
         $iHandlerId = $this->getAlertHandlerId ($sHandlerName);
         if (!$iHandlerId) // if handler is alrady missing, do nothing
@@ -137,17 +147,20 @@ class BxDolImageTranscoderQuery extends BxDolDb {
 
         $sQuery = $this->prepare("DELETE FROM `sys_alerts_handlers` WHERE `id` = ?", $iHandlerId);
         return $this->query($sQuery);
-    }    
+    }
 
-    protected function getAlertHandlerNameLocal () {
+    protected function getAlertHandlerNameLocal ()
+    {
         return 'sys_image_transcoder_local_file_delete_' . $this->_aObject['object'];
     }
 
-    protected function getAlertHandlerNameOrig () {
+    protected function getAlertHandlerNameOrig ()
+    {
         return 'sys_image_transcoder_orig_file_delete_' . $this->_aObject['object'];
     }
 
-    protected function getAlertHandlerId ($sHandlerName) {
+    protected function getAlertHandlerId ($sHandlerName)
+    {
         $sQuery = $this->prepare("SELECT `id` FROM `sys_alerts_handlers` WHERE `name` = ?", $sHandlerName);
         return $this->getOne($sQuery);
     }

+ 24 - 21
inc/classes/BxDolInformer.php

@@ -7,42 +7,42 @@
  * @{
  */
 
-define('BX_INFORMER_ALERT', 1); 
+define('BX_INFORMER_ALERT', 1);
 define('BX_INFORMER_INFO', 2);
 define('BX_INFORMER_ERROR', 3);
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section informer Informer
  * @ref BxDolInformer
  */
 
 /**
- * Informer. 
+ * Informer.
  *
  * It displays alerts or information messages in clearly visible area on the page to let user know important information.
  *
  * @section example Example of usage
  *
  * Adding message to informer:
- * 
+ *
  * @code
  *  bx_import('BxDolInformer'); // import informer class
  *  $oInformer = BxDolInformer::getInstance(); // get object instance
  *  if ($oInformer) // check if Informer is available for using
  *      echo $oInformer->add ('my_id', 'Some important information here', BX_INFORMER_ALERT); // add an alert message
  * @endcode
- * 
+ *
  */
-class BxDolInformer extends BxDol {
-
+class BxDolInformer extends BxDol
+{
     protected $_aMessages = array();
 
     /**
      * Constructor
      */
-    public function __construct() {
-
+    public function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses']['BxDolInformer']))
             trigger_error ('Multiple instances are not allowed for the BxDolInformer class.', E_USER_ERROR);
 
@@ -52,35 +52,38 @@ class BxDolInformer extends BxDol {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses']['BxDolInformer']))
             trigger_error('Clone is not allowed for the BxDolInformer class.', E_USER_ERROR);
     }
 
     /**
-     * Get Informer object instance 
+     * Get Informer object instance
      * @return object instance or false on error
      */
-    public static function getInstance($oTemplate = false) {
+    public static function getInstance($oTemplate = false)
+    {
         if (isset($GLOBALS['bxDolClasses']['BxDolInformer']))
             return $GLOBALS['bxDolClasses']['BxDolInformer'];
-    
+
         bx_import('BxTemplInformer');
         $o = new BxTemplInformer($oTemplate);
 
         return ($GLOBALS['bxDolClasses']['BxDolInformer'] = $o);
     }
-  
+
     /**
      * Add message to informer.
      * @param $sId - message id
      * @param $sMsg - message text
      * @param $iType - message type: BX_INFORMER_ALERT, BX_INFORMER_INFO or BX_INFORMER_ERROR
      */
-    public function add ($sId, $sMsg, $iType = BX_INFORMER_INFO) {
+    public function add ($sId, $sMsg, $iType = BX_INFORMER_INFO)
+    {
         $this->_aMessages[$sId] = array (
             'id' => $sId,
-            'msg' => $sMsg, 
+            'msg' => $sMsg,
             'type' => $iType,
         );
     }
@@ -89,16 +92,16 @@ class BxDolInformer extends BxDol {
      * Remove message from informer.
      * @param $sId - message id
      */
-    public function remove ($sId) {
+    public function remove ($sId)
+    {
         unset($this->_aMessages[$sId]);
     }
 
-
     /**
      * Add permanent messages which are displayed on every page.
      */
-    protected function _addPermanentMessages () {        
-
+    protected function _addPermanentMessages ()
+    {
         // add account related permament messages
         if (isLogged()) {
             bx_import('BxDolAccount');

+ 1 - 1
inc/classes/BxDolInstallerUtils.php

@@ -46,7 +46,7 @@ class BxDolInstallerUtils extends BxDolIO
     }
 
     /**
-     * Set module for delayed uninstall 
+     * Set module for delayed uninstall
      */
     static public function setModulePendingUninstall($sUri, $bPendingUninstall = true)
     {

+ 26 - 18
inc/classes/BxDolKey.php

@@ -9,28 +9,28 @@
 
 bx_import('BxDolKeyQuery');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section key Keys
  * @ref BxDolKey
  */
 
 /**
- * Key objects - automatically generate hashed keys. 
+ * Key objects - automatically generate hashed keys.
  *
  * @section example Example of usage
  *
  * Generate new hashed key:
- * 
+ *
  * @code
  *  bx_import('BxDolKey'); // import class
  *  $oKeys = BxDolKey::getInstance(); // get object instance
  *  if ($oKeys) // check if object is available for using
  *      echo $oKeys->getNewKey (3600); // get new hashed key, which will be automatically deleted after 1 hour
  * @endcode
- * 
+ *
  * Check if hashed key exists:
- * 
+ *
  * @code
  *  bx_import('BxDolKey'); // import class
  *  $oKeys = BxDolKey::getInstance(); // get object instance
@@ -40,14 +40,15 @@ bx_import('BxDolKeyQuery');
  *      echo 'key is invalid';
  * @endcode
  */
-class BxDolKey extends BxDol implements iBxDolSingleton {
-
+class BxDolKey extends BxDol implements iBxDolSingleton
+{
     protected $_oQuery;
 
     /**
      * Constructor
      */
-    public function __construct() {
+    public function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -59,7 +60,8 @@ class BxDolKey extends BxDol implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -67,7 +69,8 @@ class BxDolKey extends BxDol implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
+    public static function getInstance()
+    {
         if (!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolKey();
         return $GLOBALS['bxDolClasses'][__CLASS__];
@@ -78,19 +81,21 @@ class BxDolKey extends BxDol implements iBxDolSingleton {
      * @param $iExpire - number of seconds to generated key after, by default - 1 week
      * @return newly generated key string
      */
-    public function getNewKey ($aData = false, $iExpire = 604800) {
+    public function getNewKey ($aData = false, $iExpire = 604800)
+    {
         $sKey = md5(time() . rand() . BX_DOL_SECRET);
         if ($this->_oQuery->insert($sKey, $aData ? serialize($aData) : '', (int)$iExpire));
             return $sKey;
         return false;
     }
-  
+
     /**
      * Check if provided key exists.
      * @param $sKey - key string
      * @return true if key exists or false if key is missing
      */
-    public function isKeyExists ($sKey) {
+    public function isKeyExists ($sKey)
+    {
         return $this->_oQuery->get($sKey) ? true : false;
     }
 
@@ -99,9 +104,10 @@ class BxDolKey extends BxDol implements iBxDolSingleton {
      * @param $sKey - key string
      * @return true if key exists or false if key is missing
      */
-    public function getKeyData ($sKey) {
+    public function getKeyData ($sKey)
+    {
         $sData = $this->_oQuery->getData($sKey);
-        if ($sData) 
+        if ($sData)
             return unserialize($sData);
         return '';
     }
@@ -111,14 +117,16 @@ class BxDolKey extends BxDol implements iBxDolSingleton {
      * @param $sKey - key string
      * @return true if key was successfully found and delete if false otherwise
      */
-    public function removeKey ($sKey) {
+    public function removeKey ($sKey)
+    {
         return $this->_oQuery->remove($sKey);
     }
 
     /**
      * Delete expired keys.
      */
-    public function prune () {
+    public function prune ()
+    {
         return $this->_oQuery->prune();
     }
 

+ 14 - 8
inc/classes/BxDolKeyQuery.php

@@ -13,33 +13,39 @@ bx_import('BxDolDb');
  * Database queries for BxDolKey object.
  * @see BxDolKey
  */
-class BxDolKeyQuery extends BxDolDb {
-
-    public function __construct() {
+class BxDolKeyQuery extends BxDolDb
+{
+    public function __construct()
+    {
         parent::__construct();
     }
 
-    public function insert ($sKey, $sData, $iExpire) {
+    public function insert ($sKey, $sData, $iExpire)
+    {
         $sQuery = $this->prepare("INSERT INTO `sys_keys` SET `key` = ?, `data` = ?, `expire` = ?", $sKey, $sData, time() + $iExpire);
         return $this->query($sQuery);
     }
 
-    public function remove ($sKey) {
+    public function remove ($sKey)
+    {
         $sQuery = $this->prepare("DELETE FROM `sys_keys` WHERE `key` = ?", $sKey);
         return $this->query($sQuery);
     }
 
-    public function get ($sKey) {
+    public function get ($sKey)
+    {
         $sQuery = $this->prepare("SELECT `key` FROM `sys_keys` WHERE `key` = ?", $sKey);
         return $this->getOne($sQuery);
     }
 
-    public function getData ($sKey) {
+    public function getData ($sKey)
+    {
         $sQuery = $this->prepare("SELECT `data` FROM `sys_keys` WHERE `key` = ?", $sKey);
         return $this->getOne($sQuery);
     }
 
-    public function prune () {
+    public function prune ()
+    {
         $sQuery = $this->prepare("DELETE FROM `sys_keys` WHERE `expire` < ?", time());
         return $this->query($sQuery);
     }

+ 69 - 41
inc/classes/BxDolLanguages.php

@@ -13,11 +13,13 @@ bx_import('BxDolLanguagesQuery');
 define('BX_DOL_LANGUAGE_CATEGORY_SYSTEM', 1);
 define('BX_DOL_LANGUAGE_CATEGORY_CUSTOM', 2);
 
-class BxDolLanguages extends BxDol implements iBxDolSingleton {
+class BxDolLanguages extends BxDol implements iBxDolSingleton
+{
     protected $oDb;
     protected $sCurrentLanguage;
 
-    function __construct() {
+    function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -29,7 +31,8 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -37,7 +40,8 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    static function getInstance() {
+    static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolLanguages();
             $GLOBALS['bxDolClasses'][__CLASS__]->init();
@@ -46,7 +50,8 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    function getCurrentLangName($bSetCookie = true) {
+    function getCurrentLangName($bSetCookie = true)
+    {
         $sLang = '';
 
         if(!$sLang && !empty($_GET['lang']))
@@ -70,24 +75,29 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
         setlocale(LC_TIME, $sLang . '_' . strtoupper($sLang) . '.utf-8', $sLang . '_' . strtoupper($sLang) . '.utf8', $sLang . '.utf-8', $sLang . '.utf8', $sLang);
         return $sLang;
     }
-    
-    function getCurrentLangId() {
+
+    function getCurrentLangId()
+    {
         return $this->getLangId($this->getCurrentLanguage());
     }
 
-    function getLangId($sLang) {
+    function getLangId($sLang)
+    {
         return $this->oDb->getLanguageId($sLang);
     }
 
-    function getDefaultLangName() {
+    function getDefaultLangName()
+    {
         return getParam('lang_default');
     }
 
-    function getLanguages($bIdAsKey = false, $bActiveOnly = false) {
+    function getLanguages($bIdAsKey = false, $bActiveOnly = false)
+    {
         return $this->oDb->getLanguages($bIdAsKey, $bActiveOnly);
     }
 
-    function getLanguageCategory($sName) {
+    function getLanguageCategory($sName)
+    {
         $iId = 0;
         $this->oDb->getCategoriesBy(array('type' => 'id_by_name', 'value' => $sName), $iId);
 
@@ -100,18 +110,21 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
      * @param $sFallbackLanguage - language to return of nothis is found
      * @return language code string
      */
-    function detectLanguageFromArray($aLangs, $sFallbackLanguage = 'en') {
+    function detectLanguageFromArray($aLangs, $sFallbackLanguage = 'en')
+    {
         return isset($aLangs[$GLOBALS['sCurrentLanguage']]) ? $GLOBALS['sCurrentLanguage'] : $sFallbackLanguage;
     }
 
     /**
      * Get current language.
      */
-    function getCurrentLanguage() {
+    function getCurrentLanguage()
+    {
         return $GLOBALS['sCurrentLanguage'];
     }
 
-    function _t() {
+    function _t()
+    {
         global $LANG;
 
         $key = func_get_arg(0);
@@ -123,20 +136,22 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
                     $str = str_replace('{' . ($i - 1) . '}', func_get_arg($i), $str);
 
             return $str;
-        }
-        else
+        } else
             return $key;
     }
 
-    function _t_err() {
+    function _t_err()
+    {
         return MsgBox(call_user_func_array(array($this, '_t'), func_get_args()));
     }
 
-    function _t_action() {
+    function _t_action()
+    {
         return MsgBox(call_user_func_array(array($this, '_t'), func_get_args()));
     }
 
-    function _t_ext($key, $args) {
+    function _t_ext($key, $args)
+    {
         global $LANG;
 
         if(isset($LANG[$key])) {
@@ -149,14 +164,14 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
                 $str = str_replace('{'.$key.'}', $val, $str);
 
             return $str;
-        } 
-        else
+        } else
             return $key;
     }
 
-    function _t_format_size ($iSize) {
+    function _t_format_size ($iSize)
+    {
         $a = array (
-            1024 => '_sys_format_size_b', 
+            1024 => '_sys_format_size_b',
             1024*1024 => '_sys_format_size_kb',
             1024*1024*1024 => '_sys_format_size_mb',
             1024*1024*1024*1024 => '_sys_format_size_gb',
@@ -168,11 +183,13 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
         return $this->_t('_sys_format_size_b', 0);
     }
 
-    function _t_format_currency ($fPrice) {
+    function _t_format_currency ($fPrice)
+    {
         return $this->_t('_sys_currency', getParam('currency_sign'), sprintf("%.2f", (float)$fPrice));
     }
 
-    function _t_format_extensions ($mixedExtensions) {
+    function _t_format_extensions ($mixedExtensions)
+    {
         if (!is_array($mixedExtensions))
             $a = explode(',', $mixedExtensions);
         else
@@ -182,8 +199,9 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
         return '.' . implode(', .', $a);
     }
 
-    protected function init() {
-		/**
+    protected function init()
+    {
+        /**
          * Trying to initialize default language.
          */
         $GLOBALS['sCurrentLanguage'] = $GLOBALS['bxDolClasses'][__CLASS__]->getCurrentLangName(false);
@@ -205,7 +223,8 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
         }
     }
 
-    protected function tryToGetLang($sLangs, $bSetCookie = false) {
+    protected function tryToGetLang($sLangs, $bSetCookie = false)
+    {
         $sLangs = trim($sLangs);
         if(!$sLangs)
             return '';
@@ -218,11 +237,11 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
 
         $aLangs = explode(',', $sLangs); // ru,en-us;q=0.7,en;q=0.3 => array( 'ru' , 'en-us;q=0.7' , 'en;q=0.3' );
         foreach($aLangs as $sLang) {
-            if(!$sLang) 
+            if(!$sLang)
                 continue;
 
             list($sLang) = explode(';', $sLang, 2); // en-us;q=0.7 => en-us
-            if(!$sLang) 
+            if(!$sLang)
                 continue;
 
             // check with country
@@ -251,7 +270,8 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
         }
         return '';
     }
-    protected function checkLangExists( $sLang ) {
+    protected function checkLangExists( $sLang )
+    {
         if(!preg_match('/^[A-Za-z0-9_]+$/', $sLang))
             return false;
 
@@ -269,7 +289,8 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
         return false;
     }
 
-    protected function setLangCookie( $sLang ) {
+    protected function setLangCookie( $sLang )
+    {
         $sLang = bx_process_input($sLang);
 
         if(isLogged()) {
@@ -285,42 +306,49 @@ class BxDolLanguages extends BxDol implements iBxDolSingleton {
 
         setcookie( 'lang', '',     time() - 60*60*24,    '/' );
         setcookie( 'lang', $sLang, time() + 60*60*24*365, '/' );
-    }    
+    }
 }
 
 if (!function_exists('_t')) {
-    function _t() {
+    function _t()
+    {
         return call_user_func_array(array(BxDolLanguages::getInstance(), '_t'), func_get_args());
     }
 }
 
-function _t_err() {
+function _t_err()
+{
     return call_user_func_array(array(BxDolLanguages::getInstance(), '_t_err'), func_get_args());
 }
 
-function _t_action() {
+function _t_action()
+{
     return call_user_func_array(array(BxDolLanguages::getInstance(), '_t_action'), func_get_args());
 }
 
-function _t_ext($key, $args) {
+function _t_ext($key, $args)
+{
     return BxDolLanguages::getInstance()->_t_ext($key, $args);
 }
 
-function _t_format_size($iSize) {
+function _t_format_size($iSize)
+{
     return BxDolLanguages::getInstance()->_t_format_size($iSize);
 }
 
-function _t_format_currency($fPrice) {
+function _t_format_currency($fPrice)
+{
     return BxDolLanguages::getInstance()->_t_format_currency($fPrice);
 }
 
-function _t_format_extensions($mixedExtensions) {
+function _t_format_extensions($mixedExtensions)
+{
     return BxDolLanguages::getInstance()->_t_format_extensions($mixedExtensions);
 }
 
 function bx_lang_name()
 {
-	return BxDolLanguages::getInstance()->getCurrentLanguage();
+    return BxDolLanguages::getInstance()->getCurrentLanguage();
 }
 
 /** @} */

+ 83 - 72
inc/classes/BxDolLanguagesQuery.php

@@ -9,9 +9,10 @@
 
 bx_import('BxDolDb');
 
-class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
-
-    function __construct() {
+class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton
+{
+    function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -21,7 +22,8 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -29,14 +31,16 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    static function getInstance() {
+    static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolLanguagesQuery();
 
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    function getLanguageId($sName, $bFromCache = true) {
+    function getLanguageId($sName, $bFromCache = true)
+    {
         $sSql = $this->prepare("SELECT `ID` FROM `sys_localization_languages` WHERE `Name`=? AND `Enabled`='1' LIMIT 1", $sName);
 
         if($bFromCache)
@@ -44,58 +48,60 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
         else
             return (int)$this->getOne($sSql);
     }
-    function getLanguages($bIdAsKey = false, $bActiveOnly = false) {
+    function getLanguages($bIdAsKey = false, $bActiveOnly = false)
+    {
         $sSql = "SELECT * FROM `sys_localization_languages` WHERE 1 " . ($bActiveOnly ? " AND `Enabled`='1'" : "") . " ORDER BY `Title` ASC";
         return $this->getPairs($sSql, $bIdAsKey ? 'ID' : 'Name', 'Title');
     }
 
-    function getLanguagesBy($aParams, &$aItems, $bReturnCount = true) {
+    function getLanguagesBy($aParams, &$aItems, $bReturnCount = true)
+    {
         $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
-    	$sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
+        $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
 
-    	if(!isset($aParams['order']) || empty($aParams['order']))
-    	   $sOrderClause = " `tl`.`ID` ASC ";
+        if(!isset($aParams['order']) || empty($aParams['order']))
+           $sOrderClause = " `tl`.`ID` ASC ";
 
         switch($aParams['type']) {
             case 'by_id':
-        	    $aMethod['name'] = 'getRow';
-        		$sWhereClause .= $this->prepare(" AND `tl`.`ID`=?", $aParams['value']);
-        		break;
-        	case 'by_name':
-        	    $aMethod['name'] = 'getRow';
-        		$sWhereClause .= $this->prepare(" AND `tl`.`Name`=?", $aParams['value']);
-        		break;
+                $aMethod['name'] = 'getRow';
+                $sWhereClause .= $this->prepare(" AND `tl`.`ID`=?", $aParams['value']);
+                break;
+            case 'by_name':
+                $aMethod['name'] = 'getRow';
+                $sWhereClause .= $this->prepare(" AND `tl`.`Name`=?", $aParams['value']);
+                break;
             case 'default':
-        	    $aMethod['name'] = 'getRow';
-        		$sWhereClause .= $this->prepare(" AND `tl`.`Name`=?", getParam('lang_default'));
-        		break;
-        	case 'active':
+                $aMethod['name'] = 'getRow';
+                $sWhereClause .= $this->prepare(" AND `tl`.`Name`=?", getParam('lang_default'));
+                break;
+            case 'active':
                 $sWhereClause = " AND `tl`.`Enabled`='1'";
                 break;
-        	case 'all':
-        	    $sOrderClause = " `tl`.`Name` ASC ";
-        	    break;
+            case 'all':
+                $sOrderClause = " `tl`.`Name` ASC ";
+                break;
             case 'all_by_id':
                 $sWhereClause .= $this->prepare(" AND `tl`.`ID`=?", $aParams['value']);
-        	    $sOrderClause = " `tl`.`Name` ASC ";
-        	    break;
+                $sOrderClause = " `tl`.`Name` ASC ";
+                break;
             case 'all_key_id':
-        	    $aMethod['name'] = 'getAllWithKey';
-        	    $aMethod['params'][1] = 'id';
+                $aMethod['name'] = 'getAllWithKey';
+                $aMethod['params'][1] = 'id';
 
-        	    if(isset($aParams['language']) && (int)$aParams['language'] != 0)
-        	        $sWhereClause .= $this->prepare(" AND `tl`.`ID`=?", $aParams['language']);
-        	    break;
+                if(isset($aParams['language']) && (int)$aParams['language'] != 0)
+                    $sWhereClause .= $this->prepare(" AND `tl`.`ID`=?", $aParams['language']);
+                break;
         }
 
-        $aMethod['params'][0] = "SELECT SQL_CALC_FOUND_ROWS 
+        $aMethod['params'][0] = "SELECT SQL_CALC_FOUND_ROWS
                 `tl`.`ID` AS `id`,
                 `tl`.`Name` AS `name`,
                 `tl`.`Flag` AS `flag`,
                 `tl`.`Title` AS `title`,
                 `tl`.`Enabled` AS `enabled`" . $sSelectClause . "
             FROM `sys_localization_languages` AS `tl`" . $sJoinClause . "
-            WHERE 1" . $sWhereClause . " 
+            WHERE 1" . $sWhereClause . "
             ORDER BY" . $sOrderClause . $sLimitClause;
         $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
 
@@ -105,19 +111,21 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
         return (int)$this->getOne("SELECT FOUND_ROWS()");
     }
 
-    function getKeys() {
+    function getKeys()
+    {
         $sSql = "SELECT `ID`, `IDCategory`, `Key` FROM `sys_localization_keys`";
         return $this->getAllWithKey($sSql, 'ID');
     }
 
-    function getKeysBy($aParams, &$aItems) {
+    function getKeysBy($aParams, &$aItems)
+    {
         $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
-    	$sSelectClause = $sJoinClause = $sWhereClause = $sGroupClause = $sOrderClause = $sLimitClause = "";
+        $sSelectClause = $sJoinClause = $sWhereClause = $sGroupClause = $sOrderClause = $sLimitClause = "";
 
-    	$sSelectClause = "`tk`.`ID` AS `id`, `tk`.`IDCategory` AS `category_id`, `tk`.`Key` AS `key`";
+        $sSelectClause = "`tk`.`ID` AS `id`, `tk`.`IDCategory` AS `category_id`, `tk`.`Key` AS `key`";
 
-    	if(!isset($aParams['order']) || empty($aParams['order']))
-    	   $sOrderClause = " `tk`.`Key` ASC ";
+        if(!isset($aParams['order']) || empty($aParams['order']))
+           $sOrderClause = " `tk`.`Key` ASC ";
 
         switch($aParams['type']) {
             case 'by_ids':
@@ -126,7 +134,7 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
                 $sWhereClause .= " AND `tk`.`ID` IN ('" . implode("','", $aParams['value']) . "')";
 
                 if(isset($aParams['language']) && (int)$aParams['language'] != 0)
-        	        $sWhereClause .= $this->prepare(" AND `tl`.`ID`=?", $aParams['language']);
+                    $sWhereClause .= $this->prepare(" AND `tl`.`ID`=?", $aParams['language']);
                 break;
 
             case 'by_name':
@@ -140,17 +148,17 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
                 $sWhereClause = $this->prepare(" AND `ts`.`IDLanguage`=? ", (int)$aParams['value']);
                 break;
 
-        	case 'search':
-        	    $aMethod['name'] = 'getColumn';
+            case 'search':
+                $aMethod['name'] = 'getColumn';
 
-        	    $sSelectClause = "DISTINCT `tk`.`ID` AS `id`";
-        	    $sJoinClause = " LEFT JOIN `sys_localization_categories` AS `tc` ON `tk`.`IDCategory`=`tc`.`ID` LEFT JOIN `sys_localization_strings` AS `ts` ON `tk`.`ID`=`ts`.`IDKey` LEFT JOIN `sys_localization_languages` AS `tl` ON `ts`.`IDLanguage`=`tl`.`ID` ";
+                $sSelectClause = "DISTINCT `tk`.`ID` AS `id`";
+                $sJoinClause = " LEFT JOIN `sys_localization_categories` AS `tc` ON `tk`.`IDCategory`=`tc`.`ID` LEFT JOIN `sys_localization_strings` AS `ts` ON `tk`.`ID`=`ts`.`IDKey` LEFT JOIN `sys_localization_languages` AS `tl` ON `ts`.`IDLanguage`=`tl`.`ID` ";
 
-        	    if(isset($aParams['category']) && (int)$aParams['category'] != 0)
-        	        $sWhereClause .= $this->prepare(" AND `tc`.`ID`=?", $aParams['category']);
+                if(isset($aParams['category']) && (int)$aParams['category'] != 0)
+                    $sWhereClause .= $this->prepare(" AND `tc`.`ID`=?", $aParams['category']);
 
                 if(isset($aParams['language']) && (int)$aParams['language'] != 0)
-        	        $sWhereClause .= $this->prepare(" AND `tl`.`ID`=?", $aParams['language']);
+                    $sWhereClause .= $this->prepare(" AND `tl`.`ID`=?", $aParams['language']);
 
                 if(isset($aParams['keyword']) && $aParams['keyword'] != '' && $aParams['keyword'] != _t('_adm_pgt_txt_keyword'))
                     $sWhereClause .= $this->prepare(" AND (`tk`.`Key` LIKE ? OR `ts`.`String` LIKE ?)", '%' . $aParams['keyword'] . '%', '%' . $aParams['keyword'] . '%');
@@ -164,7 +172,7 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
                     $iLength = $aParams['length'];
 
                 $sLimitClause .= $this->prepare(" LIMIT ?, ?", $iStart, $iLength);
-        	    break;
+                break;
 
             case 'counter_by_category':
                 $aMethod['name'] = 'getPairs';
@@ -177,26 +185,28 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
 
         $aMethod['params'][0] = "SELECT " . $sSelectClause . "
             FROM `sys_localization_keys` AS `tk`" . $sJoinClause . "
-            WHERE 1" . $sWhereClause . " " . $sGroupClause . " 
+            WHERE 1" . $sWhereClause . " " . $sGroupClause . "
             ORDER BY" . $sOrderClause . $sLimitClause;
         $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
 
         return $aItems !== false;
     }
 
-    function getCategories() {
+    function getCategories()
+    {
         $sSql = "SELECT `ID`, `Name` FROM `sys_localization_categories` ORDER BY `Name`";
         return $this->getPairs($sSql, 'ID', 'Name');
     }
 
-    function getCategoriesBy($aParams, &$aItems, $bReturnCount = true) {
+    function getCategoriesBy($aParams, &$aItems, $bReturnCount = true)
+    {
         $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
-    	$sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
+        $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
 
-    	$sSelectClause = "`tc`.`ID` AS `id`, `tc`.`Name` AS `name`";
+        $sSelectClause = "`tc`.`ID` AS `id`, `tc`.`Name` AS `name`";
 
-    	if(!isset($aParams['order']) || empty($aParams['order']))
-    	   $sOrderClause = " `tc`.`ID` ASC ";
+        if(!isset($aParams['order']) || empty($aParams['order']))
+           $sOrderClause = " `tc`.`ID` ASC ";
 
         switch($aParams['type']) {
             case 'id_by_name':
@@ -208,15 +218,15 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
                 $aMethod['name'] = 'getRow';
                 $sWhereClause = $this->prepare(" AND `tc`.`Name`=?", $aParams['value']);
                 break;
-        	case 'all':
-        	    $sOrderClause = " `tc`.`Name` ASC ";
-        	    break;
+            case 'all':
+                $sOrderClause = " `tc`.`Name` ASC ";
+                break;
         }
 
-        $aMethod['params'][0] = "SELECT " . ($bReturnCount ? "SQL_CALC_FOUND_ROWS" : "") . "  
-				" . $sSelectClause . "
+        $aMethod['params'][0] = "SELECT " . ($bReturnCount ? "SQL_CALC_FOUND_ROWS" : "") . "
+                " . $sSelectClause . "
             FROM `sys_localization_categories` AS `tc`" . $sJoinClause . "
-            WHERE 1" . $sWhereClause . " 
+            WHERE 1" . $sWhereClause . "
             ORDER BY" . $sOrderClause . $sLimitClause;
         $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
 
@@ -226,12 +236,13 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
         return (int)$this->getOne("SELECT FOUND_ROWS()");
     }
 
-    function getStringsBy($aParams, &$aItems, $bReturnCount = true) {
+    function getStringsBy($aParams, &$aItems, $bReturnCount = true)
+    {
         $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
-    	$sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
+        $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
 
-    	if(!isset($aParams['order']) || empty($aParams['order']))
-    	   $sOrderClause = "`ts`.`IDKey` ASC";
+        if(!isset($aParams['order']) || empty($aParams['order']))
+           $sOrderClause = "`ts`.`IDKey` ASC";
 
         switch($aParams['type']) {
             case 'by_key_language_id':
@@ -241,20 +252,20 @@ class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton {
                 break;
 
             case 'all_by_key_key_language_id':
-        	    $aMethod['name'] = 'getAllWithKey';
-        	    $aMethod['params'][1] = 'language_id';
+                $aMethod['name'] = 'getAllWithKey';
+                $aMethod['params'][1] = 'language_id';
 
-        	    $sJoinClause = "LEFT JOIN `sys_localization_keys` AS `tk` ON `ts`.`IDKey`=`tk`.`ID`";
+                $sJoinClause = "LEFT JOIN `sys_localization_keys` AS `tk` ON `ts`.`IDKey`=`tk`.`ID`";
                 $sWhereClause .= $this->prepare("AND `tk`.`Key`=?", $aParams['value']);
-        	    break;
+                break;
         }
 
-        $aMethod['params'][0] = "SELECT SQL_CALC_FOUND_ROWS 
+        $aMethod['params'][0] = "SELECT SQL_CALC_FOUND_ROWS
                 `ts`.`IDKey` AS `key_id`,
                 `ts`.`IDLanguage` AS `language_id`,
                 `ts`.`String` AS `string` " . $sSelectClause . "
             FROM `sys_localization_strings` AS `ts` " . $sJoinClause . "
-            WHERE 1 " . $sWhereClause . " 
+            WHERE 1 " . $sWhereClause . "
             ORDER BY " . $sOrderClause . " " . $sLimitClause;
         $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
 

+ 39 - 32
inc/classes/BxDolMenu.php

@@ -10,16 +10,16 @@
 bx_import('BxDolMenuQuery');
 bx_import('BxDolPermalinks');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section menu Menu
  * @ref BxDolMenu
  */
 
 /**
- * Menus. 
+ * Menus.
  *
- * Menu uses some set of items and the template to display it, 
+ * Menu uses some set of items and the template to display it,
  * so it is possible to have several menus which uses the same set of items but different templates.
  *
  * Menu is any set of some links or actions, for example menu can be links in site's footer or actions in profile view.
@@ -29,7 +29,7 @@ bx_import('BxDolPermalinks');
  *
  * 1. Add record to 'sys_objects_menu' table:
  *
- * - object: name of the menu object, in the format: vendor prefix, underscore, module prefix, underscore, internal identifier or nothing; for example: bx_groups_actions - actions menu in group view. 
+ * - object: name of the menu object, in the format: vendor prefix, underscore, module prefix, underscore, internal identifier or nothing; for example: bx_groups_actions - actions menu in group view.
  * - title: name of the menu, displayed in the studio menu builder.
  * - set_name: name of items' set.
  * - module: the module this menu belongs to.
@@ -38,7 +38,7 @@ bx_import('BxDolPermalinks');
  * - active: it is possible to disable particular menu, then it will not be displayed.
  * - override_class_name: user defined class name which is derived from BxTemplMenu.
  * - override_class_file: the location of the user defined class, leave it empty if class is located in system folders.
- * 
+ *
  * Menu templates are stored in 'sys_menu_templates' table:
  * - id: template id.
  * - template: template file.
@@ -81,9 +81,9 @@ bx_import('BxDolPermalinks');
  *         echo $oMenu->getCode; // display menu
  * @endcode
  *
- * But in most cases you don't need to use above code to display menu, 
+ * But in most cases you don't need to use above code to display menu,
  * menu objects are integrated into pages - there is special 'menu' page block type for it.
- * 
+ *
  */
 class BxDolMenu extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
 {
@@ -103,7 +103,8 @@ class BxDolMenu extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * Constructor
      * @param $aObject array of menu options
      */
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
 
         $this->_sObject = isset($aObject['object']) ? $aObject['object'] : 'bx-menu-obj-' . time() . rand(0, PHP_INT_MAX);
@@ -129,25 +130,25 @@ class BxDolMenu extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * @param $sObject object name
      * @return object instance or false on error
      */
-    static public function getObjectInstance($sObject) {
-
+    static public function getObjectInstance($sObject)
+    {
         if (isset($GLOBALS['bxDolClasses']['BxDolMenu!'.$sObject]))
             return $GLOBALS['bxDolClasses']['BxDolMenu!'.$sObject];
-        
+
         $aObject = BxDolMenuQuery::getMenuObject($sObject);
         if (!$aObject || !is_array($aObject))
             return false;
 
         bx_import('BxTemplMenu');
-        $sClass = 'BxTemplMenu';        
+        $sClass = 'BxTemplMenu';
         if (!empty($aObject['override_class_name'])) {
             $sClass = $aObject['override_class_name'];
             if (!empty($aObject['override_class_file']))
                 require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
-            else    
+            else
                 bx_import($sClass);
         }
-        
+
         $o = new $sClass($aObject);
 
         return ($GLOBALS['bxDolClasses']['BxDolMenu!'.$sObject] = $o);
@@ -158,7 +159,8 @@ class BxDolMenu extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * @param $sModule menu item module to set as selected
      * @param $sName menu item name to set as selected
      */
-    static public function setSelectedGlobal ($sModule, $sName) {
+    static public function setSelectedGlobal ($sModule, $sName)
+    {
         self::$SEL_MODULE = $sModule;
         self::$SEL_NAME = $sName;
     }
@@ -166,22 +168,22 @@ class BxDolMenu extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
     /**
      * Process menu triggers.
      * Menu triggers allow to automatically add menu items to modules with no different if dependant module was install before or after the module menu item belongs to.
-     * For example module "Notes" adds menu items to all profiles modules (Persons, Organizations, etc) 
+     * For example module "Notes" adds menu items to all profiles modules (Persons, Organizations, etc)
      * with no difference if persons module was installed before or after "Notes" module was installed.
-     * @param $sSetName set name to ad menu item to 
+     * @param $sSetName set name to ad menu item to
      * @param $aMenuItem array of menu item descrition, array keys are database fields names, array values are database fields values
      * @return true on success
      */
-    static public function processMenuTrigger ($sMenuTriggerName) {
-
+    static public function processMenuTrigger ($sMenuTriggerName)
+    {
         // get list of active modules
         bx_import('BxDolModuleQuery');
         $aModules = BxDolModuleQuery::getInstance()->getModulesBy(array(
             'type' => 'modules',
             'active' => 1,
         ));
-        
-        // get list of menu triggers 
+
+        // get list of menu triggers
         $aMenuItem = BxDolMenuQuery::getMenuTriggers($sMenuTriggerName);
 
         // check each menu item trigger for all modules
@@ -206,7 +208,8 @@ class BxDolMenu extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * @param $sModule menu item module to set as selected
      * @param $sName menu item name to set as selected
      */
-    public function setSelected ($sModule, $sName) {
+    public function setSelected ($sModule, $sName)
+    {
         $this->_sSelModule = $sModule;
         $this->_sSelName = $sName;
     }
@@ -216,19 +219,21 @@ class BxDolMenu extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * @param $a array of markers as key => value
      * @return true on success or false on error
      */
-    public function addMarkers ($a) {
+    public function addMarkers ($a)
+    {
         if (empty($a) || !is_array($a))
             return false;
         $this->_aMarkers = array_merge ($this->_aMarkers, $a);
         return true;
     }
-  
+
     /**
      * Check if menu items is selected.
      * @param $a menu item array
      * @return boolean
-     */ 
-    protected function _isSelected ($a) {
+     */
+    protected function _isSelected ($a)
+    {
         if ($this->_sSelModule || $this->_sSelName)
             return (!isset($a['module']) || $a['module'] == $this->_sSelModule) && (isset($a['name']) && $a['name'] == $this->_sSelName) ? true : false;
         return (!isset($a['module']) || $a['module'] == self::$SEL_MODULE) && (isset($a['name']) && $a['name'] == self::$SEL_NAME) ? true : false;
@@ -238,8 +243,9 @@ class BxDolMenu extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * Check if menu items is visible.
      * @param $a menu item array
      * @return boolean
-     */ 
-    protected function _isVisible ($a) {
+     */
+    protected function _isVisible ($a)
+    {
         bx_import('BxDolAcl');
         return BxDolAcl::getInstance()->isMemberLevelInSet($a['visible_for_levels']);
     }
@@ -248,13 +254,14 @@ class BxDolMenu extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * Replace provided markers in menu item array, curently markers are replaced in title, link and onclick fields.
      * @param $a menu item array
      * @return array where markes are replaced with real values
-     */ 
-    protected function _replaceMarkers ($a) {
+     */
+    protected function _replaceMarkers ($a)
+    {
         if (empty($this->_aMarkers))
             return $a;
         $aReplacebleFields = array ('title', 'link', 'onclick');
         foreach ($aReplacebleFields as $sField)
-        	if (isset($a[$sField]))
+            if (isset($a[$sField]))
                 $a[$sField] = bx_replace_markers($a[$sField], $this->_aMarkers);
         return $a;
     }

+ 16 - 10
inc/classes/BxDolMenuQuery.php

@@ -13,33 +13,38 @@ bx_import('BxDolDb');
  * Database queries for menus.
  * @see BxDolMenu
  */
-class BxDolMenuQuery extends BxDolDb {
+class BxDolMenuQuery extends BxDolDb
+{
     protected $_aObject;
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
     }
 
-    static public function getMenuObject ($sObject) {
+    static public function getMenuObject ($sObject)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT `o`.*, `t`.`template` FROM `sys_objects_menu` AS `o` INNER JOIN `sys_menu_templates` AS `t` ON (`t`.`id` = `o`.`template_id`) WHERE `o`.`object` = ?", $sObject);
-        $aObject = $oDb->getRow($sQuery);        
-        if (!$aObject || !is_array($aObject)) 
+        $aObject = $oDb->getRow($sQuery);
+        if (!$aObject || !is_array($aObject))
             return false;
-        
+
         return $aObject;
     }
 
-    static public function getMenuTriggers($sTriggerName) {
+    static public function getMenuTriggers($sTriggerName)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_menu_items` WHERE `set_name` = ? ORDER BY `order` DESC", $sTriggerName);
         return $oDb->getAll($sQuery);
     }
 
-    static public function addMenuItemToSet($aMenuItem) {
+    static public function addMenuItemToSet($aMenuItem)
+    {
         $oDb = BxDolDb::getInstance();
-        
+
         if (empty($aMenuItem['set_name']))
             return false;
 
@@ -53,7 +58,8 @@ class BxDolMenuQuery extends BxDolDb {
         return $oDb->query("INSERT INTO `sys_menu_items` SET " . $oDb->arrayToSQL($aMenuItem));
     }
 
-    public function getMenuItems() {
+    public function getMenuItems()
+    {
         $sQuery = $this->prepare("SELECT * FROM `sys_menu_items` WHERE `set_name` = ? ORDER BY `order` ASC", $this->_aObject['set_name']);
         return $this->getAll($sQuery);
     }

+ 19 - 10
inc/classes/BxDolModule.php

@@ -39,7 +39,8 @@
  * no alerts available
  *
  */
-class BxDolModule extends BxDol {
+class BxDolModule extends BxDol
+{
     public $_aModule;
     public $_oDb;
     public $_oTemplate;
@@ -48,7 +49,8 @@ class BxDolModule extends BxDol {
     /**
      * constructor
      */
-    function __construct($aModule) {
+    function __construct($aModule)
+    {
         parent::__construct();
 
         $this->_aModule = $aModule;
@@ -75,7 +77,8 @@ class BxDolModule extends BxDol {
      *
      * @param $sName module name.
      */
-    public static function getInstance($sName) {
+    public static function getInstance($sName)
+    {
         if (empty($sName))
             return null;
 
@@ -107,18 +110,21 @@ class BxDolModule extends BxDol {
         }
     }
 
-    public static function getTitle($sUri) {
+    public static function getTitle($sUri)
+    {
         return _t(self::getTitleKey($sUri));
     }
 
-    public static function getTitleKey($sUri) {
+    public static function getTitleKey($sUri)
+    {
         return '_sys_module_' . strtolower(str_replace(' ', '_', $sUri));
     }
 
-	/**
+    /**
      * get module name
      */
-    function getName() {
+    function getName()
+    {
         return $this->_aModule['name'];
     }
 
@@ -127,7 +133,8 @@ class BxDolModule extends BxDol {
      *
      * @return boolean result of operation.
      */
-    public function isLogged() {
+    public function isLogged()
+    {
         return isLogged();
     }
 
@@ -136,7 +143,8 @@ class BxDolModule extends BxDol {
      *
      * @return integer user ID.
      */
-    public function getUserId() {
+    public function getUserId()
+    {
         return getLoggedId();
     }
 
@@ -145,7 +153,8 @@ class BxDolModule extends BxDol {
      *
      * @return string user password.
      */
-    public function getUserPassword () {
+    public function getUserPassword ()
+    {
         return getLoggedPassword();
     }
 }

+ 24 - 13
inc/classes/BxDolModuleConfig.php

@@ -26,8 +26,8 @@
  *
  */
 
-class BxDolModuleConfig extends BxDol {
-
+class BxDolModuleConfig extends BxDol
+{
     protected $_iId;
 
     protected $_sName;
@@ -51,7 +51,8 @@ class BxDolModuleConfig extends BxDol {
     /**
      * constructor
      */
-    function __construct($aModule) {
+    function __construct($aModule)
+    {
         parent::__construct();
 
         $this->_iId = empty($aModule['id']) ? 0 : (int)$aModule['id'];
@@ -67,25 +68,32 @@ class BxDolModuleConfig extends BxDol {
         $this->_sUri = $aModule['uri'];
         $this->_sHomeUrl = BX_DOL_URL_MODULES . $this->_sDirectory;
     }
-    function getId() {
+    function getId()
+    {
         return $this->_iId;
     }
-    function getName() {
+    function getName()
+    {
         return $this->_sName;
     }
-    function getClassPrefix() {
+    function getClassPrefix()
+    {
         return $this->_sClassPrefix;
     }
-    function getDbPrefix() {
+    function getDbPrefix()
+    {
         return $this->_sDbPrefix;
     }
-    function getDirectory() {
+    function getDirectory()
+    {
         return $this->_sDirectory;
     }
-    function getHomePath() {
+    function getHomePath()
+    {
         return $this->_sHomePath;
     }
-    function getClassPath() {
+    function getClassPath()
+    {
         return $this->_sClassPath;
     }
     /**
@@ -93,7 +101,8 @@ class BxDolModuleConfig extends BxDol {
      *
      * @return string with unique URI.
      */
-    function getUri() {
+    function getUri()
+    {
         return $this->_sUri;
     }
     /**
@@ -102,7 +111,8 @@ class BxDolModuleConfig extends BxDol {
      * example /modules/?r=module_uri or /m/module_uri
      * @return string with base URI.
      */
-    function getBaseUri() {
+    function getBaseUri()
+    {
         bx_import('BxDolPermalinks');
         return BxDolPermalinks::getInstance()->permalink('modules/?r=' . $this->_sUri . '/');
     }
@@ -111,7 +121,8 @@ class BxDolModuleConfig extends BxDol {
      *
      * @return string with full URL.
      */
-    function getHomeUrl() {
+    function getHomeUrl()
+    {
         return $this->_sHomeUrl;
     }
 }

+ 9 - 7
inc/classes/BxDolModuleDb.php

@@ -10,25 +10,27 @@
 /**
  * Base class for all modules DB classes
  */
-class BxDolModuleDb extends BxDolModuleQuery {
-
+class BxDolModuleDb extends BxDolModuleQuery
+{
     protected $_sPrefix;
 
     /**
      * Constructor
      */
-    public function __construct($oConfig) {
+    public function __construct($oConfig)
+    {
         parent::__construct();
 
-		if (is_a($oConfig,'BxDolModuleConfig'))
+        if (is_a($oConfig,'BxDolModuleConfig'))
             $this->_sPrefix = $oConfig->getDbPrefix();
         else
             trigger_error ('It is impossible to create BxDolModuleDb class instance without prefix: ' . get_class($this), E_USER_ERROR);
     }
 
-	public function getPrefix() {
-	    return $this->_sPrefix;
-	}
+    public function getPrefix()
+    {
+        return $this->_sPrefix;
+    }
 
 }
 

+ 62 - 43
inc/classes/BxDolModuleQuery.php

@@ -9,9 +9,11 @@
 
 bx_import('BxDolDb');
 
-class BxDolModuleQuery extends BxDolDb implements iBxDolSingleton {
-    function __construct() {
-    	if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
+class BxDolModuleQuery extends BxDolDb implements iBxDolSingleton
+{
+    function __construct()
+    {
+        if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
         parent::__construct();
@@ -19,7 +21,8 @@ class BxDolModuleQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -27,63 +30,77 @@ class BxDolModuleQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
-    	$sClass = __CLASS__;
+    public static function getInstance()
+    {
+        $sClass = __CLASS__;
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new $sClass();
 
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    function getModuleById($iId) {
+    function getModuleById($iId)
+    {
         $sSql = $this->prepare("SELECT * FROM `sys_modules` WHERE `id`=? LIMIT 1", $iId);
         return $this->fromMemory('sys_modules_' . $iId, 'getRow', $sSql);
     }
-    function getModuleByName($sName) {
+    function getModuleByName($sName)
+    {
         $sSql = $this->prepare("SELECT * FROM `sys_modules` WHERE `name`=? LIMIT 1", $sName);
         return $this->fromMemory('sys_modules_' . $sName, 'getRow', $sSql);
     }
-    function getModuleByUri($sUri) {
+    function getModuleByUri($sUri)
+    {
         $sSql = $this->prepare("SELECT * FROM `sys_modules` WHERE `uri`=? LIMIT 1", $sUri);
         return $this->fromMemory('sys_modules_' . $sUri, 'getRow', $sSql);
     }
-    function enableModuleByUri($sUri) {
+    function enableModuleByUri($sUri)
+    {
         $sSql = $this->prepare("UPDATE `sys_modules` SET `enabled`='1' WHERE `uri`=? LIMIT 1", $sUri);
         return (int)$this->query($sSql) > 0;
     }
-    function disableModuleByUri($sUri) {
+    function disableModuleByUri($sUri)
+    {
         $sSql = $this->prepare("UPDATE `sys_modules` SET `enabled`='0' WHERE `uri`=? LIMIT 1", $sUri);
         return (int)$this->query($sSql) > 0;
     }
-    function setModulePendingUninstall($sUri, $bPendingUninstall) {
+    function setModulePendingUninstall($sUri, $bPendingUninstall)
+    {
         $sSql = $this->prepare("UPDATE `sys_modules` SET `pending_uninstall` = ? WHERE `uri` = ? LIMIT 1", $bPendingUninstall ? 1 : 0, $sUri);
         return $this->query($sSql);
     }
-    function isModule($sUri) {
+    function isModule($sUri)
+    {
         $sSql = $this->prepare("SELECT `id` FROM `sys_modules` WHERE `uri`=? LIMIT 1", $sUri);
         return (int)$this->getOne($sSql) > 0;
     }
-    function isModuleByName($sName) {
+    function isModuleByName($sName)
+    {
         $sSql = $this->prepare("SELECT `id` FROM `sys_modules` WHERE `name`=? LIMIT 1", $sName);
         return (int)$this->getOne($sSql) > 0;
     }
-    function isModuleParamsUsed($sUri, $sPath, $sPrefixDb, $sPrefixClass) {
-	    $sSql = "SELECT `id` FROM `sys_modules` WHERE `uri`='" . $sUri . "' || `path`='" . $sPath . "' || `db_prefix`='" . $sPrefixDb . "' || `class_prefix`='" . $sPrefixClass . "' LIMIT 1";
-	    return (int)$this->getOne($sSql) > 0;
-	}
-	function isEnabled($sUri) {
+    function isModuleParamsUsed($sUri, $sPath, $sPrefixDb, $sPrefixClass)
+    {
+        $sSql = "SELECT `id` FROM `sys_modules` WHERE `uri`='" . $sUri . "' || `path`='" . $sPath . "' || `db_prefix`='" . $sPrefixDb . "' || `class_prefix`='" . $sPrefixClass . "' LIMIT 1";
+        return (int)$this->getOne($sSql) > 0;
+    }
+    function isEnabled($sUri)
+    {
         $sSql = $this->prepare("SELECT `id` FROM `sys_modules` WHERE `uri`=? AND `enabled`='1' LIMIT 1", $sUri);
         return (int)$this->getOne($sSql) > 0;
     }
-    function isEnabledByName($sName) {
+    function isEnabledByName($sName)
+    {
         $sSql = $this->prepare("SELECT `id` FROM `sys_modules` WHERE `name`=? AND `enabled`='1' LIMIT 1", $sName);
         return (int)$this->getOne($sSql) > 0;
     }
-    function getModules() {
+    function getModules()
+    {
         $sSql = "SELECT * FROM `sys_modules` ORDER BY `title`";
         return $this->fromMemory('sys_modules', 'getAll', $sSql);
     }
-    function getModulesBy($aParams = array()) {
+    function getModulesBy($aParams = array())
+    {
         $sPostfix = $sWhereClause = "";
 
         switch($aParams['type']) {
@@ -102,39 +119,41 @@ class BxDolModuleQuery extends BxDolDb implements iBxDolSingleton {
         }
 
         if(isset($aParams['active'])) {
-            $sPostfix .= "_active"; 
+            $sPostfix .= "_active";
             $sWhereClause .= $this->prepare(" AND `enabled`=?", (int)$aParams['active']);
         }
 
         $sOrderByClause = " ORDER BY " . (isset($aParams['order_by']) ? $aParams['order_by'] : '`title`');
 
-        $sSql = "SELECT 
-            	`id`,
-            	`type`,
-            	`name`, 
-            	`title`, 
-            	`vendor`, 
-            	`version`, 
-            	`product_url`, 
-            	`update_url`, 
-            	`path`, 
-            	`uri`, 
-            	`class_prefix`, 
-            	`db_prefix`, 
-            	`lang_category`, 
-            	`date`, 
-            	`enabled` 
-        	FROM `sys_modules` 
-        	WHERE 1 " . $sWhereClause . 
+        $sSql = "SELECT
+                `id`,
+                `type`,
+                `name`,
+                `title`,
+                `vendor`,
+                `version`,
+                `product_url`,
+                `update_url`,
+                `path`,
+                `uri`,
+                `class_prefix`,
+                `db_prefix`,
+                `lang_category`,
+                `date`,
+                `enabled`
+            FROM `sys_modules`
+            WHERE 1 " . $sWhereClause .
             $sOrderByClause;
         return $this->fromMemory('sys_modules' . $sPostfix, 'getAll', $sSql);
     }
 
-    function getModulesUri() {
+    function getModulesUri()
+    {
         $sSql = "SELECT `uri` FROM `sys_modules` ORDER BY `uri`";
         return $this->fromMemory('sys_modules_uri', 'getColumn', $sSql);
     }
-    function getDependent($sUri) {
+    function getDependent($sUri)
+    {
         $sSql = "SELECT `id`, `title` FROM `sys_modules` WHERE `dependencies` LIKE '%" . $this->escape($sUri) . "%'";
         return $this->getAll($sSql);
     }

+ 25 - 15
inc/classes/BxDolModuleTemplate.php

@@ -9,7 +9,8 @@
 
 bx_import('BxDolTemplate');
 
-class BxDolModuleTemplate extends BxDolTemplate {
+class BxDolModuleTemplate extends BxDolTemplate
+{
     protected $_oDb;
     protected $_oConfig;
     protected $_bObStarted = 0;
@@ -17,7 +18,8 @@ class BxDolModuleTemplate extends BxDolTemplate {
     /*
      * Constructor.
      */
-    function __construct(&$oConfig, &$oDb, $sRootPath = BX_DIRECTORY_PATH_ROOT, $sRootUrl = BX_DOL_URL_ROOT) {
+    function __construct(&$oConfig, &$oDb, $sRootPath = BX_DIRECTORY_PATH_ROOT, $sRootUrl = BX_DOL_URL_ROOT)
+    {
         parent::__construct($sRootPath, $sRootUrl);
 
         $this->_oDb = &$oDb;
@@ -31,30 +33,35 @@ class BxDolModuleTemplate extends BxDolTemplate {
         $this->addLocationJs($sName, $sHomePath . 'js/', $sHomeUrl . 'js/');
     }
 
-    function addCss($mixedFiles, $bDynamic = false) {
+    function addCss($mixedFiles, $bDynamic = false)
+    {
         return $this->_addFiles(BxDolTemplate::getInstance(), 'addCss', 'addLocation', 'removeLocation', '', $mixedFiles, $bDynamic, true);
     }
 
-    function addJs($mixedFiles, $bDynamic = false) {
+    function addJs($mixedFiles, $bDynamic = false)
+    {
         return $this->_addFiles(BxDolTemplate::getInstance(), 'addJs', 'addLocationJs', 'removeLocationJs', 'js/', $mixedFiles, $bDynamic, true);
     }
 
-    function addJsTranslation($mixedKey) {
-    	BxDolTemplate::getInstance()->addJsTranslation($mixedKey);
+    function addJsTranslation($mixedKey)
+    {
+        BxDolTemplate::getInstance()->addJsTranslation($mixedKey);
     }
 
-    function addStudioCss($mixedFiles, $bDynamic = false, $bSearchInModule = true) {
+    function addStudioCss($mixedFiles, $bDynamic = false, $bSearchInModule = true)
+    {
         bx_import('BxDolStudioTemplate');
         return $this->_addFiles(BxDolStudioTemplate::getInstance(), 'addCss', 'addLocation', 'removeLocation', '', $mixedFiles, $bDynamic, $bSearchInModule);
     }
 
-    function addStudioJs($mixedFiles, $bDynamic = false, $bSearchInModule = true) {
+    function addStudioJs($mixedFiles, $bDynamic = false, $bSearchInModule = true)
+    {
         bx_import('BxDolStudioTemplate');
         return $this->_addFiles(BxDolStudioTemplate::getInstance(), 'addJs', 'addLocationJs', 'removeLocationJs', 'js/', $mixedFiles, $bDynamic, $bSearchInModule);
     }
 
-    function _addFiles($oTemplate, $sFuncAddFiles, $sFuncAddLocation, $sFuncRemoveLocation, $sPath, $mixedFiles, $bDynamic = false, $bSearchInModule = true) {
-
+    function _addFiles($oTemplate, $sFuncAddFiles, $sFuncAddLocation, $sFuncRemoveLocation, $sPath, $mixedFiles, $bDynamic = false, $bSearchInModule = true)
+    {
         $sLocationKey = $bSearchInModule ? $oTemplate->$sFuncAddLocation($this->_oConfig->getUri(), $this->_oConfig->getHomePath() . $sPath, $this->_oConfig->getHomeUrl() . $sPath) : '';
         $mixedResult = $oTemplate->$sFuncAddFiles($mixedFiles, $bDynamic);
         if($sLocationKey != '')
@@ -63,7 +70,8 @@ class BxDolModuleTemplate extends BxDolTemplate {
         return $mixedResult;
     }
 
-    function addStudioInjection($sKey, $sType, $sData, $iReplace = 0) {
+    function addStudioInjection($sKey, $sType, $sData, $iReplace = 0)
+    {
         bx_import('BxDolStudioTemplate');
         BxDolStudioTemplate::getInstance()->aPage['injections']['page_0'][$sKey][] = array(
             'page_index' => 0,
@@ -74,14 +82,16 @@ class BxDolModuleTemplate extends BxDolTemplate {
         );
     }
 
-    function pageStart () {
-        if (0 == $this->_bObStarted)  {            
+    function pageStart ()
+    {
+        if (0 == $this->_bObStarted)  {
             ob_start ();
             $this->_bObStarted = 1;
         }
     }
 
-    function pageEnd ($isGetContent = true) {
+    function pageEnd ($isGetContent = true)
+    {
         if (1 == $this->_bObStarted)  {
             $sRet = '';
             if ($isGetContent)
@@ -91,7 +101,7 @@ class BxDolModuleTemplate extends BxDolTemplate {
             $this->_bObStarted = 0;
             return $sRet;
         }
-    } 
+    }
 }
 
 /** @} */

+ 25 - 23
inc/classes/BxDolObject.php

@@ -9,44 +9,46 @@
 
 /**
  * Base class for all Dolphin Object classes.
- * Child classes usually represents high level programming constructions to generate ready 'objects' functionality, like Comments, Votings, Forms. 
+ * Child classes usually represents high level programming constructions to generate ready 'objects' functionality, like Comments, Votings, Forms.
  */
-class BxDolObject extends BxDol {
-	protected $_iId = 0; ///< item id the action to be performed with
+class BxDolObject extends BxDol
+{
+    protected $_iId = 0; ///< item id the action to be performed with
     protected $_sSystem = ''; ///< current system name
     protected $_aSystem = array(); ///< current system array
 
     protected $_oQuery = null;
 
-    public function __construct($sSystem, $iId, $iInit = 1) {
-    	parent::__construct();
+    public function __construct($sSystem, $iId, $iInit = 1)
+    {
+        parent::__construct();
 
-    	$this->_aSystems = $this->getSystems();
+        $this->_aSystems = $this->getSystems();
         if(!isset($this->_aSystems[$sSystem]))
-			return;
+            return;
 
         $this->_sSystem = $sSystem;
-		$this->_aSystem = $this->_aSystems[$sSystem];
+        $this->_aSystem = $this->_aSystems[$sSystem];
 
-		if(!$this->isEnabled()) 
-			return;
+        if(!$this->isEnabled())
+            return;
 
-		if($iInit)
-			$this->init($iId);
+        if($iInit)
+            $this->init($iId);
     }
 
-	public function init($iId)
+    public function init($iId)
     {
-    	if(!$this->isEnabled()) 
-        	return false;
+        if(!$this->isEnabled())
+            return false;
 
         if(empty($this->_iId) && $iId)
-			$this->setId($iId);
+            $this->setId($iId);
 
-		return true;
+        return true;
     }
 
-	public function getSystemId()
+    public function getSystemId()
     {
         return $this->_aSystem['id'];
     }
@@ -56,25 +58,25 @@ class BxDolObject extends BxDol {
         return $this->_sSystem;
     }
 
-	public function getSystemInfo()
+    public function getSystemInfo()
     {
         return $this->_aSystem;
     }
 
-	public function getId()
+    public function getId()
     {
         return $this->_iId;
     }
 
-	public function setId($iId)
+    public function setId($iId)
     {
         if($iId == $this->getId())
-        	return;
+            return;
 
         $this->_iId = $iId;
     }
 
-	public function isEnabled ()
+    public function isEnabled ()
     {
         return $this->_aSystem && (int)$this->_aSystem['is_on'] == 1;
     }

+ 33 - 27
inc/classes/BxDolPage.php

@@ -9,25 +9,25 @@
 
 bx_import('BxDolPageQuery');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section page Page
  * @ref BxDolPage
  */
 
 /**
- * Pages. 
+ * Pages.
  *
  * It allows to display pages which are built from studio.
- *  
+ *
  * The new system has the following page features:
  * - Layouts: page can have any structure, not just columns.
  * - SEO: page can have own SEO options, like meta tags and meta keywords, as well as instructions for search bots.
  * - Cache: page can be cached on the server.
  * - Access control: page access can be controlled using member levels.
- * 
- * 
- * 
+ *
+ *
+ *
  * @section page_create Creating the Page object:
  *
  * 1. add record to 'sys_objects_page' table:
@@ -54,7 +54,7 @@ bx_import('BxDolPageQuery');
  *
  * Page can select appropriate menu automatically if 'module' and 'object' fields in 'sys_objects_page' table are matched with 'module' and 'name' fields in 'sys_menu_items' table.
  *
- * 
+ *
  * Page layout are stored in 'sys_pages_layouts' table:
  * - name: inner unique layout name.
  * - icon: layout icon to display in page builder, it should represent basic view of the layout to help studio operator determine the layout structure.
@@ -62,8 +62,8 @@ bx_import('BxDolPageQuery');
  * - template: template name to use to display page with certain layout.
  * - cells_number: number of areas in the layout, page blocks can be places into this areas(cells).
  * To define areas in the layout they should be named as '__cell_N__', where N is cell number, starting from 1.
- * 
- * 
+ *
+ *
  * 2. Add page blocks to 'sys_pages_blocks' table:
  * - object: page object name this block belongs to.
  * - cell_id: cell number in page layout to place block to.
@@ -94,7 +94,7 @@ bx_import('BxDolPageQuery');
  * - deletable: is block deletable from page builder
  * - copyable: is block can be copied to any other page from page builder.
  * - order: block order in particular cell.
- * 
+ *
  * Block design boxes are stored in 'sys_pages_design_boxes' table:
  * - id: consistent id, there are the following defines can be used in the code for each system block style:
  *      - 0 - BX_DB_CONTENT_ONLY: design box with content only - no borders, no background, no caption.
@@ -118,8 +118,8 @@ bx_import('BxDolPageQuery');
  * @endcode
  *
  */
-class BxDolPage extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable {
-
+class BxDolPage extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
+{
     protected $_sObject;
     protected $_aObject;
     protected $_oQuery;
@@ -129,7 +129,8 @@ class BxDolPage extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * Constructor
      * @param $aObject array of page options
      */
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
 
         $this->_sObject = $aObject['object'];
@@ -142,7 +143,8 @@ class BxDolPage extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * @param $sURI unique page URI
      * @return object instance or false on error
      */
-    static public function getObjectInstanceByURI($sURI) {
+    static public function getObjectInstanceByURI($sURI)
+    {
         $sObject = BxDolPageQuery::getPageObjectNameByURI($sURI);
         return $sObject ? self::getObjectInstance($sObject) : false;
     }
@@ -152,36 +154,37 @@ class BxDolPage extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * @param $sObject object name
      * @return object instance or false on error
      */
-    static public function getObjectInstance($sObject) {
-
+    static public function getObjectInstance($sObject)
+    {
         if (isset($GLOBALS['bxDolClasses']['BxDolPage!'.$sObject]))
             return $GLOBALS['bxDolClasses']['BxDolPage!'.$sObject];
-        
+
         $aObject = BxDolPageQuery::getPageObject($sObject);
         if (!$aObject || !is_array($aObject))
             return false;
 
         bx_import('BxTemplPage');
-        $sClass = 'BxTemplPage';        
+        $sClass = 'BxTemplPage';
         if (!empty($aObject['override_class_name'])) {
             $sClass = $aObject['override_class_name'];
             if (!empty($aObject['override_class_file']))
                 require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
-            else    
+            else
                 bx_import($sClass);
         }
-        
+
         $o = new $sClass($aObject);
 
         return ($GLOBALS['bxDolClasses']['BxDolPage!'.$sObject] = $o);
-    }    
+    }
 
     /**
      * Add replace markers. Markers are replaced in raw, html, lang blocks and page title, description, keywords and block titles.
      * @param $a array of markers as key => value
      * @return true on success or false on error
      */
-    public function addMarkers ($a) {
+    public function addMarkers ($a)
+    {
         if (empty($a) || !is_array($a))
             return false;
         $this->_aMarkers = array_merge ($this->_aMarkers, $a);
@@ -192,15 +195,17 @@ class BxDolPage extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
      * Replace provided markers in a string
      * @param $mixed string or array to replace markers in
      * @return string where all occured markers are replaced
-     */ 
-    protected function _replaceMarkers ($mixed) {
+     */
+    protected function _replaceMarkers ($mixed)
+    {
         return bx_replace_markers($mixed, $this->_aMarkers);
     }
 
     /**
      * Check if page block is visible.
      */
-    protected function _isVisibleBlock ($a) {
+    protected function _isVisibleBlock ($a)
+    {
         bx_import('BxDolAcl');
         return BxDolAcl::getInstance()->isMemberLevelInSet($a['visible_for_levels']);
     }
@@ -208,7 +213,8 @@ class BxDolPage extends BxDol implements iBxDolFactoryObject, iBxDolReplaceable
     /**
      * Check if page is visible.
      */
-    protected function _isVisiblePage ($a) {
+    protected function _isVisiblePage ($a)
+    {
         bx_import('BxDolAcl');
         return BxDolAcl::getInstance()->isMemberLevelInSet($a['visible_for_levels']);
     }

+ 17 - 11
inc/classes/BxDolPageQuery.php

@@ -13,32 +13,36 @@ bx_import('BxDolDb');
  * Database queries for pages.
  * @see BxDolPage
  */
-class BxDolPageQuery extends BxDolDb {
+class BxDolPageQuery extends BxDolDb
+{
     protected $_aObject;
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
     }
 
-    static public function getPageObject ($sObject) {
+    static public function getPageObject ($sObject)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT `o`.*, `l`.`template`, `l`.`cells_number` FROM `sys_objects_page` AS `o` INNER JOIN `sys_pages_layouts` AS `l` ON (`l`.`id` = `o`.`layout_id`) WHERE `o`.`object` = ?", $sObject);
-        $aObject = $oDb->getRow($sQuery);        
-        if (!$aObject || !is_array($aObject)) 
+        $aObject = $oDb->getRow($sQuery);
+        if (!$aObject || !is_array($aObject))
             return false;
-        
+
         return $aObject;
     }
 
-    static public function getPageObjectNameByURI($sURI) {
+    static public function getPageObjectNameByURI($sURI)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT `object` FROM `sys_objects_page` WHERE `uri` = ?", $sURI);
         return $oDb->getOne($sQuery);
     }
 
-
-    public function getPageBlocks() {
+    public function getPageBlocks()
+    {
         $aRet = array ();
         for ($i = 1 ; $i <= $this->_aObject['cells_number'] ; ++$i) {
             $sQuery = $this->prepare("SELECT * FROM `sys_pages_blocks` WHERE `object` = ? AND `cell_id` = ? AND `active` = 1 ORDER BY `order` ASC", $this->_aObject['object'], $i);
@@ -47,12 +51,14 @@ class BxDolPageQuery extends BxDolDb {
         return $aRet;
     }
 
-    public function getPageBlock($iBlockId) {
+    public function getPageBlock($iBlockId)
+    {
         $sQuery = $this->prepare("SELECT * FROM `sys_pages_blocks` WHERE `object` = ? AND `id` = ?", $this->_aObject['object'], $iBlockId);
         return $this->getRow($sQuery);
     }
 
-    public function getPageBlockContent($iId) {
+    public function getPageBlockContent($iId)
+    {
         $sQuery = $this->prepare("SELECT `content` FROM `sys_pages_blocks` WHERE `id` = ?", $iId);
         return $this->getOne($sQuery);
     }

+ 52 - 39
inc/classes/BxDolPaginate.php

@@ -13,10 +13,10 @@ define('BX_DOL_PAGINATE_PER_PAGE_DEFAULT', 10);
 
 /**
  * Paginage for any content.
- * It is used to create paginate, configuring it via input parameters. 
+ * It is used to create paginate, configuring it via input parameters.
  * Paginate don't support total number of pages, moreover it is not recommended to count all records - it slows down the site.
  * To correctly determine last page we need to pass number of available records on the current page plus one - so we always know if next page is available.
- * 
+ *
  *
  * Two types of paginate presentation is supported:
  * - getPaginate() - to get default paginate, it is better to use it on the whole page.
@@ -36,7 +36,7 @@ define('BX_DOL_PAGINATE_PER_PAGE_DEFAULT', 10);
  * - view_all_url - URL for 'view all' page. This url is not showed by default. It is convinient to use with @see getSimplePaginate.
  * - view_all_caption - optional caption for 'view all' link.
  *
- * 
+ *
  * Available markers to replace in 'page_url' and 'on_change_page' parameters:
  * - {per_page} - current number of items to display per page.
  * - {start} - the number to display items starting from.
@@ -62,21 +62,21 @@ define('BX_DOL_PAGINATE_PER_PAGE_DEFAULT', 10);
  * no alerts available
  *
  */
-abstract class BxDolPaginate extends BxDol {
-
+abstract class BxDolPaginate extends BxDol
+{
     protected static $_isCssAdded = false;
 
     protected $_oTemplate;
 
     protected $_iStart; ///< start display items from this number
     protected $_iNum; ///< available results, you need to query per_page + 1 results, so paginate can determine last page
-    protected $_iPerPage; ///< results per page    
+    protected $_iPerPage; ///< results per page
 
-    protected $_sPageUrl; ///< page url of next/prev page, special markers will be replaced here automatically    
-    protected $_sOnChangePage; ///< on click of next/prev page, special markers will be replaced here automatically 
-    protected $_bInfo; ///< show displayed items info    
+    protected $_sPageUrl; ///< page url of next/prev page, special markers will be replaced here automatically
+    protected $_sOnChangePage; ///< on click of next/prev page, special markers will be replaced here automatically
+    protected $_bInfo; ///< show displayed items info
 
-    protected $_sViewAllUrl; ///< view "all results" url, for "simple" paginate 
+    protected $_sViewAllUrl; ///< view "all results" url, for "simple" paginate
     protected $_sViewAllCaption; ///< 'view all' link caption
 
     protected $_sButtonsClass; ///< add this class to buttons class attribute
@@ -85,7 +85,8 @@ abstract class BxDolPaginate extends BxDol {
     /**
      * Constructor
      */
-    public function __construct($aParams, $oTemplate = null) {
+    public function __construct($aParams, $oTemplate = null)
+    {
         parent::__construct();
 
         if ($oTemplate)
@@ -94,7 +95,7 @@ abstract class BxDolPaginate extends BxDol {
             $this->_oTemplate = BxDolTemplate::getInstance();
 
         if (isset($aParams['count']))
-           trigger_error ('Paginate "count" is deprecated - use "num" instead: ' . get_class($this), E_USER_ERROR); 
+           trigger_error ('Paginate "count" is deprecated - use "num" instead: ' . get_class($this), E_USER_ERROR);
 
         //--- Main settings ---//
         $this->_iStart = isset($aParams['start']) && (int)$aParams['start'] > 0 ? (int)$aParams['start'] : 0;
@@ -109,18 +110,19 @@ abstract class BxDolPaginate extends BxDol {
         $this->_sPaginateClass = isset($aParams['paginate_class']) ? $aParams['paginate_class'] : '';
 
         // page url
-        $this->_sPageUrl = isset($aParams['page_url']) ? $aParams['page_url'] : BX_DOL_URL_ROOT;        
+        $this->_sPageUrl = isset($aParams['page_url']) ? $aParams['page_url'] : BX_DOL_URL_ROOT;
 
-        // on click (js mode)    
+        // on click (js mode)
         $this->_sOnChangePage = isset($aParams['on_change_page']) ? $aParams['on_change_page'] : '';
     }
 
     /**
-     * Get number of available results per page. If it is not last page, 
+     * Get number of available results per page. If it is not last page,
      * then this number is number of result per page plus one.
      * @return integer
      */
-    public function getNum() {
+    public function getNum()
+    {
         return $this->_iNum;
     }
 
@@ -129,7 +131,8 @@ abstract class BxDolPaginate extends BxDol {
      * Since data array should contain additional record - we will pop last item from array automatically.
      * @return nothing.
      */
-    public function setNumFromDataArray(&$a, $isAutoPopLastElement = true) {
+    public function setNumFromDataArray(&$a, $isAutoPopLastElement = true)
+    {
         if ($a && is_array($a))
             $this->_iNum = count($a);
         else
@@ -140,13 +143,14 @@ abstract class BxDolPaginate extends BxDol {
     }
 
     /**
-     * Set number of available items on the page, 
-     * it should be number of items per page + 1 (+1 is needed to correctly determine last page). 
+     * Set number of available items on the page,
+     * it should be number of items per page + 1 (+1 is needed to correctly determine last page).
      * It is possible to set this value automatically @see setNumFromDataArray.
      * @param $i positive integer.
      * @return true on success or false if $i param isn't correct.
      */
-    public function setNum($i) {
+    public function setNum($i)
+    {
         if ($i >= 0) {
             $this->_iNum = (int)$i;
             return true;
@@ -158,7 +162,8 @@ abstract class BxDolPaginate extends BxDol {
      * Position, the data is showing from.
      * @return integer.
      */
-    public function getStart() {
+    public function getStart()
+    {
         return $this->_iStart;
     }
 
@@ -167,7 +172,8 @@ abstract class BxDolPaginate extends BxDol {
      * @param $i positive integer.
      * @return true on siccess or false on error.
      */
-    public function setStart($i) {
+    public function setStart($i)
+    {
         if ($i >= 0) {
             $this->_iStart = (int)$i;
             return true;
@@ -179,7 +185,8 @@ abstract class BxDolPaginate extends BxDol {
      * Get number of records per page.
      * @return integer.
      */
-    public function getPerPage() {
+    public function getPerPage()
+    {
         return $this->_iPerPage;
     }
 
@@ -188,7 +195,8 @@ abstract class BxDolPaginate extends BxDol {
      * @param $i positive integer.
      * @return integer.
      */
-    public function setPerPage($i) {
+    public function setPerPage($i)
+    {
         if ((int)$i > 0) {
             $this->_iPerPage = $iPerPage;
             return true;
@@ -197,7 +205,7 @@ abstract class BxDolPaginate extends BxDol {
     }
 
     /**
-     * Set string to pass to 'onclick' for change page button. 
+     * Set string to pass to 'onclick' for change page button.
      * The following markers are replaced automatically:
      * - {per_page}
      * - {start}
@@ -205,21 +213,24 @@ abstract class BxDolPaginate extends BxDol {
      * @param $i positive integer.
      * @return integer.
      */
-    public function setOnChangePage($s) {
+    public function setOnChangePage($s)
+    {
         $this->_sOnChangePage = $s;
     }
 
     /**
      * @return true if previous page is available, or false if not
      */
-    public function isPrevAvail () {
+    public function isPrevAvail ()
+    {
         return $this->_iStart > 0 ? true : false;
     }
 
     /**
      * @return true if next page is available, or false if not
      */
-    public function isNextAvail () {
+    public function isNextAvail ()
+    {
         return $this->_iNum > $this->_iPerPage ? true : false;
     }
 
@@ -230,17 +241,15 @@ abstract class BxDolPaginate extends BxDol {
      * @param $iPerPage - @see setPerPage.
      * @return HTML string.
      */
-    public function getPaginate($iStart = -1, $iNum = -1, $iPerPage = -1) {
-
+    public function getPaginate($iStart = -1, $iNum = -1, $iPerPage = -1)
+    {
         $this->setNum($iNum);
         if (!$this->_iNum)
             return '';
 
-        $this->setStart($iStart);        
+        $this->setStart($iStart);
         $this->setPerPage($iPerPage);
 
-        
-
         $aReplacement = $this->_getReplacement();
 
         //--- Previous Page button ---//
@@ -300,8 +309,8 @@ abstract class BxDolPaginate extends BxDol {
      * @param $iPerPage - @see setPerPage.
      * @return HTML string.
      */
-    public function getSimplePaginate($sViewAllUrl = '', $iStart = -1, $iNum = -1, $iPerPage = -1) {
-
+    public function getSimplePaginate($sViewAllUrl = '', $iStart = -1, $iNum = -1, $iPerPage = -1)
+    {
         if ($sViewAllUrl)
             $this->_sViewAllUrl = $sViewAllUrl;
 
@@ -312,7 +321,8 @@ abstract class BxDolPaginate extends BxDol {
         return $this->getPaginate($iStart, $iNum, $iPerPage);
     }
 
-    public function addCssJs () {
+    public function addCssJs ()
+    {
         if (self::$_isCssAdded)
             return false;
         $this->_oTemplate->addCss('paginate.css');
@@ -320,18 +330,21 @@ abstract class BxDolPaginate extends BxDol {
         return true;
     }
 
-    protected function _getReplacement() {
+    protected function _getReplacement()
+    {
         return array(
             'start' => $this->_iStart,
             'per_page' => $this->_iPerPage,
         );
     }
 
-    protected function _getPageChangeUrl($aReplacement) {
+    protected function _getPageChangeUrl($aReplacement)
+    {
         return $this->_oTemplate->parseHtmlByContent($this->_sPageUrl, $aReplacement, array('{', '}'));
     }
 
-    protected function _getPageChangeOnClick($aReplacement) {
+    protected function _getPageChangeOnClick($aReplacement)
+    {
         return !empty($this->_sOnChangePage) ? 'onclick="javascript:' . $this->_oTemplate->parseHtmlByContent($this->_sOnChangePage, $aReplacement, array('{', '}')) . '; return false;"' : '';
     }
 

+ 31 - 22
inc/classes/BxDolPermalinks.php

@@ -9,8 +9,8 @@
 
 bx_import('BxDolDb');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section permalinks Permalinks
  * @ref BxDolPermalinks
  */
@@ -22,8 +22,8 @@ bx_import('BxDolDb');
  * and get it for specified standard URI.
  *
  *
- * All permalinks must match the whole URL, to be automatially determined. 
- * There are only 2 permlinks which are replaced by prefix:     
+ * All permalinks must match the whole URL, to be automatially determined.
+ * There are only 2 permlinks which are replaced by prefix:
  * - modules/?r= - for module URLs
  * - page.php?i= - for pages URLs
  *
@@ -53,14 +53,16 @@ bx_import('BxDolDb');
  * - $aExtra['return_data'] - it is possible to override default behavior, by setting 'return_data' to non NULL value.
  *
  */
-class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
+class BxDolPermalinks extends BxDolDb implements iBxDolSingleton
+{
     protected $sCacheFile;
     protected $aLinksStandard;
     protected $aLinksPermalink;
     protected $aPrefixesStandard;
     protected $aPrefixesPermalink;
 
-    function __construct() {
+    function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -84,14 +86,16 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
         $this->aPrefixesPermalink = $aPermalinksData['prefixes_permalink'];
     }
 
-    public function cacheInvalidate() {
+    public function cacheInvalidate()
+    {
         return BxDolDb::getInstance()->cleanCache ('sys_permalinks');
     }
 
-	/**
+    /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -99,14 +103,16 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
+    public static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolPermalinks();
 
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    function getPermalinksData() {
+    function getPermalinksData()
+    {
         $aLinksStandard = $this->getAll("SELECT * FROM `sys_permalinks`");
 
         $aResult = array(
@@ -140,7 +146,8 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
      * @param $iLength - position of the page name, or false to detect automatically
      * @returm page name (changeable part of URL) or empty string if page name is not detectable.
      */
-    function getPageNameFromLink($sLink, $iLength = false) {
+    function getPageNameFromLink($sLink, $iLength = false)
+    {
         if (false == $iLength) {
             $sLink = $this->_fixUrl($sLink);
             foreach ($this->aPrefixesStandard as $sKey => $iLen) {
@@ -159,8 +166,8 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
      * @param $aParams - params to add to the url.
      * @return - relative permalinked URL if it was detected and permalinks are ON or unchanged URL otherwise.
      */
-    function permalink($sLink, $aParams = array()) {
-
+    function permalink($sLink, $aParams = array())
+    {
         $sRet = null;
         bx_alert('system', 'permalink', 0, 0, array('link' => $sLink, 'params' => &$aParams, 'return_data' => &$sRet));
         if (null !== $sRet)
@@ -172,7 +179,7 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
 
             if (strncmp($sLink, $sKey, $iLength) !== 0)
                 continue;
-            
+
             $sPage = $this->getPageNameFromLink($sLink, $iLength);
 
             if (!$this->_isEnabled($sKey))
@@ -191,8 +198,8 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
      * @param $isStripBaseUrl - strip site prefix (absolute URL) automatically (enabled by default)
      * @return - relative UNpermalinked URL if it was detected or relative URL if URL withing the site or unchanged URL otherwise.
      */
-    function unpermalink($sLink, $isStripBaseUrl = true) {
-        
+    function unpermalink($sLink, $isStripBaseUrl = true)
+    {
         if ($isStripBaseUrl && 0 == strncmp($sLink, BX_DOL_URL_ROOT, strlen(BX_DOL_URL_ROOT)))
             $sLink = substr($sLink, strlen(BX_DOL_URL_ROOT));
 
@@ -205,7 +212,7 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
 
             if (strncmp($sLink, $sKey, $iLength) !== 0)
                 continue;
-            
+
             $sPage = substr($sLink, $iLength);
 
             return $this->aLinksPermalink[$sKey]['standard'] . $sPage;
@@ -215,7 +222,8 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
         return isset($this->aLinksPermalink[$sLink]) ? $this->aLinksPermalink[$sLink]['standard'] : $sLink;
     }
 
-    function _isEnabled($sLink) {
+    function _isEnabled($sLink)
+    {
         return array_key_exists($sLink, $this->aLinksStandard) && $this->aLinksStandard[$sLink]['enabled'];
     }
 
@@ -223,8 +231,8 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
      * redirect to the correct url after switching skin or language
      * only correct modules urls are supported
      */
-    function redirectIfNecessary ($aSkip = array()) {
-
+    function redirectIfNecessary ($aSkip = array())
+    {
         $sCurrentUrl = $_SERVER['PHP_SELF'] . '?' . bx_encode_url_params($_GET, $aSkip);
 
         if (!preg_match('/modules\/index.php\?r=(\w+)(.*)/', $sCurrentUrl, $m))
@@ -242,7 +250,8 @@ class BxDolPermalinks extends BxDolDb implements iBxDolSingleton {
         return true;
     }
 
-    protected function _fixUrl($sLink) {
+    protected function _fixUrl($sLink)
+    {
         if (strncmp($sLink, 'modules/index.php?r=', 20) === 0)
             $sLink = str_replace('modules/index.php?r=', 'modules/?r=', $sLink);
         return $sLink;

+ 47 - 44
inc/classes/BxDolPrivacy.php

@@ -17,8 +17,8 @@ define('BX_DOL_PG_FRIENDS', '5');
 
 define('BX_DOL_PG_DEFAULT', BX_DOL_PG_ALL);
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section privacy Privacy
  * @ref BxDolPrivacy
  */
@@ -61,8 +61,8 @@ define('BX_DOL_PG_DEFAULT', BX_DOL_PG_ALL);
  */
 class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
 {
-	protected $_oDb;
-	protected $_sObject;
+    protected $_oDb;
+    protected $_sObject;
     protected $_aObject;
 
     /**
@@ -79,7 +79,7 @@ class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
         $this->_oDb = new BxDolPrivacyQuery($this->_aObject);
     }
 
-	/**
+    /**
      * Get privacy object instance by object name
      * @param $sObject object name
      * @return object instance or false on error
@@ -92,10 +92,10 @@ class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
         bx_import('BxDolPrivacyQuery');
         $aObject = BxDolPrivacyQuery::getPrivacyObject($sObject);
         if(!$aObject || !is_array($aObject))
-			return false;
+            return false;
 
         bx_import('BxTemplPrivacy');
-        $sClass = 'BxTemplPrivacy';        
+        $sClass = 'BxTemplPrivacy';
         if(!empty($aObject['override_class_name'])) {
             $sClass = $aObject['override_class_name'];
             if(!empty($aObject['override_class_file']))
@@ -108,25 +108,25 @@ class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
         return ($GLOBALS['bxDolClasses']['BxDolPrivacy!' . $sObject] = $o);
     }
 
-	/**
+    /**
      * Get Select element with available groups.
      *
-     * @param  string $sObject privacy object name.
+     * @param  string  $sObject  privacy object name.
      * @param  integer $iOwnerId object's owner ID.
-     * @param  array $aParams an array of custom selector's params (dynamic_groups - an array of arrays('key' => group_id, 'value' => group_title), title - the title to be used for generated field).
-     * @return an array with Select element description.
+     * @param  array   $aParams  an array of custom selector's params (dynamic_groups - an array of arrays('key' => group_id, 'value' => group_title), title - the title to be used for generated field).
+     * @return an      array with Select element description.
      */
     public static function getGroupChooser($sObject, $iOwnerId = 0, $aParams = array())
     {
-    	$oPrivacy = BxDolPrivacy::getObjectInstance($sObject);
-    	if(empty($oPrivacy))
-    		return array();
+        $oPrivacy = BxDolPrivacy::getObjectInstance($sObject);
+        if(empty($oPrivacy))
+            return array();
 
-		$sModule = $oPrivacy->_aObject['module'];
-		$sAction = $oPrivacy->_aObject['action'];
+        $sModule = $oPrivacy->_aObject['module'];
+        $sAction = $oPrivacy->_aObject['action'];
 
-		if($iOwnerId == 0)
-			$iOwnerId = bx_get_logged_profile_id();
+        if($iOwnerId == 0)
+            $iOwnerId = bx_get_logged_profile_id();
 
         $sValue = $oPrivacy->_oDb->getDefaultGroupByUser($sModule, $sAction, $iOwnerId);
         if(empty($sValue))
@@ -142,14 +142,14 @@ class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
         }
 
         if(isset($aParams['dynamic_groups']) && is_array($aParams['dynamic_groups']))
-        	$aValues = array_merge($aValues, $aParams['dynamic_groups']);
+            $aValues = array_merge($aValues, $aParams['dynamic_groups']);
 
         $sName = self::getFieldName($sAction);
 
         $sTitle = isset($aParams['title']) && !empty($aParams['title']) ? $aParams['title'] : '';
         if(empty($sTitle)) {
-        	$sTitle = $oPrivacy->_oDb->getTitle($sModule, $sAction);
-        	$sTitle = _t(!empty($sTitle) ? $sTitle : '_' . $sName);
+            $sTitle = $oPrivacy->_oDb->getTitle($sModule, $sAction);
+            $sTitle = _t(!empty($sTitle) ? $sTitle : '_' . $sName);
         }
 
         return array(
@@ -184,7 +184,8 @@ class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
      * @param $mixedGroupId group ID or array of group IDs
      * @return array of conditions, for now with 'restriction' part only is returned
      */
-    public function getContentByGroupAsCondition($mixedGroupId) {
+    public function getContentByGroupAsCondition($mixedGroupId)
+    {
         return array(
             'restriction' => array (
                 'privacy_' . $this->_sObject => array(
@@ -194,7 +195,7 @@ class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
                     'table' => $this->_aObject['table'],
                 ),
             ),
-        );        
+        );
     }
 
     /**
@@ -202,10 +203,11 @@ class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
      * @param $iProfileIdOwner owner profile ID
      * @return array of conditions, for now with 'restriction' part only is returned
      */
-    public function getContentPublicAsCondition($iProfileIdOwner = 0) {
+    public function getContentPublicAsCondition($iProfileIdOwner = 0)
+    {
         $mixedPrivacyGroups = BX_DOL_PG_ALL;
         if(isLogged()) {
-        	$iProfileIdLogged = bx_get_logged_profile_id();
+            $iProfileIdLogged = bx_get_logged_profile_id();
             if($iProfileIdLogged == $iProfileIdOwner)
                 return array();
 
@@ -222,9 +224,10 @@ class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
      * @param $mixedGroupId group ID or array of group IDs
      * @return array of SQL string parts, for now 'where' part only is returned
      */
-	public function getContentByGroupAsSQLPart($mixedGroupId) {
-		$sField = self::getFieldName($this->_aObject['action']);
-		return $this->_oDb->getContentByGroupAsSQLPart($sField, $mixedGroupId);
+    public function getContentByGroupAsSQLPart($mixedGroupId)
+    {
+        $sField = self::getFieldName($this->_aObject['action']);
+        return $this->_oDb->getContentByGroupAsSQLPart($sField, $mixedGroupId);
     }
 
     /**
@@ -249,43 +252,43 @@ class BxDolPrivacy extends BxDol implements iBxDolFactoryObject
         if(isAdmin() || $iViewerId == $aObject['owner_id'])
             return true;
 
-		$aGroup = $this->_oDb->getGroupsBy(array('type' => 'id', 'id' => $aObject['group_id']));
+        $aGroup = $this->_oDb->getGroupsBy(array('type' => 'id', 'id' => $aObject['group_id']));
         if(!empty($aGroup) && is_array($aGroup) && (int)$aGroup['active'] == 1 && !empty($aGroup['check'])) {
-        	$sCheckMethod = $this->getCheckMethod($aGroup['check']);
-        	if(method_exists($this, $sCheckMethod) && $this->$sCheckMethod($aObject['owner_id'], $iViewerId))
-        		return true;
+            $sCheckMethod = $this->getCheckMethod($aGroup['check']);
+            if(method_exists($this, $sCheckMethod) && $this->$sCheckMethod($aObject['owner_id'], $iViewerId))
+                return true;
         }
 
         return $this->isDynamicGroupMember($aObject['group_id'], $aObject['owner_id'], $iViewerId, $iObjectId);
     }
 
-	public function checkMeOnly($iOwnerId, $iViewerId)
-	{
-		return false;
-	}
+    public function checkMeOnly($iOwnerId, $iViewerId)
+    {
+        return false;
+    }
 
     public function checkPublic($iOwnerId, $iViewerId)
     {
-    	return true;
+        return true;
     }
 
     public function checkMembers($iOwnerId, $iViewerId)
     {
-    	return isMember();
+        return isMember();
     }
 
     public function checkConnections($iOwnerId, $iViewerId)
     {
-    	bx_import('BxDolConnection');
-    	return BxDolConnection::getObjectInstance('sys_profiles_friends')->isConnected($iOwnerId, $iViewerId, true);
+        bx_import('BxDolConnection');
+        return BxDolConnection::getObjectInstance('sys_profiles_friends')->isConnected($iOwnerId, $iViewerId, true);
     }
 
-	protected function getCheckMethod($s)
+    protected function getCheckMethod($s)
     {
-    	if(substr($s, 0, 1) != '@')
-    		return false;
+        if(substr($s, 0, 1) != '@')
+            return false;
 
-		return bx_gen_method_name(str_replace('@', 'check_', $s));
+        return bx_gen_method_name(str_replace('@', 'check_', $s));
     }
 
     /**

+ 37 - 35
inc/classes/BxDolPrivacyQuery.php

@@ -11,29 +11,30 @@ bx_import('BxDolDb');
 
 class BxDolPrivacyQuery extends BxDolDb
 {
-	protected $_aObject;
+    protected $_aObject;
 
     protected $_sTable;
     protected $_sFieldId;
     protected $_sFieldOwnerId;
 
     protected $_sCachePrivacyObject;
-	protected $_sCachePrivacyObjectDefault;
+    protected $_sCachePrivacyObjectDefault;
 
-	protected $_sCacheGroup;
+    protected $_sCacheGroup;
     protected $_sCacheGroupFriends;
     protected $_sCacheGroupsActive;
 
-	protected $_sCacheTestedObject;
+    protected $_sCacheTestedObject;
 
-    public function __construct($aObject = array()) {
+    public function __construct($aObject = array())
+    {
         parent::__construct();
         $this->_aObject = $aObject;
 
         if(!empty($this->_aObject)) {
-	        $this->_sTable = $this->_aObject['table'];
-	        $this->_sFieldId = $this->_aObject['table_field_id'];
-	        $this->_sFieldOwnerId = $this->_aObject['table_field_author'];
+            $this->_sTable = $this->_aObject['table'];
+            $this->_sFieldId = $this->_aObject['table_field_id'];
+            $this->_sFieldOwnerId = $this->_aObject['table_field_author'];
         }
 
         $this->_sCachePrivacyObject = 'sys_privacy_object_';
@@ -43,19 +44,20 @@ class BxDolPrivacyQuery extends BxDolDb
         $this->_sCacheGroupFriends = 'sys_privacy_group_friends_';
         $this->_sCacheGroupsActVis = 'sys_privacy_group_act_vis';
 
-		$this->_sCacheTestedObject = 'sys_privacy_tested_object_';
+        $this->_sCacheTestedObject = 'sys_privacy_tested_object_';
     }
 
-    static public function getPrivacyObject($sObject) {
+    static public function getPrivacyObject($sObject)
+    {
         $oDb = BxDolDb::getInstance();
 
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_privacy` WHERE `object` = ?", $sObject);
 
-        $aObject = $oDb->getRow($sQuery);        
-        if(!$aObject || !is_array($aObject)) 
-			return false;
+        $aObject = $oDb->getRow($sQuery);
+        if(!$aObject || !is_array($aObject))
+            return false;
 
-		return $aObject;
+        return $aObject;
     }
 
     function getObjectInfo($sAction, $iObjectId)
@@ -63,9 +65,9 @@ class BxDolPrivacyQuery extends BxDolDb
         if(empty($this->_sTable) || empty($this->_sFieldId) || empty($this->_sFieldOwnerId))
             return array();
 
-		$sQuery = $this->prepare("SELECT `" . $this->_sFieldOwnerId . "` AS `owner_id`, `" . $sAction . "` AS `group_id` FROM `" . $this->_sTable . "` WHERE `" . $this->_sFieldId . "`=? LIMIT 1", $iObjectId);
+        $sQuery = $this->prepare("SELECT `" . $this->_sFieldOwnerId . "` AS `owner_id`, `" . $sAction . "` AS `group_id` FROM `" . $this->_sTable . "` WHERE `" . $this->_sFieldId . "`=? LIMIT 1", $iObjectId);
 
-		$sCacheKey = $this->_sCacheTestedObject . $this->_sTable . '_' . $this->_aObject['action'] . '_' . $iObjectId;
+        $sCacheKey = $this->_sCacheTestedObject . $this->_sTable . '_' . $this->_aObject['action'] . '_' . $iObjectId;
         return $this->fromMemory($sCacheKey, 'getRow', $sQuery);
     }
 
@@ -79,7 +81,7 @@ class BxDolPrivacyQuery extends BxDolDb
                 $sWhereClause = $this->prepare("`id`=?", (int)$aParams['id']);
                 break;
 
-			case 'active':
+            case 'active':
                 $sCacheFunction = 'fromMemory';
                 $sCacheName = $this->_sCacheGroupsActVis;
                 $sMethod = 'getAll';
@@ -116,7 +118,7 @@ class BxDolPrivacyQuery extends BxDolDb
         return $this->getAll($sQuery);
     }
 
-	function getTitle($sModule, $sAction)
+    function getTitle($sModule, $sAction)
     {
         $aAction = $this->_getAction($sModule, $sAction);
         return !empty($aAction) && isset($aAction['title']) ? $aAction['title'] : '';
@@ -128,14 +130,14 @@ class BxDolPrivacyQuery extends BxDolDb
         return !empty($aAction) && isset($aAction['default_group']) ? $aAction['default_group'] : BX_DOL_PG_DEFAULT;
     }
 
-	function getDefaultGroupByUser($sModule, $sAction, $iOwnerId)
+    function getDefaultGroupByUser($sModule, $sAction, $iOwnerId)
     {
         $sQuery = $this->prepare("SELECT
                `td`.`group_id`
             FROM `sys_objects_privacy` AS `ta`
             LEFT JOIN `sys_privacy_defaults` AS `td` ON `ta`.`id`=`td`.`action_id` AND `td`.`owner_id`=?
-            WHERE 
-            	`ta`.`module`=? AND `ta`.`action`=?
+            WHERE
+                `ta`.`module`=? AND `ta`.`action`=?
             LIMIT 1", $iOwnerId, $sModule, $sAction);
 
         $sCacheKey = $this->_sCachePrivacyObjectDefault . $sModule . '_' . $sAction . '_' . $iOwnerId;
@@ -144,26 +146,26 @@ class BxDolPrivacyQuery extends BxDolDb
 
     function replaceDefaulfGroup($iActionId, $iOwnerId, $iGroupId)
     {
-        $sSql = $this->prepare("REPLACE INTO 
-        		`sys_privacy_defaults` 
-        	SET 
-        		`owner_id`=?, 
-        		`action_id`=?, 
-        		`group_id`=?", $iOwnerId, $iActionId, $iGroupId);
+        $sSql = $this->prepare("REPLACE INTO
+                `sys_privacy_defaults`
+            SET
+                `owner_id`=?,
+                `action_id`=?,
+                `group_id`=?", $iOwnerId, $iActionId, $iGroupId);
 
         return $this->query($sSql);
     }
 
     function getContentByGroupAsSQLPart($sField, $mixedGroupId)
     {
-    	if(is_array($mixedGroupId))
-    		$sWhere = " AND `" . $this->_sTable . "`.`" . $sField . "` IN (" . $this->implode_escape($mixedGroupId) . ")";
-    	else
-    		$sWhere = $this->prepare(" AND `" . $this->_sTable . "`.`" . $sField . "` = ?", $mixedGroupId);
-
-    	return array(
-    		'where' => $sWhere
-    	);
+        if(is_array($mixedGroupId))
+            $sWhere = " AND `" . $this->_sTable . "`.`" . $sField . "` IN (" . $this->implode_escape($mixedGroupId) . ")";
+        else
+            $sWhere = $this->prepare(" AND `" . $this->_sTable . "`.`" . $sField . "` = ?", $mixedGroupId);
+
+        return array(
+            'where' => $sWhere
+        );
     }
 
     protected function _getAction($sModule, $sAction)

+ 65 - 40
inc/classes/BxDolProfile.php

@@ -10,18 +10,19 @@
 bx_import('BxDolProfileQuery');
 
 define('BX_PROFILE_ACTION_AUTO', 0); ///< automatic action without any checking
-define('BX_PROFILE_ACTION_MANUAL', 1); ///< manual action performed by human 
+define('BX_PROFILE_ACTION_MANUAL', 1); ///< manual action performed by human
 define('BX_PROFILE_ACTION_ROBOT', 2); ///< action peformed by some robot based on some conditions
 
-class BxDolProfile extends BxDol implements iBxDolProfile {
-
+class BxDolProfile extends BxDol implements iBxDolProfile
+{
     protected $_iProfileID;
     protected $_oQuery;
 
     /**
      * Constructor
      */
-    protected function __construct ($iProfileId) {
+    protected function __construct ($iProfileId)
+    {
         $iProfileId = (int)$iProfileId;
         $sClass = get_class($this) . '_' . $iProfileId;
         if (isset($GLOBALS['bxDolClasses'][$sClass]))
@@ -36,7 +37,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         $sClass = get_class($this) . '_' . $this->_iProfileID;
         if (isset($GLOBALS['bxDolClasses'][$sClass]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
@@ -45,7 +47,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get singleton instance of Account Profile by account id
      */
-    public static function getInstanceAccountProfile($iAccountId = false) {
+    public static function getInstanceAccountProfile($iAccountId = false)
+    {
         if (!$iAccountId)
             $iAccountId = getLoggedId();
         $oQuery = BxDolProfileQuery::getInstance();
@@ -58,7 +61,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get singleton instance of Profile by account id, content id and type
      */
-    public static function getInstanceByContentTypeAccount($iContent, $sType, $iAccountId = false) {
+    public static function getInstanceByContentTypeAccount($iContent, $sType, $iAccountId = false)
+    {
         if (!$iAccountId)
             $iAccountId = getLoggedId();
         $oQuery = BxDolProfileQuery::getInstance();
@@ -71,7 +75,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get singleton instance of Profile by content id and type
      */
-    public static function getInstanceByContentAndType($iContent, $sType) {
+    public static function getInstanceByContentAndType($iContent, $sType)
+    {
         $oQuery = BxDolProfileQuery::getInstance();
         $aProfile = $oQuery->getProfileByContentAndType($iContent, $sType);
         if (!$aProfile)
@@ -82,8 +87,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get singleton instance of Profile by profile id
      */
-    public static function getInstance($mixedProfileId = false) {
-
+    public static function getInstance($mixedProfileId = false)
+    {
         if (!$mixedProfileId) {
             $oQuery = BxDolProfileQuery::getInstance();
             $mixedProfileId = $oQuery->getCurrentProfileByAccount(getLoggedId());
@@ -103,14 +108,16 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get profile id
      */
-    public function id() {
+    public function id()
+    {
         return $this->_oQuery->getIdById($this->_iProfileID);
     }
 
     /**
      * Get account id associated with the profile
      */
-    public function getAccountId() {
+    public function getAccountId()
+    {
         $aInfo = $this->getInfo();
         return $aInfo['account_id'];
     }
@@ -118,7 +125,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get account object associated with the profile
      */
-    public function getAccountObject() {
+    public function getAccountObject()
+    {
         bx_import('BxDolAccount');
         return BxDolAccount::getInstance($this->getAccountId());
     }
@@ -126,7 +134,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get content id associated with the profile
      */
-    public function getContentId() {
+    public function getContentId()
+    {
         $aInfo = $this->getInfo();
         return $aInfo['content_id'];
     }
@@ -134,14 +143,16 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Check if profile status is active
      */
-    public function isActive($iProfileId = false) {
+    public function isActive($iProfileId = false)
+    {
         return BX_PROFILE_STATUS_ACTIVE == $this->getStatus($iProfileId);
     }
 
     /**
      * Get profile status
      */
-    public function getStatus($iProfileId = false) {
+    public function getStatus($iProfileId = false)
+    {
         $aInfo = $this->_oQuery->getInfoById((int)$iProfileId ? $iProfileId : $this->_iProfileID);
         return $aInfo['status'];
     }
@@ -149,16 +160,18 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get profile info
      */
-    public function getInfo($iProfileId = 0) {
+    public function getInfo($iProfileId = 0)
+    {
         return $this->_oQuery->getInfoById((int)$iProfileId ? $iProfileId : $this->_iProfileID);
     }
 
     /**
-     * Validate profile id. 
+     * Validate profile id.
      * @param $s - profile id
      * @return profile id or false if profile was not found
      */
-    static public function getID($s) {
+    static public function getID($s)
+    {
         $iId = BxDolProfileQuery::getInstance()->getIdById((int)$s);
         return $iId ? $iId : false;
     }
@@ -166,7 +179,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get name to display in thumbnail
      */
-    public function getDisplayName($iProfileId = 0) {
+    public function getDisplayName($iProfileId = 0)
+    {
         $aInfo = $this->getInfo($iProfileId);
         return BxDolService::call($aInfo['type'], 'profile_name', array($aInfo['content_id']));
     }
@@ -174,7 +188,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get profile url
      */
-    public function getUrl($iProfileId = 0) {
+    public function getUrl($iProfileId = 0)
+    {
         $aInfo = $this->getInfo($iProfileId);
         return BxDolService::call($aInfo['type'], 'profile_url', array($aInfo['content_id']));
     }
@@ -182,7 +197,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get profile unit
      */
-    public function getUnit($iProfileId = 0) {
+    public function getUnit($iProfileId = 0)
+    {
         $aInfo = $this->getInfo($iProfileId);
         return BxDolService::call($aInfo['type'], 'profile_unit', array($aInfo['content_id']));
     }
@@ -190,7 +206,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get thumbnail url
      */
-    public function getAvatar($iProfileId = 0) {
+    public function getAvatar($iProfileId = 0)
+    {
         $aInfo = $this->getInfo($iProfileId);
         return BxDolService::call($aInfo['type'], 'profile_avatar', array($aInfo['content_id']));
     }
@@ -198,7 +215,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get thumbnail url
      */
-    public function getThumb($iProfileId = 0) {
+    public function getThumb($iProfileId = 0)
+    {
         $aInfo = $this->getInfo($iProfileId);
         return BxDolService::call($aInfo['type'], 'profile_thumb', array($aInfo['content_id']));
     }
@@ -206,7 +224,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Get icon url
      */
-    public function getIcon($iProfileId = 0) {
+    public function getIcon($iProfileId = 0)
+    {
         $aInfo = $this->getInfo($iProfileId);
         return BxDolService::call($aInfo['type'], 'profile_icon', array($aInfo['content_id']));
     }
@@ -214,7 +233,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * get profile edit page url
      */
-    public function getEditUrl($iProfileId = 0) {
+    public function getEditUrl($iProfileId = 0)
+    {
         $aInfo = $this->getInfo($iProfileId);
         return BxDolService::call($aInfo['type'], 'profile_edit_url', array($aInfo['content_id']));
     }
@@ -225,8 +245,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
      * @param $bForceDelete - force deletetion is case of account profile deletion
      * @return false on error, or true on success
      */
-    function delete($ID = false, $bForceDelete = false) {
-
+    function delete($ID = false, $bForceDelete = false)
+    {
         $ID = (int)$ID;
         if (!$ID)
             $ID = $this->_iProfileID;
@@ -238,7 +258,7 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
         // delete system profiles (accounts) is not allowed, instead - delete whole account
         if (!$bForceDelete && 'system' == $aProfileInfo['type'])
             return false;
-    
+
         // switch profile context if deleted profile is active profile context
         bx_import('BxDolAccount');
         $oAccount = BxDolAccount::getInstance ($aProfileInfo['account_id']);
@@ -280,7 +300,7 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
         // unset class instance to prevent creating the instance again
         $this->_iProfileID = 0;
         $sClass = get_class($this) . '_' . $ID;
-        unset($GLOBALS['bxDolClasses'][$sClass]);        
+        unset($GLOBALS['bxDolClasses'][$sClass]);
 
         return true;
     }
@@ -293,7 +313,8 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
      * @param $sType profile content type
      * @return inserted profile's id
      */
-    static public function add ($iAction, $iAccountId, $iContentId, $sStatus, $sType = 'system') {
+    static public function add ($iAction, $iAccountId, $iContentId, $sStatus, $sType = 'system')
+    {
         $oQuery = BxDolProfileQuery::getInstance();
         if (!($iProfileId = $oQuery->insertProfile ($iAccountId, $iContentId, $sStatus, $sType)))
             return false;
@@ -304,25 +325,29 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
     /**
      * Change profile status from 'Pending' to the next level - 'Active'
      */
-    public function approve($iAction, $iProfileId = 0) {
+    public function approve($iAction, $iProfileId = 0)
+    {
         return $this->changeStatus(BX_PROFILE_STATUS_ACTIVE, 'approve', $iAction, $iProfileId);
     }
 
     /**
-     * Change profile status to 'Pending' 
+     * Change profile status to 'Pending'
      */
-    public function disapprove($iAction, $iProfileId = 0) {
+    public function disapprove($iAction, $iProfileId = 0)
+    {
         return $this->changeStatus(BX_PROFILE_STATUS_PENDING, 'disapprove', $iAction, $iProfileId);
     }
 
     /**
-     * Change profile status to 'Suspended' 
+     * Change profile status to 'Suspended'
      */
-    public function suspend($iAction, $iProfileId = 0) {
+    public function suspend($iAction, $iProfileId = 0)
+    {
         return $this->changeStatus(BX_PROFILE_STATUS_SUSPENDED, 'suspend', $iAction, $iProfileId);
     }
 
-    protected function changeStatus($sStatus, $sAlertActionName, $iAction, $iProfileId = 0) {
+    protected function changeStatus($sStatus, $sAlertActionName, $iAction, $iProfileId = 0)
+    {
         if (!$iProfileId)
             $iProfileId = $this->_iProfileID;
 
@@ -344,11 +369,12 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
 
         return true;
     }
-    
+
     /**
      * Display informer message if it is possible to switch to this profile
      */
-    public function checkSwitchToProfile($oTemplate = null, $iViewerAccountId = false, $iViewerProfileId = false) {
+    public function checkSwitchToProfile($oTemplate = null, $iViewerAccountId = false, $iViewerProfileId = false)
+    {
         if (false === $iViewerAccountId)
             $iViewerAccountId = getLoggedId();
         if (false === $iViewerProfileId)
@@ -370,4 +396,3 @@ class BxDolProfile extends BxDol implements iBxDolProfile {
 }
 
 /** @} */
-

+ 9 - 7
inc/classes/BxDolProfileForms.php

@@ -10,16 +10,18 @@
 /**
  * Functions to automate profile creation/editing/deletion forms.
  */
-class BxDolProfileForms extends BxDol {
-
+class BxDolProfileForms extends BxDol
+{
     /**
      * Constructor
      */
-    protected function __construct () {
+    protected function __construct ()
+    {
         parent::__construct ();
     }
 
-    protected function _redirectAndExit ($sUrl, $isPermalink = true, $aMarkers = false) {
+    protected function _redirectAndExit ($sUrl, $isPermalink = true, $aMarkers = false)
+    {
         if ($isPermalink) {
             bx_import('BxDolPermalinks');
             $sUrl = BxDolPermalinks::getInstance()->permalink($sUrl);
@@ -33,12 +35,12 @@ class BxDolProfileForms extends BxDol {
      * @param $mixed string or array to replace markers in
      * @param $aMarkers araay or markers for replacement, for example: array ('num' => 123, 'name' => 'Ivan');
      * @return string where all markers are replaced
-     */ 
-    protected function _replaceMarkers ($mixed, $aMarkers) {
+     */
+    protected function _replaceMarkers ($mixed, $aMarkers)
+    {
         return bx_replace_markers($mixed, $aMarkers);
     }
 
 }
 
 /** @} */
-

+ 58 - 42
inc/classes/BxDolProfileQuery.php

@@ -12,10 +12,10 @@ bx_import('BxDolDb');
 /**
  * All queries related to profiles
  */
-class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
-
-    public function __construct() {
-
+class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton
+{
+    public function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -25,7 +25,8 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -33,7 +34,8 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
+    public static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolProfileQuery();
 
@@ -42,30 +44,33 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
 
     /**
      * Get all account profiles.
-     * @param string $iAccountId account id
+     * @param  string  $iAccountId account id
      * @return profile array
      */
-    public function getProfilesByAccount ($iAccountId) {
+    public function getProfilesByAccount ($iAccountId)
+    {
         $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `account_id` = ?", $iAccountId);
         return $this->getAllWithKey($sSql, 'id');
     }
 
     /**
      * Get profile by content id, type and account.
-     * @param string $iAccountId account id
-     * @return array if aprofile ids, key is profile id
+     * @param  string $iAccountId account id
+     * @return array  if aprofile ids, key is profile id
      */
-    public function getProfileByContentTypeAccount ($iContentId, $sType, $iAccountId) {
+    public function getProfileByContentTypeAccount ($iContentId, $sType, $iAccountId)
+    {
         $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `account_id` = ? AND `type` = ? AND `content_id` = ?", $iAccountId, $sType, $iContentId);
         return $this->getRow($sSql);
     }
 
     /**
      * Get profile by content id and type.
-     * @param string $iAccountId account id
-     * @return array if aprofile ids, key is profile id
+     * @param  string $iAccountId account id
+     * @return array  if aprofile ids, key is profile id
      */
-    public function getProfileByContentAndType ($iContentId, $sType) {
+    public function getProfileByContentAndType ($iContentId, $sType)
+    {
         $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `content_id` = ? AND `type` = ?", $iContentId, $sType);
         return $this->getRow($sSql);
     }
@@ -78,7 +83,8 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
      * @param $sType profile content type
      * @return inserted profile's id
      */
-    public function insertProfile ($iAccountId, $iContentId, $sStatus, $sType = 'system') {
+    public function insertProfile ($iAccountId, $iContentId, $sStatus, $sType = 'system')
+    {
         $sSql = $this->prepare("INSERT INTO `sys_profiles` SET `account_id` = ?, `type` = ?, `content_id` = ?, `status` = ?", $iAccountId, $sType, $iContentId, $sStatus);
         if (!$this->query($sSql))
             return false;
@@ -93,24 +99,26 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
      * @param $sStatus profile status
      * @return true on success or false otherwise
      */
-    public function changeStatus ($iProfileId, $sStatus) {
+    public function changeStatus ($iProfileId, $sStatus)
+    {
         return $this->_updateField ($iProfileId, 'status', $sStatus);
     }
 
     /**
      * Get current account profile.
-     * @param string $iAccountId account id
+     * @param  string  $iAccountId account id
      * @return current account's profile id
      */
-    public function getCurrentProfileByAccount ($iAccountId) {
-        $sSql = $this->prepare("SELECT `profile_id` FROM `sys_accounts` WHERE `id` = ? LIMIT 1", $iAccountId);        
+    public function getCurrentProfileByAccount ($iAccountId)
+    {
+        $sSql = $this->prepare("SELECT `profile_id` FROM `sys_accounts` WHERE `id` = ? LIMIT 1", $iAccountId);
         $iProfileId = $this->getOne($sSql);
         if (!$iProfileId) {
             $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `account_id` = ? LIMIT 1", $iAccountId);
             $iProfileId = $this->getOne($sSql);
             if (!$iProfileId)
                 return false;
-            
+
             bx_import('BxDolAccountQuery');
             if (!BxDolAccountQuery::getInstance()->updateCurrentProfile($iAccountId, $iProfileId))
                 return false;
@@ -122,11 +130,12 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
      * Get profile by specified field name and value.
      * It is for internal usage only.
      * Use other funtions to get profile info, like getInfoById, etc.
-     * @param string $sField database field name
-     * @param mixed $sValue database field value
-     * @return array with porfile info
+     * @param  string $sField database field name
+     * @param  mixed  $sValue database field value
+     * @return array  with porfile info
      */
-    protected function _getDataByField ($sField, $sValue) {
+    protected function _getDataByField ($sField, $sValue)
+    {
         $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `$sField` = ? LIMIT 1", $sValue);
         return $this->getRow($sSql);
     }
@@ -134,22 +143,25 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
     /**
      * get profile id by id
      */
-    public function getIdById($iId) {
+    public function getIdById($iId)
+    {
         return (int)$this->_getFieldByField('id', 'id', $iId);
     }
 
     /**
-     * get account info by profile id 
+     * get account info by profile id
      */
-    public function getAccountInfoByProfileId($iId) {
+    public function getAccountInfoByProfileId($iId)
+    {
         $sSql = $this->prepare("SELECT `a`.* FROM `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON (`p`.`account_id` = `a`.`id`) WHERE `p`.`id` = ? LIMIT 1", $iId);
-        return $this->getRow($sSql);        
+        return $this->getRow($sSql);
     }
 
     /**
-     * get account email by profile id 
+     * get account email by profile id
      */
-    public function getEmailById($iId) {
+    public function getEmailById($iId)
+    {
         $a = $this->getAccountInfoByProfileId($iId);
         if (!$a || empty($a['email']))
             return false;
@@ -158,10 +170,11 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
 
     /**
      * Get profile info by id
-     * @param int $iID profile id
+     * @param  int   $iID profile id
      * @return array with profile info
      */
-    public function getInfoById( $iID )    {
+    public function getInfoById( $iID )
+    {
         return $this->_getDataByField('id', (int)$iID);
     }
 
@@ -169,12 +182,13 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
      * Get profile field by specified field name and value.
      * In most cases it is for internal usage only.
      * Use other funtions to get profile info, like getIdByEmail, etc.
-     * @param string $sFieldRequested database field name to return
-     * @param string $sFieldSearch database field name to search for
-     * @param mixed $sValue database field value
+     * @param  string    $sFieldRequested database field name to return
+     * @param  string    $sFieldSearch    database field name to search for
+     * @param  mixed     $sValue          database field value
      * @return specified profile field value
      */
-    protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue) {
+    protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue)
+    {
         $sSql = $this->prepare("SELECT `$sFieldRequested` FROM `sys_profiles` WHERE `$sFieldSearch` = ? LIMIT 1", $sValue);
         return $this->getOne($sSql);
     }
@@ -183,22 +197,24 @@ class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton {
      * Update some field by profile id
      * In most cases it is for internal usage only.
      * Use other funtions to get profile info, like updateLogged, etc.
-     * @param string $sFieldRequested database field name to return
-     * @param string $sFieldSearch database field name to search for
-     * @param mixed $sValue database field value
+     * @param  string    $sFieldRequested database field name to return
+     * @param  string    $sFieldSearch    database field name to search for
+     * @param  mixed     $sValue          database field value
      * @return specified profile field value
      */
-    protected function _updateField ($iId, $sFieldForUpdate, $sValue) {
+    protected function _updateField ($iId, $sFieldForUpdate, $sValue)
+    {
         $sSql = $this->prepare("UPDATE `sys_profiles` SET `$sFieldForUpdate` = ? WHERE `id` = ? LIMIT 1", $sValue, $iId);
         return $this->query($sSql);
     }
 
     /**
      * Delete profile info by id
-     * @param int $iID profile id
+     * @param  int      $iID profile id
      * @return affected rows
      */
-    public function delete($iID) {
+    public function delete($iID)
+    {
         $sSql = $this->prepare("DELETE FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iID);
         return $this->query($sSql);
     }

+ 27 - 18
inc/classes/BxDolProfileUndefined.php

@@ -7,13 +7,12 @@
  * @{
  */
 
-
 /**
  * When profile is not available (for example profile is deleted) then use this special class.
  *
  * @section example Example of usage
  *
- * @code 
+ * @code
  * bx_import('BxDolProfile');
  * $oProfile = BxDolProfile::getInstance($iId);
  * if (!$oProfile) {
@@ -22,19 +21,21 @@
  * }
  * @endcode
  */
-class BxDolProfileUndefined extends BxDol implements iBxDolSingleton, iBxDolProfile {
-
+class BxDolProfileUndefined extends BxDol implements iBxDolSingleton, iBxDolProfile
+{
     /**
      * Constructor
      */
-    protected function __construct () {
+    protected function __construct ()
+    {
         parent::__construct();
     }
 
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         $sClass = get_class($this);
         if (isset($GLOBALS['bxDolClasses'][$sClass]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
@@ -43,8 +44,8 @@ class BxDolProfileUndefined extends BxDol implements iBxDolSingleton, iBxDolProf
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
-
+    public static function getInstance()
+    {
         $sClass = __CLASS__;
         if(!isset($GLOBALS['bxDolClasses'][$sClass]))
             $GLOBALS['bxDolClasses'][$sClass] = new $sClass();
@@ -55,66 +56,74 @@ class BxDolProfileUndefined extends BxDol implements iBxDolSingleton, iBxDolProf
     /**
      * Get profile id
      */
-    public function id() {
+    public function id()
+    {
         return 0;
     }
 
     /**
      * Get profile display name
      */
-    public function getDisplayName() {
+    public function getDisplayName()
+    {
         return _t('_uknown');
     }
 
     /**
      * Get profile url
      */
-    public function getUrl() {
+    public function getUrl()
+    {
         return 'javascript:void(0);';
     }
 
     /**
      * Get profile unit
      */
-    public function getUnit() {
+    public function getUnit()
+    {
         return '<div>' . $this->getDisplayName() . '</div>';
     }
 
     /**
      * Get profile avatar
      */
-    public function getAvatar() {
+    public function getAvatar()
+    {
         return BxDolTemplate::getInstance()->getImageUrl('account-avatar.png');
     }
 
     /**
      * Get profile thumb
      */
-    public function getThumb() {
+    public function getThumb()
+    {
         return BxDolTemplate::getInstance()->getImageUrl('account-thumb.png');
     }
 
     /**
      * Get profile icon
      */
-    public function getIcon() {
+    public function getIcon()
+    {
         return BxDolTemplate::getInstance()->getImageUrl('account-icon.png');
     }
 
     /**
      * Get profile edit url
      */
-    public function getEditUrl() {
+    public function getEditUrl()
+    {
         return '';
     }
 
     /**
      * Check if profile is active
      */
-    public function isActive() {
+    public function isActive()
+    {
         return true;
     }
 }
 
 /** @} */
-

+ 43 - 31
inc/classes/BxDolRequest.php

@@ -10,11 +10,14 @@
 define('BX_DOL_REQUEST_ERROR_MODULE_NOT_FOUND', 1);
 define('BX_DOL_REQUEST_ERROR_PAGE_NOT_FOUND', 2);
 
-class BxDolRequest extends BxDol {
-    function __construct() {
+class BxDolRequest extends BxDol
+{
+    function __construct()
+    {
         parent::__construct();
     }
-    public static function processAsFile($aModule, &$aRequest) {
+    public static function processAsFile($aModule, &$aRequest)
+    {
         if(empty($aRequest) || ($sFileName = array_shift($aRequest)) == "")
             $sFileName = 'index';
 
@@ -27,8 +30,9 @@ class BxDolRequest extends BxDol {
             if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endModule('file', $sPrHash);
         }
     }
-    public static function processAsAction($aModule, &$aRequest, $sClass = "Module") {
-        $sAction = empty($aRequest) || (isset($aRequest[0]) && empty($aRequest[0])) ? 'Home' : array_shift($aRequest);                              
+    public static function processAsAction($aModule, &$aRequest, $sClass = "Module")
+    {
+        $sAction = empty($aRequest) || (isset($aRequest[0]) && empty($aRequest[0])) ? 'Home' : array_shift($aRequest);
         $sMethod = 'action' . bx_gen_method_name($sAction);
 
         if(isset($GLOBALS['bx_profiler']))
@@ -41,8 +45,9 @@ class BxDolRequest extends BxDol {
 
         return $mixedRet;
     }
-    public static function processAsService($aModule, $sMethod, $aParams, $sClass = "Module") {
-        if (isset($aModule['name']) && 'system' == $aModule['name'] && 'Module' == $sClass) 
+    public static function processAsService($aModule, $sMethod, $aParams, $sClass = "Module")
+    {
+        if (isset($aModule['name']) && 'system' == $aModule['name'] && 'Module' == $sClass)
             $sClass = 'BaseServices';
         $sMethod = 'service' . bx_gen_method_name($sMethod);
 
@@ -56,24 +61,30 @@ class BxDolRequest extends BxDol {
 
         return $mixedRet;
     }
-    public static function serviceExists($mixedModule, $sMethod, $sClass = "Module") {
+    public static function serviceExists($mixedModule, $sMethod, $sClass = "Module")
+    {
         return BxDolRequest::_methodExists($mixedModule, 'service', $sMethod, $sClass);
     }
-    public static function actionExists($mixedModule, $sMethod, $sClass = "Module") {
+    public static function actionExists($mixedModule, $sMethod, $sClass = "Module")
+    {
         return BxDolRequest::_methodExists($mixedModule, 'action', $sMethod, $sClass);
     }
-    public static function moduleNotFound($sModule) {
+    public static function moduleNotFound($sModule)
+    {
         BxDolRequest::_error('module', $sModule);
     }
-    public static function pageNotFound($sPage, $sModule) {
+    public static function pageNotFound($sPage, $sModule)
+    {
         BxDolRequest::_error('page', $sPage, $sModule);
     }
-    public static function methodNotFound($sMethod, $sModule) {
+    public static function methodNotFound($sMethod, $sModule)
+    {
         BxDolRequest::_error('method', $sMethod, $sModule);
     }
 
-    protected static function _perform($aModule, $sClass, $sMethod, $aParams, $bTerminateOnError = true) {
-        $sClass = $aModule['class_prefix'] . $sClass;        
+    protected static function _perform($aModule, $sClass, $sMethod, $aParams, $bTerminateOnError = true)
+    {
+        $sClass = $aModule['class_prefix'] . $sClass;
 
         $oModule = BxDolRequest::_require($aModule, $sClass);
         if($oModule === false && $bTerminateOnError)
@@ -89,27 +100,28 @@ class BxDolRequest extends BxDol {
         else if(!$bMethod && !$bTerminateOnError)
             return false;
     }
-    protected static function _require($aModule, $sClass) {
-        if(isset($GLOBALS['bxDolClasses'][$sClass])) 
-        	return $GLOBALS['bxDolClasses'][$sClass];
+    protected static function _require($aModule, $sClass)
+    {
+        if(isset($GLOBALS['bxDolClasses'][$sClass]))
+            return $GLOBALS['bxDolClasses'][$sClass];
 
-		if($aModule['path']) {
-        	$sFile = BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $sClass . '.php';
-            if(!file_exists($sFile)) 
-            	return false;
+        if($aModule['path']) {
+            $sFile = BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $sClass . '.php';
+            if(!file_exists($sFile))
+                return false;
 
-			require_once($sFile);
-		}
-		else
-        	bx_import($sClass);
+            require_once($sFile);
+        } else
+            bx_import($sClass);
 
-		if(!class_exists($sClass)) 
-			return false;
+        if(!class_exists($sClass))
+            return false;
 
-		$GLOBALS['bxDolClasses'][$sClass] = new $sClass($aModule);
+        $GLOBALS['bxDolClasses'][$sClass] = new $sClass($aModule);
         return $GLOBALS['bxDolClasses'][$sClass];
     }
-    protected static function _methodExists($mixedModule, $sMethodType, $sMethodName, $sClass = "Module"){
+    protected static function _methodExists($mixedModule, $sMethodType, $sMethodName, $sClass = "Module")
+    {
         $aModule = $mixedModule;
         if(is_string($mixedModule)) {
             bx_import('BxDolModuleQuery');
@@ -126,7 +138,8 @@ class BxDolRequest extends BxDol {
         $sMethod = $sMethodType . bx_gen_method_name($sMethodName);
         return method_exists($oModule, $sMethod);
     }
-    protected static function _error($sType, $sParam1 = '', $sParam2 = '') {
+    protected static function _error($sType, $sParam1 = '', $sParam2 = '')
+    {
         header('Status: 404 Not Found');
         header('HTTP/1.0 404 Not Found');
 
@@ -143,4 +156,3 @@ class BxDolRequest extends BxDol {
 }
 
 /** @} */
-

+ 14 - 14
inc/classes/BxDolRssFactory.php

@@ -7,22 +7,22 @@
  * @{
  */
 
-class BxDolRssFactory extends BxDol {
-
+class BxDolRssFactory extends BxDol
+{
     /**
      * @param array $aRssData, fields:
-     *    UnitID
-     *    OwnerID
-     *    UnitTitle
-     *    UnitLink
-     *    UnitDesc
-     *    UnitDateTimeUTS
-     *    UnitIcon
+     *                         UnitID
+     *                         OwnerID
+     *                         UnitTitle
+     *                         UnitLink
+     *                         UnitDesc
+     *                         UnitDateTimeUTS
+     *                         UnitIcon
      */
-    function GenRssByData($aRssData, $sUnitTitleC, $sMainLink) {
-
+    function GenRssByData($aRssData, $sUnitTitleC, $sMainLink)
+    {
         return $this->GenRssByCustomData($aRssData, $sUnitTitleC, $sMainLink, array(
-        	'Guid' => 'UnitID',
+            'Guid' => 'UnitID',
             'Link' => 'UnitLink',
             'Title' => 'UnitTitle',
             'DateTimeUTS' => 'UnitDateTimeUTS',
@@ -43,7 +43,8 @@ class BxDolRssFactory extends BxDol {
      * Optional fields:
      *  Photo
      */
-    function GenRssByCustomData($aRssData, $sUnitTitleC, $sMainLink, $aFields, $sImage = '', $iPID = 0) {
+    function GenRssByCustomData($aRssData, $sUnitTitleC, $sMainLink, $aFields, $sImage = '', $iPID = 0)
+    {
         $sRSSLast = '';
         if (isset($aRssData[0]))
             $sRSSLast = bx_time_utc($aRssData[0][$aFields['DateTimeUTS']]);
@@ -91,4 +92,3 @@ class BxDolRssFactory extends BxDol {
 }
 
 /** @} */
-

+ 53 - 59
inc/classes/BxDolSearch.php

@@ -10,8 +10,8 @@
 define('BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT', 10);
 define('BX_DOL_SEARCH_KEYWORD_PAGE', 'site-search-page');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section search Search
  * @ref BxDolSearch
  */
@@ -41,7 +41,7 @@ define('BX_DOL_SEARCH_KEYWORD_PAGE', 'site-search-page');
  * no alerts available
  *
  */
-class BxDolSearch extends BxDol 
+class BxDolSearch extends BxDol
 {
     protected $aClasses = array(); ///< array of all search classes
     protected $aChoice  = array(); ///< array of current search classes which were choosen in search area
@@ -52,7 +52,7 @@ class BxDolSearch extends BxDol
      * Constructor
      * @param array $aChoice - array of choosen classes (will take a part only existing in `sys_objects_search` table)
      */
-    public function __construct ($aChoice = '') 
+    public function __construct ($aChoice = '')
     {
         parent::__construct();
 
@@ -78,7 +78,7 @@ class BxDolSearch extends BxDol
     /**
      * create units for all classes and calling their processing methods
      */
-    public function response () 
+    public function response ()
     {
         bx_import('BxDolTemplate');
         $sCode = '';
@@ -95,7 +95,7 @@ class BxDolSearch extends BxDol
         return $sCode;
     }
 
-    public function getEmptyResult () 
+    public function getEmptyResult ()
     {
         $sKey = _t('_Empty');
         return DesignBoxContent($sKey, MsgBox($sKey), 1);
@@ -241,7 +241,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * constructor
      * filling identificator field
      */
-    function __construct () 
+    function __construct ()
     {
         if (isset($this->aPseud['id']))
             $this->aCurrent['ident'] = $this->aPseud['id'];
@@ -272,7 +272,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * @param $b - boolan value to enable or disable 'empty' message
      * @param $sLangKey [optional] - custom 'empty' message
      */
-    public function setDisplayEmptyMsg($b, $sLangKey = '') 
+    public function setDisplayEmptyMsg($b, $sLangKey = '')
     {
         $this->bDisplayEmptyMsg = $b;
         if ($sLangKey)
@@ -283,7 +283,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Perform privacy checking for every unit
      * @param $b - boolan value to enable or disable privacy checking
      */
-    public function setProcessPrivateContent ($b) 
+    public function setProcessPrivateContent ($b)
     {
         $this->bProcessPrivateContent = $b;
     }
@@ -292,14 +292,13 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Get html box of search results (usually used in grlobal search)
      * @return html code
      */
-    function processing () 
+    function processing ()
     {
         $sCode = $this->displayResultBlock();
         if ($this->aCurrent['paginate']['num'] > 0) {
             $sPaginate = $this->showPagination();
             $sCode = $this->displaySearchBox($sCode, $sPaginate);
-        }
-        else {
+        } else {
             $sCode = $this->bDisplayEmptyMsg ? $this->displaySearchBox(MsgBox(_t($this->sDisplayEmptyMsgKey ? $this->sDisplayEmptyMsgKey : '_Empty'))) : '';
         }
         return $sCode;
@@ -309,7 +308,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Get html output of search result
      * @return html code
      */
-    function displayResultBlock () 
+    function displayResultBlock ()
     {
         $aData = $this->getSearchData();
         if (count($aData) > 0) {
@@ -325,7 +324,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Add different code before html output (usually redeclared)
      * no return result
      */
-    function addCustomParts () 
+    function addCustomParts ()
     {
 
     }
@@ -333,7 +332,7 @@ class BxDolSearchResult implements iBxDolReplaceable
     /**
      * Get XML string for rss output
      */
-    function rss () 
+    function rss ()
     {
         if (!isset($this->aCurrent['rss']['fields']) || !isset($this->aCurrent['rss']['link']))
             return '';
@@ -361,7 +360,7 @@ class BxDolSearchResult implements iBxDolReplaceable
     /**
      * Output RSS XML with XML header
      */
-    function outputRSS () 
+    function outputRSS ()
     {
         header('Content-Type: text/xml; charset=UTF-8');
         echo $this->rss();
@@ -370,25 +369,24 @@ class BxDolSearchResult implements iBxDolReplaceable
     /**
      * Return rss unit link (redeclared)
      */
-    function getRssUnitLink (&$a) 
+    function getRssUnitLink (&$a)
     {
         // override this functions to return permalink to rss unit
     }
 
     /**
      * Naming fields in query's body
-     * @param string $sFieldName name of field
-     * @param string $sTableName name of field's table
-     * $param string $sOperator of field's calculation (like MAX)
+     * @param string  $sFieldName  name of field
+     * @param string  $sTableName  name of field's table
+     *                             $param string $sOperator of field's calculation (like MAX)
      * @param boolean $bRenameMode indicator for renaming and unsetting fields from field of class $this->aPseud
-     * return $sqlUnit sql code and unsetting elements from aPseud field
+     *                             return $sqlUnit sql code and unsetting elements from aPseud field
      */
-    function setFieldUnit ($sFieldName, $sTableName, $sOperator = '', $bRenameMode = true) 
+    function setFieldUnit ($sFieldName, $sTableName, $sOperator = '', $bRenameMode = true)
     {
         if (strlen($sOperator) > 0) {
             $sqlUnit  = "$sOperator(`$sTableName`.`$sFieldName`)";
-        }
-        else
+        } else
             $sqlUnit  = "`$sTableName`.`$sFieldName`";
 
         if (isset($this->aPseud) && $bRenameMode !== false) {
@@ -404,9 +402,9 @@ class BxDolSearchResult implements iBxDolReplaceable
     /**
      * Get html code of of every search unit
      * @param array $aData array of every search unit
-     * return html code
+     *                     return html code
      */
-    function displaySearchUnit ($aData)     
+    function displaySearchUnit ($aData)
     {
 
     }
@@ -414,10 +412,10 @@ class BxDolSearchResult implements iBxDolReplaceable
     /**
      * Get html code of search box with search results
      * @param string $sCode html code of search results
-     * $param $sPaginate html code of paginate
-     * return html code
+     *                      $param $sPaginate html code of paginate
+     *                      return html code
      */
-    function displaySearchBox ($sCode, $sPaginate = '') 
+    function displaySearchBox ($sCode, $sPaginate = '')
     {
 
     }
@@ -425,7 +423,7 @@ class BxDolSearchResult implements iBxDolReplaceable
     /**
      * Get html code of pagination
      */
-    function showPagination ($bAdmin = false, $bChangePage = true, $bPageReload = true) 
+    function showPagination ($bAdmin = false, $bChangePage = true, $bPageReload = true)
     {
 
     }
@@ -434,7 +432,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Get array of data with search results
      * return array with data
      */
-    function getSearchData () 
+    function getSearchData ()
     {
         $this->aPseud = $this->_getPseud();
         $this->setConditionParams();
@@ -450,7 +448,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * @param boolean #bREnameMode indicator of renmaing fields
      * return array with joinFields, ownFields, groupBy and join elements
      */
-    function getJoins ($bRenameMode = true) 
+    function getJoins ($bRenameMode = true)
     {
         $aSql = array();
         // joinFields & join
@@ -483,7 +481,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * @param $aParams addon param
      * return $aData multivariate array
      */
-    function getSearchDataByParams ($aParams = '') 
+    function getSearchDataByParams ($aParams = '')
     {
         $aSql = array('ownFields'=>'', 'joinFields'=>'', 'order'=>'');
 
@@ -498,8 +496,7 @@ class BxDolSearchResult implements iBxDolReplaceable
             $aSql['joinFields'] .= $aJoins['joinFields'];
             $aSql['join'] = $aJoins['join'];
             $aSql['groupBy'] = $aJoins['groupBy'];
-        }
-        else
+        } else
             $aSql['ownFields'] = trim($aSql['ownFields'], ', ');
 
         // from
@@ -549,7 +546,7 @@ class BxDolSearchResult implements iBxDolReplaceable
     /**
      * Set class fields condition params and paginate array
      */
-    function setConditionParams() 
+    function setConditionParams()
     {
         $aWhere = array();
         $aWhere[] = '1';
@@ -566,8 +563,7 @@ class BxDolSearchResult implements iBxDolReplaceable
             $sName = bx_process_input($_GET['ownerName']);
             $iUser = (int)BxDolProfileQuery::getInstance()->getIdByNickname($sName);
             BxDolMenu::getInstance()->setCurrentProfileID($iUser);
-        }
-        elseif (isset($_GET['userID']))
+        } elseif (isset($_GET['userID']))
             $iUser = bx_process_input($_GET['userID'], BX_DATA_INT);
 
         if (!empty($iUser))
@@ -576,9 +572,8 @@ class BxDolSearchResult implements iBxDolReplaceable
         $this->setPaginate();
         $iNum = $this->getNum();
         if ($iNum > 0) {
-            $this->aCurrent['paginate']['num'] = $iNum;            
-        }
-        else {
+            $this->aCurrent['paginate']['num'] = $iNum;
+        } else {
            $this->aCurrent['paginate']['num'] = 0;
         }
     }
@@ -587,7 +582,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Check number of records on current page
      * return number of records on current page + 1
      */
-    function getNum () 
+    function getNum ()
     {
         $aJoins = $this->getJoins(false);
         $sqlQuery =  "SELECT * FROM `{$this->aCurrent['table']}` " . (isset($aJoins['join']) ? $aJoins['join'] : '' ). $this->getRestriction() . (isset($aJoins['groupBy']) ? $aJoins['groupBy'] : '') . ' ' . $this->getLimit(true);
@@ -598,7 +593,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Check restriction params and make condition part of query
      * return $sqlWhere sql code of query for WHERE part
      */
-    function getRestriction () 
+    function getRestriction ()
     {
         $oDb = BxDolDb::getInstance();
         $sqlWhere = '';
@@ -639,7 +634,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Get limit part of query
      * return $sqlFrom code for limit part pf query
      */
-    function getLimit ($isAddPlusOne = false) 
+    function getLimit ($isAddPlusOne = false)
     {
         if (!isset($this->aCurrent['paginate']))
             return;
@@ -653,7 +648,7 @@ class BxDolSearchResult implements iBxDolReplaceable
     /**
      * Set sorting field of class
      */
-    function setSorting () 
+    function setSorting ()
     {
         $this->aCurrent['sorting'] = isset($_GET[$this->aCurrent['name'] . '_mode']) ? $_GET[$this->aCurrent['name'] . '_mode'] : $this->aCurrent['sorting'];
     }
@@ -661,9 +656,9 @@ class BxDolSearchResult implements iBxDolReplaceable
     /**
      * Get sorting part of query according current sorting mode
      * @param string $sSortType sorting type
-     * return array with sql elements order and ownFields
+     *                          return array with sql elements order and ownFields
      */
-    function getSorting ($sSortType = 'last') 
+    function getSorting ($sSortType = 'last')
     {
         $aOverride = $this->getAlterOrder();
         if (is_array($aOverride) && !empty($aOverride))
@@ -675,7 +670,7 @@ class BxDolSearchResult implements iBxDolReplaceable
                 $aSql['order'] = "ORDER BY RAND()";
                 break;
            case 'score':
-                if (is_array($this->aCurrent['restriction']['keyword'])) {    
+                if (is_array($this->aCurrent['restriction']['keyword'])) {
                     $sPseud = '';
                     if ('on' == getParam('useLikeOperator')) {
                         $aSql['order'] = "ORDER BY `score` DESC";
@@ -697,7 +692,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Return own varaint for sorting (redeclare if necessary)
      * return array of sql elements
      */
-    function getAlterOrder () 
+    function getAlterOrder ()
     {
         return array();
     }
@@ -706,7 +701,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Set paginate fields of class according GET params 'start' and 'per_page'
      * forcePage is need for setting most important number of current page
      */
-    function setPaginate () 
+    function setPaginate ()
     {
         $this->aCurrent['paginate']['perPage'] = (isset($_GET['per_page']) && (int)$_GET['per_page'] != 0) ? (int)$_GET['per_page'] : $this->aCurrent['paginate']['perPage'];
         if (empty($this->aCurrent['paginate']['perPage']))
@@ -725,9 +720,9 @@ class BxDolSearchResult implements iBxDolReplaceable
      * @param array of search fields
      * @param string $sKeyword keyword value for search
      * @param string sPseud for setting new name for generated set of fields in query
-     * return sql code of WHERE part in query
+     *                         return sql code of WHERE part in query
      */
-    function getSearchFieldsCond ($aFields, $sKeyword, $sPseud = '') 
+    function getSearchFieldsCond ($aFields, $sKeyword, $sPseud = '')
     {
         if (!$sKeyword)
             return '';
@@ -758,7 +753,7 @@ class BxDolSearchResult implements iBxDolReplaceable
             $sSqlWhere = '';
             foreach ($aFields as $sValue)
                 $sSqlWhere .= "`{$sTable}`.`$sValue`, ";
-            
+
             $sSqlWhere = trim($sSqlWhere, ', ');
             $sSqlWhere = " MATCH({$sSqlWhere}) AGAINST ('{$sKeyword}') ";
 
@@ -774,18 +769,17 @@ class BxDolSearchResult implements iBxDolReplaceable
      * @param $aValues array of values
      * return sql code for field with operator IN (NOT IN)
      */
-    function getMultiValues ($aValues) 
+    function getMultiValues ($aValues)
     {
         $oDb = BxDolDb::getInstance();
         return $oDb->implode_escape($aValues);
     }
 
-
     /**
      * System method for filling aPseud array.
      * Fill field aPseud for current class (if you will use own getSearchUnit methods then not necessary to redeclare).
      */
-    function _getPseud () 
+    function _getPseud ()
     {
 
     }
@@ -795,7 +789,7 @@ class BxDolSearchResult implements iBxDolReplaceable
      * @param $a array of markers as key => value
      * @return true on success or false on error
      */
-    public function addMarkers ($a) 
+    public function addMarkers ($a)
     {
         if (empty($a) || !is_array($a))
             return false;
@@ -807,8 +801,8 @@ class BxDolSearchResult implements iBxDolReplaceable
      * Replace provided markers in a string
      * @param $mixed string or array to replace markers in
      * @return string where all occured markers are replaced
-     */ 
-    protected function _replaceMarkers ($mixed) 
+     */
+    protected function _replaceMarkers ($mixed)
     {
         return bx_replace_markers($mixed, $this->_aMarkers);
     }

+ 5 - 6
inc/classes/BxDolService.php

@@ -30,17 +30,17 @@ bx_import('BxDolRequest');
  * no alerts available
  *
  */
-class BxDolService extends BxDol 
+class BxDolService extends BxDol
 {
     /**
      * Perform serice call
      * @param $mixed module name or module id
      * @param $sMethod service method name in format 'method_name', corresponding class metod is serviceMethodName
      * @param $aParams params to pass to service method
-     * @param $sClass class to search for service method, by default it is main module class 
+     * @param $sClass class to search for service method, by default it is main module class
      * @return service call result
      */
-    public static function call($mixed, $sMethod, $aParams = array(), $sClass = 'Module') 
+    public static function call($mixed, $sMethod, $aParams = array(), $sClass = 'Module')
     {
         bx_import('BxDolModuleQuery');
         $oDb = BxDolModuleQuery::getInstance();
@@ -70,7 +70,7 @@ class BxDolService extends BxDol
      * @param $sReplaceIn params to pass to service method
      * @return service call result
      */
-    public static function callSerialized($s, $aMarkers = array(), $sReplaceIn = 'params') 
+    public static function callSerialized($s, $aMarkers = array(), $sReplaceIn = 'params')
     {
         $a = @unserialize($s);
         if (false === $a || !is_array($a))
@@ -85,11 +85,10 @@ class BxDolService extends BxDol
     /**
      * Check if string is serialized array
      */
-    public static function isSerializedService($s) 
+    public static function isSerializedService($s)
     {
         return preg_match('/^a:[\d+]:\{/', $s);
     }
 }
 
 /** @} */
-

+ 34 - 21
inc/classes/BxDolSession.php

@@ -12,14 +12,15 @@ bx_import('BxDolSessionQuery');
 define('BX_DOL_SESSION_LIFETIME', 3600);
 define('BX_DOL_SESSION_COOKIE', 'memberSession');
 
-class BxDolSession extends BxDol implements iBxDolSingleton {
+class BxDolSession extends BxDol implements iBxDolSingleton
+{
     protected $oDb;
     protected $sId;
     protected $iUserId;
     protected $aData;
 
-    private function __construct() {
-
+    private function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -34,7 +35,8 @@ class BxDolSession extends BxDol implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -42,7 +44,8 @@ class BxDolSession extends BxDol implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
+    public static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolSession();
 
@@ -52,7 +55,8 @@ class BxDolSession extends BxDol implements iBxDolSingleton {
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    function start(){
+    function start()
+    {
         if (defined('BX_DOL_CRON_EXECUTE'))
             return true;
 
@@ -69,7 +73,8 @@ class BxDolSession extends BxDol implements iBxDolSingleton {
         return true;
     }
 
-    function destroy() {
+    function destroy()
+    {
         $aUrl = parse_url(BX_DOL_URL_ROOT);
         $sPath = isset($aUrl['path']) && !empty($aUrl['path']) ? $aUrl['path'] : '/';
         setcookie(BX_DOL_SESSION_COOKIE, '', time() - 86400, $sPath, '', false, true);
@@ -82,7 +87,8 @@ class BxDolSession extends BxDol implements iBxDolSingleton {
         $this->aData = array();
     }
 
-    function exists($sId = '') {
+    function exists($sId = '')
+    {
         if(empty($sId) && isset($_COOKIE[BX_DOL_SESSION_COOKIE]))
             $sId = bx_process_input($_COOKIE[BX_DOL_SESSION_COOKIE]);
 
@@ -92,21 +98,23 @@ class BxDolSession extends BxDol implements iBxDolSingleton {
             $this->iUserId = (int)$mixedSession['user_id'];
             $this->aData = unserialize($mixedSession['data']);
             return true;
-        }
-        else
+        } else
             return false;
     }
 
-    function getId() {
+    function getId()
+    {
         return $this->sId;
     }
 
-    function setUserId($iUserId) {
-    	$this->iUserId = $iUserId;
-    	$this->save();
+    function setUserId($iUserId)
+    {
+        $this->iUserId = $iUserId;
+        $this->save();
     }
 
-    function setValue($sKey, $mixedValue) {
+    function setValue($sKey, $mixedValue)
+    {
         if(empty($this->sId))
             $this->start();
 
@@ -114,7 +122,8 @@ class BxDolSession extends BxDol implements iBxDolSingleton {
         $this->save();
     }
 
-    function unsetValue($sKey) {
+    function unsetValue($sKey)
+    {
         if(empty($this->sId))
             $this->start();
 
@@ -126,26 +135,30 @@ class BxDolSession extends BxDol implements iBxDolSingleton {
             $this->destroy();
     }
 
-    function getValue($sKey) {
+    function getValue($sKey)
+    {
         if(empty($this->sId))
             $this->start();
 
         return isset($this->aData[$sKey]) ? $this->aData[$sKey] : false;
     }
 
-	function getUnsetValue($sKey) {
+    function getUnsetValue($sKey)
+    {
         $mixedValue = $this->getValue($sKey);
         if($mixedValue !== false)
-        	$this->unsetValue($sKey);
+            $this->unsetValue($sKey);
 
         return $mixedValue;
     }
 
-    public function maintenance() {
+    public function maintenance()
+    {
         return $this->oDb->deleteExpired();
     }
 
-    protected function save() {
+    protected function save()
+    {
         if($this->iUserId == 0)
             $this->iUserId = getLoggedId();
 

+ 14 - 8
inc/classes/BxDolSessionQuery.php

@@ -12,23 +12,28 @@ bx_import('BxDolDb');
 /**
  * @see BxDolSession
  */
-class BxDolSessionQuery extends BxDolDb {
+class BxDolSessionQuery extends BxDolDb
+{
     protected $sTable;
 
-    function __construct() {
+    function __construct()
+    {
         parent::__construct();
 
         $this->sTable = 'sys_sessions';
     }
-    function getTableName() {
+    function getTableName()
+    {
         return $this->sTable;
     }
-    function exists($sId) {
+    function exists($sId)
+    {
         $sSql = $this->prepare("SELECT `id`, `user_id`, `data` FROM `" . $this->sTable . "` WHERE `id`=? LIMIT 1", $sId);
         $aSession = $this->getRow($sSql);
         return !empty($aSession) ? $aSession : false;
     }
-    function save($sId, $aSet) {
+    function save($sId, $aSet)
+    {
         $sSetClause = $this->prepare("`id`=?", $sId);
         foreach($aSet as $sKey => $sValue)
             $sSetClause .= $this->prepare(", `" . $sKey . "`=?", $sValue);
@@ -36,11 +41,13 @@ class BxDolSessionQuery extends BxDolDb {
 
         return (int)$this->query("REPLACE INTO `" . $this->sTable . "` SET " . $sSetClause) > 0;
     }
-    function delete($sId) {
+    function delete($sId)
+    {
         $sSql = $this->prepare("DELETE FROM `" . $this->sTable . "` WHERE `id`=? LIMIT 1", $sId);
         return (int)$this->query($sSql) > 0;
     }
-    function deleteExpired() {
+    function deleteExpired()
+    {
         $sSql = $this->prepare("DELETE FROM `" . $this->sTable . "` WHERE `date` < (UNIX_TIMESTAMP() - ?)", BX_DOL_SESSION_LIFETIME);
         $iRet = (int)$this->query($sSql);
         $this->query("OPTIMIZE TABLE `" . $this->sTable . "`");
@@ -49,4 +56,3 @@ class BxDolSessionQuery extends BxDolDb {
 }
 
 /** @} */
-

+ 131 - 126
inc/classes/BxDolSocialSharing.php

@@ -1,126 +1,131 @@
-<?php defined('BX_DOL') or die('hack attempt');
-/**
- * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
- * CC-BY License - http://creativecommons.org/licenses/by/3.0/
- *
- * @defgroup    DolphinCore Dolphin Core
- * @{
- */
-
-bx_import('BxDolSocialSharingQuery');
-
-/** 
- * @page objects 
- * @section social_sharing Social Sharing Buttons
- * @ref BxDolSocialSharing
- */
-
-/**
- * Social sharing buttons for any content
- *
- * It displays sharing buttons from popular social networks, like facebook, twitter, gogole plus, etc.
- *
- * 
- * @section example Example of usage:
- *
- * @code
- * bx_import('BxTemplSocialSharing');
- * echo BxTemplSocialSharing::getInstance()->getCode($iId, $sModuleName, $sUrl, $sTitle);
- * @endcode
- *
- *
- * @section alerts Alerts:
- * 
- * Type/unit: system
- * Action: social_sharing_display
- * Options:
- *      buttons - reference to buttons array
- *      markers - reference to variables for replacement
- *      override_output - override output string
- *
- */ 
-class BxDolSocialSharing extends BxDol implements iBxDolSingleton
-{
-    protected $_oQuery;
-	protected $_aSocialButtons = array (); // active social buttons array
-
-	/**
-	 * Constructor
-	 */
-	protected function __construct() {
-        parent::__construct();
-        $this->_oQuery = new BxDolSocialSharingQuery();
-        $this->_aSocialButtons = $this->_oQuery->getActiveButtons();
-	}
-
-    /**
-     * Get object instance 
-     * @param $sObject object name
-     * @return object instance 
-     */
-    static public function getInstance() {
-
-        if (isset($GLOBALS['bxDolClasses']['BxDolSocialSharing']))
-            return $GLOBALS['bxDolClasses']['BxDolSocialSharing'];
-        
-        bx_import('BxTemplSocialSharing');
-        $o = new BxTemplSocialSharing();
-
-        return ($GLOBALS['bxDolClasses']['BxDolSocialSharing'] = $o);
-    }
-
-    public function getCode ($sContentId, $sModuleName, $sUrl, $sTitle, $aCustomVars = false) {
-        // overrided in template class
-    }
-
-    /**
-     * Replace provided markers in string.
-     * @param $s - string to replace markers in 
-     * @param $a - markers array
-     * @return string with replaces markers
-     */ 
-    protected function _replaceMarkers ($mixed, $aMarkers) {
-        if (empty($mixed) || empty($aMarkers) || !is_array($aMarkers))
-            return $mixed;
-        return bx_replace_markers($mixed, $aMarkers);
-    }
-
-    /**
-     * Get most facebook locale for provided language code.
-     * @param $sLang lang code
-     * @return locale string or empty string if no lacale is found
-     */ 
-    protected function _getLocaleFacebook ($sLang) {
-        $aLocales = $this->_getLocalesFacebook();
-        if (!$aLocales || !isset($aLocales[$sLang]))
-            return '';
-        return $aLocales[$sLang];
-    }
-
-    /**
-     * Get facebook locales
-     * @return locales array, lang is array key and locale is array value
-     */ 
-    protected function _getLocalesFacebook () {
-        $oCache = $this->_oQuery->getDbCacheObject();
-        $sCacheKey = $this->_oQuery->genDbCacheKey('sys_social_sharing_locales_fb');
-        $aData = $oCache->getData($sCacheKey);
-        if (null === $aData) {
-            $sXML = bx_file_get_contents ('http://www.facebook.com/translations/FacebookLocales.xml');
-            if (!$sXML)
-                return false;
-            $xmlLocates = new SimpleXMLElement($sXML);
-            $aData = array ();
-            foreach ($xmlLocates->locale as $xmlLocale) {
-                $sLocale = (string)($xmlLocale->codes->code->standard->representation);
-                list ($sLang,) = explode('_', $sLocale);
-                if (!isset($aData[$sLang]))
-                    $aData[$sLang] = $sLocale;
-            }
-            $oCache->setData ($sCacheKey, $aData); 
-        }
-        return $aData;
-    }
-}
-
-/** @} */
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    DolphinCore Dolphin Core
+ * @{
+ */
+
+bx_import('BxDolSocialSharingQuery');
+
+/**
+ * @page objects
+ * @section social_sharing Social Sharing Buttons
+ * @ref BxDolSocialSharing
+ */
+
+/**
+ * Social sharing buttons for any content
+ *
+ * It displays sharing buttons from popular social networks, like facebook, twitter, gogole plus, etc.
+ *
+ *
+ * @section example Example of usage:
+ *
+ * @code
+ * bx_import('BxTemplSocialSharing');
+ * echo BxTemplSocialSharing::getInstance()->getCode($iId, $sModuleName, $sUrl, $sTitle);
+ * @endcode
+ *
+ *
+ * @section alerts Alerts:
+ *
+ * Type/unit: system
+ * Action: social_sharing_display
+ * Options:
+ *      buttons - reference to buttons array
+ *      markers - reference to variables for replacement
+ *      override_output - override output string
+ *
+ */
+class BxDolSocialSharing extends BxDol implements iBxDolSingleton
+{
+    protected $_oQuery;
+    protected $_aSocialButtons = array (); // active social buttons array
+
+    /**
+     * Constructor
+     */
+    protected function __construct()
+    {
+        parent::__construct();
+        $this->_oQuery = new BxDolSocialSharingQuery();
+        $this->_aSocialButtons = $this->_oQuery->getActiveButtons();
+    }
+
+    /**
+     * Get object instance
+     * @param $sObject object name
+     * @return object instance
+     */
+    static public function getInstance()
+    {
+        if (isset($GLOBALS['bxDolClasses']['BxDolSocialSharing']))
+            return $GLOBALS['bxDolClasses']['BxDolSocialSharing'];
+
+        bx_import('BxTemplSocialSharing');
+        $o = new BxTemplSocialSharing();
+
+        return ($GLOBALS['bxDolClasses']['BxDolSocialSharing'] = $o);
+    }
+
+    public function getCode ($sContentId, $sModuleName, $sUrl, $sTitle, $aCustomVars = false)
+    {
+        // overrided in template class
+    }
+
+    /**
+     * Replace provided markers in string.
+     * @param $s - string to replace markers in
+     * @param $a - markers array
+     * @return string with replaces markers
+     */
+    protected function _replaceMarkers ($mixed, $aMarkers)
+    {
+        if (empty($mixed) || empty($aMarkers) || !is_array($aMarkers))
+            return $mixed;
+        return bx_replace_markers($mixed, $aMarkers);
+    }
+
+    /**
+     * Get most facebook locale for provided language code.
+     * @param $sLang lang code
+     * @return locale string or empty string if no lacale is found
+     */
+    protected function _getLocaleFacebook ($sLang)
+    {
+        $aLocales = $this->_getLocalesFacebook();
+        if (!$aLocales || !isset($aLocales[$sLang]))
+            return '';
+        return $aLocales[$sLang];
+    }
+
+    /**
+     * Get facebook locales
+     * @return locales array, lang is array key and locale is array value
+     */
+    protected function _getLocalesFacebook ()
+    {
+        $oCache = $this->_oQuery->getDbCacheObject();
+        $sCacheKey = $this->_oQuery->genDbCacheKey('sys_social_sharing_locales_fb');
+        $aData = $oCache->getData($sCacheKey);
+        if (null === $aData) {
+            $sXML = bx_file_get_contents ('http://www.facebook.com/translations/FacebookLocales.xml');
+            if (!$sXML)
+                return false;
+            $xmlLocates = new SimpleXMLElement($sXML);
+            $aData = array ();
+            foreach ($xmlLocates->locale as $xmlLocale) {
+                $sLocale = (string)($xmlLocale->codes->code->standard->representation);
+                list ($sLang,) = explode('_', $sLocale);
+                if (!isset($aData[$sLang]))
+                    $aData[$sLang] = $sLocale;
+            }
+            $oCache->setData ($sCacheKey, $aData);
+        }
+        return $aData;
+    }
+}
+
+/** @} */

+ 30 - 28
inc/classes/BxDolSocialSharingQuery.php

@@ -1,28 +1,30 @@
-<?php defined('BX_DOL') or die('hack attempt');
-/**
- * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
- * CC-BY License - http://creativecommons.org/licenses/by/3.0/
- *
- * @defgroup    DolphinCore Dolphin Core
- * @{
- */
-
-bx_import('BxDolDb');
-
-/**
- * @see BxDolSocialSharing
- */ 
-class BxDolSocialSharingQuery extends BxDolDb
-{
-
-	function __construct() {
-		parent::__construct();
-	}
-
-    function getActiveButtons () {
-        return $this->fromCache('sys_objects_social_sharing', 'getAll', 'SELECT * FROM `sys_objects_social_sharing` WHERE `active` = 1 ORDER BY `order` ASC');
-    }
-
-}
-
-/** @} */
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    DolphinCore Dolphin Core
+ * @{
+ */
+
+bx_import('BxDolDb');
+
+/**
+ * @see BxDolSocialSharing
+ */
+class BxDolSocialSharingQuery extends BxDolDb
+{
+
+    function __construct()
+    {
+        parent::__construct();
+    }
+
+    function getActiveButtons ()
+    {
+        return $this->fromCache('sys_objects_social_sharing', 'getAll', 'SELECT * FROM `sys_objects_social_sharing` WHERE `active` = 1 ORDER BY `order` ASC');
+    }
+
+}
+
+/** @} */

Разница между файлами не показана из-за своего большого размера
+ 236 - 182
inc/classes/BxDolStorage.php


+ 23 - 21
inc/classes/BxDolStorageLocal.php

@@ -16,21 +16,23 @@ bx_import('BxDolStorage');
  * File storage in local folder.
  * @see BxDolStorage
  */
-class BxDolStorageLocal extends BxDolStorage {
-
+class BxDolStorageLocal extends BxDolStorage
+{
     /**
      * constructor
      */
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct($aObject);
     }
 
     /**
      * Get file url.
-     * @param $iFileId file 
+     * @param $iFileId file
      * @return file url or false if file was not found
      */
-    public function getFileUrlById($iFileId) {
+    public function getFileUrlById($iFileId)
+    {
         $aFile = $this->_oDb->getFileById($iFileId);
         if (!$aFile)
             return false;
@@ -39,15 +41,15 @@ class BxDolStorageLocal extends BxDolStorage {
         if ($aFile['private']) {
             $sToken = $this->_oDb->genToken($iFileId);
             $sUrl = bx_append_url_params($sUrl, array ('t' => $sToken));
-        }        
+        }
         return $sUrl;
     }
 
     /**
      * Start file fownloading by remote id. If file is private then token is checked.
      */
-    public function download ($sRemoteId, $sToken = false) {
-
+    public function download ($sRemoteId, $sToken = false)
+    {
         $this->setErrorCode(BX_DOL_STORAGE_ERR_OK);
 
         $aFile = $this->_oDb->getFileByRemoteId($sRemoteId);
@@ -59,7 +61,7 @@ class BxDolStorageLocal extends BxDolStorage {
         if ($aFile['private'] && !$this->_oDb->isTokenValid($aFile['id'], $sToken)) {
             $this->setErrorCode(BX_DOL_STORAGE_ERR_PERMISSION_DENIED);
             return false;
-        }        
+        }
         $sFileLocation = $this->getObjectBaseDir($aFile['private']) . $aFile['path'];
         if (!file_exists($sFileLocation)) {
             $this->setErrorCode(BX_DOL_STORAGE_ERR_FILE_NOT_FOUND);
@@ -67,7 +69,7 @@ class BxDolStorageLocal extends BxDolStorage {
         }
 
         header('Content-Type: ' . $aFile['mime_type']);
-        if ($this->_iCacheControl > 0)            
+        if ($this->_iCacheControl > 0)
             header('Cache-Control: max-age=' . ($aFile['private'] && $this->_iCacheControl > $this->_aObject['token_life'] ? $this->_aObject['token_life'] : $this->_iCacheControl));
 
         if (false === readfile($sFileLocation)) {
@@ -78,10 +80,10 @@ class BxDolStorageLocal extends BxDolStorage {
         return true;
     }
 
-    // ----------------    
+    // ----------------
 
-    protected function addFileToEngine($sTmpFile, $sLocalId, $sName, $isPrivate, $iProfileId) {
-        
+    protected function addFileToEngine($sTmpFile, $sLocalId, $sName, $isPrivate, $iProfileId)
+    {
         $sPath = $this->genPath($sLocalId, $this->_aObject['levels']);
         $sNewFileDir = $this->getObjectBaseDir($isPrivate) . $sPath;
         $sNewFilePath = $sNewFileDir . $sLocalId;
@@ -91,7 +93,7 @@ class BxDolStorageLocal extends BxDolStorage {
             $this->setErrorCode(BX_DOL_STORAGE_ERR_FILESYSTEM_PERM);
             return false;
         }
-        
+
         if (!copy($sTmpFile, $sNewFilePath)) {
             $this->setErrorCode(BX_DOL_STORAGE_ERR_ENGINE_ADD);
             return false;
@@ -106,8 +108,8 @@ class BxDolStorageLocal extends BxDolStorage {
         return true;
     }
 
-    protected function deleteFileFromEngine($sFilePath, $isPrivate) { 
-
+    protected function deleteFileFromEngine($sFilePath, $isPrivate)
+    {
         $sFileLocation = $this->getObjectBaseDir($isPrivate) . $sFilePath;
 
         if (!file_exists($sFileLocation))
@@ -121,11 +123,13 @@ class BxDolStorageLocal extends BxDolStorage {
         return true;
     }
 
-    protected function getObjectBaseDir ($isPrivate = false) {
+    protected function getObjectBaseDir ($isPrivate = false)
+    {
         return BX_DIRECTORY_STORAGE . $this->_aObject['object'] . '/';
     }
 
-    protected function getObjectBaseUrl ($isPrivate = false) {
+    protected function getObjectBaseUrl ($isPrivate = false)
+    {
         bx_import('BxDolPermalinks');
         return BX_DOL_URL_ROOT . BxDolPermalinks::getInstance()->permalink('storage.php?o=' . $this->_aObject['object'] . '&f=');
     }
@@ -137,8 +141,7 @@ class BxDolStorageLocal extends BxDolStorage {
 
         $aDirs = explode('/', $sDirName);
         $sDir='';
-        foreach ($aDirs as $sPart)
-        {
+        foreach ($aDirs as $sPart) {
             $sDir .= $sPart.'/';
             if (!is_dir($sDir) && strlen($sDir) > 0 && !file_exists($sDir)) {
                 mkdir($sDir);
@@ -149,4 +152,3 @@ class BxDolStorageLocal extends BxDolStorage {
 }
 
 /** @} */
-

+ 80 - 52
inc/classes/BxDolStorageQuery.php

@@ -13,69 +13,79 @@ bx_import('BxDolDb');
  * Database queries for File storage class.
  * @see BxDolStorage
  */
-class BxDolStorageQuery extends BxDolDb {
+class BxDolStorageQuery extends BxDolDb
+{
     protected $_aObject;
     protected $_sTableFiles;
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
         $this->_sTableFiles = '`' . $aObject['table_files'] . '`';
     }
 
-    static public function getStorageObject ($sObject) {
+    static public function getStorageObject ($sObject)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_storage` WHERE `object` = ?", $sObject);
         return $oDb->getRow($sQuery);
     }
 
-    static public function getStorageObjects () {
+    static public function getStorageObjects ()
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = "SELECT * FROM `sys_objects_storage`";
         return $oDb->getAll($sQuery);
     }
 
-    public function getMimeTypeByExt($sExt) {
+    public function getMimeTypeByExt($sExt)
+    {
         $sQuery = $this->prepare("SELECT `mime_type` FROM `sys_storage_mime_types` WHERE `ext` = ?", $sExt);
         return $this->getOne($sQuery);
     }
 
-    public function getIconByExt($sExt) {
+    public function getIconByExt($sExt)
+    {
         $sQuery = $this->prepare("SELECT `icon` FROM `sys_storage_mime_types` WHERE `ext` = ?", $sExt);
         return $this->getOne($sQuery);
     }
 
-    public function clearAllMimeTypes() {
+    public function clearAllMimeTypes()
+    {
         return $this->query("TRUNCATE TABLE `sys_storage_mime_types`");
     }
 
-    public function addMimeType($sMimeType, $sExt, $sIcon = '') {
+    public function addMimeType($sMimeType, $sExt, $sIcon = '')
+    {
         $sQuery = $this->prepare("INSERT IGNORE INTO `sys_storage_mime_types` SET `ext` = ?, `mime_type` = ?, `icon` = ?", $sExt, $sMimeType, $sIcon);
         return $this->query($sQuery);
     }
 
-    public function getStorageObjectQuota() {
-        return $this->_aObject; 
+    public function getStorageObjectQuota()
+    {
+        return $this->_aObject;
     }
 
-    public function updateStorageObjectQuota($iSize, $iNumber = 1) {
+    public function updateStorageObjectQuota($iSize, $iNumber = 1)
+    {
         $iTime = time();
         $sQuery = $this->prepare("
-            UPDATE `sys_objects_storage` 
-            SET `current_size` = `current_size` + ?, `current_number` = `current_number` + (?), `ts` = ? 
-            WHERE `object` = ?", 
+            UPDATE `sys_objects_storage`
+            SET `current_size` = `current_size` + ?, `current_number` = `current_number` + (?), `ts` = ?
+            WHERE `object` = ?",
             $iSize, $iNumber, $iTime, $this->_aObject['object']
         );
         if ($this->query($sQuery)) {
-            $this->_aObject = $this->getStorageObject($this->_aObject['object']); 
+            $this->_aObject = $this->getStorageObject($this->_aObject['object']);
             return true;
         } else {
             return false;
         }
     }
 
-    public function getUserQuota($iProfileId) {
-        
+    public function getUserQuota($iProfileId)
+    {
         $sQuery = $this->prepare("SELECT `current_size`, `current_number`, 0 as `quota_size`, 0 as `quota_number`, 0 as `max_file_size` FROM `sys_storage_user_quotas` WHERE `profile_id` = ?", $iProfileId);
         $a = $this->getRow($sQuery);
         if (!is_array($a) || !$a)
@@ -96,12 +106,13 @@ class BxDolStorageQuery extends BxDolDb {
         return $a;
     }
 
-    public function updateUserQuota($iProfileId, $iSize, $iNumber = 1) {
+    public function updateUserQuota($iProfileId, $iSize, $iNumber = 1)
+    {
         $iTime = time();
         $sQuery = $this->prepare("
-            INSERT INTO `sys_storage_user_quotas` 
-            SET `profile_id` = ?, `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ? 
-            ON DUPLICATE KEY UPDATE `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ?", 
+            INSERT INTO `sys_storage_user_quotas`
+            SET `profile_id` = ?, `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ?
+            ON DUPLICATE KEY UPDATE `current_size` = `current_size` + ?, `current_number` = `current_number` + ?, `ts` = ?",
             $iProfileId, $iSize, $iNumber, $iTime, $iSize, $iNumber, $iTime
         );
         if ($this->query($sQuery))
@@ -109,20 +120,23 @@ class BxDolStorageQuery extends BxDolDb {
         else
             return false;
     }
-    
-    public function addFile($iProfileId, $sLocalId, $sPath, $aFileName, $sMimeType, $sExt, $iSize, $iTime, $isPrivate) {
-        $sQuery = $this->prepare("INSERT INTO " . $this->_sTableFiles . " SET 
+
+    public function addFile($iProfileId, $sLocalId, $sPath, $aFileName, $sMimeType, $sExt, $iSize, $iTime, $isPrivate)
+    {
+        $sQuery = $this->prepare("INSERT INTO " . $this->_sTableFiles . " SET
             `profile_id` = ?, `remote_id` = ?, `path` = ?, `file_name` = ?, `mime_type` = ?, `ext` = ?, `size` = ?, `added` = ?, `modified` = ?, `private` = ?",
-            $iProfileId, $sLocalId, $sPath, $aFileName, $sMimeType, $sExt, $iSize, $iTime, $iTime, $isPrivate ? 1 : 0 
+            $iProfileId, $sLocalId, $sPath, $aFileName, $sMimeType, $sExt, $iSize, $iTime, $iTime, $isPrivate ? 1 : 0
         );
         return $this->query($sQuery);
     }
-    
-    public function modifyFilePrivate($iFileId, $isPrivate) {
+
+    public function modifyFilePrivate($iFileId, $isPrivate)
+    {
         return $this->modifyCustomField($iFileId, 'private', $isPrivate ? 1 : 0);
     }
 
-    public function modifyCustomField($iFileId, $sField, $sValue, $isUpdateModifiedField = true) {        
+    public function modifyCustomField($iFileId, $sField, $sValue, $isUpdateModifiedField = true)
+    {
         $sAdd = '';
         if ($isUpdateModifiedField) {
             $iTime = time();
@@ -132,8 +146,8 @@ class BxDolStorageQuery extends BxDolDb {
         return $this->query($sQuery);
     }
 
-    public function deleteFile($iFileId) {
-
+    public function deleteFile($iFileId)
+    {
         // delete queued record for the file
         $sQuery = $this->prepare("DELETE FROM `sys_storage_deletions` WHERE `object` = ? AND `file_id` = ?", $this->_aObject['object'], $iFileId);
         $this->query($sQuery);
@@ -150,30 +164,36 @@ class BxDolStorageQuery extends BxDolDb {
         return true;
     }
 
-    public function getFileByFileName($sValue) {
+    public function getFileByFileName($sValue)
+    {
         return $this->_getFileBy('`file_name`', $sValue);
     }
 
-    public function getFileById($sValue) {
+    public function getFileById($sValue)
+    {
         return $this->_getFileBy('`id`', $sValue);
     }
 
-    public function getFileByRemoteId($sValue) {
+    public function getFileByRemoteId($sValue)
+    {
         return $this->_getFileBy('`remote_id`', $sValue);
     }
 
-    protected function _getFileBy($sField, $sValue) {
+    protected function _getFileBy($sField, $sValue)
+    {
         $sQuery = $this->prepare("SELECT * FROM " . $this->_sTableFiles . " WHERE " . $sField . " = ?", $sValue);
         return $this->getRow($sQuery);
     }
 
-    public function isTokenValid($iFileId, $sToken) {
+    public function isTokenValid($iFileId, $sToken)
+    {
         $iTime = time();
         $sQuery = $this->prepare("SELECT `created` FROM `sys_storage_tokens` WHERE `id` = ? AND `object` = ? AND `hash` = ? AND `created` > ?", $iFileId, $this->_aObject['object'], $sToken, $iTime - $this->_aObject['token_life']);
         return $this->getOne($sQuery) ? true : false;
     }
 
-    public function genToken($iFileId) {
+    public function genToken($iFileId)
+    {
         $iTime = time();
         $sToken = md5($iTime . mt_rand() . BX_DOL_SECRET);
         $sQuery = $this->prepare("INSERT INTO `sys_storage_tokens` SET `id` = ?, `object` = ?, `hash` = ?, `created` = ?", $iFileId, $this->_aObject['object'], $sToken, $iTime);
@@ -183,29 +203,31 @@ class BxDolStorageQuery extends BxDolDb {
             return false;
     }
 
-    public function insertGhosts($mixedFileIds, $iProfileId, $iContentId = 0) {
-
+    public function insertGhosts($mixedFileIds, $iProfileId, $iContentId = 0)
+    {
         $iTime = time();
         if (!is_array($mixedFileIds))
             $mixedFileIds = array($mixedFileIds);
-        
+
         $iCount = 0;
         foreach ($mixedFileIds as $iFileId) {
-            $sQuery = $this->prepare("INSERT INTO `sys_storage_ghosts` 
-                SET `id` = ?, `object` = ?, `profile_id` = ?, `content_id` = ?, `created` = ? 
+            $sQuery = $this->prepare("INSERT INTO `sys_storage_ghosts`
+                SET `id` = ?, `object` = ?, `profile_id` = ?, `content_id` = ?, `created` = ?
                 ON DUPLICATE KEY UPDATE `profile_id` = ?, `content_id` = ?, `created` = ?", $iFileId, $this->_aObject['object'], $iProfileId, $iContentId, $iTime, $iProfileId, $iContentId, $iTime);
             $iCount += $this->query($sQuery);
         }
         return $iCount;
     }
 
-    public function updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId) {
+    public function updateGhostsContentId($mixedFileIds, $iProfileId, $iContentId)
+    {
         $sQuery = $this->prepare("UPDATE `sys_storage_ghosts` SET `content_id` = ? WHERE `profile_id` = ? AND `object` = ?", $iContentId, $iProfileId, $this->_aObject['object']);
         $sQuery .= " AND `id` IN (" . $this->implode_escape($mixedFileIds) . ")";
         return $this->res($sQuery);
     }
 
-    public function deleteGhosts($mixedFileIds, $iProfileId, $iContentId = false) {
+    public function deleteGhosts($mixedFileIds, $iProfileId, $iContentId = false)
+    {
         $sQuery = $this->prepare("DELETE FROM `sys_storage_ghosts` WHERE `profile_id` = ? AND `object` = ? AND `id` IN (" . $this->implode_escape($mixedFileIds) . ")", $iProfileId, $this->_aObject['object']);
         if (false !== $iContentId)
             $sQuery .= $this->prepare(" AND `content_id` = ?", $iContentId);
@@ -215,15 +237,17 @@ class BxDolStorageQuery extends BxDolDb {
         return $iCount;
     }
 
-    public function getGhosts($iProfileId, $iContentId = false) {
+    public function getGhosts($iProfileId, $iContentId = false)
+    {
         return $this->getFiles($iProfileId, true, $iContentId);
     }
 
-    public function getFiles($iProfileId, $isGhostsOnly = false, $iContentId = false) {
+    public function getFiles($iProfileId, $isGhostsOnly = false, $iContentId = false)
+    {
         $sJoin = '';
         if ($isGhostsOnly) {
             $sJoin .= $this->prepare(" INNER JOIN `sys_storage_ghosts` AS `g` ON (`f`.`id` = `g`.`id` AND `g`.`profile_id` = ? AND `g`.`object` = ? ", $iProfileId, $this->_aObject['object']);
-            if (false !== $iContentId) 
+            if (false !== $iContentId)
                 $sJoin .= $this->prepare(" AND `g`.`content_id` = ?", $iContentId);
             $sJoin .= ')';
         }
@@ -231,12 +255,14 @@ class BxDolStorageQuery extends BxDolDb {
         return $this->getAll($sQuery);
     }
 
-    public function getFilesAll($iStart, $iPerPage) {
+    public function getFilesAll($iStart, $iPerPage)
+    {
         $sQuery = $this->prepare("SELECT * FROM `" . $this->_sTableFiles . "` LIMIT ?, ?", (int)$iStart, (int)$iPerPage);
         return $this->getAll($sQuery);
     }
 
-    public function prune() {
+    public function prune()
+    {
         $iTime = time();
         $sQuery = $this->prepare("DELETE FROM `sys_storage_tokens` WHERE `object` = ? AND `created` < ?", $this->_aObject['object'], $iTime - $this->_aObject['token_life']);
         $iCount = $this->query($sQuery);
@@ -245,7 +271,8 @@ class BxDolStorageQuery extends BxDolDb {
         return $iCount;
     }
 
-    public function queueFilesForDeletion ($a) {
+    public function queueFilesForDeletion ($a)
+    {
         $iTime = time();
         $iAdded = 0;
         foreach ($a as $iFileId) {
@@ -255,13 +282,15 @@ class BxDolStorageQuery extends BxDolDb {
         return $iAdded;
     }
 
-    public static function getQueuedFilesForDeletion ($iLimit = 1000) {
+    public static function getQueuedFilesForDeletion ($iLimit = 1000)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT `object`, `file_id` FROM `sys_storage_deletions` ORDER BY `requested` ASC LIMIT ?", $iLimit);
         return $oDb->getAll($sQuery);
     }
 
-    public static function isQueuedFilesForDeletion ($sPrefix) {
+    public static function isQueuedFilesForDeletion ($sPrefix)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT COUNT(*) FROM `sys_storage_deletions` WHERE `object` LIKE ?", $sPrefix . '%');
         return $oDb->getOne($sQuery);
@@ -269,4 +298,3 @@ class BxDolStorageQuery extends BxDolDb {
 }
 
 /** @} */
-

+ 34 - 30
inc/classes/BxDolStorageS3.php

@@ -21,8 +21,8 @@ require_once(BX_DIRECTORY_PATH_PLUGINS . 'amazon-s3/S3.php');
  * File storage in Amazon S3.
  * @see BxDolStorage
  */
-class BxDolStorageS3 extends BxDolStorage {
-
+class BxDolStorageS3 extends BxDolStorage
+{
     protected $_s3;
     protected $_sBucket;
     protected $_sDomain;
@@ -32,7 +32,8 @@ class BxDolStorageS3 extends BxDolStorage {
     /**
      * constructor
      */
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct($aObject);
 
         $sAccessKey = getParam('sys_storage_s3_access_key');
@@ -41,16 +42,17 @@ class BxDolStorageS3 extends BxDolStorage {
         $this->_sBucket = getParam('sys_storage_s3_bucket');
         $this->_sDomain = getParam('sys_storage_s3_domain');
 
-        $this->_bSSL = isset($this->_aParams['ssl']) && $this->_aParams['ssl'] ? true : false; 
-        $this->_bReducedRedundancy = isset($this->_aParams['reduced_redundancy']) && $this->_aParams['reduced_redundancy'] ? true : false; 
+        $this->_bSSL = isset($this->_aParams['ssl']) && $this->_aParams['ssl'] ? true : false;
+        $this->_bReducedRedundancy = isset($this->_aParams['reduced_redundancy']) && $this->_aParams['reduced_redundancy'] ? true : false;
     }
 
     /**
      * Get file url.
-     * @param $iFileId file 
+     * @param $iFileId file
      * @return file url
      */
-    public function getFileUrlById($iFileId) {
+    public function getFileUrlById($iFileId)
+    {
         $aFile = $this->_oDb->getFileById($iFileId);
         if (!$aFile)
             return false;
@@ -70,8 +72,8 @@ class BxDolStorageS3 extends BxDolStorage {
     /**
      * Set file private or public.
      */
-    public function setFilePrivate($iFileId, $isPrivate = true) {
-       
+    public function setFilePrivate($iFileId, $isPrivate = true)
+    {
         $aFile = $this->_oDb->getFileById($iFileId);
         $sFileLocation = $this->getObjectBaseDir($aFile['private']) . $aFile['path'];
         if (($aACP = $this->_s3->getAccessControlPolicy($this->_sBucket, $sFileLocation)) === false) {
@@ -83,7 +85,7 @@ class BxDolStorageS3 extends BxDolStorage {
             $this->setErrorCode(BX_DOL_STORAGE_ERR_ENGINE_GET);
             return false;
         }
-         
+
         // check current permissions
         $aNewACP = $aACP;
         unset($aNewACP['acl']);
@@ -107,28 +109,28 @@ class BxDolStorageS3 extends BxDolStorage {
 
         $aGroupAdd = false;
 
-        if ($isPrivate && (!$aGroupPrivate || $aGroupPublic)) { 
-        
+        if ($isPrivate && (!$aGroupPrivate || $aGroupPublic)) {
+
             // make private
-            $aGroupAdd = array ( 
+            $aGroupAdd = array (
                     'type' => 'Group',
                     'uri' => 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers',
                     'permission' => 'READ',
                 );
- 
+
         } elseif (!$isPrivate && ($aGroupPrivate || !$aGroupPublic)) {
- 
+
             // make public
-            $aGroupAdd = array ( 
+            $aGroupAdd = array (
                     'type' => 'Group',
                     'uri' => 'http://acs.amazonaws.com/groups/global/AllUsers',
                     'permission' => 'READ',
                 );
 
-        } 
+        }
 
         // change permission if necessary
-          
+
         if ($aGroupAdd) {
             $aNewACP['acl'][] = $aGroupAdd;
             if (!$this->_s3->setAccessControlPolicy($this->_sBucket, $sFileLocation, $aNewACP)) {
@@ -138,12 +140,12 @@ class BxDolStorageS3 extends BxDolStorage {
         }
 
         return parent::setFilePrivate($iFileId, $isPrivate);
-    } 
-
-    // ----------------    
+    }
 
-    protected function addFileToEngine($sTmpFile, $sLocalId, $sName, $isPrivate, $iProfileId) {
+    // ----------------
 
+    protected function addFileToEngine($sTmpFile, $sLocalId, $sName, $isPrivate, $iProfileId)
+    {
         $sMimeType = $this->getMimeTypeByFileName($sName);
         $sExt = $this->getFileExt($sName);
         $sPath = $this->genPath($sLocalId, $this->_aObject['levels']);
@@ -165,15 +167,15 @@ class BxDolStorageS3 extends BxDolStorage {
         if (!$this->_s3->putObject($aInputFile, $this->_sBucket, $this->getObjectBaseDir($isPrivate) . $sRemoteNamePath, $sACL, $aMetaHeaders, $aRequestHeaders, $sStorageClass)) {
             $this->setErrorCode(BX_DOL_STORAGE_ERR_ENGINE_ADD);
             return false;
-        }               
+        }
 
         return true;
     }
 
-    protected function deleteFileFromEngine($sFilePath, $isPrivate) { 
-
+    protected function deleteFileFromEngine($sFilePath, $isPrivate)
+    {
         $sFileLocation = $this->getObjectBaseDir($isPrivate) . $sFilePath;
-        
+
         if (!$this->_s3->deleteObject($this->_sBucket, $sFileLocation)) {
             $this->setErrorCode(BX_DOL_STORAGE_ERR_UNLINK);
             return false;
@@ -182,19 +184,21 @@ class BxDolStorageS3 extends BxDolStorage {
         return true;
     }
 
-    protected function genRemoteNamePath ($sPath, $sLocalId, $sExt) {
+    protected function genRemoteNamePath ($sPath, $sLocalId, $sExt)
+    {
         return $sPath . $sLocalId . ($sExt ? '.' . $sExt : '');
     }
 
-    protected function getObjectBaseDir ($isPrivate = false) {
+    protected function getObjectBaseDir ($isPrivate = false)
+    {
         return $this->_aObject['object'] . '/';
     }
 
-    protected function getObjectBaseUrl ($isPrivate = false) {
+    protected function getObjectBaseUrl ($isPrivate = false)
+    {
         $sProto = $this->_bSSL ? 'https://' : 'http://';
         return $sProto . $this->_sBucket . '.s3.amazonaws.com/' . $this->getObjectBaseDir($isPrivate);
     }
 }
 
 /** @} */
-

Разница между файлами не показана из-за своего большого размера
+ 246 - 188
inc/classes/BxDolTemplate.php


+ 72 - 55
inc/classes/BxDolUploader.php

@@ -9,15 +9,15 @@
 
 bx_import('BxDolUploaderQuery');
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section uploader Uploader
  * @ref BxDolUploader
  */
 
 /**
  * Uploaders are disigned to work as form field in forms. @see BxDolForm.
- * 
+ *
  *
  * To add file to any form, use the following form field array:
  * @code
@@ -25,29 +25,29 @@ bx_import('BxDolUploaderQuery');
  *     'type' => 'files', // this is new form type, which enable upholders automatically
  *     'storage_object' => 'sample', // the storage object, where uploaded files are going to be saved
  *     'images_transcoder' => 'sample2', // images transcoder object to use for images preview
- *     'uploaders' => array ('sys_simple', 'sys_html5'), // the set of uploaders to use to upload files 
+ *     'uploaders' => array ('sys_simple', 'sys_html5'), // the set of uploaders to use to upload files
  *     'upload_buttons_titles' => array('sys_simple' => 'Upload one by one', 'sys_html5' => 'Upload several files in bulk'); // change default button titles, array with button names, or string to assign to all bnuttons
  *     'multiple' => true, // allow to upload multiple files per one upload
  *     'content_id' => 4321, // content id to associate ghost files with
  *     'ghost_template' => $mixedGhostTemplate, // template for nested form
  *     'name' => 'attachment', // name of file form field, resulted file id is assigned to this field name
- *     'caption' => _t('Attachments'), // form field caption 
- * ), 
+ *     'caption' => _t('Attachments'), // form field caption
+ * ),
  * @endcode
  *
- * 
+ *
  * Available uploaders:
  * - sys_simple - upload files using standard HTML forms.
- * - sys_html5 - upload files using AJAX uploader with multiple files selection support (without flash), 
+ * - sys_html5 - upload files using AJAX uploader with multiple files selection support (without flash),
  *   it works in Firefox and WebKit(Safari, Chrome) browsers only, but has fallback for other browsers (IE, Opera).
  *
- * 
- * Uploaded files are showed as "nested" forms. 
- * You can pass nested form in 'ghost_template' parameter. 
- * If you don't pass anything in 'ghost_template' parameter, then only file id is passed upon form submission. 
+ *
+ * Uploaded files are showed as "nested" forms.
+ * You can pass nested form in 'ghost_template' parameter.
+ * If you don't pass anything in 'ghost_template' parameter, then only file id is passed upon form submission.
  * The nested form can be declared using the different ways:
  *
- * 
+ *
  * 1. Pass template as string - just plain string with HTML, for example:
  *
  * @code
@@ -81,40 +81,41 @@ bx_import('BxDolUploaderQuery');
  *  );
  * @endcode
  *
- * Array is automatically modified to add necessary form attributes to work as nested form, 
+ * Array is automatically modified to add necessary form attributes to work as nested form,
  * file id field is added automatically as hidden input as well.
  *
  *
- * 3. Pass instance of BxDolFormNested class - use BxDolFormNested class or its custom subclass; 
+ * 3. Pass instance of BxDolFormNested class - use BxDolFormNested class or its custom subclass;
  * to create instance use the same form array as in the previous variant, for example:
  *
  * @code
  * bx_import('BxDolFormNested');
  * $oFormNested = new BxDolFormNested('attachment', $aFormNested, 'do_submit');
- * @endcode        
+ * @endcode
  *
  * - 'attachment' is the name of file form field from main form.
  * - $aFormNested is form array from previous example.
  * - 'do_submit' is main form submit_name; field name of submit form input to determine if form is submitted or not.
- * 
+ *
  *
  * All 3 variants can have the following replace markers to substitute with real values:
  * - {file_id} - uploaded file id
  * - {file_name} - uploaded file name with extension
  * - {file_title} - uploaded file name without extension
  * - {file_icon} - URL to file icon automatically determined by file extension
- * - {file_url} - URL to the original file 
+ * - {file_url} - URL to the original file
  * - {js_instance_name} - instance of BxDolUploader javascript class
  *
  */
-abstract class BxDolUploader extends BxDol {
-	protected $_oTemplate;
+abstract class BxDolUploader extends BxDol
+{
+    protected $_oTemplate;
 
     protected $_aObject; ///< object properties
-    protected $_sStorageObject; ///< storage object name    
+    protected $_sStorageObject; ///< storage object name
 
     protected $_sUniqId; ///< uniq id used to generate UploaderJsInstance, ResultContainerId, UploadInProgressContainerId and PopupContainerId
-    protected $_sUploaderJsInstance; ///< uplooader js object instance name    
+    protected $_sUploaderJsInstance; ///< uplooader js object instance name
     protected $_sResultContainerId; ///< uploading/uploaded objects container id
     protected $_sUploadInProgressContainerId; ///< container id where upload in progress element resides
     protected $_sPopupContainerId; ///< popup container id
@@ -126,13 +127,14 @@ abstract class BxDolUploader extends BxDol {
     /**
      * constructor
      */
-    protected function __construct($aObject, $sStorageObject, $sUniqId) {
+    protected function __construct($aObject, $sStorageObject, $sUniqId)
+    {
         parent::__construct();
         $this->_oTemplate = BxDolTemplate::getInstance();
 
         $this->_aObject = $aObject;
-        $this->_sStorageObject = $sStorageObject;          
-     
+        $this->_sStorageObject = $sStorageObject;
+
         $this->_sUniqId = $sUniqId;
 
         $this->_sUploaderJsInstance = 'glUploader_' . $sUniqId . '_' . $this->_aObject['object'];
@@ -140,12 +142,12 @@ abstract class BxDolUploader extends BxDol {
         $this->_sPopupContainerId = 'bx-form-input-files-' . $sUniqId . '-popup-wrapper-' . $this->_aObject['object'];
 
         $this->_sResultContainerId = 'bx-form-input-files-' . $sUniqId . '-upload-result';
-        $this->_sErrorsContainerId = 'bx-form-input-files-' . $sUniqId . '-errors'; 
+        $this->_sErrorsContainerId = 'bx-form-input-files-' . $sUniqId . '-errors';
         $this->_sFormContainerId = 'bx-form-input-files-' . $sUniqId . '-form-cont';
     }
 
-    static public function getObjectInstance($sObject, $sStorageObject, $sResultContainerId) {
-        
+    static public function getObjectInstance($sObject, $sStorageObject, $sResultContainerId)
+    {
         $aObject = BxDolUploaderQuery::getUploaderObject($sObject);
         if (!$aObject || !is_array($aObject) || !$aObject['active'])
             return false;
@@ -153,7 +155,7 @@ abstract class BxDolUploader extends BxDol {
         $sClass = $aObject['override_class_name'];
         if (!empty($aObject['override_class_file']))
             require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
-        else    
+        else
             bx_import($sClass);
 
         $o = new $sClass($aObject, $sStorageObject, $sResultContainerId);
@@ -168,7 +170,8 @@ abstract class BxDolUploader extends BxDol {
      * Is uploader available?
      * @return boolean
      */
-    function isAvailable() {
+    function isAvailable()
+    {
         return $this->_aObject['active'] ? true : false;
     }
 
@@ -176,27 +179,33 @@ abstract class BxDolUploader extends BxDol {
      * Are required php modules installed for this uploader ?
      * @return boolean
      */
-    public function isInstalled() {
+    public function isInstalled()
+    {
         return true;
     }
 
-    public function getNameJsInstanceUploader() {
+    public function getNameJsInstanceUploader()
+    {
         return $this->_sUploaderJsInstance;
     }
 
-    public function getIdContainerResult() {
+    public function getIdContainerResult()
+    {
         return $this->_sResultContainerId;
     }
 
-    public function getIdContainerUploadInProgress() {
+    public function getIdContainerUploadInProgress()
+    {
         return $this->_sUploadInProgressContainerId;
     }
 
-    public function getIdContainerPopup() {
+    public function getIdContainerPopup()
+    {
         return $this->_sPopupContainerId;
     }
 
-    public function getIdContainerErrors() {
+    public function getIdContainerErrors()
+    {
         return $this->_sErrorsContainerId;
     }
 
@@ -205,8 +214,8 @@ abstract class BxDolUploader extends BxDol {
      * @param $mixedFiles as usual $_FILES['some_name'] array, but maybe some other params depending on the uploader
      * @return nothing, but if some files failed to upload, the actual error message can be determined by calling BxDolUploader::getUploadErrorMessages()
      */
-    public function handleUploads ($iProfileId, $mixedFiles, $isMultiple = true, $iContentId = false) {
-
+    public function handleUploads ($iProfileId, $mixedFiles, $isMultiple = true, $iContentId = false)
+    {
         bx_import('BxDolStorage');
         $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
 
@@ -220,7 +229,7 @@ abstract class BxDolUploader extends BxDol {
 
             $iId = $oStorage->storeFileFromForm($aFile, true, $iProfileId, $iContentId);
             if (!$iId)
-                $this->appendUploadErrorMessage(_t('_sys_uploader_err_msg', $aFile['name'], $oStorage->getErrorString())); 
+                $this->appendUploadErrorMessage(_t('_sys_uploader_err_msg', $aFile['name'], $oStorage->getErrorString()));
 
             if (!$isMultiple)
                 break;
@@ -229,7 +238,8 @@ abstract class BxDolUploader extends BxDol {
         echo '<script>window.parent.' . $this->getNameJsInstanceUploader() . '.onUploadCompleted(\'' . bx_js_string($this->getUploadErrorMessages(), BX_ESCAPE_STR_APOS) . '\');</script>';
     }
 
-    public function getUploadErrorMessages ($sFormat = 'HTML') {
+    public function getUploadErrorMessages ($sFormat = 'HTML')
+    {
         if ('HTML' == $sFormat)
             return nl2br($this->_sUploadErrorMessages);
         else
@@ -238,9 +248,10 @@ abstract class BxDolUploader extends BxDol {
 
     /**
      * Show uploader button.
-     * @return HTML string 
+     * @return HTML string
      */
-    public function getUploaderButton($mixedGhostTemplate, $isMultiple = true, $aParams = array()) {
+    public function getUploaderButton($mixedGhostTemplate, $isMultiple = true, $aParams = array())
+    {
         $this->_oTemplate->addCss('uploaders.css');
 
         $this->_oTemplate->addJs('BxDolUploader.js');
@@ -267,7 +278,7 @@ abstract class BxDolUploader extends BxDol {
             'engine' => $this->_aObject['object'],
             'storage_object' => $this->_sStorageObject,
             'uniq_id' => $this->_sUniqId,
-            'template_ghost' => $sJsValue, 
+            'template_ghost' => $sJsValue,
             'multiple' => $isMultiple ? 1 : 0,
         );
         $aParams = array_merge($aParamsDefault, $aParams);
@@ -277,15 +288,17 @@ abstract class BxDolUploader extends BxDol {
     /**
      * Get uploader button title
      */
-    public function getUploaderButtonTitle($mixed = false) {
+    public function getUploaderButtonTitle($mixed = false)
+    {
         // it is overrided in child classes
     }
 
     /**
      * Show uploader form.
-     * @return HTML string 
+     * @return HTML string
      */
-    public function getUploaderForm($isMultiple = true, $iContentId = false) { 
+    public function getUploaderForm($isMultiple = true, $iContentId = false)
+    {
         // it is overrided in child classes
     }
 
@@ -293,7 +306,8 @@ abstract class BxDolUploader extends BxDol {
      * Display uploaded, but not saved files - ghosts
      * @return HTML or JSON string
      */
-    public function getGhosts($iProfileId, $sFormat, $sImagesTranscoder = false, $iContentId = false) {
+    public function getGhosts($iProfileId, $sFormat, $sImagesTranscoder = false, $iContentId = false)
+    {
         bx_import('BxDolStorage');
         $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
 
@@ -328,8 +342,8 @@ abstract class BxDolUploader extends BxDol {
      * Delete file by file id, usually ghost file
      * @return 'ok' string on success or error string on error
      */
-    public function deleteGhost($iFileId, $iProfileId) {
-
+    public function deleteGhost($iFileId, $iProfileId)
+    {
         bx_import('BxDolStorage');
         $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
 
@@ -342,7 +356,7 @@ abstract class BxDolUploader extends BxDol {
 
         if (!$oStorage->deleteFile($iFileId))
             return $oStorage->getErrorString();
-    
+
         return 'ok';
     }
 
@@ -350,8 +364,8 @@ abstract class BxDolUploader extends BxDol {
      * Delete all ghosts files for the specified profile
      * @return number of delete ghost files
      */
-    public function cleanupGhostsForProfile($iProfileId, $iContentId = false) {
-
+    public function cleanupGhostsForProfile($iProfileId, $iContentId = false)
+    {
         $iCount = 0;
 
         bx_import('BxDolStorage');
@@ -364,15 +378,18 @@ abstract class BxDolUploader extends BxDol {
         return $iCount;
     }
 
-    protected function cleanUploadErrorMessages () {
+    protected function cleanUploadErrorMessages ()
+    {
         $this->_sUploadErrorMessages = '';
     }
 
-    protected function appendUploadErrorMessage ($s) {
+    protected function appendUploadErrorMessage ($s)
+    {
         $this->_sUploadErrorMessages .= ($this->_sUploadErrorMessages ? "\n" : '') . $s;
     }
 
-    protected function getRestrictionsText () {
+    protected function getRestrictionsText ()
+    {
         $sTextRestrictions = '';
         bx_import('BxDolStorage');
         $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);

+ 8 - 5
inc/classes/BxDolUploaderQuery.php

@@ -13,21 +13,24 @@ bx_import('BxDolDb');
  * Database queries for uploader objects.
  * @see BxDolUploader
  */
-class BxDolUploaderQuery extends BxDolDb {
+class BxDolUploaderQuery extends BxDolDb
+{
     protected $_aObject;
 
-    public function __construct($aObject) {
+    public function __construct($aObject)
+    {
         parent::__construct();
         $this->_aObject = $aObject;
     }
 
-    static public function getUploaderObject ($sObject) {
+    static public function getUploaderObject ($sObject)
+    {
         $oDb = BxDolDb::getInstance();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_uploader` WHERE `object` = ?", $sObject);
         $aObject = $oDb->getRow($sQuery);
-        if (!$aObject || !is_array($aObject)) 
+        if (!$aObject || !is_array($aObject))
             return false;
-        
+
         return $aObject;
     }
 

+ 33 - 32
inc/classes/BxDolView.php

@@ -12,8 +12,8 @@ bx_import('BxDolViewQuery');
 
 define ('BX_DOL_VIEW_OLD_VIEWS', 3 * 86400); ///< views older than this number of seconds will be deleted automatically
 
-/** 
- * @page objects 
+/**
+ * @page objects
  * @section views Views
  * @ref BxDolView
  */
@@ -22,7 +22,7 @@ define ('BX_DOL_VIEW_OLD_VIEWS', 3 * 86400); ///< views older than this number o
  * Track any object views automatically
  *
  * Add record to sys_object_view table to track object views,
- * to record view just create this class instance with your object id, 
+ * to record view just create this class instance with your object id,
  * for example:
  * @code
  *  BxDolView::getObjectInstance('my_system', 25); // 25 - is object id
@@ -60,23 +60,23 @@ class BxDolView extends BxDolObject
      */
     function __construct($sSystem, $iId, $iInit = true)
     {
-    	parent::__construct($sSystem, $iId, $iInit);
-		if(empty($this->_sSystem))
-			return;
-    	
+        parent::__construct($sSystem, $iId, $iInit);
+        if(empty($this->_sSystem))
+            return;
+
         $this->_oQuery = new BxDolViewQuery($this);
     }
 
    /**
      * get votes object instanse
-     * @param $sSys view object name 
+     * @param $sSys view object name
      * @param $iId associated content id, where vote is available
      * @param $iInit perform initialization
      * @return null on error, or ready to use class instance
      */
-    public static function getObjectInstance($sSys, $iId, $iInit = true) 
+    public static function getObjectInstance($sSys, $iId, $iInit = true)
     {
-    	if(isset($GLOBALS['bxDolClasses']['BxDolView!' . $sSys . $iId]))
+        if(isset($GLOBALS['bxDolClasses']['BxDolView!' . $sSys . $iId]))
             return $GLOBALS['bxDolClasses']['BxDolView!' . $sSys . $iId];
 
         $aSystems = self::getSystems();
@@ -86,8 +86,8 @@ class BxDolView extends BxDolObject
         bx_import('BxTemplView');
         $sClassName = 'BxTemplView';
         if(!empty($aSystems[$sSys]['class_name'])) {
-        	$sClassName = $aSystems[$sSys]['class_name'];
-        	if(!empty($aSystems[$sSys]['class_file']))
+            $sClassName = $aSystems[$sSys]['class_name'];
+            if(!empty($aSystems[$sSys]['class_file']))
                 require_once(BX_DIRECTORY_PATH_ROOT . $aSystems[$sSys]['class_file']);
             else
                 bx_import($sClassName);
@@ -97,11 +97,11 @@ class BxDolView extends BxDolObject
         return ($GLOBALS['bxDolClasses']['BxDolView!' . $sSys . $iId] = $o);
     }
 
-	public static function &getSystems()
+    public static function &getSystems()
     {
         if(!isset($GLOBALS['bx_dol_vote_systems']))
-			$GLOBALS['bx_dol_view_systems'] = BxDolDb::getInstance()->fromCache('sys_objects_view', 'getAllWithKey', '
-        		SELECT
+            $GLOBALS['bx_dol_view_systems'] = BxDolDb::getInstance()->fromCache('sys_objects_view', 'getAllWithKey', '
+                SELECT
                     `id` as `id`,
                     `name` AS `name`,
                     `table_track` AS `table_track`,
@@ -117,37 +117,38 @@ class BxDolView extends BxDolObject
         return $GLOBALS['bx_dol_view_systems'];
     }
 
-	/**
+    /**
      * it is called on cron every day or similar period to clean old votes
      */
-    public static function maintenance() {        
+    public static function maintenance()
+    {
         $iResult = 0;
         $oDb = BxDolDb::getInstance();
 
         $aSystems = self::getSystems();
         foreach($aSystems as $aSystem) {
-			if(!$aSystem['is_on'])
-				continue;
+            if(!$aSystem['is_on'])
+                continue;
 
             $sQuery = $oDb->prepare("DELETE FROM `{$aSystem['table_track']}` WHERE `date` < (UNIX_TIMESTAMP() - ?)", BX_DOL_VIEW_OLD_VIEWS);
             $iDeleted = (int)$oDb->query($sQuery);
             if($iDeleted > 0)
-            	$oDb->query("OPTIMIZE TABLE `{$aSystem['table_track']}`");
+                $oDb->query("OPTIMIZE TABLE `{$aSystem['table_track']}`");
 
-			$iResult += $iDeleted;
+            $iResult += $iDeleted;
         }
 
         return $iResult;
     }
 
-	function doView()
+    function doView()
     {
-        if(!$this->isEnabled()) 
-        	return false;
+        if(!$this->isEnabled())
+            return false;
 
-		$iObjectId = $this->getId();
-		$iAuthorId = $this->_getAuthorId();
-		$sAuthorIp = $this->_getAuthorIp();
+        $iObjectId = $this->getId();
+        $iAuthorId = $this->_getAuthorId();
+        $sAuthorIp = $this->_getAuthorIp();
 
         if($this->_oQuery->doView($iObjectId, $iAuthorId, $sAuthorIp)) {
             $this->_triggerView();
@@ -163,10 +164,10 @@ class BxDolView extends BxDolObject
 
     function onObjectDelete($iObjectId = 0)
     {
-    	$this->_oQuery->deleteObjectViews($iObjectId ? $iObjectId : $this->getId());
+        $this->_oQuery->deleteObjectViews($iObjectId ? $iObjectId : $this->getId());
     }
 
-	protected function _getAuthorId ()
+    protected function _getAuthorId ()
     {
         return isMember() ? bx_get_logged_profile_id() : 0;
     }
@@ -176,10 +177,10 @@ class BxDolView extends BxDolObject
         return getVisitorIP();
     }
 
-	protected function _triggerView()
+    protected function _triggerView()
     {
         if(!$this->_aSystem['trigger_table'])
-			return false;
+            return false;
 
         $iId = $this->getId();
         if(!$iId)
@@ -189,4 +190,4 @@ class BxDolView extends BxDolObject
     }
 }
 
-/** @} */ 
+/** @} */

+ 9 - 8
inc/classes/BxDolViewQuery.php

@@ -14,7 +14,7 @@ bx_import('BxDolDb');
  */
 class BxDolViewQuery extends BxDolDb
 {
-	protected $_oModule;
+    protected $_oModule;
 
     protected $_sTableTrack;
     protected $_sTriggerTable;
@@ -29,7 +29,7 @@ class BxDolViewQuery extends BxDolDb
 
         $this->_oModule = $oModule;
 
-    	$aSystem = $this->_oModule->getSystemInfo();
+        $aSystem = $this->_oModule->getSystemInfo();
         $this->_sTableTrack = $aSystem['table_track'];
         $this->_sTriggerTable = $aSystem['trigger_table'];
         $this->_sTriggerFieldId = $aSystem['trigger_field_id'];
@@ -40,15 +40,15 @@ class BxDolViewQuery extends BxDolDb
 
     public function doView($iObjectId, $iAuthorId, $sAuthorIp)
     {
-    	$iAuthorNip = ip2long($sAuthorIp);
+        $iAuthorNip = ip2long($sAuthorIp);
 
-    	if($iAuthorId)
+        if($iAuthorId)
             $sWhere = $this->prepare(" AND `viewer_id` = ? ", $iAuthorId);
         else
             $sWhere = $this->prepare(" AND `viewer_id` = '0' AND `viewer_nip` = ? ", $iAuthorNip);
 
         $sQuery = $this->prepare("SELECT `date` FROM `{$this->_sTableTrack}` WHERE `object_id` = ? $sWhere", $iObjectId);
-		$iDate = (int)$this->getOne($sQuery);
+        $iDate = (int)$this->getOne($sQuery);
         $iDateNow = time();
 
         if(!$iDate) {
@@ -58,11 +58,11 @@ class BxDolViewQuery extends BxDolDb
 
         if(($iDateNow - $iDate) > $this->_iPeriod) {
             $sQuery = $this->prepare("UPDATE `{$this->_sTableTrack}` SET `date` = ? WHERE `object_id` = ? AND `viewer_id` = ? AND `viewer_nip` = ?", $iDateNow, $iObjectId, $iAuthorId, $iAuthorNip);
-        	return (int)$this->query($sQuery) > 0;
+            return (int)$this->query($sQuery) > 0;
         }
     }
 
-	function deleteObjectViews($iObjectId)
+    function deleteObjectViews($iObjectId)
     {
         $sQuery = $this->prepare("DELETE FROM {$this->_sTableTrack} WHERE `object_id` = ?", $iObjectId);
         $this->query ($sQuery);
@@ -70,7 +70,8 @@ class BxDolViewQuery extends BxDolDb
         $this->query ("OPTIMIZE TABLE {$this->_sTableTrack}");
     }
 
-	public function updateTriggerTable($iObjectId) {
+    public function updateTriggerTable($iObjectId)
+    {
         $sQuery = $this->prepare("UPDATE `{$this->_sTriggerTable}` SET `{$this->_sTriggerFieldCount}` = `{$this->_sTriggerFieldCount}` + 1 WHERE `{$this->_sTriggerFieldId}` = ?", $iObjectId);
         return (int)$this->query($sQuery) > 0;
     }

+ 107 - 106
inc/classes/BxDolVote.php

@@ -19,7 +19,7 @@ define('BX_DOL_VOTE_USAGE_BLOCK', 'block');
 define('BX_DOL_VOTE_USAGE_INLINE', 'inline');
 define('BX_DOL_VOTE_USAGE_DEFAULT', BX_DOL_VOTE_USAGE_BLOCK);
 
-/** 
+/**
  * @page objects
  * @section votes Votes
  * @ref BxDolVote
@@ -44,7 +44,7 @@ define('BX_DOL_VOTE_USAGE_DEFAULT', BX_DOL_VOTE_USAGE_BLOCK);
  * - PostTimeout - number of seconds to not allow duplicate vote
  * - MinValue - min vote value, 1 by default
  * - MaxValue - max vote value, 5 by default
- * - IsUndo - is Undo enabled for Plus based votes 
+ * - IsUndo - is Undo enabled for Plus based votes
  * - IsOn - is this vote object enabled
  * - TriggerTable - table to be updated upon each vote
  * - TriggerFieldId - TriggerTable table field with unique record id, primary key
@@ -58,9 +58,9 @@ define('BX_DOL_VOTE_USAGE_DEFAULT', BX_DOL_VOTE_USAGE_BLOCK);
  *
  *
  * @section example Example of usage:
- * To get Star based vote you need to have different values for MinValue and MaxValue (for example 1 and 5) 
- * and IsUndo should be equal to 0. To get Plus(Like) based vote you need to have equal values 
- * for MinValue and MaxValue (for example 1) and IsUndo should be equal to 1. After filling the other 
+ * To get Star based vote you need to have different values for MinValue and MaxValue (for example 1 and 5)
+ * and IsUndo should be equal to 0. To get Plus(Like) based vote you need to have equal values
+ * for MinValue and MaxValue (for example 1) and IsUndo should be equal to 1. After filling the other
  * paramenters in the table you can show vote in any place, using the following code:
  * @code
  * bx_import('BxDolVote');
@@ -92,21 +92,21 @@ class BxDolVote extends BxDolObject
     {
         parent::__construct($sSystem, $iId, $iInit);
         if(empty($this->_sSystem))
-			return;
+            return;
 
         $this->_oQuery = new BxDolVoteQuery($this);
     }
 
-	/**
+    /**
      * get votes object instanse
-     * @param $sSys vote object name 
+     * @param $sSys vote object name
      * @param $iId associated content id, where vote is available
      * @param $iInit perform initialization
      * @return null on error, or ready to use class instance
      */
-    public static function getObjectInstance($sSys, $iId, $iInit = true) 
+    public static function getObjectInstance($sSys, $iId, $iInit = true)
     {
-    	if(isset($GLOBALS['bxDolClasses']['BxDolVote!' . $sSys . $iId]))
+        if(isset($GLOBALS['bxDolClasses']['BxDolVote!' . $sSys . $iId]))
             return $GLOBALS['bxDolClasses']['BxDolVote!' . $sSys . $iId];
 
         $aSystems = self::getSystems();
@@ -116,8 +116,8 @@ class BxDolVote extends BxDolObject
         bx_import('BxTemplVote');
         $sClassName = 'BxTemplVote';
         if(!empty($aSystems[$sSys]['class_name'])) {
-        	$sClassName = $aSystems[$sSys]['class_name'];
-        	if(!empty($aSystems[$sSys]['class_file']))
+            $sClassName = $aSystems[$sSys]['class_name'];
+            if(!empty($aSystems[$sSys]['class_file']))
                 require_once(BX_DIRECTORY_PATH_ROOT . $aSystems[$sSys]['class_file']);
             else
                 bx_import($sClassName);
@@ -130,8 +130,8 @@ class BxDolVote extends BxDolObject
     public static function &getSystems()
     {
         if(!isset($GLOBALS['bx_dol_vote_systems']))
-			$GLOBALS['bx_dol_vote_systems'] = BxDolDb::getInstance()->fromCache('sys_objects_vote', 'getAllWithKey', '
-        		SELECT
+            $GLOBALS['bx_dol_vote_systems'] = BxDolDb::getInstance()->fromCache('sys_objects_vote', 'getAllWithKey', '
+                SELECT
                     `ID` as `id`,
                     `Name` AS `name`,
                     `TableMain` AS `table_main`,
@@ -152,149 +152,150 @@ class BxDolVote extends BxDolObject
         return $GLOBALS['bx_dol_vote_systems'];
     }
 
-	/**
+    /**
      * it is called on cron every day or similar period to clean old votes
      */
-    public static function maintenance() {        
+    public static function maintenance()
+    {
         $iResult = 0;
         $oDb = BxDolDb::getInstance();
 
         $aSystems = self::getSystems();
         foreach($aSystems as $aSystem) {
-			if(!$aSystem['is_on'])
-				continue;
+            if(!$aSystem['is_on'])
+                continue;
 
             $sQuery = $oDb->prepare("DELETE FROM `{$aSystem['table_track']}` WHERE `date` < (UNIX_TIMESTAMP() - ?)", BX_DOL_VOTE_OLD_VOTES);
             $iDeleted = (int)$oDb->query($sQuery);
             if($iDeleted > 0)
-            	$oDb->query("OPTIMIZE TABLE `{$aSystem['table_track']}`");
+                $oDb->query("OPTIMIZE TABLE `{$aSystem['table_track']}`");
 
-			$iResult += $iDeleted;
+            $iResult += $iDeleted;
         }
 
         return $iResult;
     }
 
-	public function isUndo()
+    public function isUndo()
     {
         return (int)$this->_aSystem['is_undo'] == 1;
     }
 
-	public function isLikeMode()
+    public function isLikeMode()
     {
-    	$bUndo = $this->isUndo();
-    	$iMinValue = $this->getMinValue();
-    	$iMaxValue = $this->getMaxValue();
+        $bUndo = $this->isUndo();
+        $iMinValue = $this->getMinValue();
+        $iMaxValue = $this->getMaxValue();
 
-    	return $iMinValue == $iMaxValue && $bUndo;
+        return $iMinValue == $iMaxValue && $bUndo;
     }
 
-	public function getMinValue()
+    public function getMinValue()
     {
         return (int)$this->_aSystem['min_value'];
     }
 
-	public function getMaxValue()
+    public function getMaxValue()
     {
         return (int)$this->_aSystem['max_value'];
     }
 
-	/**
+    /**
      * Interface functions for outer usage
      */
-	public function getStatCounter()
+    public function getStatCounter()
     {
-    	$aVote = $this->_oQuery->getVote($this->getId());
-    	return $aVote['count'];
+        $aVote = $this->_oQuery->getVote($this->getId());
+        return $aVote['count'];
     }
 
-	public function getStatRate()
+    public function getStatRate()
     {
-    	$aVote = $this->_oQuery->getVote($this->getId());
-    	return $aVote['rate'];
+        $aVote = $this->_oQuery->getVote($this->getId());
+        return $aVote['rate'];
     }
 
-	public function getSqlParts($sMainTable, $sMainField)
+    public function getSqlParts($sMainTable, $sMainField)
     {
         if(!$this->isEnabled())
-        	return array();
+            return array();
 
-		return $this->_oQuery->getSqlParts($sMainTable, $sMainField);
+        return $this->_oQuery->getSqlParts($sMainTable, $sMainField);
     }
 
-
-	/**
+    /**
      * Actions functions
      */
     public function actionVote()
     {
-    	if(!$this->isEnabled()) {
-			$this->_echoResultJson(array('code' => 1));
-        	return;
-		}
+        if(!$this->isEnabled()) {
+            $this->_echoResultJson(array('code' => 1));
+            return;
+        }
 
-		$iObjectId = $this->getId();
-		$iAuthorId = $this->_getAuthorId();
-		$iAuthorIp = $this->_getAuthorIp();
+        $iObjectId = $this->getId();
+        $iAuthorId = $this->_getAuthorId();
+        $iAuthorIp = $this->_getAuthorIp();
 
-		$bUndo = $this->isUndo() && $this->_oQuery->isVoted($iObjectId, $iAuthorId) ? true : false;
+        $bUndo = $this->isUndo() && $this->_oQuery->isVoted($iObjectId, $iAuthorId) ? true : false;
 
-		if(!$bUndo && !$this->isAllowedVote(true)) {
-			$this->_echoResultJson(array('code' => 2, 'msg' => $this->msgErrAllowedVote()));
-        	return;
-		}
+        if(!$bUndo && !$this->isAllowedVote(true)) {
+            $this->_echoResultJson(array('code' => 2, 'msg' => $this->msgErrAllowedVote()));
+            return;
+        }
 
-    	if(!$this->isLikeMode() && !$this->_oQuery->isPostTimeoutEnded($iObjectId, $iAuthorIp)) {
-			$this->_echoResultJson(array('code' => 3, 'msg' => _t('_vote_err_duplicate_vote')));
-        	return;
-		}
+        if(!$this->isLikeMode() && !$this->_oQuery->isPostTimeoutEnded($iObjectId, $iAuthorIp)) {
+            $this->_echoResultJson(array('code' => 3, 'msg' => _t('_vote_err_duplicate_vote')));
+            return;
+        }
 
-    	$iValue = bx_get('value');
-		if($iValue === false) {
-			$this->_echoResultJson(array('code' => 4));
-        	return;
-		}
+        $iValue = bx_get('value');
+        if($iValue === false) {
+            $this->_echoResultJson(array('code' => 4));
+            return;
+        }
 
-    	$iValue = bx_process_input($iValue, BX_DATA_INT);
+        $iValue = bx_process_input($iValue, BX_DATA_INT);
 
-		$iMinValue = $this->getMinValue();
+        $iMinValue = $this->getMinValue();
         if($iValue < $iMinValue)
             $iValue = $iMinValue;
 
-    	$iMaxValue = $this->getMaxValue();
+        $iMaxValue = $this->getMaxValue();
         if($iValue > $iMaxValue)
-			$iValue = $iMaxValue;
+            $iValue = $iMaxValue;
 
-	    if(!$this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $iValue, $bUndo)) {
-	    	$this->_echoResultJson(array('code' => 5));
-        	return;
-	    }
+        if(!$this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $iValue, $bUndo)) {
+            $this->_echoResultJson(array('code' => 5));
+            return;
+        }
 
-		$this->_triggerVote();
+        $this->_triggerVote();
 
-		$oZ = new BxDolAlerts($this->_sSystem, 'rate', $this->getId(), $iAuthorId, array('value' => $iValue, 'undo' => $bUndo));
+        $oZ = new BxDolAlerts($this->_sSystem, 'rate', $this->getId(), $iAuthorId, array('value' => $iValue, 'undo' => $bUndo));
         $oZ->alert();
 
         $aVote = $this->_oQuery->getVote($iObjectId);
         $this->_echoResultJson(array(
-        	'code' => 0, 
-        	'rate' => $aVote['rate'],
-        	'count' => $aVote['count'],
-        	'countf' => (int)$aVote['count'] > 0 ? $this->_getLabelCounter($aVote['count']) : ''
+            'code' => 0,
+            'rate' => $aVote['rate'],
+            'count' => $aVote['count'],
+            'countf' => (int)$aVote['count'] > 0 ? $this->_getLabelCounter($aVote['count']) : ''
         ));
     }
 
-	public function actionGetVotedBy() {
+    public function actionGetVotedBy()
+    {
         if (!$this->isEnabled())
            return '';
 
         return $this->_getVotedBy();
     }
 
-    /** 
+    /**
      * Permissions functions
      */
-	public function checkAction ($sAction, $isPerformAction = false)
+    public function checkAction ($sAction, $isPerformAction = false)
     {
         $iId = $this->_getAuthorId();
         $a = checkActionModule($iId, $sAction, 'system', $isPerformAction);
@@ -308,28 +309,28 @@ class BxDolVote extends BxDolObject
         return $a[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED ? $a[CHECK_ACTION_MESSAGE] : '';
     }
 
-	public function isAllowedVote($isPerformAction = false)
+    public function isAllowedVote($isPerformAction = false)
     {
-    	if(isAdmin())
-    		return true;
+        if(isAdmin())
+            return true;
 
-        return $this->checkAction('vote', $isPerformAction); 
+        return $this->checkAction('vote', $isPerformAction);
     }
 
     public function msgErrAllowedVote()
-    { 
+    {
         return $this->checkActionErrorMsg('vote');
     }
 
     function onObjectDelete($iObjectId = 0)
     {
-    	$this->_oQuery->deleteObjectVotes($iObjectId ? $iObjectId : $this->getId());
+        $this->_oQuery->deleteObjectVotes($iObjectId ? $iObjectId : $this->getId());
     }
 
-    /** 
+    /**
      * Internal functions
      */
-	protected function _getAuthorId ()
+    protected function _getAuthorId ()
     {
         return isMember() ? bx_get_logged_profile_id() : 0;
     }
@@ -339,34 +340,34 @@ class BxDolVote extends BxDolObject
         return getVisitorIP();
     }
 
-	protected function _getAuthorInfo($iAuthorId = 0)
+    protected function _getAuthorInfo($iAuthorId = 0)
     {
-    	$oProfile = $this->_getAuthorObject($iAuthorId);
-
-		return array(
-			$oProfile->getDisplayName(), 
-			$oProfile->getUrl(), 
-			$oProfile->getThumb(),
-			$oProfile->getUnit()
-		);
+        $oProfile = $this->_getAuthorObject($iAuthorId);
+
+        return array(
+            $oProfile->getDisplayName(),
+            $oProfile->getUrl(),
+            $oProfile->getThumb(),
+            $oProfile->getUnit()
+        );
     }
 
-	protected function _getAuthorObject($iAuthorId = 0)
+    protected function _getAuthorObject($iAuthorId = 0)
     {
-    	bx_import('BxDolProfile');
-		$oProfile = BxDolProfile::getInstance($iAuthorId);
-		if (!$oProfile) {
-			bx_import('BxDolProfileUndefined');
-			$oProfile = BxDolProfileUndefined::getInstance();
-		}
-
-		return $oProfile;
+        bx_import('BxDolProfile');
+        $oProfile = BxDolProfile::getInstance($iAuthorId);
+        if (!$oProfile) {
+            bx_import('BxDolProfileUndefined');
+            $oProfile = BxDolProfileUndefined::getInstance();
+        }
+
+        return $oProfile;
     }
 
-	protected function _triggerVote()
+    protected function _triggerVote()
     {
         if(!$this->_aSystem['trigger_table'])
-			return false;
+            return false;
 
         $iId = $this->getId();
         if(!$iId)

+ 38 - 38
inc/classes/BxDolVoteQuery.php

@@ -14,7 +14,7 @@ bx_import('BxDolDb');
  */
 class BxDolVoteQuery extends BxDolDb
 {
-	protected $_oModule;
+    protected $_oModule;
 
     protected $_sTable;
     protected $_sTableTrack;
@@ -25,14 +25,13 @@ class BxDolVoteQuery extends BxDolDb
 
     protected $_iPostTimeout;
 
-
     public function __construct(&$oModule)
     {
         parent::__construct();
 
         $this->_oModule = $oModule;
 
-    	$aSystem = $this->_oModule->getSystemInfo();
+        $aSystem = $this->_oModule->getSystemInfo();
         $this->_sTable = $aSystem['table_main'];
         $this->_sTableTrack = $aSystem['table_track'];
         $this->_sTriggerTable = $aSystem['trigger_table'];
@@ -43,55 +42,55 @@ class BxDolVoteQuery extends BxDolDb
         $this->_iPostTimeout = (int)$aSystem['post_timeout'];
     }
 
-	public function isPostTimeoutEnded($iObjectId, $sAuthorIp)
+    public function isPostTimeoutEnded($iObjectId, $sAuthorIp)
     {
-    	if($this->_iPostTimeout == 0) 
-    		return true;
+        if($this->_iPostTimeout == 0)
+            return true;
 
-		$iDate = time() - $this->_iPostTimeout;
-		$iAuthorNip = ip2long($sAuthorIp);
-		$sQuery = $this->prepare("SELECT `object_id` FROM `{$this->_sTableTrack}` WHERE `object_id` = ? AND `author_nip` = ? AND `date` > ?", $iObjectId, $iAuthorNip, $iDate);
-		return (int)$this->getOne($sQuery) == 0;
+        $iDate = time() - $this->_iPostTimeout;
+        $iAuthorNip = ip2long($sAuthorIp);
+        $sQuery = $this->prepare("SELECT `object_id` FROM `{$this->_sTableTrack}` WHERE `object_id` = ? AND `author_nip` = ? AND `date` > ?", $iObjectId, $iAuthorNip, $iDate);
+        return (int)$this->getOne($sQuery) == 0;
     }
 
-	public function getVote($iObjectId)
+    public function getVote($iObjectId)
     {
         $sQuery = $this->prepare("SELECT `count` as `count`, `sum` as `sum`, ROUND(`sum` / `count`, 2) AS `rate` FROM {$this->_sTable} WHERE `object_id` = ? LIMIT 1", $iObjectId);
 
         $aResult = $this->getRow($sQuery);
-		if(empty($aResult) || !is_array($aResult))
-			$aResult = array('count' => 0, 'sum' => 0, 'rate' => 0);
+        if(empty($aResult) || !is_array($aResult))
+            $aResult = array('count' => 0, 'sum' => 0, 'rate' => 0);
 
-		return $aResult;
+        return $aResult;
     }
 
     public function isVoted($iObjectId, $iAuthorId)
     {
-		$sQuery = $this->prepare("SELECT `object_id` FROM `{$this->_sTableTrack}` WHERE `object_id` = ? AND `author_id` = ? LIMIT 1", $iObjectId, $iAuthorId);
-		return (int)$this->getOne($sQuery) != 0;
+        $sQuery = $this->prepare("SELECT `object_id` FROM `{$this->_sTableTrack}` WHERE `object_id` = ? AND `author_id` = ? LIMIT 1", $iObjectId, $iAuthorId);
+        return (int)$this->getOne($sQuery) != 0;
     }
 
-	public function putVote($iObjectId, $iAuthorId, $sAuthorIp, $iValue, $bUndo = false)
+    public function putVote($iObjectId, $iAuthorId, $sAuthorIp, $iValue, $bUndo = false)
     {
-    	$sQuery = $this->prepare("SELECT `object_id` FROM `{$this->_sTable}` WHERE `object_id` = ? LIMIT 1", $iObjectId);
+        $sQuery = $this->prepare("SELECT `object_id` FROM `{$this->_sTable}` WHERE `object_id` = ? LIMIT 1", $iObjectId);
         $bExists = (int)$this->getOne($sQuery) != 0;
         if(!$bExists && $bUndo)
-        	return false;
+            return false;
 
         if(!$bExists)
-			$sQuery = $this->prepare("INSERT INTO {$this->_sTable} SET `object_id` = ?, `count` = '1', `sum` = ?", $iObjectId, $iValue);
-        else 
-        	$sQuery = $this->prepare("UPDATE `{$this->_sTable}` SET `count` = `count` " . ($bUndo ? "-" : "+") . " 1, `sum` = `sum` " . ($bUndo ? "-" : "+") . " ? WHERE `object_id` = ?", $iValue, $iObjectId);
+            $sQuery = $this->prepare("INSERT INTO {$this->_sTable} SET `object_id` = ?, `count` = '1', `sum` = ?", $iObjectId, $iValue);
+        else
+            $sQuery = $this->prepare("UPDATE `{$this->_sTable}` SET `count` = `count` " . ($bUndo ? "-" : "+") . " 1, `sum` = `sum` " . ($bUndo ? "-" : "+") . " ? WHERE `object_id` = ?", $iValue, $iObjectId);
 
-        if((int)$this->query($sQuery) == 0) 
-        	return false;
+        if((int)$this->query($sQuery) == 0)
+            return false;
 
         if($bUndo)
-        	$sQuery = $this->prepare("DELETE FROM `{$this->_sTableTrack}` WHERE `object_id` = ? AND `author_id` = ? LIMIT 1", $iObjectId, $iAuthorId);
+            $sQuery = $this->prepare("DELETE FROM `{$this->_sTableTrack}` WHERE `object_id` = ? AND `author_id` = ? LIMIT 1", $iObjectId, $iAuthorId);
         else {
-        	$iNow = time();
-        	$iAuthorNip = ip2long($sAuthorIp);
-        	$sQuery = $this->prepare("INSERT INTO `{$this->_sTableTrack}` SET `object_id` = ?, `author_id` = ?, `author_nip` = ?, `value` = ?, `date` = ?", $iObjectId, $iAuthorId, $iAuthorNip, $iValue, $iNow);
+            $iNow = time();
+            $iAuthorNip = ip2long($sAuthorIp);
+            $sQuery = $this->prepare("INSERT INTO `{$this->_sTableTrack}` SET `object_id` = ?, `author_id` = ?, `author_nip` = ?, `value` = ?, `date` = ?", $iObjectId, $iAuthorId, $iAuthorNip, $iValue, $iNow);
         }
 
         return (int)$this->query($sQuery) > 0;
@@ -99,8 +98,8 @@ class BxDolVoteQuery extends BxDolDb
 
     public function getSqlParts($sMainTable, $sMainField)
     {
-    	if(empty($sMainTable) || empty($sMainField))
-			return array();
+        if(empty($sMainTable) || empty($sMainField))
+            return array();
 
         return array (
             'fields' => ",`{$this->_sTable}`.`count` as `vote_count`, (`{$this->_sTable}`.`sum` / `{$this->_sTable}`.`count`) AS `vote_rate` ",
@@ -110,13 +109,13 @@ class BxDolVoteQuery extends BxDolDb
 
     public function getVotedBy($iObjectId)
     {
-    	$sQuery = $this->prepare("SELECT `author_id` FROM `{$this->_sTableTrack}` WHERE `object_id`=?", $iObjectId);
-    	return $this->getColumn($sQuery);
+        $sQuery = $this->prepare("SELECT `author_id` FROM `{$this->_sTableTrack}` WHERE `object_id`=?", $iObjectId);
+        return $this->getColumn($sQuery);
     }
 
-	public function deleteObjectVotes($iObjectId)
+    public function deleteObjectVotes($iObjectId)
     {
-    	$sQuery = $this->prepare("DELETE FROM {$this->_sTable} WHERE `object_id` = ?", $iObjectId);
+        $sQuery = $this->prepare("DELETE FROM {$this->_sTable} WHERE `object_id` = ?", $iObjectId);
         $this->query ($sQuery);
 
         $this->query ("OPTIMIZE TABLE {$this->_sTable}");
@@ -127,10 +126,11 @@ class BxDolVoteQuery extends BxDolDb
         $this->query ("OPTIMIZE TABLE {$this->_sTableTrack}");
     }
 
-	public function updateTriggerTable($iObjectId) {
-		$aVote = $this->getVote($iObjectId);
-		if(empty($aVote) || !is_array($aVote))
-			return false;
+    public function updateTriggerTable($iObjectId)
+    {
+        $aVote = $this->getVote($iObjectId);
+        if(empty($aVote) || !is_array($aVote))
+            return false;
 
         $sQuery = $this->prepare("UPDATE `{$this->_sTriggerTable}` SET `{$this->_sTriggerFieldCount}` = ?, `{$this->_sTriggerFieldRate}` = ? WHERE `{$this->_sTriggerFieldId}` = ?", $aVote['count'], $aVote['rate'], $iObjectId);
         return (int)$this->query($sQuery) > 0;

+ 24 - 15
inc/classes/BxDolXmlParser.php

@@ -9,10 +9,12 @@
 
 bx_import('BxDol');
 
-class BxDolXmlParser extends BxDol implements iBxDolSingleton {
+class BxDolXmlParser extends BxDol implements iBxDolSingleton
+{
     protected $rParser;
 
-    function __construct() {
+    function __construct()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
 
@@ -22,7 +24,8 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
     /**
      * Prevent cloning the instance
      */
-    public function __clone() {
+    public function __clone()
+    {
         if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
             trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
     }
@@ -30,7 +33,8 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
     /**
      * Get singleton instance of the class
      */
-    public static function getInstance() {
+    public static function getInstance()
+    {
         if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolXmlParser();
 
@@ -40,7 +44,8 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
     /**
      * Get the value of specified attribute for specified tag.
      */
-    function getAttribute($sXmlContent, $sXmlTag, $sXmlAttribute) {
+    function getAttribute($sXmlContent, $sXmlTag, $sXmlAttribute)
+    {
         $aValues = $aIndexes = array();
         $rParser = xml_parser_create("UTF-8");
         xml_parse_into_struct($rParser, $sXmlContent, $aValues, $aIndexes);
@@ -53,7 +58,8 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
     /**
      * Get an array of attributes for specified tag or an array of tags with the same name.
      */
-    function getAttributes($sXmlContent, $sXmlTagName, $sXmlTagIndex = -1) {
+    function getAttributes($sXmlContent, $sXmlTagName, $sXmlTagIndex = -1)
+    {
         $aValues = $aIndexes = array();
         $rParser = xml_parser_create("UTF-8");
         xml_parse_into_struct($rParser, $sXmlContent, $aValues, $aIndexes);
@@ -70,8 +76,7 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
             foreach($aTagIndexes as $iTagIndex)
                 $aResult[] = $aValues[$iTagIndex]['attributes'];
             return $aResult;
-        }
-        else {
+        } else {
             $iTagIndex = $aIndexes[strtoupper($sXmlTagName)][$sXmlTagIndex];
             return $aValues[$iTagIndex]['attributes'];
         }
@@ -80,7 +85,8 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
     /**
      * Get an array of tags or one tag if its index is specified.
      */
-    function getTags($sXmlContent, $sXmlTagName, $iXmlTagIndex = -1) {
+    function getTags($sXmlContent, $sXmlTagName, $iXmlTagIndex = -1)
+    {
         $aValues = $aIndexes = array();
         $rParser = xml_parser_create("UTF-8");
         xml_parse_into_struct($rParser, $sXmlContent, $aValues, $aIndexes);
@@ -94,8 +100,7 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
             foreach($aTagIndexes as $iTagIndex)
                 $aResult[] = $aValues[$iTagIndex];
             return $aResult;
-        }
-        else {
+        } else {
             $iTagIndex = $aIndexes[strtoupper($sXmlTagName)][$iXmlTagIndex];
             return $aValues[$iTagIndex];
         }
@@ -104,7 +109,8 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
     /**
      * Gets the values of the given tag.
      */
-    function getValues($sXmlContent, $sXmlTagName) {
+    function getValues($sXmlContent, $sXmlTagName)
+    {
         $aValues = $aIndexes = array();
         $rParser = xml_parser_create("UTF-8");
         xml_parse_into_struct($rParser, $sXmlContent, $aValues, $aIndexes);
@@ -123,7 +129,8 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
     /**
      * Sets the values of tag where attribute "key" equals to specified.
      */
-    function setValues($sXmlContent, $sXmlTagName, $aKeyValues) {
+    function setValues($sXmlContent, $sXmlTagName, $aKeyValues)
+    {
         $aValues = $aIndexes = array();
         $rParser = xml_parser_create("UTF-8");
         xml_parse_into_struct($rParser, $sXmlContent, $aValues, $aIndexes);
@@ -143,7 +150,8 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
     /**
      * Adds given values to XML content.
      */
-    function addValues($sXmlContent, $sXmlTagName, $aKeyValues) {
+    function addValues($sXmlContent, $sXmlTagName, $aKeyValues)
+    {
         $aValues = $aIndexes = array();
         $rParser = xml_parser_create("UTF-8");
         xml_parse_into_struct($rParser, $sXmlContent, $aValues, $aIndexes);
@@ -168,7 +176,8 @@ class BxDolXmlParser extends BxDol implements iBxDolSingleton {
     /**
      * get content in XML format from given values array
      */
-    function getContent($aValues = array()) {
+    function getContent($aValues = array())
+    {
         $sContent = "";
         foreach($aValues as $aValue) {
             $sTagName = strtolower($aValue['tag']);

+ 17 - 13
inc/design.inc.php

@@ -50,12 +50,10 @@ define('BX_DB_PADDING_DEF', 11);
  */
 define('BX_DB_PADDING_NO_CAPTION', 13);
 
-
 define('BX_FORMAT_DATE', 'sys_format_date'); ///< date format identifier for use in @see bx_time_js function
 define('BX_FORMAT_TIME', 'sys_format_time'); ///< time format identifier for use in @see bx_time_js function
 define('BX_FORMAT_DATE_TIME', 'sys_format_datetime'); ///< datetime format identifier for use in @see bx_time_js function
 
-
 /**
  * Display "design box" HTML code
  *
@@ -69,7 +67,8 @@ define('BX_FORMAT_DATE_TIME', 'sys_format_datetime'); ///< datetime format ident
  * @see BX_DB_PADDING_DEF
  * @see BX_DB_PADDING_NO_CAPTION
  */
-function DesignBoxContent ($sTitle, $sContent, $iTemplateNum = BX_DB_DEF, $mixedMenu = false) {
+function DesignBoxContent ($sTitle, $sContent, $iTemplateNum = BX_DB_DEF, $mixedMenu = false)
+{
     bx_import('BxTemplFunctions');
     return BxTemplFunctions::getInstance()->designBoxContent ($sTitle, $sContent, $iTemplateNum, $mixedMenu);
 }
@@ -77,7 +76,8 @@ function DesignBoxContent ($sTitle, $sContent, $iTemplateNum = BX_DB_DEF, $mixed
 /**
  * Use this function in pages if you want to not cache it.
  **/
-function send_headers_page_changed() {
+function send_headers_page_changed()
+{
     $now = gmdate('D, d M Y H:i:s') . ' GMT';
 
     header("Expires: $now");
@@ -86,17 +86,20 @@ function send_headers_page_changed() {
     header("Pragma: no-cache");
 }
 
-function MsgBox($sText, $iTimer = 0) {
+function MsgBox($sText, $iTimer = 0)
+{
     bx_import('BxTemplFunctions');
     return BxTemplFunctions::getInstance()->msgBox($sText, $iTimer);
 }
 
-function PopupBox($sName, $sTitle, $sContent, $isHiddenByDefault = false) {
+function PopupBox($sName, $sTitle, $sContent, $isHiddenByDefault = false)
+{
     bx_import('BxTemplFunctions');
     return BxTemplFunctions::getInstance()->popupBox($sName, $sTitle, $sContent, $isHiddenByDefault);
 }
 
-function getVersionComment() {
+function getVersionComment()
+{
     $aVer = explode('.', getParam('sys_version'));
 
     // version output made for debug possibilities.
@@ -110,7 +113,7 @@ function getVersionComment() {
     return '<!-- ' . implode(' ', $aVerR) . ' -->';
 }
 
-function getSiteStatUser() 
+function getSiteStatUser()
 {
     $sqlQuery = "SELECT `Name` as `name`, `Title` as `capt`, `UserQuery` as `query`, `UserLink` as `link`, `IconName` as `icon`, `AdminQuery` as `adm_query`, `AdminLink` as `adm_link` FROM `sys_stat_site` ORDER BY `StatOrder`";
 
@@ -126,7 +129,7 @@ function getSiteStatUser()
  *
  * This is just short version for:
  * @see BxTemplFunctions::timeForJs
- * 
+ *
  * @param $iUnixTimestamp time as unixtimestamp
  * @param $sFormatIdentifier output format identifier
  *     @see BX_FORMAT_DATE
@@ -134,7 +137,8 @@ function getSiteStatUser()
  *     @see BX_FORMAT_DATE_TIME
  * @param $bForceFormat force provided format and don't use "from now" time autoformat.
  */
-function bx_time_js ($iUnixTimestamp, $sFormatIdentifier = BX_FORMAT_DATE, $bForceFormat = false) {
+function bx_time_js ($iUnixTimestamp, $sFormatIdentifier = BX_FORMAT_DATE, $bForceFormat = false)
+{
     bx_import('BxTemplFunctions');
     return BxTemplFunctions::getInstance()->timeForJs ($iUnixTimestamp, $sFormatIdentifier, $bForceFormat);
 }
@@ -144,7 +148,8 @@ function bx_time_js ($iUnixTimestamp, $sFormatIdentifier = BX_FORMAT_DATE, $bFor
  * @param $iUnixTimestamp - unix timestamp
  * @return ISO8601 formatted date/time string
  */
-function bx_time_utc ($iUnixTimestamp) {
+function bx_time_utc ($iUnixTimestamp)
+{
     return gmdate(DATE_ISO8601, (int)$iUnixTimestamp);
 }
 
@@ -152,5 +157,4 @@ bx_import('BxDolAlerts');
 $oZ = new BxDolAlerts('system', 'design_included', 0);
 $oZ->alert();
 
-/** @} */ 
-
+/** @} */

+ 25 - 28
inc/profiles.inc.php

@@ -10,7 +10,7 @@
 /**
  * @return corrently logged in profile id
  */
-function bx_get_logged_profile_id () 
+function bx_get_logged_profile_id ()
 {
     bx_import('BxDolProfile');
     $o = BxDolProfile::getInstance();
@@ -20,7 +20,7 @@ function bx_get_logged_profile_id ()
 /**
  * @return true if user is logged in
  */
-function isLogged() 
+function isLogged()
 {
     return getLoggedId() != 0;
 }
@@ -28,7 +28,7 @@ function isLogged()
 /**
  * @return logged in account id
  */
-function getLoggedId() 
+function getLoggedId()
 {
     return isset($_COOKIE['memberID']) && (!empty($GLOBALS['logged']['member']) || !empty($GLOBALS['logged']['admin'])) ? (int)$_COOKIE['memberID'] : 0;
 }
@@ -36,7 +36,7 @@ function getLoggedId()
 /**
  * @return logged in account password
  */
-function getLoggedPassword() 
+function getLoggedPassword()
 {
     return isset($_COOKIE['memberPassword']) && ($GLOBALS['logged']['member'] || $GLOBALS['logged']['admin']) ? $_COOKIE['memberPassword'] : '';
 }
@@ -44,7 +44,7 @@ function getLoggedPassword()
 /**
  * It checks if account role is member.
  */
-function isMember($iId = 0) 
+function isMember($iId = 0)
 {
     return isRole(BX_DOL_ROLE_MEMBER, $iId);
 }
@@ -53,7 +53,7 @@ if (!function_exists("isAdmin")) {
     /**
      * @return true if account is admin
      */
-    function isAdmin($iId = 0) 
+    function isAdmin($iId = 0)
     {
         if (!$iId && isset($GLOBALS['logged']['admin']) && $GLOBALS['logged']['admin']) // easier check for currently logged in user
             return true;
@@ -67,7 +67,7 @@ if (!function_exists("isAdmin")) {
  * @param $iId optional account id, if it isn't specified then curently logged in account is used
  * @return true if user is in the provided role
  */
-function isRole($iRole, $iId = 0) 
+function isRole($iRole, $iId = 0)
 {
     if (!(int)$iId)
         $iId = getLoggedId();
@@ -93,7 +93,7 @@ function isRole($iRole, $iId = 0)
  * @param $iId account id
  * @return false if id isn't correct or array of user info if user was logged in
  */
-function bx_login($iId, $bRememberMe = false) 
+function bx_login($iId, $bRememberMe = false)
 {
     bx_import('BxDolAccountQuery');
     $oAccountQuery = BxDolAccountQuery::getInstance();
@@ -112,7 +112,7 @@ function bx_login($iId, $bRememberMe = false)
     $_COOKIE['memberPassword'] = $sPassword;
 
     bx_import('BxDolSession');
-	BxDolSession::getInstance()->setUserId($iId);
+    BxDolSession::getInstance()->setUserId($iId);
 
     $oAccountQuery->updateLoggedIn($iId);
 
@@ -124,7 +124,7 @@ function bx_login($iId, $bRememberMe = false)
 /**
  * Logout user by removing cookies
  */
-function bx_logout($bNotify = true) 
+function bx_logout($bNotify = true)
 {
     if ($bNotify && isMember())
         bx_alert('account', 'logout', (int)$_COOKIE['memberID']);
@@ -139,13 +139,13 @@ function bx_logout($bNotify = true)
     unset($_COOKIE['memberPassword']);
 
     bx_import('BxDolSession');
-	BxDolSession::getInstance()->destroy();
+    BxDolSession::getInstance()->destroy();
 }
 
 /**
  * Check if user is logged in (necessary cookies are present) and set some global variables
  */
-function check_logged() 
+function check_logged()
 {
     $aAccTypes = array(
        BX_DOL_ROLE_ADMIN => 'admin',
@@ -162,26 +162,25 @@ function check_logged()
             break;
         }
     }
-    
+
     if ((isset($_COOKIE['memberID']) || isset($_COOKIE['memberPassword'])) && !$bLogged)
         bx_logout(false);
 }
 
-
 /**
  * Check unencrypted password
  * @return empty string on success or error string on error
  */
-function bx_check_password($sLogin, $sPassword, $iRole = BX_DOL_ROLE_MEMBER) 
+function bx_check_password($sLogin, $sPassword, $iRole = BX_DOL_ROLE_MEMBER)
 {
     bx_import('BxDolAccount');
-    $oAccount = BxDolAccount::getInstance($sLogin);        
+    $oAccount = BxDolAccount::getInstance($sLogin);
     if (!$oAccount) {
         bx_import('BxDolLanguages');
         return _t("_sys_txt_login_error");
     }
 
-    $aAccountInfo = $oAccount->getInfo();        
+    $aAccountInfo = $oAccount->getInfo();
 
     $sPassCheck = encryptUserPwd($sPassword, $aAccountInfo['salt']);
 
@@ -197,19 +196,18 @@ function bx_check_password($sLogin, $sPassword, $iRole = BX_DOL_ROLE_MEMBER)
     return $sErrorMsg;
 }
 
-
 /**
  * Check encrypted password (ex., from Cookie)
  * @return empty string on success or error string on error
  */
-function bx_check_login($iID, $sPassword, $iRole = BX_DOL_ROLE_MEMBER) 
+function bx_check_login($iID, $sPassword, $iRole = BX_DOL_ROLE_MEMBER)
 {
     bx_import('BxDolAccount');
     $oAccount = BxDolAccount::getInstance((int)$iID);
 
     // If no such account available
-    if (!$oAccount) { 
-        bx_import('BxDolLanguages');       
+    if (!$oAccount) {
+        bx_import('BxDolLanguages');
         return _t("_sys_txt_login_error");
     }
 
@@ -234,7 +232,7 @@ function bx_check_login($iID, $sPassword, $iRole = BX_DOL_ROLE_MEMBER)
  * Declare that content is require user authoriztion and display login form if user isn't logged in
  * @param $bStudio require webmaster authorization
  */
-function bx_require_authentication ($bStudio = false) 
+function bx_require_authentication ($bStudio = false)
 {
     $iRole = BX_DOL_ROLE_MEMBER;
     if ($bStudio)
@@ -242,10 +240,10 @@ function bx_require_authentication ($bStudio = false)
 
     $sID = isset($_COOKIE['memberID']) ? bx_process_input($_COOKIE['memberID']) : false;
     $sPassword = isset($_COOKIE['memberPassword']) ? bx_process_input($_COOKIE['memberPassword']) : false;
-    
+
     if (bx_check_login($sID, $sPassword, $iRole)) {
         bx_login_form($bStudio);
-    }   
+    }
 
     check_logged();
 }
@@ -257,13 +255,13 @@ function bx_require_authentication ($bStudio = false)
  * @param $bStudio display login form for studio
  * @param $bAjaxMode login form displayed via AJAX
  */
-function bx_login_form($bStudio = false, $bAjaxMode = false) 
+function bx_login_form($bStudio = false, $bAjaxMode = false)
 {
     if ($bStudio == 1) {
         bx_import("BxTemplStudioFunctions");
         BxTemplStudioFunctions::getInstance()->getLoginForm();
         exit;
-    }    
+    }
 
     $sFormCode = BxDolService::call('system', 'login_form', array(), 'TemplServiceLogin');
 
@@ -282,5 +280,4 @@ function bx_login_form($bStudio = false, $bAjaxMode = false)
 
 check_logged();
 
-/** @} */ 
-
+/** @} */

+ 134 - 98
inc/utils.inc.php

@@ -34,14 +34,16 @@ define('BX_EMAIL_MASS', 2); ///< mass email, one mesage send to manu users, with
  * The following two functions are needed to convert title to uri and back.
  * It usefull when titles are used in URLs, like in Categories and Tags.
  */
-function title2uri($sValue) {
+function title2uri($sValue)
+{
     return str_replace(
         array('&', '/', '\\', '"', '+'),
         array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
         $sValue
     );
 }
-function uri2title($sValue) {
+function uri2title($sValue)
+{
     return str_replace(
         array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
         array('&', '/', '\\', '"', '+'),
@@ -52,7 +54,8 @@ function uri2title($sValue) {
 /*
  * functions for limiting maximal text length
  */
-function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;') {
+function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;')
+{
     $sTail = '';
     $s = trim(strip_tags($sInput));
     if (mb_strlen($s) > $iMaxLen) {
@@ -62,7 +65,8 @@ function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;') {
     return htmlspecialchars_adv($s) . $sTail;
 }
 
-function html2txt($content, $tags = "") {
+function html2txt($content, $tags = "")
+{
     while($content != strip_tags($content, $tags)) {
         $content = strip_tags($content, $tags);
     }
@@ -70,7 +74,8 @@ function html2txt($content, $tags = "") {
     return $content;
 }
 
-function html_encode($text) {
+function html_encode($text)
+{
      $searcharray =  array(
     "'([-_\w\d.]+@[-_\w\d.]+)'",
     "'((?:(?!://).{3}|^.{0,2}))(www\.[-\d\w\.\/]+)'",
@@ -102,8 +107,8 @@ function html_encode($text) {
  * @param $mixedParams optional parameters to pass for validation
  * @return the filtered data, or FALSE if the filter fails.
  */
-function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
-
+function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
+{
     if (is_array($mixedData)) {
         foreach ($mixedData as $k => $v)
             $mixedData[$k] = bx_process_input($v, $iDataType, $mixedParams);
@@ -171,8 +176,8 @@ function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams =
  * @param $mixedParams optional parameters to pass for validation
  * @return the filtered data, or FALSE if the filter fails.
  */
-function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false) {
-
+function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false)
+{
     if (is_array($mixedData)) {
         foreach ($mixedData as $k => $v)
             $mixedData[$k] = bx_process_output($v, $iDataType, $mixedParams);
@@ -209,7 +214,8 @@ function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams
  * Use this function to output data immediately after receiving, without saving to database.
  * Patams are the same as bx_process_input function - @see bx_process_input
  */
-function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
+function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
+{
     return bx_process_output(bx_process_input ($mixedData, $iDataType, $mixedParams, $isCheckMagicQuotes), $iDataType, $mixedParams);
 }
 
@@ -223,7 +229,8 @@ function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams =
  * for data which should be outputed immediately after submit
  */
 /*
-function process_pass_data( $text, $strip_tags = 0 ) {
+function process_pass_data( $text, $strip_tags = 0 )
+{
     if ( $strip_tags )
         $text = strip_tags($text);
 
@@ -237,15 +244,16 @@ function process_pass_data( $text, $strip_tags = 0 ) {
 /*
  * function for output data from database into html
  */
-function htmlspecialchars_adv( $string ) {
+function htmlspecialchars_adv( $string )
+{
     return htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
 }
 
 /**
  * Send mail to user by parsing email template
  */
-function sendMailTemplate($sTemplateName, $iAccountId = 0, $iProfileId = 0, $aReplaceVars = array(), $iEmailType = BX_EMAIL_NOTIFY) {
-
+function sendMailTemplate($sTemplateName, $iAccountId = 0, $iProfileId = 0, $aReplaceVars = array(), $iEmailType = BX_EMAIL_NOTIFY)
+{
     bx_import('BxDolAccount');
     $oAccount = BxDolAccount::getInstance($iAccountId);
 
@@ -276,8 +284,8 @@ function sendMailTemplate($sTemplateName, $iAccountId = 0, $iProfileId = 0, $aRe
  * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  * @return true if message was send or false otherwise
  */
-function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false) {
-
+function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false)
+{
     // make sure that recipient's email is valid and message isn't empty
     if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
         return false;
@@ -302,12 +310,12 @@ function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0
         $oProfile = BxDolProfile::getInstance($iRecipientID);
         if ($oProfile)
             $aRecipientInfo = $oProfile->getInfo();
-    } 
+    }
 
     // get site vars
     $sEmailNotify       = getParam('site_email_notify');
     $sSiteTitle         = getParam('site_title');
-    
+
     // add unsubscribe link
     if (empty($aPlus['unsubscribe'])) {
         $aPlus['unsubscribe'] = '';
@@ -315,7 +323,7 @@ function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0
             $aPlus['unsubscribe'] = ($sLink = $oAccount->getUnsubscribeLink($iEmailType)) ? '<a href="' . BX_DOL_URL_ROOT . $sLink . '">' . _t('_sys_et_txt_unsubscribe') . '</a>' : '';
     }
 
-    // parse template 
+    // parse template
     if ($aPlus || $iRecipientID) {
         if(!is_array($aPlus))
             $aPlus = array();
@@ -372,23 +380,26 @@ function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0
 /*
  * Getting an array with Templates' Names
  */
-function get_templates_array($bEnabledOnly = true, $bShortInfo = true) {
-	bx_import('BxDolDb');
-	$oDb = BxDolDb::getInstance();
-
-	$sWhereAddon = $bEnabledOnly ? " AND `enabled`='1'" : "";
-	
-	if($bShortInfo)
-		return $oDb->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri", "title");
-	else 
-		return $oDb->getAllWithKey("SELECT * FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri"); 
+function get_templates_array($bEnabledOnly = true, $bShortInfo = true)
+{
+    bx_import('BxDolDb');
+    $oDb = BxDolDb::getInstance();
+
+    $sWhereAddon = $bEnabledOnly ? " AND `enabled`='1'" : "";
+
+    if($bShortInfo)
+        return $oDb->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri", "title");
+    else
+        return $oDb->getAllWithKey("SELECT * FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri");
 }
 
-function extFileExists( $sFileSrc ) {
+function extFileExists( $sFileSrc )
+{
     return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
 }
 
-function getVisitorIP() {
+function getVisitorIP()
+{
     $ip = "0.0.0.0";
     if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
@@ -402,17 +413,20 @@ function getVisitorIP() {
     return $ip;
 }
 
-function genFlag( $country ) {
+function genFlag( $country )
+{
     return '<img src="' . genFlagUrl($country) . '" />';
 }
 
-function genFlagUrl($country) {
+function genFlagUrl($country)
+{
     bx_import('BxDolTemplate');
     return BxDolTemplate::getInstance()->getIconUrl('sys_fl_' . strtolower($country) . '.gif');
 }
 
 // print debug information ( e.g. arrays )
-function echoDbg( $what, $desc = '' ) {
+function echoDbg( $what, $desc = '' )
+{
     if ( $desc )
         echo "<b>$desc:</b> ";
     echo "<pre>";
@@ -420,7 +434,8 @@ function echoDbg( $what, $desc = '' ) {
     echo "</pre>\n";
 }
 
-function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log') {
+function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log')
+{
     $sCont =
         '--- ' . date('r') . ' (' . BX_DOL_START_TIME . ") ---\n" .
         $sDesc . "\n" .
@@ -431,8 +446,8 @@ function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log') {
     fclose($rFile);
 }
 
-function clear_xss($val) {
-
+function clear_xss($val)
+{
     if ($GLOBALS['logged']['admin'])
         return $val;
 
@@ -470,9 +485,10 @@ function clear_xss($val) {
 
 //--------------------------------------- friendly permalinks --------------------------------------//
 //------------------------------------------- main functions ---------------------------------------//
-function uriGenerate ($s, $sTable, $sField, $sEmpty = '-') {
+function uriGenerate ($s, $sTable, $sField, $sEmpty = '-')
+{
     $s = uriFilter($s, $sEmpty);
-    if(uriCheckUniq($s, $sTable, $sField)) 
+    if(uriCheckUniq($s, $sTable, $sField))
         return $s;
 
     // cut off redundant part
@@ -481,7 +497,7 @@ function uriGenerate ($s, $sTable, $sField, $sEmpty = '-') {
 
     // try to add date
     $s .= '-' . date('Y-m-d');
-    if(uriCheckUniq($s, $sTable, $sField)) 
+    if(uriCheckUniq($s, $sTable, $sField))
         return $s;
 
     // try to add number
@@ -492,7 +508,8 @@ function uriGenerate ($s, $sTable, $sField, $sEmpty = '-') {
     return rand(0, 999999999);
 }
 
-function uriFilter ($s, $sEmpty = '-') {
+function uriFilter ($s, $sEmpty = '-')
+{
     bx_import('BxTemplConfig');
     if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
         $s = get_mb_replace ('/[^\pL^\pN]+/u', '-', $s); // unicode characters
@@ -505,7 +522,8 @@ function uriFilter ($s, $sEmpty = '-') {
     return $s;
 }
 
-function uriCheckUniq ($s, $sTable, $sField) {
+function uriCheckUniq ($s, $sTable, $sField)
+{
     bx_import('BxDolDb');
     $oDb = BxDolDb::getInstance();
 
@@ -513,23 +531,28 @@ function uriCheckUniq ($s, $sTable, $sField) {
     return !$oDb->query($sSql);
 }
 
-function get_mb_replace ($sPattern, $sReplace, $s) {
+function get_mb_replace ($sPattern, $sReplace, $s)
+{
     return preg_replace ($sPattern, $sReplace, $s);
 }
 
-function get_mb_len ($s) {
+function get_mb_len ($s)
+{
     return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
 }
 
-function get_mb_substr ($s, $iStart, $iLen) {
+function get_mb_substr ($s, $iStart, $iLen)
+{
     return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
 }
 
-function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength) {
+function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength)
+{
     return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
-} 
+}
 
-function bx_mb_strpos ($s, $sReplacement, $iStart = 0) {
+function bx_mb_strpos ($s, $sReplacement, $iStart = 0)
+{
     return mb_strpos($s, $sReplacement, $iStart);
 }
 
@@ -539,7 +562,8 @@ function bx_mb_strpos ($s, $sReplacement, $iStart = 0) {
  * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  * @param $mixedModule - module array or module name in the case of module class
  */
-function bx_import($sClassName, $mixedModule = array()) {
+function bx_import($sClassName, $mixedModule = array())
+{
     if (class_exists($sClassName))
         return;
 
@@ -566,19 +590,19 @@ function bx_import($sClassName, $mixedModule = array()) {
     if (0 == strncmp($sClassName, 'BxDol', 5)) {
         if (0 == strncmp($sClassName, 'BxDolStudio', 11))
             require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
-        else 
+        else
             require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
         return;
     }
 
     if (0 == strncmp($sClassName, 'BxBase', 6)) {
-    	if (0 == strncmp($sClassName, 'BxBaseMod', 9)) {
+        if (0 == strncmp($sClassName, 'BxBaseMod', 9)) {
             $aMatches = array();
             if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
                 require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
                 return;
             }
-    	} if (0 == strncmp($sClassName, 'BxBaseStudio', 12)) {
+        } if (0 == strncmp($sClassName, 'BxBaseStudio', 12)) {
             require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
             return;
         } else {
@@ -588,11 +612,10 @@ function bx_import($sClassName, $mixedModule = array()) {
     }
 
     if (0 == strncmp($sClassName, 'BxTempl', 7) && !class_exists($sClassName)) {
-    	if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
-    	    bx_import('BxDolStudioTemplate');
-    	    $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
-    	}
-        else {
+        if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
+            bx_import('BxDolStudioTemplate');
+            $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
+        } else {
             bx_import('BxDolTemplate');
             $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
         }
@@ -614,14 +637,15 @@ function bx_import($sClassName, $mixedModule = array()) {
  * @param array $aModule an array with module description. Is used when the requested class is located in some module.
  * @return unknown
  */
-function bx_instance($sClassName, $aParams = array(), $aModule = array()) {
+function bx_instance($sClassName, $aParams = array(), $aModule = array())
+{
     if(isset($GLOBALS['bxDolClasses'][$sClassName]))
         return $GLOBALS['bxDolClasses'][$sClassName];
 
     bx_import((empty($aModule) ? $sClassName : str_replace($aModule['class_prefix'], '', $sClassName)), $aModule);
 
     $oClass = new ReflectionClass($sClassName);
-    
+
     $GLOBALS['bxDolClasses'][$sClassName] = empty($aParams) ? $oClass->newInstance() : $oClass->newInstanceArgs($aParams);
 
     return $GLOBALS['bxDolClasses'][$sClassName];
@@ -636,7 +660,8 @@ function bx_instance($sClassName, $aParams = array(), $aModule = array()) {
  * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  * @return converted string / array
  */
-function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
+function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
+{
     $aUnits = array(
         "\n" => "\\n",
         "\r" => "",
@@ -664,8 +689,8 @@ function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  * @param mixed $mixedInput - string/array which should be filtered
  * @return converted string / array
  */
-function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
-
+function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
+{
     $aUnits = array ();
     if (BX_ESCAPE_STR_APOS == $iQuoteType)
         $aUnits["'"] = "\\'";
@@ -683,10 +708,12 @@ function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  * @param mixed $mixedInput - string/array which should be filtered
  * @return converted string / array
  */
-function bx_php_string_apos ($mixedInput) {
+function bx_php_string_apos ($mixedInput)
+{
     return str_replace("'", "\\'", $mixedInput);
 }
-function bx_php_string_quot ($mixedInput) {
+function bx_php_string_quot ($mixedInput)
+{
     return str_replace('"', '\\"', $mixedInput);
 }
 
@@ -697,8 +724,8 @@ function bx_php_string_quot ($mixedInput) {
  * @param array $aParams - an array of parameters to be pathed with URL.
  * @return string the file's contents.
  */
-function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false) {
-
+function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false)
+{
     if ($aParams)
         $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
 
@@ -743,7 +770,8 @@ function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = f
 }
 
 // calculation ini_get('upload_max_filesize') in bytes as example
-function return_bytes($val) {
+function return_bytes($val)
+{
     $val = trim($val);
     $last = strtolower($val{strlen($val)-1});
     $val = (int)$val;
@@ -763,7 +791,8 @@ function return_bytes($val) {
 }
 
 // Generate Random Password
-function genRndPwd($iLength = 8, $bSpecialCharacters = true) {
+function genRndPwd($iLength = 8, $bSpecialCharacters = true)
+{
     $sPassword = '';
     $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
 
@@ -780,16 +809,19 @@ function genRndPwd($iLength = 8, $bSpecialCharacters = true) {
 }
 
 // Generate Random Salt for Password encryption
-function genRndSalt() {
+function genRndSalt()
+{
     return genRndPwd(8, true);
 }
 
 // Encrypt User Password
-function encryptUserPwd($sPwd, $sSalt) {
+function encryptUserPwd($sPwd, $sSalt)
+{
     return sha1(md5($sPwd) . $sSalt);
 }
 
-function bx_get ($sName, $sMethod = false) {
+function bx_get ($sName, $sMethod = false)
+{
     if (isset($_GET[$sName]) && ('get' == $sMethod || !$sMethod))
         return $_GET[$sName];
     elseif (isset($_POST[$sName]) && ('post' == $sMethod || !$sMethod))
@@ -798,7 +830,8 @@ function bx_get ($sName, $sMethod = false) {
         return false;
 }
 
-function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false) {
+function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
+{
     $s = '';
     foreach ($a as $sKey => $sVal) {
         if (in_array($sKey, $aExcludeKeys))
@@ -816,7 +849,8 @@ function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
     return $s;
 }
 
-function bx_append_url_params ($sUrl, $mixedParams) {
+function bx_append_url_params ($sUrl, $mixedParams)
+{
     if (!$mixedParams)
         return $sUrl;
 
@@ -832,7 +866,8 @@ function bx_append_url_params ($sUrl, $mixedParams) {
     return $sUrl . $sParams;
 }
 
-function bx_rrmdir($directory) {
+function bx_rrmdir($directory)
+{
     if (substr($directory,-1) == "/")
         $directory = substr($directory,0,-1);
 
@@ -863,7 +898,8 @@ function bx_rrmdir($directory) {
     return true;
 }
 
-function bx_clear_folder ($sPath, $aExts = array ()) {
+function bx_clear_folder ($sPath, $aExts = array ())
+{
     if (substr($$sPath,-1) == "/")
         $sPath = substr($sPath,0,-1);
 
@@ -893,13 +929,14 @@ function bx_clear_folder ($sPath, $aExts = array ()) {
     return true;
 }
 
-function bx_ltrim_str ($sString, $sPrefix, $sReplace = '') {
+function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
+{
     if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
         return $sString;
     if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
         return $sReplace . substr($sString, strlen($sPrefix));
     return $sString;
-} 
+}
 
 /**
  * Convert array to attributes string
@@ -916,7 +953,8 @@ function bx_ltrim_str ($sString, $sPrefix, $sReplace = '') {
  * @param $sStyles - styles to merge with 'style' attribute
  * @return string
  */
-function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false) {
+function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
+{
     $sRet = '';
 
     if (!$a || !is_array($a))
@@ -946,26 +984,20 @@ function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false) {
     return $sRet;
 }
 
-function bx_unicode_urldecode($s) {
-
+function bx_unicode_urldecode($s)
+{
     preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
 
-    foreach ($a[1] as $uniord)
-    {
+    foreach ($a[1] as $uniord) {
         $dec = hexdec($uniord);
         $utf = '';
 
-        if ($dec < 128)
-        {
+        if ($dec < 128) {
             $utf = chr($dec);
-        }
-        else if ($dec < 2048)
-        {
+        } else if ($dec < 2048) {
             $utf = chr(192 + (($dec - ($dec % 64)) / 64));
             $utf .= chr(128 + ($dec % 64));
-        }
-        else
-        {
+        } else {
             $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
             $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
             $utf .= chr(128 + ($dec % 64));
@@ -984,12 +1016,14 @@ function bx_unicode_urldecode($s) {
  * @param int $iObjectId - object id
  * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  */
-function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array()) {
+function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
+{
     $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
     $o->alert();
-}   
+}
 
-function bx_replace_markers($mixed, $aMarkers) {
+function bx_replace_markers($mixed, $aMarkers)
+{
     if (empty($aMarkers))
         return $mixed;
 
@@ -1004,7 +1038,8 @@ function bx_replace_markers($mixed, $aMarkers) {
     return $mixed;
 }
 
-function bx_site_hash($sSalt = '', $isSkipVersion = false) {
+function bx_site_hash($sSalt = '', $isSkipVersion = false)
+{
     return md5($sSalt . ($isSkipVersion ? '' : getParam('sys_version')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
 }
 
@@ -1013,7 +1048,8 @@ function bx_site_hash($sSalt = '', $isSkipVersion = false) {
  * @param string where words are separated with underscore
  * @return string where every word begins with capital letter
  */
-function bx_gen_method_name ($s, $sWordsDelimiter = '_') {
+function bx_gen_method_name ($s, $sWordsDelimiter = '_')
+{
     return str_replace(' ', '', ucwords(str_replace($sWordsDelimiter, ' ', $s)));
 }
 
@@ -1022,11 +1058,11 @@ function bx_gen_method_name ($s, $sWordsDelimiter = '_') {
  * @param $sMsg message to display
  * @param $iNumLevelsBack add additional debug backtracing N levels back
  */
-function bx_trigger_error ($sMsg, $iNumLevelsBack = 0) {
+function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
+{
     $a = debug_backtrace();
     $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
     trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
 }
 
-/** @} */ 
-
+/** @} */

+ 4 - 6
index.php

@@ -7,8 +7,7 @@
  * @{
  */
 
-if (!file_exists("./inc/header.inc.php"))
-{
+if (!file_exists("./inc/header.inc.php")) {
     // this is dynamic page - send headers to not cache this page
     $now = gmdate('D, d M Y H:i:s') . ' GMT';
     header("Expires: $now");
@@ -17,7 +16,7 @@ if (!file_exists("./inc/header.inc.php"))
     header("Pragma: no-cache");
 
     echo "It seems to be script is <b>not</b> installed.<br />\n";
-    if ( file_exists( "install/index.php" ) ) {        
+    if ( file_exists( "install/index.php" ) ) {
         echo "Please, wait. Redirecting you to installation form...<br />\n";
         echo "<script language=\"javascript\">location.href = 'install/index.php';</script>\n";
     }
@@ -29,8 +28,8 @@ require_once(BX_DIRECTORY_PATH_INC . "profiles.inc.php");
 
 /*
 if(!isLogged()) {
-	require_once("./splash.php");
-	exit;
+    require_once("./splash.php");
+    exit;
 }
 */
 
@@ -38,4 +37,3 @@ $_GET['i'] = 'home';
 require_once("./page.php");
 
 /** @} */
-

+ 17 - 16
install/classes/BxDolInstallController.php

@@ -7,17 +7,17 @@
  * @{
  */
 
-class BxDolInstallController 
+class BxDolInstallController
 {
 
     protected $_oView;
-    
-    function __construct() 
+
+    function __construct()
     {
         $this->_oView = new BxDolInstallView();
     }
 
-    function run ($sAction = '') 
+    function run ($sAction = '')
     {
         $sMethod = 'action' . bx_gen_method_name($sAction);
         if ($sAction && method_exists($this, $sMethod))
@@ -25,15 +25,15 @@ class BxDolInstallController
         else
             $this->actionInitial ();
     }
-   
-    function actionEmpty () 
+
+    function actionEmpty ()
     {
     }
 
-    function actionAudit () 
+    function actionAudit ()
     {
         $this->_oView->pageStart();
-        
+
         $oAudit = new BxDolStudioToolsAudit();
         $sAuditOutput = $oAudit->generate();
 
@@ -42,7 +42,7 @@ class BxDolInstallController
         $this->_oView->pageEnd($this->_getTitle());
     }
 
-    function actionInitial () 
+    function actionInitial ()
     {
         $this->_oView->pageStart();
 
@@ -62,12 +62,12 @@ class BxDolInstallController
         $this->_oView->pageEnd($this->_getTitle());
     }
 
-    function actionPermissions () 
+    function actionPermissions ()
     {
         $this->_oView->pageStart();
 
         $oAdmTools = new BxDolStudioTools();
-        
+
         $sPermissionsStyles = $oAdmTools->generateStyles();
 
         ob_start();
@@ -81,7 +81,7 @@ class BxDolInstallController
         $this->_oView->pageEnd($this->_getTitle());
     }
 
-    function actionSiteConfig () 
+    function actionSiteConfig ()
     {
         $this->_oView->pageStart();
 
@@ -95,7 +95,7 @@ class BxDolInstallController
         $this->_oView->pageEnd($this->_getTitle());
     }
 
-    function actionFinish () 
+    function actionFinish ()
     {
         require_once(BX_INSTALL_PATH_HEADER);
 
@@ -103,7 +103,7 @@ class BxDolInstallController
 
         $sPathToPhp = "/replace/it/with/path/to/php/binary";
         $a = array(
-            '/usr/local/bin/php', 
+            '/usr/local/bin/php',
             '/usr/bin/php',
             '/opt/local/bin/php',
         );
@@ -118,7 +118,7 @@ class BxDolInstallController
         $this->_oView->pageEnd($this->_getTitle());
     }
 
-    function actionRemoveInstall () 
+    function actionRemoveInstall ()
     {
         require_once(BX_INSTALL_PATH_HEADER);
 
@@ -129,7 +129,8 @@ class BxDolInstallController
         $this->_oView->pageEnd($this->_getTitle());
     }
 
-    protected function _getTitle() {
+    protected function _getTitle()
+    {
         return _t('_sys_inst_title', BX_DOL_VER);
     }
 }

+ 9 - 6
install/classes/BxDolInstallLang.php

@@ -13,7 +13,7 @@ class BxDolInstallLang
     protected $_sLang;
     protected $_oModulesTools;
 
-    public function __construct($sLang) 
+    public function __construct($sLang)
     {
         $this->_oModulesTools = new BxDolInstallModulesTools();
         if (!$sLang)
@@ -29,14 +29,15 @@ class BxDolInstallLang
         $this->_aLang = $this->_oModulesTools->readLanguage($aModuleConfig);
     }
 
-    static function getInstance($sLang = '') {
+    static function getInstance($sLang = '')
+    {
         if (!isset($GLOBALS['bxDolClasses'][__CLASS__]))
             $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolInstallLang($sLang);
 
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
-    public function _t ($sKey) 
+    public function _t ($sKey)
     {
         $sKey = func_get_arg(0);
         if (isset($this->_aLang[$sKey])) {
@@ -51,8 +52,9 @@ class BxDolInstallLang
 
         return $sKey;
     }
-   
-    public function getAvailableLanguages () {
+
+    public function getAvailableLanguages ()
+    {
         $aRet = array();
         $aModules = $this->_oModulesTools->getModules('language');
         foreach ($aModules as $aModuleConfig)
@@ -78,7 +80,8 @@ if (!function_exists('_t')) {
 
     BxDolInstallLang::getInstance($sLang);
 
-    function _t() {
+    function _t()
+    {
         return call_user_func_array(array(BxDolInstallLang::getInstance(), '_t'), func_get_args());
     }
 }

+ 24 - 20
install/classes/BxDolInstallModulesTools.php

@@ -10,17 +10,18 @@
 class BxDolInstallModulesTools
 {
 
-    public function __construct() 
+    public function __construct()
     {
     }
-   
-    public function getModules ($sType = null) {
-    	$aModules = array();
+
+    public function getModules ($sType = null)
+    {
+        $aModules = array();
 
         $sPath = BX_INSTALL_DIR_MODULES;
         if (($rHandleVendor = opendir($sPath)) !== false) {
             while (($sVendor = readdir($rHandleVendor)) !== false) {
-                if (substr($sVendor, 0, 1) == '.' || !is_dir($sPath . $sVendor)) 
+                if (substr($sVendor, 0, 1) == '.' || !is_dir($sPath . $sVendor))
                     continue;
 
                 if (($rHandleModule = opendir($sPath . $sVendor)) !== false) {
@@ -28,12 +29,12 @@ class BxDolInstallModulesTools
                         if(!is_dir($sPath . $sVendor . '/' . $sModule) || substr($sModule, 0, 1) == '.')
                             continue;
 
-						$sConfigPath = $sPath . $sVendor . '/' . $sModule . '/install/config.php';
-						$aModuleConfig = $this->getModuleConfigByConfigPath($sConfigPath);
-						if (empty($aModuleConfig) || ($sType && $sType != $aModuleConfig['type']))
-							continue;
+                        $sConfigPath = $sPath . $sVendor . '/' . $sModule . '/install/config.php';
+                        $aModuleConfig = $this->getModuleConfigByConfigPath($sConfigPath);
+                        if (empty($aModuleConfig) || ($sType && $sType != $aModuleConfig['type']))
+                            continue;
 
-						$aModules[$aModuleConfig['name']] = $aModuleConfig;
+                        $aModules[$aModuleConfig['name']] = $aModuleConfig;
                     }
                     closedir($rHandleModule);
                 }
@@ -45,30 +46,33 @@ class BxDolInstallModulesTools
         return $aModules;
     }
 
-    public function getModuleConfigByUri ($sUri, $aModules) {
+    public function getModuleConfigByUri ($sUri, $aModules)
+    {
         foreach ($aModules as $aModuleConfig)
             if ($sUri == $aModuleConfig['home_uri'])
                 return $aModuleConfig;
         return null;
     }
 
-    public function readLanguage ($aModuleConfig) {
+    public function readLanguage ($aModuleConfig)
+    {
         $sPath = BX_INSTALL_DIR_MODULES . $aModuleConfig['home_dir'] . 'data/langs/system.xml';
 
-    	if(!file_exists($sPath))
-    		return array();
+        if(!file_exists($sPath))
+            return array();
 
-    	$oXmlParser = BxDolXmlParser::getInstance();
-    	$sXmlContent = file_get_contents($sPath);
+        $oXmlParser = BxDolXmlParser::getInstance();
+        $sXmlContent = file_get_contents($sPath);
 
         return $oXmlParser->getValues($sXmlContent, 'string');
     }
 
-    protected function getModuleConfigByConfigPath ($sConfigPath) {
-		if (!file_exists($sConfigPath))
-			return array();
+    protected function getModuleConfigByConfigPath ($sConfigPath)
+    {
+        if (!file_exists($sConfigPath))
+            return array();
 
-		include($sConfigPath);
+        include($sConfigPath);
 
         return $aConfig;
     }

+ 28 - 28
install/classes/BxDolInstallSiteConfig.php

@@ -210,7 +210,7 @@ class BxDolInstallSiteConfig
         );
     }
 
-    public function getAutoValues($aData = array()) 
+    public function getAutoValues($aData = array())
     {
         $aRet = array();
         foreach($this->_aConfig as $sKey => $a) {
@@ -272,7 +272,7 @@ class BxDolInstallSiteConfig
 EOF;
     }
 
-    public function processConfigData ($a) 
+    public function processConfigData ($a)
     {
         $aSteps = array('checkConfig', 'processConfigDataDb', 'processConfigDataHeader', 'processModules');
         foreach ($aSteps as $sFunc) {
@@ -284,7 +284,7 @@ EOF;
         return array();
     }
 
-    protected function checkConfig($a) 
+    protected function checkConfig($a)
     {
         $aErrorFields = array();
         foreach ($this->_aConfig as $sKey => $r) {
@@ -292,7 +292,7 @@ EOF;
                 $aErrorFields[$sKey] = true;
         }
 
-        if (!empty($aErrorFields)) 
+        if (!empty($aErrorFields))
             $aErrorFields[BX_INSTALL_ERR_GENERAL] = _t('_sys_inst_msg_form_error');
 
         return $aErrorFields;
@@ -330,15 +330,15 @@ EOF;
         return array();
     }
 
-    public function processConfigDataHeader ($a) 
+    public function processConfigDataHeader ($a)
     {
         $aMarkers = $this->getMarkersForPhp($a);
-        
+
         $sFile = $this->_sPatternHeader;
         $sHeader = file_get_contents($sFile);
         if (false === $sHeader)
             return array(BX_INSTALL_ERR_GENERAL => _t('_sys_inst_msg_file_read_failed', $sFile));
-    
+
         $sHeader = str_replace(array_keys($aMarkers), array_values($aMarkers), $sHeader);
 
         if (false === file_put_contents(BX_INSTALL_PATH_HEADER, $sHeader))
@@ -358,7 +358,7 @@ EOF;
             $sErrorMessage = $this->processModuleByUri ($a[$sModuleType], array ('install', 'enable'), $sModuleType);
             if ($sErrorMessage)
                 return array(BX_INSTALL_ERR_GENERAL => $sErrorMessage);
-        } 
+        }
 
         bx_import('BxDolAccount');
         $oAccount = BxDolAccount::getInstance($a['admin_email']);
@@ -389,7 +389,7 @@ EOF;
         require_once(BX_INSTALL_PATH_HEADER);
         bx_import('BxDolStudioInstallerUtils');
         bx_import('BxDolLanguages');
-        BxDolLanguages::getInstance();        
+        BxDolLanguages::getInstance();
         $oModulesTools = new BxDolInstallModulesTools();
 
         $aModules = $oModulesTools->getModules($sModuleType);
@@ -407,7 +407,7 @@ EOF;
         return '';
     }
 
-    protected function dbErrors2ErrorFields ($a) 
+    protected function dbErrors2ErrorFields ($a)
     {
         $s = '';
         foreach ($a as $r)
@@ -415,9 +415,9 @@ EOF;
         return array(BX_INSTALL_ERR_GENERAL => $s);
     }
 
-    protected function processInputData ($a) 
+    protected function processInputData ($a)
     {
-        foreach ($a as $sKey => $mixedValue) 
+        foreach ($a as $sKey => $mixedValue)
             $a[$sKey] = bx_process_input($mixedValue);
         return $a;
     }
@@ -438,7 +438,7 @@ EOF;
         return $aMarkers;
     }
 
-    protected function getMarkersForDb($a, $oDb) 
+    protected function getMarkersForDb($a, $oDb)
     {
         $a = $this->getMarkers($a);
         $aMarkers = array();
@@ -449,7 +449,7 @@ EOF;
         return $aMarkers;
     }
 
-    protected function getMarkersForPhp($a) 
+    protected function getMarkersForPhp($a)
     {
         $a = $this->getMarkers($a);
         $aMarkers = array();
@@ -458,7 +458,7 @@ EOF;
         return $aMarkers;
     }
 
-    protected function getFormFields($aErrorFields, $aData) 
+    protected function getFormFields($aErrorFields, $aData)
     {
         $s = '';
         foreach($this->_aConfig as $sKey => $a) {
@@ -469,7 +469,7 @@ EOF;
         return $s;
     }
 
-    protected function rowInput ($aData, $sKey, $a, $isError = false) 
+    protected function rowInput ($aData, $sKey, $a, $isError = false)
     {
         $sAutoMessage = '';
         $sValue = bx_html_attribute($this->def ($aData, $sKey, $a, $sAutoMessage));
@@ -477,7 +477,7 @@ EOF;
         return $this->rowWrapper ($aData, $sInput, $sAutoMessage, 'text', $sKey, $a, $isError);
     }
 
-    protected function rowSelect ($aData, $sKey, $a, $isError = false) 
+    protected function rowSelect ($aData, $sKey, $a, $isError = false)
     {
         $sAutoMessage = '';
         $sValue = bx_html_attribute($this->def ($aData, $sKey, $a, $sAutoMessage));
@@ -513,12 +513,12 @@ EOF;
                     $sError
                     <div class="bx-form-info bx-def-font-grayed bx-def-font-small">
                         {$sDesc}
-                    </div>                    
+                    </div>
                 </div></div>
 EOF;
     }
 
-    protected function rowSectionOpen ($aData, $sKey, $a) 
+    protected function rowSectionOpen ($aData, $sKey, $a)
     {
         return <<<EOF
                     <div class="bx-form-section-wrapper bx-def-margin-top">
@@ -528,7 +528,7 @@ EOF;
 EOF;
     }
 
-    protected function rowSectionClose ($aData, $sKey, $a) 
+    protected function rowSectionClose ($aData, $sKey, $a)
     {
         return <<<EOF
                             </div>
@@ -537,24 +537,24 @@ EOF;
 EOF;
     }
 
-    protected function check ($sKey, $sValue, $a) 
+    protected function check ($sKey, $sValue, $a)
     {
         if (empty($a['check']))
             return true;
         return $this->{$a['check'][0]}($sValue, $a['check'][1]);
     }
 
-    protected function checkLength ($s, $i) 
+    protected function checkLength ($s, $i)
     {
         return mb_strlen($s) >= $i ? true : false;
     }
 
-    protected function checkEmail ($s, $i) 
+    protected function checkEmail ($s, $i)
     {
         return mb_strlen($s) > $i && false !== strpos($s, '@') ? true : false;
     }
 
-    protected function def ($aData, $sKey, $a, &$sAutoMessage) 
+    protected function def ($aData, $sKey, $a, &$sAutoMessage)
     {
         if (isset($aData[$sKey]))
             return bx_process_pass($aData[$sKey]);
@@ -570,22 +570,22 @@ EOF;
         return isset($a['def']) ? $a['def'] : '';
     }
 
-    protected function defUrl ($foo) 
+    protected function defUrl ($foo)
     {
         $s = "http://" . $this->_sServerHttpHost . $this->_sServerPhpSelf;
         return preg_replace("/install\/(index\.php$)/", '', $s);
     }
 
-    protected function defPath ($foo) 
+    protected function defPath ($foo)
     {
         $s = rtrim($this->_sServerDocumentRoot, '/') . $this->_sServerPhpSelf;
         return preg_replace("/install\/(index\.php$)/", '', $s);
     }
 
-    protected function defImageMagickBin ($sBin) 
+    protected function defImageMagickBin ($sBin)
     {
         $a = array(
-            '/usr/X11R6/bin/', 
+            '/usr/X11R6/bin/',
             '/usr/local/bin/',
             '/usr/bin/',
             '/usr/local/X11R6/bin/',

+ 8 - 8
install/classes/BxDolInstallView.php

@@ -7,7 +7,7 @@
  * @{
  */
 
-class BxDolInstallView 
+class BxDolInstallView
 {
     protected $_sDirPlugins = BX_INSTALL_DIR_PLUGINS;
     protected $_sDirTemplates = BX_INSTALL_DIR_TEMPLATES;
@@ -64,11 +64,11 @@ class BxDolInstallView
         include($this->_sDirTemplates . '_page.php');
     }
 
-    function setToolbarItem($sIcon, $sLink, $sTitle = '', $sTarget = '') 
+    function setToolbarItem($sIcon, $sLink, $sTitle = '', $sTarget = '')
     {
         $this->_aToolbarItem = array(
-            'icon' => $sIcon, 
-            'link' => $sLink, 
+            'icon' => $sIcon,
+            'link' => $sLink,
             'title' => $sTitle,
             'target' => $sTarget,
         );
@@ -80,7 +80,7 @@ class BxDolInstallView
         foreach ($this->_aFilesCss as $sFile)
             if (substr($sFile, -4) === '.css')
                 $s .= '<link rel="stylesheet" href="' . $this->_sUrlCss . $sFile . '" />';
-        return $s; 
+        return $s;
     }
 
     protected function _getFilesJS()
@@ -88,13 +88,13 @@ class BxDolInstallView
         $s = '';
         foreach ($this->_aFilesJs as $sFile)
             $s .= '<script src="' . $this->_sUrlJs . $sFile . '"></script>';
-        return $s; 
+        return $s;
     }
 
     protected function _getInlineCSS()
     {
         $s = '';
-    	require_once($this->_sDirPlugins . 'lessphp/lessc.inc.php');
+        require_once($this->_sDirPlugins . 'lessphp/lessc.inc.php');
         $oLess = new lessc();
         $oConfigBase = new BxBaseConfig();
         $oLess->setVariables($oConfigBase->aLessConfig);
@@ -104,7 +104,7 @@ class BxDolInstallView
 
             $s .= $oLess->compileFile($this->_sPathCss . $sFile) . "\n";
         }
-        return $s; 
+        return $s;
     }
 }
 

+ 7 - 7
install/cmd.php

@@ -25,7 +25,7 @@ class BxDolInstallCmd
         'module failed' => array ('code' => 5, 'msg' => 'Additional module install failed. '),
     );
 
-    public function __construct() 
+    public function __construct()
     {
         $aPathInfo = pathinfo(__FILE__);
 
@@ -71,7 +71,7 @@ class BxDolInstallCmd
         $this->init();
 
         // peform install
-        
+
         $this->checkRequirements();
         $this->checkPermissions();
         $this->createSiteConfig();
@@ -82,13 +82,13 @@ class BxDolInstallCmd
     protected function getOptions()
     {
         $a = array ();
-        foreach ($this->_aSiteConfig as $sKey => $sValue) 
+        foreach ($this->_aSiteConfig as $sKey => $sValue)
             if ('site_config' != $sKey)
                 $a[] = "$sKey::";
         return $a;
-    } 
+    }
 
-    protected function getHelp() 
+    protected function getHelp()
     {
         $s = "Usage: php cmd.php [options]\n";
 
@@ -108,7 +108,7 @@ class BxDolInstallCmd
         return $s;
     }
 
-    protected function finish($iCode, $sMsg) 
+    protected function finish($iCode, $sMsg)
     {
         if (!$this->_isQuiet)
             fwrite($iCode ? STDERR : STDOUT, $sMsg . "\n");
@@ -119,7 +119,7 @@ class BxDolInstallCmd
     protected function init()
     {
         // skip this test if script is already installed
-        if (file_exists($this->_sHeaderPath)) 
+        if (file_exists($this->_sHeaderPath))
             $this->finish($this->_aReturnCodes['already installed']['code'], $this->_aReturnCodes['already installed']['msg']);
 
         // include necessary files to perform install

Некоторые файлы не были показаны из-за большого количества измененных файлов