예제 #1
0
        public static int file_put_contents(Context ctx, string path, PhpValue data, WriteContentsOptions flags = WriteContentsOptions.Empty, PhpResource context = null)
        {
            StreamContext sc = StreamContext.GetValid(context, true);

            if (sc == null)
            {
                return(-1);
            }

            string mode = (flags & WriteContentsOptions.AppendContents) > 0 ? "ab" : "wb";

            using (PhpStream to = PhpStream.Open(ctx, path, mode, ProcessOptions(ctx, (FileOpenOptions)flags), sc))
            {
                if (to == null)
                {
                    return(-1);
                }

                // passing array is equivalent to file_put_contents($filename, join('', $array))
                var array = data.ArrayOrNull();
                if (array != null)
                {
                    int total = 0;

                    var enumerator = array.GetFastEnumerator();
                    while (enumerator.MoveNext())
                    {
                        int written = to.WriteBytes(enumerator.CurrentValue.ToBytes(ctx));
                        if (written == -1)
                        {
                            return(total);
                        }
                        total += written;
                    }

                    return(total);
                }

                // as of PHP 5.1.0, you may also pass a stream resource to the data parameter
                var resource = data.AsResource();
                if (resource != null)
                {
                    PhpStream from = PhpStream.GetValid(resource);
                    if (from == null)
                    {
                        return(-1);
                    }

                    return(PhpStreams.stream_copy_to_stream(from, to));
                }

                return(to.WriteBytes(data.ToBytes(ctx)));
            }
        }
예제 #2
0
        /// <summary>
        /// Searches in given objects for a locale string describing an existing culture.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="locale">Contains either an instance of <see cref="PhpArray"/> containing locales or a locale.</param>
        /// <param name="moreLocales">If <paramref name="locale"/> is not of type <see cref="PhpArray"/> contains locales, ignored otherwise.</param>
        /// <param name="culture">The resulting culture. A <B>null</B> reference means no culture has been found.</param>
        /// <returns>Whether a culture settings should be changed.</returns>
        static bool GetFirstExistingCulture(Context ctx, PhpValue locale, PhpValue[] moreLocales, out CultureInfo culture)
        {
            PhpArray array;
            IEnumerator <PhpValue> locales;

            culture = null;

            if ((array = locale.ArrayOrNull()) != null)
            {
                // locales are stored in the "locale" array:
                locales = array.Values.GetEnumerator();
                locales.MoveNext();
                locale = locales.Current;
            }
            else if (moreLocales != null)
            {
                // locales are stored in the "locale" and "moreLocales":
                locales = moreLocales.AsEnumerable().GetEnumerator();
            }
            else
            {
                throw new ArgumentNullException(nameof(moreLocales));
            }

            // enumerates locales and finds out the first which is valid:
            for (;;)
            {
                var name = locale.IsNull ? null : locale.ToString(ctx);

                culture = GetCultureByName(name);

                // name is "empty" then the current culture is not changed:
                if (name == null || name == "0")
                {
                    return(false);
                }

                // if culture exists and is specific then finish searching:
                if (culture != null)
                {
                    return(true);
                }

                // the next locale:
                if (!locales.MoveNext())
                {
                    return(false);
                }

                locale = locales.Current;
            }
        }
예제 #3
0
 /// <summary>
 /// Constructs the array iterator.
 /// </summary>
 /// <param name="ctx">Runtime context.</param>
 /// <param name="array">The array or object to be iterated on.</param>
 /// <param name="flags">Flags to control the behaviour of the ArrayIterator object. See ArrayIterator::setFlags().</param>
 public virtual void __construct(Context /*!*/ ctx, PhpValue array, int flags = 0)
 {
     if ((_array = array.ArrayOrNull()) != null)
     {
         InitArrayIteratorHelper();  // instantiate now, avoid repetitous checks during iteration
     }
     else if ((_dobj = array.AsObject()) != null)
     {
         //InitObjectIteratorHelper();   // lazily to avoid one additional allocation
     }
     else
     {
         throw new ArgumentException();
         //// throw an PHP.Library.SPL.InvalidArgumentException if anything besides an array or an object is given.
         //Exception.ThrowSplException(
         //    _ctx => new InvalidArgumentException(_ctx, true),
         //    context,
         //    null, 0, null);
     }
 }
예제 #4
0
        /// <summary>
        /// Searches in given objects for a locale string describing an existing culture.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="locale">Contains either an instance of <see cref="PhpArray"/> containing locales or a locale.</param>
        /// <param name="moreLocales">If <paramref name="locale"/> is not of type <see cref="PhpArray"/> contains locales, ignored otherwise.</param>
        /// <param name="culture">The resulting culture. A <B>null</B> reference means no culture has been found.</param>
        /// <returns>Whether a culture settings should be changed.</returns>
        static bool GetFirstExistingCulture(Context ctx, PhpValue locale, PhpValue[] moreLocales, out CultureInfo culture)
        {
            PhpArray array;
            IEnumerator <PhpValue> locales;

            culture = null;

            if ((array = locale.ArrayOrNull()) != null)
            {
                // locales are stored in the "locale" array:
                locales = array.Values.GetEnumerator();
                locales.MoveNext();
                locale = locales.Current;
            }
            else if (moreLocales != null)
            {
                // locales are stored in the "locale" and "moreLocales":
                locales = moreLocales.AsEnumerable().GetEnumerator();
            }
            else
            {
                throw new ArgumentNullException(nameof(moreLocales));
            }

            // enumerates locales and finds out the first which is valid:
            for (;;)
            {
                var name = locale.IsNull ? string.Empty : locale.ToString(ctx);

                var dot = name.IndexOf('.');
                if (dot >= 0)
                {
                    // TODO: {codepage} after the dot for character encoding (usualy UTF-8)
                    name = name.Remove(dot);
                }

                // name is "empty" then the current culture is not changed:
                if (string.IsNullOrEmpty(name) || name == "0" || name == "C")
                {
                    culture = CultureInfo.InvariantCulture;
                    return(false);
                }

                //
                culture = GetCultureByName(name);

                // if culture exists and is specific then finish searching:
                if (culture != null)
                {
                    return(true);
                }

                // the next locale:
                if (!locales.MoveNext())
                {
                    return(false);
                }

                locale = locales.Current;
            }
        }
예제 #5
0
        /// <summary>
        /// Filters a variable with a specified filter.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="variable">Value to filter.</param>
        /// <param name="filter">The ID of the filter to apply.</param>
        /// <param name="options">Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callback type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.</param>
        /// <returns>Returns the filtered data, or <c>false</c> if the filter fails.</returns>
        public static PhpValue filter_var(Context ctx, PhpValue variable, int filter /*= FILTER_DEFAULT*/, PhpValue options /*= NULL*/)
        {
            switch (filter)
            {
            //
            // SANITIZE
            //

            case (int)FilterSanitize.FILTER_DEFAULT:
                return((PhpValue)variable.ToString(ctx));

            case (int)FilterSanitize.EMAIL:
                // Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
                return((PhpValue)FilterSanitizeString(variable.ToString(ctx), (c) =>
                                                      (int)c <= 0x7f && (Char.IsLetterOrDigit(c) ||
                                                                         c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' ||
                                                                         c == '*' || c == '+' || c == '-' || c == '/' || c == '=' || c == '!' ||
                                                                         c == '?' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' ||
                                                                         c == '}' || c == '~' || c == '@' || c == '.' || c == '[' || c == ']')));

            //
            // VALIDATE
            //

            case (int)FilterValidate.EMAIL:
            {
                var str = variable.ToString(ctx);
                return(RegexUtilities.IsValidEmail(str) ? (PhpValue)str : PhpValue.False);
            }

            case (int)FilterValidate.INT:
            {
                int result;
                if (int.TryParse((PhpVariable.AsString(variable) ?? string.Empty).Trim(), out result))
                {
                    if (!options.IsNull)
                    {
                        PhpException.ArgumentValueNotSupported("options", "!null");
                    }
                    return((PhpValue)result);         // TODO: options: min_range, max_range
                }
                else
                {
                    return(PhpValue.False);
                }
            }

            case (int)FilterValidate.REGEXP:
            {
                PhpArray optarray;
                // options = options['options']['regexp']
                if ((optarray = options.ArrayOrNull()) != null &&
                    optarray.TryGetValue("options", out options) && (optarray = options.ArrayOrNull()) != null &&
                    optarray.TryGetValue("regexp", out options))
                {
                    if (PCRE.preg_match(ctx, options.ToString(ctx), variable.ToString(ctx)) > 0)
                    {
                        return(variable);
                    }
                }
                else
                {
                    PhpException.InvalidArgument("options", string.Format(Resources.LibResources.option_missing, "regexp"));
                }

                return(PhpValue.False);
            }

            default:
                PhpException.ArgumentValueNotSupported(nameof(filter), filter);
                break;
            }

            return(PhpValue.False);
        }