Parses and decodes binary image data from data-url

@param  string $data_url
@return string
189640
private function decodeDataUrl($data_url)
    {
        if (!is_string($data_url)) {
            return null;
        }

        $pattern = "/^data:(?:image\/[a-zA-Z\-\.]+)(?:charset=\".+\")?;base64,(?P<data>.+)$/";
        preg_match($pattern, $data_url, $matches);

        if (is_array($matches) && array_key_exists('data', $matches)) {
            return base64_decode($matches['data']);
        }

        return null;
    }
1170282
public function getImageAsString($image_type = null, $quality = null)
    {
        $string_temp = tempnam('', '');
        $this->save($string_temp, $image_type, $quality);
        $string = file_get_contents($string_temp);
        unlink($string_temp);
        
        return $string;
    }
907758
def get_png_data_url(blob: Optional[bytes]) -> str:
    
    return BASE64_PNG_URL_PREFIX + base64.b64encode(blob).decode('ascii')
946934
final public function dataURI($as = null)
	{
		$mime = is_int($as) ? image_type_to_mime_type($as) : $this->_image_mime;
		return 'data:' . $mime . ';base64,' . base64_encode($this->imageAsBinary($as));
	}
611140
@SuppressWarnings("UnusedDeclaration")
    private String createDataURI(final URL imageURL) {
        return imgCache.computeIfAbsent(imageURL, url -> {
            String dataUrl = null;
            try (final InputStream isGuess = url.openStream();
                 final InputStream isConvert = url.openStream();
                 final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                final String contentType = URLConnection.guessContentTypeFromStream(isGuess);
                if (null != contentType) {
                    final byte[] chunk = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = isConvert.read(chunk)) > 0) {
                        os.write(chunk, 0, bytesRead);
                    }
                    os.flush();
                    dataUrl = "data:" + contentType + ";base64," + Base64.getEncoder().encodeToString(os
                            .toByteArray());
                } else {
                    if (logger.isWarnEnabled()) {
                        logger.warn("could not get content type from {}", imageURL.toExternalForm());
                    }
                }
            } catch (final IOException e) {
                if (logger.isWarnEnabled()) {
                    logger.warn("error loading image", e);
                }
            }
            if (null == dataUrl) {
                if (logger.isWarnEnabled()) {
                    logger.warn("could not create data url from {}", imageURL.toExternalForm());
                }
            }
            return dataUrl;
        });
    }
806271
public function get($url, $data) {
        curl_setopt($this->_ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($this->_ch, CURLOPT_URL, sprintf( "%s?%s", $url, http_build_query($data, '', '&', PHP_QUERY_RFC3986)));
        curl_setopt($this->_ch, CURLOPT_HTTPHEADER, array("Accept:application/json", "Content-Type: application/json"));

        return $this->_exec();
    }
655049
protected function parseData()
    {
        if (strtoupper($this->getRequestMethod()) == 'GET') {
            $this->rawData = ($this->getQueryString()) ? rawurldecode($this->getQueryString()) : null;
        } else {
            $input = fopen('php://input', 'r');
            while ($data = fread($input, 1024)) {
                $this->rawData .= $data;
            }
        }

        // If the content-type is JSON
        if ($this->getQueryString() && stripos($this->getQueryString(), 'json') !== false) {
            $this->parsedData = json_decode($this->rawData, true);
        // Else, if the content-type is XML
        } elseif ($this->getContentType() && stripos($this->getContentType(), 'xml') !== false) {
            $matches = [];
            preg_match_all('/<!\[cdata\[(.*?)\]\]>/is', $this->rawData, $matches);

            foreach ($matches[0] as $match) {
                $strip = str_replace(
                    ['<![CDATA[', ']]>', '<', '>'],
                    ['', '', '&lt;', '&gt;'],
                    $match
                );
                $this->rawData = str_replace($match, $strip, $this->rawData);
            }

            $this->parsedData = json_decode(json_encode((array) simplexml_load_string($this->rawData)), true);
        // Else, default to a regular URL-encoded string
        } else {
            switch (strtoupper($this->getRequestMethod())) {
                case 'GET':
                    $this->parsedData = $this->get;
                    break;

                case 'POST':
                    $this->parsedData = $this->post;
                    break;
                default:
                    if ($this->getContentType() && strtolower($this->getContentType()) == 'application/x-www-form-urlencoded') {
                        parse_str($this->rawData, $this->parsedData);
                    }
            }
        }
        switch (strtoupper($this->getRequestMethod())) {
            case 'PUT':
                $this->put = $this->parsedData;
                break;

            case 'PATCH':
                $this->patch = $this->parsedData;
                break;

            case 'DELETE':
                $this->delete = $this->parsedData;
                break;
        }
    }
772015
public static function postRequest($url, $data)
    {
        $url = str_replace("&amp;", "&", urldecode(trim($url)));

        $options = array('http' => array('header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data)));
        $context = stream_context_create($options);

        try {
            $data = @file_get_contents($url, false, $context);
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }
907691
public static function decodeUrlSafe($data) {
		$data = \strtr(
			$data,
			self::LAST_THREE_URL_SAFE,
			self::LAST_THREE_STANDARD
		);

		return self::decode($data);
	}
572222
public function parse($_data)
    {
        $ctrlName = Config::getField('project', 'default_ctrl_name', 'main\\main');
        $methodName = Config::getField('project', 'default_method_name', 'main');
        if (empty($this->_cache)) {
            $this->_cache = ZCache::getInstance('Php');
        }
        $fd = Request::getFd();
        $cacheData = $this->_cache->get($fd);
        if (!empty($cacheData)) {
            $_data = $cacheData . $_data;
            $this->_cache->delete($fd);
        }
        if (empty($_data)) {
            return false;
        }
        $packData = new MessagePacker($_data);
        $packLen = $packData->readInt();
        $dataLen = \strlen($_data);
        if ($packLen > $dataLen) {
            $this->_cache->set($fd, $_data);
            return false;
        } elseif ($packLen < $dataLen) {
            $this->_cache->set($fd, \substr($_data, $packLen, $dataLen - $packLen));
        }
        $packData->resetOffset(4);
        $data = [];
        $data['_cmd'] = $packData->readInt();
        $pathinfo = Config::getField('cmdlist', $data['_cmd']);
        $data['_rid'] = $packData->readInt();
        $params = $packData->readString();
        $unpackData = \json_decode(gzdecode($params), true);
        if (!empty($unpackData) && \is_array($unpackData)) {
            $data += $unpackData;
        }
        $routeMap = ZRoute::match(Config::get('route', false), $pathinfo);
        if (is_array($routeMap)) {
            $ctrlName = $routeMap[0];
            $methodName = $routeMap[1];
            if (!empty($routeMap[2]) && is_array($routeMap[2])) {
                //参数优先
                $data = $data + $routeMap[2];
            }
        }
        Request::init($ctrlName, $methodName, $data, Config::getField('project', 'view_mode', 'Zpack'));
        return true;
    }
916023
protected function mbParseUrl($url)
  {
    $enc_url = preg_replace_callback(
      '%[^:/@?&=#]+%usD',
      function ($matches) {
        return urlencode($matches[0]);
      },
      $url
    );

    if ($parts = parse_url($enc_url)) {
      foreach ($parts as $name => $value) {
        $parts[$name] = urldecode($value);
      }
    }

    return $parts;
  }
331659
public function getNormalizer($data_type)
    {
        if (!isset($this->_normalizers[$data_type])) {
            $message = 'Normalizer not attached for data type: ' . $data_type;
            throw new \InvalidArgumentException($message);
        }
        return $this->_normalizers[$data_type];
    }
752271
public function dataUrl($type = 'jpeg')
    {
        $type      = $this->getType($type);
        $imageFunc = 'image' . $type;

        ob_start();

        $imageFunc($this->newImage);

        $data = ob_get_contents();

        ob_end_clean();

        $this->destroyAll();

        $dataUrl = 'data:image/'. $type . ';base64,' . base64_encode($data);

        return $dataUrl;
    }
120736
public function http_get($url, $data_type='json') {
        
        $cl = curl_init();
        if(stripos($url, 'https://') !== FALSE) {
            curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($cl, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($cl, CURLOPT_URL, $url);
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1 );
        $content = curl_exec($cl);
        $status = curl_getinfo($cl);
        curl_close($cl);
        if (isset($status['http_code']) && $status['http_code'] == 200) {
            if ($data_type == 'json') {
                $content = json_decode($content , true);
            }
            return $content;
        } else {
            return FALSE;
        }
    }
205491
public static function getRawData($data_str)
    {
        if (is_string($data_str) && ($data_str=="''" || $data_str=='""')) {
            $data = '';
        } else {
            $data = $data_str;
        }

        if (!empty($data) && ($data{0} == '{' || $data{0} == '[')) {
            try {
                $data = self::json_decode($data);
            } catch (\Exception $e) {
                throw $e;
            }
        }

        return $data;
    }
426952
public function getDataMember( $dataMember )
    {
        if( $dataMember === 'related_images' )
        {
            $images = array();
            $relations = $this->ContentObjectAttribute->attribute( 'content' );
            foreach ( $relations['relation_list'] as $relation )
            {
                $object = eZContentObject::fetch( $relation['contentobject_id'] );
                if( $object instanceof eZContentObject )
                {
                    $dataMap = $object->attribute( 'data_map' );
                    foreach ( $dataMap as $attribute )
                    {
                        /** @var eZContentObjectAttribute $attribute */
                        if ( $attribute->attribute( 'data_type_string' ) !== eZImageType::DATA_TYPE_STRING )
                        {
                            continue;
                        }

                        if ( $attribute->hasContent() )
                        {
                            $imageAliasHandler = $attribute->attribute( 'content' );
                            $imageAlias = $imageAliasHandler->imageAlias( 'opengraph' );
                            if( $imageAlias['is_valid'] == 1 )
                            {
                                $images[] = eZSys::serverURL() . '/' . $imageAlias['full_path'];
                            }
                        }
                    }
                }
            }

            if ( empty( $images ) )
            {
                $images[] = eZSys::serverURL() . eZURLOperator::eZImage( null, 'opengraph_default_image.png', '' );
            }

            return $images;
        }

        return $this->getData();
    }
1229616
public static function parseUrl($url)
	{
		$result = false;

		// Build arrays of values we need to decode before parsing
		$entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%24', '%2C', '%2F', '%3F', '%23', '%5B', '%5D');
		$replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "$", ",", "/", "?", "#", "[", "]");

		// Create encoded URL with special URL characters decoded so it can be parsed
		// All other characters will be encoded
		$encodedURL = str_replace($entities, $replacements, urlencode($url));

		// Parse the encoded URL
		$encodedParts = parse_url($encodedURL);

		// Now, decode each value of the resulting array
		if ($encodedParts)
		{
			foreach ($encodedParts as $key => $value)
			{
				$result[$key] = urldecode(str_replace($replacements, $entities, $value));
			}
		}

		return $result;
	}