Ejemplo n.º 1
0
 /**
  * Handle a single request
  *
  * @param   string method request method
  * @param   string query query string
  * @param   [:string] headers request headers
  * @param   string data post data
  * @param   peer.Socket socket
  * @return  int
  */
 public function handleRequest($method, $query, array $headers, $data, Socket $socket)
 {
     $url = parse_url($query);
     $f = new File($this->docroot, strtr(preg_replace('#\\.\\./?#', '/', urldecode($url['path'])), '/', DIRECTORY_SEPARATOR));
     if (!is_file($f->getURI())) {
         return call_user_func($this->notFound, $this, $socket, $url['path']);
     }
     // Implement If-Modified-Since/304 Not modified
     $lastModified = $f->lastModified();
     if ($mod = $this->header($headers, 'If-Modified-Since')) {
         $d = strtotime($mod);
         if ($lastModified <= $d) {
             $this->sendHeader($socket, 304, 'Not modified', []);
             return 304;
         }
     }
     clearstatcache();
     try {
         $f->open(File::READ);
     } catch (IOException $e) {
         $this->sendErrorMessage($socket, 500, 'Internal server error', $e->getMessage());
         $f->close();
         return 500;
     }
     // Send OK header and data in 8192 byte chunks
     $this->sendHeader($socket, 200, 'OK', ['Last-Modified: ' . gmdate('D, d M Y H:i:s T', $lastModified), 'Content-Type: ' . MimeType::getByFileName($f->getFilename()), 'Content-Length: ' . $f->size()]);
     while (!$f->eof()) {
         $socket->write($f->read(8192));
     }
     $f->close();
     return 200;
 }
Ejemplo n.º 2
0
 /**
  * Find named pipe
  *
  * @return  string or NULL if no file can be found
  */
 protected function locate()
 {
     $pipes = '\\\\.\\pipe\\';
     // Check well-known pipe name
     if (file_exists($pipes . 'mysql')) {
         return $pipes . 'mysql';
     }
     // Locate my.ini in %WINDIR%, C: or the MySQL install dir, the latter of
     // which we determine by querying the registry using the "REG" tool.
     do {
         foreach ([getenv('WINDIR'), 'C:'] as $location) {
             $ini = new File($location, 'my.ini');
             if ($ini->exists()) {
                 break 2;
             }
         }
         exec('reg query "HKLM\\SOFTWARE\\MySQL AB" /s /e /f Location', $out, $ret);
         if (0 === $ret && 1 === sscanf($out[2], "    Location    REG_SZ    %[^\r]", $location)) {
             $ini = new File($location, 'my.ini');
             break;
         }
         return null;
     } while (0);
     $options = $this->parse($ini);
     return isset($options['client']['socket']) ? $pipes . $options['client']['socket'] : null;
 }
 /**
  * Constructor
  *
  * @param   io.File file
  * @throws  lang.IllegalArgumentException if the given file does not exist
  */
 public function __construct(File $file)
 {
     if (!$file->exists()) {
         throw new IllegalArgumentException('File "' . $file->getURI() . '" does not exist!');
     }
     $this->file = $file;
 }
Ejemplo n.º 4
0
 /**
  * Main
  *
  * Exitcodes used:
  * <ul>
  *   <li>127: Archive referenced in -xar [...] does not exist</li>
  *   <li>126: No manifest or manifest does not have a main-class</li>
  * </ul>
  *
  * @see     http://tldp.org/LDP/abs/html/exitcodes.html
  * @param   string[] args
  * @return  int
  */
 public static function main(array $args)
 {
     // Open archive
     $f = new File(array_shift($args));
     if (!$f->exists()) {
         Console::$err->writeLine('*** Cannot find archive ' . $f->getURI());
         return 127;
     }
     // Register class loader
     $cl = \lang\ClassLoader::registerLoader(new \lang\archive\ArchiveClassLoader(new Archive($f)));
     if (!$cl->providesResource(self::MANIFEST)) {
         Console::$err->writeLine('*** Archive ' . $f->getURI() . ' does not have a manifest');
         return 126;
     }
     // Load manifest
     $pr = Properties::fromString($cl->getResource(self::MANIFEST));
     if (null === ($class = $pr->readString('archive', 'main-class', null))) {
         Console::$err->writeLine('*** Archive ' . $f->getURI() . '\'s manifest does not have a main class');
         return 126;
     }
     // Run main()
     try {
         return \lang\XPClass::forName($class, $cl)->getMethod('main')->invoke(null, [$args]);
     } catch (\lang\reflect\TargetInvocationException $e) {
         throw $e->getCause();
     }
 }
Ejemplo n.º 5
0
 public function open_files_are_not_closed()
 {
     $file = new File($this->tempName());
     $file->open(File::REWRITE);
     $file->seek(0, SEEK_SET);
     (new FileOutput($file))->write('test');
     $this->assertTrue($file->isOpen());
 }
 /**
  * Constructor
  *
  * @param   io.File file
  * @throws  lang.IllegalArgumentException if the given file does not exist
  */
 public function __construct(File $file)
 {
     $uri = $file->getURI();
     $cl = ClassLoader::getDefault()->findUri($uri);
     if ($cl === null) {
         throw new IllegalArgumentException('File "' . $uri . ($file->exists() ? '" is not in class path' : '" not found'));
     }
     $this->loader = $cl;
     $this->uri = $uri;
 }
Ejemplo n.º 7
0
 /**
  * Locate config file
  *
  * @return  io.File
  */
 protected function locateConf()
 {
     foreach ([getenv('FREETDSCONF'), getenv('HOME') . '/.freetds.conf', '/etc/freetds/freetds.conf', '/etc/freetds.conf', '/usr/local/etc/freetds.conf'] as $location) {
         if (empty($location)) {
             continue;
         }
         $f = new File($location);
         if ($f->exists()) {
             return $f;
         }
     }
     return null;
 }
Ejemplo n.º 8
0
 /**
  * Read from a file
  *
  * @deprecated  Use img.io.MetaDataReader instead
  * @param   io.File file
  * @param   var default default void what should be returned in case no data is found
  * @return  img.util.IptcData
  * @throws  lang.FormatException in case malformed meta data is encountered
  * @throws  lang.ElementNotFoundException in case no meta data is available
  * @throws  img.ImagingException in case reading meta data fails
  */
 public static function fromFile(\io\File $file)
 {
     if (false === getimagesize($file->getURI(), $info)) {
         $e = new ImagingException('Cannot read image information from ' . $file->getURI());
         \xp::gc(__FILE__);
         throw $e;
     }
     if (!isset($info['APP13'])) {
         if (func_num_args() > 1) {
             return func_get_arg(1);
         }
         throw new ElementNotFoundException('Cannot get IPTC information from ' . $file->getURI() . ' (no APP13 marker)');
     }
     if (!($iptc = iptcparse($info['APP13']))) {
         throw new \lang\FormatException('Cannot parse IPTC information from ' . $file->getURI());
     }
     // Parse creation date
     if (3 == sscanf(@$iptc['2#055'][0], '%4d%2d%d', $year, $month, $day)) {
         $created = Date::create($year, $month, $day, 0, 0, 0);
     } else {
         $created = null;
     }
     with($i = new self());
     $i->setTitle(@$iptc['2#005'][0]);
     $i->setUrgency(@$iptc['2#010'][0]);
     $i->setCategory(@$iptc['2#015'][0]);
     $i->setSupplementalCategories(@$iptc['2#020']);
     $i->setKeywords(@$iptc['2#025']);
     $i->setSpecialInstructions(@$iptc['2#040'][0]);
     $i->setDateCreated($created);
     $i->setAuthor(@$iptc['2#080'][0]);
     $i->setAuthorPosition(@$iptc['2#085'][0]);
     $i->setCity(@$iptc['2#090'][0]);
     $i->setState(@$iptc['2#095'][0]);
     $i->setCountry(@$iptc['2#101'][0]);
     $i->setOriginalTransmissionReference(@$iptc['2#103'][0]);
     $i->setHeadline(@$iptc['2#105'][0]);
     $i->setCredit(@$iptc['2#110'][0]);
     $i->setSource(@$iptc['2#115'][0]);
     $i->setCopyrightNotice(@$iptc['2#116'][0]);
     $i->setCaption(@$iptc['2#120'][0]);
     $i->setWriter(@$iptc['2#122'][0]);
     return $i;
 }
 /**
  * Extract a ".ar" file into a given target directory
  *
  * @param   string base
  * @param   string ar
  * @param   io.Folder target
  * @throws  lang.IllegalStateException in case the target is not found
  * @throws  lang.FormatException in case the .ar-file is not parseable
  */
 protected function extract($base, $ar, Folder $target)
 {
     // Open a HTTP connection
     $url = new \peer\URL($base . $ar . '.ar');
     $r = create(new HttpConnection($url))->get();
     if (\peer\http\HttpConstants::STATUS_OK != $r->getStatusCode()) {
         throw new \lang\IllegalStateException(sprintf('Unexpected response %d:%s for %s', $r->getStatusCode(), $r->getMessage(), $url->getURL()));
     }
     $in = new BufferedInputStream($r->getInputStream());
     do {
         // Seach for first section header, --[LENGTH]:[FILENAME]-- and parse it
         do {
             $line = $this->readLine($in);
             if (!$in->available()) {
                 throw new \lang\FormatException('Cannot locate section header');
             }
         } while (2 !== sscanf($line, '--%d:%[^:]--', $length, $filename));
         // Calculate target file
         $file = new File($target, $filename);
         $folder = new Folder($file->getPath());
         $folder->exists() || $folder->create();
         \util\cmd\Console::writef('     >> [%-10s] %s (%.2f kB) [%s]%s', $ar, $filename, $length / 1024, str_repeat('.', self::PROGRESS_INDICATOR_WIDTH), str_repeat("", self::PROGRESS_INDICATOR_WIDTH + 1));
         // Transfer length bytes into file
         $c = 0;
         $out = $file->getOutputStream();
         $size = 0;
         while ($size < $length) {
             $chunk = $in->read(min(0x1000, $length - $size));
             $size += strlen($chunk);
             $out->write($chunk);
             // Update progress
             $d = ceil($size / $length * self::PROGRESS_INDICATOR_WIDTH);
             if ($d == $c) {
                 continue;
             }
             \util\cmd\Console::write(str_repeat('#', $d - $c));
             $c = $d;
         }
         $out->close();
         \util\cmd\Console::writeLine();
     } while ($in->available() > 0);
     $in->close();
 }
Ejemplo n.º 10
0
 function getSize($uncompressed = false)
 {
     if ($uncompressed) {
         $stream = new \IO\File\Stream($this, 'rb');
         $stream->open();
         $stream->seek(-1, SEEK_END);
         $reader = new \IO\File\Reader($stream);
         $buffer = $reader->read(4);
         $stream->close();
         return end(unpack("V", $buffer));
     }
     return parent::getSize();
 }
Ejemplo n.º 11
0
 /**
  * Fetches this origin into a given target folder
  *
  * @param  io.Folder $target
  */
 public function fetchInto(Folder $target)
 {
     $r = $this->client->execute($this->release);
     if (200 !== $r->status()) {
         throw new \lang\IllegalArgumentException($r->message() . ': ' . $this->release->toString());
     }
     $release = $r->data();
     Console::writeLine('Release ', $release['version']['number'], ' published ', $release['published']);
     // Download files
     $pth = create(new File($target, 'class.pth'))->getOutputStream();
     foreach ($release['files'] as $file) {
         $d = $this->client->execute(new RestRequest($file['link']));
         $f = new File($target, $file['name']);
         Console::writeLine('>> ', $file['name']);
         $tran = new StreamTransfer($d->stream(), $f->getOutputStream());
         $tran->transferAll();
         $tran->close();
         $ext = substr($file['name'], strrpos($file['name'], '.'));
         if ('.php' === $ext || '.xar' === $ext) {
             $pth->write($file['name'] . "\n");
         }
     }
     $pth->close();
 }
Ejemplo n.º 12
0
function image_tag($src, $alt = NULL, array $attrs = array())
{
    if (is_array($alt)) {
        $attrs = $alt;
        $alt = $src;
    }
    if (!$alt or $alt === $src) {
        $ext = \IO\File::ext($src, TRUE);
        $alt = titlecase(basename($src, $ext));
    }
    $attrs['alt'] = $attrs['title'] = $alt;
    try {
        $img = \Tailor\Helpers::image($src);
        $attrs['width'] = $img['dims'][0];
        $attrs['height'] = $img['dims'][1];
        $attrs['src'] = asset_url($src);
    } catch (\Exception $e) {
        $attrs['src'] = $src;
    }
    return \Labourer\Web\Html::tag('img', $attrs);
}
Ejemplo n.º 13
0
function write($file, $content, $append = FALSE)
{
    return \IO\File::write($file, $content, $append);
}
Ejemplo n.º 14
0
 /**
  * Reads the whole message, applies the header information,
  * sets the body as a plain text (thus does not parse any
  * MIME-Information and returns the created Message object.
  *
  * @param   string filename
  * @return  peer.mail.Message
  * @throws  io.IOException if file cannot be read
  */
 protected function _readMessageRaw($filename)
 {
     $header = '';
     $body = '';
     $f = new File($filename);
     $f->open();
     $d = $f->read($f->size());
     $f->close();
     if (false === ($hdrEnd = strpos($d, "\n\r\n\r"))) {
         $hdrEnd = 0;
     }
     $h = substr($c, 0, $hdrEnd);
     $b = substr($c, $hdrEnd);
     $msg = new \peer\mail\Message();
     $msg->setHdrString($h);
     $msg->setBody($b);
     return $msg;
 }
Ejemplo n.º 15
0
 /**
  * Constructor
  *
  * @param   string $prefix default "tmp"
  */
 public function __construct($prefix = 'tmp')
 {
     parent::__construct(tempnam(Environment::tempDir(), $prefix . uniqid((double) microtime())));
 }
Ejemplo n.º 16
0
 public function rooted_file()
 {
     $rooted = new File('/rooted.ext');
     $this->assertEquals($rooted->getURI(), (new Path($rooted))->toString());
 }
Ejemplo n.º 17
0
 /**
  * Execute this action
  *
  * @param  string[] $args command line args
  * @return int exit code
  */
 public function perform($args)
 {
     if (empty($args)) {
         Console::$err->writeLine('*** Missing argument #1: Module name');
         return 2;
     }
     sscanf($args[0], '%[^@]@%s', $name, $version);
     $module = Module::valueOf($name);
     $cwd = new Folder('.');
     $vendor = new FileCollection(new Folder($cwd, $module->vendor));
     $versions = new FilteredIOCollectionIterator($vendor, new NameMatchesFilter('#^' . $module->name . '@.+#'));
     if (null === $version) {
         // No version given: Remove all installed modules, and the module reference
         if (!$vendor->findElement($module->name . '.json')) {
             Console::writeLine($module, ' not installed');
             return 1;
         }
         $this->removeAll($cwd, $versions);
         Console::writeLine('Removing module reference');
         $vendor->removeElement($module->name . '.json');
     } else {
         // Specific version given: Remove this version, if it's the last one, the
         // module reference, if not, select next possible one.
         if (!($coll = $vendor->findCollection($module->name . '@' . $version))) {
             Console::writeLine($module, ' not installed in version ', $version);
             return 1;
         }
         $active = $this->remove($cwd, $coll);
         if ($versions->hasNext()) {
             if ($active) {
                 $next = $versions->next();
                 $pth = new File('.' . $module->vendor . '.' . basename($next->getURI()) . '.pth');
                 $out = $pth->getOutputStream();
                 $base = strtr(substr($next->getURI(), strlen($cwd->getURI())), DIRECTORY_SEPARATOR, '/');
                 Console::writeLine('Select ', $pth);
                 foreach (new FilteredIOCollectionIterator($next, new ExtensionEqualsFilter('.pth')) as $found) {
                     $r = new StringReader($found->getInputStream());
                     while (null !== ($line = $r->readLine())) {
                         if ('' === $line || '#' === $line[0]) {
                             continue;
                         } else {
                             if ('!' === $line[0]) {
                                 $out->write('!' . $base . substr($line, 1) . "\n");
                             } else {
                                 $out->write($base . $line . "\n");
                             }
                         }
                     }
                 }
             }
         } else {
             Console::writeLine('Removing module reference');
             $vendor->removeElement($module->name . '.json');
         }
     }
     Console::writeLine('Done');
     return 0;
 }
Ejemplo n.º 18
0
 private static function guess($path)
 {
     $ext = \IO\File::ext($path);
     $out = 'images_dir';
     foreach (static::instance()->path as $dir => $set) {
         if (in_array($ext, $set)) {
             $out = $dir;
             break;
         }
     }
     return $out;
 }
Ejemplo n.º 19
0
 /**
  * Execute this action
  *
  * @param  string[] $args command line args
  * @return int exit code
  */
 public function perform($args)
 {
     $cwd = new FileCollection('.');
     // Parse args
     $i = 1;
     if ('-r' === $args[0]) {
         $remote = true;
         array_shift($args);
         $i++;
     } else {
         if ('-i' === $args[0]) {
             $remote = false;
             array_shift($args);
             $i++;
             $installed = new File($args[0] . '.json');
         } else {
             $installed = new File($args[0] . '.json');
             $remote = !$installed->exists();
         }
     }
     if (empty($args)) {
         Console::$err->writeLine('*** Missing argument #', $i, ': Module name');
         return 2;
     }
     sscanf(rtrim($args[0], '/'), '%[^@]@%s', $name, $version);
     $module = Module::valueOf($name);
     // Search for module
     if ($remote) {
         Console::writeLine('@', $this->api->getBase()->getURL());
         $request = create(new RestRequest('/vendors/{vendor}/modules/{module}'))->withSegment('vendor', $module->vendor)->withSegment('module', $module->name);
         try {
             $result = $this->api->execute($request)->data();
         } catch (RestException $e) {
             Console::$err->writeLine('*** Cannot find remote module ', $module, ': ', $e->getMessage());
             return 3;
         }
         $releases = $result['releases'];
     } else {
         Console::writeLine('@', $cwd->getURI());
         try {
             $result = self::$json->decodeFrom($installed->getInputStream());
         } catch (IOException $e) {
             Console::$err->writeLine('*** Cannot find installed module ', $module, ': ', $e->getMessage());
             return 3;
         }
         $releases = $this->installedReleases($cwd, $module);
     }
     Console::writeLine(new Module($result['vendor'], $result['module']), ': ', $result['info']);
     Console::writeLine($result['link']['url']);
     uksort($releases, function ($a, $b) {
         return version_compare($a, $b, '<');
     });
     Console::writeLine('Releases: ', sizeof($releases), ', list {');
     foreach ($releases as $version => $release) {
         $s = '';
         foreach ($release as $key => $value) {
             $s .= ', ' . $key . '= ' . \xp::stringOf($value);
         }
         Console::writeLine('  ', $version, ' (', substr($s, 2), ')');
     }
     Console::writeLine('}');
     // List active releases for local queries
     if (!$remote) {
         foreach (new FilteredIOCollectionIterator($cwd, new NameMatchesFilter('#^\\.' . $module->vendor . '\\.' . $module->name . '.*\\.pth#')) as $found) {
             $r = new StringReader($found->getInputStream());
             Console::writeLine('Selected: ', basename($found->getURI()), ', class path {');
             while (null !== ($line = $r->readLine())) {
                 $resolved = realpath($cwd->getURI() . ltrim($line, '!'));
                 if (is_dir($resolved)) {
                     $cl = \lang\FileSystemClassLoader::instanceFor($resolved, false);
                 } else {
                     if (is_file($resolved)) {
                         $cl = \lang\archive\ArchiveClassLoader::instanceFor($resolved, false);
                     }
                 }
                 Console::writeLine('  ', $cl);
             }
             Console::writeLine('}');
         }
         return 0;
     }
 }
Ejemplo n.º 20
0
 /**
  * Prepare file for writing, including creating its parent directories and ancestors (freak, they're ancients I guess)
  *
  * @param string $path_to_file      Path to file
  * @param boolean $create           [optional] If the file should also be created
  * @param int $chmod                [optional] CHMOD permission to be applied
  * @return \IO\File
  */
 public static function Prepare($path_to_file, $create = false, $chmod = null)
 {
     $file = new File($path_to_file);
     $dirpath = $file->getPathInfo()->getDirname();
     //        if ($file->getName() == "sample2.txt")
     //            dd($dirpath);
     $directory = new \IO\Directory($dirpath);
     if (!$directory->exists()) {
         $directory->createRecursively();
     }
     // reinstantiate, and return
     $file = new File(localpath($directory->getPath(), $file->getName()), $create, $chmod);
     return $file;
 }
 /**
  * Fetches this origin into a given target folder
  *
  * @param  io.Folder $target
  */
 public function fetchInto(Folder $target)
 {
     $zip = $this->zipBallOf($this->url);
     $i = 0;
     with($iter = $zip->iterator());
     $base = rtrim($iter->next()->getName() . '/', '/');
     Console::write('Extracting (', $base, ') [');
     while ($iter->hasNext()) {
         $entry = $iter->next();
         $relative = str_replace($base, '', $entry->getName());
         if ($entry->isDirectory()) {
             $folder = new Folder($target, $relative);
             $folder->exists() || $folder->create(0755);
         } else {
             $file = new File($target, $relative);
             $tran = new StreamTransfer($entry->getInputStream(), $file->getOutputStream());
             $tran->transferAll();
             $tran->close();
         }
         $i++ % 10 || Console::write('.');
     }
     $zip->close();
     Console::writeLine(']');
 }
Ejemplo n.º 22
0
                             $out[$key] = css_min(solve_paths($out[$key]));
                         } else {
                             if (!preg_match('/\\.(min|pack)\\.js$/', $test)) {
                                 $out[$key] = js_min($out[$key]);
                             }
                         }
                         status('prepare', "{$key}");
                     }
                 }
                 // final integration
                 if (!empty($out)) {
                     $set = array_keys($out);
                     write($tmp = path(TMP, md5($file)), join("\n", $out));
                     $hash = md5(md5_file($tmp) . filesize($tmp));
                     $name = str_replace($base_path . DIRECTORY_SEPARATOR, '', $file);
                     $min_file = path($static_dir, \IO\File::extn($name) . "{$hash}.{$type}");
                     if (s3_handle()) {
                         s3_upload_asset($tmp, str_replace($static_dir . DIRECTORY_SEPARATOR, '', $min_file));
                     } else {
                         is_dir(dirname($min_file)) or mkdir(dirname($min_file), 0777, TRUE);
                         rename($tmp, $min_file);
                     }
                     \Sauce\App\Assets::assign($path = str_replace(path($base_path, $type) . DIRECTORY_SEPARATOR, '', $file), $hash);
                     status('hashing', "{$path} [{$hash}]");
                 }
             }
         });
     }
 }
 status('update', 'config/resources.php');
 \Sauce\App\Assets::save();
Ejemplo n.º 23
0
 /**
  * Returns an inputstream for a given name, or NULL
  *
  * @param  string $name
  * @return io.streams.InputStream
  */
 protected function inputStreamFor($name)
 {
     $f = new File($this->base, $name);
     return $f->exists() ? $f->in() : null;
 }
Ejemplo n.º 24
0
 /**
  * Read from a file
  *
  * @deprecated  Use img.io.MetaDataReader instead
  * @param   io.File file
  * @param   var default default void what should be returned in case no data is found
  * @return  img.util.ExifData
  * @throws  lang.FormatException in case malformed meta data is encountered
  * @throws  lang.ElementNotFoundException in case no meta data is available
  * @throws  img.ImagingException in case reading meta data fails
  */
 public static function fromFile(\io\File $file)
 {
     if (false === getimagesize($file->getURI(), $info)) {
         $e = new ImagingException('Cannot read image information from ' . $file->getURI());
         \xp::gc(__FILE__);
         throw $e;
     }
     if (!isset($info['APP1'])) {
         if (func_num_args() > 1) {
             return func_get_arg(1);
         }
         throw new ElementNotFoundException('Cannot get EXIF information from ' . $file->getURI() . ' (no APP1 marker)');
     }
     if (!($info = exif_read_data($file->getURI(), 'COMPUTED,FILE,IFD0,EXIF,COMMENT,MAKERNOTE', true, false))) {
         throw new \lang\FormatException('Cannot get EXIF information from ' . $file->getURI());
     }
     // Change key case for lookups
     foreach ($info as &$val) {
         $val = array_change_key_case($val, CASE_LOWER);
     }
     with($e = new self());
     // COMPUTED info
     $e->setWidth(self::lookup($info['COMPUTED'], 'width'));
     $e->setHeight(self::lookup($info['COMPUTED'], 'height'));
     $e->setApertureFNumber(self::lookup($info['COMPUTED'], 'aperturefnumber'));
     // IFD0 info
     $e->setMake(trim(self::lookup($info['IFD0'], 'make')));
     $e->setModel(trim(self::lookup($info['IFD0'], 'model')));
     $software = self::lookup($info['IFD0'], 'software');
     $e->setSoftware(null === $software ? null : trim($software));
     if (null !== ($o = self::lookup($info['IFD0'], 'orientation'))) {
         $e->setOrientation($o);
     } else {
         $e->setOrientation($e->width / $e->height > 1.0 ? 1 : 5);
     }
     // FILE info
     $e->setFileName(self::lookup($info['FILE'], 'filename'));
     $e->setFileSize(self::lookup($info['FILE'], 'filesize'));
     $e->setMimeType(self::lookup($info['FILE'], 'mimetype'));
     // EXIF info
     $e->setExposureTime(self::lookup($info['EXIF'], 'exposuretime'));
     $e->setExposureProgram(self::lookup($info['EXIF'], 'exposureprogram'));
     $e->setMeteringMode(self::lookup($info['EXIF'], 'meteringmode'));
     $e->setIsoSpeedRatings(self::lookup($info['EXIF'], 'isospeedratings'));
     // Sometimes white balance is in MAKERNOTE - e.g. FUJIFILM's Finepix
     if (null !== ($w = self::lookup($info['EXIF'], 'whitebalance'))) {
         $e->setWhiteBalance($w);
     } else {
         if (isset($info['MAKERNOTE']) && null !== ($w = self::lookup($info['MAKERNOTE'], 'whitebalance'))) {
             $e->setWhiteBalance($w);
         } else {
             $e->setWhiteBalance(null);
         }
     }
     // Extract focal length. Some models store "80" as "80/1", rip off
     // the divisor "1" in this case.
     if (null !== ($l = self::lookup($info['EXIF'], 'focallength'))) {
         sscanf($l, '%d/%d', $n, $frac);
         $e->setFocalLength(1 == $frac ? $n : $n . '/' . $frac);
     } else {
         $e->setFocalLength(null);
     }
     // Check for Flash and flashUsed keys
     if (null !== ($f = self::lookup($info['EXIF'], 'flash'))) {
         $e->setFlash($f);
     } else {
         $e->setFlash(null);
     }
     if (null !== ($date = self::lookup($info['EXIF'], 'datetimeoriginal', 'datetimedigitized'))) {
         $t = sscanf($date, '%4d:%2d:%2d %2d:%2d:%2d');
         $e->setDateTime(new Date(mktime($t[3], $t[4], $t[5], $t[1], $t[2], $t[0])));
     }
     return $e;
 }
Ejemplo n.º 25
0
 /**
  * Save properties to the file
  *
  * @deprecated  Use store() method instead
  * @throws  io.IOException if the property file could not be written
  */
 public function save()
 {
     $fd = new File($this->_file);
     $this->store($fd->getOutputStream());
     $fd->close();
 }
Ejemplo n.º 26
0
 public function can_create_with_file()
 {
     $file = new File($this->tempName());
     $file->touch();
     $this->assertEquals($file, (new FileInput($file))->file());
 }
Ejemplo n.º 27
0
 /**
  * Execute this action
  *
  * @param  string[] $args command line args
  * @return int exit code
  */
 public function perform($args)
 {
     if (empty($args)) {
         Console::$err->writeLine('*** Missing argument #1: Module name');
         return 2;
     }
     sscanf($args[0], '%[^@]@%s', $name, $version);
     $module = Module::valueOf($name);
     $cwd = new Folder('.');
     $base = new Folder($cwd, $module->vendor);
     // No version supplied -> check installation. If the module is already
     // installed, this is "xpi upgrade"'s job. If we have a version, the user
     // wants to install in parallel, so pass.
     if (null === $version) {
         $f = new File($base, $module->name . '.json');
         if ($f->exists()) {
             Console::$err->writeLine('*** Not changing existing ', $module, '. Use "xpi upgrade"');
             return 1;
         }
     }
     // Search for module
     $request = create(new RestRequest('/vendors/{vendor}/modules/{module}'))->withSegment('vendor', $module->vendor)->withSegment('module', $module->name);
     try {
         $info = $this->api->execute($request)->data();
         uksort($info['releases'], function ($a, $b) {
             return version_compare($a, $b, '<');
         });
     } catch (RestException $e) {
         Console::$err->writeLine('*** Cannot find module ', $module, ': ', $e->getMessage());
         return 3;
     }
     // Check newest version
     if (null === $version) {
         if (empty($info['releases'])) {
             Console::$err->writeLine('*** No releases yet for ', $module);
             return 1;
         }
         $version = key($info['releases']);
         $this->cat && $this->cat->info('Using latest release', $version);
     } else {
         if (':' === $version[0]) {
             $this->cat && $this->cat->info('Using development version', $version);
         } else {
             if (!isset($info['releases'][$version])) {
                 Console::$err->writeLine('*** No such release ', $version, ' for ', $module, ', have ', $info['releases']);
                 return 1;
             }
             $this->cat && $this->cat->info('Using version', $version);
         }
     }
     // Determine origin and target
     if (':' === $version[0]) {
         $branch = substr($version, 1);
         $target = new Folder($base, $module->name . '@' . $branch);
         $origin = new GitHubArchive($module->vendor, $module->name, $branch);
     } else {
         $target = new Folder($base, $module->name . '@' . $version);
         $origin = new XarRelease($this->api, $module->vendor, $module->name, $version);
     }
     if ($target->exists()) {
         Console::writeLine($module, ' already exists in ', $target);
     } else {
         Console::writeLine($module, ' -> ', $target);
         try {
             // Create and fetch into
             $target->create(0755);
             $origin->fetchInto($target);
             // Save module meta data
             unset($info['releases']);
             self::$json->encodeTo($info, create(new File($base, $module->name . '.json'))->getOutputStream());
         } catch (\lang\Throwable $e) {
             Console::writeLine('*** ', $e);
             $target->unlink();
             return 2;
         }
     }
     // Deselect any previously selected version
     foreach (new FilteredIOCollectionIterator(new FileCollection($cwd), new NameMatchesFilter('#^\\.' . $module->vendor . '\\.' . $module->name . '.*\\.pth#')) as $found) {
         $pth = new File($found->getURI());
         Console::writeLine('Deselect ', $pth);
         $pth->unlink();
     }
     // Rebuild paths based on .pth files found in newly selected
     $pth = new File('.' . $module->vendor . '.' . strtr($target->dirname, DIRECTORY_SEPARATOR, '.') . '.pth');
     $out = $pth->getOutputStream();
     $base = strtr(substr($target->getURI(), strlen($cwd->getURI())), DIRECTORY_SEPARATOR, '/');
     Console::writeLine('Select ', $pth);
     foreach (new FilteredIOCollectionIterator(new FileCollection($target), new ExtensionEqualsFilter('.pth')) as $found) {
         $r = new StringReader($found->getInputStream());
         while (null !== ($line = $r->readLine())) {
             if ('' === $line || '#' === $line[0]) {
                 continue;
             } else {
                 if ('!' === $line[0]) {
                     $out->write('!' . $base . substr($line, 1) . "\n");
                 } else {
                     $out->write($base . $line . "\n");
                 }
             }
         }
     }
     $out->close();
     Console::writeLine('Done');
     return 0;
 }
Ejemplo n.º 28
0
 /**
  * Assertion helper
  *
  * @param   string expected
  * @return  io.File target
  * @throws  unittest.AssertionFailedError
  */
 private function assertTarget($expected, File $target)
 {
     $this->assertEquals((new File(strtr($expected, '/', DIRECTORY_SEPARATOR)))->getURI(), str_replace(rtrim(realpath('.'), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, '', $target->getURI()));
 }
Ejemplo n.º 29
0
 public function pathClassCanBeUsedAsArg()
 {
     $fn = $this->fileKnownToExist();
     $f = new File(new Path($fn));
     $this->assertEquals($fn, $f->getURI());
 }
 public function movingToAnotherFolder()
 {
     $this->writeData($this->file, null);
     $target = new File($this->folder, $this->file->getFilename());
     $this->file->move($this->folder);
     $exists = $target->exists();
     $target->unlink();
     $this->assertTrue($exists);
 }