Applies the current context to the stream

Use this to change the values of the context after you've opened a stream

@return  boolean

@since   1.0
@throws  FilesystemException
553602
public function applyContextToStream()
	{
		$retval = false;

		if ($this->fh)
		{
			// Capture PHP errors
			$php_errormsg = 'Unknown error setting context option';
			$trackErrors  = ini_get('track_errors');
			ini_set('track_errors', true);
			$retval = @stream_context_set_option($this->fh, $this->contextOptions);

			// Restore error tracking to what it was before
			ini_set('track_errors', $trackErrors);

			if (!$retval)
			{
				throw new FilesystemException($php_errormsg);
			}
		}

		return $retval;
	}
1340991
public function current() {
        // It is possible that this context has been deleted and we now have subsequent calls being made with this
        // contextlist. Exceptions here will stop the further processing of this component and that is why we are
        // doing a try catch.
        try {
            $context = \context::instance_by_id($this->contextids[$this->iteratorposition]);
        } catch (\Exception $e) {
            // Remove this context.
            unset($this->contextids[$this->iteratorposition]);
            // Check to see if there are any more contexts left.
            if ($this->count()) {
                // Move the pointer to the next record and try again.
                $this->next();
                $context = $this->current();
            } else {
                // There are no more context ids left.
                return;
            }
        }
        return $context;
    }
144845
public function initializeContext(Context $context)
    {
        if ($context instanceof ResourceContext) {
            $reflector = new ReflectionClass(get_class($context));

            if ($this->builder->getLoader() instanceof FileResourceLoader) {
                if ($this->builder->getLoader()->getBasePath() == null) {
                    $this->builder->getLoader()->setBasePath(dirname($reflector->getFileName()));
                }
            }

            if ($context->getResourceFactory()) {
                $this->builder->setFactory($context->getResourceFactory());
            }

            $context->setResourceBuilder($this->builder);
        }
    }
496443
public function setActiveContext($context)
    {
        $oldLocale = isset($this->activeContext) ? $this->contextLocales[$this->activeContext] : null;
        $this->activeContext = $context;
        if (!isset($this->contextLocales[$context])) {
            $this->setContextLocale($context, static::BASE_LOCALE);
        }
        $newLocale = $this->contextLocales[$context];
        if ($newLocale !== $oldLocale) {
            $this->currentLocaleChanged($newLocale);
        }
    }
227982
public function setStream($stream)
    {
        // streams have to be cached to file first
        $meta = @stream_get_meta_data($stream);
        if (!$meta || !$meta['mode'] || !in_array($meta['mode'], self::$readableModes, true) || $meta['eof']) {
            throw new Exception(
                'setStream() expects parameter stream to be readable stream resource.'
            );
        }

        /** @var resource $tmp_fp */
        $tmp_fp = tmpfile();
        if ($tmp_fp) {
            while (!feof($stream)) {
                fwrite($tmp_fp, fread($stream, 2028));
            }

            if (fread($tmp_fp, 1) != "\n") {
                fwrite($tmp_fp, PHP_EOL);
            }

            fseek($tmp_fp, 0);
            $this->stream = &$tmp_fp;
        } else {
            throw new Exception(
                'Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.'
            );
        }
        fclose($stream);

        $this->resource = mailparse_msg_create();
        // parses the message incrementally (low memory usage but slower)
        while (!feof($this->stream)) {
            mailparse_msg_parse($this->resource, fread($this->stream, 2082));
        }
        $this->parse();

        return $this;
    }
1070526
def set_context(self, context):
        """"""
        self._set_context(context, emit=False)
        self._modified = (not context.load_path)
        self.dataChanged.emit(self.CONTEXT_CHANGED |
                              self.REQUEST_CHANGED |
                              self.PACKAGES_PATH_CHANGED |
                              self.LOCKS_CHANGED |
                              self.LOADPATH_CHANGED |
                              self.PACKAGE_FILTER_CHANGED |
                              self.CACHING_CHANGED)
1250206
public void setContext(Context context) {
        log = Log.instance(context);
        options = Options.instance(context);
        classLoaderClass = options.get("procloader");

        // Avoid initializing Lint
        boolean warn = options.isLintSet("path");
        locations.update(log, warn, FSInfo.instance(context));

        // Setting this option is an indication that close() should defer actually closing
        // the file manager until after a specified period of inactivity.
        // This is to accomodate clients which save references to Symbols created for use
        // within doclets or annotation processors, and which then attempt to use those
        // references after the tool exits, having closed any internally managed file manager.
        // Ideally, such clients should run the tool via the javax.tools API, providing their
        // own file manager, which can be closed by the client when all use of that file
        // manager is complete.
        // If the option has a numeric value, it will be interpreted as the duration,
        // in seconds, of the period of inactivity to wait for, before the file manager
        // is actually closed.
        // See also deferredClose().
        String s = options.get("fileManager.deferClose");
        if (s != null) {
            try {
                deferredCloseTimeout = (int) (Float.parseFloat(s) * 1000);
            } catch (NumberFormatException e) {
                deferredCloseTimeout = 60 * 1000;  // default: one minute, in millis
            }
        }
    }
289195
public function apply()
    {
        $this->backup = is_file($this->name) ? file_get_contents($this->name) : new NotSet();

        file_put_contents($this->name, $this->value);
    }
257254
public function saveTemporary()
    {
        $this->applyFilters();

        if (!$this->hasTranslations() || !$this->isValid()) {
            throw new Exception('unable to save empty or invalid translations');
        }

        $path = $this->getTemporaryTranslationPath();

        Filesystem::mkdir(dirname($path));

        return file_put_contents($path, $this->__toString());
    }
504571
public function path($value = false, $overwrite = false)
    {
        if ($value === false) {
            return $this->path;
        }

        $oldPath = $this->path;

        if (!$overwrite && $this->adapter->fileExists($value)) {
            throw new FilesystemException("Cannot rename the file '{$this->path}' to '{$value}' because a file already exists");
        }

        (new static($value, $this->adapter))->remove();

        if (! $this->adapter->rename($this->path, $value)) {
            throw new FilesystemException("Cannot rename the file '{$this->path}' to '{$value}'");
        }

        $this->path = $value;
        $this->fs = null;
        $this->pathChanged($oldPath);

        return $this;
    }
1220609
public function stream_tell()
    {
        if ($this->fileHandle === null) {
            return false;
        }
        self::restore();
        $position = ftell($this->fileHandle);
        self::register();
        return $position;
    }
646329
public function commit()
    {
        // Throws a nice exception if no token
        $this->getToken();

        if (!$this->layout instanceof Layout) {
            throw new \LogicException("No contextual instance is set, cannot commit");
        }

        // This gets the temporary storage until now
        $this->getStorage()->delete($this->layout->getId());
        // Loaded instance is supposed to be the false one
        $this->storage->save($this->layout);

        $this->setToken(null);

        return $this;
    }
1154420
protected function proxy() {
        if (!$this->context) {
            $this->context = new SyncStreamContext(
                $this->version,
                $this->solution['serviceSid'],
                $this->solution['sid']
            );
        }

        return $this->context;
    }
322378
public function createWriteContext()
    {
        $stream      = Stream::create();
        $writer      = $this->getStreamWriter();
        $sizeContext = $this->createComputeSizeContext();
        $context     = new WriteContext($stream, $writer, $sizeContext);

        return $context;
    }
1304796
public function setPreferRead()
    {
        //====================================================================//
        // Safety Checks ==> Verify a new Field Exists
        if (empty($this->new)) {
            Splash::log()->err("ErrFieldsNoNew");
        } else {
            //====================================================================//
            // Update New Field structure
            $this->new->syncmode = self::MODE_READ;
        }

        return $this;
    }
1071465
public function useGlobally()
    {
        if (!isset($this->handle)) {
            throw new \RuntimeException("The stream is closed");
        }
        
        if ($this->isGlobal()) {
            return $this;
        }
        
        $this->assertOutputBuffering();
        
        $output = $this->createOutputStream();
        if ($output === false) {
            throw new \RuntimeException("Failed to create temp stream");
        }
        
        $this->obClean();
        $this->rewind();
        stream_copy_to_stream($this->handle, $output);
        
        parent::close();
        $this->handle = $output;
        
        return $this;
    }
1102781
public function setCurrentLocaleByContext()
    {
        if (function_exists('apply_filters')) {
            // Give a chance for plugins to override this decision
            $locale = null;
            $locale = apply_filters('strata_i18n_set_current_locale_by_context', $locale);
            if (!is_null($locale)) {
                return $this->setLocale($locale);
            }
        }

        if (!is_null($this->currentLocale)) {
            return $this->currentLocale;
        }

        $request = new Request();

        // Under ajax, one could post the value.
        if (Router::isAjax() && $request->hasPost("locale")) {
            $locale = $this->getLocaleByCode($request->post("locale"));
            if (!is_null($locale)) {
                return $this->setLocale($locale);
            }
        }

        if ($request->hasGet("locale")) {
            $locale = $this->getLocaleByCode($request->get("locale"));
            if (!is_null($locale)) {
                return $this->setLocale($locale);
            }
        }

        $inAdmin = function_exists('is_admin') ? is_admin() : false;
        if (!$inAdmin) {
            // This validates all locales but the default one
            $urls = implode('|', $this->getLocaleRegexUrls());

            if (array_key_exists('REQUEST_URI', (array)$_SERVER)) {
                if (preg_match('/^\/('.$urls.')\//i', $_SERVER['REQUEST_URI'], $match)) {
                    $locale = $this->getLocaleByUrl($match[1]);
                    if (!is_null($locale)) {
                        return $this->setLocale($locale);
                    }
                // Also validates for lack of locale code, meaning
                // a possible default locale match when no ajax-ing.
                } elseif (preg_match('/^(?:(?!'.$urls.'))\/?/i', $_SERVER['REQUEST_URI'])) {
                    $locale = $this->getDefaultLocale();
                    if (!is_null($locale)) {
                        return $this->setLocale($locale);
                    }
                }
            }
        }

        if ($this->hasLocaleInSession()) {
            $locale = $this->getLocaleInSession();
            if (!is_null($locale)) {
                return $this->setLocale($locale);
            }
        }

        if ($this->hasDefaultLocale()) {
            return $this->setLocale($this->getDefaultLocale());
        }
    }