sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function optimizeDirs() { $this->optimizedDirs = []; foreach ($this->dirs as $pathname) { $pathname = \BearFramework\Internal\Utilities::normalizePath($pathname); if (substr($pathname, -3) !== '://') { $pathname = rtrim($pathname, '/') . '/'; } $this->optimizedDirs[$pathname] = strlen($pathname); } arsort($this->optimizedDirs); $this->optimizedDirs = array_keys($this->optimizedDirs); }
Must be called before using $this->optimizedDirs
entailment
public function getURL(string $filename, array $options = []): string { $filename = \BearFramework\Internal\Utilities::normalizePath($filename); $url = null; if ($this->hasEventListeners('beforeGetURL')) { $eventDetails = new \BearFramework\App\Assets\BeforeGetURLEventDetails($filename, $options); $this->dispatchEvent('beforeGetURL', $eventDetails); $filename = $eventDetails->filename; $options = $eventDetails->options; if ($eventDetails->returnValue !== null) { $url = $eventDetails->returnValue; } } if ($url === null) { if (isset($options['version'])) { $options['version'] = substr(md5(md5($filename) . $options['version']), 0, 10); } if (!empty($options)) { $this->validateOptions($options); } if (strpos($filename, '://') !== false) { $temp = explode('://', $filename); $pathInfo = pathinfo($temp[1]); $fileDir = $temp[0] . '://' . ($pathInfo['dirname'] !== '.' ? $pathInfo['dirname'] . '/' : ''); $fileBasename = $pathInfo['basename']; } else { $pathInfo = pathinfo($filename); $fileDir = $pathInfo['dirname'] . '/'; $fileBasename = $pathInfo['basename']; } $optionsString = ''; if (isset($options['width'])) { $optionsString .= '-w' . $options['width']; } if (isset($options['height'])) { $optionsString .= '-h' . $options['height']; } if (isset($options['cacheMaxAge'])) { $optionsString .= '-c' . $options['cacheMaxAge']; } if (isset($options['version'])) { $optionsString .= '-v' . $options['version']; } if (isset($options['robotsNoIndex']) && $options['robotsNoIndex'] === true) { $optionsString .= '-r1'; } if (isset($options['download']) && $options['download'] === true) { $optionsString .= '-d'; } if (isset($options['outputType']) && isset($pathInfo['extension'])) { $optionsString .= '-o' . $pathInfo['extension']; $fileBasename = substr($fileBasename, 0, -strlen($pathInfo['extension'])) . $options['outputType']; } $hash = substr(md5(md5($filename) . md5($optionsString)), 0, 12); $fileDirCacheKey = '1' . $fileDir; if (!isset($this->cache[$fileDirCacheKey])) { $this->cache[$fileDirCacheKey] = false; if ($this->optimizedDirs === null) { $this->optimizeDirs(); } foreach ($this->optimizedDirs as $dir) { if (strpos($fileDir, $dir) === 0) { $this->cache[$fileDirCacheKey] = '/' . substr($fileDir, strlen($dir)); break; } } } $url = $this->cache[$fileDirCacheKey] === false ? null : $this->app->urls->get($this->internalPathPrefix . $hash . $optionsString . $this->cache[$fileDirCacheKey] . $fileBasename); } if ($this->hasEventListeners('getURL')) { $eventDetails = new \BearFramework\App\Assets\GetURLEventDetails($filename, $options, $url); $this->dispatchEvent('getURL', $eventDetails); $url = $eventDetails->url; } if ($url !== null) { return $url; } throw new \InvalidArgumentException('The filename specified (' . $filename . ') is located in a dir that is not added'); }
Returns a public URL for the specified filename. @param string $filename The filename. @param array $options URL options. You can resize the file by providing "width", "height" or both. @throws \InvalidArgumentException @return string The URL for the specified filename and options.
entailment
public function getContent(string $filename, array $options = []): ?string { if (!empty($options)) { $this->validateOptions($options); } $urlOptions = []; if (isset($options['width'])) { $urlOptions['width'] = $options['width']; } if (isset($options['height'])) { $urlOptions['height'] = $options['height']; } if (isset($options['outputType'])) { $urlOptions['outputType'] = $options['outputType']; } $url = $this->getURL($filename, $urlOptions); $path = substr($url, strlen($this->app->request->base)); $request = new \BearFramework\App\Request(); $request->path->set($path); $response = $this->getResponse($request); if ($response === null) { return null; } $content = file_get_contents($response->filename); if (isset($options['encoding'])) { if ($options['encoding'] === 'base64') { return base64_encode($content); } elseif ($options['encoding'] === 'data-uri') { $mimeType = $this->getMimeType($filename); return 'data:' . $mimeType . ',' . $content; } elseif ($options['encoding'] === 'data-uri-base64') { $mimeType = $this->getMimeType($filename); return 'data:' . $mimeType . ';base64,' . base64_encode($content); } else { throw new \InvalidArgumentException('Unsupported encoding type (' . $options['encoding'] . ')'); } } return $content; }
Returns the content of the file specified. @param string $filename The filename. @param array $options List of options. You can resize the file by providing "width", "height" or both. You can specify encoding too (base64, data-uri, data-uri-base64). @throws \InvalidArgumentException @return string|null The content of the file or null if file does not exists.
entailment
public function getResponse(\BearFramework\App\Request $request): ?\BearFramework\App\Response { $parsePath = function($path) { if (strpos($path, $this->internalPathPrefix) !== 0) { return null; } $path = substr($path, strlen($this->internalPathPrefix)); $partParts = explode('/', $path, 2); if (sizeof($partParts) !== 2) { return null; } $result = [ 'filename' => null, 'options' => [] ]; $hash = substr($partParts[0], 0, 12); $optionsString = (string) substr($partParts[0], 12); $path = $partParts[1]; if ($optionsString !== '') { $options = explode('-', trim($optionsString, '-')); foreach ($options as $option) { if (substr($option, 0, 1) === 'w') { $value = (int) substr($option, 1); if ($value >= 1 && $value <= 100000) { $result['options']['width'] = $value; } } if (substr($option, 0, 1) === 'h') { $value = (int) substr($option, 1); if ($value >= 1 && $value <= 100000) { $result['options']['height'] = $value; } } if (substr($option, 0, 1) === 'c') { $value = (int) substr($option, 1); if ($value >= 0) { $result['options']['cacheMaxAge'] = $value; } } if (substr($option, 0, 2) === 'r1') { $result['options']['robotsNoIndex'] = true; } if (substr($option, 0, 1) === 'd') { $result['options']['download'] = true; } if (substr($option, 0, 1) === 'o') { $value = substr($option, 1); $pathExtension = pathinfo($path, PATHINFO_EXTENSION); $path = substr($path, 0, -strlen($pathExtension)) . $value; $result['options']['outputType'] = $pathExtension; } } } if ($this->optimizedDirs === null) { $this->optimizeDirs(); } foreach ($this->optimizedDirs as $dir) { if ($hash === substr(md5(md5($dir . $path) . md5($optionsString)), 0, 12)) { $result['filename'] = $dir . $path; return $result; } } return null; }; $pathData = $parsePath((string) $request->path); if ($pathData === null) { return null; } else { $filename = $pathData['filename']; $options = $pathData['options']; $this->validateOptions($options); $filename = $this->prepare($filename, $options); if ($filename === null || !is_file($filename)) { return null; } $response = new App\Response\FileReader($filename); if (isset($options['cacheMaxAge'])) { $response->headers->set($response->headers->make('Cache-Control', 'public, max-age=' . $options['cacheMaxAge'])); } if (isset($options['robotsNoIndex'])) { $response->headers->set($response->headers->make('X-Robots-Tag', 'noindex')); } if (isset($options['download'])) { $response->headers->set($response->headers->make('Content-Disposition', 'attachment; filename=' . pathinfo($filename, PATHINFO_BASENAME))); } $mimeType = $this->getMimeType($filename); if ($mimeType !== null) { $response->headers->set($response->headers->make('Content-Type', $mimeType)); } $response->headers->set($response->headers->make('Content-Length', (string) filesize($filename))); return $response; } }
Creates a response object for the asset request. @param \BearFramework\App\Request $request The request object to match against. @return \BearFramework\App\Response|null The response object for the request specified.
entailment
private function prepare(string $filename, array $options = []): ?string { if (!empty($options)) { $this->validateOptions($options); } $result = null; if ($this->hasEventListeners('beforePrepare')) { $eventDetails = new \BearFramework\App\Assets\BeforePrepareEventDetails($filename, $options); $this->dispatchEvent('beforePrepare', $eventDetails); $filename = $eventDetails->filename; $options = $eventDetails->options; } if (strlen($filename) > 0 && is_file($filename)) { if (!isset($options['width']) && !isset($options['height'])) { $result = $filename; } else { $extension = pathinfo($filename, PATHINFO_EXTENSION); if ($extension === '') { $extension = 'tmp'; } if (isset($options['outputType'])) { $extension = $options['outputType']; } $tempFilename = $this->app->data->getFilename('.temp/assets/' . md5(md5($filename) . md5(json_encode($options))) . '.' . $extension); if (!is_file($tempFilename)) { $this->resize($filename, $tempFilename, [ 'width' => (isset($options['width']) ? $options['width'] : null), 'height' => (isset($options['height']) ? $options['height'] : null) ]); } $result = $tempFilename; } } if ($this->hasEventListeners('prepare')) { $eventDetails = new \BearFramework\App\Assets\PrepareEventDetails($filename, $options, $result); $this->dispatchEvent('prepare', $eventDetails); $result = $eventDetails->returnValue; } return $result; }
Prepares a local filename that will be returned for the file requested. @param string $filename The filename to prepare. @param array $options A list of options for the filename. @return string|null The local filename of the prepared file or null.
entailment
public function getDetails(string $filename, array $list): array { $result = null; if ($this->hasEventListeners('beforeGetDetails')) { $eventDetails = new \BearFramework\App\Assets\BeforeGetDetailsEventDetails($filename, $list); $this->dispatchEvent('beforeGetDetails', $eventDetails); $filename = $eventDetails->filename; $list = $eventDetails->list; if ($eventDetails->returnValue !== null) { $result = $eventDetails->returnValue; } } if ($result === null) { $result = []; $temp = array_flip($list); if (isset($temp['mimeType'])) { $result['mimeType'] = $this->getMimeType($filename); } if (isset($temp['width']) || isset($temp['height']) || isset($temp['size'])) { $fileExists = is_file($filename); } if (isset($temp['width']) || isset($temp['height'])) { if ($fileExists) { $imageSize = $this->getImageSize($filename); } if (isset($temp['width'])) { $result['width'] = $fileExists ? $imageSize[0] : null; } if (isset($temp['height'])) { $result['height'] = $fileExists ? $imageSize[1] : null; } } if (isset($temp['size'])) { $result['size'] = $fileExists ? filesize($filename) : null; } } if ($this->hasEventListeners('getDetails')) { $eventDetails = new \BearFramework\App\Assets\GetDetailsEventDetails($filename, $list, $result); $this->dispatchEvent('getDetails', $eventDetails); $result = $eventDetails->returnValue; } return $result; }
Returns a list of details for the filename specified. @param string $filename The filename of the asset. @param array $list A list of details to return. Available values: mimeType, size, width, height. @return array A list of tails for the filename specified.
entailment
private function getImageSize(string $filename): array { $result = [null, null]; try { $size = getimagesize($filename); if (is_array($size)) { $result = [(int) $size[0], (int) $size[1]]; } elseif (pathinfo($filename, PATHINFO_EXTENSION) === 'webp' && function_exists('imagecreatefromwebp')) { $sourceImage = imagecreatefromwebp($filename); $result = [(int) imagesx($sourceImage), (int) imagesy($sourceImage)]; imagedestroy($sourceImage); } } catch (\Exception $e) { } return $result; }
Returns the size (if available) of the asset specified. @param string $filename The filename of the asset. @return array[int|null,int|null] The size of the asset specified.
entailment
private function resize(string $sourceFilename, string $destinationFilename, array $options = []): void { if (!is_file($sourceFilename)) { throw new \InvalidArgumentException('The sourceFilename specified does not exist (' . $sourceFilename . ')'); } if (isset($options['width']) && (!is_int($options['width']) || $options['width'] < 1 || $options['width'] > 100000)) { throw new \InvalidArgumentException('The width value must be higher than 0 and lower than 100001'); } if (isset($options['height']) && (!is_int($options['height']) || $options['height'] < 1 || $options['height'] > 100000)) { throw new \InvalidArgumentException('The height value must be higher than 0 and lower than 100001'); } $outputType = null; $sourcePathInfo = pathinfo($sourceFilename); $destinationPathInfo = pathinfo($destinationFilename); if (isset($destinationPathInfo['extension'])) { $extension = strtolower($destinationPathInfo['extension']); if ($extension === 'png') { $outputType = 'png'; } elseif ($extension === 'gif') { $outputType = 'gif'; } elseif ($extension === 'jpg' || $extension === 'jpeg') { $outputType = 'jpg'; } elseif ($extension === 'webp') { $outputType = 'webp'; } } if ($outputType !== 'png' && $outputType !== 'gif' && $outputType !== 'jpg' && $outputType !== 'webp') { throw new \InvalidArgumentException('The output format is not supported!'); } try { if (isset($sourcePathInfo['extension']) && strtolower($sourcePathInfo['extension']) === 'webp') { $sourceSize = $this->getImageSize($sourceFilename); $sourceWidth = $sourceSize[0]; $sourceHeight = $sourceSize[1]; $sourceMimeType = 'image/webp'; } else { $sourceImageInfo = getimagesize($sourceFilename); if (!is_array($sourceImageInfo)) { throw new \InvalidArgumentException('Cannot get source asset size of ' . $sourceFilename . '!'); } $sourceWidth = $sourceImageInfo[0]; $sourceHeight = $sourceImageInfo[1]; $sourceMimeType = $sourceImageInfo['mime']; } } catch (\Exception $e) { throw new \InvalidArgumentException('Unknown error (' . $e->getMessage() . ')'); } $width = isset($options['width']) ? $options['width'] : null; $height = isset($options['height']) ? $options['height'] : null; if ($width === null && $height === null) { $width = $sourceWidth; $height = $sourceHeight; } elseif ($width === null && $height !== null) { $width = (int) floor($sourceWidth / $sourceHeight * $height); } elseif ($height === null && $width !== null) { $height = (int) floor($sourceHeight / $sourceWidth * $width); } if ($width === 0) { $width = 1; } if ($height === 0) { $height = 1; } if ($sourceWidth === $width && $sourceHeight === $height) { copy($sourceFilename, $destinationFilename); } else { $sourceImage = null; if ($sourceMimeType === 'image/jpeg' && function_exists('imagecreatefromjpeg')) { $sourceImage = imagecreatefromjpeg($sourceFilename); } elseif ($sourceMimeType === 'image/png' && function_exists('imagecreatefrompng')) { $sourceImage = imagecreatefrompng($sourceFilename); } elseif ($sourceMimeType === 'image/gif' && function_exists('imagecreatefromgif')) { $sourceImage = imagecreatefromgif($sourceFilename); } elseif ($sourceMimeType === 'image/webp' && function_exists('imagecreatefromwebp')) { $sourceImage = imagecreatefromwebp($sourceFilename); } if (!$sourceImage) { throw new \InvalidArgumentException('Cannot read the source image (' . $sourceFilename . ')'); } $result = false; try { $resultImage = imagecreatetruecolor($width, $height); imagealphablending($resultImage, false); imagesavealpha($resultImage, true); imagefill($resultImage, 0, 0, imagecolorallocatealpha($resultImage, 0, 0, 0, 127)); $widthRatio = $sourceWidth / $width; $heightRatio = $sourceHeight / $height; $resizedImageHeight = $height; $resizedImageWidth = $width; if ($widthRatio > $heightRatio) { $resizedImageWidth = ceil($sourceWidth / $heightRatio); } else { $resizedImageHeight = ceil($sourceHeight / $widthRatio); } $destinationX = - ($resizedImageWidth - $width) / 2; $destinationY = - ($resizedImageHeight - $height) / 2; $tempFilename = $this->app->data->getFilename('.temp/assets/resize' . uniqid()); if (imagecopyresampled($resultImage, $sourceImage, floor($destinationX), floor($destinationY), 0, 0, $resizedImageWidth, $resizedImageHeight, $sourceWidth, $sourceHeight)) { if ($outputType === 'jpg') { $result = imagejpeg($resultImage, $tempFilename, 100); } elseif ($outputType === 'png') { $result = imagepng($resultImage, $tempFilename, 9); } elseif ($outputType === 'gif') { $result = imagegif($resultImage, $tempFilename); } elseif ($outputType === 'webp') { $result = imagewebp($resultImage, $tempFilename, 100); } } imagedestroy($resultImage); } catch (\Exception $e) { } imagedestroy($sourceImage); if ($result) { $e = null; try { copy($tempFilename, $destinationFilename); } catch (\Exception $e) { } unlink($tempFilename); if ($e !== null) { throw $e; } } else { throw new \Exception('Cannot save resized asset (' . $destinationFilename . ')'); } } }
Resizes an asset file. @param string $sourceFilename The asset file to resize. @param string $destinationFilename The filename where the result asset will be saved. @param array $options Resize options. You can resize the file by providing "width", "height" or both. @throws \InvalidArgumentException @throws \Exception @return void No value is returned.
entailment
private function getMimeType(string $filename) { $pathinfo = pathinfo($filename); if (isset($pathinfo['extension'])) { $extension = strtolower($pathinfo['extension']); $mimeTypes = array( '3dml' => 'text/vnd.in3d.3dml', '3ds' => 'image/x-3ds', '3g2' => 'video/3gpp2', '3gp' => 'video/3gpp', '7z' => 'application/x-7z-compressed', 'aab' => 'application/x-authorware-bin', 'aac' => 'audio/x-aac', 'aam' => 'application/x-authorware-map', 'aas' => 'application/x-authorware-seg', 'abw' => 'application/x-abiword', 'ac' => 'application/pkix-attr-cert', 'acc' => 'application/vnd.americandynamics.acc', 'ace' => 'application/x-ace-compressed', 'acu' => 'application/vnd.acucobol', 'acutc' => 'application/vnd.acucorp', 'adp' => 'audio/adpcm', 'aep' => 'application/vnd.audiograph', 'afm' => 'application/x-font-type1', 'afp' => 'application/vnd.ibm.modcap', 'ahead' => 'application/vnd.ahead.space', 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'air' => 'application/vnd.adobe.air-application-installer-package+zip', 'ait' => 'application/vnd.dvb.ait', 'ami' => 'application/vnd.amiga.ami', 'apk' => 'application/vnd.android.package-archive', 'appcache' => 'text/cache-manifest', 'application' => 'application/x-ms-application', 'apr' => 'application/vnd.lotus-approach', 'arc' => 'application/x-freearc', 'asa' => 'text/plain', 'asax' => 'application/octet-stream', 'asc' => 'application/pgp-signature', 'ascx' => 'text/plain', 'asf' => 'video/x-ms-asf', 'ashx' => 'text/plain', 'asm' => 'text/x-asm', 'asmx' => 'text/plain', 'aso' => 'application/vnd.accpac.simply.aso', 'asp' => 'text/plain', 'aspx' => 'text/plain', 'asx' => 'video/x-ms-asf', 'atc' => 'application/vnd.acucorp', 'atom' => 'application/atom+xml', 'atomcat' => 'application/atomcat+xml', 'atomsvc' => 'application/atomsvc+xml', 'atx' => 'application/vnd.antix.game-component', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'aw' => 'application/applixware', 'axd' => 'text/plain', 'azf' => 'application/vnd.airzip.filesecure.azf', 'azs' => 'application/vnd.airzip.filesecure.azs', 'azw' => 'application/vnd.amazon.ebook', 'bat' => 'application/x-msdownload', 'bcpio' => 'application/x-bcpio', 'bdf' => 'application/x-font-bdf', 'bdm' => 'application/vnd.syncml.dm+wbxml', 'bed' => 'application/vnd.realvnc.bed', 'bh2' => 'application/vnd.fujitsu.oasysprs', 'bin' => 'application/octet-stream', 'blb' => 'application/x-blorb', 'blorb' => 'application/x-blorb', 'bmi' => 'application/vnd.bmi', 'bmp' => 'image/bmp', 'book' => 'application/vnd.framemaker', 'box' => 'application/vnd.previewsystems.box', 'boz' => 'application/x-bzip2', 'bpk' => 'application/octet-stream', 'btif' => 'image/prs.btif', 'bz' => 'application/x-bzip', 'bz2' => 'application/x-bzip2', 'c' => 'text/x-c', 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', 'c4d' => 'application/vnd.clonk.c4group', 'c4f' => 'application/vnd.clonk.c4group', 'c4g' => 'application/vnd.clonk.c4group', 'c4p' => 'application/vnd.clonk.c4group', 'c4u' => 'application/vnd.clonk.c4group', 'cab' => 'application/vnd.ms-cab-compressed', 'caf' => 'audio/x-caf', 'cap' => 'application/vnd.tcpdump.pcap', 'car' => 'application/vnd.curl.car', 'cat' => 'application/vnd.ms-pki.seccat', 'cb7' => 'application/x-cbr', 'cba' => 'application/x-cbr', 'cbr' => 'application/x-cbr', 'cbt' => 'application/x-cbr', 'cbz' => 'application/x-cbr', 'cc' => 'text/x-c', 'cct' => 'application/x-director', 'ccxml' => 'application/ccxml+xml', 'cdbcmsg' => 'application/vnd.contact.cmsg', 'cdf' => 'application/x-netcdf', 'cdkey' => 'application/vnd.mediastation.cdkey', 'cdmia' => 'application/cdmi-capability', 'cdmic' => 'application/cdmi-container', 'cdmid' => 'application/cdmi-domain', 'cdmio' => 'application/cdmi-object', 'cdmiq' => 'application/cdmi-queue', 'cdx' => 'chemical/x-cdx', 'cdxml' => 'application/vnd.chemdraw+xml', 'cdy' => 'application/vnd.cinderella', 'cer' => 'application/pkix-cert', 'cfc' => 'application/x-coldfusion', 'cfm' => 'application/x-coldfusion', 'cfs' => 'application/x-cfs-compressed', 'cgm' => 'image/cgm', 'chat' => 'application/x-chat', 'chm' => 'application/vnd.ms-htmlhelp', 'chrt' => 'application/vnd.kde.kchart', 'cif' => 'chemical/x-cif', 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', 'cil' => 'application/vnd.ms-artgalry', 'cla' => 'application/vnd.claymore', 'class' => 'application/java-vm', 'clkk' => 'application/vnd.crick.clicker.keyboard', 'clkp' => 'application/vnd.crick.clicker.palette', 'clkt' => 'application/vnd.crick.clicker.template', 'clkw' => 'application/vnd.crick.clicker.wordbank', 'clkx' => 'application/vnd.crick.clicker', 'clp' => 'application/x-msclip', 'cmc' => 'application/vnd.cosmocaller', 'cmdf' => 'chemical/x-cmdf', 'cml' => 'chemical/x-cml', 'cmp' => 'application/vnd.yellowriver-custom-menu', 'cmx' => 'image/x-cmx', 'cod' => 'application/vnd.rim.cod', 'com' => 'application/x-msdownload', 'conf' => 'text/plain', 'cpio' => 'application/x-cpio', 'cpp' => 'text/x-c', 'cpt' => 'application/mac-compactpro', 'crd' => 'application/x-mscardfile', 'crl' => 'application/pkix-crl', 'crt' => 'application/x-x509-ca-cert', 'crx' => 'application/octet-stream', 'cryptonote' => 'application/vnd.rig.cryptonote', 'cs' => 'text/plain', 'csh' => 'application/x-csh', 'csml' => 'chemical/x-csml', 'csp' => 'application/vnd.commonspace', 'css' => 'text/css', 'cst' => 'application/x-director', 'csv' => 'text/csv', 'cu' => 'application/cu-seeme', 'curl' => 'text/vnd.curl', 'cww' => 'application/prs.cww', 'cxt' => 'application/x-director', 'cxx' => 'text/x-c', 'dae' => 'model/vnd.collada+xml', 'daf' => 'application/vnd.mobius.daf', 'dart' => 'application/vnd.dart', 'dataless' => 'application/vnd.fdsn.seed', 'davmount' => 'application/davmount+xml', 'dbk' => 'application/docbook+xml', 'dcr' => 'application/x-director', 'dcurl' => 'text/vnd.curl.dcurl', 'dd2' => 'application/vnd.oma.dd2+xml', 'ddd' => 'application/vnd.fujixerox.ddd', 'deb' => 'application/x-debian-package', 'def' => 'text/plain', 'deploy' => 'application/octet-stream', 'der' => 'application/x-x509-ca-cert', 'dfac' => 'application/vnd.dreamfactory', 'dgc' => 'application/x-dgc-compressed', 'dic' => 'text/x-c', 'dir' => 'application/x-director', 'dis' => 'application/vnd.mobius.dis', 'dist' => 'application/octet-stream', 'distz' => 'application/octet-stream', 'djv' => 'image/vnd.djvu', 'djvu' => 'image/vnd.djvu', 'dll' => 'application/x-msdownload', 'dmg' => 'application/x-apple-diskimage', 'dmp' => 'application/vnd.tcpdump.pcap', 'dms' => 'application/octet-stream', 'dna' => 'application/vnd.dna', 'doc' => 'application/msword', 'docm' => 'application/vnd.ms-word.document.macroenabled.12', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dot' => 'application/msword', 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'dp' => 'application/vnd.osgi.dp', 'dpg' => 'application/vnd.dpgraph', 'dra' => 'audio/vnd.dra', 'dsc' => 'text/prs.lines.tag', 'dssc' => 'application/dssc+der', 'dtb' => 'application/x-dtbook+xml', 'dtd' => 'application/xml-dtd', 'dts' => 'audio/vnd.dts', 'dtshd' => 'audio/vnd.dts.hd', 'dump' => 'application/octet-stream', 'dvb' => 'video/vnd.dvb.file', 'dvi' => 'application/x-dvi', 'dwf' => 'model/vnd.dwf', 'dwg' => 'image/vnd.dwg', 'dxf' => 'image/vnd.dxf', 'dxp' => 'application/vnd.spotfire.dxp', 'dxr' => 'application/x-director', 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', 'ecma' => 'application/ecmascript', 'edm' => 'application/vnd.novadigm.edm', 'edx' => 'application/vnd.novadigm.edx', 'efif' => 'application/vnd.picsel', 'ei6' => 'application/vnd.pg.osasli', 'elc' => 'application/octet-stream', 'emf' => 'application/x-msmetafile', 'eml' => 'message/rfc822', 'emma' => 'application/emma+xml', 'emz' => 'application/x-msmetafile', 'eol' => 'audio/vnd.digital-winds', 'eot' => 'application/vnd.ms-fontobject', 'eps' => 'application/postscript', 'epub' => 'application/epub+zip', 'es3' => 'application/vnd.eszigno3+xml', 'esa' => 'application/vnd.osgi.subsystem', 'esf' => 'application/vnd.epson.esf', 'et3' => 'application/vnd.eszigno3+xml', 'etx' => 'text/x-setext', 'eva' => 'application/x-eva', 'evy' => 'application/x-envoy', 'exe' => 'application/x-msdownload', 'exi' => 'application/exi', 'ext' => 'application/vnd.novadigm.ext', 'ez' => 'application/andrew-inset', 'ez2' => 'application/vnd.ezpix-album', 'ez3' => 'application/vnd.ezpix-package', 'f' => 'text/x-fortran', 'f4v' => 'video/x-f4v', 'f77' => 'text/x-fortran', 'f90' => 'text/x-fortran', 'fbs' => 'image/vnd.fastbidsheet', 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', 'fcs' => 'application/vnd.isac.fcs', 'fdf' => 'application/vnd.fdf', 'fe_launch' => 'application/vnd.denovo.fcselayout-link', 'fg5' => 'application/vnd.fujitsu.oasysgp', 'fgd' => 'application/x-director', 'fh' => 'image/x-freehand', 'fh4' => 'image/x-freehand', 'fh5' => 'image/x-freehand', 'fh7' => 'image/x-freehand', 'fhc' => 'image/x-freehand', 'fig' => 'application/x-xfig', 'flac' => 'audio/x-flac', 'fli' => 'video/x-fli', 'flo' => 'application/vnd.micrografx.flo', 'flv' => 'video/x-flv', 'flw' => 'application/vnd.kde.kivio', 'flx' => 'text/vnd.fmi.flexstor', 'fly' => 'text/vnd.fly', 'fm' => 'application/vnd.framemaker', 'fnc' => 'application/vnd.frogans.fnc', 'for' => 'text/x-fortran', 'fpx' => 'image/vnd.fpx', 'frame' => 'application/vnd.framemaker', 'fsc' => 'application/vnd.fsc.weblaunch', 'fst' => 'image/vnd.fst', 'ftc' => 'application/vnd.fluxtime.clip', 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', 'fvt' => 'video/vnd.fvt', 'fxp' => 'application/vnd.adobe.fxp', 'fxpl' => 'application/vnd.adobe.fxp', 'fzs' => 'application/vnd.fuzzysheet', 'g2w' => 'application/vnd.geoplan', 'g3' => 'image/g3fax', 'g3w' => 'application/vnd.geospace', 'gac' => 'application/vnd.groove-account', 'gam' => 'application/x-tads', 'gbr' => 'application/rpki-ghostbusters', 'gca' => 'application/x-gca-compressed', 'gdl' => 'model/vnd.gdl', 'geo' => 'application/vnd.dynageo', 'gex' => 'application/vnd.geometry-explorer', 'ggb' => 'application/vnd.geogebra.file', 'ggt' => 'application/vnd.geogebra.tool', 'ghf' => 'application/vnd.groove-help', 'gif' => 'image/gif', 'gim' => 'application/vnd.groove-identity-message', 'gml' => 'application/gml+xml', 'gmx' => 'application/vnd.gmx', 'gnumeric' => 'application/x-gnumeric', 'gph' => 'application/vnd.flographit', 'gpx' => 'application/gpx+xml', 'gqf' => 'application/vnd.grafeq', 'gqs' => 'application/vnd.grafeq', 'gram' => 'application/srgs', 'gramps' => 'application/x-gramps-xml', 'gre' => 'application/vnd.geometry-explorer', 'grv' => 'application/vnd.groove-injector', 'grxml' => 'application/srgs+xml', 'gsf' => 'application/x-font-ghostscript', 'gtar' => 'application/x-gtar', 'gtm' => 'application/vnd.groove-tool-message', 'gtw' => 'model/vnd.gtw', 'gv' => 'text/vnd.graphviz', 'gxf' => 'application/gxf', 'gxt' => 'application/vnd.geonext', 'gz' => 'application/x-gzip', 'h' => 'text/x-c', 'h261' => 'video/h261', 'h263' => 'video/h263', 'h264' => 'video/h264', 'hal' => 'application/vnd.hal+xml', 'hbci' => 'application/vnd.hbci', 'hdf' => 'application/x-hdf', 'hh' => 'text/x-c', 'hlp' => 'application/winhlp', 'hpgl' => 'application/vnd.hp-hpgl', 'hpid' => 'application/vnd.hp-hpid', 'hps' => 'application/vnd.hp-hps', 'hqx' => 'application/mac-binhex40', 'hta' => 'application/octet-stream', 'htc' => 'text/html', 'htke' => 'application/vnd.kenameaapp', 'htm' => 'text/html', 'html' => 'text/html', 'hvd' => 'application/vnd.yamaha.hv-dic', 'hvp' => 'application/vnd.yamaha.hv-voice', 'hvs' => 'application/vnd.yamaha.hv-script', 'i2g' => 'application/vnd.intergeo', 'icc' => 'application/vnd.iccprofile', 'ice' => 'x-conference/x-cooltalk', 'icm' => 'application/vnd.iccprofile', 'ico' => 'image/x-icon', 'ics' => 'text/calendar', 'ief' => 'image/ief', 'ifb' => 'text/calendar', 'ifm' => 'application/vnd.shana.informed.formdata', 'iges' => 'model/iges', 'igl' => 'application/vnd.igloader', 'igm' => 'application/vnd.insors.igm', 'igs' => 'model/iges', 'igx' => 'application/vnd.micrografx.igx', 'iif' => 'application/vnd.shana.informed.interchange', 'imp' => 'application/vnd.accpac.simply.imp', 'ims' => 'application/vnd.ms-ims', 'in' => 'text/plain', 'ini' => 'text/plain', 'ink' => 'application/inkml+xml', 'inkml' => 'application/inkml+xml', 'install' => 'application/x-install-instructions', 'iota' => 'application/vnd.astraea-software.iota', 'ipa' => 'application/octet-stream', 'ipfix' => 'application/ipfix', 'ipk' => 'application/vnd.shana.informed.package', 'irm' => 'application/vnd.ibm.rights-management', 'irp' => 'application/vnd.irepository.package+xml', 'iso' => 'application/x-iso9660-image', 'itp' => 'application/vnd.shana.informed.formtemplate', 'ivp' => 'application/vnd.immervision-ivp', 'ivu' => 'application/vnd.immervision-ivu', 'jad' => 'text/vnd.sun.j2me.app-descriptor', 'jam' => 'application/vnd.jam', 'jar' => 'application/java-archive', 'java' => 'text/x-java-source', 'jisp' => 'application/vnd.jisp', 'jlt' => 'application/vnd.hp-jlyt', 'jnlp' => 'application/x-java-jnlp-file', 'joda' => 'application/vnd.joost.joda-archive', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpgm' => 'video/jpm', 'jpgv' => 'video/jpeg', 'jpm' => 'video/jpm', 'js' => 'text/javascript', 'json' => 'application/json', 'jsonml' => 'application/jsonml+json', 'kar' => 'audio/midi', 'karbon' => 'application/vnd.kde.karbon', 'kfo' => 'application/vnd.kde.kformula', 'kia' => 'application/vnd.kidspiration', 'kml' => 'application/vnd.google-earth.kml+xml', 'kmz' => 'application/vnd.google-earth.kmz', 'kne' => 'application/vnd.kinar', 'knp' => 'application/vnd.kinar', 'kon' => 'application/vnd.kde.kontour', 'kpr' => 'application/vnd.kde.kpresenter', 'kpt' => 'application/vnd.kde.kpresenter', 'kpxx' => 'application/vnd.ds-keypoint', 'ksp' => 'application/vnd.kde.kspread', 'ktr' => 'application/vnd.kahootz', 'ktx' => 'image/ktx', 'ktz' => 'application/vnd.kahootz', 'kwd' => 'application/vnd.kde.kword', 'kwt' => 'application/vnd.kde.kword', 'lasxml' => 'application/vnd.las.las+xml', 'latex' => 'application/x-latex', 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', 'les' => 'application/vnd.hhe.lesson-player', 'lha' => 'application/x-lzh-compressed', 'link66' => 'application/vnd.route66.link66+xml', 'list' => 'text/plain', 'list3820' => 'application/vnd.ibm.modcap', 'listafp' => 'application/vnd.ibm.modcap', 'lnk' => 'application/x-ms-shortcut', 'log' => 'text/plain', 'lostxml' => 'application/lost+xml', 'lrf' => 'application/octet-stream', 'lrm' => 'application/vnd.ms-lrm', 'ltf' => 'application/vnd.frogans.ltf', 'lvp' => 'audio/vnd.lucent.voice', 'lwp' => 'application/vnd.lotus-wordpro', 'lz' => 'application/x-lzip', 'lzh' => 'application/x-lzh-compressed', 'lzma' => 'application/x-lzma', 'lzo' => 'application/x-lzop', 'm13' => 'application/x-msmediaview', 'm14' => 'application/x-msmediaview', 'm1v' => 'video/mpeg', 'm21' => 'application/mp21', 'm2a' => 'audio/mpeg', 'm2v' => 'video/mpeg', 'm3a' => 'audio/mpeg', 'm3u' => 'audio/x-mpegurl', 'm3u8' => 'application/vnd.apple.mpegurl', 'm4a' => 'audio/mp4', 'm4u' => 'video/vnd.mpegurl', 'm4v' => 'video/mp4', 'ma' => 'application/mathematica', 'mads' => 'application/mads+xml', 'mag' => 'application/vnd.ecowin.chart', 'maker' => 'application/vnd.framemaker', 'man' => 'text/troff', 'mar' => 'application/octet-stream', 'mathml' => 'application/mathml+xml', 'mb' => 'application/mathematica', 'mbk' => 'application/vnd.mobius.mbk', 'mbox' => 'application/mbox', 'mc1' => 'application/vnd.medcalcdata', 'mcd' => 'application/vnd.mcd', 'mcurl' => 'text/vnd.curl.mcurl', 'mdb' => 'application/x-msaccess', 'mdi' => 'image/vnd.ms-modi', 'me' => 'text/troff', 'mesh' => 'model/mesh', 'meta4' => 'application/metalink4+xml', 'metalink' => 'application/metalink+xml', 'mets' => 'application/mets+xml', 'mfm' => 'application/vnd.mfmp', 'mft' => 'application/rpki-manifest', 'mgp' => 'application/vnd.osgeo.mapguide.package', 'mgz' => 'application/vnd.proteus.magazine', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mie' => 'application/x-mie', 'mif' => 'application/vnd.mif', 'mime' => 'message/rfc822', 'mj2' => 'video/mj2', 'mjp2' => 'video/mj2', 'mk3d' => 'video/x-matroska', 'mka' => 'audio/x-matroska', 'mks' => 'video/x-matroska', 'mkv' => 'video/x-matroska', 'mlp' => 'application/vnd.dolby.mlp', 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', 'mmf' => 'application/vnd.smaf', 'mmr' => 'image/vnd.fujixerox.edmics-mmr', 'mng' => 'video/x-mng', 'mny' => 'application/x-msmoney', 'mobi' => 'application/x-mobipocket-ebook', 'mods' => 'application/mods+xml', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp21' => 'application/mp21', 'mp2a' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'mp4a' => 'audio/mp4', 'mp4s' => 'application/mp4', 'mp4v' => 'video/mp4', 'mpc' => 'application/vnd.mophun.certificate', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpg4' => 'video/mp4', 'mpga' => 'audio/mpeg', 'mpkg' => 'application/vnd.apple.installer+xml', 'mpm' => 'application/vnd.blueice.multipass', 'mpn' => 'application/vnd.mophun.application', 'mpp' => 'application/vnd.ms-project', 'mpt' => 'application/vnd.ms-project', 'mpy' => 'application/vnd.ibm.minipay', 'mqy' => 'application/vnd.mobius.mqy', 'mrc' => 'application/marc', 'mrcx' => 'application/marcxml+xml', 'ms' => 'text/troff', 'mscml' => 'application/mediaservercontrol+xml', 'mseed' => 'application/vnd.fdsn.mseed', 'mseq' => 'application/vnd.mseq', 'msf' => 'application/vnd.epson.msf', 'msh' => 'model/mesh', 'msi' => 'application/x-msdownload', 'msl' => 'application/vnd.mobius.msl', 'msty' => 'application/vnd.muvee.style', 'mts' => 'model/vnd.mts', 'mus' => 'application/vnd.musician', 'musicxml' => 'application/vnd.recordare.musicxml+xml', 'mvb' => 'application/x-msmediaview', 'mwf' => 'application/vnd.mfer', 'mxf' => 'application/mxf', 'mxl' => 'application/vnd.recordare.musicxml', 'mxml' => 'application/xv+xml', 'mxs' => 'application/vnd.triscape.mxs', 'mxu' => 'video/vnd.mpegurl', 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', 'n3' => 'text/n3', 'nb' => 'application/mathematica', 'nbp' => 'application/vnd.wolfram.player', 'nc' => 'application/x-netcdf', 'ncx' => 'application/x-dtbncx+xml', 'nfo' => 'text/x-nfo', 'ngdat' => 'application/vnd.nokia.n-gage.data', 'nitf' => 'application/vnd.nitf', 'nlu' => 'application/vnd.neurolanguage.nlu', 'nml' => 'application/vnd.enliven', 'nnd' => 'application/vnd.noblenet-directory', 'nns' => 'application/vnd.noblenet-sealer', 'nnw' => 'application/vnd.noblenet-web', 'npx' => 'image/vnd.net-fpx', 'nsc' => 'application/x-conference', 'nsf' => 'application/vnd.lotus-notes', 'ntf' => 'application/vnd.nitf', 'nzb' => 'application/x-nzb', 'oa2' => 'application/vnd.fujitsu.oasys2', 'oa3' => 'application/vnd.fujitsu.oasys3', 'oas' => 'application/vnd.fujitsu.oasys', 'obd' => 'application/x-msbinder', 'obj' => 'application/x-tgif', 'oda' => 'application/oda', 'odb' => 'application/vnd.oasis.opendocument.database', 'odc' => 'application/vnd.oasis.opendocument.chart', 'odf' => 'application/vnd.oasis.opendocument.formula', 'odft' => 'application/vnd.oasis.opendocument.formula-template', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'odi' => 'application/vnd.oasis.opendocument.image', 'odm' => 'application/vnd.oasis.opendocument.text-master', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'odt' => 'application/vnd.oasis.opendocument.text', 'oga' => 'audio/ogg', 'ogg' => 'audio/ogg', 'ogv' => 'video/ogg', 'ogx' => 'application/ogg', 'omdoc' => 'application/omdoc+xml', 'onepkg' => 'application/onenote', 'onetmp' => 'application/onenote', 'onetoc' => 'application/onenote', 'onetoc2' => 'application/onenote', 'opf' => 'application/oebps-package+xml', 'opml' => 'text/x-opml', 'oprc' => 'application/vnd.palm', 'org' => 'application/vnd.lotus-organizer', 'osf' => 'application/vnd.yamaha.openscoreformat', 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', 'otc' => 'application/vnd.oasis.opendocument.chart-template', 'otf' => 'application/x-font-otf', 'otg' => 'application/vnd.oasis.opendocument.graphics-template', 'oth' => 'application/vnd.oasis.opendocument.text-web', 'oti' => 'application/vnd.oasis.opendocument.image-template', 'otp' => 'application/vnd.oasis.opendocument.presentation-template', 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'ott' => 'application/vnd.oasis.opendocument.text-template', 'oxps' => 'application/oxps', 'oxt' => 'application/vnd.openofficeorg.extension', 'p' => 'text/x-pascal', 'p10' => 'application/pkcs10', 'p12' => 'application/x-pkcs12', 'p7b' => 'application/x-pkcs7-certificates', 'p7c' => 'application/pkcs7-mime', 'p7m' => 'application/pkcs7-mime', 'p7r' => 'application/x-pkcs7-certreqresp', 'p7s' => 'application/pkcs7-signature', 'p8' => 'application/pkcs8', 'pas' => 'text/x-pascal', 'paw' => 'application/vnd.pawaafile', 'pbd' => 'application/vnd.powerbuilder6', 'pbm' => 'image/x-portable-bitmap', 'pcap' => 'application/vnd.tcpdump.pcap', 'pcf' => 'application/x-font-pcf', 'pcl' => 'application/vnd.hp-pcl', 'pclxl' => 'application/vnd.hp-pclxl', 'pct' => 'image/x-pict', 'pcurl' => 'application/vnd.curl.pcurl', 'pcx' => 'image/x-pcx', 'pdb' => 'application/vnd.palm', 'pdf' => 'application/pdf', 'pfa' => 'application/x-font-type1', 'pfb' => 'application/x-font-type1', 'pfm' => 'application/x-font-type1', 'pfr' => 'application/font-tdpfr', 'pfx' => 'application/x-pkcs12', 'pgm' => 'image/x-portable-graymap', 'pgn' => 'application/x-chess-pgn', 'pgp' => 'application/pgp-encrypted', 'phar' => 'application/octet-stream', 'php' => 'text/plain', 'phps' => 'application/x-httpd-phps', 'pic' => 'image/x-pict', 'pkg' => 'application/octet-stream', 'pki' => 'application/pkixcmp', 'pkipath' => 'application/pkix-pkipath', 'plb' => 'application/vnd.3gpp.pic-bw-large', 'plc' => 'application/vnd.mobius.plc', 'plf' => 'application/vnd.pocketlearn', 'plist' => 'application/x-plist', 'pls' => 'application/pls+xml', 'pml' => 'application/vnd.ctc-posml', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'portpkg' => 'application/vnd.macports.portpkg', 'pot' => 'application/vnd.ms-powerpoint', 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', 'ppd' => 'application/vnd.cups-ppd', 'ppm' => 'image/x-portable-pixmap', 'pps' => 'application/vnd.ms-powerpoint', 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'ppt' => 'application/vnd.ms-powerpoint', 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pqa' => 'application/vnd.palm', 'prc' => 'application/x-mobipocket-ebook', 'pre' => 'application/vnd.lotus-freelance', 'prf' => 'application/pics-rules', 'ps' => 'application/postscript', 'psb' => 'application/vnd.3gpp.pic-bw-small', 'psd' => 'image/vnd.adobe.photoshop', 'psf' => 'application/x-font-linux-psf', 'pskcxml' => 'application/pskc+xml', 'ptid' => 'application/vnd.pvi.ptid1', 'pub' => 'application/x-mspublisher', 'pvb' => 'application/vnd.3gpp.pic-bw-var', 'pwn' => 'application/vnd.3m.post-it-notes', 'pya' => 'audio/vnd.ms-playready.media.pya', 'pyv' => 'video/vnd.ms-playready.media.pyv', 'qam' => 'application/vnd.epson.quickanime', 'qbo' => 'application/vnd.intu.qbo', 'qfx' => 'application/vnd.intu.qfx', 'qps' => 'application/vnd.publishare-delta-tree', 'qt' => 'video/quicktime', 'qwd' => 'application/vnd.quark.quarkxpress', 'qwt' => 'application/vnd.quark.quarkxpress', 'qxb' => 'application/vnd.quark.quarkxpress', 'qxd' => 'application/vnd.quark.quarkxpress', 'qxl' => 'application/vnd.quark.quarkxpress', 'qxt' => 'application/vnd.quark.quarkxpress', 'ra' => 'audio/x-pn-realaudio', 'ram' => 'audio/x-pn-realaudio', 'rar' => 'application/x-rar-compressed', 'ras' => 'image/x-cmu-raster', 'rb' => 'text/plain', 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', 'rdf' => 'application/rdf+xml', 'rdz' => 'application/vnd.data-vision.rdz', 'rep' => 'application/vnd.businessobjects', 'res' => 'application/x-dtbresource+xml', 'resx' => 'text/xml', 'rgb' => 'image/x-rgb', 'rif' => 'application/reginfo+xml', 'rip' => 'audio/vnd.rip', 'ris' => 'application/x-research-info-systems', 'rl' => 'application/resource-lists+xml', 'rlc' => 'image/vnd.fujixerox.edmics-rlc', 'rld' => 'application/resource-lists-diff+xml', 'rm' => 'application/vnd.rn-realmedia', 'rmi' => 'audio/midi', 'rmp' => 'audio/x-pn-realaudio-plugin', 'rms' => 'application/vnd.jcp.javame.midlet-rms', 'rmvb' => 'application/vnd.rn-realmedia-vbr', 'rnc' => 'application/relax-ng-compact-syntax', 'roa' => 'application/rpki-roa', 'roff' => 'text/troff', 'rp9' => 'application/vnd.cloanto.rp9', 'rpm' => 'application/x-rpm', 'rpss' => 'application/vnd.nokia.radio-presets', 'rpst' => 'application/vnd.nokia.radio-preset', 'rq' => 'application/sparql-query', 'rs' => 'application/rls-services+xml', 'rsd' => 'application/rsd+xml', 'rss' => 'application/rss+xml', 'rtf' => 'application/rtf', 'rtx' => 'text/richtext', 's' => 'text/x-asm', 's3m' => 'audio/s3m', 's7z' => 'application/x-7z-compressed', 'saf' => 'application/vnd.yamaha.smaf-audio', 'safariextz' => 'application/octet-stream', 'sass' => 'text/x-sass', 'sbml' => 'application/sbml+xml', 'sc' => 'application/vnd.ibm.secure-container', 'scd' => 'application/x-msschedule', 'scm' => 'application/vnd.lotus-screencam', 'scq' => 'application/scvp-cv-request', 'scs' => 'application/scvp-cv-response', 'scss' => 'text/x-scss', 'scurl' => 'text/vnd.curl.scurl', 'sda' => 'application/vnd.stardivision.draw', 'sdc' => 'application/vnd.stardivision.calc', 'sdd' => 'application/vnd.stardivision.impress', 'sdkd' => 'application/vnd.solent.sdkm+xml', 'sdkm' => 'application/vnd.solent.sdkm+xml', 'sdp' => 'application/sdp', 'sdw' => 'application/vnd.stardivision.writer', 'see' => 'application/vnd.seemail', 'seed' => 'application/vnd.fdsn.seed', 'sema' => 'application/vnd.sema', 'semd' => 'application/vnd.semd', 'semf' => 'application/vnd.semf', 'ser' => 'application/java-serialized-object', 'setpay' => 'application/set-payment-initiation', 'setreg' => 'application/set-registration-initiation', 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', 'sfs' => 'application/vnd.spotfire.sfs', 'sfv' => 'text/x-sfv', 'sgi' => 'image/sgi', 'sgl' => 'application/vnd.stardivision.writer-global', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'shf' => 'application/shf+xml', 'sid' => 'image/x-mrsid-image', 'sig' => 'application/pgp-signature', 'sil' => 'audio/silk', 'silo' => 'model/mesh', 'sis' => 'application/vnd.symbian.install', 'sisx' => 'application/vnd.symbian.install', 'sit' => 'application/x-stuffit', 'sitx' => 'application/x-stuffitx', 'skd' => 'application/vnd.koan', 'skm' => 'application/vnd.koan', 'skp' => 'application/vnd.koan', 'skt' => 'application/vnd.koan', 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'slt' => 'application/vnd.epson.salt', 'sm' => 'application/vnd.stepmania.stepchart', 'smf' => 'application/vnd.stardivision.math', 'smi' => 'application/smil+xml', 'smil' => 'application/smil+xml', 'smv' => 'video/x-smv', 'smzip' => 'application/vnd.stepmania.package', 'snd' => 'audio/basic', 'snf' => 'application/x-font-snf', 'so' => 'application/octet-stream', 'spc' => 'application/x-pkcs7-certificates', 'spf' => 'application/vnd.yamaha.smaf-phrase', 'spl' => 'application/x-futuresplash', 'spot' => 'text/vnd.in3d.spot', 'spp' => 'application/scvp-vp-response', 'spq' => 'application/scvp-vp-request', 'spx' => 'audio/ogg', 'sql' => 'application/x-sql', 'src' => 'application/x-wais-source', 'srt' => 'application/x-subrip', 'sru' => 'application/sru+xml', 'srx' => 'application/sparql-results+xml', 'ssdl' => 'application/ssdl+xml', 'sse' => 'application/vnd.kodak-descriptor', 'ssf' => 'application/vnd.epson.ssf', 'ssml' => 'application/ssml+xml', 'st' => 'application/vnd.sailingtracker.track', 'stc' => 'application/vnd.sun.xml.calc.template', 'std' => 'application/vnd.sun.xml.draw.template', 'stf' => 'application/vnd.wt.stf', 'sti' => 'application/vnd.sun.xml.impress.template', 'stk' => 'application/hyperstudio', 'stl' => 'application/vnd.ms-pki.stl', 'str' => 'application/vnd.pg.format', 'stw' => 'application/vnd.sun.xml.writer.template', 'styl' => 'text/x-styl', 'sub' => 'image/vnd.dvb.subtitle', 'sus' => 'application/vnd.sus-calendar', 'susp' => 'application/vnd.sus-calendar', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'svc' => 'application/vnd.dvb.service', 'svd' => 'application/vnd.svd', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'swa' => 'application/x-director', 'swf' => 'application/x-shockwave-flash', 'swi' => 'application/vnd.aristanetworks.swi', 'sxc' => 'application/vnd.sun.xml.calc', 'sxd' => 'application/vnd.sun.xml.draw', 'sxg' => 'application/vnd.sun.xml.writer.global', 'sxi' => 'application/vnd.sun.xml.impress', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 't' => 'text/troff', 't3' => 'application/x-t3vm-image', 'taglet' => 'application/vnd.mynfc', 'tao' => 'application/vnd.tao.intent-module-archive', 'tar' => 'application/x-tar', 'tcap' => 'application/vnd.3gpp2.tcap', 'tcl' => 'application/x-tcl', 'teacher' => 'application/vnd.smart.teacher', 'tei' => 'application/tei+xml', 'teicorpus' => 'application/tei+xml', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'text' => 'text/plain', 'tfi' => 'application/thraud+xml', 'tfm' => 'application/x-tex-tfm', 'tga' => 'image/x-tga', 'tgz' => 'application/x-gzip', 'thmx' => 'application/vnd.ms-officetheme', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'tmo' => 'application/vnd.tmobile-livetv', 'torrent' => 'application/x-bittorrent', 'tpl' => 'application/vnd.groove-tool-template', 'tpt' => 'application/vnd.trid.tpt', 'tr' => 'text/troff', 'tra' => 'application/vnd.trueapp', 'trm' => 'application/x-msterminal', 'tsd' => 'application/timestamped-data', 'tsv' => 'text/tab-separated-values', 'ttc' => 'application/x-font-ttf', 'ttf' => 'application/x-font-ttf', 'ttl' => 'text/turtle', 'twd' => 'application/vnd.simtech-mindmapper', 'twds' => 'application/vnd.simtech-mindmapper', 'txd' => 'application/vnd.genomatix.tuxedo', 'txf' => 'application/vnd.mobius.txf', 'txt' => 'text/plain', 'u32' => 'application/x-authorware-bin', 'udeb' => 'application/x-debian-package', 'ufd' => 'application/vnd.ufdl', 'ufdl' => 'application/vnd.ufdl', 'ulx' => 'application/x-glulx', 'umj' => 'application/vnd.umajin', 'unityweb' => 'application/vnd.unity', 'uoml' => 'application/vnd.uoml+xml', 'uri' => 'text/uri-list', 'uris' => 'text/uri-list', 'urls' => 'text/uri-list', 'ustar' => 'application/x-ustar', 'utz' => 'application/vnd.uiq.theme', 'uu' => 'text/x-uuencode', 'uva' => 'audio/vnd.dece.audio', 'uvd' => 'application/vnd.dece.data', 'uvf' => 'application/vnd.dece.data', 'uvg' => 'image/vnd.dece.graphic', 'uvh' => 'video/vnd.dece.hd', 'uvi' => 'image/vnd.dece.graphic', 'uvm' => 'video/vnd.dece.mobile', 'uvp' => 'video/vnd.dece.pd', 'uvs' => 'video/vnd.dece.sd', 'uvt' => 'application/vnd.dece.ttml+xml', 'uvu' => 'video/vnd.uvvu.mp4', 'uvv' => 'video/vnd.dece.video', 'uvva' => 'audio/vnd.dece.audio', 'uvvd' => 'application/vnd.dece.data', 'uvvf' => 'application/vnd.dece.data', 'uvvg' => 'image/vnd.dece.graphic', 'uvvh' => 'video/vnd.dece.hd', 'uvvi' => 'image/vnd.dece.graphic', 'uvvm' => 'video/vnd.dece.mobile', 'uvvp' => 'video/vnd.dece.pd', 'uvvs' => 'video/vnd.dece.sd', 'uvvt' => 'application/vnd.dece.ttml+xml', 'uvvu' => 'video/vnd.uvvu.mp4', 'uvvv' => 'video/vnd.dece.video', 'uvvx' => 'application/vnd.dece.unspecified', 'uvvz' => 'application/vnd.dece.zip', 'uvx' => 'application/vnd.dece.unspecified', 'uvz' => 'application/vnd.dece.zip', 'vcard' => 'text/vcard', 'vcd' => 'application/x-cdlink', 'vcf' => 'text/x-vcard', 'vcg' => 'application/vnd.groove-vcard', 'vcs' => 'text/x-vcalendar', 'vcx' => 'application/vnd.vcx', 'vis' => 'application/vnd.visionary', 'viv' => 'video/vnd.vivo', 'vob' => 'video/x-ms-vob', 'vor' => 'application/vnd.stardivision.writer', 'vox' => 'application/x-authorware-bin', 'vrml' => 'model/vrml', 'vsd' => 'application/vnd.visio', 'vsf' => 'application/vnd.vsf', 'vss' => 'application/vnd.visio', 'vst' => 'application/vnd.visio', 'vsw' => 'application/vnd.visio', 'vtu' => 'model/vnd.vtu', 'vxml' => 'application/voicexml+xml', 'w3d' => 'application/x-director', 'wad' => 'application/x-doom', 'wav' => 'audio/x-wav', 'wax' => 'audio/x-ms-wax', 'wbmp' => 'image/vnd.wap.wbmp', 'wbs' => 'application/vnd.criticaltools.wbs+xml', 'wbxml' => 'application/vnd.wap.wbxml', 'wcm' => 'application/vnd.ms-works', 'wdb' => 'application/vnd.ms-works', 'wdp' => 'image/vnd.ms-photo', 'weba' => 'audio/webm', 'webm' => 'video/webm', 'webp' => 'image/webp', 'wg' => 'application/vnd.pmi.widget', 'wgt' => 'application/widget', 'wks' => 'application/vnd.ms-works', 'wm' => 'video/x-ms-wm', 'wma' => 'audio/x-ms-wma', 'wmd' => 'application/x-ms-wmd', 'wmf' => 'application/x-msmetafile', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wmz' => 'application/x-ms-wmz', 'woff' => 'application/x-font-woff', 'wpd' => 'application/vnd.wordperfect', 'wpl' => 'application/vnd.ms-wpl', 'wps' => 'application/vnd.ms-works', 'wqd' => 'application/vnd.wqd', 'wri' => 'application/x-mswrite', 'wrl' => 'model/vrml', 'wsdl' => 'application/wsdl+xml', 'wspolicy' => 'application/wspolicy+xml', 'wtb' => 'application/vnd.webturbo', 'wvx' => 'video/x-ms-wvx', 'x32' => 'application/x-authorware-bin', 'x3d' => 'model/x3d+xml', 'x3db' => 'model/x3d+binary', 'x3dbz' => 'model/x3d+binary', 'x3dv' => 'model/x3d+vrml', 'x3dvz' => 'model/x3d+vrml', 'x3dz' => 'model/x3d+xml', 'xaml' => 'application/xaml+xml', 'xap' => 'application/x-silverlight-app', 'xar' => 'application/vnd.xara', 'xbap' => 'application/x-ms-xbap', 'xbd' => 'application/vnd.fujixerox.docuworks.binder', 'xbm' => 'image/x-xbitmap', 'xdf' => 'application/xcap-diff+xml', 'xdm' => 'application/vnd.syncml.dm+xml', 'xdp' => 'application/vnd.adobe.xdp+xml', 'xdssc' => 'application/dssc+xml', 'xdw' => 'application/vnd.fujixerox.docuworks', 'xenc' => 'application/xenc+xml', 'xer' => 'application/patch-ops-error+xml', 'xfdf' => 'application/vnd.adobe.xfdf', 'xfdl' => 'application/vnd.xfdl', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xhvml' => 'application/xv+xml', 'xif' => 'image/vnd.xiff', 'xla' => 'application/vnd.ms-excel', 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', 'xlc' => 'application/vnd.ms-excel', 'xlf' => 'application/x-xliff+xml', 'xlm' => 'application/vnd.ms-excel', 'xls' => 'application/vnd.ms-excel', 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlt' => 'application/vnd.ms-excel', 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'xlw' => 'application/vnd.ms-excel', 'xm' => 'audio/xm', 'xml' => 'application/xml', 'xo' => 'application/vnd.olpc-sugar', 'xop' => 'application/xop+xml', 'xpi' => 'application/x-xpinstall', 'xpl' => 'application/xproc+xml', 'xpm' => 'image/x-xpixmap', 'xpr' => 'application/vnd.is-xpr', 'xps' => 'application/vnd.ms-xpsdocument', 'xpw' => 'application/vnd.intercon.formnet', 'xpx' => 'application/vnd.intercon.formnet', 'xsl' => 'application/xml', 'xslt' => 'application/xslt+xml', 'xsm' => 'application/vnd.syncml+xml', 'xspf' => 'application/xspf+xml', 'xul' => 'application/vnd.mozilla.xul+xml', 'xvm' => 'application/xv+xml', 'xvml' => 'application/xv+xml', 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-xyz', 'xz' => 'application/x-xz', 'yaml' => 'text/yaml', 'yang' => 'application/yang', 'yin' => 'application/yin+xml', 'yml' => 'text/yaml', 'z' => 'application/x-compress', 'z1' => 'application/x-zmachine', 'z2' => 'application/x-zmachine', 'z3' => 'application/x-zmachine', 'z4' => 'application/x-zmachine', 'z5' => 'application/x-zmachine', 'z6' => 'application/x-zmachine', 'z7' => 'application/x-zmachine', 'z8' => 'application/x-zmachine', 'zaz' => 'application/vnd.zzazz.deck+xml', 'zip' => 'application/zip', 'zir' => 'application/vnd.zul', 'zirz' => 'application/vnd.zul', 'zmm' => 'application/vnd.handheld-entertainment+xml', '123' => 'application/vnd.lotus-1-2-3', ); if (isset($mimeTypes[$extension])) { return $mimeTypes[$extension]; } } return null; }
Finds the mime type of a filename by checking it's extension. @param string $filename The filename. @return string|null The mimetype of the filename specified.
entailment
public static function get($key = null) { if (null === self::$instance) { self::$instance = new self(); } return $key ? self::$instance[$key] : self::$instance; }
Returns the application singleton. @param string $key A service or parameter key. @return Go The application singleton.
entailment
public function registerUpdater() { $this->register( new UpdateServiceProvider(), array('update_url' => '@manifest_url@') ); $app = $this; $command = $this->add( 'update', function ( InputInterface $input, OutputInterface $output ) use ($app) { $output->writeln('Looking for updates...'); /** @var Console $updated */ $console = $app['console']; $updated = $app['update']( $console->getVersion(), !$input->getOption('upgrade'), $input->getOption('pre-release') ); if ($updated) { $output->writeln('<info>Updated successfully.</info>'); } else { $output->writeln('<comment>Already up-to-date.</comment>'); } } ); $command->addOption( 'pre-release', 'p', InputOption::VALUE_NONE, 'Allow pre-release updates.' ); $command->addOption( 'upgrade', 'u', InputOption::VALUE_NONE, 'Allow upgrade to next major release.' ); return $this; }
Allows the application to be updated. @return Go The application.
entailment
public function loadClassMetadata(ClassMetadataInterface $classMetadata) { $result = false; foreach ($this->loaders as $loader) { $result = $loader->loadClassMetadata($classMetadata) || $result; } return $result; }
{@inheritdoc}
entailment
public function getMappedClasses() { $classes = []; foreach ($this->loaders as $loader) { if ($loader instanceof MappedClassMetadataLoaderInterface) { $classes = array_merge($classes, $loader->getMappedClasses()); } } return array_unique($classes); }
{@inheritdoc}
entailment
public function convert($data, TypeMetadataInterface $type, ContextInterface $context) { return $context->getVisitor()->visitArray($data, $type, $context); }
{@inheritdoc}
entailment
public function setName($name) { if (!class_exists($name)) { throw new \InvalidArgumentException(sprintf('The class "%s" does not exist.', $name)); } $this->name = $name; }
{@inheritdoc}
entailment
public function addProperty(PropertyMetadataInterface $property) { $name = $property->getName(); if ($this->hasProperty($name)) { $this->getProperty($name)->merge($property); } else { $this->properties[$name] = $property; } }
{@inheritdoc}
entailment
public function merge(ClassMetadataInterface $classMetadata) { if ($classMetadata->hasXmlRoot()) { $this->setXmlRoot($classMetadata->getXmlRoot()); } foreach ($classMetadata->getProperties() as $property) { $this->addProperty($property); } }
{@inheritdoc}
entailment
public function unserialize($serialized) { list( $this->name, $this->properties, $this->xmlRoot ) = unserialize($serialized); }
{@inheritdoc}
entailment
public function prepare($data, ContextInterface $context) { return $this->decode(parent::prepare($data, $context)); }
{@inheritdoc}
entailment
public function visitBoolean($data, TypeMetadataInterface $type, ContextInterface $context) { return parent::visitBoolean( filter_var($data, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE), $type, $context ); }
{@inheritdoc}
entailment
protected function doVisitObjectProperty( $data, $name, PropertyMetadataInterface $property, ContextInterface $context ) { $type = $property->getType(); if ($type === null) { throw new \RuntimeException(sprintf( 'You must define the type of the %s:%s.', $property->getClass(), $property->getName() )); } if (!$property->isWritable() || !isset($data[$name])) { return false; } $value = $this->navigator->navigate($data[$name], $context, $type); if ($value === null && $context->isNullIgnored()) { return false; } $this->mutator->setValue( $this->result, $property->hasMutator() ? $property->getMutator() : $property->getName(), $value ); return true; }
{@inheritdoc}
entailment
public function enableErrorHandler(array $options = []): void { if ($this->errorHandlerEnabled) { throw new \Exception('The error handler is already enabled!'); } set_exception_handler(function($exception) use ($options) { \BearFramework\Internal\ErrorHandler::handleException($this, $exception, $options); }); register_shutdown_function(function() use ($options) { $errorData = error_get_last(); if (is_array($errorData)) { \BearFramework\Internal\ErrorHandler::handleFatalError($this, $errorData, $options); } }); set_error_handler(function($errorNumber, $errorMessage, $errorFile, $errorLine) { throw new \ErrorException($errorMessage, 0, $errorNumber, $errorFile, $errorLine); }); $this->errorHandlerEnabled = true; }
Enables an error handler. @param array $options Error handler options. Available values: logErrors (bool), displayErrors (bool). @return void No value is returned. @throws \Exception
entailment
public function run(): void { $response = $this->routes->getResponse($this->request); if (!($response instanceof App\Response)) { $response = new App\Response\NotFound(); } $this->send($response); }
Call this method to find the response in the registered routes and send it. @return void No value is returned.
entailment
public function send(\BearFramework\App\Response $response): void { if ($this->hasEventListeners('beforeSendResponse')) { $this->dispatchEvent('beforeSendResponse', new \BearFramework\App\BeforeSendResponseEventDetails($response)); } if (!$response->headers->exists('Content-Length')) { $response->headers->set($response->headers->make('Content-Length', ($response instanceof App\Response\FileReader ? (string) filesize($response->filename) : (string) strlen($response->content)))); } if (!$response->headers->exists('Cache-Control')) { $response->headers->set($response->headers->make('Cache-Control', 'no-cache, no-store, must-revalidate, private, max-age=0')); } http_response_code($response->statusCode); if (!headers_sent()) { $headers = $response->headers->getList(); foreach ($headers as $header) { if ($header->name === 'Content-Type' && $response->charset !== null) { $header->value .= '; charset=' . $response->charset; } header($header->name . ': ' . $header->value); } $cookies = $response->cookies->getList(); if ($cookies->count() > 0) { $baseURLParts = parse_url($this->request->base); foreach ($cookies as $cookie) { setcookie($cookie->name, $cookie->value, $cookie->expire, $cookie->path === null ? (isset($baseURLParts['path']) ? $baseURLParts['path'] . '/' : '/') : $cookie->path, $cookie->domain === null ? (isset($baseURLParts['host']) ? $baseURLParts['host'] : '') : $cookie->domain, $cookie->secure === null ? $this->request->scheme === 'https' : $cookie->secure, $cookie->httpOnly); } } } if ($response instanceof App\Response\FileReader) { readfile($response->filename); } else { echo $response->content; } if ($this->hasEventListeners('sendResponse')) { $this->dispatchEvent('sendResponse', new \BearFramework\App\SendResponseEventDetails($response)); } }
Outputs a response. @param \BearFramework\App\Response $response The response object to output. @return void No value is returned.
entailment
public function initialize(NavigatorInterface $navigator, VisitorInterface $visitor, $direction, $format) { $this ->setNavigator($navigator) ->setVisitor($visitor) ->setDirection($direction) ->setFormat($format) ->setDataStack([]) ->setMetadataStack([]); }
{@inheritdoc}
entailment
public function enterScope($data, MetadataInterface $metadata) { $this->dataStack[] = $data; $this->metadataStack[] = $metadata; return $this; }
{@inheritdoc}
entailment
public function matchesRequest() { $hasImages = ! Collection::make($this->event->get('attachments'))->isEmpty(); return parent::matchesRequest() && $hasImages; }
Determine if the request is for this driver. @return bool
entailment
public function getMessages() { $message = new IncomingMessage(File::PATTERN, $this->event->get('from')['id'], $this->event->get('conversation')['id'], $this->payload); $message->setFiles($this->getAttachmentUrls()); return [$message]; }
Retrieve the chat message. @return array
entailment
public function getAttachmentUrls() { return Collection::make($this->event->get('attachments'))->map(function ($item) { return new File($item['contentUrl'], $item); })->toArray(); }
Retrieve attachment urls from an incoming message. @return array A download for the attachment.
entailment
public function set(string $key, $value, int $ttl = null): void { $keyMD5 = md5($key); $key = $this->keyPrefix . substr($keyMD5, 0, 3) . '/' . substr($keyMD5, 3) . '.2'; $this->dataRepository->setValue($key, gzcompress(serialize([$ttl > 0 ? time() + $ttl : 0, $value]))); }
Stores a value in the cache. @param string $key The key under which to store the value. @param type $value The value to store. @param int $ttl Number of seconds to store value in the cache. @return void No value is returned.
entailment
public function get(string $key) { $keyMD5 = md5($key); $value = $this->dataRepository->getValue($this->keyPrefix . substr($keyMD5, 0, 3) . '/' . substr($keyMD5, 3) . '.2'); if ($value !== null) { try { $value = unserialize(gzuncompress($value)); if ($value[0] > 0) { if ($value[0] > time()) { return $value[1]; } return null; } return $value[1]; } catch (\Exception $e) { } } return null; }
Retrieves a value from the cache. @param string $key The key under which the value is stored. @return mixed|null Returns the stored value or null if not found or expired.
entailment
public function delete(string $key): void { $keyMD5 = md5($key); $this->dataRepository->delete($this->keyPrefix . substr($keyMD5, 0, 3) . '/' . substr($keyMD5, 3) . '.2'); }
Deletes a value from the cache. @param string $key The key under which the value is stored. @return void No value is returned.
entailment
public function setMultiple(array $items, int $ttl = null): void { foreach ($items as $key => $value) { $this->set($key, $value, $ttl); } }
Stores multiple values in the cache. @param array $items An array of key/value pairs to store in the cache. @param int $ttl Number of seconds to store values in the cache. @return void No value is returned.
entailment
public function clear(): void { $list = $this->dataRepository->getList() ->filterBy('key', $this->keyPrefix, 'startWith'); foreach ($list as $item) { $this->dataRepository->delete($item->key); }; }
Deletes all values from the cache.
entailment
public function convert($data, TypeMetadataInterface $type, ContextInterface $context) { return $context->getVisitor()->visitBoolean($data, $type, $context); }
{@inheritdoc}
entailment
public function get(string $path = '/') { return $this->app->request->base . implode('/', array_map('urlencode', explode('/', $path))); }
Constructs a url for the path specified. @param string $path The path. @return string Absolute URL containing the base URL plus the path given.
entailment
protected function loadFile($file) { $data = []; $xml = simplexml_import_dom($this->loadDocument($file)); foreach ($xml->class as $class) { $data[(string) $class['name']] = $this->loadClass($class); } return $data; }
{@inheritdoc}
entailment
private function loadClass(\SimpleXMLElement $class) { $definition = []; if (isset($class['exclusion-policy'])) { $definition['exclusion_policy'] = (string) $class['exclusion-policy']; } if (isset($class['order'])) { $definition['order'] = (string) $class['order']; } if (isset($class['readable'])) { $definition['readable'] = (string) $class['readable'] === 'true'; } if (isset($class['writable'])) { $definition['writable'] = (string) $class['writable'] === 'true'; } if (isset($class['xml-root'])) { $definition['xml_root'] = (string) $class['xml-root']; } $properties = []; foreach ($class->property as $property) { $properties[(string) $property['name']] = $this->loadProperty($property); } $definition['properties'] = $properties; return $definition; }
@param \SimpleXMLElement $class @return mixed[]
entailment
private function loadProperty(\SimpleXMLElement $element) { $property = []; if (isset($element['alias'])) { $property['alias'] = (string) $element['alias']; } if (isset($element['type'])) { $property['type'] = (string) $element['type']; } if (isset($element['exclude'])) { $property['exclude'] = (string) $element['exclude'] === 'true'; } if (isset($element['expose'])) { $property['expose'] = (string) $element['expose'] === 'true'; } if (isset($element['accessor'])) { $property['accessor'] = (string) $element['accessor']; } if (isset($element['readable'])) { $property['readable'] = (string) $element['readable'] === 'true'; } if (isset($element['writable'])) { $property['writable'] = (string) $element['writable'] === 'true'; } if (isset($element['mutator'])) { $property['mutator'] = (string) $element['mutator']; } if (isset($element['since'])) { $property['since'] = (string) $element['since']; } if (isset($element['until'])) { $property['until'] = (string) $element['until']; } if (isset($element['max-depth'])) { $property['max_depth'] = (int) $element['max-depth']; } foreach ($element->group as $group) { $property['groups'][] = (string) $group; } if (isset($element['xml-attribute'])) { $property['xml_attribute'] = (string) $element['xml-attribute'] === 'true'; } if (isset($element['xml-value'])) { $property['xml_value'] = (string) $element['xml-value'] === 'true'; } if (isset($element['xml-inline'])) { $property['xml_inline'] = (string) $element['xml-inline'] === 'true'; } if (isset($element['xml-entry'])) { $property['xml_entry'] = (string) $element['xml-entry']; } if (isset($element['xml-entry-attribute'])) { $property['xml_entry_attribute'] = (string) $element['xml-entry-attribute']; } if (isset($element['xml-key-as-attribute'])) { $property['xml_key_as_attribute'] = (string) $element['xml-key-as-attribute'] === 'true'; } if (isset($element['xml-key-as-node'])) { $property['xml_key_as_node'] = (string) $element['xml-key-as-node'] === 'true'; } return $property; }
@param \SimpleXMLElement $element @return mixed[]
entailment
private function loadDocument($file) { $data = trim(@file_get_contents($file)); if (empty($data)) { throw new \InvalidArgumentException(sprintf('The XML mapping file "%s" is not valid.', $file)); } $internalErrors = libxml_use_internal_errors(); $disableEntities = libxml_disable_entity_loader(); $this->setLibXmlState(true, true); $document = new \DOMDocument(); $document->validateOnParse = true; if (!@$document->loadXML($data, LIBXML_NONET | LIBXML_COMPACT)) { throw $this->createException($file, $internalErrors, $disableEntities); } $document->normalizeDocument(); if (!@$document->schemaValidateSource(file_get_contents(__DIR__.'/../Resource/mapping.xsd'))) { throw $this->createException($file, $internalErrors, $disableEntities); } foreach ($document->childNodes as $child) { if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { throw new \InvalidArgumentException('The document type is not allowed.'); } } $this->setLibXmlState($internalErrors, $disableEntities); return $document; }
@param string $file @return \DOMDocument
entailment
private function createException($file, $internalErrors, $disableEntities) { $errors = []; foreach (libxml_get_errors() as $error) { $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)', $error->level === LIBXML_ERR_WARNING ? 'WARNING' : 'ERROR', $error->code, trim($error->message), $file, $error->line, $error->column ); } $this->setLibXmlState($internalErrors, $disableEntities); return new \InvalidArgumentException(implode(PHP_EOL, $errors)); }
@param string $file @param bool $internalErrors @param bool $disableEntities @return \InvalidArgumentException
entailment
public function add(string $name, callable $callback): self { call_user_func($this->addCallback, $name, $callback); return $this; }
Creates a new shortcut. @param string $name The name of the shortcut property. @param callable $callback The callback to return the shortcut value. @return self Returns a reference to itself.
entailment
public function addDir(string $pathname): self { $this->appAssets->addDir($this->dir . '/' . $pathname); return $this; }
Registers a directory that will be publicly accessible relative to the current addon or application location. @param string $pathname The directory name. @return self Returns a reference to itself.
entailment
public function getURL(string $filename, array $options = []): string { return $this->appAssets->getURL($this->dir . '/' . $filename, $options); }
Returns a public URL for the specified filename in the current context. @param string $filename The filename. @param array $options URL options. You can resize the file by providing "width", "height" or both. @return string The URL for the specified filename and options.
entailment
public function getContent(string $filename, array $options = []): ?string { return $this->appAssets->getContent($this->dir . '/' . $filename, $options); }
Returns the content of the file specified in the current context. @param string $filename The filename. @param array $options List of options. You can resize the file by providing "width", "height" or both. You can specify encoding too (base64 or data-uri). @return string|null The content of the file or null if file does not exists.
entailment
public function getDetails(string $filename, array $list): array { return $this->appAssets->getDetails($this->dir . '/' . $filename, $list); }
Returns a list of details for the filename specifie in the current context. @param string $filename The filename of the asset. @param array $list A list of details to return. Available values: mimeType, size, width, height. @return array A list of tails for the filename specified.
entailment
public function getURL(): ?string { if ($this->base !== null) { $list = []; $queryList = $this->query->getList(); foreach ($queryList as $queryItem) { $list[$queryItem->name] = $queryItem->value; } return $this->base . implode('/', array_map('urlencode', explode('/', (string) $this->path))) . (empty($list) ? '' : '?' . http_build_query($list)); } return null; }
Returns the request URL or null if the base is empty. @return string|null Returns the request URL or null if the base is empty.
entailment
public function matchesRequest() { $hasImages = ! Collection::make($this->event->get('attachments'))->where('contentType', 'image')->isEmpty(); return $hasImages && (! is_null($this->event->get('recipient')) && ! is_null($this->event->get('serviceUrl'))); }
Determine if the request is for this driver. @return bool
entailment
public function getMessages() { if (empty($this->messages)) { $message = new IncomingMessage(Image::PATTERN, $this->event->get('from')['id'], $this->event->get('conversation')['id'], $this->payload); $message->setImages($this->getImagesUrls()); $this->messages = [$message]; } return $this->messages; }
Retrieve the chat message. @return array
entailment
public function getImagesUrls() { return Collection::make($this->event->get('attachments'))->where('contentType', 'image')->map(function ($item) { return new Image($item['contentUrl'], $item); })->toArray(); }
Retrieve image urls from an incoming message. @return array A download for the image file.
entailment
protected function doVisitObjectProperty( $data, $name, PropertyMetadataInterface $property, ContextInterface $context ) { if (!$property->isReadable()) { return false; } $result = $this->navigator->navigate( $this->accessor->getValue( $data, $property->hasAccessor() ? $property->getAccessor() : $property->getName() ), $context, $property->getType() ); if ($result === null && $context->isNullIgnored()) { return false; } $this->result[$name] = $result; return true; }
{@inheritdoc}
entailment
public static function create(array $types = []) { $expandedTypes = []; foreach ([Direction::SERIALIZATION, Direction::DESERIALIZATION] as $direction) { $expandedTypes[$direction] = isset($types[$direction]) ? $types[$direction] : []; unset($types[$direction]); } $types = array_merge([ Type::ARRAY_ => new ArrayType(), Type::BOOL => $booleanType = new BooleanType(), Type::BOOLEAN => $booleanType, Type::CLOSURE => new ClosureType(), Type::DATE_TIME => new DateTimeType(), Type::DOUBLE => $floatType = new FloatType(), Type::EXCEPTION => new ExceptionType(), Type::FLOAT => $floatType, Type::INT => $integerType = new IntegerType(), Type::INTEGER => $integerType, Type::NULL => new NullType(), Type::NUMERIC => $floatType, Type::OBJECT => new ObjectType(), Type::RESOURCE => new ResourceType(), Type::STD_CLASS => new StdClassType(), Type::STRING => new StringType(), ], $types); foreach ($expandedTypes as &$innerTypes) { $innerTypes = array_merge($types, $innerTypes); } return new static($expandedTypes); }
@param TypeInterface[][]|TypeInterface[] $types @return TypeRegistryInterface
entailment
public function registerType($name, $direction, TypeInterface $type) { if (!isset($this->types[$direction])) { $this->types[$direction] = []; } $this->types[$direction][$name] = $type; }
{@inheritdoc}
entailment
public function getType($name, $direction) { if (!isset($this->types[$direction][$name])) { if (!class_exists($name)) { throw new \InvalidArgumentException(sprintf( 'The type "%s" for direction "%s" does not exist.', $name, $direction === Direction::SERIALIZATION ? 'serialization' : 'deserialization' )); } if (($type = $this->findClassType($name, $direction)) === null) { $type = $this->getType(Type::OBJECT, $direction); } $this->registerType($name, $direction, $type); } return $this->types[$direction][$name]; }
{@inheritdoc}
entailment
private function findClassType($name, $direction) { if (!isset($this->types[$direction])) { return; } foreach ($this->types[$direction] as $class => $type) { if ((class_exists($class) || interface_exists($class)) && is_a($name, $class, true)) { return $type; } } }
@param string $name @param int $direction @return TypeInterface|null
entailment
public function loadClassMetadata(ClassMetadataInterface $classMetadata) { return ($loader = $this->getLoader()) !== null && $loader->loadClassMetadata($classMetadata); }
{@inheritdoc}
entailment
public function add($pattern, $callback): self { if (is_string($pattern)) { if (!isset($pattern{0})) { throw new \InvalidArgumentException('The pattern argument must be a not empty string or array of not empty strings'); } $pattern = [$pattern]; } elseif (is_array($pattern)) { if (empty($pattern)) { throw new \InvalidArgumentException('The pattern argument must be a not empty string or array of not empty strings'); } foreach ($pattern as $_pattern) { if (!is_string($_pattern)) { throw new \InvalidArgumentException('The pattern argument must be a not empty string or array of not empty strings'); } if (!isset($_pattern{0})) { throw new \InvalidArgumentException('The pattern argument must be a not empty string or array of not empty strings'); } } } else { throw new \InvalidArgumentException('The pattern argument must be a not empty string or array of not empty strings'); } if (is_callable($callback)) { $callback = [$callback]; } elseif (is_array($callback)) { if (empty($callback)) { throw new \InvalidArgumentException('The callback argument must be a valid callable or array of valid callables'); } foreach ($callback as $_callback) { if (!is_callable($_callback)) { throw new \InvalidArgumentException('The callback argument must be a valid callable or array of valid callables'); } } } else { throw new \InvalidArgumentException('The callback argument must be a valid callable or array of valid callables'); } $this->data[] = [$pattern, $callback]; return $this; }
Registers a request handler. @param string|string[] $pattern Path pattern or array of patterns. Can contain "?" (path segment) and "*" (matches everything). Can start with method name (GET, HEAD, POST, DELETE, PUT, PATCH, OPTIONS) or list of method names (GET|HEAD|POST). @param callable|callable[] $callback Function that is expected to return object of type \BearFramework\App\Response. @throws \InvalidArgumentException @return self Returns a reference to itself.
entailment
public function getResponse(\BearFramework\App\Request $request) { $requestPath = (string) $request->path; $requestMethod = $request->method; foreach ($this->data as $route) { foreach ($route[0] as $pattern) { $matches = null; preg_match('/^(?:(?:((?:[A-Z]+\|){0,}[A-Z]+) )?)(.*+)/', $pattern, $matches); $patternMethods = '|' . ($matches[1] === '' ? 'GET' : $matches[1]) . '|'; if (strpos($patternMethods, '|' . $requestMethod . '|') === false) { continue; } $patternPath = $matches[2]; if (preg_match('/^' . str_replace(['/', '?', '*'], ['\/', '[^\/]+?', '.+?'], $patternPath) . '$/u', $requestPath) === 1) { foreach ($route[1] as $callable) { ob_start(); try { $response = call_user_func($callable, $request); ob_end_clean(); } catch (\Exception $e) { ob_end_clean(); throw $e; } if ($response instanceof App\Response) { return $response; } } // continue searching } } } if ($request->method === 'HEAD') { $getRequest = clone($request); $getRequest->method = 'GET'; $response = $this->getResponse($getRequest); if ($response instanceof App\Response) { $response->content = ''; return $response; } } return null; }
Finds the matching callback and returns its result. @param \BearFramework\App\Request $request The request object to match against. @return mixed The result of the matching callback. NULL if none.
entailment
protected function getType(&$value) { if (ctype_alpha($value[0])) { return self::T_NAME; } if ($value[0] === '\'') { $value = str_replace('\'\'', '\'', substr($value, 1, -1)); return self::T_STRING; } if ($value === '>') { return self::T_GREATER_THAN; } if ($value === '<') { return self::T_LOWER_THAN; } if ($value === ',') { return self::T_COMMA; } if ($value === '=') { return self::T_EQUAL; } return self::T_NONE; }
{@inheritdoc}
entailment
public function skipClass(ClassMetadataInterface $class, ContextInterface $context) { foreach ($this->strategies as $strategy) { if ($strategy->skipClass($class, $context)) { return true; } } return false; }
{@inheritdoc}
entailment
public function skipProperty(PropertyMetadataInterface $property, ContextInterface $context) { foreach ($this->strategies as $strategy) { if ($strategy->skipProperty($property, $context)) { return true; } } return false; }
{@inheritdoc}
entailment
public function skipType(TypeMetadataInterface $type, ContextInterface $context) { foreach ($this->strategies as $strategy) { if ($strategy->skipType($type, $context)) { return true; } } return false; }
{@inheritdoc}
entailment
protected function fetchClassMetadata($class) { $item = $this->pool->getItem(strtr($this->prefix.$class, '\\', '_')); if ($item->isHit()) { return $item->get(); } $classMetadata = $this->factory->getClassMetadata($class); $this->pool->save($item->set($classMetadata)); return $classMetadata; }
{@inheritdoc}
entailment
public function visitArray($data, TypeMetadataInterface $type, ContextInterface $context) { if ($data === []) { return $this->visitData('[]', $type, $context); } return parent::visitArray($data, $type, $context); }
{@inheritdoc}
entailment
protected function encode($data) { $resource = fopen('php://temp,', 'w+'); $headers = null; if (!is_array($data)) { $data = [[$data]]; } elseif (!empty($data) && !$this->isIndexedArray($data)) { $data = [$data]; } foreach ($data as $value) { $result = []; $this->flatten($value, $result); if ($headers === null) { if (!$this->isIndexedArray($result)) { $headers = array_keys($result); fputcsv($resource, $headers, $this->delimiter, $this->enclosure, $this->escapeChar); } else { $headers = count($result); } } elseif (is_array($headers) && $headers !== array_keys($result)) { fclose($resource); throw new \InvalidArgumentException(sprintf( 'The input dimension is not equals for all entries (Expected: %d, got %d).', count($headers), count($result) )); } elseif ($headers !== count($result)) { fclose($resource); throw new \InvalidArgumentException(sprintf( 'The input dimension is not equals for all entries (Expected: %d, got %d).', $headers, count($result) )); } fputcsv($resource, $result, $this->delimiter, $this->enclosure, $this->escapeChar); } rewind($resource); $result = stream_get_contents($resource); fclose($resource); return $result; }
{@inheritdoc}
entailment
public function convert($data, TypeMetadataInterface $type, ContextInterface $context) { return $context->getVisitor()->visitInteger($data, $type, $context); }
{@inheritdoc}
entailment
public function additionalCleanup($additionalFiles) { foreach ($additionalFiles as $path) { $dir_to_remove = $path; $print_message = $this->io->isVeryVerbose(); if (is_dir($dir_to_remove)) { if (static::deleteRecursive($dir_to_remove)) { $message = sprintf(" <info>Removing directory '%s'</info>", $path); } else { // Always display a message if this fails as it means something has // gone wrong. Therefore the message has to include the package name // as the first informational message might not exist. $print_message = true; $message = sprintf(" <error>Failure removing directory '%s'</error>.", $path); } } else { // If the package has changed or the --prefer-dist version does not // include the directory this is not an error. $message = sprintf(" Directory '%s' does not exist", $path); } if ($print_message) { $this->io->write($message); } } if ($this->io->isVeryVerbose()) { // Add a new line to separate this output from the next package. $this->io->write(""); } }
Remove other files that could be possibly problematic. @param \Composer\Script\Event $event A Event object.
entailment
protected function findPackageKey($package_name) { $package_key = null; // In most cases the package name is already used as the array key. if (isset(static::$packageToCleanup[$package_name])) { $package_key = $package_name; } else { // Handle any mismatch in case between the package name and array key. // For example, the array key 'mikey179/vfsStream' needs to be found // when composer returns a package name of 'mikey179/vfsstream'. foreach (static::$packageToCleanup as $key => $dirs) { if (strtolower($key) === $package_name) { $package_key = $key; break; } } } return $package_key; }
Find the array key for a given package name with a case-insensitive search. @param string $package_name The package name from composer. This is always already lower case. @return string|null The string key, or NULL if none was found.
entailment
protected function deleteRecursive($path) { if (is_file($path) || is_link($path)) { return unlink($path); } $success = true; $dir = dir($path); while (($entry = $dir->read()) !== false) { if ($entry == '.' || $entry == '..') { continue; } $entry_path = $path . '/' . $entry; $success = static::deleteRecursive($entry_path) && $success; } $dir->close(); return rmdir($path) && $success; }
Helper method to remove directories and the files they contain. @param string $path The directory or file to remove. It must exist. @return bool TRUE on success or FALSE on failure.
entailment
protected function loadClass(\ReflectionClass $class) { $definition = parent::loadClass($class); foreach ($this->reader->getClassAnnotations($class) as $annotation) { if ($annotation instanceof ExclusionPolicy) { $definition['exclusion_policy'] = $annotation->policy; } elseif ($annotation instanceof Order) { $definition['order'] = $annotation->order; } elseif ($annotation instanceof Readable) { $definition['readable'] = $annotation->readable; } elseif ($annotation instanceof Writable) { $definition['writable'] = $annotation->writable; } elseif ($annotation instanceof XmlRoot) { $definition['xml_root'] = $annotation->name; } } return $definition; }
{@inheritdoc}
entailment
protected function loadMethod(\ReflectionMethod $method) { $result = $this->loadAnnotations($this->reader->getMethodAnnotations($method)); if (!empty($result)) { return $result; } }
{@inheritdoc}
entailment
private function loadAnnotations(array $annotations) { $definition = []; foreach ($annotations as $annotation) { if ($annotation instanceof Alias) { $definition['alias'] = $annotation->alias; } elseif ($annotation instanceof Type) { $definition['type'] = $annotation->type; } elseif ($annotation instanceof Expose) { $definition['expose'] = true; } elseif ($annotation instanceof Exclude) { $definition['exclude'] = true; } elseif ($annotation instanceof Readable) { $definition['readable'] = $annotation->readable; } elseif ($annotation instanceof Writable) { $definition['writable'] = $annotation->writable; } elseif ($annotation instanceof Accessor) { $definition['accessor'] = $annotation->accessor; } elseif ($annotation instanceof Mutator) { $definition['mutator'] = $annotation->mutator; } elseif ($annotation instanceof Since) { $definition['since'] = $annotation->version; } elseif ($annotation instanceof Until) { $definition['until'] = $annotation->version; } elseif ($annotation instanceof MaxDepth) { $definition['max_depth'] = $annotation->maxDepth; } elseif ($annotation instanceof Groups) { $definition['groups'] = $annotation->groups; } elseif ($annotation instanceof XmlAttribute) { $definition['xml_attribute'] = true; } elseif ($annotation instanceof XmlValue) { $definition['xml_value'] = true; } elseif ($annotation instanceof XmlCollection) { if ($annotation->entry !== null) { $definition['xml_entry'] = $annotation->entry; } if ($annotation->entryAttribute !== null) { $definition['xml_entry_attribute'] = $annotation->entryAttribute; } if ($annotation->keyAsAttribute !== null) { $definition['xml_key_as_attribute'] = $annotation->keyAsAttribute; } if ($annotation->keyAsNode !== null) { $definition['xml_key_as_node'] = $annotation->keyAsNode; } if ($annotation->inline !== null) { $definition['xml_inline'] = $annotation->inline; } } } return $definition; }
@param object[] $annotations @return mixed[]
entailment
protected function doConvert($name) { $item = $this->cache->getItem($name); if ($item->isHit()) { return $item->get(); } $result = $this->strategy->convert($name); $this->cache->save($item->set($result)); return $result; }
{@inheritdoc}
entailment
public function navigate($data, ContextInterface $context, TypeMetadataInterface $type = null) { $type = $type ?: $this->typeGuesser->guess($data); $name = $type->getName(); if ($data === null) { $name = Type::NULL; } return $this->typeRegistry->getType($name, $context->getDirection())->convert($data, $type, $context); }
{@inheritdoc}
entailment
public function convert($data, TypeMetadataInterface $type, ContextInterface $context) { return $context->getVisitor()->visitFloat($data, $type, $context); }
{@inheritdoc}
entailment
public function add(string $id): self { if (!isset($this->data[$id])) { $registeredAddon = \BearFramework\Addons::get($id); if ($registeredAddon === null) { throw new \Exception('The addon ' . $id . ' is not registered!'); } $registeredAddonOptions = $registeredAddon->options; if (isset($registeredAddonOptions['require']) && is_array($registeredAddonOptions['require'])) { foreach ($registeredAddonOptions['require'] as $requiredAddonID) { if (is_string($requiredAddonID) && !isset($this->data[$requiredAddonID])) { $this->add($requiredAddonID); } } } $dir = $registeredAddon->dir; $this->data[$id] = new \BearFramework\App\Addon($id, $dir); $this->app->contexts->add($dir); } return $this; }
Enables an addon. @param string $id The id of the addon. @throws \Exception @return self Returns a reference to itself.
entailment
public function get(string $id): ?\BearFramework\App\Addon { if (isset($this->data[$id])) { return clone($this->data[$id]); } return null; }
Returns the enabled addon or null if not found. @param string $id The id of the addon. @return BearFramework\App\Addon|null The enabled addon or null if not found.
entailment
public function getList() { $list = new \BearFramework\DataList(); foreach ($this->data as $addon) { $list[] = clone($addon); } return $list; }
Returns a list of all enabled addons. @return \BearFramework\DataList|\BearFramework\App\Addon[] An array containing all enabled addons.
entailment
public function navigate($data, ContextInterface $context, TypeMetadataInterface $type = null) { $type = $type ?: $this->typeGuesser->guess($data); $serialization = $context->getDirection() === Direction::SERIALIZATION; if ($serialization) { $this->dispatcher->dispatch( SerializerEvents::PRE_SERIALIZE, $event = new PreSerializeEvent($data, $type, $context) ); } else { $this->dispatcher->dispatch( SerializerEvents::PRE_DESERIALIZE, $event = new PreDeserializeEvent($data, $type, $context) ); } $result = $this->navigator->navigate($data = $event->getData(), $context, $type = $event->getType()); if ($serialization) { $this->dispatcher->dispatch( SerializerEvents::POST_SERIALIZE, new PostSerializeEvent($data, $type, $context) ); } else { $this->dispatcher->dispatch( SerializerEvents::POST_DESERIALIZE, new PostDeserializeEvent($result, $type, $context) ); } return $result; }
{@inheritdoc}
entailment
public function populate($source, array $propertyNameMap = array(), $onlyMappedProperties = false) { $this->populateInternal($source, $propertyNameMap, $onlyMappedProperties, false); }
Populates this instance, using standard references (as opposed to cloning) when objects are encountered. @param PopulateInterface|array $source A key=>value array or another PopulateInterface instance to use as data @param array $propertyNameMap Optional array of property names supporting mapping (see README) @param boolean $onlyMappedProperties If <code>true</code> will only populate properties contained in map @throws Exception Will pass through any Exception during populating
entailment
public function populateWithClones($source, array $propertyNameMap = array(), $onlyMappedProperties = false) { $this->populateInternal($source, $propertyNameMap, $onlyMappedProperties, true); }
Populates this instance, cloning any object values that may be encountered. @param PopulateInterface|array $source A key=>value array or another PopulateInterface instance to use as data @param array $propertyNameMap Optional array of property names supporting mapping (see README) @param boolean $onlyMappedProperties If <code>true</code> will only populate properties contained in map @throws Exception Will pass through any Exception during populating
entailment
private function populateInternal($source, array $propertyNameMap, $onlyMappedProperties, $cloneObjects) { // decide where values come from or throw Exception if not retrievable if ($source instanceof PopulateInterface) { $data = $source->exportGettableProperties($propertyNameMap, $onlyMappedProperties); // ignore setter presence failures when values come from another object } elseif (!$onlyMappedProperties && $source instanceof \ArrayAccess && !$source instanceof \Iterator) { // fail if passing ArrayAccess without Iterator without explicit property list: // no way to perform the necessary iteration over $source later in this method. throw new Exception( 'ArrayAccess without Iterator only supported with explicit property mapping', 1422045181 ); } elseif (!$source instanceof \ArrayAccess && !is_array($source)) { throw new Exception( 'Invalid source type: ' . gettype($source), 1422045180 ); } else { $data = $source; } $propertyNameMap = $this->convertPropertyMap($propertyNameMap); // loop values, skipping mapped properties, use Trait's internal setter to set value if (!$onlyMappedProperties) { foreach ($data as $propertyName => $propertyValue) { if (!isset($propertyNameMap[$propertyName])) { try { // Note: $propertyValue is re-assigned directly from $data, again. We do // this to make sure that if an Iterator+ArrayAccess instance is given, // then the value returned from the ArrayAccess will replace the value // returned from the Iterator portion. Re-assigning the variable this // way looks redundant but serves a purpose. $propertyValue = $data[$propertyName]; $this->setPopulatedProperty($propertyName, $propertyValue, $cloneObjects); } catch (AccessException $error) { // source was another Populate; $data may contain gettable but unsettable properties. if (!$source instanceof PopulateInterface) { throw $error; } } } } } // loop the mapped properties last to ensure mapped names override default names foreach ($propertyNameMap as $sourcePropertyName => $destinationPropertyName) { // only populate properties which were passed in source values if (isset($data[$sourcePropertyName])) { $propertyValue = $data[$sourcePropertyName]; $this->setPopulatedProperty($destinationPropertyName, $propertyValue, $cloneObjects); } } }
Populate this instance using data from $source, optionally mapping properties from source to this object using $propertyNameMap and if using the property map, only populating those properties whose names were passed in the property map. To selectively populate properties without mapping their names, use a mirror array as property name map and <code>true</code> as third parameter, e.g. $object->populate($source, array('test' => 'test'), true); This causes $object to be populated using $only the "test" property from $source. @param PopulateInterface|array $source A key=>value array or another PopulateInterface instance to use as data @param array $propertyNameMap Optional array of property names supporting mapping (see README) @param boolean $onlyMappedProperties If <code>true</code> will only populate properties contained in map @param boolean $cloneObjects If <code>true</code> will use <code>clone</coode> on any object instances @throws Exception Thrown on invalid or unsupported input data @throws AccessException Thrown on problems while setting properties
entailment
public function exportGettableProperties(array $propertyNameMap = array(), $onlyMappedProperties = false) { $export = array(); $propertyNameMap = $this->convertPropertyMap($propertyNameMap); // Loop values, skipping mapped properties, use Trait's internal getter to get value. // We are suppressing Exceptions in this step in order to not disclose the reason why // a particular property could not be read. Possible causes are visibility, typos // in getter method name, non-standard getter method naming, or third-party Exceptions // being thrown from a getter. if (!$onlyMappedProperties) { $sourcePropertyNames = array_keys(get_class_vars(get_called_class())); foreach ($sourcePropertyNames as $propertyName) { if (isset($propertyNameMap[$propertyName]) || $propertyName === 'populatableAccessorMethodNames') { continue; } try { $export[$propertyName] = $this->getPopulatedProperty($propertyName); } catch (Exception $error) { // @TODO: consider logging failures w/ reason continue; } } } // loop the mapped properties last to ensure mapping overrides defaults foreach ($propertyNameMap as $sourcePropertyName => $targetPropertyName) { $export[$targetPropertyName] = $this->getPopulatedProperty($sourcePropertyName); } return $export; }
Exports properties from this object to a plain array, optionally mapping property names to array indices using a property name map - and optionally only exporting those properties whose names are included in the property name map. To selectively populate properties without mapping their names, use a mirror array as property name map and <code>true</code> as third parameter, e.g. $object->exportGettableProperties(array('test' => 'test'), true); This causes $object to be populated using $only the "test" property from $source. @param array $propertyNameMap Optional array of property names supporting mapping (see README) @param boolean $onlyMappedProperties If <code>true</code> will only populate properties contained in map @throws Exception If a property name map is passed and only mapped properties flag is <code>true</code>, any Exceptions will be passed through because this is considered an explicit attempt at access. However, if _all_ properties are requested (which happens when the only mapped properties flag is <code>false</code>), Exceptions are suppressed and erroneous properties silently ignored and removed from the output array because in this case, it is likely that the list of property names came from a source like <code>get_class_vars</code> which does not care about the presence of getter/setter methods so we must tolerate and skip failures.
entailment
private function determinePropertyAccessFunctionName($propertyName, $method) { $methodSuffix = ucfirst($propertyName); $accessMethodNames = array(); foreach ($this->populatableAccessorMethodNamePrefixes[$method] as $methodPrefix) { if (method_exists($this, $methodPrefix . $methodSuffix)) { $accessMethodNames[] = $methodPrefix . $methodSuffix; } } // special case for getter allowing the raw property name as getter function name; // see README.md about property name processing. if ($method === 'get' && method_exists($this, $propertyName)) { $accessMethodNames[] = $propertyName; } if (empty($accessMethodNames)) { throw new AccessException( 'No "' . $method . '" method(s) can be determined for property ' . $propertyName, 1422021212 ); } elseif (count($accessMethodNames) > 1) { throw new AccessException( 'Found multiple "' . $method . '" access methods for property ' . $propertyName . ' (' . implode(', ', $accessMethodNames) . ') but there must be only one!', 1424776261 ); } return (empty($accessMethodNames)) ? false : $accessMethodNames[0]; }
Determines the function name used for property access through a getter/setter. For a property named `employed`, the following methods are checked: - setEmployed() - getEmployed() If those aren't found and in order to accommodate booleans: - setIsEmployed() - getIsEmployed() - isEmployed() - employed() @param string $propertyName The name of the property on this object @param string $method Either `get` or `set` @return string|boolean Method name ready for property value getting or setting as determined by $method, <code>false</code> if no function was found.
entailment
private function setPopulatedProperty($propertyName, $value, $cloneObjects) { $method = $this->determinePropertyAccessFunctionName($propertyName, 'set'); if ($value !== null || $this->determineMethodParameterAllowsNull($method)) { if ($cloneObjects && is_object($value)) { $value = clone $value; } set_error_handler(function($errorNumber, $errorString, $errorFile, $errorLine, array $errorContext) { // error was suppressed with the @-operator if (0 === error_reporting()) { return false; } throw new \ErrorException($errorString, 0, $errorNumber, $errorFile, $errorLine); }); $this->$method($value); restore_error_handler(); } }
Sets a single property via the resolved setter method, throws a Dkd\Populate\Exception if no method could be found and $ignoreFailures was false. @param string $propertyName Name of the property to set on this instance @param mixed $value New value of the property @param boolean $cloneObjects If <code>true</code> and <code>$value</code> is an object instance, <code>clone</code> will be used on the value @throws AccessException Thrown if a viable setter method cannot be determined
entailment
private function convertPropertyMap(array $propertyNameMap) { $rebuilt = array(); foreach ($propertyNameMap as $origin => $destination) { if (is_integer($origin)) { $origin = $destination; } $rebuilt[$origin] = $destination; } return $rebuilt; }
Converts the input array if necessary: check each property defined in the array to ensure an output of an associative array regardless of the input array structure. The array can be mixed associative and numerically indexed - the output will always be associative; any entries which have numeric indexes will be returned with the property name as both index and value for that entry. The output array can then be consumed by populate/export methods. @param array $propertyNameMap Optional array of property names supporting mapping (see README) @return array The property map with expected name=>value format
entailment
public function smartALookup($hostname, $depth = 0) { $this->debug('SmartALookup for ' . $hostname . ' depth ' . $depth); // avoid recursive lookups if ($depth > 5) { return ''; } // The SmartALookup function will resolve CNAMES using the additional properties if possible $answer = $this->query($hostname, 'A'); // failed totally if ($answer === false) { return ''; } // no records at all returned if (count($answer) === 0) { return ''; } foreach ($answer as $record) { // found it if ($record->getTypeid() == 'A') { $best_answer = $record; break; } // alias if ($record->getTypeid() == 'CNAME') { $best_answer = $record; // and keep going } } if (!isset($best_answer)) { return ''; } if ($best_answer->getTypeid() == 'A') { return $best_answer->getData(); } // got an IP ok if ($best_answer->getTypeid() != 'CNAME') { return ''; } // shouldn't ever happen $newtarget = $best_answer->getData(); // this is what we now need to resolve // First is it in the additional section foreach ($this->lastadditional as $result) { if (($result->getDomain() == $hostname) && ($result->getTypeid() == 'A')) { return $result->getData(); } } // Not in the results return $this->smartALookup($newtarget, $depth + 1); }
@param string $hostname @param int $depth @return string
entailment
public function topMenu() { $topMenus = $this->collectNodes->filter(function ($value, $key) { return 0 == $value['parent_id']; }); $currentTopMenu = $this->currentTopMenu; $topMenus = $topMenus->map(function ($value, $key) use ($currentTopMenu) { if ($currentTopMenu['id'] == $value['id']) { $value['class'] = 'active'; } else { $value['class'] = ''; } return $value; })->all(); return $topMenus; }
Left sider-bar menu. @return array
entailment
protected function getCurrentTopMenuByUri($currentMenuUri) { $topMenus = $this->collectNodes->filter(function ($value, $key) { return 0 == $value['parent_id']; }); $topMenus->each(function ($item, $key) use ($currentMenuUri, &$currentTopMenu) { $currentUri = array_first(explode('/', trim($currentMenuUri, '/'))); $itemUri = array_first(explode('/', trim($item['uri'], '/'))); if ($currentUri == $itemUri) { $currentTopMenu = $item; } }); return $currentTopMenu; }
@param $currentMenuUri @return mixed
entailment
protected function grid() { return Administrator::grid(function (Grid $grid) { $grid->id('ID')->sortable(); $grid->username(trans('admin.username')); $grid->name(trans('admin.name')); $grid->roles(trans('admin.roles'))->pluck('name')->label(); $grid->created_at(trans('admin.created_at')); $grid->updated_at(trans('admin.updated_at')); $grid->actions(function (Grid\Displayers\Actions $actions) { if ($actions->getKey() == 1) { $actions->disableDelete(); } }); $grid->tools(function (Grid\Tools $tools) { $tools->batch(function (Grid\Tools\BatchActions $actions) { $actions->disableDelete(); }); }); }); }
Make a grid builder. @return Grid
entailment
public function form($id=0) { return Administrator::form(function (Form $form) { $form->display('id', 'ID'); $form->text('username', trans('admin.username'))->rules('required'); $form->text('name', trans('admin.name'))->rules('required'); $form->email('email', '邮箱')->rules('required'); $form->mobile('mobile', '手机')->rules('required'); $form->image('avatar', trans('admin.avatar')); $form->password('password', trans('admin.password'))->rules('required|confirmed'); $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required') ->default(function ($form) { return $form->model()->password; }); $form->ignore(['password_confirmation']); $form->multipleSelect('roles', trans('admin.roles'))->options(Role::all()->pluck('name', 'id')); $form->multipleSelect('permissions', trans('admin.permissions'))->options(Permission::all()->pluck('name', 'id')); $form->display('created_at', trans('admin.created_at')); $form->display('updated_at', trans('admin.updated_at')); $form->saving(function (Form $form) { if ($form->password && $form->model()->password != $form->password) { $form->password = bcrypt($form->password); } }); }); }
Make a form builder. @return Form
entailment
public function boot() { app('view')->prependNamespace('admin', __DIR__ . '/../resources/views'); // merge configs $this->mergeConfigFrom( __DIR__ . '/../config/backend.php', 'ibrand.backend' ); if ($this->app->runningInConsole()) { $this->publishes([ __DIR__ . '/../config/backend.php' => config_path('ibrand/backend.php'), ]); $this->publishes([__DIR__ . '/../resources/assets' => public_path('vendor')]); } //merge filesystem $this->setAdminDisk(); $this->registerMigrations(); $this->mapWebRoutes(); }
Boot the service provider.
entailment
public function retrieveByToken($identifier, $token) { $userModel = $this->createUserModel(); return $userModel->newQuery() ->where($userModel->getKeyName(), $identifier) ->where($userModel->getRememberTokenName(), $token) ->first(); }
Retrieve a user by their unique identifier and "remember me" token. @param mixed $identifier @param string $token @return \Illuminate\Contracts\Auth\Authenticatable|null
entailment
public function retrieveByCredentials(array $credentials) { // First we will add each credential element to the query as a where clause. // Then we can execute the query and, if we found a user, return it in a // Eloquent User "model" that will be utilized by the Guard instances. $query = $this->createUserModel()->newQuery(); foreach ($credentials as $key => $value) { if (!Str::contains($key, 'password')) { $query->where($key, $value); } } // return $query->first(); $user = $query->first(); // If the user was not found in the local database, and LDAP authentication // is enabled, and the option is set to automatically create new accounts // on first login, create the user and return it. Otherwise return what // we found, which could be a user or null. if ( is_null($user) && Settings::get('eloquent-ldap.enabled') && Settings::get('eloquent-ldap.create_accounts') ) { $user = $this->createUserFromLDAP($credentials['username']); } return $user; }
Retrieve a user by the given credentials. @param array $credentials @return \Illuminate\Contracts\Auth\Authenticatable|null
entailment
public function validateCredentials(UserContract $user, array $credentials) { $credentialsValidated = false; // If the user is set AND, either of auth_type 'internal' or with // auth_type unset or null, then validate against the stored // password hash. Otherwise if the LDAP authentication // method is enabled, try it. if ( isset($user) && ( ( isset($user->auth_type) && (Settings::get('eloquent-ldap.label_internal') === $user->auth_type) ) || ( !isset($user->auth_type) ) ) ) { $plain = $credentials['password']; $credentialsValidated = $this->hasher->check($plain, $user->getAuthPassword()); } else if ( (Settings::get('eloquent-ldap.enabled')) && (Settings::get('eloquent-ldap.label_ldap') === $user->auth_type) ) { // Validate credentials against LDAP/AD server. $credentialsValidated = $this->validateLDAPCredentials($credentials); // If validated and config set to resync group membership on login. if ( $credentialsValidated ) { // Sync user enable/disable state $this->syncEnable($user); if ( (Settings::get('eloquent-ldap.resync_on_login')) && (Settings::get('eloquent-ldap.replicate_group_membership'))) { // First, revoke membership to all groups marked to 'resync_on_login'. $this->revokeMembership($user); // Then replicate group membership. $this->replicateMembershipFromLDAP($user); } } } return $credentialsValidated; }
Validate a user against the given credentials. @param \Illuminate\Contracts\Auth\Authenticatable $user @param array $credentials @return bool
entailment
private function createUserFromLDAP($userName) { $user = null; $ldapUser = $this->getLDAPUser($userName); // If we found the user in LDAP if (true == $ldapUser ) { $firstName = $ldapUser->getFirstAttribute(Settings::get('eloquent-ldap.first_name_field')); $lastName = $ldapUser->getFirstAttribute(Settings::get('eloquent-ldap.last_name_field')); $email = $ldapUser->getFirstAttribute(Settings::get('eloquent-ldap.email_field')); $enabled = (($ldapUser->getFirstAttribute('useraccountcontrol') & 2) == 0); $userModel = $this->createUserModel(); $ldapFields = [ 'username' => $userName, 'first_name' => $firstName, 'last_name' => $lastName, 'email' => $email, 'enabled' => $enabled, ]; $validator = Validator::make($ldapFields, $userModel::getCreateValidationRules($this->app)); if ($validator->fails()) { Log::error('Validation failed for user ['.$userName.'], in [EloquentLDAPUserProvider::createUserFromLDAP].'); $messages = $validator->errors(); foreach ($messages->all() as $message) { Log::error('Validation message: ' . $message); } } else { $user = $userModel->create(array( 'username' => $userName, 'first_name' => $firstName, 'last_name' => $lastName, 'email' => $email, 'password' => 'Password handled by AD/LDAP.', 'auth_type' => Settings::get('eloquent-ldap.label_ldap'), )); if ($enabled) { $user->enabled = true; } else { $user->enabled = false; } $user->save(); if (Settings::get('eloquent-ldap.replicate_group_membership')) { $this->replicateMembershipFromLDAP($user); } } } return $user; }
Creates a local user from the information gained from the LDAP/AD server. @param $userName The name of the user to create.
entailment
private function GetLDAPConnectionOptions() { if (!isset($this->ldapConOp) || is_null($this->ldapConOp)) { // Build basic LDAP connection configuration. $this->ldapConOp = [ "account_suffix" => Settings::get('eloquent-ldap.account_suffix'), "base_dn" => Settings::get('eloquent-ldap.base_dn'), "domain_controllers" => [ Settings::get('eloquent-ldap.server') ], // config item must be an array. "admin_username" => Settings::get('eloquent-ldap.user_name'), "admin_password" => Settings::get('eloquent-ldap.password'), // "real_primarygroup" => Settings::get('eloquent-ldap.return_real_primary_group'), // "recursive_groups" => Settings::get('eloquent-ldap.recursive_groups'), // "sso" => false, // Settings::get('eloquent-ldap.sso'), // NOT SUPPORTED HARD CODED TO FALSE. "follow_referrals" => false, // Settings::get('eloquent-ldap.follow_referrals'), // NOT SUPPORTED HARD CODED TO FALSE. ]; // Create the communication option part, add the encryption and port info. if ('tls' === Settings::get('eloquent-ldap.secured')) { $comOpt = [ "use_ssl" => false, "use_tls" => true, "port" => Settings::get('eloquent-ldap.secured_port'), ]; } else if ('ssl' === Settings::get('eloquent-ldap.secured')) { $comOpt = [ "use_ssl" => true, "use_tls" => false, "port" => Settings::get('eloquent-ldap.secured_port'), ]; } else { $comOpt = [ "use_ssl" => false, "use_tls" => false, "port" => Settings::get('eloquent-ldap.port'), ]; } // Merge all options together. $this->ldapConOp = array_merge($this->ldapConOp, $comOpt); } return $this->ldapConOp; }
Builds the LDAP connection options from the configuration files. @return array
entailment
private function GetArrayValueOrDefault($array, $key, $default = null) { $value = $default; try { $value = $array[$key]; if (null === $value) { $value = $default; } } catch( Exception $ex) { $value = $default; } return $value; }
Returns the value of a key in an array, or if not found, returns the default provided. @param $array The array to return the value from. @param $key The key to lookup. @param null $default The default value to return if the key does not exist. @return The value requested or the default provided.
entailment
private function GetArrayIndexedValueOrDefault($array, $key, $index, $default = null) { $value = $default; try { $value = $this->GetArrayValueOrDefault($array, $key, $default); if ( (isset($value)) && ($value !== $default) ) { $value = $value[$index]; } } catch( Exception $ex) { $value = $default; } return $value; }
Returns the value of a key at an index in a multi-dimensional array, or if not found, returns the default provided. @param $array The array to return the value from. @param $key The key to lookup. @param $index The index of the value to return. @param null $default The default value to return if the key does not exist. @return The value requested or the default provided.
entailment
private function getLDAPUser($username) { $adldap = false; $adUser = false; try { $ldapQuery = Settings::get('eloquent-ldap.user_filter'); if (strpos($ldapQuery, self::USER_TOKEN)) { $ldapQuery = str_replace(self::USER_TOKEN, $username, $ldapQuery); } else { throw new \Exception("Invalid AD/LDAP query filter, check the configuration of 'LDAP_USER_FILTER'."); } $ldapFields = [ Settings::get('eloquent-ldap.username_field'), Settings::get('eloquent-ldap.first_name_field'), Settings::get('eloquent-ldap.last_name_field'), Settings::get('eloquent-ldap.email_field'), 'useraccountcontrol', 'dn', ]; // Build connection info. $ldapConOp = $this->GetLDAPConnectionOptions(); if (Settings::get('eloquent-ldap.debug')) { // Set LDAP debug log level - useful in DEV, dangerous in PROD!! ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); } // Connect to AD/LDAP $adldap = new Adldap(); $adldap->addProvider($ldapConOp); $provider = $adldap->connect(); // Search... $adUser = $provider->search()->select($ldapFields)->rawFilter($ldapQuery)->first(); // $adResults = $provider->search()->select($ldapFields)->rawFilter($ldapQuery)->get(); // // if (isset($adResults) && is_array($adResults) && isset($adResults[0])) { // $adResults = $adResults[0]; // } if (!$adUser) { $this->handleLDAPError($adldap); } } catch (\Exception $ex) { Log::error('Exception retrieving user information: ' . $ex->getMessage()); Log::error($ex->getTraceAsString()); } // Close connection. if (isset($provider)) { unset($provider); } // Close connection. if (isset($adldap)) { unset($adldap); } return $adUser; }
Queries the LDAP/AD server for a user. @param $userName The name of the user to get information for. @return Adldap User The user.
entailment