Robert Vogel has submitted this change and it was merged. ( 
https://gerrit.wikimedia.org/r/388498 )

Change subject: BSAvatars: Partially rework
......................................................................


BSAvatars: Partially rework

* Using new config mechanism
* Moved the generate mechanism to its own class
* Used new Hook base classes

=> Requires:
- https://gerrit.wikimedia.org/r/#/c/390247/
- https://gerrit.wikimedia.org/r/#/c/378243/

Change-Id: Iba259cb1c976046895e23cb93a1c8a46f803c560
---
D Avatars.class.php
A Avatars.php
M composer.json
M extension.json
M includes/api/BSApiAvatarsTasks.php
A src/ConfigDefinition/AvatarsDefaultSize.php
A src/ConfigDefinition/AvatarsGenerator.php
A src/Generator.php
A src/Hook/BSCoreGetUserMiniProfileBeforeInit/SetAvatar.php
A src/Hook/BeforePageDisplay/AddModules.php
10 files changed, 397 insertions(+), 327 deletions(-)

Approvals:
  Robert Vogel: Verified; Looks good to me, approved



diff --git a/Avatars.class.php b/Avatars.class.php
deleted file mode 100644
index 6f0ae97..0000000
--- a/Avatars.class.php
+++ /dev/null
@@ -1,317 +0,0 @@
-<?php
-
-/**
- * Avatars extension for BlueSpice
- *
- * Provide generic and individual user images
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * This file is part of BlueSpice MediaWiki
- * For further information visit http://www.bluespice.com
- *
- * @author     Marc Reymann <[email protected]>
- * @version    2.23.1
- * @package    BlueSpice_Extensions
- * @subpackage Avatars
- * @copyright  Copyright (C) 2016 Hallo Welt! GmbH, All rights reserved.
- * @license    http://www.gnu.org/copyleft/gpl.html GNU Public License v2 or 
later
- * @filesource
- */
-
-/**
- * Base class for the Avatars extension
- * @package BlueSpice_Extensions
- * @subpackage Avatars
- */
-class Avatars extends BsExtensionMW {
-
-       public static $bAvatarsActive = true;
-       public static $sAvatarFilePrefix = "BS_avatar_";
-
-       /**
-        * Initialization of Avatar extension
-        */
-       protected function initExt() {
-               wfProfileIn('BS::' . __METHOD__);
-
-               BsConfig::registerVar('MW::Avatars::DefaultSize', 40, 
BsConfig::LEVEL_PUBLIC | BsConfig::TYPE_INT, 'bs-avatars-pref-defaultsize', 
'int');
-               BsConfig::registerVar('MW::Avatars::Generator', 
'InstantAvatar', BsConfig::LEVEL_PUBLIC | BsConfig::TYPE_STRING | 
BsConfig::USE_PLUGIN_FOR_PREFS, 'bs-avatars-pref-generator', 'select');
-
-               $this->setHook('BSCoreGetUserMiniProfileBeforeInit');
-               $this->setHook('BsAuthorPageProfileImageAfterInitFields');
-
-               # TODO: required rights? user->read?
-               #$this->mCore->registerPermission( 'viewfiles', array( 'user' ) 
);
-               wfProfileOut('BS::' . __METHOD__);
-       }
-
-       /**
-        * extension.json callback
-        * @global array $wgForeignFileRepos
-        */
-       public static function onRegistration() {
-               global $wgForeignFileRepos;
-               if ( version_compare( $GLOBALS['wgVersion'], '1.28c', '>' ) ) {
-                       $wgForeignFileRepos[] = array(
-                               'class' => 'FileRepo',
-                               'name' => 'Avatars',
-                               'directory' => BS_DATA_DIR . '/Avatars/',
-                               'hashLevels' => 0,
-                               'url' => BS_DATA_PATH . '/Avatars',
-                       );
-               } else {
-                       $wgForeignFileRepos[] = array(
-                               'class' => 'FSRepo',
-                               'name' => 'Avatars',
-                               'directory' => BS_DATA_DIR . '/Avatars/',
-                               'hashLevels' => 0,
-                               'url' => BS_DATA_PATH . '/Avatars',
-                       );
-               }
-       }
-
-       /**
-        * Adds module
-        * @param OutputPage $out
-        * @param SkinTemplate $skin
-        * @return boolean
-        */
-       public static function onBeforePageDisplay(&$out, &$skin) {
-               if (!$out->getTitle()->equals($out->getUser()->getUserPage()))
-                       return true;
-               $out->addModules("ext.bluespice.avatars.js");
-               return true;
-       }
-
-       public function runPreferencePlugin($sAdapterName, $oVariable) {
-               $aPrefs = array('options' => array('InstantAvatar (random)' => 
'InstantAvatar', 'Identicon (non-random)' => 'Identicon'));
-               return $aPrefs;
-       }
-
-       /**
-        * Show avatar if user has no UserImage setting
-        * @param type $oUserMiniProfileView
-        * @param User $oUser
-        * @param type $aParams
-        * @return boolean
-        */
-       public function 
onBSCoreGetUserMiniProfileBeforeInit(&$oUserMiniProfileView, &$oUser, 
&$aParams) {
-               # Set anonymous image for anonymous or deleted users
-               if ($oUser->isAnon()) {
-                       
$oUserMiniProfileView->setUserImageSrc(BsConfig::get('MW::DeletedUserImage'));
-                       $oUserMiniProfileView->setOption('linktargethref', ''); 
# don't link to user page
-                       return true;
-               }
-
-               # If user has set MW image or URL return immediately
-               if( !empty( $oUser->getOption( 'MW::UserImage' ) ) ) {
-                       return true;
-               }
-
-               # Set default image in read-only mode or thumb creation might 
get triggered
-               if (wfReadOnly()) {
-                       
$oUserMiniProfileView->setUserImageSrc(BsConfig::get('MW::DefaultUserImage'));
-                       return true;
-               }
-
-               # Set or generate user's avatar
-               $oUserMiniProfileView->setUserImageSrc( $this->generateAvatar(
-                       $oUser,
-                       $aParams
-               ));
-
-               return true;
-       }
-
-       /**
-        * Gets Avatar file from user ID
-        * @param int $iUserId
-        * @return boolean|\File
-        */
-       public static function getAvatarFile( $iUserId ) {
-               $sAvatarFileName = self::$sAvatarFilePrefix . $iUserId . ".png";
-               return BsFileSystemHelper::getFileFromRepoName( 
$sAvatarFileName, 'Avatars' );
-       }
-
-       /**
-        * Show avatar on user page
-        * @param ViewAuthorsUserPageProfileImageSetting $oView
-        * @param User $oUser
-        * @return boolean
-        */
-       public function onBsAuthorPageProfileImageAfterInitFields($oView, 
$oUser) {
-               # If user has set MW image or URL return immediately
-               if ($oUser->getOption('MW::UserImage'))
-                       return true;
-               # Set default image in read-only mode or thumb creation might 
get triggered
-               if (wfReadOnly()) {
-                       
$oView->setImagePath(BsConfig::get('MW::DefaultUserImage'));
-                       return true;
-               }
-               $oView->setImagePath($this->generateAvatar($oUser));
-               return true;
-       }
-
-       /**
-        * Generate a new generic avatar on user request
-        * @return type
-        */
-       public static function generateAvatarAjax() {
-               if (wfReadOnly()) {
-                       global $wgReadOnly;
-                       return new 
AjaxResponse(FormatJson::encode(wfMessage('bs-readonly', 
$wgReadOnly)->escaped()));
-               }
-               $oUser = RequestContext::getMain()->getUser();
-               self::unsetUserImage($oUser);
-               $oAvatars = BsExtensionManager::getExtension('Avatars');
-               $sNewPath = $oAvatars->generateAvatar($oUser, array(), true);
-               return 
FormatJson::encode(wfMessage('bs-avatars-generate-complete')->plain());
-       }
-
-       /**
-        * Clears a user's UserImage setting
-        * @param User $oUser
-        */
-       public static function unsetUserImage($oUser) {
-               if( $oUser->getOption( 'MW::UserImage' ) ) {
-                       $oUser->setOption( 'MW::UserImage', false );
-                       $oUser->saveSettings();
-                       $oUser->invalidateCache();
-               }
-               return;
-       }
-
-       /**
-        * Generate an avatar image
-        * @param User $oUser
-        * @return string Relative URL to avatar image
-        */
-       public function generateAvatar($oUser, $aParams = array(), $bOverwrite 
= false) {
-               $iAvatarDefaultSize = BsConfig::get('MW::Avatars::DefaultSize');
-               $iAvatarHeight = ( isset($aParams['height']) ) ? 
$aParams['height'] : $iAvatarDefaultSize;
-               $iAvatarWidth = ( isset($aParams['width']) ) ? 
$aParams['width'] : $iAvatarDefaultSize;
-
-               $iUserId = $oUser->getId();
-               $sUserName = $oUser->getName();
-               $sUserRealName = $oUser->getRealName();
-
-               # TODO: Check if this is more expensive than a simple 
file_exists()
-               $oFile = self::getAvatarFile( $iUserId );
-
-               // Prevent fatal when filerepo cannot be found.
-               if ( !$oFile ) {
-                       return '';
-               }
-
-               # If avatar doesn't yet exit, create one
-               if (!$oFile->exists() || $bOverwrite) {
-                       $sGenerator = BsConfig::get('MW::Avatars::Generator');
-                       switch ($sGenerator) {
-                               case 'Identicon':
-                                       require_once( __DIR__ . 
"/includes/lib/Identicon/identicon.php" );
-                                       $sRawPNGAvatar = 
generateIdenticon($iUserId, $iAvatarDefaultSize); # non-random
-                                       break;
-                               case 'InstantAvatar':
-                                       require_once( __DIR__ . 
"/includes/lib/InstantAvatar/instantavatar.php" );
-                                       $iFontSize = round(18 / 40 * 
$iAvatarDefaultSize);
-                                       $oIA = new InstantAvatar(__DIR__ . 
'/includes/lib/InstantAvatar/Comfortaa-Regular.ttf', $iFontSize, 
$iAvatarDefaultSize, $iAvatarDefaultSize, 2, __DIR__ . 
'/includes/lib/InstantAvatar/glass.png');
-                                       if ($sUserRealName) {
-                                               preg_match_all('#(^| )(.)#u', 
$sUserRealName, $aMatches);
-                                               $sChars = implode('', 
$aMatches[2]);
-                                               if (mb_strlen($sChars) < 2)
-                                                       $sChars = 
$sUserRealName;
-                                       }
-                                       else {
-                                               $sChars = $sUserName;
-                                       }
-                                       $oIA->generateRandom($sChars); # random
-                                       $sRawPNGAvatar = $oIA->getRawPNG();
-                                       break;
-                               default:
-                                       throw new MWException('FATAL: Avatar 
generator not found!');
-                                       break;
-                       }
-
-                       $sAvatarFileName = $oFile->getName();
-                       $oStatus = 
BsFileSystemHelper::saveToDataDirectory($sAvatarFileName, $sRawPNGAvatar, 
'Avatars');
-                       if ( !$oStatus->isGood() ) {
-                               throw new MWException( 'FATAL: Avatar could not 
be saved! '.$oStatus->getMessage() );
-                       }
-                       # found no way to regenerate thumbs. just delete thumb 
folder if it exists
-                       $oStatus = BsFileSystemHelper::deleteFolder('Avatars' . 
DS . 'thumb' . DS . $sAvatarFileName, true);
-                       if (!$oStatus->isGood())
-                               throw new MWException('FATAL: Avatar thumbs 
could no be deleted!');
-                       $oFile = 
BsFileSystemHelper::getFileFromRepoName($sAvatarFileName, 'Avatars');
-
-                       $oUser->invalidateCache();
-               }
-               $sNewUserImageSrc = $oFile->createThumb($iAvatarWidth, 
$iAvatarHeight);
-               return $sNewUserImageSrc;
-       }
-
-       /**
-        * Create an initial Avatar
-        * @param User $user
-        * @param boolean $autocreated
-        * @return boolean
-        */
-       public static function onLocalUserCreated( $user, $autocreated ) {
-               $oAvatars = BsExtensionManager::getExtension( 'Avatars' );
-               try{
-                       $sNewPath = $oAvatars->generateAvatar( $user, array(), 
true );
-               } catch( Exception $e ) {
-                       wfDebugLog(
-                               'BS::Avatars',
-                               'onLocalUserCreated: Error: '.$e->getMessage()
-                       );
-               }
-               return true;
-       }
-
-       /**
-        * Create an initial Avatar
-        * @param UserManager $oUserManager
-        * @param User $oUser
-        * @param array $aMetaData
-        * @param Status $oStatus
-        * @param User $oPerformer
-        * @return boolean
-        */
-       public static function onBSUserManagerAfterAddUser( $oUserManager, 
$oUser, $aMetaData, &$oStatus, $oPerformer ) {
-               $oAvatars = BsExtensionManager::getExtension( 'Avatars' );
-               try{
-                       $sNewPath = $oAvatars->generateAvatar( $oUser, array(), 
true );
-               } catch( Exception $e ) {
-                       wfDebugLog(
-                               'BS::Avatars',
-                               'onBSUserManagerAfterAddUser: Error: 
'.$e->getMessage()
-                       );
-               }
-               return true;
-       }
-
-       /**
-        * UnitTestsList allows registration of additional test suites to 
execute
-        * under PHPUnit. Extensions can append paths to files to the $paths 
array,
-        * and since MediaWiki 1.24, can specify paths to directories, which 
will
-        * be scanned recursively for any test case files with the suffix 
"Test.php".
-        * @param array $paths
-        */
-       public static function onUnitTestsList( array &$paths ) {
-               $paths[] = __DIR__ . '/tests/phpunit/';
-               return true;
-       }
-}
diff --git a/Avatars.php b/Avatars.php
new file mode 100644
index 0000000..a1dc32c
--- /dev/null
+++ b/Avatars.php
@@ -0,0 +1,126 @@
+<?php
+
+/**
+ * Avatars extension for BlueSpice
+ *
+ * Provide generic and individual user images
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * This file is part of BlueSpice MediaWiki
+ * For further information visit http://www.bluespice.com
+ *
+ * @author     Marc Reymann <[email protected]>
+ * @version    3.0.0
+ * @package    BlueSpiceAvatars
+ * @subpackage Avatars
+ * @copyright  Copyright (C) 2016 Hallo Welt! GmbH, All rights reserved.
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU Public License v2 or 
later
+ * @filesource
+ */
+
+/**
+ * Base class for the Avatars extension
+ * @package BlueSpiceAvatars
+ * @subpackage Avatars
+ */
+class Avatars extends \BlueSpice\Extension {
+
+       /**
+        * extension.json callback
+        * @global array $wgForeignFileRepos
+        */
+       public static function onRegistration() {
+               global $wgForeignFileRepos;
+               if ( version_compare( $GLOBALS['wgVersion'], '1.28c', '>' ) ) {
+                       $wgForeignFileRepos[] = array(
+                               'class' => 'FileRepo',
+                               'name' => 'Avatars',
+                               'directory' => BS_DATA_DIR . '/Avatars/',
+                               'hashLevels' => 0,
+                               'url' => BS_DATA_PATH . '/Avatars',
+                       );
+               } else {
+                       $wgForeignFileRepos[] = array(
+                               'class' => 'FSRepo',
+                               'name' => 'Avatars',
+                               'directory' => BS_DATA_DIR . '/Avatars/',
+                               'hashLevels' => 0,
+                               'url' => BS_DATA_PATH . '/Avatars',
+                       );
+               }
+       }
+
+       /**
+        * DEPRECATED - Use new \BlueSpice\Avatars\Generator()->getAvatarFile()
+        * instread
+        * Gets Avatar file from user ID
+        * @deprecated since version 3.0.0
+        * @param int $iUserId
+        * @return boolean|\File
+        */
+       public static function getAvatarFile( $iUserId ) {
+               $config = \BsExtensionManager::getExtension(
+                       'BlueSpiceAvatars'
+               )->getConfig();
+               $avatarGenerator = new \BlueSpice\Avatars\Generator( $config );
+               return $avatarGenerator->getAvatarFile( \User::newFromId( 
$iUserId ) );
+       }
+
+       /**
+        * Clears a user's UserImage setting
+        * @param User $oUser
+        */
+       public static function unsetUserImage($oUser) {
+               if( $oUser->getOption( 'MW::UserImage' ) ) {
+                       $oUser->setOption( 'MW::UserImage', false );
+                       $oUser->saveSettings();
+                       $oUser->invalidateCache();
+               }
+               return;
+       }
+
+       /**
+        * DEPRECATED - Use new \BlueSpice\Avatars\Generator()->generate() 
instread
+        * Generate an avatar image
+        * @deprecated since version 3.0.0
+        * @param User $oUser
+        * @return string Relative URL to avatar image
+        */
+       public function generateAvatar( $oUser, $aParams = array(), $bOverwrite 
= false ) {
+               wfDeprecated( __METHOD__, "3.0.0" );
+               $config = \BsExtensionManager::getExtension(
+                       'BlueSpiceAvatars'
+               )->getConfig();
+               $avatarGenerator = new \BlueSpice\Avatars\Generator( $config );
+
+               if( $bOverwrite ) {
+                       $aParams[\BlueSpice\Avatars\Generator::PARAM_OVERWRITE] 
= true;
+               }
+               return $avatarGenerator->generate( $oUser, $aParams );
+       }
+
+       /**
+        * UnitTestsList allows registration of additional test suites to 
execute
+        * under PHPUnit. Extensions can append paths to files to the $paths 
array,
+        * and since MediaWiki 1.24, can specify paths to directories, which 
will
+        * be scanned recursively for any test case files with the suffix 
"Test.php".
+        * @param array $paths
+        */
+       public static function onUnitTestsList( array &$paths ) {
+               $paths[] = __DIR__ . '/tests/phpunit/';
+               return true;
+       }
+}
diff --git a/composer.json b/composer.json
index 2461e1b..01af609 100644
--- a/composer.json
+++ b/composer.json
@@ -8,6 +8,7 @@
        },
        "autoload": {
                "psr-4": {
+                       "BlueSpice\\Avatars\\" : "src"
                }
        }
 }
\ No newline at end of file
diff --git a/extension.json b/extension.json
index 9b19712..ea71092 100644
--- a/extension.json
+++ b/extension.json
@@ -2,13 +2,20 @@
        "name": "BlueSpiceAvatars",
        "version": "2.27.1-alpha",
        "url": "https://help.bluespice.com/index.php/Avatars";,
-       "author": "Marc Reymann",
+       "author": [
+               "Marc Reymann",
+               "Patric Wirth"
+       ],
        "descriptionmsg": "bs-avatars-desc",
        "type": "bluespice",
        "bsgExtensions": {
                "BlueSpiceAvatars": {
                        "className": "Avatars",
-                       "extPath": "/BlueSpiceAvatars"
+                       "extPath": "/BlueSpiceAvatars",
+                       "configDefinitions": {
+                               "AvatarsDefaultSize": 
"\\BlueSpice\\Avatars\\ConfigDefinition\\AvatarsDefaultSize::getInstance",
+                               "AvatarsGenerator": 
"\\BlueSpice\\Avatars\\ConfigDefinition\\AvatarsGenerator::getInstance"
+                       }
                }
        },
        "callback": "Avatars::onRegistration",
@@ -21,13 +28,16 @@
                ]
        },
        "AutoloadClasses": {
-               "Avatars": "Avatars.class.php",
+               "Avatars": "Avatars.php",
                "BSApiAvatarsTasks": "includes/api/BSApiAvatarsTasks.php"
        },
        "ResourceModules": {
                "ext.bluespice.avatars.js": {
                        "scripts": [
                                "bluespice.avatars.js"
+                       ],
+                       "dependencies": [
+                               "ext.bluespice.extjs"
                        ],
                        "messages": [
                                "bs-avatars-upload-title",
@@ -49,11 +59,19 @@
                "localBasePath": "resources",
                "remoteExtPath": "BlueSpiceAvatars/resources"
        },
+       "config_prefix": "bsg",
+       "config": {
+               "AvatarsDefaultSize": {
+                       "value": 40
+               },
+               "AvatarsGenerator": {
+                       "value": "InstantAvatar"
+               }
+       },
        "Hooks": {
-               "BeforePageDisplay": "Avatars::onBeforePageDisplay",
-               "BSUserManagerAfterAddUser": 
"Avatars::onBSUserManagerAfterAddUser",
-               "LocalUserCreated": "Avatars::onLocalUserCreated",
-               "UnitTestsList": "Avatars::onUnitTestsList"
+               "BeforePageDisplay": 
"\\BlueSpice\\Avatars\\Hook\\BeforePageDisplay\\AddModules::callback",
+               "UnitTestsList": "Avatars::onUnitTestsList",
+               "BSCoreGetUserMiniProfileBeforeInit": 
"\\BlueSpice\\Avatars\\Hook\\BSCoreGetUserMiniProfileBeforeInit\\SetAvatar::callback"
        },
        "load_composer_autoloader": true,
        "manifest_version": 1
diff --git a/includes/api/BSApiAvatarsTasks.php 
b/includes/api/BSApiAvatarsTasks.php
index d717219..afa244e 100644
--- a/includes/api/BSApiAvatarsTasks.php
+++ b/includes/api/BSApiAvatarsTasks.php
@@ -1,5 +1,7 @@
 <?php
 
+use BlueSpice\Avatars\Generator;
+
 class BSApiAvatarsTasks extends BSApiTasksBase {
 
        protected $aTasks = array(
@@ -41,7 +43,7 @@
                $oUser = $this->getUser();
                Avatars::unsetUserImage( $oUser );
                $oAvatars = BsExtensionManager::getExtension( 'Avatars' );
-               $sAvatarFileName = Avatars::$sAvatarFilePrefix . 
$oUser->getId() . ".png";
+               $sAvatarFileName = Generator::FILE_PREFIX . $oUser->getId() . 
".png";
                $oStatus = BsFileSystemHelper::uploadAndConvertImage(
                        $this->getRequest()->getVal( 'name' ),
                        'Avatars',
@@ -88,8 +90,8 @@
 
                $oUser = $this->getUser();
                Avatars::unsetUserImage($oUser);
-               $oAvatars = BsExtensionManager::getExtension( 'Avatars' );
-               $sNewPath = $oAvatars->generateAvatar( $oUser, array(), true );
+               $generator = new Generator( $this->getConfig() );
+               $generator->generate( $oUser, [], true );
 
                $oResponse->success = true;
                $oResponse->message = wfMessage( 'bs-avatars-generate-complete' 
)->plain();
diff --git a/src/ConfigDefinition/AvatarsDefaultSize.php 
b/src/ConfigDefinition/AvatarsDefaultSize.php
new file mode 100644
index 0000000..1884a2e
--- /dev/null
+++ b/src/ConfigDefinition/AvatarsDefaultSize.php
@@ -0,0 +1,14 @@
+<?php
+
+namespace BlueSpice\Avatars\ConfigDefinition;
+
+class AvatarsDefaultSize extends \BlueSpice\ConfigDefinition\IntSetting {
+
+       public function getLabelMessageKey() {
+               return 'bs-avatars-pref-defaultsize';
+       }
+
+       public function isStored() {
+               return true;
+       }
+}
diff --git a/src/ConfigDefinition/AvatarsGenerator.php 
b/src/ConfigDefinition/AvatarsGenerator.php
new file mode 100644
index 0000000..399d200
--- /dev/null
+++ b/src/ConfigDefinition/AvatarsGenerator.php
@@ -0,0 +1,18 @@
+<?php
+
+namespace BlueSpice\Avatars\ConfigDefinition;
+
+class AvatarsGenerator extends \BlueSpice\ConfigDefinition\ArraySetting {
+
+       public function getHtmlFormField() {
+               return new \HTMLSelectField( $this->makeFormFieldParams() );
+       }
+
+       public function getLabelMessageKey() {
+               return 'bs-avatars-pref-generator';
+       }
+
+       public function isStored() {
+               return true;
+       }
+}
diff --git a/src/Generator.php b/src/Generator.php
new file mode 100644
index 0000000..01dbfdb
--- /dev/null
+++ b/src/Generator.php
@@ -0,0 +1,146 @@
+<?php
+
+namespace BlueSpice\Avatars;
+
+class Generator {
+       const FILE_PREFIX = "BS_avatar_";
+
+       const PARAM_OVERWRITE = 'overwrite';
+       const PARAM_HEIGHT = 'height';
+       const PARAM_WIDTH = 'width';
+
+       /**
+        *
+        * @var \Config
+        */
+       protected $config = null;
+
+       /**
+        *
+        * @param \Contig $contig
+        */
+       public function __construct( $contig ) {
+               $this->config = $contig;
+       }
+
+       /**
+        *
+        * @param \User $user
+        * @param array $params
+        * @return string
+        */
+       public function generate( \User $user, array $params = [] ) {
+               $defaultSize = 1024;
+
+               if( !$oFile = $this->getAvatarFile( $user ) ) {
+                       return '';
+               }
+
+               if( !$oFile->exists() || isset( 
$params[static::PARAM_OVERWRITE] ) ) {
+                       switch( $this->config->get( 'AvatarsGenerator' ) ) {
+                               case 'Identicon':
+                                       $rawPNGAvatar = $this->generateIdention(
+                                               $user,
+                                               $defaultSize
+                                       );
+                                       break;
+                               case 'InstantAvatar':
+                                       $rawPNGAvatar = 
$this->generateInstantAvatar(
+                                               $user,
+                                               $defaultSize
+                                       );
+                                       break;
+                               default:
+                                       throw new MWException(
+                                               'FATAL: Avatar generator not 
found!'
+                                       );
+                       }
+
+                       $status = \BsFileSystemHelper::saveToDataDirectory(
+                               $oFile->getName(),
+                               $rawPNGAvatar,
+                               'Avatars'
+                       );
+                       if ( !$status->isGood() ) {
+                               throw new MWException(
+                                       'FATAL: Avatar could not be saved! 
'.$status->getMessage()
+                               );
+                       }
+                       # Delete thumb folder if it exists
+                       $status = \BsFileSystemHelper::deleteFolder(
+                               'Avatars' . DS . 'thumb' . DS . 
$oFile->getName(),
+                               true
+                       );
+                       if( !$status->isGood() ) {
+                               throw new MWException(
+                                       'FATAL: Avatar thumbs could no be 
deleted!'
+                               );
+                       }
+                       $oFile = \BsFileSystemHelper::getFileFromRepoName(
+                               $oFile->getName(),
+                               'Avatars'
+                       );
+
+                       $user->invalidateCache();
+               }
+
+               $iAvatarHeight = empty( $params[static::PARAM_HEIGHT] )
+                       ? $this->config->get( 'AvatarsDefaultSize' )
+                       : $params[static::PARAM_HEIGHT]
+               ;
+
+               $iAvatarWidth = empty( $params[static::PARAM_WIDTH] )
+                       ? $this->config->get( 'AvatarsDefaultSize' )
+                       : $params[static::PARAM_WIDTH]
+               ;
+
+               return $oFile->createThumb( $iAvatarWidth, $iAvatarHeight );
+       }
+
+       protected function generateIdention( \User $user, $size ) {
+               require_once dirname( __DIR__ ) . 
"/includes/lib/Identicon/identicon.php";
+               return generateIdenticon( $user->getId(), $size );
+       }
+
+       protected function generateInstantAvatar( \User $user, $size ) {
+               $dir = dirname( __DIR__ ) . "/includes/lib/InstantAvatar";
+               require_once "$dir/instantavatar.php";
+
+               $instantAvatar = new \InstantAvatar(
+                       "$dir/Comfortaa-Regular.ttf",
+                       round( 18 / 40 * $size ),
+                       $size,
+                       $size,
+                       2,
+                       "$dir/glass.png"
+               );
+
+               if( !empty( $user->getRealName() ) ) {
+                       preg_match_all(
+                               '#(^| )(.)#u',
+                               $user->getRealName(),
+                               $matches
+                       );
+                       $chars = implode( '', $matches[2] );
+                       if( mb_strlen( $chars ) < 2 )
+                               $chars = $user->getRealName();
+               }
+               else {
+                       $chars = $user->getName();
+               }
+               $instantAvatar->generateRandom( $chars );
+               return $instantAvatar->getRawPNG();
+       }
+
+       /**
+        * Gets Avatar file from user ID
+        * @param \User $user
+        * @return boolean|\File
+        */
+       public function getAvatarFile( \User $user ) {
+               return \BsFileSystemHelper::getFileFromRepoName(
+                       static::FILE_PREFIX . $user->getId() . ".png",
+                       'Avatars'
+               );
+       }
+}
diff --git a/src/Hook/BSCoreGetUserMiniProfileBeforeInit/SetAvatar.php 
b/src/Hook/BSCoreGetUserMiniProfileBeforeInit/SetAvatar.php
new file mode 100644
index 0000000..904ed85
--- /dev/null
+++ b/src/Hook/BSCoreGetUserMiniProfileBeforeInit/SetAvatar.php
@@ -0,0 +1,36 @@
+<?php
+
+namespace BlueSpice\Avatars\Hook\BSCoreGetUserMiniProfileBeforeInit;
+use BlueSpice\Hook\BSCoreGetUserMiniProfileBeforeInit;
+use BlueSpice\Avatars\Generator;
+
+/**
+ * Set avatar image if user has no UserImage setting
+ */
+class SetAvatar extends BSCoreGetUserMiniProfileBeforeInit {
+
+       protected function skipProcessing() {
+               if( $this->user->isAnon() ) {
+                       return true;
+               }
+               if( !empty( $this->user->getOption( 'MW::UserImage' ) ) ) {
+                       return true;
+               }
+               if( wfReadOnly() ) {
+                       return true;
+               }
+
+               return false;
+       }
+
+       protected function doProcess() {
+               $generator = new Generator( $this->getConfig() );
+               $this->userMiniProfileView->setUserImageSrc( 
$generator->generate(
+                       $this->user,
+                       $this->params
+               ));
+
+               return true;
+       }
+
+}
\ No newline at end of file
diff --git a/src/Hook/BeforePageDisplay/AddModules.php 
b/src/Hook/BeforePageDisplay/AddModules.php
new file mode 100644
index 0000000..66f52a1
--- /dev/null
+++ b/src/Hook/BeforePageDisplay/AddModules.php
@@ -0,0 +1,26 @@
+<?php
+
+namespace BlueSpice\Avatars\Hook\BeforePageDisplay;
+use BlueSpice\Hook\BeforePageDisplay;
+/**
+ * Adds style and script modules
+ */
+class AddModules extends BeforePageDisplay {
+
+       protected function skipProcessing() {
+               $user = $this->out->getUser();
+               if( !$user || $user->isAnon() ) {
+                       return true;
+               }
+               if( !$this->out->getTitle()->equals( $user->getUserPage() ) ) {
+                       return true;
+               }
+
+               return false;
+       }
+
+       protected function doProcess() {
+               $this->out->addModules( "ext.bluespice.avatars.js" );
+       }
+
+}
\ No newline at end of file

-- 
To view, visit https://gerrit.wikimedia.org/r/388498
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: merged
Gerrit-Change-Id: Iba259cb1c976046895e23cb93a1c8a46f803c560
Gerrit-PatchSet: 4
Gerrit-Project: mediawiki/extensions/BlueSpiceAvatars
Gerrit-Branch: master
Gerrit-Owner: Pwirth <[email protected]>
Gerrit-Reviewer: Ljonka <[email protected]>
Gerrit-Reviewer: Mglaser <[email protected]>
Gerrit-Reviewer: Robert Vogel <[email protected]>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to