sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
function nusoap_xmlschema($schema='',$xml='',$namespaces=array()){
parent::nusoap_base();
$this->debug('nusoap_xmlschema class instantiated, inside constructor');
// files
$this->schema = $schema;
$this->xml = $xml;
// namespaces
$this->enclosingNamespaces = $namespaces;
$this->namespaces = array_merge($this->namespaces, $namespaces);
// parse schema file
if($schema != ''){
$this->debug('initial schema file: '.$schema);
$this->parseFile($schema, 'schema');
}
// parse xml file
if($xml != ''){
$this->debug('initial xml file: '.$xml);
$this->parseFile($xml, 'xml');
}
} | constructor
@param string $schema schema document URI
@param string $xml xml document URI
@param string $namespaces namespaces defined in enclosing XML
@access public | entailment |
function schemaCharacterData($parser, $data){
$pos = $this->depth_array[$this->depth - 1];
$this->message[$pos]['cdata'] .= $data;
} | element content handler
@param string $parser XML parser object
@param string $data element content
@access private | entailment |
function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
$this->simpleTypes[$name] = array(
'name' => $name,
'typeClass' => $typeClass,
'phpType' => $phpType,
'type' => $restrictionBase,
'enumeration' => $enumeration
);
$this->xdebug("addSimpleType $name:");
$this->appendDebug($this->varDump($this->simpleTypes[$name]));
} | adds a simple type to the schema
@param string $name
@param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
@param string $typeClass (should always be simpleType)
@param string $phpType (should always be scalar)
@param array $enumeration array of values
@access public
@see nusoap_xmlschema
@see getTypeDef | entailment |
public function offsetGet($offset)
{
$this->validateKeyType($offset);
$this->validateKeyBounds($offset);
return $this->container[$offset];
} | identical to at, implemented for ArrayAccess | entailment |
function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) {
parent::nusoap_base();
$this->name = $name;
$this->type = $type;
$this->value = $value;
$this->element_ns = $element_ns;
$this->type_ns = $type_ns;
$this->attributes = $attributes;
} | constructor
@param string $name optional name
@param mixed $type optional type name
@param mixed $value optional value
@param mixed $element_ns optional namespace of value
@param mixed $type_ns optional namespace of type
@param mixed $attributes associative array of attributes to add to element serialization
@access public | entailment |
function debug($string){
if ($this->debugLevel > 0) {
$this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n");
}
} | adds debug data to the instance debug string with formatting
@param string $string debug data
@access private | entailment |
function isArraySimpleOrStruct($val) {
$keyList = array_keys($val);
foreach ($keyList as $keyListValue) {
if (!is_int($keyListValue)) {
return 'arrayStruct';
}
}
return 'arraySimple';
} | detect if array is a simple array or a struct (associative array)
@param mixed $val The PHP array
@return string (arraySimple|arrayStruct)
@access private | entailment |
function contractQname($qname){
// get element namespace
//$this->xdebug("Contract $qname");
if (strrpos($qname, ':')) {
// get unqualified name
$name = substr($qname, strrpos($qname, ':') + 1);
// get ns
$ns = substr($qname, 0, strrpos($qname, ':'));
$p = $this->getPrefixFromNamespace($ns);
if ($p) {
return $p . ':' . $name;
}
return $qname;
} else {
return $qname;
}
} | contracts (changes namespace to prefix) a qualified name
@param string $qname qname
@return string contracted qname
@access private | entailment |
function expandQname($qname){
// get element prefix
if(strpos($qname,':') && !preg_match('/^http:\/\//',$qname)){
// get unqualified name
$name = substr(strstr($qname,':'),1);
// get ns prefix
$prefix = substr($qname,0,strpos($qname,':'));
if(isset($this->namespaces[$prefix])){
return $this->namespaces[$prefix].':'.$name;
} else {
return $qname;
}
} else {
return $qname;
}
} | expands (changes prefix to namespace) a qualified name
@param string $qname qname
@return string expanded qname
@access private | entailment |
function getNamespaceFromPrefix($prefix){
if (isset($this->namespaces[$prefix])) {
return $this->namespaces[$prefix];
}
//$this->setError("No namespace registered for prefix '$prefix'");
return false;
} | pass it a prefix, it returns a namespace
@param string $prefix The prefix
@return mixed The namespace, false if no namespace has the specified prefix
@access public | entailment |
function getmicrotime() {
if (function_exists('gettimeofday')) {
$tod = gettimeofday();
$sec = $tod['sec'];
$usec = $tod['usec'];
} else {
$sec = time();
$usec = 0;
}
return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec);
} | returns the time in ODBC canonical form with microseconds
@return string The time in ODBC canonical form with microseconds
@access public | entailment |
function nusoap_wsdlcache($cache_dir='.', $cache_lifetime=0) {
$this->fplock = array();
$this->cache_dir = $cache_dir != '' ? $cache_dir : '.';
$this->cache_lifetime = $cache_lifetime;
} | constructor
@param string $cache_dir directory for cache-files
@param integer $cache_lifetime lifetime for caching-files in seconds or 0 for unlimited
@access public | entailment |
function put($wsdl_instance) {
$filename = $this->createFilename($wsdl_instance->wsdl);
$s = serialize($wsdl_instance);
if ($this->obtainMutex($filename, "w")) {
$fp = fopen($filename, "w");
if (! $fp) {
$this->debug("Cannot write $wsdl_instance->wsdl ($filename) in cache");
$this->releaseMutex($filename);
return false;
}
fputs($fp, $s);
fclose($fp);
$this->debug("Put $wsdl_instance->wsdl ($filename) in cache");
$this->releaseMutex($filename);
return true;
} else {
$this->debug("Unable to obtain mutex for $filename in put");
}
return false;
} | adds a wsdl instance to the cache
@param object wsdl $wsdl_instance The wsdl instance to add
@return boolean WSDL successfully cached
@access public | entailment |
function releaseMutex($filename) {
$ret = flock($this->fplock[md5($filename)], LOCK_UN);
fclose($this->fplock[md5($filename)]);
unset($this->fplock[md5($filename)]);
if (! $ret) {
$this->debug("Not able to release lock for $filename");
}
return $ret;
} | releases the local mutex
@param string $filename The Filename of the Cache to lock
@return boolean Lock successfully released
@access private | entailment |
function remove($wsdl) {
$filename = $this->createFilename($wsdl);
if (!file_exists($filename)) {
$this->debug("$wsdl ($filename) not in cache to be removed");
return false;
}
// ignore errors obtaining mutex
$this->obtainMutex($filename, "w");
$ret = unlink($filename);
$this->debug("Removed ($ret) $wsdl ($filename) from cache");
$this->releaseMutex($filename);
return $ret;
} | removes a wsdl instance from the cache
@param string $wsdl The URL of the wsdl instance
@return boolean Whether there was an instance to remove
@access public | entailment |
public function groupBy($callback)
{
$group = new Map();
foreach ($this as $value) {
$key = $callback($value);
if (!$group->containsKey($key)) {
$element = $this instanceof VectorInterface ? new static([$value]) : new Vector([$value]);
$group->add(new Pair($key, $element));
} else {
$value = $group->get($key)->add($value);
$group->set($key, $value);
}
}
return $group;
} | {@inheritDoc}
@return $this | entailment |
public function indexBy($callback)
{
$group = new Map();
foreach ($this as $value) {
$key = $callback($value);
$group->set($key, $value);
}
return $group;
} | {@inheritDoc}
@return $this | entailment |
public function reduce(callable $callback, $initial = null)
{
foreach ($this as $element) {
$initial = $callback($initial, $element);
}
return $initial;
} | {@inheritdoc} | entailment |
public function set($key, $value)
{
$this->validateKeyType($key);
$this->container[$key] = $value;
return $this;
} | Stores a value into the Vector with the specified key, overwriting the
previous value associated with the key. If the key is not present,
an exception is thrown. "$vec->set($k,$v)" is semantically equivalent
to "$vec[$k] = $v" (except that set() returns the Vector).
@param $key
@param $value
@return $this | entailment |
public function setAll($items)
{
$this->validateTraversable($items);
foreach ($items as $key => $item) {
if (is_array($item)) {
$item = new static($item);
}
$this->set($key, $item);
}
return $this;
} | {@inheritdoc} | entailment |
public function removeKey($key)
{
$this->validateKeyType($key);
$this->validateKeyBounds($key);
array_splice($this->container, $key, 1);
return $this;
} | {@inheritdoc} | entailment |
public function splice($offset, $length = null)
{
if (!is_int($offset)) {
throw new \InvalidArgumentException('Parameter offset must be an integer');
}
if (!is_null($length) && !is_int($length)) {
throw new \InvalidArgumentException('Parameter len must be null or an integer');
}
$removed = is_null($length) ? array_splice($this->container, $offset) :
array_splice($this->container, $offset, $len);
// if (count($removed) > 0) {
// $this->hacklib_expireAllIterators();
// }
} | {@inheritdoc} | entailment |
public static function fromArray(array $arr)
{
$map = new static();
foreach ($arr as $k => $v) {
if (is_array($v)) {
$map[$k] = new static($v);
} else {
$map[$k] = $v;
}
}
return $map;
} | {@inheritdoc} | entailment |
public function zip($traversable)
{
if (is_array($traversable)) {
$traversable = new ImmVector($traversable);
}
if ($traversable instanceof \Traversable) {
return new static(new LazyZipIterable($this, $traversable));
} else {
throw new \InvalidArgumentException('Parameter must be an array or an instance of Traversable');
}
} | {@inheritDoc}
@return $this | entailment |
public function last()
{
if ($this->isEmpty()) {
return null;
}
$lastItem = array_slice($this->container, -1, 1);
return current($lastItem);
} | {@inheritDoc}
@return $this | entailment |
public function add($pair)
{
if (!($pair instanceof Pair)) {
throw new \InvalidArgumentException('Parameter must be an instance of Pair');
}
list($key, $value) = $pair;
$this->validateKeyExists($key);
$this->set($key, $value);
return $this;
} | {@inheritdoc} | entailment |
public function remove($element)
{
$key = array_search($element, $this->container);
if (false === $key) {
throw new \OutOfBoundsException('No element found in the collection');
}
$this->removeKey($key);
return $this;
} | {@inheritdoc} | entailment |
public function toArray()
{
$arr = [];
foreach ($this as $k => $v) {
if ($v instanceof Enumerable) {
$arr[] = $v->toArray();
} else {
$arr[] = $v;
}
}
return $arr;
} | Returns an array containing the values from this VectorLike. | entailment |
public function add($item)
{
if ($this->contains($item)) {
throw ElementAlreadyExists::duplicatedElement($item);
}
$this->container[] = $item;
return $this;
} | {@inheritdoc} | entailment |
function nusoap_client($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30, $portName = ''){
parent::nusoap_base();
$this->endpoint = $endpoint;
$this->proxyhost = $proxyhost;
$this->proxyport = $proxyport;
$this->proxyusername = $proxyusername;
$this->proxypassword = $proxypassword;
$this->timeout = $timeout;
$this->response_timeout = $response_timeout;
$this->portName = $portName;
$this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
$this->appendDebug('endpoint=' . $this->varDump($endpoint));
// make values
if($wsdl){
if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) {
$this->wsdl = $endpoint;
$this->endpoint = $this->wsdl->wsdl;
$this->wsdlFile = $this->endpoint;
$this->debug('existing wsdl instance created from ' . $this->endpoint);
$this->checkWSDL();
} else {
$this->wsdlFile = $this->endpoint;
$this->wsdl = null;
$this->debug('will use lazy evaluation of wsdl from ' . $this->endpoint);
}
$this->endpointType = 'wsdl';
} else {
$this->debug("instantiate SOAP with endpoint at $endpoint");
$this->endpointType = 'soap';
}
} | constructor
@param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object)
@param mixed $wsdl optional, set to 'wsdl' or true if using WSDL
@param string $proxyhost optional
@param string $proxyport optional
@param string $proxyusername optional
@param string $proxypassword optional
@param integer $timeout set the connection timeout
@param integer $response_timeout set the response timeout
@param string $portName optional portName in WSDL document
@access public | entailment |
function getOperationData($operation){
if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
$this->loadWSDL();
if ($this->getError())
return false;
}
if(isset($this->operations[$operation])){
return $this->operations[$operation];
}
$this->debug("No data for operation: $operation");
} | get available data pertaining to an operation
@param string $operation operation name
@return array array of data pertaining to the operation
@access public | entailment |
function setCurlOption($option, $value) {
$this->debug("setCurlOption option=$option, value=");
$this->appendDebug($this->varDump($value));
$this->curl_options[$option] = $value;
} | sets user-specified cURL options
@param mixed $option The cURL option (always integer?)
@param mixed $value The cURL option value
@access public | entailment |
function setHeaders($headers){
$this->debug("setHeaders headers=");
$this->appendDebug($this->varDump($headers));
$this->requestHeaders = $headers;
} | set the SOAP headers
@param mixed $headers String of XML with SOAP header content, or array of soapval objects for SOAP headers
@access public | entailment |
function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
$this->debug("setCredentials username=$username authtype=$authtype certRequest=");
$this->appendDebug($this->varDump($certRequest));
$this->username = $username;
$this->password = $password;
$this->authtype = $authtype;
$this->certRequest = $certRequest;
} | if authenticating, set user credentials here
@param string $username
@param string $password
@param string $authtype (basic|digest|certificate|ntlm)
@param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
@access public | entailment |
function nusoap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){
parent::nusoap_base();
$this->faultcode = $faultcode;
$this->faultactor = $faultactor;
$this->faultstring = $faultstring;
$this->faultdetail = $faultdetail;
} | constructor
@param string $faultcode (SOAP-ENV:Client | SOAP-ENV:Server)
@param string $faultactor only used when msg routed between multiple actors
@param string $faultstring human readable error message
@param mixed $faultdetail detail, typically a string or array of string | entailment |
function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30,$curl_options=null,$use_curl=false){
parent::nusoap_base();
$this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
$this->proxyhost = $proxyhost;
$this->proxyport = $proxyport;
$this->proxyusername = $proxyusername;
$this->proxypassword = $proxypassword;
$this->timeout = $timeout;
$this->response_timeout = $response_timeout;
if (is_array($curl_options))
$this->curl_options = $curl_options;
$this->use_curl = $use_curl;
$this->fetchWSDL($wsdl);
} | constructor
@param string $wsdl WSDL document URL
@param string $proxyhost
@param string $proxyport
@param string $proxyusername
@param string $proxypassword
@param integer $timeout set the connection timeout
@param integer $response_timeout set the response timeout
@param array $curl_options user-specified cURL options
@param boolean $use_curl try to use cURL
@access public | entailment |
function fetchWSDL($wsdl) {
$this->debug("parse and process WSDL path=$wsdl");
$this->wsdl = $wsdl;
// parse wsdl file
if ($this->wsdl != "") {
$this->parseWSDL($this->wsdl);
}
// imports
// TODO: handle imports more properly, grabbing them in-line and nesting them
$imported_urls = array();
$imported = 1;
while ($imported > 0) {
$imported = 0;
// Schema imports
foreach ($this->schemas as $ns => $list) {
foreach ($list as $xs) {
$wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
foreach ($xs->imports as $ns2 => $list2) {
for ($ii = 0; $ii < count($list2); $ii++) {
if (! $list2[$ii]['loaded']) {
$this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true;
$url = $list2[$ii]['location'];
if ($url != '') {
$urlparts = parse_url($url);
if (!isset($urlparts['host'])) {
$url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') .
substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
}
if (! in_array($url, $imported_urls)) {
$this->parseWSDL($url);
$imported++;
$imported_urls[] = $url;
}
} else {
$this->debug("Unexpected scenario: empty URL for unloaded import");
}
}
}
}
}
}
// WSDL imports
$wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
foreach ($this->import as $ns => $list) {
for ($ii = 0; $ii < count($list); $ii++) {
if (! $list[$ii]['loaded']) {
$this->import[$ns][$ii]['loaded'] = true;
$url = $list[$ii]['location'];
if ($url != '') {
$urlparts = parse_url($url);
if (!isset($urlparts['host'])) {
$url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') .
substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
}
if (! in_array($url, $imported_urls)) {
$this->parseWSDL($url);
$imported++;
$imported_urls[] = $url;
}
} else {
$this->debug("Unexpected scenario: empty URL for unloaded import");
}
}
}
}
}
// add new data to operation data
foreach($this->bindings as $binding => $bindingData) {
if (isset($bindingData['operations']) && is_array($bindingData['operations'])) {
foreach($bindingData['operations'] as $operation => $data) {
$this->debug('post-parse data gathering for ' . $operation);
$this->bindings[$binding]['operations'][$operation]['input'] =
isset($this->bindings[$binding]['operations'][$operation]['input']) ?
array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) :
$this->portTypes[ $bindingData['portType'] ][$operation]['input'];
$this->bindings[$binding]['operations'][$operation]['output'] =
isset($this->bindings[$binding]['operations'][$operation]['output']) ?
array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) :
$this->portTypes[ $bindingData['portType'] ][$operation]['output'];
if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){
$this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ];
}
if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){
$this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ];
}
// Set operation style if necessary, but do not override one already provided
if (isset($bindingData['style']) && !isset($this->bindings[$binding]['operations'][$operation]['style'])) {
$this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style'];
}
$this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : '';
$this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : '';
$this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : '';
}
}
}
} | fetches the WSDL document and parses it
@access public | entailment |
function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') {
if ($bindingType == 'soap') {
$bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
} elseif ($bindingType == 'soap12') {
$bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
}
// loop thru ports
foreach($this->ports as $port => $portData) {
// binding type of port matches parameter
if ($portData['bindingType'] == $bindingType) {
// loop through operations for the binding
foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
if ($opData['soapAction'] == $soapAction) {
return $opData;
}
}
}
}
} | returns an associative array of data necessary for calling an operation
@param string $soapAction soapAction for operation
@param string $bindingType type of binding eg: soap, soap12
@return array
@access public | entailment |
function getTypeDef($type, $ns) {
$this->debug("in getTypeDef: type=$type, ns=$ns");
if ((! $ns) && isset($this->namespaces['tns'])) {
$ns = $this->namespaces['tns'];
$this->debug("in getTypeDef: type namespace forced to $ns");
}
if (!isset($this->schemas[$ns])) {
foreach ($this->schemas as $ns0 => $schema0) {
if (strcasecmp($ns, $ns0) == 0) {
$this->debug("in getTypeDef: replacing schema namespace $ns with $ns0");
$ns = $ns0;
break;
}
}
}
if (isset($this->schemas[$ns])) {
$this->debug("in getTypeDef: have schema for namespace $ns");
for ($i = 0; $i < count($this->schemas[$ns]); $i++) {
$xs = &$this->schemas[$ns][$i];
$t = $xs->getTypeDef($type);
$this->appendDebug($xs->getDebug());
$xs->clearDebug();
if ($t) {
$this->debug("in getTypeDef: found type $type");
if (!isset($t['phpType'])) {
// get info for type to tack onto the element
$uqType = substr($t['type'], strrpos($t['type'], ':') + 1);
$ns = substr($t['type'], 0, strrpos($t['type'], ':'));
$etype = $this->getTypeDef($uqType, $ns);
if ($etype) {
$this->debug("found type for [element] $type:");
$this->debug($this->varDump($etype));
if (isset($etype['phpType'])) {
$t['phpType'] = $etype['phpType'];
}
if (isset($etype['elements'])) {
$t['elements'] = $etype['elements'];
}
if (isset($etype['attrs'])) {
$t['attrs'] = $etype['attrs'];
}
} else {
$this->debug("did not find type for [element] $type");
}
}
return $t;
}
}
$this->debug("in getTypeDef: did not find type $type");
} else {
$this->debug("in getTypeDef: do not have schema for namespace $ns");
}
return false;
} | returns an array of information about a given type
returns false if no type exists by the given name
typeDef = array(
'elements' => array(), // refs to elements array
'restrictionBase' => '',
'phpType' => '',
'order' => '(sequence|all)',
'attrs' => array() // refs to attributes array
)
@param string $type the type
@param string $ns namespace (not prefix) of the type
@return mixed
@access public
@see nusoap_xmlschema | entailment |
function serialize($debug = 0)
{
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xml .= "\n<definitions";
foreach($this->namespaces as $k => $v) {
$xml .= " xmlns:$k=\"$v\"";
}
// 10.9.02 - add poulter fix for wsdl and tns declarations
if (isset($this->namespaces['wsdl'])) {
$xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\"";
}
if (isset($this->namespaces['tns'])) {
$xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\"";
}
$xml .= '>';
// imports
if (sizeof($this->import) > 0) {
foreach($this->import as $ns => $list) {
foreach ($list as $ii) {
if ($ii['location'] != '') {
$xml .= '<import location="' . $ii['location'] . '" namespace="' . $ns . '" />';
} else {
$xml .= '<import namespace="' . $ns . '" />';
}
}
}
}
// types
if (count($this->schemas)>=1) {
$xml .= "\n<types>\n";
foreach ($this->schemas as $ns => $list) {
foreach ($list as $xs) {
$xml .= $xs->serializeSchema();
}
}
$xml .= '</types>';
}
// messages
if (count($this->messages) >= 1) {
foreach($this->messages as $msgName => $msgParts) {
$xml .= "\n<message name=\"" . $msgName . '">';
if(is_array($msgParts)){
foreach($msgParts as $partName => $partType) {
// print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'<br>';
if (strpos($partType, ':')) {
$typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType));
} elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) {
// print 'checking typemap: '.$this->XMLSchemaVersion.'<br>';
$typePrefix = 'xsd';
} else {
foreach($this->typemap as $ns => $types) {
if (isset($types[$partType])) {
$typePrefix = $this->getPrefixFromNamespace($ns);
}
}
if (!isset($typePrefix)) {
die("$partType has no namespace!");
}
}
$ns = $this->getNamespaceFromPrefix($typePrefix);
$localPart = $this->getLocalPart($partType);
$typeDef = $this->getTypeDef($localPart, $ns);
if ($typeDef['typeClass'] == 'element') {
$elementortype = 'element';
if (substr($localPart, -1) == '^') {
$localPart = substr($localPart, 0, -1);
}
} else {
$elementortype = 'type';
}
$xml .= "\n" . ' <part name="' . $partName . '" ' . $elementortype . '="' . $typePrefix . ':' . $localPart . '" />';
}
}
$xml .= '</message>';
}
}
// bindings & porttypes
if (count($this->bindings) >= 1) {
$binding_xml = '';
$portType_xml = '';
foreach($this->bindings as $bindingName => $attrs) {
$binding_xml .= "\n<binding name=\"" . $bindingName . '" type="tns:' . $attrs['portType'] . '">';
$binding_xml .= "\n" . ' <soap:binding style="' . $attrs['style'] . '" transport="' . $attrs['transport'] . '"/>';
$portType_xml .= "\n<portType name=\"" . $attrs['portType'] . '">';
foreach($attrs['operations'] as $opName => $opParts) {
$binding_xml .= "\n" . ' <operation name="' . $opName . '">';
$binding_xml .= "\n" . ' <soap:operation soapAction="' . $opParts['soapAction'] . '" style="'. $opParts['style'] . '"/>';
if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') {
$enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"';
} else {
$enc_style = '';
}
$binding_xml .= "\n" . ' <input><soap:body use="' . $opParts['input']['use'] . '" namespace="' . $opParts['input']['namespace'] . '"' . $enc_style . '/></input>';
if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') {
$enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"';
} else {
$enc_style = '';
}
$binding_xml .= "\n" . ' <output><soap:body use="' . $opParts['output']['use'] . '" namespace="' . $opParts['output']['namespace'] . '"' . $enc_style . '/></output>';
$binding_xml .= "\n" . ' </operation>';
$portType_xml .= "\n" . ' <operation name="' . $opParts['name'] . '"';
if (isset($opParts['parameterOrder'])) {
$portType_xml .= ' parameterOrder="' . $opParts['parameterOrder'] . '"';
}
$portType_xml .= '>';
if(isset($opParts['documentation']) && $opParts['documentation'] != '') {
$portType_xml .= "\n" . ' <documentation>' . htmlspecialchars($opParts['documentation']) . '</documentation>';
}
$portType_xml .= "\n" . ' <input message="tns:' . $opParts['input']['message'] . '"/>';
$portType_xml .= "\n" . ' <output message="tns:' . $opParts['output']['message'] . '"/>';
$portType_xml .= "\n" . ' </operation>';
}
$portType_xml .= "\n" . '</portType>';
$binding_xml .= "\n" . '</binding>';
}
$xml .= $portType_xml . $binding_xml;
}
// services
$xml .= "\n<service name=\"" . $this->serviceName . '">';
if (count($this->ports) >= 1) {
foreach($this->ports as $pName => $attrs) {
$xml .= "\n" . ' <port name="' . $pName . '" binding="tns:' . $attrs['binding'] . '">';
$xml .= "\n" . ' <soap:address location="' . $attrs['location'] . ($debug ? '?debug=1' : '') . '"/>';
$xml .= "\n" . ' </port>';
}
}
$xml .= "\n" . '</service>';
return $xml . "\n</definitions>";
} | serialize the parsed wsdl
@param mixed $debug whether to put debug=1 in endpoint URL
@return string serialization of WSDL
@access public | entailment |
function parametersMatchWrapped($type, &$parameters) {
$this->debug("in parametersMatchWrapped type=$type, parameters=");
$this->appendDebug($this->varDump($parameters));
// split type into namespace:unqualified-type
if (strpos($type, ':')) {
$uqType = substr($type, strrpos($type, ':') + 1);
$ns = substr($type, 0, strrpos($type, ':'));
$this->debug("in parametersMatchWrapped: got a prefixed type: $uqType, $ns");
if ($this->getNamespaceFromPrefix($ns)) {
$ns = $this->getNamespaceFromPrefix($ns);
$this->debug("in parametersMatchWrapped: expanded prefixed type: $uqType, $ns");
}
} else {
// TODO: should the type be compared to types in XSD, and the namespace
// set to XSD if the type matches?
$this->debug("in parametersMatchWrapped: No namespace for type $type");
$ns = '';
$uqType = $type;
}
// get the type information
if (!$typeDef = $this->getTypeDef($uqType, $ns)) {
$this->debug("in parametersMatchWrapped: $type ($uqType) is not a supported type.");
return false;
}
$this->debug("in parametersMatchWrapped: found typeDef=");
$this->appendDebug($this->varDump($typeDef));
if (substr($uqType, -1) == '^') {
$uqType = substr($uqType, 0, -1);
}
$phpType = $typeDef['phpType'];
$arrayType = (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '');
$this->debug("in parametersMatchWrapped: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: $arrayType");
// we expect a complexType or element of complexType
if ($phpType != 'struct') {
$this->debug("in parametersMatchWrapped: not a struct");
return false;
}
// see whether the parameter names match the elements
if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
$elements = 0;
$matches = 0;
foreach ($typeDef['elements'] as $name => $attrs) {
if (isset($parameters[$name])) {
$this->debug("in parametersMatchWrapped: have parameter named $name");
$matches++;
} else {
$this->debug("in parametersMatchWrapped: do not have parameter named $name");
}
$elements++;
}
$this->debug("in parametersMatchWrapped: $matches parameter names match $elements wrapped parameter names");
if ($matches == 0) {
return false;
}
return true;
}
// since there are no elements for the type, if the user passed no
// parameters, the parameters match wrapped.
$this->debug("in parametersMatchWrapped: no elements type $ns:$uqType");
return count($parameters) == 0;
} | determine whether a set of parameters are unwrapped
when they are expect to be wrapped, Microsoft-style.
@param string $type the type (element name) of the wrapper
@param array $parameters the parameter values for the SOAP call
@return boolean whether they parameters are unwrapped (and should be wrapped)
@access private | entailment |
function serializeRPCParameters($operation, $direction, $parameters, $bindingType = 'soap') {
$this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion, bindingType=$bindingType");
$this->appendDebug('parameters=' . $this->varDump($parameters));
if ($direction != 'input' && $direction != 'output') {
$this->debug('The value of the \$direction argument needs to be either "input" or "output"');
$this->setError('The value of the \$direction argument needs to be either "input" or "output"');
return false;
}
if (!$opData = $this->getOperationData($operation, $bindingType)) {
$this->debug('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
$this->setError('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
return false;
}
$this->debug('in serializeRPCParameters: opData:');
$this->appendDebug($this->varDump($opData));
// Get encoding style for output and set to current
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
$encodingStyle = $opData['output']['encodingStyle'];
$enc_style = $encodingStyle;
}
// set input params
$xml = '';
if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
$parts = &$opData[$direction]['parts'];
$part_count = sizeof($parts);
$style = $opData['style'];
$use = $opData[$direction]['use'];
$this->debug("have $part_count part(s) to serialize using $style/$use");
if (is_array($parameters)) {
$parametersArrayType = $this->isArraySimpleOrStruct($parameters);
$parameter_count = count($parameters);
$this->debug("have $parameter_count parameter(s) provided as $parametersArrayType to serialize");
// check for Microsoft-style wrapped parameters
if ($style == 'document' && $use == 'literal' && $part_count == 1 && isset($parts['parameters'])) {
$this->debug('check whether the caller has wrapped the parameters');
if ($direction == 'output' && $parametersArrayType == 'arraySimple' && $parameter_count == 1) {
// TODO: consider checking here for double-wrapping, when
// service function wraps, then NuSOAP wraps again
$this->debug("change simple array to associative with 'parameters' element");
$parameters['parameters'] = $parameters[0];
unset($parameters[0]);
}
if (($parametersArrayType == 'arrayStruct' || $parameter_count == 0) && !isset($parameters['parameters'])) {
$this->debug('check whether caller\'s parameters match the wrapped ones');
if ($this->parametersMatchWrapped($parts['parameters'], $parameters)) {
$this->debug('wrap the parameters for the caller');
$parameters = array('parameters' => $parameters);
$parameter_count = 1;
}
}
}
foreach ($parts as $name => $type) {
$this->debug("serializing part $name of type $type");
// Track encoding style
if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
$encodingStyle = $opData[$direction]['encodingStyle'];
$enc_style = $encodingStyle;
} else {
$enc_style = false;
}
// NOTE: add error handling here
// if serializeType returns false, then catch global error and fault
if ($parametersArrayType == 'arraySimple') {
$p = array_shift($parameters);
$this->debug('calling serializeType w/indexed param');
$xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
} elseif (isset($parameters[$name])) {
$this->debug('calling serializeType w/named param');
$xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
} else {
// TODO: only send nillable
$this->debug('calling serializeType w/null param');
$xml .= $this->serializeType($name, $type, null, $use, $enc_style);
}
}
} else {
$this->debug('no parameters passed.');
}
}
$this->debug("serializeRPCParameters returning: $xml");
return $xml;
} | serialize PHP values according to a WSDL message definition
contrary to the method name, this is not limited to RPC
TODO
- multi-ref serialization
- validate PHP values against type definitions, return errors if invalid
@param string $operation operation name
@param string $direction (input|output)
@param mixed $parameters parameter value(s)
@param string $bindingType (soap|soap12)
@return mixed parameters serialized as XML or false on error (e.g. operation not found)
@access public | entailment |
function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) {
$this->debug("serializeComplexTypeAttributes for XML Schema type $ns:$uqType");
$xml = '';
if (isset($typeDef['extensionBase'])) {
$nsx = $this->getPrefix($typeDef['extensionBase']);
$uqTypex = $this->getLocalPart($typeDef['extensionBase']);
if ($this->getNamespaceFromPrefix($nsx)) {
$nsx = $this->getNamespaceFromPrefix($nsx);
}
if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
$this->debug("serialize attributes for extension base $nsx:$uqTypex");
$xml .= $this->serializeComplexTypeAttributes($typeDefx, $value, $nsx, $uqTypex);
} else {
$this->debug("extension base $nsx:$uqTypex is not a supported type");
}
}
if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) {
$this->debug("serialize attributes for XML Schema type $ns:$uqType");
if (is_array($value)) {
$xvalue = $value;
} elseif (is_object($value)) {
$xvalue = get_object_vars($value);
} else {
$this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
$xvalue = array();
}
foreach ($typeDef['attrs'] as $aName => $attrs) {
if (isset($xvalue['!' . $aName])) {
$xname = '!' . $aName;
$this->debug("value provided for attribute $aName with key $xname");
} elseif (isset($xvalue[$aName])) {
$xname = $aName;
$this->debug("value provided for attribute $aName with key $xname");
} elseif (isset($attrs['default'])) {
$xname = '!' . $aName;
$xvalue[$xname] = $attrs['default'];
$this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName);
} else {
$xname = '';
$this->debug("no value provided for attribute $aName");
}
if ($xname) {
$xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\"";
}
}
} else {
$this->debug("no attributes to serialize for XML Schema type $ns:$uqType");
}
return $xml;
} | serializes the attributes for a complexType
@param array $typeDef our internal representation of an XML schema type (or element)
@param mixed $value a native PHP value (parameter value)
@param string $ns the namespace of the type
@param string $uqType the local part of the type
@return string value serialized as an XML string
@access private | entailment |
function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) {
$this->debug("in serializeComplexTypeElements for XML Schema type $ns:$uqType");
$xml = '';
if (isset($typeDef['extensionBase'])) {
$nsx = $this->getPrefix($typeDef['extensionBase']);
$uqTypex = $this->getLocalPart($typeDef['extensionBase']);
if ($this->getNamespaceFromPrefix($nsx)) {
$nsx = $this->getNamespaceFromPrefix($nsx);
}
if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
$this->debug("serialize elements for extension base $nsx:$uqTypex");
$xml .= $this->serializeComplexTypeElements($typeDefx, $value, $nsx, $uqTypex, $use, $encodingStyle);
} else {
$this->debug("extension base $nsx:$uqTypex is not a supported type");
}
}
if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
$this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType");
if (is_array($value)) {
$xvalue = $value;
} elseif (is_object($value)) {
$xvalue = get_object_vars($value);
} else {
$this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
$xvalue = array();
}
// toggle whether all elements are present - ideally should validate against schema
if (count($typeDef['elements']) != count($xvalue)){
$optionals = true;
}
foreach ($typeDef['elements'] as $eName => $attrs) {
if (!isset($xvalue[$eName])) {
if (isset($attrs['default'])) {
$xvalue[$eName] = $attrs['default'];
$this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName);
}
}
// if user took advantage of a minOccurs=0, then only serialize named parameters
if (isset($optionals)
&& (!isset($xvalue[$eName]))
&& ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true')
){
if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') {
$this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']);
}
// do nothing
$this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing");
} else {
// get value
if (isset($xvalue[$eName])) {
$v = $xvalue[$eName];
} else {
$v = null;
}
if (isset($attrs['form'])) {
$unqualified = ($attrs['form'] == 'unqualified');
} else {
$unqualified = false;
}
if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') {
$vv = $v;
foreach ($vv as $k => $v) {
if (isset($attrs['type']) || isset($attrs['ref'])) {
// serialize schema-defined type
$xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
} else {
// serialize generic type (can this ever really happen?)
$this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
$xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
}
}
} else {
if (is_null($v) && isset($attrs['minOccurs']) && $attrs['minOccurs'] == '0') {
// do nothing
} elseif (is_null($v) && isset($attrs['nillable']) && $attrs['nillable'] == 'true') {
// TODO: serialize a nil correctly, but for now serialize schema-defined type
$xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
} elseif (isset($attrs['type']) || isset($attrs['ref'])) {
// serialize schema-defined type
$xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
} else {
// serialize generic type (can this ever really happen?)
$this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
$xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
}
}
}
}
} else {
$this->debug("no elements to serialize for XML Schema type $ns:$uqType");
}
return $xml;
} | serializes the elements for a complexType
@param array $typeDef our internal representation of an XML schema type (or element)
@param mixed $value a native PHP value (parameter value)
@param string $ns the namespace of the type
@param string $uqType the local part of the type
@param string $use use for part (encoded|literal)
@param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
@return string value serialized as an XML string
@access private | entailment |
function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
$restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
$typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
$this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration);
} | adds an XML Schema simple type to the WSDL types
@param string $name
@param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
@param string $typeClass (should always be simpleType)
@param string $phpType (should always be scalar)
@param array $enumeration array of values
@see nusoap_xmlschema
@access public | entailment |
function addElement($attrs) {
$typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
$this->schemas[$typens][0]->addElement($attrs);
} | adds an element to the WSDL types
@param array $attrs attributes that must include name and type
@see nusoap_xmlschema
@access public | entailment |
function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){
if ($use == 'encoded' && $encodingStyle == '') {
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
}
if ($style == 'document') {
$elements = array();
foreach ($in as $n => $t) {
$elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
}
$this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements);
$this->addElement(array('name' => $name, 'type' => $name . 'RequestType'));
$in = array('parameters' => 'tns:' . $name . '^');
$elements = array();
foreach ($out as $n => $t) {
$elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
}
$this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements);
$this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType', 'form' => 'qualified'));
$out = array('parameters' => 'tns:' . $name . 'Response' . '^');
}
// get binding
$this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] =
array(
'name' => $name,
'binding' => $this->serviceName . 'Binding',
'endpoint' => $this->endpoint,
'soapAction' => $soapaction,
'style' => $style,
'input' => array(
'use' => $use,
'namespace' => $namespace,
'encodingStyle' => $encodingStyle,
'message' => $name . 'Request',
'parts' => $in),
'output' => array(
'use' => $use,
'namespace' => $namespace,
'encodingStyle' => $encodingStyle,
'message' => $name . 'Response',
'parts' => $out),
'namespace' => $namespace,
'transport' => 'http://schemas.xmlsoap.org/soap/http',
'documentation' => $documentation);
// add portTypes
// add messages
if($in)
{
foreach($in as $pName => $pType)
{
if(strpos($pType,':')) {
$pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
}
$this->messages[$name.'Request'][$pName] = $pType;
}
} else {
$this->messages[$name.'Request']= '0';
}
if($out)
{
foreach($out as $pName => $pType)
{
if(strpos($pType,':')) {
$pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
}
$this->messages[$name.'Response'][$pName] = $pType;
}
} else {
$this->messages[$name.'Response']= '0';
}
return true;
} | register an operation with the server
@param string $name operation (method) name
@param array $in assoc array of input values: key = param name, value = param type
@param array $out assoc array of output values: key = param name, value = param type
@param string $namespace optional The namespace for the operation
@param string $soapaction optional The soapaction for the operation
@param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically
@param string $use (encoded|literal) optional The use for the parameters (cannot mix right now)
@param string $documentation optional The description to include in the WSDL
@param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
@access public | entailment |
public function concat($Enumerable)
{
if (is_array($Enumerable)) {
$Enumerable = new ImmVector($Enumerable);
}
if ($Enumerable instanceof \Traversable) {
return new ImmVector(new LazyConcatIterator($this, $Enumerable));
} else {
throw new \InvalidArgumentException('Parameter must be an array or an instance of Traversable');
}
} | {@inheritDoc} | entailment |
public function at($key)
{
$this->validateKeyType($key);
$this->validateKeyBounds($key);
return $this->container[$key];
} | {@inheritdoc} | entailment |
public function sort(ComparerInterface $comparer = null)
{
if ($comparer === null) {
$comparer = $this->getDefaultComparer();
}
usort($this->container, array($comparer, 'compare'));
return $this;
} | Sorts the elements in the entire Collection<T> using the specified comparer.
@param ComparerInterface $comparer The ComparerInterface implementation to use when comparing elements, or null
to use the default comparer Comparer<T>.Default.
@return $this | entailment |
public function sortByKey(ComparerInterface $comparer = null)
{
if ($comparer === null) {
$comparer = $this->getDefaultComparer();
}
uksort($this->container, array($comparer, 'compare'));
return $this;
} | Sorts the keys in the entire Collection<T> using the specified comparer.
@param ComparerInterface $comparer The ComparerInterface implementation to use when comparing elements, or
null to use the default comparer Comparer<T>.Default.
@return $this | entailment |
public function addAll($items)
{
$this->validateTraversable($items);
$isMap = $items instanceof MapInterface;
foreach ($items as $key => $value) {
if (is_array($value)) {
$value = new static($value);
}
if ($isMap && !$value instanceof Pair) {
$value = new Pair($key, $value);
}
$this->add($value);
}
} | {@inheritdoc} | entailment |
public function concat($Enumerable)
{
if ($Enumerable instanceof Enumerable) {
$Enumerable = $Enumerable->toArray();
}
return new static(array_merge_recursive($this->toArray(), $Enumerable));
} | {@inheritDoc} | entailment |
function Analyze() {
$info = &$this->getid3->info;
$info['fileformat'] = 'ogg';
// Warn about illegal tags - only vorbiscomments are allowed
if (isset($info['id3v2'])) {
$info['warning'][] = 'Illegal ID3v2 tag present.';
}
if (isset($info['id3v1'])) {
$info['warning'][] = 'Illegal ID3v1 tag present.';
}
if (isset($info['ape'])) {
$info['warning'][] = 'Illegal APE tag present.';
}
// Page 1 - Stream Header
fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
$oggpageinfo = $this->ParseOggPageHeader();
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']] = $oggpageinfo;
if (ftell($this->getid3->fp) >= $this->getid3->fread_buffer_size()) {
$info['error'][] = 'Could not find start of Ogg page in the first '.$this->getid3->fread_buffer_size().' bytes (this might not be an Ogg-Vorbis file?)';
unset($info['fileformat']);
unset($info['ogg']);
return false;
}
$filedata = fread($this->getid3->fp, $oggpageinfo['page_length']);
$filedataoffset = 0;
if (substr($filedata, 0, 4) == 'fLaC') {
$info['audio']['dataformat'] = 'flac';
$info['audio']['bitrate_mode'] = 'vbr';
$info['audio']['lossless'] = true;
} elseif (substr($filedata, 1, 6) == 'vorbis') {
$this->ParseVorbisPageHeader($filedata, $filedataoffset, $oggpageinfo);
} elseif (substr($filedata, 0, 8) == 'Speex ') {
// http://www.speex.org/manual/node10.html
$info['audio']['dataformat'] = 'speex';
$info['mime_type'] = 'audio/speex';
$info['audio']['bitrate_mode'] = 'abr';
$info['audio']['lossless'] = false;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['speex_string'] = substr($filedata, $filedataoffset, 8); // hard-coded to 'Speex '
$filedataoffset += 8;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['speex_version'] = substr($filedata, $filedataoffset, 20);
$filedataoffset += 20;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['speex_version_id'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['header_size'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['rate'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['mode'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['mode_bitstream_version'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['nb_channels'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['bitrate'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['framesize'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['vbr'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['frames_per_packet'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['extra_headers'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['reserved1'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['reserved2'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['speex']['speex_version'] = trim($info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['speex_version']);
$info['speex']['sample_rate'] = $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['rate'];
$info['speex']['channels'] = $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['nb_channels'];
$info['speex']['vbr'] = (bool) $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['vbr'];
$info['speex']['band_type'] = $this->SpeexBandModeLookup($info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['mode']);
$info['audio']['sample_rate'] = $info['speex']['sample_rate'];
$info['audio']['channels'] = $info['speex']['channels'];
if ($info['speex']['vbr']) {
$info['audio']['bitrate_mode'] = 'vbr';
}
} elseif (substr($filedata, 0, 8) == "fishead\x00") {
// Ogg Skeleton version 3.0 Format Specification
// http://xiph.org/ogg/doc/skeleton.html
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['version_major'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 2));
$filedataoffset += 2;
$info['ogg']['skeleton']['fishead']['raw']['version_minor'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 2));
$filedataoffset += 2;
$info['ogg']['skeleton']['fishead']['raw']['presentationtime_numerator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['presentationtime_denominator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['basetime_numerator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['basetime_denominator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['utc'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 20));
$filedataoffset += 20;
$info['ogg']['skeleton']['fishead']['version'] = $info['ogg']['skeleton']['fishead']['raw']['version_major'].'.'.$info['ogg']['skeleton']['fishead']['raw']['version_minor'];
$info['ogg']['skeleton']['fishead']['presentationtime'] = $info['ogg']['skeleton']['fishead']['raw']['presentationtime_numerator'] / $info['ogg']['skeleton']['fishead']['raw']['presentationtime_denominator'];
$info['ogg']['skeleton']['fishead']['basetime'] = $info['ogg']['skeleton']['fishead']['raw']['basetime_numerator'] / $info['ogg']['skeleton']['fishead']['raw']['basetime_denominator'];
$info['ogg']['skeleton']['fishead']['utc'] = $info['ogg']['skeleton']['fishead']['raw']['utc'];
$counter = 0;
do {
$oggpageinfo = $this->ParseOggPageHeader();
$info['ogg']['pageheader'][$oggpageinfo['page_seqno'].'.'.$counter++] = $oggpageinfo;
$filedata = fread($this->getid3->fp, $oggpageinfo['page_length']);
fseek($this->getid3->fp, $oggpageinfo['page_end_offset'], SEEK_SET);
if (substr($filedata, 0, 8) == "fisbone\x00") {
$filedataoffset = 8;
$info['ogg']['skeleton']['fisbone']['raw']['message_header_offset'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['skeleton']['fisbone']['raw']['serial_number'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['skeleton']['fisbone']['raw']['number_header_packets'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['skeleton']['fisbone']['raw']['granulerate_numerator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fisbone']['raw']['granulerate_denominator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fisbone']['raw']['basegranule'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fisbone']['raw']['preroll'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['skeleton']['fisbone']['raw']['granuleshift'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1));
$filedataoffset += 1;
$info['ogg']['skeleton']['fisbone']['raw']['padding'] = substr($filedata, $filedataoffset, 3);
$filedataoffset += 3;
} elseif (substr($filedata, 1, 6) == 'theora') {
$info['video']['dataformat'] = 'theora';
$info['error'][] = 'Ogg Theora not correctly handled in this version of getID3 ['.$this->getid3->version().']';
//break;
} elseif (substr($filedata, 1, 6) == 'vorbis') {
$this->ParseVorbisPageHeader($filedata, $filedataoffset, $oggpageinfo);
} else {
$info['error'][] = 'unexpected';
//break;
}
//} while ($oggpageinfo['page_seqno'] == 0);
} while (($oggpageinfo['page_seqno'] == 0) && (substr($filedata, 0, 8) != "fisbone\x00"));
fseek($this->getid3->fp, $oggpageinfo['page_start_offset'], SEEK_SET);
$info['error'][] = 'Ogg Skeleton not correctly handled in this version of getID3 ['.$this->getid3->version().']';
//return false;
} else {
$info['error'][] = 'Expecting either "Speex " or "vorbis" identifier strings, found "'.substr($filedata, 0, 8).'"';
unset($info['ogg']);
unset($info['mime_type']);
return false;
}
// Page 2 - Comment Header
$oggpageinfo = $this->ParseOggPageHeader();
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']] = $oggpageinfo;
switch ($info['audio']['dataformat']) {
case 'vorbis':
$filedata = fread($this->getid3->fp, $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_length']);
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['packet_type'] = getid3_lib::LittleEndian2Int(substr($filedata, 0, 1));
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['stream_type'] = substr($filedata, 1, 6); // hard-coded to 'vorbis'
$this->ParseVorbisCommentsFilepointer();
break;
case 'flac':
$getid3_flac = new getid3_flac($this->getid3);
if (!$getid3_flac->FLACparseMETAdata()) {
$info['error'][] = 'Failed to parse FLAC headers';
return false;
}
unset($getid3_flac);
break;
case 'speex':
fseek($this->getid3->fp, $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_length'], SEEK_CUR);
$this->ParseVorbisCommentsFilepointer();
break;
}
// Last Page - Number of Samples
if (!getid3_lib::intValueSupported($info['avdataend'])) {
$info['warning'][] = 'Unable to parse Ogg end chunk file (PHP does not support file operations beyond '.round(PHP_INT_MAX / 1073741824).'GB)';
} else {
fseek($this->getid3->fp, max($info['avdataend'] - $this->getid3->fread_buffer_size(), 0), SEEK_SET);
$LastChunkOfOgg = strrev(fread($this->getid3->fp, $this->getid3->fread_buffer_size()));
if ($LastOggSpostion = strpos($LastChunkOfOgg, 'SggO')) {
fseek($this->getid3->fp, $info['avdataend'] - ($LastOggSpostion + strlen('SggO')), SEEK_SET);
$info['avdataend'] = ftell($this->getid3->fp);
$info['ogg']['pageheader']['eos'] = $this->ParseOggPageHeader();
$info['ogg']['samples'] = $info['ogg']['pageheader']['eos']['pcm_abs_position'];
if ($info['ogg']['samples'] == 0) {
$info['error'][] = 'Corrupt Ogg file: eos.number of samples == zero';
return false;
}
if (!empty($info['audio']['sample_rate'])) {
$info['ogg']['bitrate_average'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / ($info['ogg']['samples'] / $info['audio']['sample_rate']);
}
}
}
if (!empty($info['ogg']['bitrate_average'])) {
$info['audio']['bitrate'] = $info['ogg']['bitrate_average'];
} elseif (!empty($info['ogg']['bitrate_nominal'])) {
$info['audio']['bitrate'] = $info['ogg']['bitrate_nominal'];
} elseif (!empty($info['ogg']['bitrate_min']) && !empty($info['ogg']['bitrate_max'])) {
$info['audio']['bitrate'] = ($info['ogg']['bitrate_min'] + $info['ogg']['bitrate_max']) / 2;
}
if (isset($info['audio']['bitrate']) && !isset($info['playtime_seconds'])) {
if ($info['audio']['bitrate'] == 0) {
$info['error'][] = 'Corrupt Ogg file: bitrate_audio == zero';
return false;
}
$info['playtime_seconds'] = (float) ((($info['avdataend'] - $info['avdataoffset']) * 8) / $info['audio']['bitrate']);
}
if (isset($info['ogg']['vendor'])) {
$info['audio']['encoder'] = preg_replace('/^Encoded with /', '', $info['ogg']['vendor']);
// Vorbis only
if ($info['audio']['dataformat'] == 'vorbis') {
// Vorbis 1.0 starts with Xiph.Org
if (preg_match('/^Xiph.Org/', $info['audio']['encoder'])) {
if ($info['audio']['bitrate_mode'] == 'abr') {
// Set -b 128 on abr files
$info['audio']['encoder_options'] = '-b '.round($info['ogg']['bitrate_nominal'] / 1000);
} elseif (($info['audio']['bitrate_mode'] == 'vbr') && ($info['audio']['channels'] == 2) && ($info['audio']['sample_rate'] >= 44100) && ($info['audio']['sample_rate'] <= 48000)) {
// Set -q N on vbr files
$info['audio']['encoder_options'] = '-q '.$this->get_quality_from_nominal_bitrate($info['ogg']['bitrate_nominal']);
}
}
if (empty($info['audio']['encoder_options']) && !empty($info['ogg']['bitrate_nominal'])) {
$info['audio']['encoder_options'] = 'Nominal bitrate: '.intval(round($info['ogg']['bitrate_nominal'] / 1000)).'kbps';
}
}
}
return true;
} | true: return full data for all attachments; false: return no data for all attachments; integer: return data for attachments <= than this; string: save as file to this directory | entailment |
public function addTo($email, $name = '', $type = 'to')
{
$this->to[] = array('email' => $email, 'name' => $name, 'type' => $type);
return $this;
} | Add a recipient
@param string $email
@param string $name
@param string $type
@return Message | entailment |
public function addGlobalMergeVar($name, $content)
{
$this->globalMergeVars[] = array(
'name' => $name,
'content' => $content,
);
$this->setMerge(true);
return $this;
} | Set global merge variable to use for all recipients.
You can override these per recipient.
@param string $name
@param string $content
@return Message | entailment |
public function addMergeVar($recipient, $name, $content)
{
$this->mergeVars[] = array(
'rcpt' => $recipient,
'vars' => array(
array(
'name' => $name,
'content' => $content
)
)
);
$this->setMerge(true);
return $this;
} | Add per-recipient merge variable,
which override global merge variables with the same name.
@param string $recipient
@param string $name
@param string $content
@return Message | entailment |
public function addMergeVars($recipient, $data)
{
$vars = array();
foreach ( $data as $name => $content ) {
$vars[] = array('name' => $name, 'content' => $content);
}
$this->mergeVars[] = array(
'rcpt' => $recipient,
'vars' => $vars
);
return $this;
} | Add several per-recipient merge variables,
which override global merge variables with the same name.
@param string $recipient
@param array $data
@return Message | entailment |
public function addMetadata($data)
{
if (is_array($data)) {
foreach ($data as $k => $v) {
$this->metadata[$k] = $v;
}
}
else {
$this->metadata[] = $data;
}
return $this;
} | Add global metadata.
Mandrill will store this metadata and make it available for retrieval.
In addition, you can select up to 10 metadata fields to index and
make searchable using the Mandrill search api.
@param string|array $data
@return Message | entailment |
public function addRecipientMetadata($recipient, $data)
{
foreach ($this->recipientMetadata as $idx => $rcptMetadata) {
if (isset($rcptMetadata['rcpt']) && $rcptMetadata['rcpt'] == $recipient) {
if (is_array($data)) {
foreach ($data as $k => $v) {
$this->recipientMetadata[$idx]['values'][$k] = $v;
}
}
else {
$this->recipientMetadata[$idx]['values'][] = $data;
}
return $this;
}
}
$this->recipientMetadata[] = array('rcpt' => $recipient, 'values' => is_array($data) ? $data : array($data));
return $this;
} | Add Per-recipient metadata that will override the global
values specified in the metadata parameter.
@param string $recipient
@param string|array $data
@return Message | entailment |
public function addAttachment($type, $name, $data)
{
$this->attachments[] = array(
'type' => $type,
'name' => $name,
'content' => $data
);
return $this;
} | Add supported attachments to add to the message
@param string $type - the MIME type of the attachment - allowed types are text/*, image/*, and application/pdf
@param string $name - the file name of the attachment
@param string $data - base64 encoded attachment data
@return Message | entailment |
public function addImage($type, $name, $data)
{
$this->images[] = array(
'type' => $type,
'name' => $name,
'content' => $data
);
return $this;
} | Add images embedded in the message
@param string $type - the MIME type of the image - must start with "image/"
@param string $name - the Content-ID of the embedded image - use <img src="cid:THIS_VALUE"> to reference the image in your HTML content
@param string $data - base64 encoded image data
@return Message | entailment |
public function getIpVersion($ip)
{
if (false !== filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return self::IPv6;
}
else if (false !== filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return self::IPv4;
}
// invalid ip
return false;
} | Get IP verison
@param string $ip
@return integer|boolean Returns version or false on invalid address | entailment |
public function getIp6array($ip){
// expand - example: "2600:3c00::" -> "2600:3c00:0000:0000:0000:0000:0000:0000"
$hex = unpack("H*hex", inet_pton($ip));
$ipStr = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);
$ipIntArray = array();
$ipStrArray = explode(":", $ipStr);
foreach ($ipStrArray as &$value) {
$ipIntArray[] = hexdec($value);
}
return $ipIntArray;
} | Ipv6 to array
@param string $ip
@return array | entailment |
public function account()
{
$this->logger->debug("account: start");
if (empty($this->access_key)) {
throw new \Exception("access key not set");
}
$accountUrl = sprintf("%s/%s", $this->api_url, "account");
$client = new \GuzzleHttp\Client();
$result = $client->post($accountUrl, array(
'multipart' => array(
array(
'name' => 'accesskey',
'contents' => $this->access_key
)
),
'timeout' => $this->timeout
));
$contents = $result->getBody()->getContents();
$data = json_decode($contents, true);
// check for non zero staus codes
if (isset($data['flag']) && $data['flag'] > 0) {
throw new \Exception($data['errortext']);
}
return $data;
} | Check your subscription
@return array | entailment |
public function setUA($ua)
{
$this->logger->debug('setting: set useragent string to ' . $ua);
$this->ua = $ua;
return true;
} | Set the useragent string
@param string
@return bool | entailment |
public function setIP($ip)
{
$this->logger->debug('setting: set IP address to ' . $ip);
$this->ip = $ip;
return true;
} | Set the IP address
@param string
@return bool | entailment |
public function parse()
{
$this->setDBdat();
// validate
if (is_null($this->dbdat) === true) {
$this->logger->debug('db: data file not found, download the data manually from http://data.udger.com/');
return array('flag' => 3,
'errortext' => 'data file not found');
}
//ret values
$ret = array('user_agent' =>
array('ua_string' => '',
'ua_class' => '',
'ua_class_code' => '',
'ua' => '',
'ua_version' => '',
'ua_version_major' => '',
'ua_uptodate_current_version' => '',
'ua_family' => '',
'ua_family_code' => '',
'ua_family_homepage' => '',
'ua_family_vendor' => '',
'ua_family_vendor_code' => '',
'ua_family_vendor_homepage' => '',
'ua_family_icon' => '',
'ua_family_icon_big' => '',
'ua_family_info_url' => '',
'ua_engine' => '',
'os' => '',
'os_code' => '',
'os_homepage' => '',
'os_icon' => '',
'os_icon_big' => '',
'os_info_url' => '',
'os_family' => '',
'os_family_code' => '',
'os_family_vendor' => '',
'os_family_vendor_code' => '',
'os_family_vendor_homepage' => '',
'device_class' => '',
'device_class_code' => '',
'device_class_icon' => '',
'device_class_icon_big' => '',
'device_class_info_url' => '',
'device_marketname' => '',
'device_brand' => '',
'device_brand_code' => '',
'device_brand_homepage' => '',
'device_brand_icon' => '',
'device_brand_icon_big' => '',
'device_brand_info_url' => '',
'crawler_last_seen' => '',
'crawler_category' => '',
'crawler_category_code' => '',
'crawler_respect_robotstxt' => ''
),
'ip_address' =>
array('ip' => '',
'ip_ver' => '',
'ip_classification' => '',
'ip_classification_code' => '',
'ip_hostname' => '',
'ip_last_seen' => '',
'ip_country' => '',
'ip_country_code' => '',
'ip_city' => '',
'crawler_name' => '',
'crawler_ver' => '',
'crawler_ver_major' => '',
'crawler_family' => '',
'crawler_family_code' => '',
'crawler_family_homepage' => '',
'crawler_family_vendor' => '',
'crawler_family_vendor_code' => '',
'crawler_family_vendor_homepage' => '',
'crawler_family_icon' => '',
'crawler_family_info_url' => '',
'crawler_last_seen' => '',
'crawler_category' => '',
'crawler_category_code' => '',
'crawler_respect_robotstxt' => '',
'datacenter_name' => '',
'datacenter_name_code' => '',
'datacenter_homepage' => ''
)
);
if (!empty($this->ua)) {
$this->logger->debug("parse useragent string: START (useragent: " . $this->ua . ")");
$usedCache = false;
if($this->cacheEnable) {
$retCache = $this->getCache( md5($this->ua) );
if($retCache) {
$ret['user_agent'] = unserialize($retCache);
$usedCache = true;
}
}
if(!$usedCache) {
$client_id = 0;
$client_class_id = -1;
$os_id = 0;
$deviceclass_id = 0;
$ret['user_agent']['ua_string'] = $this->ua;
$ret['user_agent']['ua_class'] = 'Unrecognized';
$ret['user_agent']['ua_class_code'] = 'unrecognized';
// crawler
$q = $this->dbdat->query("SELECT udger_crawler_list.id as botid,name,ver,ver_major,last_seen,respect_robotstxt,family,family_code,family_homepage,family_icon,vendor,vendor_code,vendor_homepage,crawler_classification,crawler_classification_code
FROM udger_crawler_list
LEFT JOIN udger_crawler_class ON udger_crawler_class.id=udger_crawler_list.class_id
WHERE ua_string='" . $this->dbdat->escapeString($this->ua) . "'");
if ($r = $q->fetchArray(SQLITE3_ASSOC)) {
$this->logger->debug("parse useragent string: crawler found");
$client_class_id = 99;
$ret['user_agent']['ua_class'] = 'Crawler';
$ret['user_agent']['ua_class_code'] = 'crawler';
$ret['user_agent']['ua'] = $r['name'];
$ret['user_agent']['ua_version'] = $r['ver'];
$ret['user_agent']['ua_version_major'] = $r['ver_major'];
$ret['user_agent']['ua_family'] = $r['family'];
$ret['user_agent']['ua_family_code'] = $r['family_code'];
$ret['user_agent']['ua_family_homepage'] = $r['family_homepage'];
$ret['user_agent']['ua_family_vendor'] = $r['vendor'];
$ret['user_agent']['ua_family_vendor_code'] = $r['vendor_code'];
$ret['user_agent']['ua_family_vendor_homepage'] = $r['vendor_homepage'];
$ret['user_agent']['ua_family_icon'] = $r['family_icon'];
$ret['user_agent']['ua_family_info_url'] = "https://udger.com/resources/ua-list/bot-detail?bot=" . $r['family'] . "#id" . $r['botid'];
$ret['user_agent']['crawler_last_seen'] = $r['last_seen'];
$ret['user_agent']['crawler_category'] = $r['crawler_classification'];
$ret['user_agent']['crawler_category_code'] = $r['crawler_classification_code'];
$ret['user_agent']['crawler_respect_robotstxt'] = $r['respect_robotstxt'];
} else {
// client
$q = $this->dbdat->query("SELECT class_id,client_id,regstring,name,name_code,homepage,icon,icon_big,engine,vendor,vendor_code,vendor_homepage,uptodate_current_version,client_classification,client_classification_code
FROM udger_client_regex
JOIN udger_client_list ON udger_client_list.id=udger_client_regex.client_id
JOIN udger_client_class ON udger_client_class.id=udger_client_list.class_id
ORDER BY sequence ASC");
while ($r = $q->fetchArray(SQLITE3_ASSOC)) {
if (@preg_match($r["regstring"], $this->ua, $result)) {
$this->logger->debug("parse useragent string: client found");
$client_id = $r['client_id'];
$client_class_id = $r['class_id'];
$ret['user_agent']['ua_class'] = $r['client_classification'];
$ret['user_agent']['ua_class_code'] = $r['client_classification_code'];
if (isset($result[1])) {
$ret['user_agent']['ua'] = $r['name'] . " " . $result[1];
$ret['user_agent']['ua_version'] = $result[1];
$ver_major = explode(".", $result[1]);
$ret['user_agent']['ua_version_major'] = $ver_major[0];
} else {
$ret['user_agent']['ua'] = $r['name'];
$ret['user_agent']['ua_version'] = '';
$ret['user_agent']['ua_version_major'] = '';
}
$ret['user_agent']['ua_uptodate_current_version'] = $r['uptodate_current_version'];
$ret['user_agent']['ua_family'] = $r['name'];
$ret['user_agent']['ua_family_code'] = $r['name_code'];
$ret['user_agent']['ua_family_homepage'] = $r['homepage'];
$ret['user_agent']['ua_family_vendor'] = $r['vendor'];
$ret['user_agent']['ua_family_vendor_code'] = $r['vendor_code'];
$ret['user_agent']['ua_family_vendor_homepage'] = $r['vendor_homepage'];
$ret['user_agent']['ua_family_icon'] = $r['icon'];
$ret['user_agent']['ua_family_icon_big'] = $r['icon_big'];
$ret['user_agent']['ua_family_info_url'] = "https://udger.com/resources/ua-list/browser-detail?browser=" . $r['name'];
$ret['user_agent']['ua_engine'] = $r['engine'];
break;
}
}
// os
$q = $this->dbdat->query("SELECT os_id,regstring,family,family_code,name,name_code,homepage,icon,icon_big,vendor,vendor_code,vendor_homepage
FROM udger_os_regex
JOIN udger_os_list ON udger_os_list.id=udger_os_regex.os_id
ORDER BY sequence ASC");
while ($r = $q->fetchArray(SQLITE3_ASSOC)) {
if (@preg_match($r["regstring"], $this->ua, $result)) {
$this->logger->debug("parse useragent string: os found");
$os_id = $r['os_id'];
$ret['user_agent']['os'] = $r['name'];
$ret['user_agent']['os_code'] = $r['name_code'];
$ret['user_agent']['os_homepage'] = $r['homepage'];
$ret['user_agent']['os_icon'] = $r['icon'];
$ret['user_agent']['os_icon_big'] = $r['icon_big'];
$ret['user_agent']['os_info_url'] = "https://udger.com/resources/ua-list/os-detail?os=" . $r['name'];
$ret['user_agent']['os_family'] = $r['family'];
$ret['user_agent']['os_family_code'] = $r['family_code'];
$ret['user_agent']['os_family_vendor'] = $r['vendor'];
$ret['user_agent']['os_family_vendor_code'] = $r['vendor_code'];
$ret['user_agent']['os_family_vendor_homepage'] = $r['vendor_homepage'];
break;
}
}
// client_os_relation
if ($os_id == 0 AND $client_id != 0) {
$q = $this->dbdat->query("SELECT os_id,family,family_code,name,name_code,homepage,icon,icon_big,vendor,vendor_code,vendor_homepage
FROM udger_client_os_relation
JOIN udger_os_list ON udger_os_list.id=udger_client_os_relation.os_id
WHERE client_id=" . $client_id . " ");
if ($r = $q->fetchArray(SQLITE3_ASSOC)) {
$this->logger->debug("parse useragent string: client os relation found");
$os_id = $r['os_id'];
$ret['user_agent']['os'] = $r['name'];
$ret['user_agent']['os_code'] = $r['name_code'];
$ret['user_agent']['os_homepage'] = $r['homepage'];
$ret['user_agent']['os_icon'] = $r['icon'];
$ret['user_agent']['os_icon_big'] = $r['icon_big'];
$ret['user_agent']['os_info_url'] = "https://udger.com/resources/ua-list/os-detail?os=" . $r['name'];
$ret['user_agent']['os_family'] = $r['family'];
$ret['user_agent']['os_family_code'] = $r['family_code'];
$ret['user_agent']['os_family_vendor'] = $r['vendor'];
$ret['user_agent']['os_family_vendor_code'] = $r['vendor_code'];
$ret['user_agent']['os_family_vendor_homepage'] = $r['vendor_homepage'];
}
}
//device
$q = $this->dbdat->query("SELECT deviceclass_id,regstring,name,name_code,icon,icon_big
FROM udger_deviceclass_regex
JOIN udger_deviceclass_list ON udger_deviceclass_list.id=udger_deviceclass_regex.deviceclass_id
ORDER BY sequence ASC");
while ($r = $q->fetchArray(SQLITE3_ASSOC)) {
if (@preg_match($r["regstring"], $this->ua, $result)) {
$this->logger->debug("parse useragent string: device found by regex");
$deviceclass_id = $r['deviceclass_id'];
$ret['user_agent']['device_class'] = $r['name'];
$ret['user_agent']['device_class_code'] = $r['name_code'];
$ret['user_agent']['device_class_icon'] = $r['icon'];
$ret['user_agent']['device_class_icon_big'] = $r['icon_big'];
$ret['user_agent']['device_class_info_url'] = "https://udger.com/resources/ua-list/device-detail?device=" . $r['name'];
break;
}
}
if ($deviceclass_id == 0 AND $client_class_id != -1) {
$q = $this->dbdat->query("SELECT deviceclass_id,name,name_code,icon,icon_big
FROM udger_deviceclass_list
JOIN udger_client_class ON udger_client_class.deviceclass_id=udger_deviceclass_list.id
WHERE udger_client_class.id=" . $client_class_id . " ");
if ($r = $q->fetchArray(SQLITE3_ASSOC)) {
$this->logger->debug("parse useragent string: device found by deviceclass");
$deviceclass_id = $r['deviceclass_id'];
$ret['user_agent']['device_class'] = $r['name'];
$ret['user_agent']['device_class_code'] = $r['name_code'];
$ret['user_agent']['device_class_icon'] = $r['icon'];
$ret['user_agent']['device_class_icon_big'] = $r['icon_big'];
$ret['user_agent']['device_class_info_url'] = "https://udger.com/resources/ua-list/device-detail?device=" . $r['name'];
}
}
// device marketname
if($ret['user_agent']['os_family_code']) {
$q = $this->dbdat->query("SELECT id,regstring FROM udger_devicename_regex WHERE
((os_family_code='".$ret['user_agent']['os_family_code']."' AND os_code='-all-')
OR
(os_family_code='".$ret['user_agent']['os_family_code']."' AND os_code='".$ret['user_agent']['os_code']."'))
order by sequence");
while ($r = $q->fetchArray(SQLITE3_ASSOC)) {
@preg_match($r["regstring"],$this->ua,$result);
if(array_key_exists(1, $result)) {
$qC=$this->dbdat->query("SELECT marketname,brand_code,brand,brand_url,icon,icon_big
FROM udger_devicename_list
JOIN udger_devicename_brand ON udger_devicename_brand.id=udger_devicename_list.brand_id
WHERE regex_id=".$r["id"]." and code = '".\SQLite3::escapeString(trim($result[1]))."' COLLATE NOCASE ");
if($rC = $qC->fetchArray(SQLITE3_ASSOC)) {
$this->logger->debug("parse useragent string: device marketname found");
$ret['user_agent']['device_marketname'] = $rC['marketname'];
$ret['user_agent']['device_brand'] = $rC['brand'];
$ret['user_agent']['device_brand_code'] = $rC['brand_code'];
$ret['user_agent']['device_brand_homepage'] = $rC['brand_url'];
$ret['user_agent']['device_brand_icon'] = $rC['icon'];
$ret['user_agent']['device_brand_icon_big'] = $rC['icon_big'];
$ret['user_agent']['device_brand_info_url'] = "https://udger.com/resources/ua-list/devices-brand-detail?brand=".$rC['brand_code'];
break;
}
}
}
}
if($this->cacheEnable) {
$this->setCache( md5($this->ua) , serialize($ret['user_agent']) );
}
}
}
$this->logger->debug("parse useragent string: END, unset useragent string");
$this->ua = '';
}
if (!empty($this->ip)) {
$this->logger->debug("parse IP address: START (IP: " . $this->ip . ")");
$ret['ip_address']['ip'] = $this->ip;
$ipver = $this->ipHelper->getIpVersion($this->ip);
if ($ipver !== false) {
if ($ipver === IPInterface::IPv6) {
$this->ip = inet_ntop(inet_pton($this->ip));
$this->logger->debug("compress IP address is:" . $this->ip);
}
$ret['ip_address']['ip_ver'] = $ipver;
$q = $this->dbdat->query("SELECT udger_crawler_list.id as botid,ip_last_seen,ip_hostname,ip_country,ip_city,ip_country_code,ip_classification,ip_classification_code,
name,ver,ver_major,last_seen,respect_robotstxt,family,family_code,family_homepage,family_icon,vendor,vendor_code,vendor_homepage,crawler_classification,crawler_classification_code
FROM udger_ip_list
JOIN udger_ip_class ON udger_ip_class.id=udger_ip_list.class_id
LEFT JOIN udger_crawler_list ON udger_crawler_list.id=udger_ip_list.crawler_id
LEFT JOIN udger_crawler_class ON udger_crawler_class.id=udger_crawler_list.class_id
WHERE ip='" . $this->ip . "' ORDER BY sequence");
if ($r = $q->fetchArray(SQLITE3_ASSOC)) {
$ret['ip_address']['ip_classification'] = $r['ip_classification'];
$ret['ip_address']['ip_classification_code'] = $r['ip_classification_code'];
$ret['ip_address']['ip_last_seen'] = $r['ip_last_seen'];
$ret['ip_address']['ip_hostname'] = $r['ip_hostname'];
$ret['ip_address']['ip_country'] = $r['ip_country'];
$ret['ip_address']['ip_country_code'] = $r['ip_country_code'];
$ret['ip_address']['ip_city'] = $r['ip_city'];
$ret['ip_address']['crawler_name'] = $r['name'];
$ret['ip_address']['crawler_ver'] = $r['ver'];
$ret['ip_address']['crawler_ver_major'] = $r['ver_major'];
$ret['ip_address']['crawler_family'] = $r['family'];
$ret['ip_address']['crawler_family_code'] = $r['family_code'];
$ret['ip_address']['crawler_family_homepage'] = $r['family_homepage'];
$ret['ip_address']['crawler_family_vendor'] = $r['vendor'];
$ret['ip_address']['crawler_family_vendor_code'] = $r['vendor_code'];
$ret['ip_address']['crawler_family_vendor_homepage'] = $r['vendor_homepage'];
$ret['ip_address']['crawler_family_icon'] = $r['family_icon'];
if ($r['ip_classification_code'] == 'crawler') {
$ret['ip_address']['crawler_family_info_url'] = "https://udger.com/resources/ua-list/bot-detail?bot=" . $r['family'] . "#id" . $r['botid'];
}
$ret['ip_address']['crawler_last_seen'] = $r['last_seen'];
$ret['ip_address']['crawler_category'] = $r['crawler_classification'];
$ret['ip_address']['crawler_category_code'] = $r['crawler_classification_code'];
$ret['ip_address']['crawler_respect_robotstxt'] = $r['respect_robotstxt'];
} else {
$ret['ip_address']['ip_classification'] = 'Unrecognized';
$ret['ip_address']['ip_classification_code'] = 'unrecognized';
}
if ($this->ipHelper->getIpVersion($ret['ip_address']['ip']) === IPInterface::IPv4) {
$ipLong = $this->ipHelper->getIpLong($ret['ip_address']['ip']);
$q = $this->dbdat->query("select name,name_code,homepage
FROM udger_datacenter_range
JOIN udger_datacenter_list ON udger_datacenter_range.datacenter_id=udger_datacenter_list.id
where iplong_from <= " . $ipLong . " AND iplong_to >= " . $ipLong . " ");
if ($r = $q->fetchArray(SQLITE3_ASSOC)) {
$ret['ip_address']['datacenter_name'] = $r['name'];
$ret['ip_address']['datacenter_name_code'] = $r['name_code'];
$ret['ip_address']['datacenter_homepage'] = $r['homepage'];
}
}
else if ($this->ipHelper->getIpVersion($ret['ip_address']['ip']) === IPInterface::IPv6) {
$ipInt = $this->ipHelper->getIp6array($ret['ip_address']['ip']);
$q = $this->dbdat->query("select name,name_code,homepage
FROM udger_datacenter_range6
JOIN udger_datacenter_list ON udger_datacenter_range6.datacenter_id=udger_datacenter_list.id
where
iplong_from0 <= ".$ipInt[0]." AND iplong_to0 >= ".$ipInt[0]." AND
iplong_from1 <= ".$ipInt[1]." AND iplong_to1 >= ".$ipInt[1]." AND
iplong_from2 <= ".$ipInt[2]." AND iplong_to2 >= ".$ipInt[2]." AND
iplong_from3 <= ".$ipInt[3]." AND iplong_to3 >= ".$ipInt[3]." AND
iplong_from4 <= ".$ipInt[4]." AND iplong_to4 >= ".$ipInt[4]." AND
iplong_from5 <= ".$ipInt[5]." AND iplong_to5 >= ".$ipInt[5]." AND
iplong_from6 <= ".$ipInt[6]." AND iplong_to6 >= ".$ipInt[6]." AND
iplong_from7 <= ".$ipInt[7]." AND iplong_to7 >= ".$ipInt[7]."
");
if ($r = $q->fetchArray(SQLITE3_ASSOC)) {
$ret['ip_address']['datacenter_name'] = $r['name'];
$ret['ip_address']['datacenter_name_code'] = $r['name_code'];
$ret['ip_address']['datacenter_homepage'] = $r['homepage'];
}
}
}
$this->logger->debug("parse IP address: END, unset IP address");
$this->ip = '';
}
return $ret;
} | Parse the useragent string and/or IP
@return array | entailment |
protected function setDBdat()
{
if (is_null($this->dbdat)) {
$this->logger->debug(sprintf("db: open file: %s", $this->path));
$this->dbdat = new \SQLite3($this->path, SQLITE3_OPEN_READONLY);
}
} | Open DB file | entailment |
protected function setCache($key, $value) {
$this->logger->debug('LRUcache: set to key' . $key);
$this->cache[$key] = $value;
if (count($this->cache) > $this->cacheSize) {
array_shift($this->cache);
}
} | LRU cashe set | entailment |
protected function getCache($key) {
$this->logger->debug('LRUcache: get key' . $key);
if ( ! isset($this->cache[$key])) {
$this->logger->debug('LRUcache: key' . $key . ' Not Found' );
return null;
}
// Put the value gotten to last.
$tmpValue = $this->cache[$key];
unset($this->cache[$key]);
$this->cache[$key] = $tmpValue;
$this->logger->debug('LRUcache: key' . $key . ' Found' );
return $tmpValue;
} | LRU cashe get | entailment |
public function setCacheEnable($set)
{
$this->cacheEnable = $set;
$log = $set ? 'true' : 'false';
$this->logger->debug('LRUcache: enable/disable: ' . $log );
return true;
} | Set LRU cache enable/disable
@param bool
@return bool | entailment |
public function setCacheSize($size)
{
$this->cacheSize = $size;
$this->logger->debug('LRUcache: set size: ' . $size );
return true;
} | Set LRU cache enable/disable
@param Int
@return bool | entailment |
public function setDataFile($path)
{
if (false === file_exists($path)) {
throw new \Exception(sprintf("%s does not exist", $path));
}
$this->path = $path;
return true;
} | Set path to sqlite file
@param string
@return bool | entailment |
public function setAccessKey($access_key)
{
$this->logger->debug('setting: set accesskey to ' . $access_key);
$this->access_key = $access_key;
return true;
} | Set the account access key
@param string
@return bool | entailment |
public function handleRequest(Request $request): Promise {
$method = $request->getMethod();
$path = \rawurldecode($request->getUri()->getPath());
$toMatch = "{$method}\0{$path}";
if (null === $match = $this->cache->get($toMatch)) {
$match = $this->routeDispatcher->dispatch($method, $path);
$this->cache->put($toMatch, $match);
}
switch ($match[0]) {
case Dispatcher::FOUND:
/**
* @var RequestHandler $requestHandler
* @var string[] $routeArgs
*/
list(, $requestHandler, $routeArgs) = $match;
$request->setAttribute(self::class, $routeArgs);
return $requestHandler->handleRequest($request);
case Dispatcher::NOT_FOUND:
if ($this->fallback !== null) {
return $this->fallback->handleRequest($request);
}
return $this->makeNotFoundResponse($request);
case Dispatcher::METHOD_NOT_ALLOWED:
return $this->makeMethodNotAllowedResponse($match[1], $request);
default:
// @codeCoverageIgnoreStart
throw new \UnexpectedValueException(
"Encountered unexpected dispatcher code: " . $match[0]
);
// @codeCoverageIgnoreEnd
}
} | Route a request and dispatch it to the appropriate handler.
@param Request $request
@return Promise<\Amp\Http\Server\Response> | entailment |
private function makeNotFoundResponse(Request $request): Promise {
return $this->errorHandler->handleError(Status::NOT_FOUND, null, $request);
} | Create a response if no routes matched and no fallback has been set.
@param Request $request
@return Promise<\Amp\Http\Server\Response> | entailment |
private function makeMethodNotAllowedResponse(array $methods, Request $request): Promise {
return call(function () use ($methods, $request) {
/** @var \Amp\Http\Server\Response $response */
$response = yield $this->errorHandler->handleError(Status::METHOD_NOT_ALLOWED, null, $request);
$response->setHeader("allow", \implode(", ", $methods));
return $response;
});
} | Create a response if the requested method is not allowed for the matched path.
@param string[] $methods
@param Request $request
@return Promise<\Amp\Http\Server\Response> | entailment |
public function merge(self $router) {
if ($this->running) {
throw new \Error("Cannot merge routers after the server has started");
}
foreach ($router->routes as $route) {
$route[1] = \ltrim($router->prefix, "/") . $route[1];
$route[2] = Middleware\stack($route[2], ...$router->middlewares);
$this->routes[] = $route;
}
$this->observers->addAll($router->observers);
} | Merge another router's routes into this router.
Doing so might improve performance for request dispatching.
@param self $router Router to merge. | entailment |
public function prefix(string $prefix) {
if ($this->running) {
throw new \Error("Cannot alter routes after the server has started");
}
$prefix = \trim($prefix, "/");
if ($prefix !== "") {
$this->prefix = "/" . $prefix . $this->prefix;
}
} | Prefix all currently defined routes with a given prefix.
If this method is called multiple times, the second prefix will be before the first prefix and so on.
@param string $prefix Path segment to prefix, leading and trailing slashes will be normalized. | entailment |
public function addRoute(string $method, string $uri, RequestHandler $requestHandler, Middleware ...$middlewares) {
if ($this->running) {
throw new \Error(
"Cannot add routes once the server has started"
);
}
if ($method === "") {
throw new \Error(
__METHOD__ . "() requires a non-empty string HTTP method at Argument 1"
);
}
if ($requestHandler instanceof ServerObserver) {
$this->observers->attach($requestHandler);
}
if (!empty($middlewares)) {
foreach ($middlewares as $middleware) {
if ($middleware instanceof ServerObserver) {
$this->observers->attach($middleware);
}
}
$requestHandler = Middleware\stack($requestHandler, ...$middlewares);
}
$this->routes[] = [$method, \ltrim($uri, "/"), $requestHandler];
} | Define an application route.
Matched URI route arguments are made available to request handlers as a request attribute
which may be accessed with:
$request->getAttribute(Router::class)
Route URIs ending in "/?" (without the quotes) allow a URI match with or without
the trailing slash. Temporary redirects are used to redirect to the canonical URI
(with a trailing slash) to avoid search engine duplicate content penalties.
@param string $method The HTTP method verb for which this route applies.
@param string $uri The string URI.
@param RequestHandler $requestHandler Request handler invoked on a route match.
@param Middleware[] ...$middlewares
@throws \Error If the server has started, or if $method is empty. | entailment |
public function stack(Middleware ...$middlewares) {
if ($this->running) {
throw new \Error("Cannot set middlewares after the server has started");
}
$this->middlewares = array_merge($middlewares, $this->middlewares);
} | Specifies a set of middlewares that is applied to every route, but will not be applied to the fallback request
handler.
All middlewares are called in the order they're passed, so the first middleware is the outer middleware.
On repeated calls, the later call will wrap the passed middlewares around the previous stack. This ensures a
router can use `stack()` and then another entity can wrap a router with additional middlewares.
@param Middleware[] ...$middlewares
@throws \Error If the server has started. | entailment |
function analyze($filename) {
try {
if (!$this->openfile($filename)) {
return $this->info;
}
// Handle tags
foreach (array('id3v2'=>'id3v2', 'id3v1'=>'id3v1', 'apetag'=>'ape', 'lyrics3'=>'lyrics3') as $tag_name => $tag_key) {
$option_tag = 'option_tag_'.$tag_name;
if ($this->$option_tag) {
$this->include_module('tag.'.$tag_name);
try {
$tag_class = 'getid3_'.$tag_name;
$tag = new $tag_class($this);
$tag->Analyze();
}
catch (getid3_exception $e) {
throw $e;
}
}
}
if (isset($this->info['id3v2']['tag_offset_start'])) {
$this->info['avdataoffset'] = max($this->info['avdataoffset'], $this->info['id3v2']['tag_offset_end']);
}
foreach (array('id3v1'=>'id3v1', 'apetag'=>'ape', 'lyrics3'=>'lyrics3') as $tag_name => $tag_key) {
if (isset($this->info[$tag_key]['tag_offset_start'])) {
$this->info['avdataend'] = min($this->info['avdataend'], $this->info[$tag_key]['tag_offset_start']);
}
}
// ID3v2 detection (NOT parsing), even if ($this->option_tag_id3v2 == false) done to make fileformat easier
if (!$this->option_tag_id3v2) {
fseek($this->fp, 0, SEEK_SET);
$header = fread($this->fp, 10);
if ((substr($header, 0, 3) == 'ID3') && (strlen($header) == 10)) {
$this->info['id3v2']['header'] = true;
$this->info['id3v2']['majorversion'] = ord($header{3});
$this->info['id3v2']['minorversion'] = ord($header{4});
$this->info['avdataoffset'] += getid3_lib::BigEndian2Int(substr($header, 6, 4), 1) + 10; // length of ID3v2 tag in 10-byte header doesn't include 10-byte header length
}
}
// read 32 kb file data
fseek($this->fp, $this->info['avdataoffset'], SEEK_SET);
$formattest = fread($this->fp, 32774);
// determine format
$determined_format = $this->GetFileFormat($formattest, $filename);
// unable to determine file format
if (!$determined_format) {
fclose($this->fp);
return $this->error('unable to determine file format');
}
// check for illegal ID3 tags
if (isset($determined_format['fail_id3']) && (in_array('id3v1', $this->info['tags']) || in_array('id3v2', $this->info['tags']))) {
if ($determined_format['fail_id3'] === 'ERROR') {
fclose($this->fp);
return $this->error('ID3 tags not allowed on this file type.');
} elseif ($determined_format['fail_id3'] === 'WARNING') {
$this->warning('ID3 tags not allowed on this file type.');
}
}
// check for illegal APE tags
if (isset($determined_format['fail_ape']) && in_array('ape', $this->info['tags'])) {
if ($determined_format['fail_ape'] === 'ERROR') {
fclose($this->fp);
return $this->error('APE tags not allowed on this file type.');
} elseif ($determined_format['fail_ape'] === 'WARNING') {
$this->warning('APE tags not allowed on this file type.');
}
}
// set mime type
$this->info['mime_type'] = $determined_format['mime_type'];
// supported format signature pattern detected, but module deleted
if (!file_exists(GETID3_INCLUDEPATH.$determined_format['include'])) {
fclose($this->fp);
return $this->error('Format not supported, module "'.$determined_format['include'].'" was removed.');
}
// module requires iconv support
// Check encoding/iconv support
if (!empty($determined_format['iconv_req']) && !function_exists('iconv') && !in_array($this->encoding, array('ISO-8859-1', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'UTF-16'))) {
$errormessage = 'iconv() support is required for this module ('.$determined_format['include'].') for encodings other than ISO-8859-1, UTF-8, UTF-16LE, UTF16-BE, UTF-16. ';
if (GETID3_OS_ISWINDOWS) {
$errormessage .= 'PHP does not have iconv() support. Please enable php_iconv.dll in php.ini, and copy iconv.dll from c:/php/dlls to c:/windows/system32';
} else {
$errormessage .= 'PHP is not compiled with iconv() support. Please recompile with the --with-iconv switch';
}
return $this->error($errormessage);
}
// include module
include_once(GETID3_INCLUDEPATH.$determined_format['include']);
// instantiate module class
$class_name = 'getid3_'.$determined_format['module'];
if (!class_exists($class_name)) {
return $this->error('Format not supported, module "'.$determined_format['include'].'" is corrupt.');
}
//if (isset($determined_format['option'])) {
// //$class = new $class_name($this->fp, $this->info, $determined_format['option']);
//} else {
//$class = new $class_name($this->fp, $this->info);
$class = new $class_name($this);
//}
if (!empty($determined_format['set_inline_attachments'])) {
$class->inline_attachments = $this->option_save_attachments;
}
$class->Analyze();
unset($class);
// close file
fclose($this->fp);
// process all tags - copy to 'tags' and convert charsets
if ($this->option_tags_process) {
$this->HandleAllTags();
}
// perform more calculations
if ($this->option_extra_info) {
$this->ChannelsBitratePlaytimeCalculations();
$this->CalculateCompressionRatioVideo();
$this->CalculateCompressionRatioAudio();
$this->CalculateReplayGain();
$this->ProcessAudioStreams();
}
// get the MD5 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
if ($this->option_md5_data) {
// do not cald md5_data if md5_data_source is present - set by flac only - future MPC/SV8 too
if (!$this->option_md5_data_source || empty($this->info['md5_data_source'])) {
$this->getHashdata('md5');
}
}
// get the SHA1 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
if ($this->option_sha1_data) {
$this->getHashdata('sha1');
}
// remove undesired keys
$this->CleanUp();
} catch (Exception $e) {
$this->error('Caught exception: '.$e->getMessage());
}
// return info array
return $this->info;
} | public: analyze file | entailment |
function error($message) {
$this->CleanUp();
if (!isset($this->info['error'])) {
$this->info['error'] = array();
}
$this->info['error'][] = $message;
return $this->info;
} | private: error handling | entailment |
function GetFileFormatArray() {
static $format_info = array();
if (empty($format_info)) {
$format_info = array(
// Audio formats
// AC-3 - audio - Dolby AC-3 / Dolby Digital
'ac3' => array(
'pattern' => '^\x0B\x77',
'group' => 'audio',
'module' => 'ac3',
'mime_type' => 'audio/ac3',
),
// AAC - audio - Advanced Audio Coding (AAC) - ADIF format
'adif' => array(
'pattern' => '^ADIF',
'group' => 'audio',
'module' => 'aac',
'mime_type' => 'application/octet-stream',
'fail_ape' => 'WARNING',
),
// AA - audio - Audible Audiobook
'adts' => array(
'pattern' => '^.{4}\x57\x90\x75\x36',
'group' => 'audio',
'module' => 'aa',
'mime_type' => 'audio/audible ',
),
// AAC - audio - Advanced Audio Coding (AAC) - ADTS format (very similar to MP3)
'adts' => array(
'pattern' => '^\xFF[\xF0-\xF1\xF8-\xF9]',
'group' => 'audio',
'module' => 'aac',
'mime_type' => 'application/octet-stream',
'fail_ape' => 'WARNING',
),
// AU - audio - NeXT/Sun AUdio (AU)
'au' => array(
'pattern' => '^\.snd',
'group' => 'audio',
'module' => 'au',
'mime_type' => 'audio/basic',
),
// AVR - audio - Audio Visual Research
'avr' => array(
'pattern' => '^2BIT',
'group' => 'audio',
'module' => 'avr',
'mime_type' => 'application/octet-stream',
),
// BONK - audio - Bonk v0.9+
'bonk' => array(
'pattern' => '^\x00(BONK|INFO|META| ID3)',
'group' => 'audio',
'module' => 'bonk',
'mime_type' => 'audio/xmms-bonk',
),
// DSS - audio - Digital Speech Standard
'dss' => array(
'pattern' => '^[\x02-\x03]dss',
'group' => 'audio',
'module' => 'dss',
'mime_type' => 'application/octet-stream',
),
// DTS - audio - Dolby Theatre System
'dts' => array(
'pattern' => '^\x7F\xFE\x80\x01',
'group' => 'audio',
'module' => 'dts',
'mime_type' => 'audio/dts',
),
// FLAC - audio - Free Lossless Audio Codec
'flac' => array(
'pattern' => '^fLaC',
'group' => 'audio',
'module' => 'flac',
'mime_type' => 'audio/x-flac',
'set_inline_attachments' => true,
),
// LA - audio - Lossless Audio (LA)
'la' => array(
'pattern' => '^LA0[2-4]',
'group' => 'audio',
'module' => 'la',
'mime_type' => 'application/octet-stream',
),
// LPAC - audio - Lossless Predictive Audio Compression (LPAC)
'lpac' => array(
'pattern' => '^LPAC',
'group' => 'audio',
'module' => 'lpac',
'mime_type' => 'application/octet-stream',
),
// MIDI - audio - MIDI (Musical Instrument Digital Interface)
'midi' => array(
'pattern' => '^MThd',
'group' => 'audio',
'module' => 'midi',
'mime_type' => 'audio/midi',
),
// MAC - audio - Monkey's Audio Compressor
'mac' => array(
'pattern' => '^MAC ',
'group' => 'audio',
'module' => 'monkey',
'mime_type' => 'application/octet-stream',
),
// has been known to produce false matches in random files (e.g. JPEGs), leave out until more precise matching available
// // MOD - audio - MODule (assorted sub-formats)
// 'mod' => array(
// 'pattern' => '^.{1080}(M\\.K\\.|M!K!|FLT4|FLT8|[5-9]CHN|[1-3][0-9]CH)',
// 'group' => 'audio',
// 'module' => 'mod',
// 'option' => 'mod',
// 'mime_type' => 'audio/mod',
// ),
// MOD - audio - MODule (Impulse Tracker)
'it' => array(
'pattern' => '^IMPM',
'group' => 'audio',
'module' => 'mod',
//'option' => 'it',
'mime_type' => 'audio/it',
),
// MOD - audio - MODule (eXtended Module, various sub-formats)
'xm' => array(
'pattern' => '^Extended Module',
'group' => 'audio',
'module' => 'mod',
//'option' => 'xm',
'mime_type' => 'audio/xm',
),
// MOD - audio - MODule (ScreamTracker)
's3m' => array(
'pattern' => '^.{44}SCRM',
'group' => 'audio',
'module' => 'mod',
//'option' => 's3m',
'mime_type' => 'audio/s3m',
),
// MPC - audio - Musepack / MPEGplus
'mpc' => array(
'pattern' => '^(MPCK|MP\+|[\x00\x01\x10\x11\x40\x41\x50\x51\x80\x81\x90\x91\xC0\xC1\xD0\xD1][\x20-37][\x00\x20\x40\x60\x80\xA0\xC0\xE0])',
'group' => 'audio',
'module' => 'mpc',
'mime_type' => 'audio/x-musepack',
),
// MP3 - audio - MPEG-audio Layer 3 (very similar to AAC-ADTS)
'mp3' => array(
'pattern' => '^\xFF[\xE2-\xE7\xF2-\xF7\xFA-\xFF][\x00-\x0B\x10-\x1B\x20-\x2B\x30-\x3B\x40-\x4B\x50-\x5B\x60-\x6B\x70-\x7B\x80-\x8B\x90-\x9B\xA0-\xAB\xB0-\xBB\xC0-\xCB\xD0-\xDB\xE0-\xEB\xF0-\xFB]',
'group' => 'audio',
'module' => 'mp3',
'mime_type' => 'audio/mpeg',
),
// OFR - audio - OptimFROG
'ofr' => array(
'pattern' => '^(\*RIFF|OFR)',
'group' => 'audio',
'module' => 'optimfrog',
'mime_type' => 'application/octet-stream',
),
// RKAU - audio - RKive AUdio compressor
'rkau' => array(
'pattern' => '^RKA',
'group' => 'audio',
'module' => 'rkau',
'mime_type' => 'application/octet-stream',
),
// SHN - audio - Shorten
'shn' => array(
'pattern' => '^ajkg',
'group' => 'audio',
'module' => 'shorten',
'mime_type' => 'audio/xmms-shn',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// TTA - audio - TTA Lossless Audio Compressor (http://tta.corecodec.org)
'tta' => array(
'pattern' => '^TTA', // could also be '^TTA(\x01|\x02|\x03|2|1)'
'group' => 'audio',
'module' => 'tta',
'mime_type' => 'application/octet-stream',
),
// VOC - audio - Creative Voice (VOC)
'voc' => array(
'pattern' => '^Creative Voice File',
'group' => 'audio',
'module' => 'voc',
'mime_type' => 'audio/voc',
),
// VQF - audio - transform-domain weighted interleave Vector Quantization Format (VQF)
'vqf' => array(
'pattern' => '^TWIN',
'group' => 'audio',
'module' => 'vqf',
'mime_type' => 'application/octet-stream',
),
// WV - audio - WavPack (v4.0+)
'wv' => array(
'pattern' => '^wvpk',
'group' => 'audio',
'module' => 'wavpack',
'mime_type' => 'application/octet-stream',
),
// Audio-Video formats
// ASF - audio/video - Advanced Streaming Format, Windows Media Video, Windows Media Audio
'asf' => array(
'pattern' => '^\x30\x26\xB2\x75\x8E\x66\xCF\x11\xA6\xD9\x00\xAA\x00\x62\xCE\x6C',
'group' => 'audio-video',
'module' => 'asf',
'mime_type' => 'video/x-ms-asf',
'iconv_req' => false,
),
// BINK - audio/video - Bink / Smacker
'bink' => array(
'pattern' => '^(BIK|SMK)',
'group' => 'audio-video',
'module' => 'bink',
'mime_type' => 'application/octet-stream',
),
// FLV - audio/video - FLash Video
'flv' => array(
'pattern' => '^FLV\x01',
'group' => 'audio-video',
'module' => 'flv',
'mime_type' => 'video/x-flv',
),
// MKAV - audio/video - Mastroka
'matroska' => array(
'pattern' => '^\x1A\x45\xDF\xA3',
'group' => 'audio-video',
'module' => 'matroska',
'mime_type' => 'video/x-matroska', // may also be audio/x-matroska
'set_inline_attachments' => true,
),
// MPEG - audio/video - MPEG (Moving Pictures Experts Group)
'mpeg' => array(
'pattern' => '^\x00\x00\x01(\xBA|\xB3)',
'group' => 'audio-video',
'module' => 'mpeg',
'mime_type' => 'video/mpeg',
),
// NSV - audio/video - Nullsoft Streaming Video (NSV)
'nsv' => array(
'pattern' => '^NSV[sf]',
'group' => 'audio-video',
'module' => 'nsv',
'mime_type' => 'application/octet-stream',
),
// Ogg - audio/video - Ogg (Ogg-Vorbis, Ogg-FLAC, Speex, Ogg-Theora(*), Ogg-Tarkin(*))
'ogg' => array(
'pattern' => '^OggS',
'group' => 'audio',
'module' => 'ogg',
'mime_type' => 'application/ogg',
'fail_id3' => 'WARNING',
'fail_ape' => 'WARNING',
'set_inline_attachments' => true,
),
// QT - audio/video - Quicktime
'quicktime' => array(
'pattern' => '^.{4}(cmov|free|ftyp|mdat|moov|pnot|skip|wide)',
'group' => 'audio-video',
'module' => 'quicktime',
'mime_type' => 'video/quicktime',
),
// RIFF - audio/video - Resource Interchange File Format (RIFF) / WAV / AVI / CD-audio / SDSS = renamed variant used by SmartSound QuickTracks (www.smartsound.com) / FORM = Audio Interchange File Format (AIFF)
'riff' => array(
'pattern' => '^(RIFF|SDSS|FORM)',
'group' => 'audio-video',
'module' => 'riff',
'mime_type' => 'audio/x-wave',
'fail_ape' => 'WARNING',
),
// Real - audio/video - RealAudio, RealVideo
'real' => array(
'pattern' => '^(\\.RMF|\\.ra)',
'group' => 'audio-video',
'module' => 'real',
'mime_type' => 'audio/x-realaudio',
),
// SWF - audio/video - ShockWave Flash
'swf' => array(
'pattern' => '^(F|C)WS',
'group' => 'audio-video',
'module' => 'swf',
'mime_type' => 'application/x-shockwave-flash',
),
// Still-Image formats
// BMP - still image - Bitmap (Windows, OS/2; uncompressed, RLE8, RLE4)
'bmp' => array(
'pattern' => '^BM',
'group' => 'graphic',
'module' => 'bmp',
'mime_type' => 'image/bmp',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// GIF - still image - Graphics Interchange Format
'gif' => array(
'pattern' => '^GIF',
'group' => 'graphic',
'module' => 'gif',
'mime_type' => 'image/gif',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// JPEG - still image - Joint Photographic Experts Group (JPEG)
'jpg' => array(
'pattern' => '^\xFF\xD8\xFF',
'group' => 'graphic',
'module' => 'jpg',
'mime_type' => 'image/jpeg',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// PCD - still image - Kodak Photo CD
'pcd' => array(
'pattern' => '^.{2048}PCD_IPI\x00',
'group' => 'graphic',
'module' => 'pcd',
'mime_type' => 'image/x-photo-cd',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// PNG - still image - Portable Network Graphics (PNG)
'png' => array(
'pattern' => '^\x89\x50\x4E\x47\x0D\x0A\x1A\x0A',
'group' => 'graphic',
'module' => 'png',
'mime_type' => 'image/png',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// SVG - still image - Scalable Vector Graphics (SVG)
'svg' => array(
'pattern' => '(<!DOCTYPE svg PUBLIC |xmlns="http:\/\/www\.w3\.org\/2000\/svg")',
'group' => 'graphic',
'module' => 'svg',
'mime_type' => 'image/svg+xml',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// TIFF - still image - Tagged Information File Format (TIFF)
'tiff' => array(
'pattern' => '^(II\x2A\x00|MM\x00\x2A)',
'group' => 'graphic',
'module' => 'tiff',
'mime_type' => 'image/tiff',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// EFAX - still image - eFax (TIFF derivative)
'bmp' => array(
'pattern' => '^\xDC\xFE',
'group' => 'graphic',
'module' => 'efax',
'mime_type' => 'image/efax',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// Data formats
// ISO - data - International Standards Organization (ISO) CD-ROM Image
'iso' => array(
'pattern' => '^.{32769}CD001',
'group' => 'misc',
'module' => 'iso',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
'iconv_req' => false,
),
// RAR - data - RAR compressed data
'rar' => array(
'pattern' => '^Rar\!',
'group' => 'archive',
'module' => 'rar',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// SZIP - audio/data - SZIP compressed data
'szip' => array(
'pattern' => '^SZ\x0A\x04',
'group' => 'archive',
'module' => 'szip',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// TAR - data - TAR compressed data
'tar' => array(
'pattern' => '^.{100}[0-9\x20]{7}\x00[0-9\x20]{7}\x00[0-9\x20]{7}\x00[0-9\x20\x00]{12}[0-9\x20\x00]{12}',
'group' => 'archive',
'module' => 'tar',
'mime_type' => 'application/x-tar',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// GZIP - data - GZIP compressed data
'gz' => array(
'pattern' => '^\x1F\x8B\x08',
'group' => 'archive',
'module' => 'gzip',
'mime_type' => 'application/x-gzip',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// ZIP - data - ZIP compressed data
'zip' => array(
'pattern' => '^PK\x03\x04',
'group' => 'archive',
'module' => 'zip',
'mime_type' => 'application/zip',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// Misc other formats
// PAR2 - data - Parity Volume Set Specification 2.0
'par2' => array (
'pattern' => '^PAR2\x00PKT',
'group' => 'misc',
'module' => 'par2',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// PDF - data - Portable Document Format
'pdf' => array(
'pattern' => '^\x25PDF',
'group' => 'misc',
'module' => 'pdf',
'mime_type' => 'application/pdf',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// MSOFFICE - data - ZIP compressed data
'msoffice' => array(
'pattern' => '^\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1', // D0CF11E == DOCFILE == Microsoft Office Document
'group' => 'misc',
'module' => 'msoffice',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// CUE - data - CUEsheet (index to single-file disc images)
'cue' => array(
'pattern' => '', // empty pattern means cannot be automatically detected, will fall through all other formats and match based on filename and very basic file contents
'group' => 'misc',
'module' => 'cue',
'mime_type' => 'application/octet-stream',
),
);
}
return $format_info;
} | return array containing information about all supported formats | entailment |
function CharConvert(&$array, $encoding) {
// identical encoding - end here
if ($encoding == $this->encoding) {
return;
}
// loop thru array
foreach ($array as $key => $value) {
// go recursive
if (is_array($value)) {
$this->CharConvert($array[$key], $encoding);
}
// convert string
elseif (is_string($value)) {
$array[$key] = trim(getid3_lib::iconv_fallback($encoding, $this->encoding, $value));
}
}
} | converts array to $encoding charset from $this->encoding | entailment |
public function AnalyzeString(&$string) {
// Enter string mode
$this->data_string_flag = true;
$this->data_string = $string;
// Save info
$saved_avdataoffset = $this->getid3->info['avdataoffset'];
$saved_avdataend = $this->getid3->info['avdataend'];
$saved_filesize = $this->getid3->info['filesize'];
// Reset some info
$this->getid3->info['avdataoffset'] = 0;
$this->getid3->info['avdataend'] = $this->getid3->info['filesize'] = strlen($string);
// Analyze
$this->Analyze();
// Restore some info
$this->getid3->info['avdataoffset'] = $saved_avdataoffset;
$this->getid3->info['avdataend'] = $saved_avdataend;
$this->getid3->info['filesize'] = $saved_filesize;
// Exit string mode
$this->data_string_flag = false;
} | Analyze from string instead | entailment |
function Analyze() {
$info = &$this->getid3->info;
$initialOffset = $info['avdataoffset'];
if (!$this->getOnlyMPEGaudioInfo($info['avdataoffset'])) {
if ($this->allow_bruteforce) {
$info['error'][] = 'Rescanning file in BruteForce mode';
$this->getOnlyMPEGaudioInfoBruteForce($this->getid3->fp, $info);
}
}
if (isset($info['mpeg']['audio']['bitrate_mode'])) {
$info['audio']['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']);
}
if (((isset($info['id3v2']['headerlength']) && ($info['avdataoffset'] > $info['id3v2']['headerlength'])) || (!isset($info['id3v2']) && ($info['avdataoffset'] > 0) && ($info['avdataoffset'] != $initialOffset)))) {
$synchoffsetwarning = 'Unknown data before synch ';
if (isset($info['id3v2']['headerlength'])) {
$synchoffsetwarning .= '(ID3v2 header ends at '.$info['id3v2']['headerlength'].', then '.($info['avdataoffset'] - $info['id3v2']['headerlength']).' bytes garbage, ';
} elseif ($initialOffset > 0) {
$synchoffsetwarning .= '(should be at '.$initialOffset.', ';
} else {
$synchoffsetwarning .= '(should be at beginning of file, ';
}
$synchoffsetwarning .= 'synch detected at '.$info['avdataoffset'].')';
if (isset($info['audio']['bitrate_mode']) && ($info['audio']['bitrate_mode'] == 'cbr')) {
if (!empty($info['id3v2']['headerlength']) && (($info['avdataoffset'] - $info['id3v2']['headerlength']) == $info['mpeg']['audio']['framelength'])) {
$synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90-3.92) DLL in CBR mode.';
$info['audio']['codec'] = 'LAME';
$CurrentDataLAMEversionString = 'LAME3.';
} elseif (empty($info['id3v2']['headerlength']) && ($info['avdataoffset'] == $info['mpeg']['audio']['framelength'])) {
$synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90 - 3.92) DLL in CBR mode.';
$info['audio']['codec'] = 'LAME';
$CurrentDataLAMEversionString = 'LAME3.';
}
}
$info['warning'][] = $synchoffsetwarning;
}
if (isset($info['mpeg']['audio']['LAME'])) {
$info['audio']['codec'] = 'LAME';
if (!empty($info['mpeg']['audio']['LAME']['long_version'])) {
$info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['long_version'], "\x00");
} elseif (!empty($info['mpeg']['audio']['LAME']['short_version'])) {
$info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['short_version'], "\x00");
}
}
$CurrentDataLAMEversionString = (!empty($CurrentDataLAMEversionString) ? $CurrentDataLAMEversionString : (isset($info['audio']['encoder']) ? $info['audio']['encoder'] : ''));
if (!empty($CurrentDataLAMEversionString) && (substr($CurrentDataLAMEversionString, 0, 6) == 'LAME3.') && !preg_match('[0-9\)]', substr($CurrentDataLAMEversionString, -1))) {
// a version number of LAME that does not end with a number like "LAME3.92"
// or with a closing parenthesis like "LAME3.88 (alpha)"
// or a version of LAME with the LAMEtag-not-filled-in-DLL-mode bug (3.90-3.92)
// not sure what the actual last frame length will be, but will be less than or equal to 1441
$PossiblyLongerLAMEversion_FrameLength = 1441;
// Not sure what version of LAME this is - look in padding of last frame for longer version string
$PossibleLAMEversionStringOffset = $info['avdataend'] - $PossiblyLongerLAMEversion_FrameLength;
fseek($this->getid3->fp, $PossibleLAMEversionStringOffset);
$PossiblyLongerLAMEversion_Data = fread($this->getid3->fp, $PossiblyLongerLAMEversion_FrameLength);
switch (substr($CurrentDataLAMEversionString, -1)) {
case 'a':
case 'b':
// "LAME3.94a" will have a longer version string of "LAME3.94 (alpha)" for example
// need to trim off "a" to match longer string
$CurrentDataLAMEversionString = substr($CurrentDataLAMEversionString, 0, -1);
break;
}
if (($PossiblyLongerLAMEversion_String = strstr($PossiblyLongerLAMEversion_Data, $CurrentDataLAMEversionString)) !== false) {
if (substr($PossiblyLongerLAMEversion_String, 0, strlen($CurrentDataLAMEversionString)) == $CurrentDataLAMEversionString) {
$PossiblyLongerLAMEversion_NewString = substr($PossiblyLongerLAMEversion_String, 0, strspn($PossiblyLongerLAMEversion_String, 'LAME0123456789., (abcdefghijklmnopqrstuvwxyzJFSOND)')); //"LAME3.90.3" "LAME3.87 (beta 1, Sep 27 2000)" "LAME3.88 (beta)"
if (empty($info['audio']['encoder']) || (strlen($PossiblyLongerLAMEversion_NewString) > strlen($info['audio']['encoder']))) {
$info['audio']['encoder'] = $PossiblyLongerLAMEversion_NewString;
}
}
}
}
if (!empty($info['audio']['encoder'])) {
$info['audio']['encoder'] = rtrim($info['audio']['encoder'], "\x00 ");
}
switch (isset($info['mpeg']['audio']['layer']) ? $info['mpeg']['audio']['layer'] : '') {
case 1:
case 2:
$info['audio']['dataformat'] = 'mp'.$info['mpeg']['audio']['layer'];
break;
}
if (isset($info['fileformat']) && ($info['fileformat'] == 'mp3')) {
switch ($info['audio']['dataformat']) {
case 'mp1':
case 'mp2':
case 'mp3':
$info['fileformat'] = $info['audio']['dataformat'];
break;
default:
$info['warning'][] = 'Expecting [audio][dataformat] to be mp1/mp2/mp3 when fileformat == mp3, [audio][dataformat] actually "'.$info['audio']['dataformat'].'"';
break;
}
}
if (empty($info['fileformat'])) {
unset($info['fileformat']);
unset($info['audio']['bitrate_mode']);
unset($info['avdataoffset']);
unset($info['avdataend']);
return false;
}
$info['mime_type'] = 'audio/mpeg';
$info['audio']['lossless'] = false;
// Calculate playtime
if (!isset($info['playtime_seconds']) && isset($info['audio']['bitrate']) && ($info['audio']['bitrate'] > 0)) {
$info['playtime_seconds'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / $info['audio']['bitrate'];
}
$info['audio']['encoder_options'] = $this->GuessEncoderOptions();
return true;
} | forces getID3() to scan the file byte-by-byte and log all the valid audio frame headers - extremely slow, unrecommended, but may provide data from otherwise-unusuable files | entailment |
public function command($args)
{
// Access items in container
$settings = $this->container->get('settings');
// Throw if no arguments provided
if (empty($args)) {
throw new RuntimeException("No arguments passed to command");
}
$firstArg = $args[0];
// Output the first argument
return $firstArg;
} | SampleTask command
@param array $args
@return void | entailment |
function Analyze() {
$info = &$this->getid3->info;
// http://flac.sourceforge.net/format.html
$this->fseek($info['avdataoffset'], SEEK_SET);
$StreamMarker = $this->fread(4);
$magic = 'fLaC';
if ($StreamMarker != $magic) {
$info['error'][] = 'Expecting "'.getid3_lib::PrintHexBytes($magic).'" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes($StreamMarker).'"';
return false;
}
$info['fileformat'] = 'flac';
$info['audio']['dataformat'] = 'flac';
$info['audio']['bitrate_mode'] = 'vbr';
$info['audio']['lossless'] = true;
return $this->FLACparseMETAdata();
} | true: return full data for all attachments; false: return no data for all attachments; integer: return data for attachments <= than this; string: save as file to this directory | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('slot_mandrill');
$rootNode
->children()
->arrayNode('default')
->isRequired()
->children()
->scalarNode('sender')->isRequired()->cannotBeEmpty()->end()
->scalarNode('sender_name')->defaultNull()->end()
->scalarNode('subaccount')->defaultNull()->end()
->end()
->end()
->scalarNode('api_key')->defaultNull()->end()
->scalarNode('disable_delivery')->defaultFalse()->end()
->scalarNode('debug')->defaultFalse()->end()
->arrayNode('proxy')
->addDefaultsIfNotSet()
->children()
->booleanNode('use')->defaultFalse()->end()
->scalarNode('host')->defaultNull()->end()
->scalarNode('port')->defaultNull()->end()
->scalarNode('user')->defaultNull()->end()
->scalarNode('password')->defaultNull()->end()
->end()
->end()
->end();
return $treeBuilder;
} | {@inheritDoc} | entailment |
static function hash_data($file, $offset, $end, $algorithm) {
static $tempdir = '';
if (!getid3_lib::intValueSupported($end)) {
return false;
}
switch ($algorithm) {
case 'md5':
$hash_function = 'md5_file';
$unix_call = 'md5sum';
$windows_call = 'md5sum.exe';
$hash_length = 32;
break;
case 'sha1':
$hash_function = 'sha1_file';
$unix_call = 'sha1sum';
$windows_call = 'sha1sum.exe';
$hash_length = 40;
break;
default:
throw new Exception('Invalid algorithm ('.$algorithm.') in getid3_lib::hash_data()');
break;
}
$size = $end - $offset;
while (true) {
if (GETID3_OS_ISWINDOWS) {
// It seems that sha1sum.exe for Windows only works on physical files, does not accept piped data
// Fall back to create-temp-file method:
if ($algorithm == 'sha1') {
break;
}
$RequiredFiles = array('cygwin1.dll', 'head.exe', 'tail.exe', $windows_call);
foreach ($RequiredFiles as $required_file) {
if (!is_readable(GETID3_HELPERAPPSDIR.$required_file)) {
// helper apps not available - fall back to old method
break;
}
}
$commandline = GETID3_HELPERAPPSDIR.'head.exe -c '.$end.' "'.escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $file)).'" | ';
$commandline .= GETID3_HELPERAPPSDIR.'tail.exe -c '.$size.' | ';
$commandline .= GETID3_HELPERAPPSDIR.$windows_call;
} else {
$commandline = 'head -c'.$end.' '.escapeshellarg($file).' | ';
$commandline .= 'tail -c'.$size.' | ';
$commandline .= $unix_call;
}
if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
//throw new Exception('PHP running in Safe Mode - backtick operator not available, using slower non-system-call '.$algorithm.' algorithm');
break;
}
return substr(`$commandline`, 0, $hash_length);
}
if (empty($tempdir)) {
// yes this is ugly, feel free to suggest a better way
require_once(dirname(__FILE__).'/getid3.php');
$getid3_temp = new getID3();
$tempdir = $getid3_temp->tempdir;
unset($getid3_temp);
}
// try to create a temporary file in the system temp directory - invalid dirname should force to system temp dir
if (($data_filename = tempnam($tempdir, 'gI3')) === false) {
// can't find anywhere to create a temp file, just fail
return false;
}
// Init
$result = false;
// copy parts of file
try {
getid3_lib::CopyFileParts($file, $data_filename, $offset, $end - $offset);
$result = $hash_function($data_filename);
} catch (Exception $e) {
throw new Exception('getid3_lib::CopyFileParts() failed in getid_lib::hash_data(): '.$e->getMessage());
}
unlink($data_filename);
return $result;
} | getid3_lib::md5_data() - returns md5sum for a file from startuing position to absolute end position | entailment |
static function iconv_fallback_iso88591_utf8($string, $bom=false) {
if (function_exists('utf8_encode')) {
return utf8_encode($string);
}
// utf8_encode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xEF\xBB\xBF";
}
for ($i = 0; $i < strlen($string); $i++) {
$charval = ord($string{$i});
$newcharstring .= getid3_lib::iconv_fallback_int_utf8($charval);
}
return $newcharstring;
} | ISO-8859-1 => UTF-8 | entailment |
static function iconv_fallback_utf16be_utf8($string) {
if (substr($string, 0, 2) == "\xFE\xFF") {
// strip BOM
$string = substr($string, 2);
}
$newcharstring = '';
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = getid3_lib::BigEndian2Int(substr($string, $i, 2));
$newcharstring .= getid3_lib::iconv_fallback_int_utf8($charval);
}
return $newcharstring;
} | UTF-16BE => UTF-8 | entailment |
static function iconv_fallback_utf16_iso88591($string) {
$bom = substr($string, 0, 2);
if ($bom == "\xFE\xFF") {
return getid3_lib::iconv_fallback_utf16be_iso88591(substr($string, 2));
} elseif ($bom == "\xFF\xFE") {
return getid3_lib::iconv_fallback_utf16le_iso88591(substr($string, 2));
}
return $string;
} | UTF-16 (BOM) => ISO-8859-1 | entailment |
static function iconv_fallback_utf16_utf8($string) {
$bom = substr($string, 0, 2);
if ($bom == "\xFE\xFF") {
return getid3_lib::iconv_fallback_utf16be_utf8(substr($string, 2));
} elseif ($bom == "\xFF\xFE") {
return getid3_lib::iconv_fallback_utf16le_utf8(substr($string, 2));
}
return $string;
} | UTF-16 (BOM) => UTF-8 | entailment |
private function parseEBML(&$info)
{
// http://www.matroska.org/technical/specs/index.html#EBMLBasics
$this->current_offset = $info['avdataoffset'];
while ($this->getEBMLelement($top_element, $info['avdataend'])) {
switch ($top_element['id']) {
case EBML_ID_EBML:
$info['fileformat'] = 'matroska';
$info['matroska']['header']['offset'] = $top_element['offset'];
$info['matroska']['header']['length'] = $top_element['length'];
while ($this->getEBMLelement($element_data, $top_element['end'], true)) {
switch ($element_data['id']) {
case EBML_ID_EBMLVERSION:
case EBML_ID_EBMLREADVERSION:
case EBML_ID_EBMLMAXIDLENGTH:
case EBML_ID_EBMLMAXSIZELENGTH:
case EBML_ID_DOCTYPEVERSION:
case EBML_ID_DOCTYPEREADVERSION:
$element_data['data'] = getid3_lib::BigEndian2Int($element_data['data']);
break;
case EBML_ID_DOCTYPE:
$element_data['data'] = getid3_lib::trimNullByte($element_data['data']);
$info['matroska']['doctype'] = $element_data['data'];
break;
case EBML_ID_CRC32: // not useful, ignore
$this->current_offset = $element_data['end'];
unset($element_data);
break;
default:
$this->unhandledElement('header', __LINE__, $element_data);
}
if (!empty($element_data)) {
unset($element_data['offset'], $element_data['end']);
$info['matroska']['header']['elements'][] = $element_data;
}
}
break;
case EBML_ID_SEGMENT:
$info['matroska']['segment'][0]['offset'] = $top_element['offset'];
$info['matroska']['segment'][0]['length'] = $top_element['length'];
while ($this->getEBMLelement($element_data, $top_element['end'])) {
if ($element_data['id'] != EBML_ID_CLUSTER || !self::$hide_clusters) { // collect clusters only if required
$info['matroska']['segments'][] = $element_data;
}
switch ($element_data['id']) {
case EBML_ID_SEEKHEAD: // Contains the position of other level 1 elements.
while ($this->getEBMLelement($seek_entry, $element_data['end'])) {
switch ($seek_entry['id']) {
case EBML_ID_SEEK: // Contains a single seek entry to an EBML element
while ($this->getEBMLelement($sub_seek_entry, $seek_entry['end'], true)) {
switch ($sub_seek_entry['id']) {
case EBML_ID_SEEKID:
$seek_entry['target_id'] = self::EBML2Int($sub_seek_entry['data']);
$seek_entry['target_name'] = self::EBMLidName($seek_entry['target_id']);
break;
case EBML_ID_SEEKPOSITION:
$seek_entry['target_offset'] = $element_data['offset'] + getid3_lib::BigEndian2Int($sub_seek_entry['data']);
break;
default:
$this->unhandledElement('seekhead.seek', __LINE__, $sub_seek_entry); }
}
if ($seek_entry['target_id'] != EBML_ID_CLUSTER || !self::$hide_clusters) { // collect clusters only if required
$info['matroska']['seek'][] = $seek_entry;
}
break;
default:
$this->unhandledElement('seekhead', __LINE__, $seek_entry);
}
}
break;
case EBML_ID_TRACKS: // A top-level block of information with many tracks described.
$info['matroska']['tracks'] = $element_data;
while ($this->getEBMLelement($track_entry, $element_data['end'])) {
switch ($track_entry['id']) {
case EBML_ID_TRACKENTRY: //subelements: Describes a track with all elements.
while ($this->getEBMLelement($subelement, $track_entry['end'], array(EBML_ID_VIDEO, EBML_ID_AUDIO, EBML_ID_CONTENTENCODINGS))) {
switch ($subelement['id']) {
case EBML_ID_TRACKNUMBER:
case EBML_ID_TRACKUID:
case EBML_ID_TRACKTYPE:
case EBML_ID_MINCACHE:
case EBML_ID_MAXCACHE:
case EBML_ID_MAXBLOCKADDITIONID:
case EBML_ID_DEFAULTDURATION: // nanoseconds per frame
$track_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']);
break;
case EBML_ID_TRACKTIMECODESCALE:
$track_entry[$subelement['id_name']] = getid3_lib::BigEndian2Float($subelement['data']);
break;
case EBML_ID_CODECID:
case EBML_ID_LANGUAGE:
case EBML_ID_NAME:
case EBML_ID_CODECNAME:
$track_entry[$subelement['id_name']] = getid3_lib::trimNullByte($subelement['data']);
break;
case EBML_ID_CODECPRIVATE:
$track_entry[$subelement['id_name']] = $subelement['data'];
break;
case EBML_ID_FLAGENABLED:
case EBML_ID_FLAGDEFAULT:
case EBML_ID_FLAGFORCED:
case EBML_ID_FLAGLACING:
case EBML_ID_CODECDECODEALL:
$track_entry[$subelement['id_name']] = (bool) getid3_lib::BigEndian2Int($subelement['data']);
break;
case EBML_ID_VIDEO:
while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) {
switch ($sub_subelement['id']) {
case EBML_ID_PIXELWIDTH:
case EBML_ID_PIXELHEIGHT:
case EBML_ID_STEREOMODE:
case EBML_ID_PIXELCROPBOTTOM:
case EBML_ID_PIXELCROPTOP:
case EBML_ID_PIXELCROPLEFT:
case EBML_ID_PIXELCROPRIGHT:
case EBML_ID_DISPLAYWIDTH:
case EBML_ID_DISPLAYHEIGHT:
case EBML_ID_DISPLAYUNIT:
case EBML_ID_ASPECTRATIOTYPE:
$track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_FLAGINTERLACED:
$track_entry[$sub_subelement['id_name']] = (bool)getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_GAMMAVALUE:
$track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Float($sub_subelement['data']);
break;
case EBML_ID_COLOURSPACE:
$track_entry[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']);
break;
default:
$this->unhandledElement('track.video', __LINE__, $sub_subelement);
}
}
break;
case EBML_ID_AUDIO:
while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) {
switch ($sub_subelement['id']) {
case EBML_ID_CHANNELS:
case EBML_ID_BITDEPTH:
$track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_SAMPLINGFREQUENCY:
case EBML_ID_OUTPUTSAMPLINGFREQUENCY:
$track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Float($sub_subelement['data']);
break;
case EBML_ID_CHANNELPOSITIONS:
$track_entry[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']);
break;
default:
$this->unhandledElement('track.audio', __LINE__, $sub_subelement);
}
}
break;
case EBML_ID_CONTENTENCODINGS:
while ($this->getEBMLelement($sub_subelement, $subelement['end'])) {
switch ($sub_subelement['id']) {
case EBML_ID_CONTENTENCODING:
while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], array(EBML_ID_CONTENTCOMPRESSION, EBML_ID_CONTENTENCRYPTION))) {
switch ($sub_sub_subelement['id']) {
case EBML_ID_CONTENTENCODINGORDER:
case EBML_ID_CONTENTENCODINGSCOPE:
case EBML_ID_CONTENTENCODINGTYPE:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
case EBML_ID_CONTENTCOMPRESSION:
while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) {
switch ($sub_sub_sub_subelement['id']) {
case EBML_ID_CONTENTCOMPALGO:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_sub_subelement['data']);
break;
case EBML_ID_CONTENTCOMPSETTINGS:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = $sub_sub_sub_subelement['data'];
break;
default:
$this->unhandledElement('track.contentencodings.contentencoding.contentcompression', __LINE__, $sub_sub_sub_subelement);
}
}
break;
case EBML_ID_CONTENTENCRYPTION:
while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) {
switch ($sub_sub_sub_subelement['id']) {
case EBML_ID_CONTENTENCALGO:
case EBML_ID_CONTENTSIGALGO:
case EBML_ID_CONTENTSIGHASHALGO:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_sub_subelement['data']);
break;
case EBML_ID_CONTENTENCKEYID:
case EBML_ID_CONTENTSIGNATURE:
case EBML_ID_CONTENTSIGKEYID:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = $sub_sub_sub_subelement['data'];
break;
default:
$this->unhandledElement('track.contentencodings.contentencoding.contentcompression', __LINE__, $sub_sub_sub_subelement);
}
}
break;
default:
$this->unhandledElement('track.contentencodings.contentencoding', __LINE__, $sub_sub_subelement);
}
}
break;
default:
$this->unhandledElement('track.contentencodings', __LINE__, $sub_subelement);
}
}
break;
default:
$this->unhandledElement('track', __LINE__, $subelement);
}
}
$info['matroska']['tracks']['tracks'][] = $track_entry;
break;
default:
$this->unhandledElement('tracks', __LINE__, $track_entry);
}
}
break;
case EBML_ID_INFO: // Contains miscellaneous general information and statistics on the file.
$info_entry = array();
while ($this->getEBMLelement($subelement, $element_data['end'], true)) {
switch ($subelement['id']) {
case EBML_ID_CHAPTERTRANSLATEEDITIONUID:
case EBML_ID_CHAPTERTRANSLATECODEC:
case EBML_ID_TIMECODESCALE:
$info_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']);
break;
case EBML_ID_DURATION:
$info_entry[$subelement['id_name']] = getid3_lib::BigEndian2Float($subelement['data']);
break;
case EBML_ID_DATEUTC:
$info_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']);
$info_entry[$subelement['id_name'].'_unix'] = self::EBMLdate2unix($info_entry[$subelement['id_name']]);
break;
case EBML_ID_SEGMENTUID:
case EBML_ID_PREVUID:
case EBML_ID_NEXTUID:
case EBML_ID_SEGMENTFAMILY:
case EBML_ID_CHAPTERTRANSLATEID:
$info_entry[$subelement['id_name']] = getid3_lib::trimNullByte($subelement['data']);
break;
case EBML_ID_SEGMENTFILENAME:
case EBML_ID_PREVFILENAME:
case EBML_ID_NEXTFILENAME:
case EBML_ID_TITLE:
case EBML_ID_MUXINGAPP:
case EBML_ID_WRITINGAPP:
$info_entry[$subelement['id_name']] = getid3_lib::trimNullByte($subelement['data']);
$info['matroska']['comments'][strtolower($subelement['id_name'])][] = $info_entry[$subelement['id_name']];
break;
default:
$this->unhandledElement('info', __LINE__, $subelement);
}
}
$info['matroska']['info'][] = $info_entry;
break;
case EBML_ID_CUES: // A top-level element to speed seeking access. All entries are local to the segment. Should be mandatory for non "live" streams.
if (self::$hide_clusters) { // do not parse cues if hide clusters is "ON" till they point to clusters anyway
$this->current_offset = $element_data['end'];
break;
}
$cues_entry = array();
while ($this->getEBMLelement($subelement, $element_data['end'])) {
switch ($subelement['id']) {
case EBML_ID_CUEPOINT:
$cuepoint_entry = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_CUETRACKPOSITIONS))) {
switch ($sub_subelement['id']) {
case EBML_ID_CUETRACKPOSITIONS:
$cuetrackpositions_entry = array();
while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], true)) {
switch ($sub_sub_subelement['id']) {
case EBML_ID_CUETRACK:
case EBML_ID_CUECLUSTERPOSITION:
case EBML_ID_CUEBLOCKNUMBER:
case EBML_ID_CUECODECSTATE:
$cuetrackpositions_entry[$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
default:
$this->unhandledElement('cues.cuepoint.cuetrackpositions', __LINE__, $sub_sub_subelement);
}
}
$cuepoint_entry[$sub_subelement['id_name']][] = $cuetrackpositions_entry;
break;
case EBML_ID_CUETIME:
$cuepoint_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
default:
$this->unhandledElement('cues.cuepoint', __LINE__, $sub_subelement);
}
}
$cues_entry[] = $cuepoint_entry;
break;
default:
$this->unhandledElement('cues', __LINE__, $subelement);
}
}
$info['matroska']['cues'] = $cues_entry;
break;
case EBML_ID_TAGS: // Element containing elements specific to Tracks/Chapters.
$tags_entry = array();
while ($this->getEBMLelement($subelement, $element_data['end'], false)) {
switch ($subelement['id']) {
case EBML_ID_TAG:
$tag_entry = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], false)) {
switch ($sub_subelement['id']) {
case EBML_ID_TARGETS:
$targets_entry = array();
while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], true)) {
switch ($sub_sub_subelement['id']) {
case EBML_ID_TARGETTYPEVALUE:
$targets_entry[$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
$targets_entry[strtolower($sub_sub_subelement['id_name']).'_long'] = self::MatroskaTargetTypeValue($targets_entry[$sub_sub_subelement['id_name']]);
break;
case EBML_ID_TARGETTYPE:
$targets_entry[$sub_sub_subelement['id_name']] = $sub_sub_subelement['data'];
break;
case EBML_ID_TAGTRACKUID:
case EBML_ID_TAGEDITIONUID:
case EBML_ID_TAGCHAPTERUID:
case EBML_ID_TAGATTACHMENTUID:
$targets_entry[$sub_sub_subelement['id_name']][] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
default:
$this->unhandledElement('tags.tag.targets', __LINE__, $sub_sub_subelement);
}
}
$tag_entry[$sub_subelement['id_name']] = $targets_entry;
break;
case EBML_ID_SIMPLETAG:
$tag_entry[$sub_subelement['id_name']][] = $this->HandleEMBLSimpleTag($sub_subelement['end']);
break;
default:
$this->unhandledElement('tags.tag', __LINE__, $sub_subelement);
}
}
$tags_entry[] = $tag_entry;
break;
default:
$this->unhandledElement('tags', __LINE__, $subelement);
}
}
$info['matroska']['tags'] = $tags_entry;
break;
case EBML_ID_ATTACHMENTS: // Contain attached files.
while ($this->getEBMLelement($subelement, $element_data['end'])) {
switch ($subelement['id']) {
case EBML_ID_ATTACHEDFILE:
$attachedfile_entry = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_FILEDATA))) {
switch ($sub_subelement['id']) {
case EBML_ID_FILEDESCRIPTION:
case EBML_ID_FILENAME:
case EBML_ID_FILEMIMETYPE:
$attachedfile_entry[$sub_subelement['id_name']] = $sub_subelement['data'];
break;
case EBML_ID_FILEDATA:
$attachedfile_entry['data_offset'] = $this->current_offset;
$attachedfile_entry['data_length'] = $sub_subelement['length'];
$this->getid3->saveAttachment(
$attachedfile_entry[$sub_subelement['id_name']],
$attachedfile_entry['FileName'],
$attachedfile_entry['data_offset'],
$attachedfile_entry['data_length']);
if (@$attachedfile_entry[$sub_subelement['id_name']] && is_file($attachedfile_entry[$sub_subelement['id_name']])) {
$attachedfile_entry[$sub_subelement['id_name'].'_filename'] = $attachedfile_entry[$sub_subelement['id_name']];
unset($attachedfile_entry[$sub_subelement['id_name']]);
}
$this->current_offset = $sub_subelement['end'];
break;
case EBML_ID_FILEUID:
$attachedfile_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
default:
$this->unhandledElement('attachments.attachedfile', __LINE__, $sub_subelement);
}
}
if (!empty($attachedfile_entry['FileData']) && !empty($attachedfile_entry['FileMimeType']) && preg_match('#^image/#i', $attachedfile_entry['FileMimeType'])) {
if ($this->getid3->option_save_attachments === getID3::ATTACHMENTS_INLINE) {
$attachedfile_entry['data'] = $attachedfile_entry['FileData'];
$attachedfile_entry['image_mime'] = $attachedfile_entry['FileMimeType'];
$info['matroska']['comments']['picture'][] = array('data' => $attachedfile_entry['data'], 'image_mime' => $attachedfile_entry['image_mime'], 'filename' => (!empty($attachedfile_entry['FileName']) ? $attachedfile_entry['FileName'] : ''));
unset($attachedfile_entry['FileData'], $attachedfile_entry['FileMimeType']);
}
}
if (!empty($attachedfile_entry['image_mime']) && preg_match('#^image/#i', $attachedfile_entry['image_mime'])) {
// don't add a second copy of attached images, which are grouped under the standard location [comments][picture]
} else {
$info['matroska']['attachments'][] = $attachedfile_entry;
}
break;
default:
$this->unhandledElement('attachments', __LINE__, $subelement);
}
}
break;
case EBML_ID_CHAPTERS:
while ($this->getEBMLelement($subelement, $element_data['end'])) {
switch ($subelement['id']) {
case EBML_ID_EDITIONENTRY:
$editionentry_entry = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_CHAPTERATOM))) {
switch ($sub_subelement['id']) {
case EBML_ID_EDITIONUID:
$editionentry_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_EDITIONFLAGHIDDEN:
case EBML_ID_EDITIONFLAGDEFAULT:
case EBML_ID_EDITIONFLAGORDERED:
$editionentry_entry[$sub_subelement['id_name']] = (bool)getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_CHAPTERATOM:
$chapteratom_entry = array();
while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], array(EBML_ID_CHAPTERTRACK, EBML_ID_CHAPTERDISPLAY))) {
switch ($sub_sub_subelement['id']) {
case EBML_ID_CHAPTERSEGMENTUID:
case EBML_ID_CHAPTERSEGMENTEDITIONUID:
$chapteratom_entry[$sub_sub_subelement['id_name']] = $sub_sub_subelement['data'];
break;
case EBML_ID_CHAPTERFLAGENABLED:
case EBML_ID_CHAPTERFLAGHIDDEN:
$chapteratom_entry[$sub_sub_subelement['id_name']] = (bool)getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
case EBML_ID_CHAPTERUID:
case EBML_ID_CHAPTERTIMESTART:
case EBML_ID_CHAPTERTIMEEND:
$chapteratom_entry[$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
case EBML_ID_CHAPTERTRACK:
$chaptertrack_entry = array();
while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) {
switch ($sub_sub_sub_subelement['id']) {
case EBML_ID_CHAPTERTRACKNUMBER:
$chaptertrack_entry[$sub_sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_sub_subelement['data']);
break;
default:
$this->unhandledElement('chapters.editionentry.chapteratom.chaptertrack', __LINE__, $sub_sub_sub_subelement);
}
}
$chapteratom_entry[$sub_sub_subelement['id_name']][] = $chaptertrack_entry;
break;
case EBML_ID_CHAPTERDISPLAY:
$chapterdisplay_entry = array();
while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) {
switch ($sub_sub_sub_subelement['id']) {
case EBML_ID_CHAPSTRING:
case EBML_ID_CHAPLANGUAGE:
case EBML_ID_CHAPCOUNTRY:
$chapterdisplay_entry[$sub_sub_sub_subelement['id_name']] = $sub_sub_sub_subelement['data'];
break;
default:
$this->unhandledElement('chapters.editionentry.chapteratom.chapterdisplay', __LINE__, $sub_sub_sub_subelement);
}
}
$chapteratom_entry[$sub_sub_subelement['id_name']][] = $chapterdisplay_entry;
break;
default:
$this->unhandledElement('chapters.editionentry.chapteratom', __LINE__, $sub_sub_subelement);
}
}
$editionentry_entry[$sub_subelement['id_name']][] = $chapteratom_entry;
break;
default:
$this->unhandledElement('chapters.editionentry', __LINE__, $sub_subelement);
}
}
$info['matroska']['chapters'][] = $editionentry_entry;
break;
default:
$this->unhandledElement('chapters', __LINE__, $subelement);
}
}
break;
case EBML_ID_CLUSTER: // The lower level element containing the (monolithic) Block structure.
$cluster_entry = array();
while ($this->getEBMLelement($subelement, $element_data['end'], array(EBML_ID_CLUSTERSILENTTRACKS, EBML_ID_CLUSTERBLOCKGROUP, EBML_ID_CLUSTERSIMPLEBLOCK))) {
switch ($subelement['id']) {
case EBML_ID_CLUSTERTIMECODE:
case EBML_ID_CLUSTERPOSITION:
case EBML_ID_CLUSTERPREVSIZE:
$cluster_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']);
break;
case EBML_ID_CLUSTERSILENTTRACKS:
$cluster_silent_tracks = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) {
switch ($sub_subelement['id']) {
case EBML_ID_CLUSTERSILENTTRACKNUMBER:
$cluster_silent_tracks[] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
default:
$this->unhandledElement('cluster.silenttracks', __LINE__, $sub_subelement);
}
}
$cluster_entry[$subelement['id_name']][] = $cluster_silent_tracks;
break;
case EBML_ID_CLUSTERBLOCKGROUP:
$cluster_block_group = array('offset' => $this->current_offset);
while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_CLUSTERBLOCK))) {
switch ($sub_subelement['id']) {
case EBML_ID_CLUSTERBLOCK:
$cluster_block_group[$sub_subelement['id_name']] = $this->HandleEMBLClusterBlock($sub_subelement, EBML_ID_CLUSTERBLOCK, $info);
break;
case EBML_ID_CLUSTERREFERENCEPRIORITY: // unsigned-int
case EBML_ID_CLUSTERBLOCKDURATION: // unsigned-int
$cluster_block_group[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_CLUSTERREFERENCEBLOCK: // signed-int
$cluster_block_group[$sub_subelement['id_name']][] = getid3_lib::BigEndian2Int($sub_subelement['data'], false, true);
break;
case EBML_ID_CLUSTERCODECSTATE:
$cluster_block_group[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']);
break;
default:
$this->unhandledElement('clusters.blockgroup', __LINE__, $sub_subelement);
}
}
$cluster_entry[$subelement['id_name']][] = $cluster_block_group;
break;
case EBML_ID_CLUSTERSIMPLEBLOCK:
$cluster_entry[$subelement['id_name']][] = $this->HandleEMBLClusterBlock($subelement, EBML_ID_CLUSTERSIMPLEBLOCK, $info);
break;
default:
$this->unhandledElement('cluster', __LINE__, $subelement);
}
$this->current_offset = $subelement['end'];
}
if (!self::$hide_clusters) {
$info['matroska']['cluster'][] = $cluster_entry;
}
// check to see if all the data we need exists already, if so, break out of the loop
if (!self::$parse_whole_file) {
if (isset($info['matroska']['info']) && is_array($info['matroska']['info'])) {
if (isset($info['matroska']['tracks']['tracks']) && is_array($info['matroska']['tracks']['tracks'])) {
return;
}
}
}
break;
default:
$this->unhandledElement('segment', __LINE__, $element_data);
}
}
break;
default:
$this->unhandledElement('root', __LINE__, $top_element);
}
}
} | ///////////////////////////////////// | entailment |
public function send(Message $message, $templateName = '', $templateContent = array(), $async = false, $ipPool = null, $sendAt = null)
{
if ($this->disableDelivery) {
return false;
}
if (strlen($message->getFromEmail()) == 0) {
$message->setFromEmail($this->defaultSender);
}
if (strlen($message->getFromName()) == 0 && null !== $this->defaultSenderName) {
$message->setFromName($this->defaultSenderName);
}
if (strlen($message->getSubaccount()) == 0 && null !== $this->subaccount) {
$message->setSubaccount($this->subaccount);
}
if (!empty($templateName)) {
return $this->service->messages->sendTemplate($templateName, $templateContent, $message->toArray(), $async, $ipPool, $sendAt);
}
return $this->service->messages->send($message->toArray(), $async, $ipPool, $sendAt);
} | Send a message
@param Message $message
@param string $templateName
@param array $templateContent
@param bool $async
@param string $ipPool
@param string $sendAt
@return array|bool | entailment |
public function command($args)
{
// Throw if no arguments provided and args less than 2
if (empty($args) || count($args) < 2) {
throw new RuntimeException("Invalid argument count");
}
$secondArg = $args[1];
// Output the second argument
return $secondArg;
} | SampleTask command
@param array $args
@return void | entailment |
static function OptimFROGencoderNameLookup($EncoderID) {
// version = (encoderID >> 4) + 4500
// system = encoderID & 0xF
$EncoderVersion = number_format(((($EncoderID & 0xF0) >> 4) + 4500) / 1000, 3);
$EncoderSystemID = ($EncoderID & 0x0F);
static $OptimFROGencoderSystemLookup = array(
0x00 => 'Windows console',
0x01 => 'Linux console',
0x0F => 'unknown'
);
return $EncoderVersion.' ('.(isset($OptimFROGencoderSystemLookup[$EncoderSystemID]) ? $OptimFROGencoderSystemLookup[$EncoderSystemID] : 'undefined encoder type (0x'.dechex($EncoderSystemID).')').')';
} | } | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.