MediaWiki  1.27.2
ApiResult.php
Go to the documentation of this file.
1 <?php
33 class ApiResult implements ApiSerializable {
34 
39  const OVERRIDE = 1;
40 
47  const ADD_ON_TOP = 2;
48 
56  const NO_SIZE_CHECK = 4;
57 
64  const NO_VALIDATE = 12;
65 
70  const META_INDEXED_TAG_NAME = '_element';
71 
76  const META_SUBELEMENTS = '_subelements';
77 
82  const META_PRESERVE_KEYS = '_preservekeys';
83 
88  const META_CONTENT = '_content';
89 
108  const META_TYPE = '_type';
109 
117  const META_KVP_KEY_NAME = '_kvpkeyname';
118 
127  const META_KVP_MERGE = '_kvpmerge';
128 
134  const META_BC_BOOLS = '_BC_bools';
135 
141  const META_BC_SUBELEMENTS = '_BC_subelements';
142 
143  private $data, $size, $maxSize;
145 
146  // Deprecated fields
148 
153  public function __construct( $maxSize ) {
154  if ( $maxSize instanceof ApiMain ) {
155  wfDeprecated( 'ApiMain to ' . __METHOD__, '1.25' );
156  $this->errorFormatter = $maxSize->getErrorFormatter();
157  $this->mainForContinuation = $maxSize;
158  $maxSize = $maxSize->getConfig()->get( 'APIMaxResultSize' );
159  }
160 
161  $this->maxSize = $maxSize;
162  $this->checkingSize = true;
163  $this->reset();
164  }
165 
171  public function setErrorFormatter( ApiErrorFormatter $formatter ) {
172  $this->errorFormatter = $formatter;
173  }
174 
180  public function serializeForApiResult() {
181  return $this->data;
182  }
183 
184  /************************************************************************/
192  public function reset() {
193  $this->data = [
194  self::META_TYPE => 'assoc', // Usually what's desired
195  ];
196  $this->size = 0;
197  }
198 
252  public function getResultData( $path = [], $transforms = [] ) {
253  $path = (array)$path;
254  if ( !$path ) {
255  return self::applyTransformations( $this->data, $transforms );
256  }
257 
258  $last = array_pop( $path );
259  $ret = &$this->path( $path, 'dummy' );
260  if ( !isset( $ret[$last] ) ) {
261  return null;
262  } elseif ( is_array( $ret[$last] ) ) {
263  return self::applyTransformations( $ret[$last], $transforms );
264  } else {
265  return $ret[$last];
266  }
267  }
268 
273  public function getSize() {
274  return $this->size;
275  }
276 
289  public static function setValue( array &$arr, $name, $value, $flags = 0 ) {
290  if ( ( $flags & ApiResult::NO_VALIDATE ) !== ApiResult::NO_VALIDATE ) {
291  $value = self::validateValue( $value );
292  }
293 
294  if ( $name === null ) {
295  if ( $flags & ApiResult::ADD_ON_TOP ) {
296  array_unshift( $arr, $value );
297  } else {
298  array_push( $arr, $value );
299  }
300  return;
301  }
302 
303  $exists = isset( $arr[$name] );
304  if ( !$exists || ( $flags & ApiResult::OVERRIDE ) ) {
305  if ( !$exists && ( $flags & ApiResult::ADD_ON_TOP ) ) {
306  $arr = [ $name => $value ] + $arr;
307  } else {
308  $arr[$name] = $value;
309  }
310  } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
311  $conflicts = array_intersect_key( $arr[$name], $value );
312  if ( !$conflicts ) {
313  $arr[$name] += $value;
314  } else {
315  $keys = implode( ', ', array_keys( $conflicts ) );
316  throw new RuntimeException(
317  "Conflicting keys ($keys) when attempting to merge element $name"
318  );
319  }
320  } else {
321  throw new RuntimeException(
322  "Attempting to add element $name=$value, existing value is {$arr[$name]}"
323  );
324  }
325  }
326 
332  private static function validateValue( $value ) {
334 
335  if ( is_object( $value ) ) {
336  // Note we use is_callable() here instead of instanceof because
337  // ApiSerializable is an informal protocol (see docs there for details).
338  if ( is_callable( [ $value, 'serializeForApiResult' ] ) ) {
339  $oldValue = $value;
340  $value = $value->serializeForApiResult();
341  if ( is_object( $value ) ) {
342  throw new UnexpectedValueException(
343  get_class( $oldValue ) . '::serializeForApiResult() returned an object of class ' .
344  get_class( $value )
345  );
346  }
347 
348  // Recursive call instead of fall-through so we can throw a
349  // better exception message.
350  try {
351  return self::validateValue( $value );
352  } catch ( Exception $ex ) {
353  throw new UnexpectedValueException(
354  get_class( $oldValue ) . '::serializeForApiResult() returned an invalid value: ' .
355  $ex->getMessage(),
356  0,
357  $ex
358  );
359  }
360  } elseif ( is_callable( [ $value, '__toString' ] ) ) {
361  $value = (string)$value;
362  } else {
363  $value = (array)$value + [ self::META_TYPE => 'assoc' ];
364  }
365  }
366  if ( is_array( $value ) ) {
367  // Work around PHP bug 45959 by copying to a temporary
368  // (in this case, foreach gets $k === "1" but $tmp[$k] assigns as if $k === 1)
369  $tmp = [];
370  foreach ( $value as $k => $v ) {
371  $tmp[$k] = self::validateValue( $v );
372  }
373  $value = $tmp;
374  } elseif ( is_float( $value ) && !is_finite( $value ) ) {
375  throw new InvalidArgumentException( 'Cannot add non-finite floats to ApiResult' );
376  } elseif ( is_string( $value ) ) {
377  $value = $wgContLang->normalize( $value );
378  } elseif ( $value !== null && !is_scalar( $value ) ) {
379  $type = gettype( $value );
380  if ( is_resource( $value ) ) {
381  $type .= '(' . get_resource_type( $value ) . ')';
382  }
383  throw new InvalidArgumentException( "Cannot add $type to ApiResult" );
384  }
385 
386  return $value;
387  }
388 
405  public function addValue( $path, $name, $value, $flags = 0 ) {
406  $arr = &$this->path( $path, ( $flags & ApiResult::ADD_ON_TOP ) ? 'prepend' : 'append' );
407 
408  if ( $this->checkingSize && !( $flags & ApiResult::NO_SIZE_CHECK ) ) {
409  // self::valueSize needs the validated value. Then flag
410  // to not re-validate later.
411  $value = self::validateValue( $value );
413 
414  $newsize = $this->size + self::valueSize( $value );
415  if ( $this->maxSize !== false && $newsize > $this->maxSize ) {
417  $msg = new ApiRawMessage( 'This result was truncated because it would otherwise ' .
418  ' be larger than the limit of $1 bytes', 'truncatedresult' );
419  $msg->numParams( $this->maxSize );
420  $this->errorFormatter->addWarning( 'result', $msg );
421  return false;
422  }
423  $this->size = $newsize;
424  }
425 
426  self::setValue( $arr, $name, $value, $flags );
427  return true;
428  }
429 
436  public static function unsetValue( array &$arr, $name ) {
437  $ret = null;
438  if ( isset( $arr[$name] ) ) {
439  $ret = $arr[$name];
440  unset( $arr[$name] );
441  }
442  return $ret;
443  }
444 
455  public function removeValue( $path, $name, $flags = 0 ) {
456  $path = (array)$path;
457  if ( $name === null ) {
458  if ( !$path ) {
459  throw new InvalidArgumentException( 'Cannot remove the data root' );
460  }
461  $name = array_pop( $path );
462  }
463  $ret = self::unsetValue( $this->path( $path, 'dummy' ), $name );
464  if ( $this->checkingSize && !( $flags & ApiResult::NO_SIZE_CHECK ) ) {
465  $newsize = $this->size - self::valueSize( $ret );
466  $this->size = max( $newsize, 0 );
467  }
468  return $ret;
469  }
470 
480  public static function setContentValue( array &$arr, $name, $value, $flags = 0 ) {
481  if ( $name === null ) {
482  throw new InvalidArgumentException( 'Content value must be named' );
483  }
484  self::setContentField( $arr, $name, $flags );
485  self::setValue( $arr, $name, $value, $flags );
486  }
487 
498  public function addContentValue( $path, $name, $value, $flags = 0 ) {
499  if ( $name === null ) {
500  throw new InvalidArgumentException( 'Content value must be named' );
501  }
502  $this->addContentField( $path, $name, $flags );
503  $this->addValue( $path, $name, $value, $flags );
504  }
505 
513  public function addParsedLimit( $moduleName, $limit ) {
514  // Add value, allowing overwriting
515  $this->addValue( 'limits', $moduleName, $limit,
517  }
518 
521  /************************************************************************/
534  public static function setContentField( array &$arr, $name, $flags = 0 ) {
535  if ( isset( $arr[self::META_CONTENT] ) &&
536  isset( $arr[$arr[self::META_CONTENT]] ) &&
537  !( $flags & self::OVERRIDE )
538  ) {
539  throw new RuntimeException(
540  "Attempting to set content element as $name when " . $arr[self::META_CONTENT] .
541  ' is already set as the content element'
542  );
543  }
544  $arr[self::META_CONTENT] = $name;
545  }
546 
555  public function addContentField( $path, $name, $flags = 0 ) {
556  $arr = &$this->path( $path, ( $flags & ApiResult::ADD_ON_TOP ) ? 'prepend' : 'append' );
557  self::setContentField( $arr, $name, $flags );
558  }
559 
567  public static function setSubelementsList( array &$arr, $names ) {
568  if ( !isset( $arr[self::META_SUBELEMENTS] ) ) {
569  $arr[self::META_SUBELEMENTS] = (array)$names;
570  } else {
571  $arr[self::META_SUBELEMENTS] = array_merge( $arr[self::META_SUBELEMENTS], (array)$names );
572  }
573  }
574 
582  public function addSubelementsList( $path, $names ) {
583  $arr = &$this->path( $path );
584  self::setSubelementsList( $arr, $names );
585  }
586 
594  public static function unsetSubelementsList( array &$arr, $names ) {
595  if ( isset( $arr[self::META_SUBELEMENTS] ) ) {
596  $arr[self::META_SUBELEMENTS] = array_diff( $arr[self::META_SUBELEMENTS], (array)$names );
597  }
598  }
599 
607  public function removeSubelementsList( $path, $names ) {
608  $arr = &$this->path( $path );
609  self::unsetSubelementsList( $arr, $names );
610  }
611 
618  public static function setIndexedTagName( array &$arr, $tag ) {
619  if ( !is_string( $tag ) ) {
620  throw new InvalidArgumentException( 'Bad tag name' );
621  }
622  $arr[self::META_INDEXED_TAG_NAME] = $tag;
623  }
624 
631  public function addIndexedTagName( $path, $tag ) {
632  $arr = &$this->path( $path );
633  self::setIndexedTagName( $arr, $tag );
634  }
635 
643  public static function setIndexedTagNameRecursive( array &$arr, $tag ) {
644  if ( !is_string( $tag ) ) {
645  throw new InvalidArgumentException( 'Bad tag name' );
646  }
647  $arr[self::META_INDEXED_TAG_NAME] = $tag;
648  foreach ( $arr as $k => &$v ) {
649  if ( !self::isMetadataKey( $k ) && is_array( $v ) ) {
650  self::setIndexedTagNameRecursive( $v, $tag );
651  }
652  }
653  }
654 
662  public function addIndexedTagNameRecursive( $path, $tag ) {
663  $arr = &$this->path( $path );
664  self::setIndexedTagNameRecursive( $arr, $tag );
665  }
666 
677  public static function setPreserveKeysList( array &$arr, $names ) {
678  if ( !isset( $arr[self::META_PRESERVE_KEYS] ) ) {
679  $arr[self::META_PRESERVE_KEYS] = (array)$names;
680  } else {
681  $arr[self::META_PRESERVE_KEYS] = array_merge( $arr[self::META_PRESERVE_KEYS], (array)$names );
682  }
683  }
684 
692  public function addPreserveKeysList( $path, $names ) {
693  $arr = &$this->path( $path );
694  self::setPreserveKeysList( $arr, $names );
695  }
696 
704  public static function unsetPreserveKeysList( array &$arr, $names ) {
705  if ( isset( $arr[self::META_PRESERVE_KEYS] ) ) {
706  $arr[self::META_PRESERVE_KEYS] = array_diff( $arr[self::META_PRESERVE_KEYS], (array)$names );
707  }
708  }
709 
717  public function removePreserveKeysList( $path, $names ) {
718  $arr = &$this->path( $path );
719  self::unsetPreserveKeysList( $arr, $names );
720  }
721 
730  public static function setArrayType( array &$arr, $type, $kvpKeyName = null ) {
731  if ( !in_array( $type, [
732  'default', 'array', 'assoc', 'kvp', 'BCarray', 'BCassoc', 'BCkvp'
733  ], true ) ) {
734  throw new InvalidArgumentException( 'Bad type' );
735  }
736  $arr[self::META_TYPE] = $type;
737  if ( is_string( $kvpKeyName ) ) {
738  $arr[self::META_KVP_KEY_NAME] = $kvpKeyName;
739  }
740  }
741 
749  public function addArrayType( $path, $tag, $kvpKeyName = null ) {
750  $arr = &$this->path( $path );
751  self::setArrayType( $arr, $tag, $kvpKeyName );
752  }
753 
761  public static function setArrayTypeRecursive( array &$arr, $type, $kvpKeyName = null ) {
762  self::setArrayType( $arr, $type, $kvpKeyName );
763  foreach ( $arr as $k => &$v ) {
764  if ( !self::isMetadataKey( $k ) && is_array( $v ) ) {
765  self::setArrayTypeRecursive( $v, $type, $kvpKeyName );
766  }
767  }
768  }
769 
777  public function addArrayTypeRecursive( $path, $tag, $kvpKeyName = null ) {
778  $arr = &$this->path( $path );
779  self::setArrayTypeRecursive( $arr, $tag, $kvpKeyName );
780  }
781 
784  /************************************************************************/
795  public static function isMetadataKey( $key ) {
796  return substr( $key, 0, 1 ) === '_';
797  }
798 
808  protected static function applyTransformations( array $dataIn, array $transforms ) {
809  $strip = isset( $transforms['Strip'] ) ? $transforms['Strip'] : 'none';
810  if ( $strip === 'base' ) {
811  $transforms['Strip'] = 'none';
812  }
813  $transformTypes = isset( $transforms['Types'] ) ? $transforms['Types'] : null;
814  if ( $transformTypes !== null && !is_array( $transformTypes ) ) {
815  throw new InvalidArgumentException( __METHOD__ . ':Value for "Types" must be an array' );
816  }
817 
818  $metadata = [];
819  $data = self::stripMetadataNonRecursive( $dataIn, $metadata );
820 
821  if ( isset( $transforms['Custom'] ) ) {
822  if ( !is_callable( $transforms['Custom'] ) ) {
823  throw new InvalidArgumentException( __METHOD__ . ': Value for "Custom" must be callable' );
824  }
825  call_user_func_array( $transforms['Custom'], [ &$data, &$metadata ] );
826  }
827 
828  if ( ( isset( $transforms['BC'] ) || $transformTypes !== null ) &&
829  isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] === 'BCkvp' &&
830  !isset( $metadata[self::META_KVP_KEY_NAME] )
831  ) {
832  throw new UnexpectedValueException( 'Type "BCkvp" used without setting ' .
833  'ApiResult::META_KVP_KEY_NAME metadata item' );
834  }
835 
836  // BC transformations
837  $boolKeys = null;
838  if ( isset( $transforms['BC'] ) ) {
839  if ( !is_array( $transforms['BC'] ) ) {
840  throw new InvalidArgumentException( __METHOD__ . ':Value for "BC" must be an array' );
841  }
842  if ( !in_array( 'nobool', $transforms['BC'], true ) ) {
843  $boolKeys = isset( $metadata[self::META_BC_BOOLS] )
844  ? array_flip( $metadata[self::META_BC_BOOLS] )
845  : [];
846  }
847 
848  if ( !in_array( 'no*', $transforms['BC'], true ) &&
849  isset( $metadata[self::META_CONTENT] ) && $metadata[self::META_CONTENT] !== '*'
850  ) {
851  $k = $metadata[self::META_CONTENT];
852  $data['*'] = $data[$k];
853  unset( $data[$k] );
854  $metadata[self::META_CONTENT] = '*';
855  }
856 
857  if ( !in_array( 'nosub', $transforms['BC'], true ) &&
858  isset( $metadata[self::META_BC_SUBELEMENTS] )
859  ) {
860  foreach ( $metadata[self::META_BC_SUBELEMENTS] as $k ) {
861  if ( isset( $data[$k] ) ) {
862  $data[$k] = [
863  '*' => $data[$k],
864  self::META_CONTENT => '*',
865  self::META_TYPE => 'assoc',
866  ];
867  }
868  }
869  }
870 
871  if ( isset( $metadata[self::META_TYPE] ) ) {
872  switch ( $metadata[self::META_TYPE] ) {
873  case 'BCarray':
874  case 'BCassoc':
875  $metadata[self::META_TYPE] = 'default';
876  break;
877  case 'BCkvp':
878  $transformTypes['ArmorKVP'] = $metadata[self::META_KVP_KEY_NAME];
879  break;
880  }
881  }
882  }
883 
884  // Figure out type, do recursive calls, and do boolean transform if necessary
885  $defaultType = 'array';
886  $maxKey = -1;
887  foreach ( $data as $k => &$v ) {
888  $v = is_array( $v ) ? self::applyTransformations( $v, $transforms ) : $v;
889  if ( $boolKeys !== null && is_bool( $v ) && !isset( $boolKeys[$k] ) ) {
890  if ( !$v ) {
891  unset( $data[$k] );
892  continue;
893  }
894  $v = '';
895  }
896  if ( is_string( $k ) ) {
897  $defaultType = 'assoc';
898  } elseif ( $k > $maxKey ) {
899  $maxKey = $k;
900  }
901  }
902  unset( $v );
903 
904  // Determine which metadata to keep
905  switch ( $strip ) {
906  case 'all':
907  case 'base':
908  $keepMetadata = [];
909  break;
910  case 'none':
911  $keepMetadata = &$metadata;
912  break;
913  case 'bc':
914  $keepMetadata = array_intersect_key( $metadata, [
915  self::META_INDEXED_TAG_NAME => 1,
916  self::META_SUBELEMENTS => 1,
917  ] );
918  break;
919  default:
920  throw new InvalidArgumentException( __METHOD__ . ': Unknown value for "Strip"' );
921  }
922 
923  // Type transformation
924  if ( $transformTypes !== null ) {
925  if ( $defaultType === 'array' && $maxKey !== count( $data ) - 1 ) {
926  $defaultType = 'assoc';
927  }
928 
929  // Override type, if provided
930  $type = $defaultType;
931  if ( isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] !== 'default' ) {
932  $type = $metadata[self::META_TYPE];
933  }
934  if ( ( $type === 'kvp' || $type === 'BCkvp' ) &&
935  empty( $transformTypes['ArmorKVP'] )
936  ) {
937  $type = 'assoc';
938  } elseif ( $type === 'BCarray' ) {
939  $type = 'array';
940  } elseif ( $type === 'BCassoc' ) {
941  $type = 'assoc';
942  }
943 
944  // Apply transformation
945  switch ( $type ) {
946  case 'assoc':
947  $metadata[self::META_TYPE] = 'assoc';
948  $data += $keepMetadata;
949  return empty( $transformTypes['AssocAsObject'] ) ? $data : (object)$data;
950 
951  case 'array':
952  ksort( $data );
953  $data = array_values( $data );
954  $metadata[self::META_TYPE] = 'array';
955  return $data + $keepMetadata;
956 
957  case 'kvp':
958  case 'BCkvp':
959  $key = isset( $metadata[self::META_KVP_KEY_NAME] )
960  ? $metadata[self::META_KVP_KEY_NAME]
961  : $transformTypes['ArmorKVP'];
962  $valKey = isset( $transforms['BC'] ) ? '*' : 'value';
963  $assocAsObject = !empty( $transformTypes['AssocAsObject'] );
964  $merge = !empty( $metadata[self::META_KVP_MERGE] );
965 
966  $ret = [];
967  foreach ( $data as $k => $v ) {
968  if ( $merge && ( is_array( $v ) || is_object( $v ) ) ) {
969  $vArr = (array)$v;
970  if ( isset( $vArr[self::META_TYPE] ) ) {
971  $mergeType = $vArr[self::META_TYPE];
972  } elseif ( is_object( $v ) ) {
973  $mergeType = 'assoc';
974  } else {
975  $keys = array_keys( $vArr );
976  sort( $keys, SORT_NUMERIC );
977  $mergeType = ( $keys === array_keys( $keys ) ) ? 'array' : 'assoc';
978  }
979  } else {
980  $mergeType = 'n/a';
981  }
982  if ( $mergeType === 'assoc' ) {
983  $item = $vArr + [
984  $key => $k,
985  ];
986  if ( $strip === 'none' ) {
987  self::setPreserveKeysList( $item, [ $key ] );
988  }
989  } else {
990  $item = [
991  $key => $k,
992  $valKey => $v,
993  ];
994  if ( $strip === 'none' ) {
995  $item += [
996  self::META_PRESERVE_KEYS => [ $key ],
997  self::META_CONTENT => $valKey,
998  self::META_TYPE => 'assoc',
999  ];
1000  }
1001  }
1002  $ret[] = $assocAsObject ? (object)$item : $item;
1003  }
1004  $metadata[self::META_TYPE] = 'array';
1005 
1006  return $ret + $keepMetadata;
1007 
1008  default:
1009  throw new UnexpectedValueException( "Unknown type '$type'" );
1010  }
1011  } else {
1012  return $data + $keepMetadata;
1013  }
1014  }
1015 
1026  public static function stripMetadata( $data ) {
1027  if ( is_array( $data ) || is_object( $data ) ) {
1028  $isObj = is_object( $data );
1029  if ( $isObj ) {
1030  $data = (array)$data;
1031  }
1032  $preserveKeys = isset( $data[self::META_PRESERVE_KEYS] )
1033  ? (array)$data[self::META_PRESERVE_KEYS]
1034  : [];
1035  foreach ( $data as $k => $v ) {
1036  if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1037  unset( $data[$k] );
1038  } elseif ( is_array( $v ) || is_object( $v ) ) {
1039  $data[$k] = self::stripMetadata( $v );
1040  }
1041  }
1042  if ( $isObj ) {
1043  $data = (object)$data;
1044  }
1045  }
1046  return $data;
1047  }
1048 
1060  public static function stripMetadataNonRecursive( $data, &$metadata = null ) {
1061  if ( !is_array( $metadata ) ) {
1062  $metadata = [];
1063  }
1064  if ( is_array( $data ) || is_object( $data ) ) {
1065  $isObj = is_object( $data );
1066  if ( $isObj ) {
1067  $data = (array)$data;
1068  }
1069  $preserveKeys = isset( $data[self::META_PRESERVE_KEYS] )
1070  ? (array)$data[self::META_PRESERVE_KEYS]
1071  : [];
1072  foreach ( $data as $k => $v ) {
1073  if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1074  $metadata[$k] = $v;
1075  unset( $data[$k] );
1076  }
1077  }
1078  if ( $isObj ) {
1079  $data = (object)$data;
1080  }
1081  }
1082  return $data;
1083  }
1084 
1093  private static function valueSize( $value ) {
1094  $s = 0;
1095  if ( is_array( $value ) ) {
1096  foreach ( $value as $k => $v ) {
1097  if ( !self::isMetadataKey( $k ) ) {
1098  $s += self::valueSize( $v );
1099  }
1100  }
1101  } elseif ( is_scalar( $value ) ) {
1102  $s = strlen( $value );
1103  }
1104 
1105  return $s;
1106  }
1107 
1119  private function &path( $path, $create = 'append' ) {
1120  $path = (array)$path;
1121  $ret = &$this->data;
1122  foreach ( $path as $i => $k ) {
1123  if ( !isset( $ret[$k] ) ) {
1124  switch ( $create ) {
1125  case 'append':
1126  $ret[$k] = [];
1127  break;
1128  case 'prepend':
1129  $ret = [ $k => [] ] + $ret;
1130  break;
1131  case 'dummy':
1132  $tmp = [];
1133  return $tmp;
1134  default:
1135  $fail = implode( '.', array_slice( $path, 0, $i + 1 ) );
1136  throw new InvalidArgumentException( "Path $fail does not exist" );
1137  }
1138  }
1139  if ( !is_array( $ret[$k] ) ) {
1140  $fail = implode( '.', array_slice( $path, 0, $i + 1 ) );
1141  throw new InvalidArgumentException( "Path $fail is not an array" );
1142  }
1143  $ret = &$ret[$k];
1144  }
1145  return $ret;
1146  }
1147 
1156  public static function addMetadataToResultVars( $vars, $forceHash = true ) {
1157  // Process subarrays and determine if this is a JS [] or {}
1158  $hash = $forceHash;
1159  $maxKey = -1;
1160  $bools = [];
1161  foreach ( $vars as $k => $v ) {
1162  if ( is_array( $v ) || is_object( $v ) ) {
1163  $vars[$k] = ApiResult::addMetadataToResultVars( (array)$v, is_object( $v ) );
1164  } elseif ( is_bool( $v ) ) {
1165  // Better here to use real bools even in BC formats
1166  $bools[] = $k;
1167  }
1168  if ( is_string( $k ) ) {
1169  $hash = true;
1170  } elseif ( $k > $maxKey ) {
1171  $maxKey = $k;
1172  }
1173  }
1174  if ( !$hash && $maxKey !== count( $vars ) - 1 ) {
1175  $hash = true;
1176  }
1177 
1178  // Set metadata appropriately
1179  if ( $hash ) {
1180  // Get the list of keys we actually care about. Unfortunately, we can't support
1181  // certain keys that conflict with ApiResult metadata.
1182  $keys = array_diff( array_keys( $vars ), [
1185  ] );
1186 
1187  return [
1188  ApiResult::META_TYPE => 'kvp',
1191  ApiResult::META_BC_BOOLS => $bools,
1193  ] + $vars;
1194  } else {
1195  return [
1196  ApiResult::META_TYPE => 'array',
1197  ApiResult::META_BC_BOOLS => $bools,
1199  ] + $vars;
1200  }
1201  }
1202 
1205  /************************************************************************/
1216  public function setRawMode( $flag = true ) {
1217  wfDeprecated( __METHOD__, '1.25' );
1218  }
1219 
1225  public function getIsRawMode() {
1226  wfDeprecated( __METHOD__, '1.25' );
1227  return true;
1228  }
1229 
1235  public function getData() {
1236  wfDeprecated( __METHOD__, '1.25' );
1237  return $this->getResultData( null, [
1238  'BC' => [],
1239  'Types' => [],
1240  'Strip' => 'all',
1241  ] );
1242  }
1243 
1250  public function disableSizeCheck() {
1251  wfDeprecated( __METHOD__, '1.24' );
1252  $this->checkingSize = false;
1253  }
1254 
1259  public function enableSizeCheck() {
1260  wfDeprecated( __METHOD__, '1.24' );
1261  $this->checkingSize = true;
1262  }
1263 
1277  public static function setElement( &$arr, $name, $value, $flags = 0 ) {
1278  wfDeprecated( __METHOD__, '1.25' );
1279  self::setValue( $arr, $name, $value, $flags );
1280  }
1281 
1292  public static function setContent( &$arr, $value, $subElemName = null ) {
1293  wfDeprecated( __METHOD__, '1.25' );
1294  if ( is_array( $value ) ) {
1295  throw new InvalidArgumentException( __METHOD__ . ': Bad parameter' );
1296  }
1297  if ( is_null( $subElemName ) ) {
1298  self::setContentValue( $arr, 'content', $value );
1299  } else {
1300  if ( !isset( $arr[$subElemName] ) ) {
1301  $arr[$subElemName] = [];
1302  }
1303  self::setContentValue( $arr[$subElemName], 'content', $value );
1304  }
1305  }
1306 
1316  public function setIndexedTagName_recursive( &$arr, $tag ) {
1317  wfDeprecated( __METHOD__, '1.25' );
1318  if ( !is_array( $arr ) ) {
1319  return;
1320  }
1321  if ( !is_string( $tag ) ) {
1322  throw new InvalidArgumentException( 'Bad tag name' );
1323  }
1324  foreach ( $arr as $k => &$v ) {
1325  if ( !self::isMetadataKey( $k ) && is_array( $v ) ) {
1326  $v[self::META_INDEXED_TAG_NAME] = $tag;
1327  $this->setIndexedTagName_recursive( $v, $tag );
1328  }
1329  }
1330  }
1331 
1338  public function setIndexedTagName_internal( $path, $tag ) {
1339  wfDeprecated( __METHOD__, '1.25' );
1340  $this->addIndexedTagName( $path, $tag );
1341  }
1342 
1349  public function setParsedLimit( $moduleName, $limit ) {
1350  wfDeprecated( __METHOD__, '1.25' );
1351  $this->addParsedLimit( $moduleName, $limit );
1352  }
1353 
1360  public function setMainForContinuation( ApiMain $main ) {
1361  $this->mainForContinuation = $main;
1362  }
1363 
1376  public function beginContinuation(
1377  $continue, array $allModules = [], array $generatedModules = []
1378  ) {
1379  wfDeprecated( __METHOD__, '1.25' );
1380  if ( $this->mainForContinuation->getContinuationManager() ) {
1381  throw new UnexpectedValueException(
1382  __METHOD__ . ': Continuation already in progress from ' .
1383  $this->mainForContinuation->getContinuationManager()->getSource()
1384  );
1385  }
1386 
1387  // Ugh. If $continue doesn't match that in the request, temporarily
1388  // replace the request when creating the ApiContinuationManager.
1389  if ( $continue === null ) {
1390  $continue = '';
1391  }
1392  if ( $this->mainForContinuation->getVal( 'continue', '' ) !== $continue ) {
1393  $oldCtx = $this->mainForContinuation->getContext();
1394  $newCtx = new DerivativeContext( $oldCtx );
1395  $newCtx->setRequest( new DerivativeRequest(
1396  $oldCtx->getRequest(),
1397  [ 'continue' => $continue ] + $oldCtx->getRequest()->getValues(),
1398  $oldCtx->getRequest()->wasPosted()
1399  ) );
1400  $this->mainForContinuation->setContext( $newCtx );
1401  $reset = new ScopedCallback(
1402  [ $this->mainForContinuation, 'setContext' ],
1403  [ $oldCtx ]
1404  );
1405  }
1406  $manager = new ApiContinuationManager(
1407  $this->mainForContinuation, $allModules, $generatedModules
1408  );
1409  $reset = null;
1410 
1411  $this->mainForContinuation->setContinuationManager( $manager );
1412 
1413  return [
1414  $manager->isGeneratorDone(),
1415  $manager->getRunModules(),
1416  ];
1417  }
1418 
1426  public function setContinueParam( ApiBase $module, $paramName, $paramValue ) {
1427  wfDeprecated( __METHOD__, '1.25' );
1428  if ( $this->mainForContinuation->getContinuationManager() ) {
1429  $this->mainForContinuation->getContinuationManager()->addContinueParam(
1430  $module, $paramName, $paramValue
1431  );
1432  }
1433  }
1434 
1442  public function setGeneratorContinueParam( ApiBase $module, $paramName, $paramValue ) {
1443  wfDeprecated( __METHOD__, '1.25' );
1444  if ( $this->mainForContinuation->getContinuationManager() ) {
1445  $this->mainForContinuation->getContinuationManager()->addGeneratorContinueParam(
1446  $module, $paramName, $paramValue
1447  );
1448  }
1449  }
1450 
1458  public function endContinuation( $style = 'standard' ) {
1459  wfDeprecated( __METHOD__, '1.25' );
1460  if ( !$this->mainForContinuation->getContinuationManager() ) {
1461  return;
1462  }
1463 
1464  if ( $style === 'raw' ) {
1465  $data = $this->mainForContinuation->getContinuationManager()->getRawContinuation();
1466  if ( $data ) {
1467  $this->addValue( null, 'query-continue', $data, self::ADD_ON_TOP | self::NO_SIZE_CHECK );
1468  }
1469  } else {
1470  $this->mainForContinuation->getContinuationManager()->setContinuationIntoResult( $this );
1471  }
1472  }
1473 
1478  public function cleanUpUTF8() {
1479  wfDeprecated( __METHOD__, '1.25' );
1480  }
1481 
1491  public static function size( $value ) {
1492  wfDeprecated( __METHOD__, '1.25' );
1493  return self::valueSize( self::validateValue( $value ) );
1494  }
1495 
1503  public function convertStatusToArray( $status, $errorType = 'error' ) {
1504  wfDeprecated( __METHOD__, '1.25' );
1505  return $this->errorFormatter->arrayFromStatus( $status, $errorType );
1506  }
1507 
1509 }
1510 
& path($path, $create= 'append')
Return a reference to the internal data at $path.
Definition: ApiResult.php:1119
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 data
Definition: hooks.txt:6
the array() calling protocol came about after MediaWiki 1.4rc1.
Formats errors and warnings for the API, and add them to the associated ApiResult.
setErrorFormatter(ApiErrorFormatter $formatter)
Set the error formatter.
Definition: ApiResult.php:171
endContinuation($style= 'standard')
Close continuation, writing the data into the result.
Definition: ApiResult.php:1458
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
addSubelementsList($path, $names)
Causes the elements with the specified names to be output as subelements rather than attributes...
Definition: ApiResult.php:582
static unsetSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as attributes (when possible) rather than a...
Definition: ApiResult.php:594
$mainForContinuation
Definition: ApiResult.php:147
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:1798
An IContextSource implementation which will inherit context from another source but allow individual ...
Similar to FauxRequest, but only fakes URL parameters and method (POST or GET) and use the base reque...
This manages continuation state.
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:177
$value
setRawMode($flag=true)
Formerly used to enable/disable "raw mode".
Definition: ApiResult.php:1216
const META_TYPE
Key for the 'type' metadata item.
Definition: ApiResult.php:108
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
removeValue($path, $name, $flags=0)
Remove value from the output data at the given path.
Definition: ApiResult.php:455
getSize()
Get the size of the result, i.e.
Definition: ApiResult.php:273
const META_PRESERVE_KEYS
Key for the 'preserve keys' metadata item.
Definition: ApiResult.php:82
const ADD_ON_TOP
For addValue(), setValue() and similar functions, if the value does not exist, add it as the first el...
Definition: ApiResult.php:47
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
Definition: ApiResult.php:480
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:618
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition: globals.txt:25
static size($value)
Get the 'real' size of a result item.
Definition: ApiResult.php:1491
addParsedLimit($moduleName, $limit)
Add the numeric limit for a limit=max to the result.
Definition: ApiResult.php:513
getData()
Get the result's internal data array (read-only)
Definition: ApiResult.php:1235
setGeneratorContinueParam(ApiBase $module, $paramName, $paramValue)
Definition: ApiResult.php:1442
getIsRawMode()
Returns true, the equivalent of "raw mode" is always enabled now.
Definition: ApiResult.php:1225
$last
serializeForApiResult()
Allow for adding one ApiResult into another.
Definition: ApiResult.php:180
Class for asserting that a callback happens when an dummy object leaves scope.
static unsetValue(array &$arr, $name)
Remove an output value to the array by name.
Definition: ApiResult.php:436
cleanUpUTF8()
No-op, this is now checked on insert.
Definition: ApiResult.php:1478
addIndexedTagName($path, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:631
setIndexedTagName_internal($path, $tag)
Alias for self::addIndexedTagName()
Definition: ApiResult.php:1338
addValue($path, $name, $value, $flags=0)
Add value to the output data at the given path.
Definition: ApiResult.php:405
addPreserveKeysList($path, $names)
Preserve specified keys.
Definition: ApiResult.php:692
static stripMetadata($data)
Recursively remove metadata keys from a data array or object.
Definition: ApiResult.php:1026
setParsedLimit($moduleName, $limit)
Alias for self::addParsedLimit()
Definition: ApiResult.php:1349
static setArrayTypeRecursive(array &$arr, $type, $kvpKeyName=null)
Set the array data type recursively.
Definition: ApiResult.php:761
static validateValue($value)
Validate a value for addition to the result.
Definition: ApiResult.php:332
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
static applyTransformations(array $dataIn, array $transforms)
Apply transformations to an array, returning the transformed array.
Definition: ApiResult.php:808
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
beginContinuation($continue, array $allModules=[], array $generatedModules=[])
Parse a 'continue' parameter and return status information.
Definition: ApiResult.php:1376
static stripMetadataNonRecursive($data, &$metadata=null)
Remove metadata keys from a data array or object, non-recursive.
Definition: ApiResult.php:1060
const META_KVP_MERGE
Key for the metadata item that indicates that the KVP key should be added into an assoc value...
Definition: ApiResult.php:127
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
Definition: ApiResult.php:56
This interface allows for overriding the default conversion applied by ApiResult::validateValue().
This class represents the result of the API operations.
Definition: ApiResult.php:33
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition: hooks.txt:965
const NO_VALIDATE
For addValue(), setValue() and similar functions, do not validate data.
Definition: ApiResult.php:64
static setElement(&$arr, $name, $value, $flags=0)
Alias for self::setValue()
Definition: ApiResult.php:1277
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
static setSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as subelements rather than attributes...
Definition: ApiResult.php:567
static setIndexedTagNameRecursive(array &$arr, $tag)
Set indexed tag name on $arr and all subarrays.
Definition: ApiResult.php:643
static valueSize($value)
Get the 'real' size of a result item.
Definition: ApiResult.php:1093
static unsetPreserveKeysList(array &$arr, $names)
Don't preserve specified keys.
Definition: ApiResult.php:704
addArrayType($path, $tag, $kvpKeyName=null)
Set the array data type for a path.
Definition: ApiResult.php:749
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
convertStatusToArray($status, $errorType= 'error')
Converts a Status object to an array suitable for addValue.
Definition: ApiResult.php:1503
addContentValue($path, $name, $value, $flags=0)
Add value to the output data at the given path and mark as META_CONTENT.
Definition: ApiResult.php:498
removeSubelementsList($path, $names)
Causes the elements with the specified names to be output as attributes (when possible) rather than a...
Definition: ApiResult.php:607
const META_INDEXED_TAG_NAME
Key for the 'indexed tag name' metadata item.
Definition: ApiResult.php:70
static addMetadataToResultVars($vars, $forceHash=true)
Add the correct metadata to an array of vars we want to export through the API.
Definition: ApiResult.php:1156
setMainForContinuation(ApiMain $main)
Set the ApiMain for use by $this->beginContinuation()
Definition: ApiResult.php:1360
static setValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name.
Definition: ApiResult.php:289
const META_SUBELEMENTS
Key for the 'subelements' metadata item.
Definition: ApiResult.php:76
reset()
Clear the current result data.
Definition: ApiResult.php:192
removePreserveKeysList($path, $names)
Don't preserve specified keys.
Definition: ApiResult.php:717
addContentField($path, $name, $flags=0)
Set the name of the content field name (META_CONTENT)
Definition: ApiResult.php:555
const META_BC_BOOLS
Key for the 'BC bools' metadata item.
Definition: ApiResult.php:134
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition: hooks.txt:1004
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 local content language as $wgContLang
Definition: design.txt:56
setIndexedTagName_recursive(&$arr, $tag)
Set indexed tag name on all subarrays of $arr.
Definition: ApiResult.php:1316
addArrayTypeRecursive($path, $tag, $kvpKeyName=null)
Set the array data type for a path recursively.
Definition: ApiResult.php:777
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1004
Extension of RawMessage implementing IApiMessage.
Definition: ApiMessage.php:171
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
addIndexedTagNameRecursive($path, $tag)
Set indexed tag name on $path and all subarrays.
Definition: ApiResult.php:662
static setPreserveKeysList(array &$arr, $names)
Preserve specified keys.
Definition: ApiResult.php:677
static setContentField(array &$arr, $name, $flags=0)
Set the name of the content field name (META_CONTENT)
Definition: ApiResult.php:534
const META_CONTENT
Key for the 'content' metadata item.
Definition: ApiResult.php:88
static setContent(&$arr, $value, $subElemName=null)
Adds a content element to an array.
Definition: ApiResult.php:1292
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
Definition: ApiResult.php:730
enableSizeCheck()
Re-enable size checking in addValue()
Definition: ApiResult.php:1259
const META_BC_SUBELEMENTS
Key for the 'BC subelements' metadata item.
Definition: ApiResult.php:141
const OVERRIDE
Override existing value in addValue(), setValue(), and similar functions.
Definition: ApiResult.php:39
disableSizeCheck()
Disable size checking in addValue().
Definition: ApiResult.php:1250
getResultData($path=[], $transforms=[])
Get the result data array.
Definition: ApiResult.php:252
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:1996
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2338
setContinueParam(ApiBase $module, $paramName, $paramValue)
Definition: ApiResult.php:1426
__construct($maxSize)
Definition: ApiResult.php:153
const META_KVP_KEY_NAME
Key for the metadata item whose value specifies the name used for the kvp key in the alternative outp...
Definition: ApiResult.php:117
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310
static isMetadataKey($key)
Test whether a key should be considered metadata.
Definition: ApiResult.php:795