Пример #1
0
 /// <summary>
 /// Creates a new instance of the <see cref="PhpBytes"/> class that shares internal byte array
 /// with another <see cref="PhpBytes"/> instance.
 /// </summary>
 /// <param name="data">The original bytes array.</param>
 public PhpBytes(PhpBytes /*!*/ data)
 {
     if (data == null)
     {
         throw new ArgumentNullException("data");
     }
     this._data = data._data.Share();
 }
Пример #2
0
        static void Concat()
        {
            PhpBytes a = new PhpBytes(new byte[] { 61, 62, 63 });
            string b = "-hello-";
            PhpBytes c = new PhpBytes(new byte[] { 61, 61, 61 });
            string d = "-bye-";

            object result = Operators.Concat(a, b, c, d);
            Assert.IsTrue(Operators.StrictEquality(result, "=>?-hello-===-bye-"));
        }
Пример #3
0
        public bool Equals(PhpBytes /*!*/ other)
        {
            Debug.Assert(other != null);

            return
                (this._data == other._data ||                                       // compare internal data structures if they are shared first
                 (
                     this._data.Length == other._data.Length &&                     // arrays have to be the same length
                     ArrayUtils.Compare(this.ReadonlyData, other.ReadonlyData) == 0 // compare byte by byte
                 ));
        }
Пример #4
0
        public static PhpBytes Concat(PhpBytes /*!*/ x, PhpBytes /*!*/ y)
        {
            if (x == null)
            {
                throw new ArgumentNullException("x");
            }
            if (y == null)
            {
                throw new ArgumentNullException("y");
            }

            int lx = x.Length;
            int ly = y.Length;

            byte[] result = new byte[lx + ly];

            Buffer.BlockCopy(x.ReadonlyData, 0, result, 0, lx);
            Buffer.BlockCopy(y.ReadonlyData, 0, result, lx, ly);

            return(new PhpBytes(result));
        }
Пример #5
0
        public static PhpBytes Append(object x, PhpBytes y)
        {
            Debug.Assert(!(x is PhpReference));

            return(PhpBytes.Concat(Convert.ObjectToPhpBytes(x), y));
        }
Пример #6
0
		/// <summary>
		/// Deserializes a graph of connected object from a byte array using a given formatter.
		/// </summary>
		/// <param name="bytes">The byte array to deserialize the graph from.</param>
        /// <param name="caller">DTypeDesc of the caller's class context if it is known or UnknownTypeDesc if it should be determined lazily.</param>
        /// <returns>
		/// The deserialized object graph or an instance of <see cref="PhpReference"/> containing <B>false</B> on error.
		/// </returns>
		/// <exception cref="PhpException">Deserialization failed (Notice).</exception>
        public PhpReference Deserialize(PhpBytes bytes, DTypeDesc caller)
		{
            MemoryStream stream = new MemoryStream(bytes.ReadonlyData);
			object result = null;

			try
			{
				try
				{
					// deserialize the data
                    result = GetFormatter(caller).Deserialize(stream);
				}
				catch (System.Reflection.TargetInvocationException e)
				{
					throw e.InnerException;
				}
			}
			catch (SerializationException e)
			{
				PhpException.Throw(PhpError.Notice, LibResources.GetString("deserialization_failed",
				  e.Message, stream.Position, stream.Length));
				return new PhpReference(false);
			}

			return PhpVariable.MakeReference(result);
		}
Пример #7
0
		public static string EncodeBase64(PhpBytes data_to_encode)
		{
			if (data_to_encode == null) return null;
            return System.Convert.ToBase64String(data_to_encode.ReadonlyData);
		}
Пример #8
0
        /// <summary>
        /// Flushes data on current level of buffering to the sinks or to the previous level.
        /// The current level clean up MUST follow this method's call.
        /// </summary>
        internal void InternalFlush()
        {
            Debug.Assert(level != null);

            if (level.filter != null)
            {
                ChunkPosition chunk_position = ChunkPosition.First | ChunkPosition.Middle | ChunkPosition.Last;

                // writes data to the current level of buffering or to sinks depending on the level count:
                if (level.index > 0)
                {
                    // gets data from user's callback:
                    object data = level.filter.Invoke(GetContent(), chunk_position);

                    // store level to allow its restore:
                    LevelElement old_level = level;

                    // temporarily decreases the level of buffering toredirect writes to the lower level:
                    level = (LevelElement)levels[level.index - 1];

                    // checks whether the filtered data are binary at first; if not so, converts them to a string:
                    PhpBytes bin = data as PhpBytes;
                    if (bin != null)
                    {
                        stream.Write(bin.ReadonlyData, 0, bin.Length);
                    }
                    else
                    {
                        this.Write(PHP.Core.Convert.ObjectToString(data));
                    }

                    // restore the level of buffering:
                    level = old_level;
                }
                else
                {
                    // gets data from user's callback:
                    object data = level.filter.Invoke(GetContent(), chunk_position);

                    // checks whether the filtered data are binary at first; if not so, converts them to a string:
                    PhpBytes bin = data as PhpBytes;
                    if (bin != null)
                    {
                        if (bin.Length > 0)
                        {
                            byteSink.Write(bin.ReadonlyData, 0, bin.Length);
                        }
                    }
                    else
                    {
                        charSink.Write(PHP.Core.Convert.ObjectToString(data));
                    }
                }
            }
            else
            {
                if (level.index > 0)
                {
                    // joins levels (data are not copied => the current level MUST be cleaned up after the return from this method):
                    if (level.size > 0)
                    {
                        LevelElement lower_level = (LevelElement)levels[level.index - 1];

                        lower_level.buffers.AddRange(level.buffers);
                        lower_level.size             += level.size;
                        lower_level.freeSpace         = level.freeSpace;                      // free space in the last buffer of the level
                        lower_level.containsByteData |= level.containsByteData;
                        lower_level.containsCharData |= level.containsCharData;
                    }
                }
                else
                {
                    // writes top-level data to sinks:
                    for (int i = 0; i < level.buffers.Count; i++)
                    {
                        BufferElement element = (BufferElement)level.buffers[i];

                        byte[] bytes = element.data as byte[];
                        if (bytes != null)
                        {
                            byteSink.Write(bytes, 0, element.size);
                        }
                        else
                        {
                            charSink.Write((char[])element.data, 0, element.size);
                        }
                    }
                }
            }
        }
Пример #9
0
        /// <include file='Doc/Streams.xml' path='docs/method[@name="RawWrite"]/*'/>
        protected override int RawWrite(byte[] buffer, int offset, int count)
        {
            PhpBytes bytes;
            if (count == 0)
            {
                bytes = PhpBytes.Empty;
            }
            if (offset == 0 && count == buffer.Length)
            {
                bytes = new PhpBytes(buffer);
            }
            else
            {
                byte[] data = new byte[count];
                Array.Copy(buffer, offset, data, 0, count);
                bytes = new PhpBytes(data);
            }

            object result = UserWrapper.InvokeWrapperMethod(USERSTREAM_WRITE, bytes);

            int byteswrote = Convert.ObjectToInteger(result);
            if (byteswrote > count)
            {
                //php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_WRITE " wrote %ld bytes more data than requested (%ld written, %ld max)",
                //us->wrapper->classname, (long)(didwrite - count), (long)didwrite, (long)count);
                byteswrote = count;
            }

            return byteswrote;
        }
Пример #10
0
		/// <summary>
		/// Joins the read buffers to get at least <paramref name="length"/> bytes
		/// in a <see cref="PhpBytes"/>. 
		/// </summary>
		/// <param name="length">The desired maximum result length.</param>
		/// <returns>A <see cref="PhpBytes"/> dequeued from the buffer or <c>null</c> if the buffer is empty.</returns>
		protected PhpBytes ReadBinaryBuffer(int length)
		{
			if (length == 0) return PhpBytes.Empty;

			PhpBytes peek = (PhpBytes)readBuffers.Peek();
			Debug.Assert(peek.Length >= readPosition);

			if (peek.Length - readPosition >= length)
			{
				// Great! We can just take a sub-data.
				byte[] data = new byte[length];
                Array.Copy(peek.ReadonlyData, readPosition, data, 0, length);
				PhpBytes res = new PhpBytes(data);
				readPosition += length;

				if (peek.Length == readPosition)
				{
					// We just consumed the entire string. Dequeue it.
					DropReadBuffer();
				}
				return res;
			}
			else
			{
				// Start building the data from the remainder in the buffer.
				int buffered = this.ReadBufferLength;
				if (buffered < length) length = buffered;
				byte[] data = new byte[length];
				int copied = peek.Length - readPosition;
                Array.Copy(peek.ReadonlyData, readPosition, data, 0, copied); readPosition += copied;
				length -= copied;

				// We just consumed the entire data. Dequeue it.
				DropReadBuffer();

				while (length > 0)
				{
					peek = readBuffers.Peek() as PhpBytes;
					if (peek.Length > length)
					{
						// This data is long enough. It is the last one.
                        Array.Copy(peek.ReadonlyData, 0, data, copied, length);
						readPosition = length;
						length = 0;
						break;
					}
					else
					{
						// Append just another whole buffer to the array.
                        Array.Copy(peek.ReadonlyData, 0, data, copied, peek.Length);
						length -= peek.Length;
						copied += peek.Length;
						DropReadBuffer();

						// When this is the last buffer (it's probably an EOF), return.
						if (readBuffers.Count == 0)
							break;
					}
				} // while

				Debug.Assert(copied > 0);
				if (copied < length)
				{
					byte[] sub = new byte[copied];
					Array.Copy(data, 0, sub, 0, copied);
					return new PhpBytes(sub);
				}
				return new PhpBytes(data);
			} // else
		}
Пример #11
0
        /// <summary>
        /// Concatenate list of PhpBytes. Given array can contain nulls.
        /// </summary>
        /// <param name="args">List of PhpArray objects. Can contain null.</param>
        /// <param name="startIndex">First element in args to start concatenation from.</param>
        /// <param name="count">Amount of element to concatenate from the startIndex index.</param>
        /// <returns>PhpBytes with concatenated args.</returns>
        public static PhpBytes Concat(PhpBytes[]/*!*/args, int startIndex, int count)
        {
            int num = startIndex + count;

            Debug.Assert(args != null);
            Debug.Assert(startIndex >= 0);
            Debug.Assert(count >= 0);
            Debug.Assert(num <= args.Length);

            // computes the length of the result:
            int length = 0;
            for (int i = startIndex; i < num; ++i)
                if (args[i] != null)
                    length += args[i].Length;

            if (length == 0)
                return PhpBytes.Empty;

            var result = new byte[length];

            // copies data to the result array:
            int pos = 0;
            for (int i = startIndex; i < num; ++i)
                if (args[i] != null)
                {
                    byte[] bytes = args[i].ReadonlyData;
                    Buffer.BlockCopy(bytes, 0, result, pos, bytes.Length);
                    pos += bytes.Length;
                }

            return new PhpBytes(result);
        }
Пример #12
0
        public static PhpBytes Append(object x, PhpBytes y)
        {
            Debug.Assert(!(x is PhpReference));

            return PhpBytes.Concat(Convert.ObjectToPhpBytes(x), y);
        }
Пример #13
0
		public static PhpBytes Concat(PhpBytes/*!*/x, PhpBytes/*!*/y)
		{
			if (x == null) throw new ArgumentNullException("x");
			if (y == null) throw new ArgumentNullException("y");

			int lx = x.Length;
			int ly = y.Length;

            byte[] result = new byte[lx + ly];
			
			Buffer.BlockCopy(x.ReadonlyData, 0, result, 0, lx);
            Buffer.BlockCopy(y.ReadonlyData, 0, result, lx, ly);

			return new PhpBytes(result);
		}
Пример #14
0
        public static PhpBytes Concat(PhpBytes x, object y)
        {
            Debug.Assert(!(y is PhpReference));

            return PhpBytes.Concat(x, Convert.ObjectToPhpBytes(y));
        }
Пример #15
0
 /// <summary>
 /// Creates a new instance of the <see cref="PhpBytes"/> class that shares internal byte array
 /// with another <see cref="PhpBytes"/> instance.
 /// </summary>
 /// <param name="data">The original bytes array.</param>
 public PhpBytes(PhpBytes/*!*/data)
 {
     if (data == null) throw new ArgumentNullException("data");
     this._data = data._data.Share();
 }
Пример #16
0
		/// <summary>
		/// Stores serialized variables.
		/// </summary>
		/// <param name="savePath">A path where session files can be stored in.</param>
		/// <param name="sid">A session ID.</param>
		/// <param name="data">Variables in serialized form.</param>
		protected abstract void SaveSerializedVariables(string savePath, string sid, PhpBytes data);
Пример #17
0
		/// <summary>
		/// Calls "write" and "close" user handlers if not empty.
		/// </summary>
		protected override void SaveSerializedVariables(string savePath, string sid, PhpBytes data)
		{
			Handlers handlers = Handlers.Current;

			if (handlers.Write != null && !Core.Convert.ObjectToBoolean(handlers.Write.Invoke(sid, data)))
			{
				ReportError("write", savePath, sid);
				return;
			}

			if (handlers.Close != null && !Core.Convert.ObjectToBoolean(handlers.Close.Invoke()))
			{
				ReportError("close", savePath, sid);
				return;
			}
		}
Пример #18
0
		/// <summary>
		/// Stores serialied variables to the session file.
		/// </summary>
		protected override void SaveSerializedVariables(string savePath, string sid, PhpBytes data)
		{
			using (PhpStream file = OpenSessionFile(savePath, sid, true))
			{
				if (file != null)
				{
					file.WriteBytes(data);
					file.Close();
				}
			}
		}
Пример #19
0
        public bool Equals(PhpBytes/*!*/other)
        {
            Debug.Assert(other != null);

            return
                this._data == other._data ||    // compare internal data structures if they are shared first
                (
                    this._data.Length == other._data.Length &&  // arrays have to be the same length
                    ArrayUtils.Compare(this.ReadonlyData, other.ReadonlyData) == 0 // compare byte by byte
                );
        }
Пример #20
0
		/// <summary>
		/// Apppends the binary data to the output buffer passing through the output filter-chain. 
		/// When the buffer is full or buffering is disabled, pass the data to the low-level stream.
		/// </summary>
		/// <param name="data">The <see cref="PhpBytes"/> to store.</param>
		/// <returns>Number of bytes successfully written or <c>-1</c> on an error.</returns>
		public int WriteBytes(PhpBytes data)
		{
			Debug.Assert(this.IsBinary);
			return WriteData(data, false);
		}
Пример #21
0
			public DebuggerProxy(PhpBytes phpBytes)
			{
				_phpBytes = phpBytes;
			}
Пример #22
0
		/// <summary>
		/// Fills the <see cref="readBuffers"/> with more data from the underlying stream
		/// passed through all the stream filters. 
		/// </summary>
		/// <param name="chunkSize">Maximum number of bytes to be read from the stream.</param>
		/// <returns>A <see cref="string"/> or <see cref="PhpBytes"/> containing the 
		/// data as returned from the last stream filter or <b>null</b> in case of an error or <c>EOF</c>.</returns>
		protected object ReadFiltered(int chunkSize)
		{
			byte[] chunk = new byte[chunkSize];
			object filtered = null;

			while (filtered == null)
			{
				// Read data until there is an output or error or EOF.
				if (RawEof) return null;
				int read = RawRead(chunk, 0, chunkSize);
				if (read <= 0)
				{
					// Error or EOF.
					return null;
				}

				if (read < chunkSize)
				{
					byte[] sub = new byte[read];
					Array.Copy(chunk, 0, sub, 0, read);
					chunk = sub;
				}
				filtered = new PhpBytes(chunk);

				bool closing = RawEof;

				if (textReadFilter != null)
				{
					// First use the text-input filter if any.
					filtered = textReadFilter.Filter(filtered, closing);
				}

				if (readFilters != null)
				{
					// After that apply the user-filters.
					foreach (IFilter f in readFilters)
					{
						if (filtered == null)
						{
							// This is the last chance to output something. Give chance to all filters.
							if (closing) filtered = PhpBytes.Empty;
							else break; // Continue with next RawRead()
						}
						filtered = f.Filter(filtered, closing);
					} // foreach
				} // if
			} // while 

			return filtered;
		}
Пример #23
0
 public static PhpArray getimagesizefromstring(PhpBytes bytes)
 {
     return getimagesizefromstring(bytes, null);
 }
Пример #24
0
        public static PhpReference Unserialize(PHP.Core.Reflection.DTypeDesc caller, PhpBytes bytes)
		{
            LibraryConfiguration config = LibraryConfiguration.GetLocal(ScriptContext.CurrentContext);

            return config.Serialization.DefaultSerializer.Deserialize(bytes, caller);
		}
Пример #25
0
        public static PhpArray getimagesizefromstring(PhpBytes bytes, PhpReference imageinfo)
        {
            if (bytes == null)
                return null;

            return getimagesize(new MemoryStream(bytes.ReadonlyData), imageinfo);
        }
Пример #26
0
        public static PhpReference Unserialize(PHP.Core.Reflection.DTypeDesc caller, PhpBytes bytes)
		{
            if (bytes == null || bytes.Length == 0)
                return new PhpReference(false);

            LibraryConfiguration config = LibraryConfiguration.GetLocal(ScriptContext.CurrentContext);

            return config.Serialization.DefaultSerializer.Deserialize(bytes, caller);
		}
Пример #27
0
        public static PhpArray iptcparse(PhpBytes iptcblock)
        {
            // validate arguments:
            if (iptcblock == null)
                return null;

            // parse IPTC block:
            uint inx = 0, len;
            var buffer = iptcblock.ReadonlyData;

            // find 1st tag:
            for (; inx < buffer.Length; ++inx)
            {
                if ((buffer[inx] == 0x1c) && ((buffer[inx + 1] == 0x01) || (buffer[inx + 1] == 0x02)))
                    break;
            }

            PhpArray result = null;

            // search for IPTC items:
            while (inx < buffer.Length)
            {
                if (buffer[inx++] != 0x1c)
                    break;   // we ran against some data which does not conform to IPTC - stop parsing!

                if ((inx + 4) >= buffer.Length)
                    break;

                // data, recnum:
                byte dataset = buffer[inx++];
                byte recnum = buffer[inx++];

                // len:
                if ((buffer[inx] & (byte)0x80) != 0)
                { // long tag
                    len = (((uint)buffer[inx + 2]) << 24) | (((uint)buffer[inx + 3]) << 16) |
                          (((uint)buffer[inx + 4]) << 8) | (((uint)buffer[inx + 5]));
                    inx += 6;
                }
                else
                { // short tag
                    len = (((uint)buffer[inx + 0]) << 8) | (((uint)buffer[inx + 1]));
                    inx += 2;
                }

                if ((len > buffer.Length) || (inx + len) > buffer.Length)
                    break;

                // snprintf(key, sizeof(key), "%d#%03d", (unsigned int) dataset, (unsigned int) recnum);
                string key = string.Format("{0}#{1}", dataset, recnum.ToString("D3"));

                // create result array lazily:
                if (result == null)
                    result = new PhpArray();

                // parse out the data (buffer+inx)[len]:
                var data = new PhpBytes(new byte[len]);
                Buffer.BlockCopy(buffer, (int)inx, data.Data, 0, (int)len);

                // add data into result[key][]:
                PhpArray values = result[key] as PhpArray;
                if (values != null)
                    values.Add(data);
                else
                    result[key] = new PhpArray(2) { data };

                //
                inx += len;
            }

            //
            return result;  // null if no items were found
        }
Пример #28
0
        public static PhpResource imagecreatefromstring(PhpBytes image)
        {
            if (image == null)
            {
                PhpException.Throw(PhpError.Warning, Utils.Resources.GetString("empty_string_or_invalid_image"));
                return null;
            }

            PhpGdImageResource res;

            try
            {
                MemoryStream stream = new MemoryStream(image.ReadonlyData);
                Image img = Image.FromStream(stream, true, false);

                res = new PhpGdImageResource(img);
            }
            catch
            {
                PhpException.Throw(PhpError.Warning, Utils.Resources.GetString("empty_string_or_invalid_image"));
                return null;
            }

            return res;
        }
Пример #29
0
 public DebuggerProxy(PhpBytes phpBytes)
 {
     _phpBytes = phpBytes;
 }
Пример #30
0
        public static PhpBytes exif_thumbnail(string filename, PhpReference width, PhpReference height, PhpReference imagetype)
        {
            if (string.IsNullOrEmpty(filename))
            {
                PhpException.Throw(PhpError.Warning, Utils.Resources.GetString("filename_cannot_be_empty"));
                return null;
            }

            if (imagetype != null)
            {
                PhpException.ArgumentValueNotSupported("imagetype", "!=null");
            }

            Bitmap thumbnail = null;
            PhpBytes bytes, result;

            bytes = Utils.ReadPhpBytes(filename);

            if (bytes == null)
                return null;

            // get thumbnail from <filename>'s content:
            using (MemoryStream ms = new MemoryStream(bytes.ReadonlyData))
            {
                try
                {
                    using (Bitmap image = (Bitmap)Image.FromStream(ms))
                    {
                        thumbnail = (Bitmap)image.GetThumbnailImage(0, 0, () => true, IntPtr.Zero);
                    }
                }
                catch
                {
                    return null;
                }
            }

            if (thumbnail == null)
                return null;

            //
            if (width != null)
                width.Value = thumbnail.Width;
            
            if (height != null)
                height.Value = thumbnail.Height;
            
            using (MemoryStream ms2 = new MemoryStream())
            {
                thumbnail.Save(ms2, ImageFormat.Png);
                result = new PhpBytes(ms2.GetBuffer());
            }

            thumbnail.Dispose();

            return result;
        }
Пример #31
0
		public static PhpArray Unpack(string format, PhpBytes data)
		{
			if (format == null) return null;
			byte[] buffer = (data != null) ? data.ReadonlyData : ArrayUtils.EmptyBytes;

			Encoding encoding = Configuration.Application.Globalization.PageEncoding;
			byte[] reversed = new byte[4]; // used for reversing the order of bytes in buffer

			int i = 0;
			int pos = 0;
			PhpArray result = new PhpArray();

			while (i < format.Length)
			{
				string name;
				int repeater;
				char specifier;

				// parses specifier, repeater, and name from the format string:
				ParseFormatToken(format, ref i, out specifier, out repeater, out name);

				int remains = buffer.Length - pos;          // the number of bytes remaining in the buffer
				int size;                                   // a size of data to be extracted corresponding to the specifier  

				// repeater of '@' specifier has a special meaning:
				if (specifier == '@')
				{
					if (repeater > buffer.Length || repeater == InfiniteRepeater)
						PhpException.Throw(PhpError.Warning, LibResources.GetString("outside_string", specifier));
					else
						pos = repeater;

					continue;
				}

				// number of operations:
				int op_count;

				// gets the size of the data to read and adjust repeater:
				if (!GetSizeToUnpack(specifier, remains, repeater, out op_count, out size))
				{
					PhpException.Throw(PhpError.Warning, LibResources.GetString("unknown_format_code", specifier));
					return null;
				}

				// repeats operation determined by specifier "op_count" times;
				// if op_count is infinite then stops when the number of remaining characters is zero:
				for (int j = 0; j < op_count || op_count == InfiniteRepeater; j++)
				{
					if (size > remains)
					{
						// infinite means "while data are available":
						if (op_count == InfiniteRepeater) break;

						PhpException.Throw(PhpError.Warning, LibResources.GetString("not_enought_input", specifier, size, remains));
						return null;
					}

					object item;
					switch (specifier)
					{
						case 'X': // decreases position, no value stored:
							if (pos == 0)
								PhpException.Throw(PhpError.Warning, LibResources.GetString("outside_string", specifier));
							else
								pos--;
							continue;

						case 'x': // advances position, no value stored
							pos++;
							continue;

						case 'a': // NUL-padded string
						case 'A': // SPACE-padded string 
							{
								byte pad = (byte)(specifier == 'a' ? 0x00 : 0x20);

								int last = pos + size - 1;
								while (last >= pos && buffer[last] == pad)
									last--;

								item = encoding.GetString(buffer, pos, last - pos + 1);
								break;
							}

						case 'h': // Hex string, low/high nibble first - converts to a string, takes n hex digits from string:
						case 'H':
							{
								int p = pos;
								int nibble_shift = (specifier == 'h') ? 0 : 4;

								StringBuilder sb = new StringBuilder(size);
								for (int k = 0; k < size; k++)
								{
									const string hex_digits = "0123456789ABCDEF";

									sb.Append(hex_digits[(buffer[p] >> nibble_shift) & 0x0f]);

									// beware of odd repeaters!
									if (repeater == InfiniteRepeater || repeater > sb.Length)
									{
										sb.Append(hex_digits[(buffer[p] >> (4 - nibble_shift)) & 0x0f]);
									}
									p++;
								}

								item = sb.ToString();
								break;
							}

						case 'c': // signed char
							item = (int)unchecked((sbyte)buffer[pos]);
							break;

						case 'C': // unsigned char 
							item = (int)buffer[pos];
							break;

						case 's': // signed short (always 16 bit, machine byte order) 
							item = (int)BitConverter.ToInt16(buffer, pos);
							break;

						case 'S': // unsigned short (always 16 bit, machine byte order) 
							item = (int)BitConverter.ToUInt16(buffer, pos);
							break;

						case 'n': // unsigned short (always 16 bit, big endian byte order) 
							if (BitConverter.IsLittleEndian)
								item = (int)BitConverter.ToUInt16(LoadReverseBuffer(reversed, buffer, pos, 2), 0);
							else
								item = (int)BitConverter.ToUInt16(buffer, pos);
							break;

						case 'v': // unsigned short (always 16 bit, little endian byte order) 
							if (!BitConverter.IsLittleEndian)
								item = (int)BitConverter.ToUInt16(LoadReverseBuffer(reversed, buffer, pos, 2), 0);
							else
								item = (int)BitConverter.ToUInt16(buffer, pos);
							break;

						case 'i': // signed integer (machine dependent size and byte order - always 32 bit) 
						case 'I': // unsigned integer (machine dependent size and byte order - always 32 bit) 
						case 'l': // signed long (always 32 bit, machine byte order) 
						case 'L': // unsigned long (always 32 bit, machine byte order) 
							item = BitConverter.ToInt32(buffer, pos);
							break;
						
						case 'N': // unsigned long (always 32 bit, big endian byte order) 
							item = unchecked(((int)buffer[pos] << 24) + (buffer[pos + 1] << 16) + (buffer[pos + 2] << 8) + buffer[pos + 3]);
							break;
							
						case 'V': // unsigned long (always 32 bit, little endian byte order) 
							item = unchecked(((int)buffer[pos + 3] << 24) + (buffer[pos + 2] << 16) + (buffer[pos + 1] << 8) + buffer[pos + 0]);
							break;

						case 'f': // float (machine dependent size and representation - size is always 4B) 
							item = (double)BitConverter.ToSingle(buffer, pos);
							break;

						case 'd': // double (machine dependent size and representation - size is always 8B) 
							item = BitConverter.ToDouble(buffer, pos);
							break;

						default:
							Debug.Fail("Invalid specifier.");
							return null;
					}

					AddValue(result, name, item, op_count, j);

					pos += size;
					remains -= size;
				}
			}

			return result;
		}
Пример #32
0
        public static PhpBytes Concat(PhpBytes x, object y)
        {
            Debug.Assert(!(y is PhpReference));

            return(PhpBytes.Concat(x, Convert.ObjectToPhpBytes(y)));
        }
Пример #33
0
		/// <summary>
        /// Split a <see cref="String"/> or <see cref="PhpBytes"/> to "upto" bytes at left and the rest or <c>null</c> at right.
		/// </summary>
		private static void SplitData(object data, int upto, out object left, out object right)
		{
			Debug.Assert(data != null);
			Debug.Assert(upto >= 0);
			//if (this.IsText)
            if (data.GetType() == typeof(string))
			{
                string s = (string)data;
				Debug.Assert(s != null);
				if (upto < s.Length - 1)
				{
					left = s.Substring(0, upto + 1);
					right = s.Substring(upto + 2);
				}
				else
				{
					left = s;
					right = null;
				}
			}
			else
			{
                Debug.Assert(data is PhpBytes);
				PhpBytes bin = (PhpBytes)data;
				if (upto < bin.Length - 1)
				{
					byte[] l = new byte[upto + 1], r = new byte[bin.Length - upto - 1];
                    Array.Copy(bin.ReadonlyData, 0, l, 0, upto + 1);
                    Array.Copy(bin.ReadonlyData, upto + 1, r, 0, bin.Length - upto - 1);
					left = new PhpBytes(l);
					right = new PhpBytes(r);
				}
				else
				{
					left = bin;
					right = null;
				}
			}
		}
Пример #34
0
 public static object iptcembed(PhpBytes iptcdata, string jpeg_file_name, int spool)
 {
     return null;
 }
Пример #35
0
		public static bool DecodeVariables(PhpBytes data)
		{
			RequestContext request_context;
			if (!Web.EnsureRequestContext(out request_context)) return false;

			if (!request_context.SessionExists)
			{
				PhpException.Throw(PhpError.Notice, LibResources.GetString("session_not_exists"));
				return false;
			}

			ScriptContext context = request_context.ScriptContext;
			LibraryConfiguration config = LibraryConfiguration.GetLocal(context);
			GlobalConfiguration global = Configuration.Global;

            PhpReference php_ref = config.Session.Serializer.Deserialize(data, UnknownTypeDesc.Singleton);
			if (php_ref == null) return false;

			context.AutoGlobals.Session = php_ref;

			// copies session variables to $GLOBALS array if necessary:
			if (global.GlobalVariables.RegisterGlobals)
				context.RegisterSessionGlobals();

			return true;
		}
Пример #36
0
        /// <summary>
        /// Implements oprators [],{} on a byte array.
        /// </summary>
        /// <param name="bytes">The variable which item to set.</param>
        /// <param name="index">The index of an item.</param>
        /// <param name="value">The new value of an item.</param>
        /// <exception cref="PhpException"><paramref name="index"/> converted to integer by <see cref="Convert.ObjectToInteger"/> is negative. (Warning)</exception>
        /// <include file='Doc/Operators.xml' path='docs/operator[@name="SetBytesItem"]/*'/>
        internal static void SetBytesItem(PhpBytes/*!*/ bytes, int index, object value)
        {
            Debug.Assert(bytes != null && bytes.Length > 0);

            // the new byte will be the first byte of the value converted to byte[] or zero byte
            // if the length of the converted value is zero; dereferencing is also done:
            byte[] bval = Convert.ObjectToPhpBytes(value).ReadonlyData;
            byte b = (bval.Length == 0) ? (byte)0 : bval[0];

            // if index is greater than the data length the array is padded by space bytes (0x20):
            if (index >= bytes.Length)
            {
                // TODO (J): optimize by using elastic array (some future implementation PhpString)
                byte[] new_bytes = new byte[index + 1];

                Buffer.BlockCopy(bytes.ReadonlyData, 0, new_bytes, 0, bytes.Length);
                ArrayUtils.Fill(new_bytes, 0x20, bytes.Length, index - bytes.Length);
                new_bytes[index] = b;

                bytes.Data = new_bytes;
            }
            else
            {
                // otherwise, the respective byte of the array is replaced by the new one: 
                bytes.Data[index] = b;
            }
        }
Пример #37
0
			private void Callback(IAsyncResult ar)
			{
				if (access == StreamAccessOptions.Read)
				{
					int count = stream.EndRead(ar);
					if (count > 0)
					{
						if (count != buffer.Length)
						{
							// TODO: improve streams
							var buf = new byte[count];
							Buffer.BlockCopy(buffer.ReadonlyData, 0, buf, 0, count);
							phpStream.WriteBytes(new PhpBytes(buf));
						}
						else
						{
							phpStream.WriteBytes(buffer);
						}

						stream.BeginRead(buffer.Data, 0, buffer.Length, callback, ar.AsyncState);
					}
					else
					{
						stream.Close();
					}
				}
				else
				{
					buffer = phpStream.ReadBytes(BufferSize);
					if (buffer != null)
					{
                        stream.BeginWrite(buffer.ReadonlyData, 0, buffer.Length, callback, ar.AsyncState);
					}
					else
					{
						stream.EndWrite(ar);
						stream.Close();
					}
				}
			}