Insert a snippet of Javascript to fetch the actual widget's contents.

@param WidgetAssetInterface $widget
@param Response             $response
181922
protected function addDeferredJavaScript(WidgetAssetInterface $widget, Response $response)
    {
        if ($this->deferAdded) {
            return;
        }

        $javaScript = $this->render->render(
            'widgetjavascript.twig',
            [
                'widget' => $widget,
            ]
        );
        $snippet = (new Snippet())
            ->setLocation(Target::AFTER_BODY_JS)
            ->setCallback((string) $javaScript)
        ;

        $this->deferAdded = true;

        $this->injector->inject($snippet, Target::AFTER_BODY_JS, $response);
    }
763958
private function persistWidget($widgetConfiguration, Widget $widget)
    {
        $widget->setName($widgetConfiguration['name']);
        $widget->setContext(isset($widgetConfiguration['context']) ? $widgetConfiguration['context'] : []);
        $widget->setSources(isset($widgetConfiguration['sources']) ? $widgetConfiguration['sources'] : []);
        $widget->setClass(isset($widgetConfiguration['class']) ? $widgetConfiguration['class'] : null);
        $widget->setExportable($widgetConfiguration['exportable']);
        $widget->setTags(isset($widgetConfiguration['tags']) ? $widgetConfiguration['tags'] : []);

        $this->em->persist($widget);

        return $widget;
    }
20629
public function onDisplay(DisplayWidgetEvent $event)
    {
        if (!$this->request) {
            throw new NoHttpRequestException();
        }

        $workspace = $event->getInstance()->getWorkspace();

        $templatePath = 'ClarolineForumBundle:Forum:forumsWorkspaceWidget.html.twig';
        $widgetType = 'workspace';
        if ($workspace == null) {
            $templatePath = 'ClarolineForumBundle:Forum:forumsDesktopWidget.html.twig';
            $widgetType = 'desktop';
        }

        $event->setContent($this->templatingEngine->render(
            $templatePath,
            array(
                'widgetType' => $widgetType,
                'messages' => $this->forumWidgetManager->getLastMessages($event->getInstance(), $workspace)
            )
        ));
        $event->stopPropagation();
    }
1032561
protected function addJquery(Request $request, Response $response)
    {
        if (!$this->config->get('general/add_jquery', false) &&
            !$this->config->get('theme/add_jquery', false)) {
            return;
        }

        // Check zone to skip expensive regex
        if (Zone::isFrontend($request) === false) {
            return;
        }

        $html = $response->getContent();
        $regex = '/<script(.*)jquery(-latest|-[0-9\.]*)?(\.min)?\.js/';
        if (preg_match($regex, $html)) {
            return;
        }

        $this->add(
            (new JavaScript('js/jquery-2.2.4.min.js', 'bolt'))
                ->setLocation(Target::BEFORE_JS)
        );
    }
525428
public function loadResponse(string $file, ResponseInterface $response) : ResponseInterface
    {
        return $this->includeResponse('load', $file, $response);
    }
1085078
protected void insert(List<Widget> widgets) {
        switch (type) {
            case DETACH:
                for (Widget widget : widgets) {
                    int index = widgets.indexOf(widget);
                    parent.insert(widget, index);
                }

                break;
            case DISPLAY:
                widgets.forEach(widget -> widget.getElement().getStyle().setDisplay(Style.Display.BLOCK));
                break;
        }
    }
847695
protected function handleResponse(ResponseInterface $response)
    {
        $contents = $response->getBody()->getContents();
        try
        {
            return $contents ? \GuzzleHttp\json_decode($contents) : null;
        }
        catch (\InvalidArgumentException $e)
        {
            throw new Exception('Unable to decode PDF Generator API response', $e->getCode(), $e);
        }
    }
1135177
public function addWidget( $widget, $service, $priority = null )
    {
        if ( ! isset( $this->widgets[$widget] ) )
        {
            $this->widgets[$widget] = new PriorityQueue;
        }

        if ( ! is_a( $service, static::WIDGET_INTERFACE, true ) )
        {
            throw new \InvalidArgumentException( sprintf(
                '%s: $service must implement "%s"',
                __METHOD__,
                static::WIDGET_INTERFACE
            ) );
        }

        $this->widgets[$widget]->insert(
            $service,
            null === $priority ? 1 : (int) $priority
        );

        return $this;
    }
738337
public function setAssetOnResponse(ResponseInterface $response)
    {
        if (!$this->asset instanceof AssetInterface) {
            throw new Exception\RuntimeException(
                'Unable to set asset on response. Request has not been resolved to an asset.'
            );
        }

        // @todo: Create Asset wrapper for mimetypes
        if (empty($this->asset->mimetype)) {
            throw new Exception\RuntimeException('Expected property "mimetype" on asset.');
        }

        $this->getAssetFilterManager()->setFilters($this->path, $this->asset);

        $this->asset    = $this->getAssetCacheManager()->setCache($this->path, $this->asset);
        $mimeType       = $this->asset->mimetype;
        $assetContents  = $this->asset->dump();

        // @codeCoverageIgnoreStart
        if (function_exists('mb_strlen')) {
            $contentLength = mb_strlen($assetContents, '8bit');
        } else {
            $contentLength = strlen($assetContents);
        }
        // @codeCoverageIgnoreEnd

        if (!empty($this->config['clear_output_buffer']) && $this->config['clear_output_buffer']) {
            // Only clean the output buffer if it's turned on and something
            // has been buffered.
            if (ob_get_length() > 0) {
                ob_clean();
            }
        }

        /* Get Last Modified */
        $lastModified   = new \DateTime();
        $lastModified->setTimestamp($this->asset->getLastModified());
        $lastModified->setTimezone(new \DateTimeZone('UTC'));

        /* Build up the response */
        $withEncoding      = $response->withAddedHeader('Content-Transfer-Encoding', 'binary');
        $withContentType   = $withEncoding->withAddedHeader('Content-Type', $mimeType);
        $withContentLength = $withContentType->withAddedHeader('Content-Length', "$contentLength");
        $withLastModified  = $withContentLength->withAddedHeader(
            'Last-Modified',
            $lastModified->format('D, d M Y H:i:s \G\M\T')
        );

        $final = clone $withLastModified;
        $final->getBody()->write($assetContents);

        $this->assetSetOnResponse = true;

        return $final;
    }
256915
public static function attachAjaxUpdateEvent($widget)
    {
        $trigger = '$("#'.$widget->id.'").trigger("ajaxUpdate.editable");';

        //check if trigger already inserted by another column
        if(strpos($widget->afterAjaxUpdate, $trigger) !== false) return;

        //inserting trigger
        if(strlen($widget->afterAjaxUpdate)) {
            $orig = $widget->afterAjaxUpdate;
            if(strpos($orig, 'js:')===0) $orig = substr($orig,3);
            $orig = "\n($orig).apply(this, arguments);";
        } else {
            $orig = '';
        }
        $widget->afterAjaxUpdate = "js: function(id, data) {
            $trigger $orig
        }";

        $widget->registerClientScript();
    }
961699
private function injectTokenToResponse(ResponseInterface $response, string $tokenValue): ResponseInterface
    {
        // Check if response is html
        $contentTypes = $response->getHeader('content-type');
        $contentType = reset($contentTypes) ?: '';
        if (strpos($contentType, 'text/html') === false) {
            return $response;
        }

        $content = $response->getBody()->__toString();

        if ($this->protectForms) {
            $content = $this->injectFormHiddenFieldToResponse($content, $tokenValue);
        }

        if ($this->protectJqueryAjax) {
            $content = $this->injectJqueryToResponse($content, $tokenValue);
        }

        return $response->withBody($this->streamFactory->createStream($content));
    }
530801
protected function injectToolbar(Response $response, Request $request)
    {
        $content = $response->getContent();
        $pos = strripos($content, '</body>');

        if (false !== $pos) {
            $toolbar = "\n".str_replace(
                    "\n",
                    '',
                    $this->twig->render(
                        '@KunstmaanAdmin/Toolbar/toolbar.html.twig',
                        ['collectors' => $this->dataCollector->getDataCollectors()]
                    )
                )."\n";
            $content = substr($content, 0, $pos).$toolbar.substr($content, $pos);
            $response->setContent($content);
        }
    }
979375
private function renderResponse($viewType, array $templateParams = [], $widget = false)
    {
        return new Response($this->renderTemplate($viewType, $templateParams, $widget));
    }
876975
private function renderNewTemplate($widget, FormInterface $form, $parentEntity)
    {
        return $this->renderTemplate('new', [
            'ajax_form'     => $widget,
            'form'          => $form->createView(),
            'meta'          => $this->meta,
            'parent_entity' => $parentEntity,
        ], $widget);
    }
491322
public function renderIntoSetCookieHeader(ResponseInterface $response) : ResponseInterface
    {
        $response = $response->withoutHeader(static::SET_COOKIE_HEADER);
        foreach ($this->setCookies as $setCookie) {
            $response = $response->withAddedHeader(static::SET_COOKIE_HEADER, (string) $setCookie);
        }

        return $response;
    }
488743
protected function processAsset(FileAssetInterface $asset, Request $request, Response $response)
    {
        $url = $this->packages->getUrl($asset->getPath(), $asset->getPackageName());
        $asset->setUrl($url);

        if ($asset->getZone() !== Zone::get($request)) {
            return;
        }

        if ($asset->isLate()) {
            if ($asset->getLocation() === null) {
                $location = Target::END_OF_BODY;
            } else {
                $location = $asset->getLocation();
            }
        } elseif ($asset->getLocation() !== null) {
            $location = $asset->getLocation();
        } else {
            $location = Target::END_OF_HEAD;
        }

        $this->injector->inject($asset, $location, $response);
    }
1003431
protected function formFilesOutput($includes, $widget)
    {
        if (!count($includes)) {
            return '';
        }

        ksort($includes); // Sort by priority.
        $usedSources = [];
        $widgets = [];
        $widgetTemplate = "WidgetsHandler.registerFile('%s', '%s');";
        $scriptTemplate = '<script type="text/javascript" src="%s"></script>';
        foreach ($includes as $priority) {
            foreach ($priority as $source) {
                if (!in_array($source, $usedSources)) {
                    $widgets[] = sprintf(($widget ? $widgetTemplate : $scriptTemplate), $source, $widget);
                    $usedSources[] = $source;
                }
            }
        }
        $output = implode(PHP_EOL, $widgets);
        if ($widget && !empty($output)) {
            $output = <<<JS
<script type='text/javascript'>
    window.addEventListener('load', function() {
        $output
    }, false)
</script>
JS;
        }

        return $output;
    }