Prepare the base string.
Ref: Spec: 9.1.3 ("Concatenate Request Elements")

@return void prepared base string is stored in a class variables
352492
private function prepare_base_string() {
    $base = array(
      $this->method,
      $this->url,
      $this->signing_params
    );
    $this->base_string = implode('&', $this->safe_encode($base));
  }
525381
protected function prepareForValidation(): void
    {
        $data = $this->all();

        $data['base_cost'] = (int) $data['base_cost'];

        $this->replace($data);
    }
235459
public function prepare()
    {
        $request = parent::prepare();

        $url = $request->getUrl(true);

        $query = $url->getQuery();
        $query->merge($this->templateVariables);
        $request->setUrl($url);

        return $request;
    }
713580
protected function prepareUrlRewrites()
    {

        // call the parent method
        parent::prepareUrlRewrites();

        // (re-)initialize the array for the existing URL rewrites
        $this->existingUrlRewrites = array();

        // load primary key and entity type
        $pk = $this->getPrimaryKey();
        $entityType = UrlRewriteObserver::ENTITY_TYPE;

        // load the store ID to use
        $storeId = $this->getSubject()->getRowStoreId();

        // load the existing URL rewrites of the actual entity
        $existingUrlRewrites = $this->getUrlRewritesByEntityTypeAndEntityIdAndStoreId($entityType, $pk, $storeId);

        // prepare the existing URL rewrites to improve searching them by store ID/request path
        foreach ($existingUrlRewrites as $existingUrlRewrite) {
            // load the request path from the existing URL rewrite
            $requestPath = $existingUrlRewrite[MemberNames::REQUEST_PATH];

            // append the URL rewrite with its store ID/request path
            $this->existingUrlRewrites[$requestPath] = $existingUrlRewrite;
        }
    }
672864
public function prepare()
    {

        // prepare the context path
        $contextPath = str_replace($this->getContext()->getAppBase(), '', $this->getContext()->getWebappPath());

        // set the context path
        $this->setContextPath($contextPath);

        // Fixed #735 - Endless Loop for URLs without servlet name
        // Load the request URI and query string from the server vars, because we have to
        // take care about changes from other modules like directory or rewrite module!
        $uri = $this->getRequestUri();
        $queryString = $this->getQueryString();

        // get uri without querystring
        $uriWithoutQueryString = str_replace('?' . $queryString, '', $uri);

        // initialize the path information and the directory to start with
        list ($dirname, $basename, $extension) = array_values(pathinfo($uriWithoutQueryString));

        // make the registered handlers local
        $handlers = $this->getHandlers();

        // descent the directory structure down to find the (almost virtual) servlet file
        do {
            // bingo we found a (again: almost virtual) servlet file
            if (isset($handlers[".$extension"])) {
                // prepare the servlet path (we've to take care, because the
                // pathinfo() function converts / to \ on Windows OS
                if ($dirname === DIRECTORY_SEPARATOR) {
                    $servletPath = '/' . $basename;
                } else {
                    $servletPath = $dirname . '/' . $basename;
                }

                // we set the basename, because this is the servlet path
                $this->setServletPath($servletPath);

                // we set the path info, what is the request URI with stripped dir- and basename
                $this->setPathInfo(str_replace($servletPath, '', $uriWithoutQueryString));

                // we've found what we were looking for, so break here
                break;
            }

            // break if we finally can't find a servlet to handle the request
            if ($dirname === '/') {
                throw new ServletException(
                    sprintf('Can\'t find a handler for URI %s, either ', $uri)
                );
            }

            // descend down the directory tree
            list ($dirname, $basename, $extension) = array_values(pathinfo($dirname));

        } while ($dirname !== false); // stop until we reached the root of the URI

        // prepare and set the servlet path
        $this->setServletPath(str_replace($contextPath, '', $this->getServletPath()));

        // prepare the base modifier which allows our apps to provide a base URL
        $webappsDir = str_replace($this->getContext()->getBaseDirectory(), '', $this->getContext()->getAppBase());
        $relativeRequestPath = strstr($this->getDocumentRoot(), $webappsDir);
        $proposedBaseModifier = str_replace(DIRECTORY_SEPARATOR, '/', str_replace($webappsDir, '', $relativeRequestPath));

        //  prepare the base modifier
        if (strpos($proposedBaseModifier, $contextPath) === 0) {
            $this->setBaseModifier('');
        } else {
            $this->setBaseModifier($contextPath);
        }
    }
448248
protected function prepareRequest()
    {
        $this->formatUrl();
        $this->validateInput();
        $this->addHeaders();
        $this->addRequestBody();
        $this->initOptions();
    }
1022884
protected function prepare()
    {
        //Force passice mode if not specified
        $this->addOption('passive', true);

        //To make call on different files, we must retrieve the root and apply commands to the path
        $tmp = clone $this->getUrl();
        $tmp->path('');
        $this->addOption('url', $tmp->toString());
    }
1025583
protected static function _prepare()
    {
        if (empty(static::$_module)) {
            $module = Module::getModuleByClassname(Module::className());
            if (!empty($module)) {
                static::$_sysControllerUid = "/sys/main";
                static::$_routeActionView = "/{$module->uniqueId}/main/view";
                static::$_routeActionShow = "/{$module->uniqueId}/main/show";
                static::$_model = $module::model(self::MODEL_ALIAS);
            }
        }
    }
862849
protected function prepare_request_params() {
        global $CFG;

        $this->load_current_environment();
        $this->restore_response();

        $params = array();
        $params['format'] = 'json';

        if (isset($this->recentresponse['ticket'])) {
            $params['ticket'] = $this->recentresponse['ticket'];
        }

        if (isset($this->currentversion)) {
            $params['version'] = $this->currentversion;
        } else {
            throw new coding_exception('Main Moodle version must be already known here');
        }

        if (isset($this->currentbranch)) {
            $params['branch'] = $this->currentbranch;
        } else {
            throw new coding_exception('Moodle release must be already known here');
        }

        $plugins = array();
        foreach ($this->currentplugins as $plugin => $version) {
            $plugins[] = $plugin.'@'.$version;
        }
        if (!empty($plugins)) {
            $params['plugins'] = implode(',', $plugins);
        }

        return $params;
    }
441084
public function prepare(){
	
		/*
		Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. 
		http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1
		*/
		
		// Must be a multipart request
		if($this->files->all()){
		
			$boundary = self::generateBoundary();
			
			$this->prepared_body = Request::buildPostBody($this->post->all(), $this->files->all(), $boundary);
			$this->headers->set('content-type', 'multipart/form-data; boundary='.$boundary);
		
		} else if($this->post->all()){
			
			$this->prepared_body = http_build_query($this->post->all());
			$this->headers->set('content-type', 'application/x-www-form-urlencoded');
			
		} else {
		
			$this->headers->set('content-type', $this->detectContentType($this->body));
			$this->prepared_body = $this->body;
		}
		
		/*
		The transfer-length of a message is the length of the message-body as it appears in the message; that is, after any transfer-codings have been applied.
		http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4
		*/
		
		$len = strlen($this->prepared_body);
		
		if($len > 0){
			$this->headers->set('content-length', $len);
		} else {
			$this->headers->remove('content-length');
			$this->headers->remove('content-type');
		}
	}
334167
protected function prepare_form_data() {
		$this->data = [];

		foreach ( $this->fields as $field ) {
			$this->data[ $field->get_id() ] = $field->get_value();
		}
	}
345587
private function _initialize()
    {
        if ($this->getInitialized()) {
            return;
        }

        $params = $this->getParameters();
        if ($params !== null) {
            foreach ($params as $param) {
                if ('in' == $param->getName()) {
                    $this->setInputEncoding($param->getValue());
                } else {
                    if ('out' == $param->getName()) {
                        $this->setOutputEncoding($param->getValue());
                    }
                }
            }
        }

        $this->setInitialized(true);
    }
693692
private function prepareData()
    {
        $data = [];
        foreach (get_object_vars($this) as $property => $value) {
            if (in_array($property, ['apiHost', 'debug'])) {
                continue;
            }

            if ($property == 'format') {
                $data[$value] = '';
            } elseif (is_bool($value) && $value) {
                $data[$property] = '';
            } elseif (!is_null($value) && !is_bool($value)) {
                if (is_array($value)) {
                    foreach ($value as $key => $val) {
                        $value[$key] = $val;
                    }
                } else {
                    $value = $value;
                }

                $data[$property] = $value;
            }
        }

        if (empty($data) && $this->debug) {
            throw new \Exception('Query have not data');
        }

        $data = http_build_query($data);

        return $data;
    }
415019
private function prepare(): void
  {
    $this->addClass(static::$class);

    if (static::$responsiveMediaQuery!==null && $this->getAttribute('id')===null)
    {
      $this->setAttrId(Html::getAutoId());
    }
  }
308893
public function prepareQuery()
    {
        $query = $this->model->newQuery();
        $primaryTable = $this->model->getTable();
        $selects = [$primaryTable.'.*'];
        $joins = [];
        $withs = [];

        /**
         * @event backend.list.extendQueryBefore
         * Provides an opportunity to modify the `$query` object before the List widget applies its scopes to it.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQueryBefore', function($listWidget, $query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQueryBefore', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        $this->fireSystemEvent('backend.list.extendQueryBefore', [$query]);

        /*
         * Prepare searchable column names
         */
        $primarySearchable = [];
        $relationSearchable = [];

        $columnsToSearch = [];
        if (!empty($this->searchTerm) && ($searchableColumns = $this->getSearchableColumns())) {
            foreach ($searchableColumns as $column) {
                /*
                 * Related
                 */
                if ($this->isColumnRelated($column)) {
                    $table = $this->model->makeRelation($column->relation)->getTable();
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $table))
                        : $table . '.' . $column->valueFrom;

                    $relationSearchable[$column->relation][] = $columnName;
                }
                /*
                 * Primary
                 */
                else {
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $primaryTable))
                        : DbDongle::cast(Db::getTablePrefix() . $primaryTable . '.' . $column->columnName, 'TEXT');

                    $primarySearchable[] = $columnName;
                }
            }
        }

        /*
         * Prepare related eager loads (withs) and custom selects (joins)
         */
        foreach ($this->getVisibleColumns() as $column) {

            // If useRelationCount is enabled, eager load the count of the relation into $relation_count
            if ($column->relation && @$column->config['useRelationCount']) {
                $query->withCount($column->relation);
            }

            if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom))) {
                continue;
            }

            if (isset($column->valueFrom)) {
                $withs[] = $column->relation;
            }

            $joins[] = $column->relation;
        }

        /*
         * Add eager loads to the query
         */
        if ($withs) {
            $query->with(array_unique($withs));
        }

        /*
         * Apply search term
         */
        $query->where(function ($innerQuery) use ($primarySearchable, $relationSearchable, $joins) {

            /*
             * Search primary columns
             */
            if (count($primarySearchable) > 0) {
                $this->applySearchToQuery($innerQuery, $primarySearchable, 'or');
            }

            /*
             * Search relation columns
             */
            if ($joins) {
                foreach (array_unique($joins) as $join) {
                    /*
                     * Apply a supplied search term for relation columns and
                     * constrain the query only if there is something to search for
                     */
                    $columnsToSearch = array_get($relationSearchable, $join, []);

                    if (count($columnsToSearch) > 0) {
                        $innerQuery->orWhereHas($join, function ($_query) use ($columnsToSearch) {
                            $this->applySearchToQuery($_query, $columnsToSearch);
                        });
                    }
                }
            }

        });

        /*
         * Custom select queries
         */
        foreach ($this->getVisibleColumns() as $column) {
            if (!isset($column->sqlSelect)) {
                continue;
            }

            $alias = $query->getQuery()->getGrammar()->wrap($column->columnName);

            /*
             * Relation column
             */
            if (isset($column->relation)) {

                // @todo Find a way...
                $relationType = $this->model->getRelationType($column->relation);
                if ($relationType == 'morphTo') {
                    throw new ApplicationException('The relationship morphTo is not supported for list columns.');
                }

                $table =  $this->model->makeRelation($column->relation)->getTable();
                $sqlSelect = $this->parseTableName($column->sqlSelect, $table);

                /*
                 * Manipulate a count query for the sub query
                 */
                $relationObj = $this->model->{$column->relation}();
                $countQuery = $relationObj->getRelationExistenceQuery($relationObj->getRelated()->newQueryWithoutScopes(), $query);

                $joinSql = $this->isColumnRelated($column, true)
                    ? DbDongle::raw("group_concat(" . $sqlSelect . " separator ', ')")
                    : DbDongle::raw($sqlSelect);

                $joinSql = $countQuery->select($joinSql)->toSql();

                $selects[] = Db::raw("(".$joinSql.") as ".$alias);
            }
            /*
             * Primary column
             */
            else {
                $sqlSelect = $this->parseTableName($column->sqlSelect, $primaryTable);
                $selects[] = DbDongle::raw($sqlSelect . ' as '. $alias);
            }
        }

        /*
         * Apply sorting
         */
        if (($sortColumn = $this->getSortColumn()) && !$this->showTree) {
            if (($column = array_get($this->allColumns, $sortColumn)) && $column->valueFrom) {
                $sortColumn = $this->isColumnPivot($column)
                    ? 'pivot_' . $column->valueFrom
                    : $column->valueFrom;
            }

            // Set the sorting column to $relation_count if useRelationCount enabled
            if (isset($column->relation) && @$column->config['useRelationCount']) {
                $sortColumn = $column->relation . '_count';
            }

            $query->orderBy($sortColumn, $this->sortDirection);
        }

        /*
         * Apply filters
         */
        foreach ($this->filterCallbacks as $callback) {
            $callback($query);
        }

        /*
         * Add custom selects
         */
        $query->addSelect($selects);

        /**
         * @event backend.list.extendQuery
         * Provides an opportunity to modify and / or return the `$query` object after the List widget has applied its scopes to it and before it's used to get the records.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQuery', function($listWidget, $query) {
         *         $newQuery = MyModel::newQuery();
         *         return $newQuery;
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQuery', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        if ($event = $this->fireSystemEvent('backend.list.extendQuery', [$query])) {
            return $event;
        }

        return $query;
    }
1139751
public function prep_request() {
		$curl_handle = curl_init ();
		// Set default options.
		curl_setopt ( $curl_handle, CURLOPT_URL, $this->request_url );
		curl_setopt ( $curl_handle, CURLOPT_FILETIME, true );
		curl_setopt ( $curl_handle, CURLOPT_FRESH_CONNECT, false );
		curl_setopt ( $curl_handle, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt ( $curl_handle, CURLOPT_SSL_VERIFYHOST, true );
		curl_setopt ( $curl_handle, CURLOPT_CLOSEPOLICY, CURLCLOSEPOLICY_LEAST_RECENTLY_USED );
		curl_setopt ( $curl_handle, CURLOPT_MAXREDIRS, 5 );
		curl_setopt ( $curl_handle, CURLOPT_HEADER, true );
		curl_setopt ( $curl_handle, CURLOPT_RETURNTRANSFER, true );
		curl_setopt ( $curl_handle, CURLOPT_TIMEOUT, 5184000 );
		curl_setopt ( $curl_handle, CURLOPT_CONNECTTIMEOUT, 120 );
		curl_setopt ( $curl_handle, CURLOPT_NOSIGNAL, true );
		curl_setopt ( $curl_handle, CURLOPT_REFERER, $this->request_url );
		curl_setopt ( $curl_handle, CURLOPT_USERAGENT, $this->useragent );
		curl_setopt ( $curl_handle, CURLOPT_READFUNCTION, array (
				$this,
				'streaming_read_callback' ) );
		if ($this->debug_mode) {
			curl_setopt ( $curl_handle, CURLOPT_VERBOSE, true );
		}
		//if (! ini_get ( 'safe_mode' )) {
		//modify by zhengkan
		//curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true);
		//}
		// Enable a proxy connection if requested.
		if ($this->proxy) {
			curl_setopt ( $curl_handle, CURLOPT_HTTPPROXYTUNNEL, true );
			$host = $this->proxy ['host'];
			$host .= ($this->proxy ['port']) ? ':' . $this->proxy ['port'] : '';
			curl_setopt ( $curl_handle, CURLOPT_PROXY, $host );
			if (isset ( $this->proxy ['user'] ) && isset ( $this->proxy ['pass'] )) {
				curl_setopt ( $curl_handle, CURLOPT_PROXYUSERPWD, $this->proxy ['user'] . ':' . $this->proxy ['pass'] );
			}
		}
		// Set credentials for HTTP Basic/Digest Authentication.
		if ($this->username && $this->password) {
			curl_setopt ( $curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY );
			curl_setopt ( $curl_handle, CURLOPT_USERPWD, $this->username . ':' . $this->password );
		}
		// Handle the encoding if we can.
		if (extension_loaded ( 'zlib' )) {
			curl_setopt ( $curl_handle, CURLOPT_ENCODING, '' );
		}
		// Process custom headers
		if (isset ( $this->request_headers ) && count ( $this->request_headers )) {
			$temp_headers = array ();
			foreach ( $this->request_headers as $k => $v ) {
				$temp_headers [] = $k . ': ' . $v;
			}
			curl_setopt ( $curl_handle, CURLOPT_HTTPHEADER, $temp_headers );
		}
		switch ($this->method) {
			case self::HTTP_PUT :
				curl_setopt ( $curl_handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
				if (isset ( $this->read_stream )) {
					if (! isset ( $this->read_stream_size ) || $this->read_stream_size < 0) {
						throw new BCS_RequestCore_Exception ( 'The stream size for the streaming upload cannot be determined.' );
					}
					curl_setopt ( $curl_handle, CURLOPT_INFILESIZE, $this->read_stream_size );
					curl_setopt ( $curl_handle, CURLOPT_UPLOAD, true );
				} else {
					curl_setopt ( $curl_handle, CURLOPT_POSTFIELDS, $this->request_body );
				}
				break;
			case self::HTTP_POST :
				curl_setopt ( $curl_handle, CURLOPT_POST, true );
				curl_setopt ( $curl_handle, CURLOPT_POSTFIELDS, $this->request_body );
				break;
			case self::HTTP_HEAD :
				curl_setopt ( $curl_handle, CURLOPT_CUSTOMREQUEST, self::HTTP_HEAD );
				curl_setopt ( $curl_handle, CURLOPT_NOBODY, 1 );
				break;
			default : // Assumed GET
				curl_setopt ( $curl_handle, CURLOPT_CUSTOMREQUEST, $this->method );
				if (isset ( $this->write_stream )) {
					curl_setopt ( $curl_handle, CURLOPT_WRITEFUNCTION, array (
							$this,
							'streaming_write_callback' ) );
					curl_setopt ( $curl_handle, CURLOPT_HEADER, false );
				} else {
					curl_setopt ( $curl_handle, CURLOPT_POSTFIELDS, $this->request_body );
				}
				break;
		}
		// Merge in the CURLOPTs
		if (isset ( $this->curlopts ) && sizeof ( $this->curlopts ) > 0) {
			foreach ( $this->curlopts as $k => $v ) {
				curl_setopt ( $curl_handle, $k, $v );
			}
		}
		return $curl_handle;
	}
1201520
protected function prepare()
    {
        if ($this->bodyRange !== null) {
            return;
        }

        if (isset($this->formatters[$this->format])) {
            $formatter = $this->formatters[$this->format];
            if (!is_object($formatter)) {
                $this->formatters[$this->format] = $formatter = Yii::createObject($formatter);
            }
            if ($formatter instanceof ResponseFormatterInterface) {
                $formatter->format($this);
                return;
            }
            throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
        } elseif ($this->format !== self::FORMAT_RAW) {
            throw new InvalidConfigException("Unsupported response format: {$this->format}");
        }

        if ($this->data !== null) {
            if (is_array($this->data)) {
                throw new InvalidArgumentException('Response raw data must not be an array.');
            } elseif (is_object($this->data)) {
                if (method_exists($this->data, '__toString')) {
                    $content = $this->data->__toString();
                } else {
                    throw new InvalidArgumentException('Response raw data must be a string or an object implementing '
                        . ' __toString().');
                }
            } else {
                $content = $this->data;
            }

            $body = new MemoryStream();
            $body->write($content);
            $this->setBody($body);
        }
    }