/// <summary> /// Currently not supported. /// </summary> public bool setCompressionIndex(int index, int comp_method, int comp_flags = 0) { PhpException.FunctionNotSupported(nameof(setCompressionIndex)); return(false); }
public static PhpArray /*!*/ filter_list() { PhpException.FunctionNotSupported(nameof(filter_list)); return(new PhpArray()); }
public static PhpString exif_thumbnail(Context ctx, string filename, PhpAlias width = null, PhpAlias height = null, PhpAlias imagetype = null) { if (string.IsNullOrEmpty(filename)) { PhpException.Throw(PhpError.Warning, Resources.filename_cannot_be_empty); return(default(PhpString)); } Image <Rgba32> thumbnail = null; IImageFormat format = null; byte[] result; var bytes = Utils.ReadPhpBytes(ctx, filename); if (bytes == null) { return(default(PhpString)); } // get thumbnail from <filename>'s content: using (var ms = new MemoryStream(bytes)) { try { using (var image = Image.Load(ms, out format)) { // return byte[] ~ image.MetaData.ExifProfile{ this.data, this.thumbnailOffset, this.thumbnailLength } thumbnail = image.MetaData.ExifProfile.CreateThumbnail <Rgba32>(); } } catch { return(default(PhpString)); } } if (thumbnail == null) { return(default(PhpString)); } // if (width != null) { width.Value = (PhpValue)thumbnail.Width; } if (height != null) { height.Value = (PhpValue)thumbnail.Height; } if (imagetype != null) // TODO: get thumbnail image format { imagetype.Value = (PhpValue)(format == ImageFormats.Jpeg ? PhpImage.IMAGETYPE_JPEG : PhpImage.IMAGETYPE_TIFF_II); } using (var ms2 = new MemoryStream()) { thumbnail.Save(ms2, new PngEncoder()); result = ms2.ToArray(); } thumbnail.Dispose(); // return(new PhpString(result)); }
public void setIdAttributeNS(string namespaceUri, string localName, bool isId) { PhpException.Throw(PhpError.Warning, Resources.NotYetImplemented); }
/// <summary> /// Unserializes storage entries and attach them to the current storage. /// </summary> public virtual void unserialize(PhpString serialized) { // x:{count_int};{item0},{value0};...;m:{members_array} if (serialized.Length < 12) { throw new ArgumentException(nameof(serialized)); // quick check } var stream = new MemoryStream(serialized.ToBytes(_ctx)); try { var reader = new PhpSerialization.PhpSerializer.ObjectReader(_ctx, stream, default); // x: if (stream.ReadByte() != 'x' || stream.ReadByte() != ':') { throw new InvalidDataException(); } // i:{count}; var tmp = reader.Deserialize(); if (!tmp.IsLong(out var count) || count < 0) { throw new InvalidDataException(); } stream.Seek(-1, SeekOrigin.Current); // back to `;` // {item},{value} while (count-- > 0) { // ;obj if (stream.ReadByte() != ';') { throw new InvalidDataException(); } var obj = reader.Deserialize(); // ,data PhpValue data; if (stream.ReadByte() == ',') { data = reader.Deserialize(); } else { // backward compatibility with data created with old PHP SplObjectStorage data = PhpValue.Void; stream.Seek(-1, SeekOrigin.Current); // back to `;` } // Keys.AttachImpl(storage, obj.AsObject(), data); } // ; if (stream.ReadByte() != ';') { throw new InvalidDataException(); } // m:{array} if (stream.ReadByte() != 'm' || stream.ReadByte() != ':') { throw new InvalidDataException(); } tmp = reader.Deserialize(); if (tmp.IsArray) { var arr = tmp.AsArray(); if (arr != null && arr.Count != 0) // do not leak empty arrays { __peach__runtimeFields = arr; } } else { throw new InvalidDataException(); } } catch (Exception e) { PhpException.Throw(PhpError.Notice, Resources.LibResources.deserialization_failed, e.Message, stream.Position.ToString(), stream.Length.ToString()); } }
public static PhpString gzinflate(byte[] data, long length = 0) { uint factor = 1, maxfactor = 16; long ilength; var zs = new ZStream(); zs.avail_in = data.Length; zs.next_in = data; zs.total_out = 0; // -15 omits the header (undocumented feature of zlib) int status = zs.inflateInit(-15); if (status != zlibConst.Z_OK) { PhpException.Throw(PhpError.Warning, zError(status)); return(null); } do { ilength = length != 0 ? length : data.Length * (1 << (int)(factor++)); try { byte[] newOutput = new byte[ilength]; if (zs.next_out != null) { Buffer.BlockCopy(zs.next_out, 0, newOutput, 0, zs.next_out.Length); } zs.next_out = newOutput; } catch (OutOfMemoryException) { zs.inflateEnd(); return(null); } zs.next_out_index = (int)zs.total_out; zs.avail_out = unchecked ((int)(ilength - zs.total_out)); status = zs.inflate(zlibConst.Z_NO_FLUSH); }while ((status == zlibConst.Z_BUF_ERROR || (status == zlibConst.Z_OK && (zs.avail_in != 0 || zs.avail_out == 0))) && length == 0 && factor < maxfactor); zs.inflateEnd(); if ((length != 0 && status == zlibConst.Z_OK) || factor >= maxfactor) { status = zlibConst.Z_MEM_ERROR; } if (status == zlibConst.Z_STREAM_END || status == zlibConst.Z_OK) { byte[] result = new byte[zs.total_out]; Buffer.BlockCopy(zs.next_out, 0, result, 0, (int)zs.total_out); return(new PhpString(result)); } else { PhpException.Throw(PhpError.Warning, zError(status)); return(null); } }
public static PhpString gzencode(byte[] data, int level = -1, int encoding_mode = FORCE_GZIP) { if ((level < -1) || (level > 9)) { PhpException.Throw(PhpError.Warning, "compression level ({0}) must be within -1..9", level.ToString()); return(null); } ZStream zs = new ZStream(); int status = zlibConst.Z_OK; zs.next_in = data; zs.avail_in = data.Length; // heuristic for max data length zs.avail_out = data.Length + data.Length / Zlib.PHP_ZLIB_MODIFIER + 15 + 1; zs.next_out = new byte[zs.avail_out]; switch (encoding_mode) { case (int)ForceConstants.FORCE_GZIP: if ((status = zs.deflateInit(level, -MAX_WBITS)) != zlibConst.Z_OK) { PhpException.Throw(PhpError.Warning, zError(status)); return(null); } break; case (int)ForceConstants.FORCE_DEFLATE: if ((status = zs.deflateInit(level)) != zlibConst.Z_OK) { PhpException.Throw(PhpError.Warning, zError(status)); return(null); } break; } status = zs.deflate(zlibConst.Z_FINISH); if (status != zlibConst.Z_STREAM_END) { zs.deflateEnd(); if (status == zlibConst.Z_OK) { status = zlibConst.Z_STREAM_ERROR; } } else { status = zs.deflateEnd(); } z_error = zs.msg; if (status == zlibConst.Z_OK) { long output_length = zs.total_out + (encoding_mode == (int)ForceConstants.FORCE_GZIP ? GZIP_HEADER_LENGTH + GZIP_FOOTER_LENGTH : GZIP_HEADER_LENGTH); long output_offset = GZIP_HEADER_LENGTH; byte[] output = new byte[output_length]; Buffer.BlockCopy(zs.next_out, 0, output, (int)output_offset, (int)zs.total_out); // fill the header output[0] = GZIP_HEADER[0]; output[1] = GZIP_HEADER[1]; output[2] = Z_DEFLATED; // zlib constant (private in ZLIB.NET) output[3] = 0; // reserved flag bits (this function puts invalid flags in here) // 4-8 represent time and are set to zero output[9] = OS_CODE; // php constant if (encoding_mode == (int)ForceConstants.FORCE_GZIP) { var crc_algo = new PhpHash.HashPhpResource.CRC32(); byte[] crc = crc_algo.ComputeHash(data); crc_algo.Dispose(); output[output_length - 8] = crc[0]; output[output_length - 7] = crc[1]; output[output_length - 6] = crc[2]; output[output_length - 5] = crc[3]; output[output_length - 4] = (byte)(zs.total_in & 0xFF); output[output_length - 3] = (byte)((zs.total_in >> 8) & 0xFF); output[output_length - 2] = (byte)((zs.total_in >> 16) & 0xFF); output[output_length - 1] = (byte)((zs.total_in >> 24) & 0xFF); } return(new PhpString(output)); } else { PhpException.Throw(PhpError.Warning, zError(status)); return(null); } }
/// <summary> /// Currently not supported. /// </summary> public bool renameName(string name, string newname) { PhpException.FunctionNotSupported(nameof(renameName)); return(false); }
/// <summary> /// Currently not supported. /// </summary> public bool renameIndex(int index, string newname) { PhpException.FunctionNotSupported(nameof(renameIndex)); return(false); }
/// <summary> /// Currently not supported. /// </summary> public bool unchangeIndex(int index) { PhpException.FunctionNotSupported(nameof(unchangeIndex)); return(false); }
/// <summary> /// Currently not supported. /// </summary> public bool unchangeName(string name) { PhpException.FunctionNotSupported(nameof(unchangeName)); return(false); }
/// <summary> /// Currently not supported. /// </summary> public bool unchangeArchive() { PhpException.FunctionNotSupported(nameof(unchangeArchive)); return(false); }
/// <summary> /// Currently not supported. /// </summary> public bool setPassword(string password) { PhpException.FunctionNotSupported(nameof(setPassword)); return(false); }
/// <summary> /// Currently not supported. /// </summary> public bool setCompressionName(string name, int comp_method, int comp_flags = 0) { PhpException.FunctionNotSupported(nameof(setCompressionName)); return(false); }
void SerializeObject(object obj) { Debug.Assert(obj != null); var tinfo = obj.GetPhpTypeInfo(); var classname = tinfo.Name; if (obj is __PHP_Incomplete_Class) { // classname = ((__PHP_Incomplete_Class)obj).ClassName ?? classname; throw new NotImplementedException("__PHP_Incomplete_Class"); } var classnameBytes = Encoding.GetBytes(classname); PhpArray serializedArray = null; byte[] serializedBytes = null; List <KeyValuePair <string, PhpValue> > serializedProperties = null; var __serialize = tinfo.RuntimeMethods[TypeMethods.MagicMethods.__serialize]; if (__serialize != null) { // TODO: check accessibility // CONSIDER do not reflect non-public methods in tinfo.RuntimeMethods at all! var rvalue = __serialize.Invoke(_ctx, obj); if (rvalue.IsPhpArray(out serializedArray) == false) { // FATAL ERROR // {0}::__serialize must return an array throw PhpException.TypeErrorException(string.Format(LibResources.__serialize_must_return_array, tinfo.Name)); } } else if (obj is global::Serializable serializable) { var res = serializable.serialize(); if (res.IsDefault) { AcceptNull(); return; } serializedBytes = res.ToBytes(Encoding); //if (resdata == null) //{ // // serialize did not return NULL nor a string -> throw an exception // SPL.Exception.ThrowSplException( // _ctx => new SPL.Exception(_ctx, true), // context, // string.Format(CoreResources.serialize_must_return_null_or_string, value.TypeName), 0, null); //} } else { // try to call the __sleep method // otherwise list object properties var __sleep = tinfo.RuntimeMethods[TypeMethods.MagicMethods.__sleep]; // TODO: __sleep accessibility -> ThrowMethodVisibilityError if (__sleep != null) { var sleep_result = __sleep.Invoke(_ctx, obj).ArrayOrNull(); if (sleep_result == null) { PhpException.Throw(PhpError.Notice, Core.Resources.ErrResources.sleep_must_return_array); AcceptNull(); return; } serializedProperties = EnumerateSerializableProperties(obj, tinfo, sleep_result).ToList(); } else { serializedProperties = Serialization.EnumerateSerializableProperties(obj, tinfo).ToList(); } } Write((serializedBytes == null) ? Tokens.Object : Tokens.ObjectSer); Write(Tokens.Colon); // write out class name Write(classnameBytes.Length.ToString()); Write(Tokens.Colon); Write(Tokens.Quote); Write(classnameBytes); Write(Tokens.Quote); Write(Tokens.Colon); if (serializedBytes != null) { Debug.Assert(serializedProperties == null); // write out the result of serialize Write(serializedBytes.Length.ToString()); Write(Tokens.Colon); Write(Tokens.BraceOpen); // write serialized data Write(serializedBytes); } else if (serializedArray != null) { // write out property count Write(serializedArray.Count.ToString()); Write(Tokens.Colon); Write(Tokens.BraceOpen); // enumerate array items and serialize them base.Accept(serializedArray); } else { // write out property count Write(serializedProperties.Count.ToString()); Write(Tokens.Colon); Write(Tokens.BraceOpen); // write out properties AcceptObjectProperties(serializedProperties); } // } Write(Tokens.BraceClose); }
/// <summary> /// Fetches the specified fetch style. /// </summary> /// <param name="fetch_style">Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants.</param> /// <param name="cursor_orientation">This value determines which row will be returned to the caller.</param> /// <param name="cursor_offet">Relative or absolute position move for the cursor.</param> /// <returns>The return value of this function on success depends on the fetch type. In all cases, FALSE is returned on failure.</returns> public virtual PhpValue fetch(PDO.PDO_FETCH fetch_style = PDO_FETCH.Default /*0*/, PDO_FETCH_ORI cursor_orientation = PDO_FETCH_ORI.FETCH_ORI_NEXT /*0*/, int cursor_offet = 0) { ClearError(); if (cursor_orientation != PDO_FETCH_ORI.FETCH_ORI_NEXT) // 0 { throw new NotImplementedException(cursor_orientation.ToString()); } if (Result == null) { // statement not executed PhpException.Throw(PhpError.Notice, "no results to fetch"); return(false); } try { var how = fetch_style != PDO_FETCH.Default ? fetch_style : _default_fetch_type; var flags = how & PDO_FETCH.Flags; switch (how & ~PDO_FETCH.Flags) { case PDO_FETCH.Default: case PDO_FETCH.FETCH_BOTH: return(Result.FetchArray(true, true) ?? PhpValue.False); case PDO_FETCH.FETCH_ASSOC: return(Result.FetchAssocArray() ?? PhpValue.False); case PDO_FETCH.FETCH_NUM: return(Result.FetchArray(true, false) ?? PhpValue.False); case PDO_FETCH.FETCH_OBJ: return(ObjectOrFalse(Result.FetchStdClass())); case PDO_FETCH.FETCH_BOUND: return(FetchBound()); case PDO_FETCH.FETCH_COLUMN: return(fetchColumn(_fetch_column)); case PDO.PDO_FETCH.FETCH_CLASS: return(ObjectOrFalse(FetchClass(_default_fetch_class, _default_fetch_class_args))); case PDO_FETCH.FETCH_NAMED: return(this.ReadNamed()); //case PDO_FETCH.FETCH_LAZY: // return new PDORow( ... ) reads columns lazily //case PDO_FETCH.FETCH_INTO: //case PDO_FETCH.FETCH_FUNC: //case PDO_FETCH.FETCH_KEY_PAIR: default: throw new NotImplementedException($"fetch {how}"); } } catch (System.Exception ex) { HandleError(ex); return(PhpValue.False); } }
IEnumerable <KeyValuePair <string, PhpValue> > EnumerateSerializableProperties(object obj, PhpTypeInfo tinfo, PhpArray properties) { Debug.Assert(obj != null); Debug.Assert(tinfo != null); Debug.Assert(properties != null); PhpArray runtime_fields = null; var enumerator = properties.GetFastEnumerator(); while (enumerator.MoveNext()) { FieldAttributes visibility; string name = enumerator.CurrentValue.ToStringOrThrow(_ctx); string declaring_type_name; string property_name = Serialization.ParseSerializedPropertyName(name, out declaring_type_name, out visibility); PhpTypeInfo declarer; // for visibility check if (declaring_type_name == null) { declarer = tinfo; } else { declarer = _ctx.GetDeclaredType(declaring_type_name); if (declarer == null) { // property name refers to an unknown class -> value will be null yield return(new KeyValuePair <string, PhpValue>(name, PhpValue.Null)); continue; } } // obtain the property desc and decorate the prop name according to its visibility and declaring class var property = tinfo.GetDeclaredProperty(property_name); if (property != null && !property.IsStatic && property.IsVisible(declarer.Type)) { // if certain conditions are met, serialize the property as null // (this is to precisely mimic the PHP behavior) if ((visibility == (property.Attributes & FieldAttributes.FieldAccessMask) && visibility != FieldAttributes.Public) || (visibility == FieldAttributes.Private && declarer != property.ContainingType)) { yield return(new KeyValuePair <string, PhpValue>(name, PhpValue.Null)); continue; } name = Serialization.FormatSerializedPropertyName(property); } else { property = null; // field is not visible, try runtime fields } // obtain the property value PhpValue val; if (property != null) { val = property.GetValue(_ctx, obj); } else { if (runtime_fields == null) { runtime_fields = tinfo.GetRuntimeFields(obj) ?? PhpArray.Empty; } if (!runtime_fields.TryGetValue(name, out val)) { // PHP 5.1+ PhpException.Throw(PhpError.Notice, string.Format(Core.Resources.ErrResources.sleep_returned_bad_field, name)); } } yield return(new KeyValuePair <string, PhpValue>(name, val)); } }
/// <summary> /// Helper method that stores an openssl error message within the current context. /// </summary> private static void HandleError(Context ctx, string message) { ctx.GetStatic <ErrorList>().Push(message); PhpException.Throw(PhpError.E_WARNING, message); }
public static PhpString gzdecode(byte[] data, int length = 0) { PhpException.FunctionNotSupported("gzdecode"); return(null); }
private static SymmetricAlgorithm PrepareCipher(byte[] decodedKey, Cipher cipher, byte[] iv, Options options) { // Pad key out to KeyLength in bytes if its too short or trancuate if it is too long int KeyLengthInBytes = cipher.KeyLength / 8; if (decodedKey.Length < KeyLengthInBytes || decodedKey.Length > KeyLengthInBytes) { var resizedKey = new byte[KeyLengthInBytes]; Buffer.BlockCopy(decodedKey, 0, resizedKey, 0, Math.Min(decodedKey.Length, resizedKey.Length)); decodedKey = resizedKey; } var iVector = new byte[cipher.IVLength]; if (!ArrayUtils.IsNullOrEmpty(iv)) { var ivLength = iv.Length; if (ivLength != cipher.IVLength) { if (ivLength < cipher.IVLength) // Pad zeros { if ((options & Options.OPENSSL_DONT_ZERO_PAD_KEY) != 0 /* && !EVP_CIPHER_CTX_set_key_length(ivLength)*/) { // Warning: Key length cannot be set for the cipher method throw new CryptographicException(Resources.LibResources.openssl_cannot_set_iv_length); } PhpException.Throw(PhpError.E_WARNING, Resources.LibResources.openssl_short_iv, iv.Length.ToString(), cipher.IVLength.ToString()); } else if (ivLength > cipher.IVLength) // Trancuate { PhpException.Throw(PhpError.E_WARNING, Resources.LibResources.openssl_long_iv, iv.Length.ToString(), cipher.IVLength.ToString()); ivLength = cipher.IVLength; } } Buffer.BlockCopy(iv, 0, iVector, 0, ivLength); } SymmetricAlgorithm alg = null; switch (cipher.Type) { case CipherType.AES: if (cipher.Mode == SupportedCipherMode.CTR) { alg = new AesCounterMode(); } else { alg = new RijndaelManaged { Padding = PaddingMode.PKCS7, KeySize = cipher.KeyLength } }; break; case CipherType.DES: alg = DES.Create(); break; case CipherType.TripleDES: alg = TripleDES.Create(); break; } if (TryGetDotNetCipherMode(cipher.Mode, out var cipherMode)) { alg.Mode = cipherMode; } alg.Key = decodedKey; alg.IV = iVector; if ((options & Options.OPENSSL_ZERO_PADDING) == Options.OPENSSL_ZERO_PADDING) { alg.Padding = PaddingMode.None; } return(alg); }
public static string zlib_get_coding_type() { PhpException.FunctionNotSupported("zlib_get_coding_type"); return(null); // gzip, deflate, or FALSE. }
public static object mb_substitute_character() { PhpException.FunctionNotSupported("mb_substitute_character"); return(false); }
public void setIdAttributeNode(DOMAttr attribute, bool isId) { PhpException.Throw(PhpError.Warning, Resources.NotYetImplemented); }
public static object mb_substitute_character(object substrchar) { PhpException.FunctionNotSupported("mb_substitute_character"); return("none"); }
public static int filter_id(string filtername) { PhpException.FunctionNotSupported(nameof(filter_id)); return(-1); }
/// <summary> /// Set the language used by mail functions. /// </summary> /// <param name="language"></param> /// <returns>True if language was set, otherwise false.</returns> public static bool mb_language(string language) { PhpException.FunctionNotSupported("mb_language"); return(false); }
public static PhpValue filter_var_array(PhpArray data, PhpValue definition = default, bool add_empty = true) { PhpException.FunctionNotSupported(nameof(filter_var_array)); return(PhpValue.False); }
/// <summary> /// Not implemented (TODO: will need a Relax NG validator for this). /// </summary> public virtual bool relaxNGValidateSource(string schema) { PhpException.Throw(PhpError.Warning, Resources.RelaxNGUnsupported); return(true); }
public static PhpArray exif_read_data(Context ctx, string filename, string sections = null, bool arrays = false, bool thumbnail = false) { if (string.IsNullOrEmpty(filename)) { PhpException.Throw(PhpError.Warning, Resources.filename_cannot_be_empty); return(null); } if (!string.IsNullOrEmpty(sections)) { PhpException.ArgumentValueNotSupported("sections", sections); } if (arrays) { PhpException.ArgumentValueNotSupported("arrays", arrays); } if (thumbnail) { PhpException.ArgumentValueNotSupported("thumbnail", thumbnail); } PhpArray array = new PhpArray(); var bytes = Utils.ReadPhpBytes(ctx, filename); if (bytes == null) { return(null); } array.Add("FileName", Path.GetFileName(filename)); //array.Add("FileDateTime", (int)File.GetCreationTime(filename).ToOADate()); array.Add("FileSize", (int)bytes.Length); Image <Rgba32> image; using (var ms = new MemoryStream(bytes)) { try { image = Image.Load(ms); } catch { return(null); } var encoding = System.Text.Encoding.ASCII; var unicode = System.Text.Encoding.Unicode; //foreach (var item in image.MetaData.Properties) //{ //} foreach (var item in image.MetaData.ExifProfile.Values) { array.Add(item.Tag.ToString(), ExifValueToPhpValue(item.Value)); } image.Dispose(); } return(array); }
/// <summary> /// Currently not supported. /// </summary> public bool setExternalAttributesName(string name, int opsys, int attr, int flags = 0) { PhpException.FunctionNotSupported(nameof(setExternalAttributesName)); return(false); }