/**
  * {@inheritdoc}
  */
 public function handle(\Input $input)
 {
     if ($input->post('FORM_SUBMIT') == 'tl_composer_migrate_undo') {
         /** @var RootPackage $rootPackage */
         $rootPackage = $this->composer->getPackage();
         $requires = $rootPackage->getRequires();
         foreach (array_keys($requires) as $package) {
             if ($package != 'contao-community-alliance/composer') {
                 unset($requires[$package]);
             }
         }
         $rootPackage->setRequires($requires);
         $lockPathname = preg_replace('#\\.json$#', '.lock', $this->configPathname);
         /** @var DownloadManager $downloadManager */
         $downloadManager = $this->composer->getDownloadManager();
         $downloadManager->setOutputProgress(false);
         $installer = Installer::create($this->io, $this->composer);
         if (file_exists(TL_ROOT . '/' . $lockPathname)) {
             $installer->setUpdate(true);
         }
         if ($installer->run()) {
             $_SESSION['COMPOSER_OUTPUT'] .= $this->io->getOutput();
         } else {
             $_SESSION['COMPOSER_OUTPUT'] .= $this->io->getOutput();
             $this->redirect('contao/main.php?do=composer&migrate=undo');
         }
         // load config
         $json = new JsonFile(TL_ROOT . '/' . $this->configPathname);
         $config = $json->read();
         // remove migration status
         unset($config['extra']['contao']['migrated']);
         // write config
         $json->write($config);
         // disable composer client and enable repository client
         $inactiveModules = deserialize($GLOBALS['TL_CONFIG']['inactiveModules']);
         $inactiveModules[] = '!composer';
         foreach (array('rep_base', 'rep_client', 'repository') as $module) {
             $pos = array_search($module, $inactiveModules);
             if ($pos !== false) {
                 unset($inactiveModules[$pos]);
             }
         }
         if (version_compare(VERSION, '3', '>=')) {
             $skipFile = new \File('system/modules/!composer/.skip');
             $skipFile->write('Remove this file to enable the module');
             $skipFile->close();
         }
         if (file_exists(TL_ROOT . '/system/modules/repository/.skip')) {
             $skipFile = new \File('system/modules/repository/.skip');
             $skipFile->delete();
         }
         $this->Config->update("\$GLOBALS['TL_CONFIG']['inactiveModules']", serialize($inactiveModules));
         $this->redirect('contao/main.php?do=repository_manager');
     }
     $template = new \BackendTemplate('be_composer_client_migrate_undo');
     $template->composer = $this->composer;
     $template->output = $_SESSION['COMPOSER_OUTPUT'];
     unset($_SESSION['COMPOSER_OUTPUT']);
     return $template->parse();
 }
Example #2
0
 function main()
 {
     if (empty($this->args)) {
         return $this->err('Usage: ./cake fixturize <table>');
     }
     if ($this->args[0] == '?') {
         return $this->out('Usage: ./cake fixturize <table> [-force] [-reindex]');
     }
     $options = array('force' => false, 'reindex' => false);
     foreach ($this->params as $key => $val) {
         foreach ($options as $name => $option) {
             if (isset($this->params[$name]) || isset($this->params['-' . $name]) || isset($this->params[$name[0]])) {
                 $options[$name] = true;
             }
         }
     }
     foreach ($this->args as $table) {
         $name = Inflector::classify($table);
         $Model = new AppModel(array('name' => $name, 'table' => $table));
         $file = sprintf('%stests/fixtures/%s_fixture.php', APP, Inflector::underscore($name));
         $File = new File($file);
         if ($File->exists() && !$options['force']) {
             $this->err(sprintf('File %s already exists, use --force option.', $file));
             continue;
         }
         $records = $Model->find('all');
         $out = array();
         $out[] = '<?php';
         $out[] = '';
         $out[] = sprintf('class %sFixture extends CakeTestFixture {', $name);
         $out[] = sprintf('	var $name = \'%s\';', $name);
         $out[] = '	var $records = array(';
         $File->write(join("\n", $out));
         foreach ($records as $record) {
             $out = array();
             $out[] = '		array(';
             if ($options['reindex']) {
                 foreach (array('old_id', 'vendor_id') as $field) {
                     if ($Model->hasField($field)) {
                         $record[$name][$field] = $record[$name]['id'];
                         break;
                     }
                 }
                 $record[$name]['id'] = String::uuid();
             }
             foreach ($record[$name] as $field => $val) {
                 $out[] = sprintf('			\'%s\' => \'%s\',', addcslashes($field, "'"), addcslashes($val, "'"));
             }
             $out[] = '		),';
             $File->write(join("\n", $out));
         }
         $out = array();
         $out[] = '	);';
         $out[] = '}';
         $out[] = '';
         $out[] = '?>';
         $File->write(join("\n", $out));
         $this->out(sprintf('-> Create %sFixture with %d records (%d bytes) in "%s"', $name, count($records), $File->size(), $file));
     }
 }
Example #3
0
 /**
  * Write the contents into the file
  *
  * @param   string  $fileName  The full path to the file
  * @param   string  $contents  The contents to write to the file
  *
  * @return  boolean  True on success
  */
 public function write($fileName, $contents)
 {
     $ret = $this->fileAdapter->write($fileName, $contents);
     if (!$ret && is_object($this->abstractionAdapter)) {
         return $this->abstractionAdapter->write($fileName, $contents);
     }
     return $ret;
 }
 /**
  * @see CacheSource::set()
  */
 public function set($cacheResource, $value)
 {
     // write cache
     $targetFile = new File($cacheResource['file']);
     $targetFile->write("<?php exit; /* cache: " . $cacheResource['cache'] . " (generated at " . gmdate('r') . ") DO NOT EDIT THIS FILE */ ?>\n");
     $targetFile->write(serialize($value));
     $targetFile->close();
     // add value
     $this->cache[$cacheResource['cache']] = $value;
     $this->loaded[$cacheResource['file']] = true;
 }
Example #5
0
/**
 * Write CSS cache
 *
 * @param unknown_type $path
 * @param unknown_type $content
 * @return unknown
 */
function write_css_cache($path, $content) {
	if (!is_dir(dirname($path))) {
		mkdir(dirname($path));
	}
	$cache = new File($path);
	return $cache->write($content);
}
Example #6
0
 /**
  * Update the inactive modules
  * @param mixed
  * @return mixed
  */
 public function updateInactiveModules($varValue)
 {
     $arrModules = deserialize($varValue);
     if (!is_array($arrModules)) {
         $arrModules = array();
     }
     foreach (scan(TL_ROOT . '/system/modules') as $strModule) {
         if (strncmp($strModule, '.', 1) === 0) {
             continue;
         }
         // Add the .skip file to disable the module
         if (in_array($strModule, $arrModules)) {
             if (!file_exists(TL_ROOT . '/system/modules/' . $strModule . '/.skip')) {
                 $objFile = new File('system/modules/' . $strModule . '/.skip');
                 $objFile->write('As long as this file exists, the module will be ignored.');
                 $objFile->close();
             }
         } else {
             if (file_exists(TL_ROOT . '/system/modules/' . $strModule . '/.skip')) {
                 $objFile = new File('system/modules/' . $strModule . '/.skip');
                 $objFile->delete();
             }
         }
     }
     return $varValue;
 }
 /**
  * [ADMIN] サイトマップXML生成実行ページ
  */
 public function admin_index()
 {
     $path = WWW_ROOT . Configure::read('Sitemapxml.filename');
     if ($this->request->data) {
         $sitemap = $this->requestAction('/admin/sitemapxml/sitemapxml/create', array('return', $this->request->data));
         ClassRegistry::removeObject('View');
         $File = new File($path);
         $File->write($sitemap);
         $File->close();
         $this->setMessage('サイトマップの生成が完了しました。');
         chmod($path, 0666);
     }
     $dirWritable = true;
     $fileWritable = true;
     if (file_exists($path)) {
         if (!is_writable($path)) {
             $fileWritable = false;
         }
     } else {
         if (!is_writable(dirname($path))) {
             $dirWritable = false;
         }
     }
     $this->set('path', $path);
     $this->set('fileWritable', $fileWritable);
     $this->set('dirWritable', $dirWritable);
     $this->pageTitle = 'サイトマップXML作成';
     $this->render('index');
 }
 public function testDeletingFileMarksBackedPagesAsBroken()
 {
     // Test entry
     $file = new File();
     $file->Filename = 'test-file.pdf';
     $file->write();
     $obj = $this->objFromFixture('Page', 'content');
     $obj->Content = sprintf('<p><a href="[file_link,id=%d]">Working Link</a></p>', $file->ID);
     $obj->write();
     $this->assertTrue($obj->doPublish());
     // Confirm that it isn't marked as broken to begin with
     $obj->flushCache();
     $obj = DataObject::get_by_id("SiteTree", $obj->ID);
     $this->assertEquals(0, $obj->HasBrokenFile);
     $liveObj = Versioned::get_one_by_stage("SiteTree", "Live", "\"SiteTree\".\"ID\" = {$obj->ID}");
     $this->assertEquals(0, $liveObj->HasBrokenFile);
     // Delete the file
     $file->delete();
     // Confirm that it is marked as broken in both stage and live
     $obj->flushCache();
     $obj = DataObject::get_by_id("SiteTree", $obj->ID);
     $this->assertEquals(1, $obj->HasBrokenFile);
     $liveObj = Versioned::get_one_by_stage("SiteTree", "Live", "\"SiteTree\".\"ID\" = {$obj->ID}");
     $this->assertEquals(1, $liveObj->HasBrokenFile);
 }
Example #9
0
 /**
  * Run
  *
  * Runs the application.
  *
  * @param array $args
  * @return true
  * @throws Exception
  */
 public function run(array $args)
 {
     if (!isset($args[1]) || !isset($args[2])) {
         throw new Exception("Invalid input.");
     }
     $command = $args[1];
     $param = $args[2];
     if (count($args) > 4) {
         throw new Exception("Expected 2-3 params, received: " . count($args));
     }
     switch ($command) {
         case 'year':
             $param = (int) $param;
             $out = $this->commandYear($param);
             break;
         case 'matches':
             $out = $this->commandMatches($param);
             break;
         case 'rankings':
             $out = $this->commandRankings($param);
             break;
         default:
             throw new Exception("Unknown command: " . $command);
             break;
     }
     echo $out . PHP_EOL;
     if (isset($args[3])) {
         echo "Saving to " . $args[3] . PHP_EOL;
         if (!File::write($args[3], $out)) {
             throw new Exception("File failed to write.");
         }
     }
     return true;
 }
Example #10
0
 public function disableOldClientHook()
 {
     // disable the repo client
     $reset = false;
     $activeModules = $this->Config->getActiveModules();
     $inactiveModules = deserialize($GLOBALS['TL_CONFIG']['inactiveModules']);
     if (in_array('rep_base', $activeModules)) {
         $inactiveModules[] = 'rep_base';
         $reset = true;
     }
     if (in_array('rep_client', $activeModules)) {
         $inactiveModules[] = 'rep_client';
         $reset = true;
     }
     if (in_array('repository', $activeModules)) {
         $inactiveModules[] = 'repository';
         $skipFile = new \File('system/modules/repository/.skip');
         $skipFile->write('Remove this file to enable the module');
         $skipFile->close();
         $reset = true;
     }
     if ($reset) {
         $this->Config->update("\$GLOBALS['TL_CONFIG']['inactiveModules']", serialize($inactiveModules));
         $this->reload();
     }
     unset($GLOBALS['TL_HOOK']['loadLanguageFiles']['composer']);
 }
Example #11
0
 function testCreateWithFilenameWithSubfolder()
 {
     // Note: We can't use fixtures/setUp() for this, as we want to create the db record manually.
     // Creating the folder is necessary to avoid having "Filename" overwritten by setName()/setRelativePath(),
     // because the parent folders don't exist in the database
     $folder = Folder::findOrMake('/FileTest/');
     $testfilePath = 'assets/FileTest/CreateWithFilenameHasCorrectPath.txt';
     // Important: No leading slash
     $fh = fopen(BASE_PATH . '/' . $testfilePath, "w");
     fwrite($fh, str_repeat('x', 1000000));
     fclose($fh);
     $file = new File();
     $file->Filename = $testfilePath;
     // TODO This should be auto-detected
     $file->ParentID = $folder->ID;
     $file->write();
     $this->assertEquals('CreateWithFilenameHasCorrectPath.txt', $file->Name, '"Name" property is automatically set from "Filename"');
     $this->assertEquals($testfilePath, $file->Filename, '"Filename" property remains unchanged');
     // TODO This should be auto-detected, see File->updateFilesystem()
     // $this->assertType('Folder', $file->Parent(), 'Parent folder is created in database');
     // $this->assertFileExists($file->Parent()->getFullPath(), 'Parent folder is created on filesystem');
     // $this->assertEquals('FileTest', $file->Parent()->Name);
     // $this->assertType('Folder', $file->Parent()->Parent(), 'Grandparent folder is created in database');
     // $this->assertFileExists($file->Parent()->Parent()->getFullPath(), 'Grandparent folder is created on filesystem');
     // $this->assertEquals('assets', $file->Parent()->Parent()->Name);
 }
 /**
  * Step 1: database
  *
  * @return void
  */
 public function database()
 {
     $this->pageTitle = __('Step 1: Database', true);
     if (!empty($this->data)) {
         // test database connection
         if (mysql_connect($this->data['Install']['host'], $this->data['Install']['login'], $this->data['Install']['password']) && mysql_select_db($this->data['Install']['database'])) {
             // rename database.php.install
             rename(APP . 'config' . DS . 'database.php.install', APP . 'config' . DS . 'database.php');
             // open database.php file
             App::import('Core', 'File');
             $file = new File(APP . 'config' . DS . 'database.php', true);
             $content = $file->read();
             // write database.php file
             if (!class_exists('String')) {
                 App::import('Core', 'String');
             }
             $this->data['Install']['prefix'] = '';
             //disabled
             $content = String::insert($content, $this->data['Install'], array('before' => '{default_', 'after' => '}'));
             if ($file->write($content)) {
                 $this->redirect(array('action' => 'data'));
             } else {
                 $this->Session->setFlash(__('Could not write database.php file.', true));
             }
         } else {
             $this->Session->setFlash(__('Could not connect to database.', true));
         }
     }
 }
Example #13
0
 /**
  * Step 1: database
  *
  * @return void
  */
 function database()
 {
     $this->pageTitle = __('Step 1: Database', true);
     if (!empty($this->data)) {
         // test database connection
         if (mysql_connect($this->data['Install']['host'], $this->data['Install']['login'], $this->data['Install']['password']) && mysql_select_db($this->data['Install']['database'])) {
             // rename database.php.install
             rename(APP . 'config' . DS . 'database.php.install', APP . 'config' . DS . 'database.php');
             // open database.php file
             App::import('Core', 'File');
             $file = new File(APP . 'config' . DS . 'database.php', true);
             $content = $file->read();
             // write database.php file
             $content = str_replace('{default_host}', $this->data['Install']['host'], $content);
             $content = str_replace('{default_login}', $this->data['Install']['login'], $content);
             $content = str_replace('{default_password}', $this->data['Install']['password'], $content);
             $content = str_replace('{default_database}', $this->data['Install']['database'], $content);
             if ($file->write($content)) {
                 $this->redirect(array('action' => 'data'));
             } else {
                 $this->Session->setFlash(__('Could not write database.php file.', true));
             }
         } else {
             $this->Session->setFlash(__('Could not connect to database.', true));
         }
     }
 }
Example #14
0
 /**
  * @param array $arr
  * @param $type
  * @throws \Exception
  */
 public function mount(array $arr, $type)
 {
     foreach ($arr as $k => $v) {
         if (array_key_exists($k, $this->format[$type])) {
             $v = $this->parseAlphanum($v);
             if (isset($this->format[$type][$k]['default'])) {
                 $v = $this->getDefault($v, $this->format[$type][$k]['default']);
             }
             if (isset($this->format[$type][$k]['date_format'])) {
                 $v = $this->dateFormat($v, $this->format[$type][$k], $k);
             }
             $v = $this->picture->encode($v, $this->format[$type][$k]['picture']);
             $this->file->write($v, $this->format[$type][$k]['pos'][0]);
         }
     }
 }
Example #15
0
 function find($conditions = null, $fields = array(), $order = null, $recursive = null)
 {
     if ($conditions != 'range') {
         return parent::find($conditions, $fields, $order, $recursive);
     }
     $file = Set::extract($fields, 'file');
     if (empty($file)) {
         $file = ROOT . DS . APP_DIR . DS . 'plugins/mobileip/config/mobile_ips.yml';
     }
     if (!file_exists($file)) {
         return false;
     }
     $cacheDir = $this->getCacheDir();
     $folder = new Folder($cacheDir);
     $folder->create($cacheDir, 0777);
     $cacheFile = $this->getCacheFile();
     if (file_exists($cacheFile) && $this->_getLastModified($file) <= filemtime($cacheFile)) {
         return include $cacheFile;
     }
     $mobile_ips =& Spyc::YAMLLoad($file);
     if (!is_array($mobile_ips)) {
         return false;
     }
     $data = $this->_get_ranges($mobile_ips);
     $file = new File($cacheFile, true);
     $file->write($data);
     $file->close();
     return include $cacheFile;
 }
Example #16
0
 private function log()
 {
     if (!$this->output || strlen($this->output) < 1) {
         return false;
     }
     $endTime = time();
     $this->console('//--------');
     $this->console('Time: ' . ($endTime - $this->startTime) . ' sec.');
     $this->console('Start script: ' . $this->startTime);
     $this->console('End script: ' . $endTime);
     $dir = LOG_DIR . DS . 'cron' . DS . Request::get('app') . DS . Request::get('module') . DS;
     $name = Request::get('action') . '.' . time() . '.' . LOG_FILE_EXTENTION;
     File::mkdir($dir);
     $log = new File($dir . $name, true);
     $log->write($this->output);
     $files = array_map(function ($a) {
         return array('file' => $a, 'time' => filemtime($a));
     }, glob($dir . Request::get('action') . '.*.' . LOG_FILE_EXTENTION));
     usort($files, function ($a, $b) {
         if ($a['time'] == $b['time']) {
             return 0;
         }
         return $a['time'] > $b['time'] ? -1 : 1;
     });
     $delete = array_slice($files, 10);
     foreach ($delete as $file) {
         unlink($file['file']);
     }
 }
 function startTest()
 {
     $dispatcher = new TestShellDispatcher();
     $this->PostReceive = new TestPostReceive($dispatcher);
     Configure::write('Content.git', TMP . 'tests/git/');
     $this->__repos[1] = array('class' => 'Repo.Git', 'type' => 'git', 'path' => TMP . 'tests/git/repo/test.git', 'working' => TMP . 'tests/git/working/test', 'chmod' => 0777);
     $this->PostReceive->Project = ClassRegistry::init('Project');
     $this->PostReceive->Commit = ClassRegistry::init('Commit');
     $this->PostReceive->Timeline = ClassRegistry::init('Timeline');
     $this->PostReceive->Project->User->save(array('username' => 'gwoo'), false);
     $data = array('Project' => array('id' => 1, 'name' => 'test', 'user_id' => 1, 'username' => 'gwoo', 'repo_type' => 'Git', 'private' => 0, 'config' => array('groups' => 'user, docs team, developer, admin', 'ticket' => array('types' => 'rfc, bug, enhancement', 'statuses' => 'pending, approved, in progress, on hold, closed', 'priorities' => 'low, normal, high')), 'description' => 'this is a test project', 'active' => 1, 'approved' => 1, 'remote' => '*****@*****.**'));
     $this->assertTrue($this->PostReceive->Project->save($data));
     $this->assertTrue(file_exists(TMP . 'tests/git/repo/test.git'));
     $this->assertTrue(file_exists(TMP . 'tests/git/working/test/master/.git'));
     $File = new File(TMP . 'tests/git/working/test/master/.gitignore');
     $File->write('this is something new');
     $this->PostReceive->Project->Repo->commit(array("-m", "'Second Commit'"));
     $this->PostReceive->Project->Repo->push();
     $File = new File(TMP . 'tests/git/working/test/master/new.txt');
     $File->write('definitely new');
     $this->PostReceive->Project->Repo->commit(array("-m", "'Third Commit'"));
     $this->PostReceive->Project->Repo->push();
     $this->PostReceive->Project->Repo->update();
     $_SERVER['PHP_CHAWUSER'] = '******';
 }
Example #18
0
 function dot($projects, $relations, $userId, $calculatedProjectIds, $filtertype = "hide")
 {
     // TODO secure $graphname!
     App::import('Model', 'ProjectsUsers');
     $projectsUsersClass = new ProjectsUsers();
     $projectAssocs = $projectsUsersClass->find('list', array('conditions' => array('ProjectsUsers.user_id' => $userId, 'OR' => array('ProjectsUsers.done' => 1, 'ProjectsUsers.wanted' => 1)), 'fields' => array('ProjectsUsers.project_id', 'ProjectsUsers.wanted')));
     $data = 'digraph go4d {' . "\n";
     foreach ($projects as $id => $name) {
         $dotProjectArr = array('label = "WP0' . $id . ': ' . $name . '"');
         $dotProjectArr[] = 'href="project_' . $id . '_imap"';
         if (in_array($id, array_keys($projectAssocs)) && $projectAssocs[$id]['wanted'] == 1) {
             $dotProjectArr[] = 'color="red"';
         } elseif (in_array($id, array_keys($projectAssocs))) {
             $dotProjectArr[] = 'color="green"';
         } elseif (in_array($id, $calculatedProjectIds)) {
             $dotProjectArr[] = 'color="black"';
         } else {
             if ($filtertype == "focus") {
                 $dotProjectArr[] = 'color="#aaaaaa"';
                 $dotProjectArr[] = 'fontcolor="#aaaaaa"';
             } elseif ($filtertype == "hide") {
                 $dotProjectArr = null;
             }
         }
         if ($dotProjectArr) {
             $data .= $id . ' [' . implode(', ', $dotProjectArr) . ']' . ";\n";
         }
     }
     foreach ($relations as $r) {
         $relStart = $r['Relation']['project_preceding_id'] . ' -> ' . $r['Relation']['project_id'];
         $relData = array('color' => 'color="#000044"');
         if ($r['Relation']['type'] == 'constraint') {
             $relData['color'] = 'color="green"';
         }
         if (!(in_array($r['Relation']['project_preceding_id'], $calculatedProjectIds) && in_array($r['Relation']['project_id'], $calculatedProjectIds))) {
             if ($filtertype == "focus") {
                 $relData = array('color' => 'color="#aaaaaa"');
             } elseif ($filtertype == "hide") {
                 $relData = null;
             }
         }
         if ($relData) {
             $data .= $relStart . ' [' . implode(', ', $relData) . "];\n";
         }
     }
     $data .= '}';
     $file = new File(TMP . 'graphs' . DS . $userId . '.dot', true);
     $file->write($data);
     $file->close();
     $cmd = 'dot -v -Tpng -o"' . IMAGES . 'graphs' . DS . $userId . '.png" -Timap_np -o"' . TMP . 'graphs' . DS . $userId . '.map" ' . TMP . 'graphs' . DS . $userId . '.dot';
     $graphOutput = shell_exec($cmd);
     $fn = IMAGES . 'graphs' . DS . $userId . '.png';
     //        header('Content-Length: '.filesize($fn));
     Configure::write('debug', 0);
     header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT', true, 200);
     header('Content-Type: image/png');
     print file_get_contents($fn);
     exit;
     //      return $graphOutput;
 }
Example #19
0
 /**
  * Write data for key into cache
  *
  * @param string $key Identifier for the data
  * @param mixed $data Data to be cached
  * @param mixed $duration How long to cache the data, in seconds
  * @return boolean True if the data was succesfully cached, false on failure
  * @access public
  */
 function write($key, &$data, $duration)
 {
     // Modifications by webligo
     $key .= '.php';
     // end modifications
     if ($data === '' || !$this->__init) {
         return false;
     }
     if ($this->__setKey($key) === false) {
         return false;
     }
     $lineBreak = "\n";
     if ($this->settings['isWindows']) {
         $lineBreak = "\r\n";
     }
     if (!empty($this->settings['serialize'])) {
         if ($this->settings['isWindows']) {
             $data = str_replace('\\', '\\\\\\\\', serialize($data));
         } else {
             $data = serialize($data);
         }
     }
     if ($this->settings['lock']) {
         $this->__File->lock = true;
     }
     $expires = time() + $duration;
     // Original
     $contents = $expires . $lineBreak . $data . $lineBreak;
     // Modifications by webligo
     $contents = "<?php die(); ?>" . $lineBreak . $expires . $lineBreak . $data . $lineBreak;
     // end modifications
     $success = $this->__File->write($contents);
     $this->__File->close();
     return $success;
 }
Example #20
0
 public function auto_compile_less($lessFilename, $cssFilename)
 {
     if (!is_dir(CACHE . 'less')) {
         mkdir(CACHE . 'less');
     }
     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->lessPath, '', $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) {
         $cssFile = new File($cssFilename, true);
         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));
     }
 }
 function testWritingSubsiteID()
 {
     $this->objFromFixture('Member', 'admin')->logIn();
     $subsite = $this->objFromFixture('Subsite', 'domaintest1');
     FileSubsites::$default_root_folders_global = true;
     Subsite::changeSubsite(0);
     $file = new File();
     $file->write();
     $file->onAfterUpload();
     $this->assertEquals((int) $file->SubsiteID, 0);
     Subsite::changeSubsite($subsite->ID);
     $this->assertTrue($file->canEdit());
     $file = new File();
     $file->write();
     $this->assertEquals((int) $file->SubsiteID, 0);
     $this->assertTrue($file->canEdit());
     FileSubsites::$default_root_folders_global = false;
     Subsite::changeSubsite($subsite->ID);
     $file = new File();
     $file->write();
     $this->assertEquals($file->SubsiteID, $subsite->ID);
     // Test inheriting from parent folder
     $folder = new Folder();
     $folder->write();
     $this->assertEquals($folder->SubsiteID, $subsite->ID);
     FileSubsites::$default_root_folders_global = true;
     $file = new File();
     $file->ParentID = $folder->ID;
     $file->onAfterUpload();
     $this->assertEquals($folder->SubsiteID, $file->SubsiteID);
 }
Example #22
0
 /**
  * 生成视图缓存
  *
  * @param string $tplfile
  * @return number
  */
 public function refresh($tplfile)
 {
     $str = File::read($tplfile);
     $str = $this->template_parse($str);
     $strlen = File::write($this->compilefile, $str);
     return $strlen;
 }
 /**
  * Completes the job by zipping up the generated export and creating an
  * export record for it.
  */
 protected function complete()
 {
     $siteTitle = SiteConfig::current_site_config()->Title;
     $filename = preg_replace('/[^a-zA-Z0-9-.+]/', '-', sprintf('%s-%s.zip', $siteTitle, date('c')));
     $dir = Folder::findOrMake(SiteExportExtension::EXPORTS_DIR);
     $dirname = ASSETS_PATH . '/' . SiteExportExtension::EXPORTS_DIR;
     $pathname = "{$dirname}/{$filename}";
     SiteExportUtils::zip_directory($this->tempDir, "{$dirname}/{$filename}");
     Filesystem::removeFolder($this->tempDir);
     $file = new File();
     $file->ParentID = $dir->ID;
     $file->Title = $siteTitle . ' ' . date('c');
     $file->Filename = $dir->Filename . $filename;
     $file->write();
     $export = new SiteExport();
     $export->ParentClass = $this->rootClass;
     $export->ParentID = $this->rootId;
     $export->Theme = $this->theme;
     $export->BaseUrlType = ucfirst($this->baseUrlType);
     $export->BaseUrl = $this->baseUrl;
     $export->ArchiveID = $file->ID;
     $export->write();
     if ($this->email) {
         $email = new Email();
         $email->setTo($this->email);
         $email->setTemplate('SiteExportCompleteEmail');
         $email->setSubject(sprintf('Site Export For "%s" Complete', $siteTitle));
         $email->populateTemplate(array('SiteTitle' => $siteTitle, 'Link' => $file->getAbsoluteURL()));
         $email->send();
     }
 }
Example #24
0
 public function createDatabaseFile($data)
 {
     App::uses('File', 'Utility');
     App::uses('ConnectionManager', 'Model');
     $config = $this->defaultConfig;
     foreach ($data['Install'] as $key => $value) {
         if (isset($data['Install'][$key])) {
             $config[$key] = $value;
         }
     }
     $result = copy(APP . 'Config' . DS . 'database.php.install', APP . 'Config' . DS . 'database.php');
     if (!$result) {
         return __d('croogo', 'Could not copy database.php file.');
     }
     $file = new File(APP . 'Config' . DS . 'database.php', true);
     $content = $file->read();
     foreach ($config as $configKey => $configValue) {
         $content = str_replace('{default_' . $configKey . '}', $configValue, $content);
     }
     if (!$file->write($content)) {
         return __d('croogo', 'Could not write database.php file.');
     }
     try {
         ConnectionManager::create('default', $config);
         $db = ConnectionManager::getDataSource('default');
     } catch (MissingConnectionException $e) {
         return __d('croogo', 'Could not connect to database: ') . $e->getMessage();
     }
     if (!$db->isConnected()) {
         return __d('croogo', 'Could not connect to database.');
     }
     return true;
 }
Example #25
0
File: Alias.php Project: ayaou/Zuha
 /**
  * afterSave
  * 
  * Write out the routes.php file
  */
 public function afterSave($created, $options = array())
 {
     $aliases = $this->find('all');
     $routes = '';
     foreach ($aliases as $alias) {
         $alias['Alias']['name'] = $alias['Alias']['name'] == 'home' ? '' : $alias['Alias']['name'];
         // keyword home is the homepage
         $plugin = !empty($alias['Alias']['plugin']) ? '/' . $alias['Alias']['plugin'] : null;
         $controller = !empty($alias['Alias']['controller']) ? '/' . $alias['Alias']['controller'] : null;
         $action = !empty($alias['Alias']['action']) ? '/' . $alias['Alias']['action'] : null;
         $value = !empty($alias['Alias']['value']) ? '/' . $alias['Alias']['value'] : null;
         $url = $plugin . $controller . $action . $value;
         $routes .= 'Router::redirect(\'' . $url . '\', \'/' . $alias['Alias']['name'] . '\', array(\'status\' => 301));' . PHP_EOL;
         $routes .= 'Router::connect(\'/' . $alias['Alias']['name'] . '\', array(\'plugin\' => \'' . $alias['Alias']['plugin'] . '\', \'controller\' => \'' . $alias['Alias']['controller'] . '\', \'action\' => \'' . $alias['Alias']['action'] . '\', \'' . implode('\', \'', explode('/', $alias['Alias']['value'])) . '\'));' . PHP_EOL;
     }
     App::uses('File', 'Utility');
     $file = new File(ROOT . DS . SITE_DIR . DS . 'Config' . DS . 'routes.php');
     $currentRoutes = str_replace(array('<?php ', '<?php'), '', explode('// below this gets overwritten', $file->read()));
     $routes = '<?php ' . $currentRoutes[0] . '// below this gets overwritten' . PHP_EOL . PHP_EOL . $routes;
     if ($file->write($routes)) {
         $file->close();
     } else {
         $file->close();
         // Be sure to close the file when you're done
         throw new Exception(__('Error writing routes file'));
     }
     // <?php
     // Router::redirect('/webpages/webpages/view/113', '/lenovo', array('status' => 301));
     // Router::connect('/lenovo', array('plugin' => 'webpages', 'controller' => 'webpages', 'action' => 'view', 113));
 }
 /**
  * edit
  *
  * @return void
  */
 public function edit()
 {
     //リクエストセット
     if ($this->request->is('post')) {
         //登録処理
         if (!$this->request->data['SiteSetting']['only_session']) {
             unset($this->request->data['SiteSetting']['only_session']);
             $this->Session->write('debug', null);
             //application.ymlに書き込み
             $conf = Spyc::YAMLLoad(APP . 'Config' . DS . 'application.yml');
             $conf['debug'] = (int) $this->request->data['SiteSetting']['debug']['0']['value'];
             $file = new File(APP . 'Config' . DS . $this->appYmlPrefix . 'application.yml', true);
             $file->write(Spyc::YAMLDump($conf));
             $this->SiteManager->saveData();
         } else {
             $this->SiteSetting->validateDeveloper($this->request->data);
             if (!$this->SiteSetting->validationErrors) {
                 $this->Session->write('debug', (int) $this->request->data['SiteSetting']['debug']['0']['value']);
                 $this->NetCommons->setFlashNotification(__d('net_commons', 'Successfully saved.'), array('class' => 'success'));
                 $this->redirect($this->referer());
             } else {
                 $this->NetCommons->handleValidationError($this->SiteSetting->validationErrors);
             }
         }
     } else {
         $this->request->data['SiteSetting'] = $this->SiteSetting->getSiteSettingForEdit(array('SiteSetting.key' => array('debug')));
         $onlySession = $this->Session->read('debug');
         $this->request->data['SiteSetting']['only_session'] = isset($onlySession);
         if ($this->request->data['SiteSetting']['only_session']) {
             $this->request->data['SiteSetting']['debug']['0']['value'] = $onlySession;
         }
     }
 }
 public function buildCss()
 {
     App::import('Vendor', 'AssetMinify.JSMinPlus');
     // Ouverture des fichiers de config
     $dir = new Folder(Configure::read('App.www_root') . 'css' . DS . 'minified');
     if ($dir->path !== null) {
         foreach ($dir->find('config_.*.ini') as $file) {
             preg_match('`^config_(.*)\\.ini$`', $file, $grep);
             $file = new File($dir->pwd() . DS . $file);
             $ini = parse_ini_file($file->path, true);
             $fileFull = new File($dir->path . DS . 'full_' . $grep[1] . '.css', true, 0644);
             $fileGz = new File($dir->path . DS . 'gz_' . $grep[1] . '.css', true, 0644);
             $contentFull = '';
             foreach ($ini as $data) {
                 // On a pas de version minifié
                 if (!($fileMin = $dir->find('file_' . md5($data['url'] . $data['md5']) . '.css'))) {
                     $fileMin = new File($dir->path . DS . 'file_' . md5($data['url'] . $data['md5']) . '.css', true, 0644);
                     $this->out("Compression de " . $data['file'] . ' ... ', 0);
                     $fileMin->write(MinifyUtils::compressCss(MinifyUtils::cssAbsoluteUrl($data['url'], file_get_contents($data['file']))));
                     $this->out('OK');
                 } else {
                     $fileMin = new File($dir->path . DS . 'file_' . md5($data['url'] . $data['md5']) . '.css');
                 }
                 $contentFull .= $fileMin->read() . PHP_EOL;
             }
             // version full
             $fileFull->write($contentFull);
             $fileFull->close();
             // compression
             $fileGz->write(gzencode($contentFull, 6));
         }
     }
 }
Example #28
0
 function testCache()
 {
     $dir = __DIR__ . '/../cache';
     $cache = new File(['directory' => $dir]);
     $users = ['Masoud', 'Alireza'];
     $cache->write('users', $users);
     $this->assertCount(1, $cache->stats());
     $this->assertTrue($cache->contains('users'));
     $this->assertEquals($users, $cache->read('users'));
     $this->assertFalse($cache->expired('users', 1));
     $i = 0;
     $posts = ['Post 1', 'Post 2'];
     for ($j = 0; $j < 10; $j++) {
         $result = $cache->remember('posts', function () use(&$i, $posts) {
             $i++;
             return $posts;
         }, 10);
     }
     $this->assertEquals(1, $i);
     $this->assertEquals($posts, $result);
     $this->assertEquals($posts, $cache->read('posts'));
     $this->assertCount(2, $cache->stats());
     $cache->delete('users');
     $this->assertFalse($cache->contains('users'));
     $this->assertTrue($cache->contains('posts'));
     $cache->deleteAll();
     $this->assertCount(0, $cache->stats());
     @unlink($dir);
 }
 /**
  * Write data for key into cache
  *
  * @param string $key Identifier for the data
  * @param mixed $data Data to be cached
  * @param mixed $duration How long to cache the data, in seconds
  * @return boolean True if the data was succesfully cached, false on failure
  * @access public
  */
 function write($key, &$data, $duration)
 {
     if ($data === '' || !$this->__init) {
         return false;
     }
     if ($this->__setKey($key) === false) {
         return false;
     }
     $lineBreak = "\n";
     if ($this->settings['isWindows']) {
         $lineBreak = "\r\n";
     }
     if (!empty($this->settings['serialize'])) {
         if ($this->settings['isWindows']) {
             $data = str_replace('\\', '\\\\\\\\', serialize($data));
         } else {
             $data = serialize($data);
         }
     }
     if ($this->settings['lock']) {
         $this->__File->lock = true;
     }
     $expires = time() + $duration;
     $contents = $expires . $lineBreak . $data . $lineBreak;
     $success = $this->__File->write($contents);
     $this->__File->close();
     return $success;
 }
Example #30
0
 function download()
 {
     $result = array('success' => true, 'error' => null);
     $home = Configure::read('20Couch.home');
     App::import('Core', array('HttpSocket', 'File'));
     $Http = new HttpSocket();
     $Setting = ClassRegistry::init('Setting');
     $url = sprintf('%s/registrations/direct/%s/' . Configure::read('Update.file'), $home, $Setting->find('value', 'registration_key'));
     $latest = $Http->get($url);
     if ($latest === false || $Http->response['status']['code'] != 200) {
         if ($Http->response['status']['code'] == 401) {
             $msg = 'Invalid registration key';
         } else {
             $msg = 'Unable to retrieve latest file from ' . $home;
         }
         $this->log($url);
         $this->log($Http->response);
         $result = array('success' => false, 'error' => $msg);
         $this->set('result', $result);
         return;
     }
     $File = new File(TMP . Configure::read('Update.file'), false);
     $File->write($latest);
     $File->close();
     $latestChecksum = trim($Http->get($home . '/checksum'));
     $yourChecksum = sha1_file(TMP . Configure::read('Update.file'));
     if ($yourChecksum != $latestChecksum) {
         $result = array('success' => false, 'error' => 'Checksum doesn\'t match (' . $yourChecksum . ' vs ' . $latestChecksum . ')');
         $this->set('result', $result);
         return;
     }
     $result = array('success' => true, 'error' => null);
     $this->set('result', $result);
 }