MediaWiki  master
MemcachedClient.php
Go to the documentation of this file.
1 <?php
2 // phpcs:ignoreFile -- It's an external lib and it isn't. Let's not bother.
71 
72 // {{{ class MemcachedClient
80  // {{{ properties
81  // {{{ public
82 
83  // {{{ constants
84  // {{{ flags
85 
89  const SERIALIZED = 1;
90 
94  const COMPRESSED = 2;
95 
99  const INTVAL = 4;
100 
101  // }}}
102 
106  const COMPRESSION_SAVINGS = 0.20;
107 
108  // }}}
109 
116  public $stats;
117 
118  // }}}
119  // {{{ private
120 
127  public $_cache_sock;
128 
135  public $_debug;
136 
143  public $_host_dead;
144 
151  public $_have_zlib;
152 
160 
168 
175  public $_persistent;
176 
184 
191  public $_servers;
192 
199  public $_buckets;
200 
208 
215  public $_active;
216 
224 
232 
237 
242 
246  private $_logger;
247 
248  // }}}
249  // }}}
250  // {{{ methods
251  // {{{ public functions
252  // {{{ memcached()
253 
259  public function __construct( $args ) {
260  $this->set_servers( $args['servers'] ?? array() );
261  $this->_debug = $args['debug'] ?? false;
262  $this->stats = array();
263  $this->_compress_threshold = $args['compress_threshold'] ?? 0;
264  $this->_persistent = $args['persistent'] ?? false;
265  $this->_compress_enable = true;
266  $this->_have_zlib = function_exists( 'gzcompress' );
267 
268  $this->_cache_sock = array();
269  $this->_host_dead = array();
270 
271  $this->_timeout_seconds = 0;
272  $this->_timeout_microseconds = $args['timeout'] ?? 500000;
273 
274  $this->_connect_timeout = $args['connect_timeout'] ?? 0.1;
275  $this->_connect_attempts = 2;
276 
277  $this->_logger = $args['logger'] ?? new NullLogger();
278  }
279 
280  // }}}
281 
286  public function serialize( $value ) {
287  return serialize( $value );
288  }
289 
294  public function unserialize( $value ) {
295  return unserialize( $value );
296  }
297 
298  // {{{ add()
299 
314  public function add( $key, $val, $exp = 0 ) {
315  return $this->_set( 'add', $key, $val, $exp );
316  }
317 
318  // }}}
319  // {{{ decr()
320 
329  public function decr( $key, $amt = 1 ) {
330  return $this->_incrdecr( 'decr', $key, $amt );
331  }
332 
333  // }}}
334  // {{{ delete()
335 
344  public function delete( $key, $time = 0 ) {
345  if ( !$this->_active ) {
346  return false;
347  }
348 
349  $sock = $this->get_sock( $key );
350  if ( !is_resource( $sock ) ) {
351  return false;
352  }
353 
354  $key = is_array( $key ) ? $key[1] : $key;
355 
356  if ( isset( $this->stats['delete'] ) ) {
357  $this->stats['delete']++;
358  } else {
359  $this->stats['delete'] = 1;
360  }
361  $cmd = "delete $key $time\r\n";
362  if ( !$this->_fwrite( $sock, $cmd ) ) {
363  return false;
364  }
365  $res = $this->_fgets( $sock );
366 
367  if ( $this->_debug ) {
368  $this->_debugprint( sprintf( "MemCache: delete %s (%s)", $key, $res ) );
369  }
370 
371  if ( $res == "DELETED" || $res == "NOT_FOUND" ) {
372  return true;
373  }
374 
375  return false;
376  }
377 
386  public function touch( $key, $time = 0 ) {
387  if ( !$this->_active ) {
388  return false;
389  }
390 
391  $sock = $this->get_sock( $key );
392  if ( !is_resource( $sock ) ) {
393  return false;
394  }
395 
396  $key = is_array( $key ) ? $key[1] : $key;
397 
398  if ( isset( $this->stats['touch'] ) ) {
399  $this->stats['touch']++;
400  } else {
401  $this->stats['touch'] = 1;
402  }
403  $cmd = "touch $key $time\r\n";
404  if ( !$this->_fwrite( $sock, $cmd ) ) {
405  return false;
406  }
407  $res = $this->_fgets( $sock );
408 
409  if ( $this->_debug ) {
410  $this->_debugprint( sprintf( "MemCache: touch %s (%s)", $key, $res ) );
411  }
412 
413  if ( $res == "TOUCHED" ) {
414  return true;
415  }
416 
417  return false;
418  }
419 
425  public function lock( $key, $timeout = 0 ) {
426  /* stub */
427  return true;
428  }
429 
434  public function unlock( $key ) {
435  /* stub */
436  return true;
437  }
438 
439  // }}}
440  // {{{ disconnect_all()
441 
445  public function disconnect_all() {
446  foreach ( $this->_cache_sock as $sock ) {
447  fclose( $sock );
448  }
449 
450  $this->_cache_sock = array();
451  }
452 
453  // }}}
454  // {{{ enable_compress()
455 
461  public function enable_compress( $enable ) {
462  $this->_compress_enable = $enable;
463  }
464 
465  // }}}
466  // {{{ forget_dead_hosts()
467 
471  public function forget_dead_hosts() {
472  $this->_host_dead = array();
473  }
474 
475  // }}}
476  // {{{ get()
477 
486  public function get( $key, &$casToken = null ) {
487  if ( $this->_debug ) {
488  $this->_debugprint( "get($key)" );
489  }
490 
491  if ( !is_array( $key ) && strval( $key ) === '' ) {
492  $this->_debugprint( "Skipping key which equals to an empty string" );
493  return false;
494  }
495 
496  if ( !$this->_active ) {
497  return false;
498  }
499 
500  $sock = $this->get_sock( $key );
501 
502  if ( !is_resource( $sock ) ) {
503  return false;
504  }
505 
506  $key = is_array( $key ) ? $key[1] : $key;
507  if ( isset( $this->stats['get'] ) ) {
508  $this->stats['get']++;
509  } else {
510  $this->stats['get'] = 1;
511  }
512 
513  $cmd = "gets $key\r\n";
514  if ( !$this->_fwrite( $sock, $cmd ) ) {
515  return false;
516  }
517 
518  $val = array();
519  $this->_load_items( $sock, $val, $casToken );
520 
521  if ( $this->_debug ) {
522  foreach ( $val as $k => $v ) {
523  $this->_debugprint(
524  sprintf( "MemCache: sock %s got %s", $this->serialize( $sock ), $k ) );
525  }
526  }
527 
528  $value = false;
529  if ( isset( $val[$key] ) ) {
530  $value = $val[$key];
531  }
532  return $value;
533  }
534 
535  // }}}
536  // {{{ get_multi()
537 
545  public function get_multi( $keys ) {
546  if ( !$this->_active ) {
547  return array();
548  }
549 
550  if ( isset( $this->stats['get_multi'] ) ) {
551  $this->stats['get_multi']++;
552  } else {
553  $this->stats['get_multi'] = 1;
554  }
555  $sock_keys = array();
556  $socks = array();
557  foreach ( $keys as $key ) {
558  $sock = $this->get_sock( $key );
559  if ( !is_resource( $sock ) ) {
560  continue;
561  }
562  $key = is_array( $key ) ? $key[1] : $key;
563  if ( !isset( $sock_keys[$sock] ) ) {
564  $sock_keys[intval( $sock )] = array();
565  $socks[] = $sock;
566  }
567  $sock_keys[intval( $sock )][] = $key;
568  }
569 
570  $gather = array();
571  // Send out the requests
572  foreach ( $socks as $sock ) {
573  $cmd = 'gets';
574  foreach ( $sock_keys[intval( $sock )] as $key ) {
575  $cmd .= ' ' . $key;
576  }
577  $cmd .= "\r\n";
578 
579  if ( $this->_fwrite( $sock, $cmd ) ) {
580  $gather[] = $sock;
581  }
582  }
583 
584  // Parse responses
585  $val = array();
586  foreach ( $gather as $sock ) {
587  $this->_load_items( $sock, $val, $casToken );
588  }
589 
590  if ( $this->_debug ) {
591  foreach ( $val as $k => $v ) {
592  $this->_debugprint( sprintf( "MemCache: got %s", $k ) );
593  }
594  }
595 
596  return $val;
597  }
598 
599  // }}}
600  // {{{ incr()
601 
612  public function incr( $key, $amt = 1 ) {
613  return $this->_incrdecr( 'incr', $key, $amt );
614  }
615 
616  // }}}
617  // {{{ replace()
618 
632  public function replace( $key, $value, $exp = 0 ) {
633  return $this->_set( 'replace', $key, $value, $exp );
634  }
635 
636  // }}}
637  // {{{ run_command()
638 
648  public function run_command( $sock, $cmd ) {
649  if ( !is_resource( $sock ) ) {
650  return array();
651  }
652 
653  if ( !$this->_fwrite( $sock, $cmd ) ) {
654  return array();
655  }
656 
657  $ret = array();
658  while ( true ) {
659  $res = $this->_fgets( $sock );
660  $ret[] = $res;
661  if ( preg_match( '/^END/', $res ) ) {
662  break;
663  }
664  if ( strlen( $res ) == 0 ) {
665  break;
666  }
667  }
668  return $ret;
669  }
670 
671  // }}}
672  // {{{ set()
673 
688  public function set( $key, $value, $exp = 0 ) {
689  return $this->_set( 'set', $key, $value, $exp );
690  }
691 
692  // }}}
693  // {{{ cas()
694 
710  public function cas( $casToken, $key, $value, $exp = 0 ) {
711  return $this->_set( 'cas', $key, $value, $exp, $casToken );
712  }
713 
714  // }}}
715  // {{{ set_compress_threshold()
716 
722  public function set_compress_threshold( $thresh ) {
723  $this->_compress_threshold = $thresh;
724  }
725 
726  // }}}
727  // {{{ set_debug()
728 
735  public function set_debug( $dbg ) {
736  $this->_debug = $dbg;
737  }
738 
739  // }}}
740  // {{{ set_servers()
741 
748  public function set_servers( $list ) {
749  $this->_servers = $list;
750  $this->_active = count( $list );
751  $this->_buckets = null;
752  $this->_bucketcount = 0;
753 
754  $this->_single_sock = null;
755  if ( $this->_active == 1 ) {
756  $this->_single_sock = $this->_servers[0];
757  }
758  }
759 
766  public function set_timeout( $seconds, $microseconds ) {
767  $this->_timeout_seconds = $seconds;
768  $this->_timeout_microseconds = $microseconds;
769  }
770 
771  // }}}
772  // }}}
773  // {{{ private methods
774  // {{{ _close_sock()
775 
783  function _close_sock( $sock ) {
784  $host = array_search( $sock, $this->_cache_sock );
785  fclose( $this->_cache_sock[$host] );
786  unset( $this->_cache_sock[$host] );
787  }
788 
789  // }}}
790  // {{{ _connect_sock()
791 
801  function _connect_sock( &$sock, $host ) {
802  list( $ip, $port ) = preg_split( '/:(?=\d)/', $host );
803  $sock = false;
804  $timeout = $this->_connect_timeout;
805  $errno = $errstr = null;
806  for ( $i = 0; !$sock && $i < $this->_connect_attempts; $i++ ) {
807  Wikimedia\suppressWarnings();
808  if ( $this->_persistent == 1 ) {
809  $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
810  } else {
811  $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
812  }
813  Wikimedia\restoreWarnings();
814  }
815  if ( !$sock ) {
816  $this->_error_log( "Error connecting to $host: $errstr" );
817  $this->_dead_host( $host );
818  return false;
819  }
820 
821  // Initialise timeout
822  stream_set_timeout( $sock, $this->_timeout_seconds, $this->_timeout_microseconds );
823 
824  // If the connection was persistent, flush the read buffer in case there
825  // was a previous incomplete request on this connection
826  if ( $this->_persistent ) {
827  $this->_flush_read_buffer( $sock );
828  }
829  return true;
830  }
831 
832  // }}}
833  // {{{ _dead_sock()
834 
842  function _dead_sock( $sock ) {
843  $host = array_search( $sock, $this->_cache_sock );
844  $this->_dead_host( $host );
845  }
846 
850  function _dead_host( $host ) {
851  $ip = explode( ':', $host )[0];
852  $this->_host_dead[$ip] = time() + 30 + intval( rand( 0, 10 ) );
853  $this->_host_dead[$host] = $this->_host_dead[$ip];
854  unset( $this->_cache_sock[$host] );
855  }
856 
857  // }}}
858  // {{{ get_sock()
859 
868  function get_sock( $key ) {
869  if ( !$this->_active ) {
870  return false;
871  }
872 
873  if ( $this->_single_sock !== null ) {
874  return $this->sock_to_host( $this->_single_sock );
875  }
876 
877  $hv = is_array( $key ) ? intval( $key[0] ) : $this->_hashfunc( $key );
878  if ( $this->_buckets === null ) {
879  $bu = array();
880  foreach ( $this->_servers as $v ) {
881  if ( is_array( $v ) ) {
882  for ( $i = 0; $i < $v[1]; $i++ ) {
883  $bu[] = $v[0];
884  }
885  } else {
886  $bu[] = $v;
887  }
888  }
889  $this->_buckets = $bu;
890  $this->_bucketcount = count( $bu );
891  }
892 
893  $realkey = is_array( $key ) ? $key[1] : $key;
894  for ( $tries = 0; $tries < 20; $tries++ ) {
895  $host = $this->_buckets[$hv % $this->_bucketcount];
896  $sock = $this->sock_to_host( $host );
897  if ( is_resource( $sock ) ) {
898  return $sock;
899  }
900  $hv = $this->_hashfunc( $hv . $realkey );
901  }
902 
903  return false;
904  }
905 
906  // }}}
907  // {{{ _hashfunc()
908 
917  function _hashfunc( $key ) {
918  # Hash function must be in [0,0x7ffffff]
919  # We take the first 31 bits of the MD5 hash, which unlike the hash
920  # function used in a previous version of this client, works
921  return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
922  }
923 
924  // }}}
925  // {{{ _incrdecr()
926 
937  function _incrdecr( $cmd, $key, $amt = 1 ) {
938  if ( !$this->_active ) {
939  return null;
940  }
941 
942  $sock = $this->get_sock( $key );
943  if ( !is_resource( $sock ) ) {
944  return null;
945  }
946 
947  $key = is_array( $key ) ? $key[1] : $key;
948  if ( isset( $this->stats[$cmd] ) ) {
949  $this->stats[$cmd]++;
950  } else {
951  $this->stats[$cmd] = 1;
952  }
953  if ( !$this->_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
954  return null;
955  }
956 
957  $line = $this->_fgets( $sock );
958  $match = array();
959  if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
960  return null;
961  }
962  return $match[1];
963  }
964 
965  // }}}
966  // {{{ _load_items()
967 
978  function _load_items( $sock, &$ret, &$casToken = null ) {
979  $results = array();
980 
981  while ( 1 ) {
982  $decl = $this->_fgets( $sock );
983 
984  if ( $decl === false ) {
985  /*
986  * If nothing can be read, something is wrong because we know exactly when
987  * to stop reading (right after "END") and we return right after that.
988  */
989  return false;
990  } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+) (\d+)$/', $decl, $match ) ) {
991  /*
992  * Read all data returned. This can be either one or multiple values.
993  * Save all that data (in an array) to be processed later: we'll first
994  * want to continue reading until "END" before doing anything else,
995  * to make sure that we don't leave our client in a state where it's
996  * output is not yet fully read.
997  */
998  $results[] = array(
999  $match[1], // rkey
1000  $match[2], // flags
1001  $match[3], // len
1002  $match[4], // casToken
1003  $this->_fread( $sock, $match[3] + 2 ), // data
1004  );
1005  } elseif ( $decl == "END" ) {
1006  if ( count( $results ) == 0 ) {
1007  return false;
1008  }
1009 
1014  foreach ( $results as $vars ) {
1015  list( $rkey, $flags, $len, $casToken, $data ) = $vars;
1016 
1017  if ( $data === false || substr( $data, -2 ) !== "\r\n" ) {
1018  $this->_handle_error( $sock,
1019  'line ending missing from data block from $1' );
1020  return false;
1021  }
1022  $data = substr( $data, 0, -2 );
1023  $ret[$rkey] = $data;
1024 
1025  if ( $this->_have_zlib && $flags & self::COMPRESSED ) {
1026  $ret[$rkey] = gzuncompress( $ret[$rkey] );
1027  }
1028 
1029  /*
1030  * This unserialize is the exact reason that we only want to
1031  * process data after having read until "END" (instead of doing
1032  * this right away): "unserialize" can trigger outside code:
1033  * in the event that $ret[$rkey] is a serialized object,
1034  * unserializing it will trigger __wakeup() if present. If that
1035  * function attempted to read from memcached (while we did not
1036  * yet read "END"), these 2 calls would collide.
1037  */
1038  if ( $flags & self::SERIALIZED ) {
1039  $ret[$rkey] = $this->unserialize( $ret[$rkey] );
1040  } elseif ( $flags & self::INTVAL ) {
1041  $ret[$rkey] = intval( $ret[$rkey] );
1042  }
1043  }
1044 
1045  return true;
1046  } else {
1047  $this->_handle_error( $sock, 'Error parsing response from $1' );
1048  return false;
1049  }
1050  }
1051  }
1052 
1053  // }}}
1054  // {{{ _set()
1055 
1072  function _set( $cmd, $key, $val, $exp, $casToken = null ) {
1073  if ( !$this->_active ) {
1074  return false;
1075  }
1076 
1077  $sock = $this->get_sock( $key );
1078  if ( !is_resource( $sock ) ) {
1079  return false;
1080  }
1081 
1082  if ( isset( $this->stats[$cmd] ) ) {
1083  $this->stats[$cmd]++;
1084  } else {
1085  $this->stats[$cmd] = 1;
1086  }
1087 
1088  $flags = 0;
1089 
1090  if ( is_int( $val ) ) {
1091  $flags |= self::INTVAL;
1092  } elseif ( !is_scalar( $val ) ) {
1093  $val = $this->serialize( $val );
1094  $flags |= self::SERIALIZED;
1095  if ( $this->_debug ) {
1096  $this->_debugprint( sprintf( "client: serializing data as it is not scalar" ) );
1097  }
1098  }
1099 
1100  $len = strlen( $val );
1101 
1102  if ( $this->_have_zlib && $this->_compress_enable
1103  && $this->_compress_threshold && $len >= $this->_compress_threshold
1104  ) {
1105  $c_val = gzcompress( $val, 9 );
1106  $c_len = strlen( $c_val );
1107 
1108  if ( $c_len < $len * ( 1 - self::COMPRESSION_SAVINGS ) ) {
1109  if ( $this->_debug ) {
1110  $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes", $len, $c_len ) );
1111  }
1112  $val = $c_val;
1113  $len = $c_len;
1114  $flags |= self::COMPRESSED;
1115  }
1116  }
1117 
1118  $command = "$cmd $key $flags $exp $len";
1119  if ( $casToken ) {
1120  $command .= " $casToken";
1121  }
1122 
1123  if ( !$this->_fwrite( $sock, "$command\r\n$val\r\n" ) ) {
1124  return false;
1125  }
1126 
1127  $line = $this->_fgets( $sock );
1128 
1129  if ( $this->_debug ) {
1130  $this->_debugprint( sprintf( "%s %s (%s)", $cmd, $key, $line ) );
1131  }
1132  if ( $line === "STORED" ) {
1133  return true;
1134  } elseif ( $line === "NOT_STORED" && $cmd === "set" ) {
1135  // "Not stored" is always used as the mcrouter response with AllAsyncRoute
1136  return true;
1137  }
1138 
1139  return false;
1140  }
1141 
1142  // }}}
1143  // {{{ sock_to_host()
1144 
1153  function sock_to_host( $host ) {
1154  if ( isset( $this->_cache_sock[$host] ) ) {
1155  return $this->_cache_sock[$host];
1156  }
1157 
1158  $sock = null;
1159  $now = time();
1160  list( $ip, /* $port */) = explode( ':', $host );
1161  if ( isset( $this->_host_dead[$host] ) && $this->_host_dead[$host] > $now ||
1162  isset( $this->_host_dead[$ip] ) && $this->_host_dead[$ip] > $now
1163  ) {
1164  return null;
1165  }
1166 
1167  if ( !$this->_connect_sock( $sock, $host ) ) {
1168  return null;
1169  }
1170 
1171  // Do not buffer writes
1172  stream_set_write_buffer( $sock, 0 );
1173 
1174  $this->_cache_sock[$host] = $sock;
1175 
1176  return $this->_cache_sock[$host];
1177  }
1178 
1182  function _debugprint( $text ) {
1183  $this->_logger->debug( $text );
1184  }
1185 
1189  function _error_log( $text ) {
1190  $this->_logger->error( "Memcached error: $text" );
1191  }
1192 
1200  function _fwrite( $sock, $buf ) {
1201  $bytesWritten = 0;
1202  $bufSize = strlen( $buf );
1203  while ( $bytesWritten < $bufSize ) {
1204  $result = fwrite( $sock, $buf );
1205  $data = stream_get_meta_data( $sock );
1206  if ( $data['timed_out'] ) {
1207  $this->_handle_error( $sock, 'timeout writing to $1' );
1208  return false;
1209  }
1210  // Contrary to the documentation, fwrite() returns zero on error in PHP 5.3.
1211  if ( $result === false || $result === 0 ) {
1212  $this->_handle_error( $sock, 'error writing to $1' );
1213  return false;
1214  }
1215  $bytesWritten += $result;
1216  }
1217 
1218  return true;
1219  }
1220 
1227  function _handle_error( $sock, $msg ) {
1228  $peer = stream_socket_get_name( $sock, true );
1229  if ( strval( $peer ) === '' ) {
1230  $peer = array_search( $sock, $this->_cache_sock );
1231  if ( $peer === false ) {
1232  $peer = '[unknown host]';
1233  }
1234  }
1235  $msg = str_replace( '$1', $peer, $msg );
1236  $this->_error_log( "$msg" );
1237  $this->_dead_sock( $sock );
1238  }
1239 
1248  function _fread( $sock, $len ) {
1249  $buf = '';
1250  while ( $len > 0 ) {
1251  $result = fread( $sock, $len );
1252  $data = stream_get_meta_data( $sock );
1253  if ( $data['timed_out'] ) {
1254  $this->_handle_error( $sock, 'timeout reading from $1' );
1255  return false;
1256  }
1257  if ( $result === false ) {
1258  $this->_handle_error( $sock, 'error reading buffer from $1' );
1259  return false;
1260  }
1261  if ( $result === '' ) {
1262  // This will happen if the remote end of the socket is shut down
1263  $this->_handle_error( $sock, 'unexpected end of file reading from $1' );
1264  return false;
1265  }
1266  $len -= strlen( $result );
1267  $buf .= $result;
1268  }
1269  return $buf;
1270  }
1271 
1279  function _fgets( $sock ) {
1280  $result = fgets( $sock );
1281  // fgets() may return a partial line if there is a select timeout after
1282  // a successful recv(), so we have to check for a timeout even if we
1283  // got a string response.
1284  $data = stream_get_meta_data( $sock );
1285  if ( $data['timed_out'] ) {
1286  $this->_handle_error( $sock, 'timeout reading line from $1' );
1287  return false;
1288  }
1289  if ( $result === false ) {
1290  $this->_handle_error( $sock, 'error reading line from $1' );
1291  return false;
1292  }
1293  if ( substr( $result, -2 ) === "\r\n" ) {
1294  $result = substr( $result, 0, -2 );
1295  } elseif ( substr( $result, -1 ) === "\n" ) {
1296  $result = substr( $result, 0, -1 );
1297  } else {
1298  $this->_handle_error( $sock, 'line ending missing in response from $1' );
1299  return false;
1300  }
1301  return $result;
1302  }
1303 
1308  function _flush_read_buffer( $f ) {
1309  if ( !is_resource( $f ) ) {
1310  return;
1311  }
1312  $r = array( $f );
1313  $w = null;
1314  $e = null;
1315  $n = stream_select( $r, $w, $e, 0, 0 );
1316  while ( $n == 1 && !feof( $f ) ) {
1317  fread( $f, 1024 );
1318  $r = array( $f );
1319  $w = null;
1320  $e = null;
1321  $n = stream_select( $r, $w, $e, 0, 0 );
1322  }
1323  }
1324 
1325  // }}}
1326  // }}}
1327  // }}}
1328 }
1329 
1330 // }}}
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
sock_to_host( $host)
Returns the socket for the host.
array $stats
Command statistics.
memcached client class implemented using (p)fsockopen()
array $_host_dead
Dead hosts, assoc array, &#39;host&#39;=>&#39;unixtime when ok to check again&#39;.
_handle_error( $sock, $msg)
Handle an I/O error.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1982
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
_flush_read_buffer( $f)
Flush the read buffer of a stream.
$command
Definition: cdb.php:65
const INTVAL
Flag: indicates data is an integer.
$value
_close_sock( $sock)
Close the specified socket.
run_command( $sock, $cmd)
Passes through $cmd to the memcache server connected by $sock; returns output as an array (null array...
forget_dead_hosts()
Forget about all of the dead hosts.
$_connect_timeout
Connect timeout in seconds.
_load_items( $sock, &$ret, &$casToken=null)
Load items into $ret from $sock.
get_multi( $keys)
Get multiple keys from the server(s)
disconnect_all()
Disconnects all connected sockets.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1799
decr( $key, $amt=1)
Decrease a value stored on the memcache server.
int $_timeout_microseconds
Stream timeout in microseconds.
__construct( $args)
Memcache initializer.
bool $_have_zlib
Is compression available?
get_sock( $key)
get_sock
_connect_sock(&$sock, $host)
Connects $sock to $host, timing out after $timeout.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
if( $line===false) $args
Definition: cdb.php:64
int $_timeout_seconds
Stream timeout in seconds.
set_compress_threshold( $thresh)
Set the compression threshold.
replace( $key, $value, $exp=0)
Overwrites an existing value for key; only works if key is already set.
int $_compress_threshold
At how many bytes should we compress?
bool $_persistent
Are we using persistent links?
incr( $key, $amt=1)
Increments $key (optionally) by $amt.
lock( $key, $timeout=0)
$res
Definition: database.txt:21
const SERIALIZED
Flag: indicates data is serialized.
set_timeout( $seconds, $microseconds)
Sets the timeout for new connections.
array $_servers
Array containing ip:port or array(ip:port, weight)
set_debug( $dbg)
Set the debug flag.
_hashfunc( $key)
Creates a hash integer based on the $key.
_fread( $sock, $len)
Read the specified number of bytes from a stream.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
bool $_debug
Current debug status; 0 - none to 9 - profiling.
_fwrite( $sock, $buf)
Write to a stream.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
array $_buckets
Our bit buckets.
_dead_sock( $sock)
Marks a host as dead until 30-40 seconds in the future.
_incrdecr( $cmd, $key, $amt=1)
Perform increment/decriment on $key.
string $_single_sock
If only using one server; contains ip:port to connect to.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
int $_active
of total servers we have
cas( $casToken, $key, $value, $exp=0)
Sets a key to a given value in the memcache if the current value still corresponds to a known...
bool $_compress_enable
Do we want to use compression?
enable_compress( $enable)
Enable / Disable compression.
$line
Definition: cdb.php:59
_set( $cmd, $key, $val, $exp, $casToken=null)
Performs the requested storage operation to the memcache server.
$f
Definition: router.php:79
array $_cache_sock
Cached Sockets that are connected.
const COMPRESSED
Flag: indicates data is compressed.
set_servers( $list)
Set the server list to distribute key gets and puts between.
const COMPRESSION_SAVINGS
Minimum savings to store data compressed.
_fgets( $sock)
Read a line from a stream.
add( $key, $val, $exp=0)
Adds a key/value to the memcache server if one isn&#39;t already set with that key.
int $_bucketcount
Total # of bit buckets we have.
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2217
touch( $key, $time=0)
Changes the TTL on a key from the server to $time.
$_connect_attempts
Number of connection attempts for each server.
LoggerInterface $_logger