Ejemplo n.º 1
0
        ///// <summary>
        ///// A counter used to generate unique filenames for <see cref="tempnam(string, string)"/>.
        ///// </summary>
        //static int _tempCounter = 0;

        /// <summary>
        /// Returns canonicalized absolute path name.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="path">Arbitrary path.</param>
        /// <returns>
        /// The given <paramref name="path"/> combined with the current working directory or
        /// <B>null</B> (<B>false</B> in PHP) if the path is invalid or doesn't exists.
        /// </returns>
        public static string realpath(Context ctx, string path)
        {
            if (path == null)
            {
                return(null);
            }

            if (path.Length == 0)
            {
                return(ctx.WorkingDirectory);
            }

            // string ending slash
            if (path[path.Length - 1].IsDirectorySeparator())
            {
                path = path.Substring(0, path.Length - 1);
            }

            string realpath = FileSystemUtils.AbsolutePath(ctx, path);

            if (!File.Exists(realpath) && !System.IO.Directory.Exists(realpath))
            {
                return(null);
            }

            return(realpath);
        }
        /// <summary>
        /// Adds a file to a ZIP archive from a given path.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="filename">The path to the file to add.</param>
        /// <param name="localname">If supplied, this is the local name inside the ZIP archive that will override the filename.</param>
        /// <param name="start">This parameter is not used.</param>
        /// <param name="length">This parameter is not used.</param>
        /// <returns></returns>
        public bool addFile(Context ctx, string filename, string localname = null, int start = 0, int length = 0)
        {
            if (!CheckInitialized())
            {
                return(false);
            }

            ZipArchiveEntry entry = null;

            try
            {
                entry = CreateEntryIfNotExists(localname ?? Path.GetFileName(filename));
                entry.LastWriteTime = File.GetLastWriteTime(FileSystemUtils.AbsolutePath(ctx, filename));

                using (var entryStream = entry.Open())
                    using (PhpStream handle = PhpStream.Open(ctx, filename, "r", StreamOpenOptions.Empty))
                    {
                        handle.RawStream.CopyTo(entryStream);
                    }

                return(true);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                entry?.Delete();
                return(false);
            }
        }
Ejemplo n.º 3
0
        public static string tempnam(Context ctx, string dir, string prefix)
        {
            // makes "dir" a valid directory:
            dir = FileSystemUtils.AbsolutePath(ctx, dir);                       // Resolve to current working directory (Context.WorkingDirectory)

            if (string.IsNullOrEmpty(dir) || !System.IO.Directory.Exists(dir))
            {
                dir = Path.GetTempPath();
            }
            else
            {
                dir += Path.DirectorySeparatorChar;
            }

            // makes "prefix" a valid file prefix:
            if (string.IsNullOrEmpty(prefix) || prefix.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
            {
                prefix = "tmp_";
            }

            var    suffix = unchecked ((ulong)System.DateTime.UtcNow.Ticks / 5) & 0xffff;
            string result;

            try
            {
                for (; ; suffix++)
                {
                    result = string.Concat(dir, prefix, suffix.ToString("x4"), ".tmp");
                    if (!File.Exists(result))
                    {
                        try
                        {
                            File.Open(result, FileMode.CreateNew).Close();
                            break;
                        }
                        catch (UnauthorizedAccessException)
                        {
                            // try system temp directory:
                            dir = Path.GetTempPath();
                        }
                        catch (PathTooLongException e)
                        {
                            PhpException.Throw(PhpError.Notice, PhpException.ToErrorMessage(e.Message));
                            return(Path.GetTempFileName());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                PhpException.Throw(PhpError.Notice, PhpException.ToErrorMessage(e.Message));
                return(null);
            }

            return(result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Set the URI containing the XML document to be parsed.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="URI">URI pointing to the document.</param>
        /// <param name="encoding">The document encoding or NULL.</param>
        /// <param name="options">A bitmask of the LIBXML_* constants.</param>
        /// <returns>Returns TRUE on success or FALSE on failure.</returns>
        public bool open(Context ctx, string URI, string encoding = null, int options = 0)
        {
            if (string.IsNullOrWhiteSpace(URI))
            {
                PhpException.Throw(PhpError.Warning, Pchp.Library.Resources.Resources.arg_empty, nameof(URI));
                return(false);
            }

            _source    = FileSystemUtils.AbsolutePath(ctx, URI);
            _uriSource = true;
            _encoding  = encoding;
            _options   = options;
            return(createReader());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Adds a file to a ZIP archive from a given path.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="filename">The path to the file to add.</param>
        /// <param name="localname">If supplied, this is the local name inside the ZIP archive that will override the filename.</param>
        /// <param name="start">For partial copy, start position.</param>
        /// <param name="length">For partial copy, length to be copied, if 0 or -1 the whole file (starting from <paramref name="start"/>) is used.</param>
        /// <returns>TRUE on success or FALSE on failure.</returns>
        public bool addFile(Context ctx, string filename, string localname = null, int start = 0, int length = 0)
        {
            if (!CheckInitialized())
            {
                return(false);
            }

            ZipArchiveEntry entry = null;

            try
            {
                entry = CreateEntryIfNotExists(localname ?? Path.GetFileName(filename));
                entry.LastWriteTime = File.GetLastWriteTime(FileSystemUtils.AbsolutePath(ctx, filename));

                using (var entryStream = entry.Open())
                    using (PhpStream handle = PhpStream.Open(ctx, filename, "r", StreamOpenOptions.Empty))
                    {
                        if (start != 0)
                        {
                            handle.Seek(start, SeekOrigin.Begin);
                        }

                        if (length == 0 || length == -1)
                        {
                            handle.RawStream.CopyTo(entryStream);
                        }
                        else
                        {
                            // We need to copy the contents manually if the length was specified
                            var buffer = new byte[Math.Min(length, PhpStream.DefaultBufferSize)];
                            int copied = 0;
                            while (copied < length)
                            {
                                int lastCopied = handle.RawStream.Read(buffer, 0, Math.Min(buffer.Length, length - copied));
                                entryStream.Write(buffer, 0, lastCopied);
                                copied += lastCopied;
                            }
                        }
                    }

                return(true);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                entry?.Delete();
                return(false);
            }
        }
 /// <summary>Changes the virtual working directory for the current script.</summary>
 /// <param name="ctx">Runtime context.</param>
 /// <param name="directory">Absolute or relative path to the new working directory.</param>
 /// <returns>Returns <c>true</c> on success or <c>false</c> on failure.</returns>
 /// <exception cref="PhpException">If the specified directory does not exist.</exception>
 public static bool chdir(Context ctx, string directory)
 {
     if (directory != null)
     {
         string newPath = FileSystemUtils.AbsolutePath(ctx, directory);
         if (System.IO.Directory.Exists(newPath))
         {
             // Note: open_basedir not applied here, URL will not pass through
             ctx.WorkingDirectory = newPath;
             return(true);
         }
     }
     PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.directory_not_found, directory));
     return(false);
 }
Ejemplo n.º 7
0
        public static string?bindtextdomain(Context ctx, string domain, string directory)
        {
            string localeDir = FileSystemUtils.AbsolutePath(ctx, directory);

            var culture = Locale.GetCulture(ctx, Locale.Category.All);

            var catalog = GetOrLoadCatalog(new CacheKey()
            {
                LocaleDir = localeDir, Culture = culture, Domain = domain
            });

            var translationCtx = ctx.GetStatic <TranslationContext>();

            translationCtx.BindTextDomain(domain, localeDir);

            return(catalog.IsValid ? localeDir : null);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Stores a local file on the FTP server.
        /// </summary>
        /// <param name="context">Runtime context.</param>
        /// <param name="ftp_stream">The link identifier of the FTP connection.</param>
        /// <param name="remote_file">The remote file path.</param>
        /// <param name="local_file">The local file path.</param>
        /// <param name="mode">The transfer mode. Must be either <see cref="FTP_ASCII"/> or <see cref="FTP_BINARY"/>.</param>
        /// <param name="startpos">Not Supported</param>
        /// <returns>Returns TRUE on success or FALSE on failure.</returns>
        public static bool ftp_put(Context context, PhpResource ftp_stream, string remote_file, string local_file, int mode = FTP_IMAGE, int startpos = 0)
        {
            var resource = ValidateFtpResource(ftp_stream);

            if (resource == null)
            {
                return(false);
            }

            string localPath = FileSystemUtils.AbsolutePath(context, local_file);

            if (!FileSystemUtils.IsLocalFile(localPath))
            {
                PhpException.Throw(PhpError.Warning, Resources.Resources.file_not_exists, local_file);
                return(false);
            }

            // Two types of data transfer
            resource.Client.UploadDataType = (mode == FTP_ASCII) ? FtpDataType.ASCII : FtpDataType.Binary;

            if (startpos != 0) // There is no API for this parameter in FluentFTP Library.
            {
                PhpException.ArgumentValueNotSupported(nameof(startpos), startpos);
            }

            try
            {
                return(resource.Client.UploadFile(localPath, remote_file, FtpExists.Overwrite));
            }

            /* FtpException everytime wraps other exceptions (Message from server).
             * https://github.com/robinrodricks/FluentFTP/blob/master/FluentFTP/Client/FtpClient_HighLevelUpload.cs#L595 */
            catch (FtpException ex)
            {
                PhpException.Throw(PhpError.Warning, ex.InnerException.Message);
            }
            catch (ArgumentException ex)
            {
                PhpException.Throw(PhpError.Warning, Resources.Resources.file_not_exists, ex.ParamName);
            }

            return(false);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Opens a new zip archive for reading.
 /// </summary>
 /// <param name="ctx">Current runtime context.</param>
 /// <param name="filename">The file name of the ZIP archive to open.</param>
 /// <returns>Returns a resource handle for later use with <see cref="zip_read(ZipArchiveResource)"/>
 /// and <see cref="zip_close(ZipArchiveResource)"/> or returns the number of error if
 /// <paramref name="filename"/> does not exist or in case of other error.</returns>
 public static PhpValue zip_open(Context ctx, string filename)
 {
     try
     {
         string fullPath   = FileSystemUtils.AbsolutePath(ctx, filename);
         var    fileStream = File.Open(fullPath, FileMode.Open);
         var    archive    = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Read);
         return(PhpValue.FromClass(new ZipArchiveResource(archive)));
     }
     catch (FileNotFoundException e)
     {
         PhpException.Throw(PhpError.Warning, e.Message);
         return(ER_NOENT);
     }
     catch (IOException e)
     {
         PhpException.Throw(PhpError.Warning, e.Message);
         return(ER_OPEN);
     }
 }
Ejemplo n.º 10
0
        public static string realpath(Context ctx, string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(ctx.WorkingDirectory);
            }

            // string ending slash
            path = path.TrimEndSeparator();

            //
            var realpath = FileSystemUtils.AbsolutePath(ctx, path);

            if (File.Exists(realpath) ||
                System.IO.Directory.Exists(realpath) ||
                Context.TryResolveScript(ctx.RootPath, realpath).IsValid)   // check a compiled script
            {
                return(realpath);
            }

            return(null);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Extract the complete archive to the specified destination.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="destination">Location where to extract the files.</param>
        /// <param name="entries">The entries to extract, currently not supported.</param>
        /// <returns>TRUE on success or FALSE on failure.</returns>
        public bool extractTo(Context ctx, string destination, PhpValue entries = default(PhpValue))
        {
            if (!CheckInitialized())
            {
                return(false);
            }

            if (!Operators.IsEmpty(entries))
            {
                PhpException.ArgumentValueNotSupported(nameof(entries), entries);
                return(false);
            }

            try
            {
                _archive.ExtractToDirectory(FileSystemUtils.AbsolutePath(ctx, destination));
                return(true);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(false);
            }
        }
Ejemplo n.º 12
0
 public void __construct(Context ctx, string file_name)
 {
     _root         = ctx.RootPath;
     _originalPath = file_name;
     _fullpath     = FileSystemUtils.AbsolutePath(ctx, file_name);
 }
Ejemplo n.º 13
0
 public virtual void __construct(Context ctx, string file_name)
 {
     _relativePath = file_name;
     _fullpath     = FileSystemUtils.AbsolutePath(ctx, file_name);
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Open a ZIP file archive.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="filename">The file name of the ZIP archive to open.</param>
        /// <param name="flags">The mode to use to open the archive.</param>
        /// <returns>TRUE on success or the error code.</returns>
        public PhpValue open(Context ctx, string filename, int flags = 0)
        {
            if ((flags & CHECKCONS) != 0)
            {
                PhpException.ArgumentValueNotSupported(nameof(flags), nameof(CHECKCONS));
            }

            if (_archive != null)
            {
                // Save the changes to the current archive before opening another one
                _archive.Dispose();
                _archive = null;
            }

            try
            {
                string fullPath = FileSystemUtils.AbsolutePath(ctx, filename);

                FileMode mode;
                if (File.Exists(fullPath))
                {
                    if ((flags & EXCL) != 0)
                    {
                        PhpException.Throw(PhpError.Warning, Resources.Resources.file_exists, fullPath);
                        return(ER_EXISTS);
                    }
                    else if ((flags & OVERWRITE) != 0)
                    {
                        mode = FileMode.Truncate;
                    }
                    else
                    {
                        mode = FileMode.Open;
                    }
                }
                else
                {
                    if ((flags & CREATE) != 0)
                    {
                        mode = FileMode.Create;
                    }
                    else
                    {
                        PhpException.Throw(PhpError.Warning, Resources.Resources.file_not_exists, fullPath);
                        return(ER_NOENT);
                    }
                }

                var fileStream = File.Open(fullPath, mode);
                _archive      = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update);
                this.filename = fullPath;

                return(true);
            }
            catch (IOException e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(ER_OPEN);
            }
            catch (InvalidDataException e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(ER_INCONS);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(ER_INTERNAL);
            }
        }