MediaWiki  REL1_31
DatabaseOracle.php
Go to the documentation of this file.
1 <?php
29 
33 class DatabaseOracle extends Database {
35  protected $mLastResult = null;
36 
38  protected $mAffectedRows;
39 
41  private $ignoreDupValOnIndex = false;
42 
44  private $sequenceData = null;
45 
47  private $defaultCharset = 'AL32UTF8';
48 
50  private $mFieldInfoCache = [];
51 
52  function __construct( array $p ) {
54 
55  if ( $p['tablePrefix'] == 'get from global' ) {
56  $p['tablePrefix'] = $wgDBprefix;
57  }
58  $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
59  parent::__construct( $p );
60  Hooks::run( 'DatabaseOraclePostInit', [ $this ] );
61  }
62 
63  function __destruct() {
64  if ( $this->opened ) {
65  Wikimedia\suppressWarnings();
66  $this->close();
67  Wikimedia\restoreWarnings();
68  }
69  }
70 
71  function getType() {
72  return 'oracle';
73  }
74 
75  function implicitGroupby() {
76  return false;
77  }
78 
79  function implicitOrderby() {
80  return false;
81  }
82 
92  function open( $server, $user, $password, $dbName ) {
94  if ( !function_exists( 'oci_connect' ) ) {
95  throw new DBConnectionError(
96  $this,
97  "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
98  "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
99  "and database)\n" );
100  }
101 
102  $this->close();
103  $this->user = $user;
104  $this->password = $password;
105  // changed internal variables functions
106  // mServer now holds the TNS endpoint
107  // mDBname is schema name if different from username
108  if ( !$server ) {
109  // backward compatibillity (server used to be null and TNS was supplied in dbname)
110  $this->server = $dbName;
111  $this->dbName = $user;
112  } else {
113  $this->server = $server;
114  if ( !$dbName ) {
115  $this->dbName = $user;
116  } else {
117  $this->dbName = $dbName;
118  }
119  }
120 
121  if ( !strlen( $user ) ) { # e.g. the class is being loaded
122  return null;
123  }
124 
125  if ( $wgDBOracleDRCP ) {
126  $this->setFlag( DBO_PERSISTENT );
127  }
128 
129  $session_mode = $this->flags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
130 
131  Wikimedia\suppressWarnings();
132  if ( $this->flags & DBO_PERSISTENT ) {
133  $this->conn = oci_pconnect(
134  $this->user,
135  $this->password,
136  $this->server,
137  $this->defaultCharset,
138  $session_mode
139  );
140  } elseif ( $this->flags & DBO_DEFAULT ) {
141  $this->conn = oci_new_connect(
142  $this->user,
143  $this->password,
144  $this->server,
145  $this->defaultCharset,
146  $session_mode
147  );
148  } else {
149  $this->conn = oci_connect(
150  $this->user,
151  $this->password,
152  $this->server,
153  $this->defaultCharset,
154  $session_mode
155  );
156  }
157  Wikimedia\restoreWarnings();
158 
159  if ( $this->user != $this->dbName ) {
160  // change current schema in session
161  $this->selectDB( $this->dbName );
162  }
163 
164  if ( !$this->conn ) {
165  throw new DBConnectionError( $this, $this->lastError() );
166  }
167 
168  $this->opened = true;
169 
170  # removed putenv calls because they interfere with the system globaly
171  $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
172  $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
173  $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
174 
175  return $this->conn;
176  }
177 
183  protected function closeConnection() {
184  return oci_close( $this->conn );
185  }
186 
187  function execFlags() {
188  return $this->trxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
189  }
190 
191  protected function doQuery( $sql ) {
192  wfDebug( "SQL: [$sql]\n" );
193  if ( !StringUtils::isUtf8( $sql ) ) {
194  throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
195  }
196 
197  // handle some oracle specifics
198  // remove AS column/table/subquery namings
199  if ( !$this->getFlag( DBO_DDLMODE ) ) {
200  $sql = preg_replace( '/ as /i', ' ', $sql );
201  }
202 
203  // Oracle has issues with UNION clause if the statement includes LOB fields
204  // So we do a UNION ALL and then filter the results array with array_unique
205  $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
206  // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
207  // you have to select data from plan table after explain
208  $explain_id = MWTimestamp::getLocalInstance()->format( 'dmYHis' );
209 
210  $sql = preg_replace(
211  '/^EXPLAIN /',
212  'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
213  $sql,
214  1,
215  $explain_count
216  );
217 
218  Wikimedia\suppressWarnings();
219 
220  $this->mLastResult = $stmt = oci_parse( $this->conn, $sql );
221  if ( $stmt === false ) {
222  $e = oci_error( $this->conn );
223  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
224 
225  return false;
226  }
227 
228  if ( !oci_execute( $stmt, $this->execFlags() ) ) {
229  $e = oci_error( $stmt );
230  if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
231  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
232 
233  return false;
234  }
235  }
236 
237  Wikimedia\restoreWarnings();
238 
239  if ( $explain_count > 0 ) {
240  return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
241  'WHERE statement_id = \'' . $explain_id . '\'' );
242  } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
243  return new ORAResult( $this, $stmt, $union_unique );
244  } else {
245  $this->mAffectedRows = oci_num_rows( $stmt );
246 
247  return true;
248  }
249  }
250 
251  function queryIgnore( $sql, $fname = '' ) {
252  return $this->query( $sql, $fname, true );
253  }
254 
259  function freeResult( $res ) {
260  if ( $res instanceof ResultWrapper ) {
261  $res = $res->result;
262  }
263 
264  $res->free();
265  }
266 
271  function fetchObject( $res ) {
272  if ( $res instanceof ResultWrapper ) {
273  $res = $res->result;
274  }
275 
276  return $res->fetchObject();
277  }
278 
283  function fetchRow( $res ) {
284  if ( $res instanceof ResultWrapper ) {
285  $res = $res->result;
286  }
287 
288  return $res->fetchRow();
289  }
290 
295  function numRows( $res ) {
296  if ( $res instanceof ResultWrapper ) {
297  $res = $res->result;
298  }
299 
300  return $res->numRows();
301  }
302 
307  function numFields( $res ) {
308  if ( $res instanceof ResultWrapper ) {
309  $res = $res->result;
310  }
311 
312  return $res->numFields();
313  }
314 
315  function fieldName( $stmt, $n ) {
316  return oci_field_name( $stmt, $n );
317  }
318 
319  function insertId() {
320  $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
321  $row = $this->fetchRow( $res );
322  return is_null( $row[0] ) ? null : (int)$row[0];
323  }
324 
329  function dataSeek( $res, $row ) {
330  if ( $res instanceof ORAResult ) {
331  $res->seek( $row );
332  } else {
333  $res->result->seek( $row );
334  }
335  }
336 
337  function lastError() {
338  if ( $this->conn === false ) {
339  $e = oci_error();
340  } else {
341  $e = oci_error( $this->conn );
342  }
343 
344  return $e['message'];
345  }
346 
347  function lastErrno() {
348  if ( $this->conn === false ) {
349  $e = oci_error();
350  } else {
351  $e = oci_error( $this->conn );
352  }
353 
354  return $e['code'];
355  }
356 
357  protected function fetchAffectedRowCount() {
358  return $this->mAffectedRows;
359  }
360 
369  function indexInfo( $table, $index, $fname = __METHOD__ ) {
370  return false;
371  }
372 
373  function indexUnique( $table, $index, $fname = __METHOD__ ) {
374  return false;
375  }
376 
377  function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
378  if ( !count( $a ) ) {
379  return true;
380  }
381 
382  if ( !is_array( $options ) ) {
383  $options = [ $options ];
384  }
385 
386  if ( in_array( 'IGNORE', $options ) ) {
387  $this->ignoreDupValOnIndex = true;
388  }
389 
390  if ( !is_array( reset( $a ) ) ) {
391  $a = [ $a ];
392  }
393 
394  foreach ( $a as &$row ) {
395  $this->insertOneRow( $table, $row, $fname );
396  }
397  $retVal = true;
398 
399  if ( in_array( 'IGNORE', $options ) ) {
400  $this->ignoreDupValOnIndex = false;
401  }
402 
403  return $retVal;
404  }
405 
406  private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
407  $col_info = $this->fieldInfoMulti( $table, $col );
408  $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
409 
410  $bind = '';
411  if ( is_numeric( $col ) ) {
412  $bind = $val;
413  $val = null;
414 
415  return $bind;
416  } elseif ( $includeCol ) {
417  $bind = "$col = ";
418  }
419 
420  if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
421  $val = null;
422  }
423 
424  if ( $val === 'NULL' ) {
425  $val = null;
426  }
427 
428  if ( $val === null ) {
429  if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
430  $bind .= 'DEFAULT';
431  } else {
432  $bind .= 'NULL';
433  }
434  } else {
435  $bind .= ':' . $col;
436  }
437 
438  return $bind;
439  }
440 
448  private function insertOneRow( $table, $row, $fname ) {
450 
451  $table = $this->tableName( $table );
452  // "INSERT INTO tables (a, b, c)"
453  $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
454  $sql .= " VALUES (";
455 
456  // for each value, append ":key"
457  $first = true;
458  foreach ( $row as $col => &$val ) {
459  if ( !$first ) {
460  $sql .= ', ';
461  } else {
462  $first = false;
463  }
464  if ( $this->isQuotedIdentifier( $val ) ) {
465  $sql .= $this->removeIdentifierQuotes( $val );
466  unset( $row[$col] );
467  } else {
468  $sql .= $this->fieldBindStatement( $table, $col, $val );
469  }
470  }
471  $sql .= ')';
472 
473  $this->mLastResult = $stmt = oci_parse( $this->conn, $sql );
474  if ( $stmt === false ) {
475  $e = oci_error( $this->conn );
476  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
477 
478  return false;
479  }
480  foreach ( $row as $col => &$val ) {
481  $col_info = $this->fieldInfoMulti( $table, $col );
482  $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
483 
484  if ( $val === null ) {
485  // do nothing ... null was inserted in statement creation
486  } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
487  if ( is_object( $val ) ) {
488  $val = $val->fetch();
489  }
490 
491  // backward compatibility
492  if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
493  $val = $this->getInfinity();
494  }
495 
496  $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
497  if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
498  $e = oci_error( $stmt );
499  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
500 
501  return false;
502  }
503  } else {
505  $lob[$col] = oci_new_descriptor( $this->conn, OCI_D_LOB );
506  if ( $lob[$col] === false ) {
507  $e = oci_error( $stmt );
508  throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
509  }
510 
511  if ( is_object( $val ) ) {
512  $val = $val->fetch();
513  }
514 
515  if ( $col_type == 'BLOB' ) {
516  $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
517  oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB );
518  } else {
519  $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
520  oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
521  }
522  }
523  }
524 
525  Wikimedia\suppressWarnings();
526 
527  if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
528  $e = oci_error( $stmt );
529  if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
530  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
531 
532  return false;
533  } else {
534  $this->mAffectedRows = oci_num_rows( $stmt );
535  }
536  } else {
537  $this->mAffectedRows = oci_num_rows( $stmt );
538  }
539 
540  Wikimedia\restoreWarnings();
541 
542  if ( isset( $lob ) ) {
543  foreach ( $lob as $lob_v ) {
544  $lob_v->free();
545  }
546  }
547 
548  if ( !$this->trxLevel ) {
549  oci_commit( $this->conn );
550  }
551 
552  return oci_free_statement( $stmt );
553  }
554 
555  function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
556  $insertOptions = [], $selectOptions = [], $selectJoinConds = []
557  ) {
558  $destTable = $this->tableName( $destTable );
559 
560  $sequenceData = $this->getSequenceData( $destTable );
561  if ( $sequenceData !== false &&
562  !isset( $varMap[$sequenceData['column']] )
563  ) {
564  $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
565  }
566 
567  // count-alias subselect fields to avoid abigious definition errors
568  $i = 0;
569  foreach ( $varMap as &$val ) {
570  $val = $val . ' field' . ( $i++ );
571  }
572 
573  $selectSql = $this->selectSQLText(
574  $srcTable,
575  array_values( $varMap ),
576  $conds,
577  $fname,
578  $selectOptions,
579  $selectJoinConds
580  );
581 
582  $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
583 
584  if ( in_array( 'IGNORE', $insertOptions ) ) {
585  $this->ignoreDupValOnIndex = true;
586  }
587 
588  $retval = $this->query( $sql, $fname );
589 
590  if ( in_array( 'IGNORE', $insertOptions ) ) {
591  $this->ignoreDupValOnIndex = false;
592  }
593 
594  return $retval;
595  }
596 
597  public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
598  $fname = __METHOD__
599  ) {
600  if ( !count( $rows ) ) {
601  return true; // nothing to do
602  }
603 
604  if ( !is_array( reset( $rows ) ) ) {
605  $rows = [ $rows ];
606  }
607 
608  $sequenceData = $this->getSequenceData( $table );
609  if ( $sequenceData !== false ) {
610  // add sequence column to each list of columns, when not set
611  foreach ( $rows as &$row ) {
612  if ( !isset( $row[$sequenceData['column']] ) ) {
613  $row[$sequenceData['column']] =
614  $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
615  $sequenceData['sequence'] . '\')' );
616  }
617  }
618  }
619 
620  return parent::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
621  }
622 
623  function tableName( $name, $format = 'quoted' ) {
624  /*
625  Replace reserved words with better ones
626  Using uppercase because that's the only way Oracle can handle
627  quoted tablenames
628  */
629  switch ( $name ) {
630  case 'user':
631  $name = 'MWUSER';
632  break;
633  case 'text':
634  $name = 'PAGECONTENT';
635  break;
636  }
637 
638  return strtoupper( parent::tableName( $name, $format ) );
639  }
640 
641  function tableNameInternal( $name ) {
642  $name = $this->tableName( $name );
643 
644  return preg_replace( '/.*\.(.*)/', '$1', $name );
645  }
646 
653  private function getSequenceData( $table ) {
654  if ( $this->sequenceData == null ) {
655  $result = $this->doQuery( "SELECT lower(asq.sequence_name),
656  lower(atc.table_name),
657  lower(atc.column_name)
658  FROM all_sequences asq, all_tab_columns atc
659  WHERE decode(
660  atc.table_name,
661  '{$this->tablePrefix}MWUSER',
662  '{$this->tablePrefix}USER',
663  atc.table_name
664  ) || '_' ||
665  atc.column_name || '_SEQ' = '{$this->tablePrefix}' || asq.sequence_name
666  AND asq.sequence_owner = upper('{$this->dbName}')
667  AND atc.owner = upper('{$this->dbName}')" );
668 
669  while ( ( $row = $result->fetchRow() ) !== false ) {
670  $this->sequenceData[$row[1]] = [
671  'sequence' => $row[0],
672  'column' => $row[2]
673  ];
674  }
675  }
676  $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
677 
678  return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
679  }
680 
688  function textFieldSize( $table, $field ) {
689  $fieldInfoData = $this->fieldInfo( $table, $field );
690 
691  return $fieldInfoData->maxLength();
692  }
693 
694  function limitResult( $sql, $limit, $offset = false ) {
695  if ( $offset === false ) {
696  $offset = 0;
697  }
698 
699  return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
700  }
701 
702  function encodeBlob( $b ) {
703  return new Blob( $b );
704  }
705 
706  function decodeBlob( $b ) {
707  if ( $b instanceof Blob ) {
708  $b = $b->fetch();
709  }
710 
711  return $b;
712  }
713 
714  function unionQueries( $sqls, $all ) {
715  $glue = ' UNION ALL ';
716 
717  return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) .
718  'FROM (' . implode( $glue, $sqls ) . ')';
719  }
720 
721  function wasDeadlock() {
722  return $this->lastErrno() == 'OCI-00060';
723  }
724 
725  function duplicateTableStructure( $oldName, $newName, $temporary = false,
726  $fname = __METHOD__
727  ) {
728  $temporary = $temporary ? 'TRUE' : 'FALSE';
729 
730  $newName = strtoupper( $newName );
731  $oldName = strtoupper( $oldName );
732 
733  $tabName = substr( $newName, strlen( $this->tablePrefix ) );
734  $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
735  $newPrefix = strtoupper( $this->tablePrefix );
736 
737  return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
738  "'$oldPrefix', '$newPrefix', $temporary ); END;" );
739  }
740 
741  function listTables( $prefix = null, $fname = __METHOD__ ) {
742  $listWhere = '';
743  if ( !empty( $prefix ) ) {
744  $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
745  }
746 
747  $owner = strtoupper( $this->dbName );
748  $result = $this->doQuery( "SELECT table_name FROM all_tables " .
749  "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
750 
751  // dirty code ... i know
752  $endArray = [];
753  $endArray[] = strtoupper( $prefix . 'MWUSER' );
754  $endArray[] = strtoupper( $prefix . 'PAGE' );
755  $endArray[] = strtoupper( $prefix . 'IMAGE' );
756  $fixedOrderTabs = $endArray;
757  while ( ( $row = $result->fetchRow() ) !== false ) {
758  if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
759  $endArray[] = $row['table_name'];
760  }
761  }
762 
763  return $endArray;
764  }
765 
766  public function dropTable( $tableName, $fName = __METHOD__ ) {
767  $tableName = $this->tableName( $tableName );
768  if ( !$this->tableExists( $tableName ) ) {
769  return false;
770  }
771 
772  return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
773  }
774 
775  function timestamp( $ts = 0 ) {
776  return wfTimestamp( TS_ORACLE, $ts );
777  }
778 
786  public function aggregateValue( $valuedata, $valuename = 'value' ) {
787  return $valuedata;
788  }
789 
793  public function getSoftwareLink() {
794  return '[{{int:version-db-oracle-url}} Oracle]';
795  }
796 
800  function getServerVersion() {
801  // better version number, fallback on driver
802  $rset = $this->doQuery(
803  'SELECT version FROM product_component_version ' .
804  'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
805  );
806  $row = $rset->fetchRow();
807  if ( !$row ) {
808  return oci_server_version( $this->conn );
809  }
810 
811  return $row['version'];
812  }
813 
821  function indexExists( $table, $index, $fname = __METHOD__ ) {
822  $table = $this->tableName( $table );
823  $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
824  $index = strtoupper( $index );
825  $owner = strtoupper( $this->dbName );
826  $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
827  $res = $this->doQuery( $sql );
828  if ( $res ) {
829  $count = $res->numRows();
830  $res->free();
831  } else {
832  $count = 0;
833  }
834 
835  return $count != 0;
836  }
837 
844  function tableExists( $table, $fname = __METHOD__ ) {
845  $table = $this->tableName( $table );
846  $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
847  $owner = $this->addQuotes( strtoupper( $this->dbName ) );
848  $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
849  $res = $this->doQuery( $sql );
850  if ( $res && $res->numRows() > 0 ) {
851  $exists = true;
852  } else {
853  $exists = false;
854  }
855 
856  $res->free();
857 
858  return $exists;
859  }
860 
871  private function fieldInfoMulti( $table, $field ) {
872  $field = strtoupper( $field );
873  if ( is_array( $table ) ) {
874  $table = array_map( [ $this, 'tableNameInternal' ], $table );
875  $tableWhere = 'IN (';
876  foreach ( $table as &$singleTable ) {
877  $singleTable = $this->removeIdentifierQuotes( $singleTable );
878  if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
879  return $this->mFieldInfoCache["$singleTable.$field"];
880  }
881  $tableWhere .= '\'' . $singleTable . '\',';
882  }
883  $tableWhere = rtrim( $tableWhere, ',' ) . ')';
884  } else {
885  $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
886  if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
887  return $this->mFieldInfoCache["$table.$field"];
888  }
889  $tableWhere = '= \'' . $table . '\'';
890  }
891 
892  $fieldInfoStmt = oci_parse(
893  $this->conn,
894  'SELECT * FROM wiki_field_info_full WHERE table_name ' .
895  $tableWhere . ' and column_name = \'' . $field . '\''
896  );
897  if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
898  $e = oci_error( $fieldInfoStmt );
899  $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
900 
901  return false;
902  }
903  $res = new ORAResult( $this, $fieldInfoStmt );
904  if ( $res->numRows() == 0 ) {
905  if ( is_array( $table ) ) {
906  foreach ( $table as &$singleTable ) {
907  $this->mFieldInfoCache["$singleTable.$field"] = false;
908  }
909  } else {
910  $this->mFieldInfoCache["$table.$field"] = false;
911  }
912  $fieldInfoTemp = null;
913  } else {
914  $fieldInfoTemp = new ORAField( $res->fetchRow() );
915  $table = $fieldInfoTemp->tableName();
916  $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
917  }
918  $res->free();
919 
920  return $fieldInfoTemp;
921  }
922 
929  function fieldInfo( $table, $field ) {
930  if ( is_array( $table ) ) {
931  throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
932  }
933 
934  return $this->fieldInfoMulti( $table, $field );
935  }
936 
937  protected function doBegin( $fname = __METHOD__ ) {
938  $this->trxLevel = 1;
939  $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
940  }
941 
942  protected function doCommit( $fname = __METHOD__ ) {
943  if ( $this->trxLevel ) {
944  $ret = oci_commit( $this->conn );
945  if ( !$ret ) {
946  throw new DBUnexpectedError( $this, $this->lastError() );
947  }
948  $this->trxLevel = 0;
949  $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
950  }
951  }
952 
953  protected function doRollback( $fname = __METHOD__ ) {
954  if ( $this->trxLevel ) {
955  oci_rollback( $this->conn );
956  $this->trxLevel = 0;
957  $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
958  }
959  }
960 
961  function sourceStream(
962  $fp,
963  callable $lineCallback = null,
964  callable $resultCallback = null,
965  $fname = __METHOD__, callable $inputCallback = null
966  ) {
967  $cmd = '';
968  $done = false;
969  $dollarquote = false;
970 
971  $replacements = [];
972  // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
973  while ( !feof( $fp ) ) {
974  if ( $lineCallback ) {
975  call_user_func( $lineCallback );
976  }
977  $line = trim( fgets( $fp, 1024 ) );
978  $sl = strlen( $line ) - 1;
979 
980  if ( $sl < 0 ) {
981  continue;
982  }
983  if ( '-' == $line[0] && '-' == $line[1] ) {
984  continue;
985  }
986 
987  // Allow dollar quoting for function declarations
988  if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
989  if ( $dollarquote ) {
990  $dollarquote = false;
991  $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
992  $done = true;
993  } else {
994  $dollarquote = true;
995  }
996  } elseif ( !$dollarquote ) {
997  if ( ';' == $line[$sl] && ( $sl < 2 || ';' != $line[$sl - 1] ) ) {
998  $done = true;
999  $line = substr( $line, 0, $sl );
1000  }
1001  }
1002 
1003  if ( $cmd != '' ) {
1004  $cmd .= ' ';
1005  }
1006  $cmd .= "$line\n";
1007 
1008  if ( $done ) {
1009  $cmd = str_replace( ';;', ";", $cmd );
1010  if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1011  if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1012  $replacements[$defines[2]] = $defines[1];
1013  }
1014  } else {
1015  foreach ( $replacements as $mwVar => $scVar ) {
1016  $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1017  }
1018 
1019  $cmd = $this->replaceVars( $cmd );
1020  if ( $inputCallback ) {
1021  call_user_func( $inputCallback, $cmd );
1022  }
1023  $res = $this->doQuery( $cmd );
1024  if ( $resultCallback ) {
1025  call_user_func( $resultCallback, $res, $this );
1026  }
1027 
1028  if ( false === $res ) {
1029  $err = $this->lastError();
1030 
1031  return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1032  }
1033  }
1034 
1035  $cmd = '';
1036  $done = false;
1037  }
1038  }
1039 
1040  return true;
1041  }
1042 
1043  function selectDB( $db ) {
1044  $this->dbName = $db;
1045  if ( $db == null || $db == $this->user ) {
1046  return true;
1047  }
1048  $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1049  $stmt = oci_parse( $this->conn, $sql );
1050  Wikimedia\suppressWarnings();
1051  $success = oci_execute( $stmt );
1052  Wikimedia\restoreWarnings();
1053  if ( !$success ) {
1054  $e = oci_error( $stmt );
1055  if ( $e['code'] != '1435' ) {
1056  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1057  }
1058 
1059  return false;
1060  }
1061 
1062  return true;
1063  }
1064 
1065  function strencode( $s ) {
1066  return str_replace( "'", "''", $s );
1067  }
1068 
1069  function addQuotes( $s ) {
1071  if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1072  $s = $wgContLang->checkTitleEncoding( $s );
1073  }
1074 
1075  return "'" . $this->strencode( $s ) . "'";
1076  }
1077 
1078  public function addIdentifierQuotes( $s ) {
1079  if ( !$this->getFlag( DBO_DDLMODE ) ) {
1080  $s = '/*Q*/' . $s;
1081  }
1082 
1083  return $s;
1084  }
1085 
1086  public function removeIdentifierQuotes( $s ) {
1087  return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1088  }
1089 
1090  public function isQuotedIdentifier( $s ) {
1091  return strpos( $s, '/*Q*/' ) !== false;
1092  }
1093 
1094  private function wrapFieldForWhere( $table, &$col, &$val ) {
1096 
1097  $col_info = $this->fieldInfoMulti( $table, $col );
1098  $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1099  if ( $col_type == 'CLOB' ) {
1100  $col = 'TO_CHAR(' . $col . ')';
1101  $val = $wgContLang->checkTitleEncoding( $val );
1102  } elseif ( $col_type == 'VARCHAR2' ) {
1103  $val = $wgContLang->checkTitleEncoding( $val );
1104  }
1105  }
1106 
1107  private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1108  $conds2 = [];
1109  foreach ( $conds as $col => $val ) {
1110  if ( is_array( $val ) ) {
1111  $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1112  } else {
1113  if ( is_numeric( $col ) && $parentCol != null ) {
1114  $this->wrapFieldForWhere( $table, $parentCol, $val );
1115  } else {
1116  $this->wrapFieldForWhere( $table, $col, $val );
1117  }
1118  $conds2[$col] = $val;
1119  }
1120  }
1121 
1122  return $conds2;
1123  }
1124 
1125  function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1126  $options = [], $join_conds = []
1127  ) {
1128  if ( is_array( $conds ) ) {
1129  $conds = $this->wrapConditionsForWhere( $table, $conds );
1130  }
1131 
1132  return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1133  }
1134 
1144  $preLimitTail = $postLimitTail = '';
1145  $startOpts = '';
1146 
1147  $noKeyOptions = [];
1148  foreach ( $options as $key => $option ) {
1149  if ( is_numeric( $key ) ) {
1150  $noKeyOptions[$option] = true;
1151  }
1152  }
1153 
1154  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1155 
1156  $preLimitTail .= $this->makeOrderBy( $options );
1157 
1158  if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1159  $postLimitTail .= ' FOR UPDATE';
1160  }
1161 
1162  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1163  $startOpts .= 'DISTINCT';
1164  }
1165 
1166  if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1167  $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1168  } else {
1169  $useIndex = '';
1170  }
1171 
1172  if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1173  $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1174  } else {
1175  $ignoreIndex = '';
1176  }
1177 
1178  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1179  }
1180 
1181  public function delete( $table, $conds, $fname = __METHOD__ ) {
1183 
1184  if ( is_array( $conds ) ) {
1185  $conds = $this->wrapConditionsForWhere( $table, $conds );
1186  }
1187  // a hack for deleting pages, users and images (which have non-nullable FKs)
1188  // all deletions on these tables have transactions so final failure rollbacks these updates
1189  // @todo: Normalize the schema to match MySQL, no special FKs and such
1190  $table = $this->tableName( $table );
1191  if ( $table == $this->tableName( 'user' ) && $wgActorTableSchemaMigrationStage < MIGRATION_NEW ) {
1192  $this->update( 'archive', [ 'ar_user' => 0 ],
1193  [ 'ar_user' => $conds['user_id'] ], $fname );
1194  $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1195  [ 'ipb_user' => $conds['user_id'] ], $fname );
1196  $this->update( 'image', [ 'img_user' => 0 ],
1197  [ 'img_user' => $conds['user_id'] ], $fname );
1198  $this->update( 'oldimage', [ 'oi_user' => 0 ],
1199  [ 'oi_user' => $conds['user_id'] ], $fname );
1200  $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1201  [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1202  $this->update( 'filearchive', [ 'fa_user' => 0 ],
1203  [ 'fa_user' => $conds['user_id'] ], $fname );
1204  $this->update( 'uploadstash', [ 'us_user' => 0 ],
1205  [ 'us_user' => $conds['user_id'] ], $fname );
1206  $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1207  [ 'rc_user' => $conds['user_id'] ], $fname );
1208  $this->update( 'logging', [ 'log_user' => 0 ],
1209  [ 'log_user' => $conds['user_id'] ], $fname );
1210  } elseif ( $table == $this->tableName( 'image' ) ) {
1211  $this->update( 'oldimage', [ 'oi_name' => 0 ],
1212  [ 'oi_name' => $conds['img_name'] ], $fname );
1213  }
1214 
1215  return parent::delete( $table, $conds, $fname );
1216  }
1217 
1227  function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1229 
1230  $table = $this->tableName( $table );
1231  $opts = $this->makeUpdateOptions( $options );
1232  $sql = "UPDATE $opts $table SET ";
1233 
1234  $first = true;
1235  foreach ( $values as $col => &$val ) {
1236  $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1237 
1238  if ( !$first ) {
1239  $sqlSet = ', ' . $sqlSet;
1240  } else {
1241  $first = false;
1242  }
1243  $sql .= $sqlSet;
1244  }
1245 
1246  if ( $conds !== [] && $conds !== '*' ) {
1247  $conds = $this->wrapConditionsForWhere( $table, $conds );
1248  $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1249  }
1250 
1251  $this->mLastResult = $stmt = oci_parse( $this->conn, $sql );
1252  if ( $stmt === false ) {
1253  $e = oci_error( $this->conn );
1254  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1255 
1256  return false;
1257  }
1258  foreach ( $values as $col => &$val ) {
1259  $col_info = $this->fieldInfoMulti( $table, $col );
1260  $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1261 
1262  if ( $val === null ) {
1263  // do nothing ... null was inserted in statement creation
1264  } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1265  if ( is_object( $val ) ) {
1266  $val = $val->getData();
1267  }
1268 
1269  if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1270  $val = '31-12-2030 12:00:00.000000';
1271  }
1272 
1273  $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1274  if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1275  $e = oci_error( $stmt );
1276  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1277 
1278  return false;
1279  }
1280  } else {
1282  $lob[$col] = oci_new_descriptor( $this->conn, OCI_D_LOB );
1283  if ( $lob[$col] === false ) {
1284  $e = oci_error( $stmt );
1285  throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1286  }
1287 
1288  if ( is_object( $val ) ) {
1289  $val = $val->getData();
1290  }
1291 
1292  if ( $col_type == 'BLOB' ) {
1293  $lob[$col]->writeTemporary( $val );
1294  oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB );
1295  } else {
1296  $lob[$col]->writeTemporary( $val );
1297  oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
1298  }
1299  }
1300  }
1301 
1302  Wikimedia\suppressWarnings();
1303 
1304  if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1305  $e = oci_error( $stmt );
1306  if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
1307  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1308 
1309  return false;
1310  } else {
1311  $this->mAffectedRows = oci_num_rows( $stmt );
1312  }
1313  } else {
1314  $this->mAffectedRows = oci_num_rows( $stmt );
1315  }
1316 
1317  Wikimedia\restoreWarnings();
1318 
1319  if ( isset( $lob ) ) {
1320  foreach ( $lob as $lob_v ) {
1321  $lob_v->free();
1322  }
1323  }
1324 
1325  if ( !$this->trxLevel ) {
1326  oci_commit( $this->conn );
1327  }
1328 
1329  return oci_free_statement( $stmt );
1330  }
1331 
1332  function bitNot( $field ) {
1333  // expecting bit-fields smaller than 4bytes
1334  return 'BITNOT(' . $field . ')';
1335  }
1336 
1337  function bitAnd( $fieldLeft, $fieldRight ) {
1338  return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1339  }
1340 
1341  function bitOr( $fieldLeft, $fieldRight ) {
1342  return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1343  }
1344 
1345  function getDBname() {
1346  return $this->dbName;
1347  }
1348 
1349  function getServer() {
1350  return $this->server;
1351  }
1352 
1353  public function buildGroupConcatField(
1354  $delim, $table, $field, $conds = '', $join_conds = []
1355  ) {
1356  $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1357 
1358  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1359  }
1360 
1361  public function buildSubstring( $input, $startPosition, $length = null ) {
1362  $this->assertBuildSubstringParams( $startPosition, $length );
1363  $params = [ $input, $startPosition ];
1364  if ( $length !== null ) {
1365  $params[] = $length;
1366  }
1367  return 'SUBSTR(' . implode( ',', $params ) . ')';
1368  }
1369 
1375  public function buildStringCast( $field ) {
1376  return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1377  }
1378 
1379  public function getInfinity() {
1380  return '31-12-2030 12:00:00.000000';
1381  }
1382 }
DBO_PERSISTENT
const DBO_PERSISTENT
Definition: defines.php:14
code
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of or an object and a method hook function The function part of a third party developers and administrators to define code that will be run at certain points in the mainline code
Definition: hooks.txt:28
DatabaseOracle\insert
insert( $table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
Definition: DatabaseOracle.php:377
DatabaseOracle\numFields
numFields( $res)
Definition: DatabaseOracle.php:307
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
DatabaseOracle\encodeBlob
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
Definition: DatabaseOracle.php:702
DatabaseOracle\__construct
__construct(array $p)
Definition: DatabaseOracle.php:52
return
return[ 'DBLoadBalancerFactory'=> function(MediaWikiServices $services) { $mainConfig=$services->getMainConfig();$lbConf=MWLBFactory::applyDefaultConfig($mainConfig->get( 'LBFactoryConf'), $mainConfig, $services->getConfiguredReadOnlyMode());$class=MWLBFactory::getLBFactoryClass( $lbConf);$instance=new $class( $lbConf);MWLBFactory::setSchemaAliases( $instance, $mainConfig);return $instance;}, 'DBLoadBalancer'=> function(MediaWikiServices $services) { return $services->getDBLoadBalancerFactory() ->getMainLB();}, 'SiteStore'=> function(MediaWikiServices $services) { $rawSiteStore=new DBSiteStore( $services->getDBLoadBalancer());$cache=wfGetCache(wfIsHHVM() ? CACHE_ACCEL :CACHE_ANYTHING);return new CachingSiteStore( $rawSiteStore, $cache);}, 'SiteLookup'=> function(MediaWikiServices $services) { $cacheFile=$services->getMainConfig() ->get( 'SitesCacheFile');if( $cacheFile !==false) { return new FileBasedSiteLookup( $cacheFile);} else { return $services->getSiteStore();} }, 'ConfigFactory'=> function(MediaWikiServices $services) { $registry=$services->getBootstrapConfig() ->get( 'ConfigRegistry');$factory=new ConfigFactory();foreach( $registry as $name=> $callback) { $factory->register( $name, $callback);} return $factory;}, 'MainConfig'=> function(MediaWikiServices $services) { return $services->getConfigFactory() ->makeConfig( 'main');}, 'InterwikiLookup'=> function(MediaWikiServices $services) { global $wgContLang;$config=$services->getMainConfig();return new ClassicInterwikiLookup($wgContLang, $services->getMainWANObjectCache(), $config->get( 'InterwikiExpiry'), $config->get( 'InterwikiCache'), $config->get( 'InterwikiScopes'), $config->get( 'InterwikiFallbackSite'));}, 'StatsdDataFactory'=> function(MediaWikiServices $services) { return new BufferingStatsdDataFactory(rtrim( $services->getMainConfig() ->get( 'StatsdMetricPrefix'), '.'));}, 'EventRelayerGroup'=> function(MediaWikiServices $services) { return new EventRelayerGroup( $services->getMainConfig() ->get( 'EventRelayerConfig'));}, 'SearchEngineFactory'=> function(MediaWikiServices $services) { return new SearchEngineFactory( $services->getSearchEngineConfig());}, 'SearchEngineConfig'=> function(MediaWikiServices $services) { global $wgContLang;return new SearchEngineConfig( $services->getMainConfig(), $wgContLang);}, 'SkinFactory'=> function(MediaWikiServices $services) { $factory=new SkinFactory();$names=$services->getMainConfig() ->get( 'ValidSkinNames');foreach( $names as $name=> $skin) { $factory->register( $name, $skin, function() use( $name, $skin) { $class="Skin$skin";return new $class( $name);});} $factory->register( 'fallback', 'Fallback', function() { return new SkinFallback;});$factory->register( 'apioutput', 'ApiOutput', function() { return new SkinApi;});return $factory;}, 'WatchedItemStore'=> function(MediaWikiServices $services) { $store=new WatchedItemStore($services->getDBLoadBalancer(), new HashBagOStuff([ 'maxKeys'=> 100]), $services->getReadOnlyMode(), $services->getMainConfig() ->get( 'UpdateRowsPerQuery'));$store->setStatsdDataFactory( $services->getStatsdDataFactory());if( $services->getMainConfig() ->get( 'ReadOnlyWatchedItemStore')) { $store=new NoWriteWatchedItemStore( $store);} return $store;}, 'WatchedItemQueryService'=> function(MediaWikiServices $services) { return new WatchedItemQueryService($services->getDBLoadBalancer(), $services->getCommentStore(), $services->getActorMigration());}, 'CryptRand'=> function(MediaWikiServices $services) { $secretKey=$services->getMainConfig() ->get( 'SecretKey');return new CryptRand(['wfHostname', 'wfWikiID', function() use( $secretKey) { return $secretKey ?:'';}], defined( 'MW_CONFIG_FILE') ?[MW_CONFIG_FILE] :[], LoggerFactory::getInstance( 'CryptRand'));}, 'CryptHKDF'=> function(MediaWikiServices $services) { $config=$services->getMainConfig();$secret=$config->get( 'HKDFSecret') ?:$config->get( 'SecretKey');if(! $secret) { throw new RuntimeException("Cannot use MWCryptHKDF without a secret.");} $context=[microtime(), getmypid(), gethostname()];$cache=$services->getLocalServerObjectCache();if( $cache instanceof EmptyBagOStuff) { $cache=ObjectCache::getLocalClusterInstance();} return new CryptHKDF( $secret, $config->get( 'HKDFAlgorithm'), $cache, $context, $services->getCryptRand());}, 'MediaHandlerFactory'=> function(MediaWikiServices $services) { return new MediaHandlerFactory($services->getMainConfig() ->get( 'MediaHandlers'));}, 'MimeAnalyzer'=> function(MediaWikiServices $services) { $logger=LoggerFactory::getInstance( 'Mime');$mainConfig=$services->getMainConfig();$params=['typeFile'=> $mainConfig->get( 'MimeTypeFile'), 'infoFile'=> $mainConfig->get( 'MimeInfoFile'), 'xmlTypes'=> $mainConfig->get( 'XMLMimeTypes'), 'guessCallback'=> function( $mimeAnalyzer, &$head, &$tail, $file, &$mime) use( $logger) { $deja=new DjVuImage( $file);if( $deja->isValid()) { $logger->info(__METHOD__ . ": detected $file as image/vnd.djvu\n");$mime='image/vnd.djvu';return;} Hooks::run('MimeMagicGuessFromContent', [ $mimeAnalyzer, &$head, &$tail, $file, &$mime]);}, 'extCallback'=> function( $mimeAnalyzer, $ext, &$mime) { Hooks::run( 'MimeMagicImproveFromExtension', [ $mimeAnalyzer, $ext, &$mime]);}, 'initCallback'=> function( $mimeAnalyzer) { Hooks::run( 'MimeMagicInit', [ $mimeAnalyzer]);}, 'logger'=> $logger];if( $params['infoFile']==='includes/mime.info') { $params['infoFile']=__DIR__ . "/libs/mime/mime.info";} if( $params['typeFile']==='includes/mime.types') { $params['typeFile']=__DIR__ . "/libs/mime/mime.types";} $detectorCmd=$mainConfig->get( 'MimeDetectorCommand');if( $detectorCmd) { $factory=$services->getShellCommandFactory();$params['detectCallback']=function( $file) use( $detectorCmd, $factory) { $result=$factory->create() ->unsafeParams( $detectorCmd) ->params( $file) ->execute();return $result->getStdout();};} return new MimeMagic( $params);}, 'ProxyLookup'=> function(MediaWikiServices $services) { $mainConfig=$services->getMainConfig();return new ProxyLookup($mainConfig->get( 'SquidServers'), $mainConfig->get( 'SquidServersNoPurge'));}, 'Parser'=> function(MediaWikiServices $services) { $conf=$services->getMainConfig() ->get( 'ParserConf');return ObjectFactory::constructClassInstance( $conf['class'], [ $conf]);}, 'ParserCache'=> function(MediaWikiServices $services) { $config=$services->getMainConfig();$cache=ObjectCache::getInstance( $config->get( 'ParserCacheType'));wfDebugLog( 'caches', 'parser:' . get_class( $cache));return new ParserCache($cache, $config->get( 'CacheEpoch'));}, 'LinkCache'=> function(MediaWikiServices $services) { return new LinkCache($services->getTitleFormatter(), $services->getMainWANObjectCache());}, 'LinkRendererFactory'=> function(MediaWikiServices $services) { return new LinkRendererFactory($services->getTitleFormatter(), $services->getLinkCache());}, 'LinkRenderer'=> function(MediaWikiServices $services) { global $wgUser;if(defined( 'MW_NO_SESSION')) { return $services->getLinkRendererFactory() ->create();} else { return $services->getLinkRendererFactory() ->createForUser( $wgUser);} }, 'GenderCache'=> function(MediaWikiServices $services) { return new GenderCache();}, '_MediaWikiTitleCodec'=> function(MediaWikiServices $services) { global $wgContLang;return new MediaWikiTitleCodec($wgContLang, $services->getGenderCache(), $services->getMainConfig() ->get( 'LocalInterwikis'));}, 'TitleFormatter'=> function(MediaWikiServices $services) { return $services->getService( '_MediaWikiTitleCodec');}, 'TitleParser'=> function(MediaWikiServices $services) { return $services->getService( '_MediaWikiTitleCodec');}, 'MainObjectStash'=> function(MediaWikiServices $services) { $mainConfig=$services->getMainConfig();$id=$mainConfig->get( 'MainStash');if(!isset( $mainConfig->get( 'ObjectCaches')[$id])) { throw new UnexpectedValueException("Cache type \"$id\" is not present in \$wgObjectCaches.");} return \ObjectCache::newFromParams( $mainConfig->get( 'ObjectCaches')[$id]);}, 'MainWANObjectCache'=> function(MediaWikiServices $services) { $mainConfig=$services->getMainConfig();$id=$mainConfig->get( 'MainWANCache');if(!isset( $mainConfig->get( 'WANObjectCaches')[$id])) { throw new UnexpectedValueException("WAN cache type \"$id\" is not present in \$wgWANObjectCaches.");} $params=$mainConfig->get( 'WANObjectCaches')[$id];$objectCacheId=$params['cacheId'];if(!isset( $mainConfig->get( 'ObjectCaches')[$objectCacheId])) { throw new UnexpectedValueException("Cache type \"$objectCacheId\" is not present in \$wgObjectCaches.");} $params['store']=$mainConfig->get( 'ObjectCaches')[$objectCacheId];return \ObjectCache::newWANCacheFromParams( $params);}, 'LocalServerObjectCache'=> function(MediaWikiServices $services) { $mainConfig=$services->getMainConfig();if(function_exists( 'apc_fetch')) { $id='apc';} elseif(function_exists( 'apcu_fetch')) { $id='apcu';} elseif(function_exists( 'wincache_ucache_get')) { $id='wincache';} else { $id=CACHE_NONE;} if(!isset( $mainConfig->get( 'ObjectCaches')[$id])) { throw new UnexpectedValueException("Cache type \"$id\" is not present in \$wgObjectCaches.");} return \ObjectCache::newFromParams( $mainConfig->get( 'ObjectCaches')[$id]);}, 'VirtualRESTServiceClient'=> function(MediaWikiServices $services) { $config=$services->getMainConfig() ->get( 'VirtualRestConfig');$vrsClient=new VirtualRESTServiceClient(new MultiHttpClient([]));foreach( $config['paths'] as $prefix=> $serviceConfig) { $class=$serviceConfig['class'];$constructArg=isset( $serviceConfig['options']) ? $serviceConfig['options'] :[];$constructArg+=$config['global'];$vrsClient->mount( $prefix, [ 'class'=> $class, 'config'=> $constructArg]);} return $vrsClient;}, 'ConfiguredReadOnlyMode'=> function(MediaWikiServices $services) { return new ConfiguredReadOnlyMode( $services->getMainConfig());}, 'ReadOnlyMode'=> function(MediaWikiServices $services) { return new ReadOnlyMode($services->getConfiguredReadOnlyMode(), $services->getDBLoadBalancer());}, 'UploadRevisionImporter'=> function(MediaWikiServices $services) { return new ImportableUploadRevisionImporter($services->getMainConfig() ->get( 'EnableUploads'), LoggerFactory::getInstance( 'UploadRevisionImporter'));}, 'OldRevisionImporter'=> function(MediaWikiServices $services) { return new ImportableOldRevisionImporter(true, LoggerFactory::getInstance( 'OldRevisionImporter'), $services->getDBLoadBalancer());}, 'WikiRevisionOldRevisionImporterNoUpdates'=> function(MediaWikiServices $services) { return new ImportableOldRevisionImporter(false, LoggerFactory::getInstance( 'OldRevisionImporter'), $services->getDBLoadBalancer());}, 'ShellCommandFactory'=> function(MediaWikiServices $services) { $config=$services->getMainConfig();$limits=['time'=> $config->get( 'MaxShellTime'), 'walltime'=> $config->get( 'MaxShellWallClockTime'), 'memory'=> $config->get( 'MaxShellMemory'), 'filesize'=> $config->get( 'MaxShellFileSize'),];$cgroup=$config->get( 'ShellCgroup');$restrictionMethod=$config->get( 'ShellRestrictionMethod');$factory=new CommandFactory( $limits, $cgroup, $restrictionMethod);$factory->setLogger(LoggerFactory::getInstance( 'exec'));$factory->logStderr();return $factory;}, 'ExternalStoreFactory'=> function(MediaWikiServices $services) { $config=$services->getMainConfig();return new ExternalStoreFactory($config->get( 'ExternalStores'));}, 'RevisionStore'=> function(MediaWikiServices $services) { $blobStore=$services->getService( '_SqlBlobStore');$store=new RevisionStore($services->getDBLoadBalancer(), $blobStore, $services->getMainWANObjectCache(), $services->getCommentStore(), $services->getActorMigration());$store->setLogger(LoggerFactory::getInstance( 'RevisionStore'));$config=$services->getMainConfig();$store->setContentHandlerUseDB( $config->get( 'ContentHandlerUseDB'));return $store;}, 'RevisionLookup'=> function(MediaWikiServices $services) { return $services->getRevisionStore();}, 'RevisionFactory'=> function(MediaWikiServices $services) { return $services->getRevisionStore();}, 'BlobStoreFactory'=> function(MediaWikiServices $services) { global $wgContLang;return new BlobStoreFactory($services->getDBLoadBalancer(), $services->getMainWANObjectCache(), $services->getMainConfig(), $wgContLang);}, 'BlobStore'=> function(MediaWikiServices $services) { return $services->getService( '_SqlBlobStore');}, '_SqlBlobStore'=> function(MediaWikiServices $services) { return $services->getBlobStoreFactory() ->newSqlBlobStore();}, 'ContentModelStore'=> function(MediaWikiServices $services) { return new NameTableStore($services->getDBLoadBalancer(), $services->getMainWANObjectCache(), LoggerFactory::getInstance( 'NameTableSqlStore'), 'content_models', 'model_id', 'model_name');}, 'SlotRoleStore'=> function(MediaWikiServices $services) { return new NameTableStore($services->getDBLoadBalancer(), $services->getMainWANObjectCache(), LoggerFactory::getInstance( 'NameTableSqlStore'), 'slot_roles', 'role_id', 'role_name', 'strtolower');}, 'PreferencesFactory'=> function(MediaWikiServices $services) { global $wgContLang;$authManager=AuthManager::singleton();$linkRenderer=$services->getLinkRendererFactory() ->create();$config=$services->getMainConfig();$factory=new DefaultPreferencesFactory( $config, $wgContLang, $authManager, $linkRenderer);$factory->setLogger(LoggerFactory::getInstance( 'preferences'));return $factory;}, 'HttpRequestFactory'=> function(MediaWikiServices $services) { return new \MediaWiki\Http\HttpRequestFactory();}, 'CommentStore'=> function(MediaWikiServices $services) { global $wgContLang;return new CommentStore($wgContLang, $services->getMainConfig() ->get( 'CommentTableSchemaMigrationStage'));}, 'ActorMigration'=> function(MediaWikiServices $services) { return new ActorMigration($services->getMainConfig() ->get( 'ActorTableSchemaMigrationStage'));},]
Definition: ServiceWiring.php:616
StringUtils\isUtf8
static isUtf8( $value)
Test whether a string is valid UTF-8.
Definition: StringUtils.php:41
DatabaseOracle\$mAffectedRows
int $mAffectedRows
The number of rows affected as an integer.
Definition: DatabaseOracle.php:38
DatabaseOracle\lastErrno
lastErrno()
Get the last error number.
Definition: DatabaseOracle.php:347
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
DatabaseOracle\dropTable
dropTable( $tableName, $fName=__METHOD__)
Delete a table.
Definition: DatabaseOracle.php:766
DatabaseOracle\bitOr
bitOr( $fieldLeft, $fieldRight)
Definition: DatabaseOracle.php:1341
array
the array() calling protocol came about after MediaWiki 1.4rc1.
is
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------ Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server. Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It 's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use. Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves. The master writes thequery to the binlog when the transaction is committed. The slaves pollthe binlog and start executing the query as soon as it appears. They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes. Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load. MediaWiki 's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database. All edits and other write operations will berefused, with an error returned to the user. This gives the slaves achance to catch up. Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order. A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests. This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it. Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in "lagged slave mode". Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode(). The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time. Multi-row INSERT ...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it 's not practical to guarantee a low-lagenvironment. Lag will usually be less than one second, but mayoccasionally be up to 30 seconds. For scalability, it 's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer. So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn 't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum. In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------ Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks. By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent. Locks willbe held from the time when the query is done until the commit. So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction. Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
Wikimedia\Rdbms\Database\$password
string $password
Password used to establish the current connection.
Definition: Database.php:83
DatabaseOracle\doCommit
doCommit( $fname=__METHOD__)
Issues the COMMIT command to the database server.
Definition: DatabaseOracle.php:942
DatabaseOracle\nativeInsertSelect
nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
Native server-side implementation of insertSelect() for situations where we don't want to select ever...
Definition: DatabaseOracle.php:555
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1980
$ret
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:2005
DatabaseOracle\strencode
strencode( $s)
Wrapper for addslashes()
Definition: DatabaseOracle.php:1065
DatabaseOracle\textFieldSize
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".
Definition: DatabaseOracle.php:688
MIGRATION_NEW
const MIGRATION_NEW
Definition: Defines.php:305
DatabaseOracle\wrapFieldForWhere
wrapFieldForWhere( $table, &$col, &$val)
Definition: DatabaseOracle.php:1094
DatabaseOracle\tableNameInternal
tableNameInternal( $name)
Definition: DatabaseOracle.php:641
DatabaseOracle\buildGroupConcatField
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.
Definition: DatabaseOracle.php:1353
DatabaseOracle\fieldInfoMulti
fieldInfoMulti( $table, $field)
Function translates mysql_fetch_field() functionality on ORACLE.
Definition: DatabaseOracle.php:871
$params
$params
Definition: styleTest.css.php:40
e
in this case you re responsible for computing and outputting the entire conflict i e
Definition: hooks.txt:1421
DatabaseOracle\fetchAffectedRowCount
fetchAffectedRowCount()
Definition: DatabaseOracle.php:357
$s
$s
Definition: mergeMessageFileList.php:187
DatabaseOracle\addIdentifierQuotes
addIdentifierQuotes( $s)
Quotes an identifier using backticks or "double quotes" depending on the database type.
Definition: DatabaseOracle.php:1078
message
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a message
Definition: hooks.txt:2163
$res
$res
Definition: database.txt:21
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:24
DatabaseOracle\limitResult
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.
Definition: DatabaseOracle.php:694
$success
$success
Definition: NoLocalSettings.php:42
DatabaseOracle\doRollback
doRollback( $fname=__METHOD__)
Issues the ROLLBACK command to the database server.
Definition: DatabaseOracle.php:953
DatabaseOracle\duplicateTableStructure
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.
Definition: DatabaseOracle.php:725
$wgDBOracleDRCP
$wgDBOracleDRCP
Set true to enable Oracle DCRP (supported from 11gR1 onward)
Definition: DefaultSettings.php:2087
$result
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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:1993
ORAField
Definition: ORAField.php:5
DatabaseOracle\timestamp
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
Definition: DatabaseOracle.php:775
Wikimedia\Rdbms\Database\getFlag
getFlag( $flag)
Returns a boolean whether the flag $flag is set for this connection.
Definition: Database.php:797
DatabaseOracle\aggregateValue
aggregateValue( $valuedata, $valuename='value')
Return aggregated value function call.
Definition: DatabaseOracle.php:786
$wgDBprefix
$wgDBprefix
Table name prefix.
Definition: DefaultSettings.php:1871
php
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:37
LIST_AND
const LIST_AND
Definition: Defines.php:53
DatabaseOracle\listTables
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
Definition: DatabaseOracle.php:741
DatabaseOracle\execFlags
execFlags()
Definition: DatabaseOracle.php:187
DatabaseOracle\$defaultCharset
string $defaultCharset
Character set for Oracle database.
Definition: DatabaseOracle.php:47
DatabaseOracle\fieldName
fieldName( $stmt, $n)
Get a field name in a result object.
Definition: DatabaseOracle.php:315
DatabaseOracle\selectDB
selectDB( $db)
Change the current database.
Definition: DatabaseOracle.php:1043
flags
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database etc For and for historical it also represents a few features of articles that don t involve their such as access rights See also title txt Article Encapsulates access to the page table of the database The object represents a an and maintains state such as flags
Definition: design.txt:34
DatabaseOracle\freeResult
freeResult( $res)
Frees resources associated with the LOB descriptor.
Definition: DatabaseOracle.php:259
DatabaseOracle\tableExists
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists (in the given schema, or the default mw one if not given)
Definition: DatabaseOracle.php:844
DatabaseOracle\lastError
lastError()
Get a description of the last error.
Definition: DatabaseOracle.php:337
DatabaseOracle\removeIdentifierQuotes
removeIdentifierQuotes( $s)
Definition: DatabaseOracle.php:1086
user
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 and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
Definition: distributors.txt:25
DatabaseOracle\getDBname
getDBname()
Get the current DB name.
Definition: DatabaseOracle.php:1345
tableName
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes(). You will need both of them. ------------------------------------------------------------------------ Basic query optimisation ------------------------------------------------------------------------ MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them. Patches containing unacceptably slow features will not be accepted. Unindexed queries are generally not welcome in MediaWiki
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:577
$input
if(is_array( $mode)) switch( $mode) $input
Definition: postprocess-phan.php:145
DatabaseOracle\numRows
numRows( $res)
Definition: DatabaseOracle.php:295
Wikimedia\Rdbms\Database\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Definition: Database.php:762
DatabaseOracle\getServerVersion
getServerVersion()
Definition: DatabaseOracle.php:800
DatabaseOracle\getServer
getServer()
Get the server hostname or IP address.
Definition: DatabaseOracle.php:1349
DatabaseOracle\update
update( $table, $values, $conds, $fname=__METHOD__, $options=[])
Definition: DatabaseOracle.php:1227
DatabaseOracle\$ignoreDupValOnIndex
bool $ignoreDupValOnIndex
Definition: DatabaseOracle.php:41
Wikimedia\Rdbms\Database\$user
string $user
User that this instance is currently connected under the name of.
Definition: Database.php:81
DatabaseOracle
Definition: DatabaseOracle.php:33
DatabaseOracle\fetchRow
fetchRow( $res)
Definition: DatabaseOracle.php:283
DatabaseOracle\doBegin
doBegin( $fname=__METHOD__)
Issues the BEGIN command to the database server.
Definition: DatabaseOracle.php:937
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:95
DatabaseOracle\doQuery
doQuery( $sql)
Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
Definition: DatabaseOracle.php:191
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:994
query
For a write query
Definition: database.txt:26
DatabaseOracle\getSequenceData
getSequenceData( $table)
Return sequence_name if table has a sequence.
Definition: DatabaseOracle.php:653
DatabaseOracle\wasDeadlock
wasDeadlock()
Determines if the last failure was due to a deadlock.
Definition: DatabaseOracle.php:721
DatabaseOracle\addQuotes
addQuotes( $s)
Adds quotes and backslashes.
Definition: DatabaseOracle.php:1069
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:112
$options
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 & $options
Definition: hooks.txt:2001
DatabaseOracle\fetchObject
fetchObject( $res)
Definition: DatabaseOracle.php:271
$line
$line
Definition: cdb.php:59
DatabaseOracle\$sequenceData
bool array $sequenceData
Definition: DatabaseOracle.php:44
DatabaseOracle\buildStringCast
buildStringCast( $field)
Definition: DatabaseOracle.php:1375
DatabaseOracle\decodeBlob
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
Definition: DatabaseOracle.php:706
DBO_DDLMODE
const DBO_DDLMODE
Definition: defines.php:16
DatabaseOracle\unionQueries
unionQueries( $sqls, $all)
Construct a UNION query This is used for providing overload point for other DB abstractions not compa...
Definition: DatabaseOracle.php:714
DatabaseOracle\indexInfo
indexInfo( $table, $index, $fname=__METHOD__)
Returns information about an index If errors are explicitly ignored, returns NULL on failure.
Definition: DatabaseOracle.php:369
DatabaseOracle\wrapConditionsForWhere
wrapConditionsForWhere( $table, $conds, $parentCol=null)
Definition: DatabaseOracle.php:1107
DBO_SYSDBA
const DBO_SYSDBA
Definition: defines.php:15
Wikimedia\Rdbms\Database\$conn
resource null $conn
Database connection.
Definition: Database.php:108
DatabaseOracle\__destruct
__destruct()
Run a few simple sanity checks and close dangling connections.
Definition: DatabaseOracle.php:63
DatabaseOracle\makeSelectOptions
makeSelectOptions( $options)
Returns an optional USE INDEX clause to go after the table, and a string to go at the end of the quer...
Definition: DatabaseOracle.php:1143
DatabaseOracle\indexExists
indexExists( $table, $index, $fname=__METHOD__)
Query whether a given index exists.
Definition: DatabaseOracle.php:821
DatabaseOracle\dataSeek
dataSeek( $res, $row)
Definition: DatabaseOracle.php:329
Wikimedia\Rdbms\DBUnexpectedError
Definition: DBUnexpectedError.php:27
DatabaseOracle\getSoftwareLink
getSoftwareLink()
Definition: DatabaseOracle.php:793
ORAResult
The oci8 extension is fairly weak and doesn't support oci_num_rows, among other things.
Definition: ORAResult.php:11
DatabaseOracle\queryIgnore
queryIgnore( $sql, $fname='')
Definition: DatabaseOracle.php:251
DatabaseOracle\getInfinity
getInfinity()
Find out when 'infinity' is.
Definition: DatabaseOracle.php:1379
Wikimedia\Rdbms\Database\close
close()
Close the database connection.
Definition: Database.php:900
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
DatabaseOracle\open
open( $server, $user, $password, $dbName)
Usually aborts on failure.
Definition: DatabaseOracle.php:92
DatabaseOracle\$mLastResult
resource $mLastResult
Definition: DatabaseOracle.php:35
FROM
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to and or sell copies of the and to permit persons to whom the Software is furnished to do subject to the following WITHOUT WARRANTY OF ANY EXPRESS OR INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER WHETHER IN AN ACTION OF TORT OR ARISING FROM
Definition: LICENSE.txt:24
DatabaseOracle\isQuotedIdentifier
isQuotedIdentifier( $s)
Returns if the given identifier looks quoted or not according to the database convention for quoting ...
Definition: DatabaseOracle.php:1090
DatabaseOracle\sourceStream
sourceStream( $fp, callable $lineCallback=null, callable $resultCallback=null, $fname=__METHOD__, callable $inputCallback=null)
Read and execute commands from an open file handle.
Definition: DatabaseOracle.php:961
DatabaseOracle\insertId
insertId()
Get the inserted value of an auto-increment row.
Definition: DatabaseOracle.php:319
DatabaseOracle\buildSubstring
buildSubstring( $input, $startPosition, $length=null)
Definition: DatabaseOracle.php:1361
as
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:22
DatabaseOracle\fieldInfo
fieldInfo( $table, $field)
Definition: DatabaseOracle.php:929
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:26
Wikimedia\Rdbms\Database\$server
string $server
Server that this instance is currently connected to.
Definition: Database.php:79
DatabaseOracle\closeConnection
closeConnection()
Closes a database connection, if it is open Returns success, true if already closed.
Definition: DatabaseOracle.php:183
DatabaseOracle\bitNot
bitNot( $field)
Definition: DatabaseOracle.php:1332
DatabaseOracle\getType
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
Definition: DatabaseOracle.php:71
DatabaseOracle\indexUnique
indexUnique( $table, $index, $fname=__METHOD__)
Definition: DatabaseOracle.php:373
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2228
DatabaseOracle\implicitGroupby
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
Definition: DatabaseOracle.php:75
DatabaseOracle\$mFieldInfoCache
array $mFieldInfoCache
Definition: DatabaseOracle.php:50
DBO_DEFAULT
const DBO_DEFAULT
Definition: defines.php:13
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
DatabaseOracle\implicitOrderby
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
Definition: DatabaseOracle.php:79
server
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 and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break but it is *strongly *advised not to try any more intrusive changes to get MediaWiki to conform more closely to your filesystem hierarchy Any such attempt will almost certainly result in unnecessary bugs The standard recommended location to install relative to the web is it should be possible to enable the appropriate rewrite rules by if you can reconfigure the web server
Definition: distributors.txt:54
MWTimestamp\getLocalInstance
static getLocalInstance( $ts=false)
Get a timestamp instance in the server local timezone ($wgLocaltimezone)
Definition: MWTimestamp.php:204
DatabaseOracle\bitAnd
bitAnd( $fieldLeft, $fieldRight)
Definition: DatabaseOracle.php:1337
DatabaseOracle\fieldBindStatement
fieldBindStatement( $table, $col, &$val, $includeCol=false)
Definition: DatabaseOracle.php:406
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
DatabaseOracle\selectRow
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Single row SELECT wrapper.
Definition: DatabaseOracle.php:1125
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2171
$wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
Definition: design.txt:57
Wikimedia\Rdbms\Blob
Definition: Blob.php:5
DatabaseOracle\insertOneRow
insertOneRow( $table, $row, $fname)
Definition: DatabaseOracle.php:448
Wikimedia\Rdbms\Database\$dbName
string $dbName
Database that this instance is currently connected to.
Definition: Database.php:85
$wgActorTableSchemaMigrationStage
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
Definition: DefaultSettings.php:8878