Install requirements.

@param  \Composer\DependencyResolver\Request  $request
@param  \Composer\Package\Link[]              $links
@param  bool                                  $dev
481938
private function installRequires(Request $request, array $links, $dev = false)
    {
        foreach ($links as $link) {
            $this->logger->info($dev
                ? "Adding dev dependency <comment>{$link}</comment>"
                : "Adding dependency <comment>{$link}</comment>"
            );
            $request->install($link->getTarget(), $link->getConstraint());
        }
    }
1272756
public function selectLinkAction(Request $request)
    {
        $params = $this->getTemplateParameters($request);
        $params['cke'] = false;
        $params['multilanguage'] = $this->getParameter('kunstmaan_admin.multi_language');

        return $params;
    }
801405
function downloadDependantPackages( $sitePackage )
    {
        $dependencies = $sitePackage->attribute( 'dependencies' );
        $requirements = $dependencies['requires'];
        $remotePackagesInfo = $this->retrieveRemotePackagesList();

        foreach ( $requirements as $req )
        {
            $requiredPackageName = $req['name'];

            if ( isset( $req['min-version'] ) )
                $requiredPackageVersion = $req['min-version'];
            else
                $requiredPackageVersion = 0;

            $downloadNewPackage   = false;
            $removeCurrentPackage = false;

            // try to fetch the required package
            $package = eZPackage::fetch( $requiredPackageName, false, false, false );

            // if it already exists
            if ( is_object( $package ) )
            {
                // check its version
                $currentPackageVersion = $package->getVersion();

                // if existing package's version is less than required one
                // we remove the package and download newer one.

                if ( version_compare( $currentPackageVersion, $requiredPackageVersion ) < 0 )
                {
                    $downloadNewPackage   = true;
                    $removeCurrentPackage = true;
                }

                // else (if the version is greater or equal to the required one)
                // then do nothing (skip downloading)
            }
            else
                // if the package does not exist, we download it.
                $downloadNewPackage   = true;

            if ( $removeCurrentPackage )
            {
                $package->remove();
                unset( $package );
            }

            if ( $downloadNewPackage )
            {
                if ( !isset( $remotePackagesInfo[$requiredPackageName]['url'] ) )
                {
                    eZDebug::writeWarning( "Download of package '$requiredPackageName' failed: the URL is unknown." );
                    $this->ErrorMsg = ezpI18n::tr( 'design/standard/setup/init',
                                              'Download of package \'%pkg\' failed. You may upload the package manually.',
                                              false, array( '%pkg' => $requiredPackageName ) );
                    $this->ShowURL = true;

                    return false;
                }

                $requiredPackageURL = $remotePackagesInfo[$requiredPackageName]['url'];
                $rc = $this->downloadAndImportPackage( $requiredPackageName, $requiredPackageURL );
                if( !is_object( $rc ) )
                {
                    return false;
                }
            }
        }

        return true;
    }
215288
public function addAboutLink(Link $link)
    {
        if ($link->getName() !== 'about') {
            throw new \Exception('Error Objects only support "about" links');
        }

        $this->links->addLink($link);
    }
742106
public function rewritingSelfVersionDependencies()
    {
        $composer = $this->embeddedComposer->createComposer($this->io);
        $package = $composer->getPackage();
        $configSource = new JsonConfigSource(new JsonFile('composer.json'));

        foreach (BasePackage::$supportedLinkTypes as $type => $meta) {
            foreach ($package->{'get'.$meta['method']}() as $link) {
                if ($link->getPrettyConstraint() === 'self.version') {
                    $configSource->addLink(
                        $type,
                        $link->getTarget(),
                        $package->getPrettyVersion()
                    );
                }
            }
        }
    }
1357038
private function annotationLink(LinkType $link, ResourceObject $current, AbstractRequest $request)
    {
        if (! is_array($current->body)) {
            throw new Exception\LinkQueryException('Only array is allowed for link in ' . get_class($current), 500);
        }
        $classMethod = 'on' . ucfirst($request->method);
        $annotations = $this->reader->getMethodAnnotations(new \ReflectionMethod(get_class($current), $classMethod));
        if ($link->type === LinkType::CRAWL_LINK) {
            return $this->annotationCrawl($annotations, $link, $current);
        }

        /* @noinspection ExceptionsAnnotatingAndHandlingInspection */
        return $this->annotationRel($annotations, $link, $current)->body;
    }
913254
public function linkAction(Request $request, $id, $locale)
    {
        /** @var PageInterface $page */
        $page = $this->admin->getObject($id);

        if (!$page) {
            throw new NotFoundHttpException(sprintf('unable to find the Page with id : %s', $id));
        }

        if ($request->getMethod() == 'POST') {
            $linkPageId = $request->get('page');
            if (!$linkPageId) {
                $this->get('session')->getFlashBag()->add('sonata_flash_error', 'flash_link_error');
            } else {
                /** @var PageInterface $linkPage */
                $linkPage = $this->admin->getObject($linkPageId);

                $page->addTranslation($linkPage);

                $this->admin->update($page);

                if ($this->isXmlHttpRequest()) {
                    $html = $this->renderView(
                        '@NetworkingInitCms/PageAdmin/page_translation_settings.html.twig',
                        ['object' => $page, 'admin' => $this->admin]
                    );

                    return $this->renderJson(
                        [
                            'result' => 'ok',
                            'html' => $html,
                        ]
                    );
                }

                $this->get('session')->getFlashBag()->add('sonata_flash_success', 'flash_link_success');

                return new RedirectResponse($this->admin->generateUrl('edit', ['id' => $page->getId()]));
            }
        }

        $pages = $this->admin->getModelManager()->findBy($this->admin->getClass(), ['locale' => $locale]);

        if (count($pages)) {
            $pages = new ArrayCollection($pages);
            $originalLocale = $page->getLocale();
            $pages = $pages->filter(
                function (PageInterface $linkPage) use ($originalLocale) {
                    return !in_array($originalLocale, $linkPage->getTranslatedLocales());
                }
            );
        }

        return $this->renderWithExtraParams(
            '@NetworkingInitCms/PageAdmin/page_translation_link_list.html.twig',
            [
                'page' => $page,
                'pages' => $pages,
                'locale' => $locale,
                'original_language' => \Locale::getDisplayLanguage($page->getLocale()),
                'language' => \Locale::getDisplayLanguage($locale),
                'admin' => $this->admin,
            ]
        );
    }
291515
public void addRequiredBundles(Set<String> bundles) {
		// TODO manage transitive dependencies
		// don't require self
		Set<String> bundlesToMerge;
		String bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME);
		if (bundleName != null) {
			int idx = bundleName.indexOf(';');
			if (idx >= 0) {
				bundleName = bundleName.substring(0, idx);
			}
		}
		if (bundleName != null && bundles.contains(bundleName)
				|| projectName != null && bundles.contains(projectName)) {
			bundlesToMerge = new LinkedHashSet<String>(bundles);
			bundlesToMerge.remove(bundleName);
			bundlesToMerge.remove(projectName);
		} else {
			bundlesToMerge = bundles;
		}
		String s = (String) getMainAttributes().get(REQUIRE_BUNDLE);
		Wrapper<Boolean> modified = Wrapper.wrap(this.modified);
		String result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified, lineDelimiter);
		this.modified = modified.get();
		getMainAttributes().put(REQUIRE_BUNDLE, result);
	}
1246877
private function loadRequiredModules(
		Module $module,
		&$modules,
		array $moduleList,
		DependencyInjectionContainer $dic) {
		foreach ($module->getRequiredModules() as $requiredModule) {
			if (!\in_array($requiredModule, $moduleList)) {
				$this->loadModule($requiredModule, $modules, $moduleList, $dic);
				if ($module instanceof RequiredModuleAwareModule) {
					$module->addRequiredModule($dic->make($requiredModule));
				}
			}
		}
	}
161329
public function init($request)
    {
        if (($shopId = $request->getParameter('shp')) && (1 < $shopId)) {
            $this->switchToShop($shopId);
        }

        $modulesToActivate = $request->getParameter("modulestoactivate");
        $moduleDirectory = \OxidEsales\Eshop\Core\Registry::getConfig()->getModulesDir();

        $this->prepareModulesForActivation($moduleDirectory);
        foreach ($modulesToActivate as $modulePath) {
            $this->installModule($modulePath);
        }
    }
223904
public function searchAction(Request $request)
    {
        // TODO: switch to master language of element
        $defaultLanguage = $this->container->getParameter('phlexible_cms.languages.default');

        $language = $request->get('language', $defaultLanguage);
        $query = $request->get('query');
        $siterootId = $request->get('siteroot_id');
        $allowTid = $request->get('allow_tid');
        $allowIntrasiteroot = $request->get('allow_intrasiteroot');
        $elementTypeIds = $request->get('element_type_ids', '');

        $conn = $this->get('doctrine.dbal.default_connection');

        $qb = $conn->createQueryBuilder();

        if ($elementTypeIds) {
            $elementTypeIds = explode(',', $elementTypeIds);
            foreach ($elementTypeIds as $key => $elementTypeId) {
                $elementTypeIds[$key] = $qb->expr()->literal($elementTypeId);
            }
        }

        $or = null;
        if (!$allowTid || !$allowIntrasiteroot) {
            $or = $qb->expr()->orX();
            if ($allowTid) {
                $or->add($qb->expr()->eq('t.siteroot_id', $qb->expr()->literal($siterootId)));
            }

            if ($allowIntrasiteroot) {
                $or->add($qb->expr()->neq('t.siteroot_id', $qb->expr()->literal($siterootId)));
            }
        }

        $qb
            ->select('t.id', 't.type_id AS eid', 't.siteroot_id', 'evmf.backend AS title')
            ->from('tree', 't')
            ->join('t', 'element', 'e', 't.type_id = e.eid')
            ->join('e', 'element_version', 'ev', 'e.eid = ev.eid AND e.latest_version = ev.version')
            ->join('ev', 'element_version_mapped_field', 'evmf', 'evmf.element_version_id = ev.id AND evmf.language = '.$qb->expr()->literal($language))
            ->where($qb->expr()->eq('t.id', $qb->expr()->literal($query)))
            ->orderBy('title', 'ASC');

        if ($or) {
            $qb->andWhere($or);
        }

        if ($elementTypeIds) {
            $qb->andWhere($qb->expr()->in('e.elementtype_id', $elementTypeIds));
        }

        $results1 = $conn->fetchAll($qb->getSQL());

        $qb = $conn->createQueryBuilder();
        $qb
            ->select('t.id', 't.type_id AS eid', 't.siteroot_id', 'evmf.backend AS title')
            ->from('tree', 't')
            ->join('t', 'element', 'e', 't.type_id = e.eid')
            ->join('e', 'element_version', 'ev', 'e.eid = ev.eid AND e.latest_version = ev.version')
            ->join('ev', 'element_version_mapped_field', 'evmf', 'evmf.element_version_id = ev.id AND evmf.language = '.$qb->expr()->literal($language))
            ->where($qb->expr()->like('evmf.backend', $qb->expr()->literal("%$query%")))
            ->orderBy('title', 'ASC');

        if ($or) {
            $qb->andWhere($or);
        }

        if ($elementTypeIds) {
            $qb->andWhere($qb->expr()->in('e.elementtype_id', $elementTypeIds));
        }

        $results2 = $conn->fetchAll($qb->getSQL());

        $results = array_merge($results1, $results2);

        $siterootManager = $this->get('phlexible_siteroot.siteroot_manager');

        $data = [];
        foreach ($results as $row) {
            $siteroot = $siterootManager->find($row['siteroot_id']);
            $data[] = [
                'id' => $row['id'],
                'type' => ($siterootId === $row['siteroot_id'] ? 'internal' : 'intrasiteroot'),
                'tid' => $row['id'],
                'eid' => $row['eid'],
                'title' => $siteroot->getTitle($language)
                    .' :: '.$row['title'].' ['.$row['id'].']',
            ];
        }

        return new JsonResponse(['results' => $data]);
    }
492551
private function createRequest(Request $request = null): void
    {
        if (!$this->request && is_null($request)) {
            $request = ServerRequest::fromGlobals()
                ->withParsedBody(json_decode(file_get_contents('php://input')));
        }

        $this->container->set(Request::class, $request);
        $this->request = $request;
    }
990527
public function __doRequest($request, $location, $action, $version, $oneWay = 0)
    {
        $aFind = [':ns1', 'ns1:', "\n", "\r"];
        $sReplace = '';
        $newrequest = str_replace($aFind, $sReplace, $request);

        return parent::__doRequest($newrequest, $location, $action, $version, $oneWay);
    }
1054157
def prepare_linked_requirement(
        self,
        req,  # type: InstallRequirement
        session,  # type: PipSession
        finder,  # type: PackageFinder
        upgrade_allowed,  # type: bool
        require_hashes  # type: bool
    ):
        # type: (...) -> DistAbstraction
        
        # TODO: Breakup into smaller functions
        if req.link and req.link.scheme == 'file':
            path = url_to_path(req.link.url)
            logger.info('Processing %s', display_path(path))
        else:
            logger.info('Collecting %s', req)

        with indent_log():
            # @@ if filesystem packages are not marked
            # editable in a req, a non deterministic error
            # occurs when the script attempts to unpack the
            # build directory
            req.ensure_has_source_dir(self.build_dir)
            # If a checkout exists, it's unwise to keep going.  version
            # inconsistencies are logged later, but do not fail the
            # installation.
            # FIXME: this won't upgrade when there's an existing
            # package unpacked in `req.source_dir`
            # package unpacked in `req.source_dir`
            if os.path.exists(os.path.join(req.source_dir, 'setup.py')):
                rmtree(req.source_dir)
            req.populate_link(finder, upgrade_allowed, require_hashes)

            # We can't hit this spot and have populate_link return None.
            # req.satisfied_by is None here (because we're
            # guarded) and upgrade has no impact except when satisfied_by
            # is not None.
            # Then inside find_requirement existing_applicable -> False
            # If no new versions are found, DistributionNotFound is raised,
            # otherwise a result is guaranteed.
            assert req.link
            link = req.link

            # Now that we have the real link, we can tell what kind of
            # requirements we have and raise some more informative errors
            # than otherwise. (For example, we can raise VcsHashUnsupported
            # for a VCS URL rather than HashMissing.)
            if require_hashes:
                # We could check these first 2 conditions inside
                # unpack_url and save repetition of conditions, but then
                # we would report less-useful error messages for
                # unhashable requirements, complaining that there's no
                # hash provided.
                if is_vcs_url(link):
                    raise VcsHashUnsupported()
                elif is_file_url(link) and is_dir_url(link):
                    raise DirectoryUrlHashUnsupported()
                if not req.original_link and not req.is_pinned:
                    # Unpinned packages are asking for trouble when a new
                    # version is uploaded. This isn't a security check, but
                    # it saves users a surprising hash mismatch in the
                    # future.
                    #
                    # file:/// URLs aren't pinnable, so don't complain
                    # about them not being pinned.
                    raise HashUnpinned()

            hashes = req.hashes(trust_internet=not require_hashes)
            if require_hashes and not hashes:
                # Known-good hashes are missing for this requirement, so
                # shim it with a facade object that will provoke hash
                # computation and then raise a HashMissing exception
                # showing the user what the hash should be.
                hashes = MissingHashes()

            try:
                download_dir = self.download_dir
                # We always delete unpacked sdists after pip ran.
                autodelete_unpacked = True
                if req.link.is_wheel and self.wheel_download_dir:
                    # when doing 'pip wheel` we download wheels to a
                    # dedicated dir.
                    download_dir = self.wheel_download_dir
                if req.link.is_wheel:
                    if download_dir:
                        # When downloading, we only unpack wheels to get
                        # metadata.
                        autodelete_unpacked = True
                    else:
                        # When installing a wheel, we use the unpacked
                        # wheel.
                        autodelete_unpacked = False
                unpack_url(
                    req.link, req.source_dir,
                    download_dir, autodelete_unpacked,
                    session=session, hashes=hashes,
                    progress_bar=self.progress_bar
                )
            except requests.HTTPError as exc:
                logger.critical(
                    'Could not install requirement %s because of error %s',
                    req,
                    exc,
                )
                raise InstallationError(
                    'Could not install requirement %s because of HTTP '
                    'error %s for URL %s' %
                    (req, exc, req.link)
                )
            abstract_dist = make_abstract_dist(req)
            with self.req_tracker.track(req):
                abstract_dist.prep_for_dist(finder, self.build_isolation)
            if self._download_should_save:
                # Make a .zip of the source_dir we already created.
                if req.link.scheme in vcs.all_schemes:
                    req.archive(self.download_dir)
        return abstract_dist
530189
@Override
    protected ResolutionResult resolveDependencies(String projectFolder, String topLevelFolder, Set<String> bomFiles) {
        boolean installSuccess = true;
        Collection<DependencyInfo> dependencyInfos = new LinkedList<>();
        Collection<String> directDependencies = new LinkedList<>();
        File composerLock = new File(topLevelFolder + FORWARD_SLASH + COMPOSER_LOCK);

        // run pre step according to phpPreStep flag
        if (phpPreStep) {
            installSuccess = !executePreStepCommand(topLevelFolder);
        } else {
            if (!composerLock.exists()) {
                logger.warn("Could not find {} file in {}. Please execute {} {} first.", COMPOSER_LOCK, topLevelFolder, COMPOSER, INSTALL);
            }
        }
        if (installSuccess && composerLock.exists()) {
            try {
                Map<String, Object> requireMap = new HashMap<>();
                InputStream is = new FileInputStream(topLevelFolder + FORWARD_SLASH + COMPOSER_JSON);
                String jsonText = IOUtils.toString(is);
                JSONObject json = new JSONObject(jsonText);
                if (json.has(REQUIRE)) {
                    JSONObject require = json.getJSONObject(REQUIRE);
                    requireMap = require.toMap();
                }
                if (includeDevDependencies) {
                    if (json.has(REQUIRE_DEV)) {
                        JSONObject requireDev = json.getJSONObject(REQUIRE_DEV);
                        Map<String, Object> requireDevMap = requireDev.toMap();
                        requireMap.putAll(requireDevMap);
                    }
                }
                if (!requireMap.isEmpty()) {
                    if (requireMap.containsKey(PHP)) {
                        requireMap.remove(PHP);
                    }
                    directDependencies.addAll(requireMap.keySet());
                }

            } catch (IOException e) {
                logger.error("Didn't succeed to read {} - {} ", COMPOSER_JSON, e.getMessage());
            }
        }

        if (!directDependencies.isEmpty()) {
            try {
                JsonReader jsonReader = new JsonReader(new FileReader(topLevelFolder + FORWARD_SLASH + COMPOSER_LOCK));
                PhpModel phpModel = new Gson().fromJson(jsonReader, PhpModel.class);
                Collection<PhpPackage> phpPackages = phpModel.getPhpPackages();
                if (includeDevDependencies) {
                    phpPackages.addAll(phpModel.getPhpPackagesDev());
                }
                if (!phpPackages.isEmpty()) {
                    dependencyInfos = createDependencyInfos(phpPackages, dependencyInfos, directDependencies);
                } else {
                    logger.debug("The file {} is empty", COMPOSER_LOCK);
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
        return new ResolutionResult(dependencyInfos, getExcludes(), getDependencyType(), topLevelFolder);
    }
1141431
public function createLinks($web) {
        $web = Path::ds($web, true);

        foreach ($this->getModules() as $key => $module) {
            $moduleWeb = $module->getPath() . 'web' . Path::SEPARATOR;

            if (!file_exists($moduleWeb)) {
                continue;
            }

            $targetLink = $web . $key . Path::SEPARATOR;

            // Create symlink if folder doesn't exist
            if (!file_exists($targetLink)) {
                symlink($moduleWeb, $targetLink);

            // Throw an error if file exists but is not a symlink
            } else if (is_file($targetLink) && !is_link($targetLink)) {
                throw new AssetSymlinkException(sprintf('Webroot folder %s must not exist so that static assets can be symlinked', $key));
            }
        }
    }
1085479
public function addRequires(array $requires, $dev = false)
    {
        foreach ($requires as $vendor => $version) {
            if (!isset($vendor) || !isset($version)) {
                continue;
            }

            if (!$dev) {
                $this->addRequire($vendor, $version);
            } else {
                $this->addDevRequire($vendor, $version);
            }
        }

        return $this;
    }