4 * Caches user genders when needed to use correct namespace aliases.
5 * @author Niklas Laxström
9 protected $cache = array();
11 protected $misses = 0;
12 protected $missLimit = 1000;
14 public static function singleton() {
16 if ( $that === null ) {
22 protected function __construct() {}
25 * Returns the default gender option in this wiki.
28 protected function getDefault() {
29 if ( $this->default === null ) {
30 $this->default = User
::getDefaultOption( 'gender' );
32 return $this->default;
36 * Returns the gender for given username.
37 * @param $users String: username
38 * @param $caller String: the calling method
41 public function getGenderOf( $username, $caller = '' ) {
44 $username = strtr( $username, '_', ' ' );
45 if ( !isset( $this->cache
[$username] ) ) {
47 if ( $this->misses
>= $this->missLimit
&& $wgUser->getName() !== $username ) {
48 if( $this->misses
=== $this->missLimit
) {
50 wfDebug( __METHOD__
. ": too many misses, returning default onwards\n" );
52 return $this->getDefault();
56 if ( !User
::isValidUserName( $username ) ) {
57 $this->cache
[$username] = $this->getDefault();
59 $this->doQuery( $username, $caller );
65 /* Undefined if there is a valid username which for some reason doesn't
66 * exist in the database.
68 return isset( $this->cache
[$username] ) ?
$this->cache
[$username] : $this->getDefault();
72 * Wrapper for doQuery that processes raw LinkBatch data.
74 public function doLinkBatch( $data, $caller = '' ) {
76 foreach ( $data as $ns => $pagenames ) {
77 if ( !MWNamespace
::hasGenderDistinction( $ns ) ) continue;
78 foreach ( array_keys( $pagenames ) as $username ) {
79 if ( isset( $this->cache
[$username] ) ) continue;
80 $users[$username] = true;
84 $this->doQuery( array_keys( $users ), $caller );
89 * Preloads genders for given list of users.
90 * @param $users List|String: usernames
91 * @param $caller String: the calling method
93 public function doQuery( $users, $caller = '' ) {
94 if ( count( $users ) === 0 ) {
98 foreach ( (array) $users as $index => $value ) {
99 $users[$index] = strtr( $value, '_', ' ' );
102 $dbr = wfGetDB( DB_SLAVE
);
103 $table = array( 'user', 'user_properties' );
104 $fields = array( 'user_name', 'up_value' );
105 $conds = array( 'user_name' => $users );
106 $joins = array( 'user_properties' =>
107 array( 'LEFT JOIN', array( 'user_id = up_user', 'up_property' => 'gender' ) ) );
109 $comment = __METHOD__
;
110 if ( strval( $caller ) !== '' ) {
111 $comment .= "/$caller";
113 $res = $dbr->select( $table, $fields, $conds, $comment, $joins, $joins );
115 $default = $this->getDefault();
116 foreach ( $res as $row ) {
117 $this->cache
[$row->user_name
] = $row->up_value ?
$row->up_value
: $default;