File PHP Class Code Examples

This page contains top rated real world PHP examples of class File extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: file.class.simpletest.php Project: Ariflaw/b2evolution
0
 /**
  * Test get_ext()
  */
 function testGetExt()
 {
     $File = new File('user', 1, 'abc.def');
     $this->assertEqual($File->get_ext(), 'def', 'Simple file extension recognized.');
     $File = new File('user', 1, 'abc.noext.def');
     $this->assertEqual($File->get_ext(), 'def', 'File extension recognized.');
 }
Example #2
Show file File: Attribute.php Project: humbertcostas/MISP
0
 public function handleMaliciousBase64($event_id, $original_filename, $base64, $hash_types, $proposal = false)
 {
     if (!is_numeric($event_id)) {
         throw new Exception('Something went wrong. Received a non numeric event ID while trying to create a zip archive of an uploaded malware sample.');
     }
     if ($proposal) {
         $dir = new Folder(APP . "files" . DS . $event_id . DS . 'shadow', true);
     } else {
         $dir = new Folder(APP . "files" . DS . $event_id, true);
     }
     $tmpFile = new File($dir->path . DS . $this->generateRandomFileName(), true, 0600);
     $tmpFile->write(base64_decode($base64));
     $hashes = array();
     foreach ($hash_types as $hash) {
         $hashes[$hash] = $this->__hashRouter($hash, $tmpFile->path);
     }
     $contentsFile = new File($dir->path . DS . $hashes['md5']);
     rename($tmpFile->path, $contentsFile->path);
     $fileNameFile = new File($dir->path . DS . $hashes['md5'] . '.filename.txt');
     $fileNameFile->write($original_filename);
     $fileNameFile->close();
     $zipFile = new File($dir->path . DS . $hashes['md5'] . '.zip');
     exec('zip -j -P infected "' . addslashes($zipFile->path) . '" "' . addslashes($contentsFile->path) . '" "' . addslashes($fileNameFile->path) . '"', $execOutput, $execRetval);
     if ($execRetval != 0) {
         $result = array('success' => false);
     } else {
         $result = array_merge(array('data' => base64_encode($zipFile->read()), 'success' => true), $hashes);
     }
     $fileNameFile->delete();
     $zipFile->delete();
     $contentsFile->delete();
     return $result;
 }
Example #3
Show file File: LessHelper.php Project: Marcin11/_mojePanstwo-Portal
0
 public function auto_compile_less($lessFilename, $cssFilename, $plugin = null)
 {
     // Check if cache & output folders are writable and the less file exists.
     if (!is_writable(CACHE . 'less')) {
         trigger_error(__d('cake_dev', '"%s" directory is NOT writable.', CACHE . 'less'), E_USER_NOTICE);
         return;
     }
     if (file_exists($lessFilename) == false) {
         trigger_error(__d('cake_dev', 'File: "%s" not found.', $lessFilename), E_USER_NOTICE);
         return;
     }
     // Cache location
     $cacheFilename = CACHE . 'less' . DS . str_replace('/', '_', str_replace($this->lessFolder->path, '', $lessFilename) . ".cache");
     //         Load the cache
     if (file_exists($cacheFilename)) {
         $cache = unserialize(file_get_contents($cacheFilename));
     } else {
         $cache = $lessFilename;
     }
     $new_cache = Lessify::cexecute($cache);
     if (!is_array($cache) || $new_cache['updated'] > $cache['updated'] || file_exists($cssFilename) === false || md5(serialize($new_cache)) != md5(serialize($cache))) {
         $cssFile = new File($cssFilename, true);
         /*debug('Less cache rebuilt');*/
         if ($cssFile->write($new_cache['compiled']) === false) {
             if (!is_writable(dirname($cssFilename))) {
                 trigger_error(__d('cake_dev', '"%s" directory is NOT writable.', dirname($cssFilename)), E_USER_NOTICE);
             }
             trigger_error(__d('cake_dev', 'Failed to write "%s"', $cssFilename), E_USER_NOTICE);
         }
         $cacheFile = new File($cacheFilename, true);
         $cacheFile->write(serialize($new_cache));
     }
 }
Example #4
Show file File: PageSplitter.php Project: XEdwin/Aspose_Words_Java
0
 public static function SplitDocumentToPages(File $docName)
 {
     $folderName = $docName->getParent();
     $fileName = $docName->getName();
     $extensionName = $fileName->substring($fileName->lastIndexOf("."));
     $outFolder_obj = new File($folderName, "Out");
     $outFolder = $outFolder_obj->getAbsolutePath();
     echo "<BR> Processing document: " . $fileName . $extensionName;
     $doc = new Document($docName->getAbsolutePath());
     // Create and attach collector to the document before page layout is built.
     $layoutCollector = new LayoutCollector(doc);
     // This will build layout model and collect necessary information.
     $doc->updatePageLayout();
     // Split nodes in the document into separate pages.
     $splitter = new DocumentPageSplitter($layoutCollector);
     // Save each page to the disk as a separate document.
     for ($page = 1; $page <= java_values($doc->getPageCount()); $page++) {
         $pageDoc = $splitter->GetDocumentOfPage($page);
         $file_obj = new File($outFolder, MessageFormat::format("{0} - page{1} Out{2}", $fileName, $page, $extensionName));
         $abs_path = $file_obj->getAbsolutePath();
         $pageDoc->save($abs_path);
     }
     // Detach the collector from the document.
     $layoutCollector->setDocument(null);
 }
Example #5
Show file File: filelist.class.simpletest.php Project: Ariflaw/b2evolution
0
 /**
  * Insert three files and sort them with different settings.
  */
 function testSort()
 {
     $FileA = new File('user', 1, 'a');
     $this->Filelist->add($FileA);
     $FileB = new File('user', 1, 'b');
     $this->Filelist->add($FileB);
     $FileC = new File('user', 1, 'c');
     $this->Filelist->add($FileC);
     // ascending, dirs not at top:
     $this->Filelist->sort('name', true, false);
     $this->assertReference($this->Filelist->get_by_idx(0), $FileA, 'First file sorted ok.');
     $this->assertReference($this->Filelist->get_by_idx(1), $FileB, 'Second file sorted ok.');
     $this->assertReference($this->Filelist->get_by_idx(2), $FileC, 'Third file sorted ok.');
     // descending, dirs not at top:
     $this->Filelist->sort('name', false, false);
     $this->assertReference($this->Filelist->get_by_idx(0), $FileC, 'First file sorted ok.');
     $this->assertReference($this->Filelist->get_by_idx(1), $FileB, 'Second file sorted ok.');
     $this->assertReference($this->Filelist->get_by_idx(2), $FileA, 'Third file sorted ok.');
     // Make $FileA a directory
     $FileA->_is_dir = true;
     // descending, dirs at top:
     $this->Filelist->sort('name', false, true);
     $this->assertReference($this->Filelist->get_by_idx(0), $FileA, 'Directory at top.');
     $this->assertReference($this->Filelist->get_by_idx(1), $FileC, 'First File below directory.');
     $this->assertReference($this->Filelist->get_by_idx(2), $FileB, 'Second File below directory.');
     // ascending, dirs not at top:
     $this->Filelist->sort('name', true, false);
     $this->assertReference($this->Filelist->get_by_idx(0), $FileA, 'First file sorted ok.');
     $this->assertReference($this->Filelist->get_by_idx(1), $FileB, 'Second file sorted ok.');
     $this->assertReference($this->Filelist->get_by_idx(2), $FileC, 'Third file sorted ok.');
 }
Example #6
Show file File: ClientHttpGoogleTest.php Project: jxav/oauth_lib
0
 /**
  * testStepByStepTokenRequest
  *
  * @return void
  */
 public function testStepByStepTokenRequest()
 {
     $this->consumer = new Consumer('weitu.googlepages.com', 'secret');
     $this->ConsumerToken = new ConsumerToken($this->consumer, 'token_411a7f', '3196ffd991c8ebdb');
     $requestUri =& new URI('https://www.google.com/accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds');
     $nonce = 'fa95f7d3-8ff0-4dd6-b7f1-49a691ec34ca';
     $timestamp = time();
     $config = array('host' => 'www.google.com', 'scheme' => 'https', 'request' => array('uri' => array('scheme' => 'https', 'host' => 'www.google.com')));
     $http = new HttpSocket($config);
     $token = null;
     $requestParams = array('scheme' => 'header', 'nonce' => $nonce, 'timestamp' => $timestamp, 'signature_method' => 'RSA-SHA1', 'parameters' => array('scope' => 'https://www.google.com/m8/feeds'));
     $privateFile = new File(APP . 'Plugin' . DS . 'OauthLib' . DS . 'Test' . DS . 'Fixture' . DS . 'Certificate' . DS . 'termie.pem');
     $publicFile = new File(APP . 'Plugin' . DS . 'OauthLib' . DS . 'Test' . DS . 'Fixture' . DS . 'Certificate' . DS . 'termie.cer');
     $requestParams['privateCert'] = $privateFile->read();
     $requestParams['privateCertPass'] = '';
     $requestParams['publicCert'] = $publicFile->read();
     $request =& new ClientHttp($http, $requestUri->path . $requestUri->queryWithQ());
     $signatureBaseString = $request->signatureBaseString($http, $this->consumer, $token, $requestParams);
     $this->assertEqual("GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dweitu.googlepages.com%26oauth_nonce%3D{$nonce}%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D{$timestamp}%26oauth_version%3D1.0%26scope%3Dhttps%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds", $signatureBaseString);
     $request->oauth($http, $this->consumer, $token, $requestParams);
     $this->assertEqual('GET', $request->method);
     $response = $request->request();
     $this->assertEqual("200", $response['status']['code']);
     $this->assertEqual("oauth_token=", substr($response['body'], 0, 12));
 }
Example #7
Show file File: VersionedFileTest.php Project: camfindlay/silverstripe-versionedfiles
0
 /**
  * We need to test that the _versions folder isn't completed wiped by
  * {@link VersionedFileExtension::onBeforeDelete()} when there is more than the file currently being deleted.
  */
 public function testOnBeforeDelete()
 {
     // Create the second file
     $file2 = $this->folder->getFullPath() . 'test-file2.txt';
     file_put_contents($file2, 'first-version');
     $file2Obj = new File();
     $file2Obj->ParentID = $this->folder->ID;
     $file2Obj->Filename = $this->folder->getFilename() . 'test-file2.txt';
     $file2Obj->write();
     // Create a second version of the second file
     file_put_contents($file2Obj->getFullPath(), 'second-version');
     $file2Obj->createVersion();
     // Delete the second file
     $file2Obj->delete();
     // Ensure the _versions folder still exists
     $this->assertTrue(is_dir($this->folder->getFullPath()));
     $this->assertTrue(is_dir($this->folder->getFullPath() . '/_versions'));
     // Now delete the first file, and ensure the _versions folder no longer exists
     $this->file->delete();
     $this->assertTrue(is_dir($this->folder->getFullPath()));
     $this->assertFalse(is_dir($this->folder->getFullPath() . '/_versions'));
     // Now create another file to ensure that the _versions folder can be successfully re-created
     $file3 = $this->folder->getFullPath() . 'test-file3.txt';
     file_put_contents($file3, 'first-version');
     $file3Obj = new File();
     $file3Obj->ParentID = $this->folder->ID;
     $file3Obj->Filename = $this->folder->getFilename() . 'test-file3.txt';
     $file3Obj->write();
     $this->assertTrue(is_file($file3Obj->getFullPath()));
     $this->assertTrue(is_dir($this->folder->getFullPath() . '/_versions'));
 }
Example #8
Show file File: FileTest.php Project: fedeisas/lithium
0
 public function testWriteNoExpiry()
 {
     $file = Libraries::get(true, 'resources') . '/tmp/cache/key1';
     $keys = array('key1' => 'data1');
     $adapter = new File(array('expiry' => null));
     $expiry = null;
     $result = $adapter->write($keys, $expiry);
     $this->assertTrue($result);
     $expected = "{:expiry:0}\ndata1";
     $result = file_get_contents($file);
     $this->assertEqual($expected, $result);
     unlink($file);
     $adapter = new File(array('expiry' => Cache::PERSIST));
     $expiry = Cache::PERSIST;
     $result = $adapter->write($keys, $expiry);
     $this->assertTrue($result);
     $expected = "{:expiry:0}\ndata1";
     $result = file_get_contents($file);
     $this->assertEqual($expected, $result);
     unlink($file);
     $adapter = new File();
     $expiry = Cache::PERSIST;
     $result = $adapter->write($keys, $expiry);
     $this->assertTrue($result);
     $expected = "{:expiry:0}\ndata1";
     $result = file_get_contents($file);
     $this->assertEqual($expected, $result);
     unlink($file);
 }
Example #9
Show file File: AuthorizationRepositoryTest.php Project: gbelmm/ACL
0
 /**
  * @depends testInsertBulk
  */
 public function testRemoveForResource()
 {
     $user = new User();
     $this->em->persist($user);
     $resource1 = new File();
     $this->em->persist($resource1);
     $role1 = new FileOwnerRole($user, $resource1);
     $this->em->persist($role1);
     $this->em->flush();
     $resource2 = new File();
     $this->em->persist($resource2);
     $role2 = new FileOwnerRole($user, $resource2);
     $this->em->persist($role2);
     $this->em->flush();
     $authorizations = [Authorization::create($role1, new Actions([Actions::VIEW]), $resource1), Authorization::create($role2, new Actions([Actions::VIEW]), $resource2)];
     /** @var AuthorizationRepository $repository */
     $repository = $this->em->getRepository('MyCLabs\\ACL\\Model\\Authorization');
     $repository->insertBulk($authorizations);
     // We remove the authorizations for the resource 1
     $repository->removeAuthorizationsForResource($resource1);
     // We check that they were removed
     $this->assertFalse($repository->isAllowedOnEntity($user, Actions::VIEW, $resource1));
     // and that authorizations for the resource 2 weren't removed
     $this->assertTrue($repository->isAllowedOnEntity($user, Actions::VIEW, $resource2));
 }
Example #10
Show file File: JobCsvsController.php Project: okagen/fjn
0
 public function getDataInFile($_up_file)
 {
     $fileName = WWW_ROOT . 'files\\job_csv\\dpcsv.csv';
     $file = new File($fileName);
     if ($file->exists()) {
         $this->Session->setFlash('CSVファイルのアップロード実行中。しばらくお待ちください。');
         $this->redirect(array('action' => 'index'));
     }
     //uploadされたファイルをpostという名前でwebrootに保存。
     move_uploaded_file($_up_file, $fileName);
     //DPファイルのインスタンスを作成
     $file = new File($fileName);
     //中身を読込みUTF-8に変換
     $dpData = $file->read();
     $file->close();
     $file->delete();
     //あとで適当な位置に移動
     //UTF-8に変換
     $dpData = mb_convert_encoding($dpData, 'UTF-8', 'sjis');
     //改行コードで分解。一行とみなす。
     $dpData = explode("\r", $dpData);
     //csv形式から配列に変換する
     $dpData = $this->splitDpData($dpData);
     return $dpData;
 }
Example #11
Show file File: ExtractTask.php Project: cc2i/calibrephp
0
 /**
  * Write the files that need to be stored
  *
  * @return void
  */
 protected function _writeFiles()
 {
     $overwriteAll = false;
     if (!empty($this->params['overwrite'])) {
         $overwriteAll = true;
     }
     foreach ($this->_storage as $domain => $sentences) {
         $output = $this->_writeHeader();
         foreach ($sentences as $sentence => $header) {
             $output .= $header . $sentence;
         }
         $filename = $domain . '.pot';
         $File = new File($this->_output . $filename);
         $response = '';
         while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
             $this->out();
             $response = $this->in(__d('cake_console', 'Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', $filename), array('y', 'n', 'a'), 'y');
             if (strtoupper($response) === 'N') {
                 $response = '';
                 while (!$response) {
                     $response = $this->in(__d('cake_console', "What would you like to name this file?"), null, 'new_' . $filename);
                     $File = new File($this->_output . $response);
                     $filename = $response;
                 }
             } elseif (strtoupper($response) === 'A') {
                 $overwriteAll = true;
             }
         }
         $File->write($output);
         $File->close();
     }
 }
Example #12
Show file File: EventShell.php Project: humbertcostas/MISP
0
 public function cachenids()
 {
     $org = $this->args[0];
     $isSiteAdmin = $this->args[1];
     $id = $this->args[2];
     $this->Job->id = $id;
     $format = $this->args[3];
     $sid = $this->args[4];
     $eventIds = $this->Event->fetchEventIds($org, $isSiteAdmin);
     $eventCount = count($eventIds);
     $dir = new Folder(APP . DS . '/tmp/cached_exports/' . $format);
     if ($isSiteAdmin) {
         $file = new File($dir->pwd() . DS . 'misp.' . $format . '.ADMIN.rules');
     } else {
         $file = new File($dir->pwd() . DS . 'misp.' . $format . '.' . $org . '.rules');
     }
     $file->write('');
     foreach ($eventIds as $k => $eventId) {
         if ($k == 0) {
             $temp = $this->Attribute->nids($isSiteAdmin, $org, $format, $sid, $eventId['Event']['id']);
         } else {
             $temp = $this->Attribute->nids($isSiteAdmin, $org, $format, $sid, $eventId['Event']['id'], true);
         }
         foreach ($temp as $line) {
             $file->append($line . PHP_EOL);
         }
         if ($k % 10 == 0) {
             $this->Job->saveField('progress', $k / $eventCount * 80);
         }
     }
     $file->close();
     $this->Job->saveField('progress', '100');
 }
Example #13
Show file File: ClientHttpTermieTest.php Project: jxav/oauth_lib
0
 /**
  * testRsaSha1
  *
  * Need to analyze why term.ie some times return error
  *
  * @return void
  */
 public function testRsaSha1()
 {
     $signatureMethod = 'RSA-SHA1';
     $this->consumer = new Consumer('key', 'secret');
     $requestUri =& new URI('http://term.ie/oauth/example/request_token.php');
     $nonce = rand(0, pow(2, 128));
     $timestamp = time();
     $config = array('host' => 'term.ie', 'request' => array('uri' => array('host' => 'term.ie')));
     $http = new HttpSocket($config);
     $token = null;
     $requestParams = array('scheme' => 'query_string', 'nonce' => $nonce, 'timestamp' => $timestamp, 'signature_method' => $signatureMethod);
     $privateFile = new File(APP . 'Plugin' . DS . 'OauthLib' . DS . 'Test' . DS . 'Fixture' . DS . 'Certificate' . DS . 'termie.pem');
     $publicFile = new File(APP . 'Plugin' . DS . 'OauthLib' . DS . 'Test' . DS . 'Fixture' . DS . 'Certificate' . DS . 'termie.cer');
     $requestParams['privateCert'] = $privateFile->read();
     $requestParams['publicCert'] = $publicFile->read();
     $requestParams['privateCertPass'] = '';
     $request =& new ClientHttp($http, $requestUri->path . $requestUri->queryWithQ());
     $signatureBaseString = $request->signatureBaseString($http, $this->consumer, $token, $requestParams);
     $this->assertEqual("GET&http%3A%2F%2Fterm.ie%2Foauth%2Fexample%2Frequest_token.php&oauth_consumer_key%3Dkey%26oauth_nonce%3D{$nonce}%26oauth_signature_method%3D{$signatureMethod}%26oauth_timestamp%3D{$timestamp}%26oauth_version%3D1.0", $signatureBaseString);
     $request =& new ClientHttp($http, $requestUri->path . $requestUri->queryWithQ());
     $request->oauth($http, $this->consumer, $token, $requestParams);
     $this->assertEqual('GET', $request->method);
     $this->assertEqual('', $request->body());
     $this->assertEqual('', $request->authorization);
     $response = $request->request();
     $this->assertEqual("200", $response['status']['code']);
     $this->assertEqual("oauth_token=requestkey&oauth_token_secret=requestsecret", $response['body']);
 }
Example #14
Show file File: extract.php Project: cls1991/ryzomcore
0
 /**
  * Write the files that need to be stored
  *
  * @return void
  * @access private
  */
 function __writeFiles()
 {
     $overwriteAll = false;
     foreach ($this->__storage as $domain => $sentences) {
         $output = $this->__writeHeader();
         foreach ($sentences as $sentence => $header) {
             $output .= $header . $sentence;
         }
         $filename = $domain . '.pot';
         $File = new File($this->__output . $filename);
         $response = '';
         while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
             $this->out();
             $response = $this->in(sprintf(__('Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', true), $filename), array('y', 'n', 'a'), 'y');
             if (strtoupper($response) === 'N') {
                 $response = '';
                 while ($response == '') {
                     $response = $this->in(sprintf(__("What would you like to name this file?\nExample: %s", true), 'new_' . $filename), null, 'new_' . $filename);
                     $File = new File($this->__output . $response);
                     $filename = $response;
                 }
             } elseif (strtoupper($response) === 'A') {
                 $overwriteAll = true;
             }
         }
         $File->write($output);
         $File->close();
     }
 }
Example #15
Show file File: TidyHelper.php Project: cc2i/calibrephp
0
 /**
  * Run the html string through tidy, and return the (raw) errors. pass back a reference to the
  * normalized string so that the error messages can be linked to the line that caused them.
  *
  * @param string $in ''
  * @param string $out ''
  * @return string
  * @access public
  */
 public function tidyErrors($in = '', &$out = '')
 {
     $out = preg_replace('@>\\s*<@s', ">\n<", $in);
     // direct access? windows etc
     if (function_exists('tidy_parse_string')) {
         $tidy = tidy_parse_string($out, array(), 'UTF8');
         $tidy->cleanRepair();
         $errors = $tidy->errorBuffer . "\n";
         return $errors;
     }
     // cli
     $File = new File(rtrim(TMP, DS) . DS . rand() . '.html', true);
     $File->write($out);
     $path = $File->pwd();
     $errors = $path . '.err';
     $this->_exec("tidy -eq -utf8 -f {$errors} {$path}");
     $File->delete();
     if (!file_exists($errors)) {
         return '';
     }
     $Error = new File($errors);
     $errors = $Error->read();
     $Error->delete();
     return $errors;
 }
Frequently Used Methods