Example #1
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);
 }
 private function read_packet()
 {
     $buffer = $this->file->read($this->offset_in_file, $this->buffer_max_size);
     $buffer_size = strlen($buffer);
     $this->offset_in_file += strlen($buffer);
     if ($buffer_size == 0) {
         $this->reached_end_of_file = true;
     }
     return $buffer;
 }
Example #3
0
 public function test_basic_write()
 {
     $file = new File("/tmp/test.txt");
     FuzzyTest::assert_true($file->exists(), "File not found");
     $save_path = DOCUMENT_SAVE_PATH . "/test.txt";
     $file->write($save_path);
     FuzzyTest::assert_true($file->exists(), "File not written");
     $contents = $file->read();
     FuzzyTest::assert_equal($file->read(), "This is the content of the file", "Contents were not read");
     $file->delete();
     FuzzyTest::assert_false($file->exists(), "File not deleted");
 }
 /**
  * Bower update
  *
  * @param Model $model Model using this behavior
  * @param string $plugin Plugin namespace
  * @param string $option It is '' or '--save'. '--save' is used install.
  * @return bool True on success
  */
 public function updateBower(Model $model, $plugin, $option = '')
 {
     if (!$plugin) {
         return false;
     }
     $pluginPath = ROOT . DS . 'app' . DS . 'Plugin' . DS . Inflector::camelize($plugin) . DS;
     if (!file_exists($pluginPath . 'bower.json')) {
         return true;
     }
     $file = new File($pluginPath . 'bower.json');
     $bower = json_decode($file->read(), true);
     $file->close();
     foreach ($bower['dependencies'] as $package => $version) {
         CakeLog::info(sprintf('[bower] Start bower install %s#%s for %s', $package, $version, $plugin));
         $messages = array();
         $ret = null;
         exec(sprintf('cd %s && `which bower` --allow-root install %s#%s %s', ROOT, $package, $version, $option), $messages, $ret);
         // Write logs
         if (Configure::read('debug')) {
             foreach ($messages as $message) {
                 CakeLog::info(sprintf('[bower]   %s', $message));
             }
         }
         CakeLog::info(sprintf('[bower] Successfully bower install %s#%s for %s', $package, $version, $plugin));
     }
     return true;
 }
Example #5
0
 public static function read($sql = false)
 {
     if (!($data = self::_data($sql)) || !($cont = File::read($data['path'] . $data['file']))) {
         return false;
     }
     return unserialize($cont);
 }
Example #6
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;
 }
Example #7
0
 public static function decodeFile($filepath, $toArray = true)
 {
     // Attempt to retrieve the file content
     if ($serializedData = File::read($filepath)) {
         return self::decode($serializedData, $toArray);
     }
 }
Example #8
0
 /**
  * Reads a MagicDb from various formats
  *
  * @var $magicDb mixed Can be an array containing the db, a magic db as a string, or a filename pointing to a magic db in .db or magic.db.php format
  * @return boolean Returns false if reading / validation failed or true on success.
  * @access private
  */
 public function read($magicDb = null)
 {
     if (!is_string($magicDb) && !is_array($magicDb)) {
         return false;
     }
     if (is_array($magicDb) || strpos($magicDb, '# FILE_ID DB') === 0) {
         $data = $magicDb;
     } else {
         $File = new File($magicDb);
         if (!$File->exists()) {
             return false;
         }
         if ($File->ext() == 'php') {
             include $File->pwd();
             $data = $magicDb;
         } else {
             // @TODO: Needs test coverage
             $data = $File->read();
         }
     }
     $magicDb = $this->toArray($data);
     if (!$this->validates($magicDb)) {
         return false;
     }
     return !!($this->db = $magicDb);
 }
Example #9
0
 public function action_create()
 {
     if (Input::method() == 'POST') {
         $config = array('path' => DOCROOT . DS . 'files', 'randomize' => true, 'ext_whitelist' => array('txt'));
         Upload::process($config);
         if (Upload::is_valid()) {
             $file = Upload::get_files(0);
             $contents = File::read($file['file'], true);
             foreach (explode("\n", $contents) as $line) {
                 if (preg_match('/record [0-9]+ BAD- PHONE: ([0-9]+) ROW: \\|[0-9]+\\| DUP: [0-9] [0-9]+/i', $line, $matches)) {
                     $all_dupes[] = $matches[1];
                 }
             }
             $dupe_check = \Goautodial\Insert::duplicate_check($all_dupes);
             foreach ($dupe_check as $dupe_number => $dupe_details) {
                 $new_duplicate = new Model_Data_Supplier_Campaign_Lists_Duplicate();
                 $new_duplicate->list_id = Input::post('list_id');
                 $new_duplicate->database_server_id = Input::post('database_server_id');
                 $new_duplicate->duplicate_number = $dupe_number;
                 $new_duplicate->dialler = $dupe_details['dialler'];
                 $new_duplicate->lead_id = $dupe_details['data']['lead_id'];
                 $new_duplicate->save();
             }
         } else {
             print "No Uploads";
         }
     }
     $this->template->title = "Data_Supplier_Campaign_Lists_Duplicates";
     $this->template->content = View::forge('data/supplier/campaign/lists/duplicates/create');
 }
Example #10
0
 /**
  * Loads a language from cache or locales files
  *
  * @param string $languages	Language code (e.g. en_US or fr_FR)
  */
 public static function load($language)
 {
     if (!preg_match('#^([a-z]{2})(?:_[A-Z]{2})?$#', $language, $match)) {
         throw new Exception('Wrong language format');
     }
     $language_base = $match[0];
     // Locale of PHP
     setlocale(LC_ALL, $language . '.UTF-8', $language_base . '.UTF-8', 'en_EN.UTF-8');
     // Retrieving the translations
     $last_modif = max(filemtime(CF_DIR . 'locales/' . $language), filemtime(APP_DIR . 'locales/' . $language));
     self::$translations = Cache::read('translations_' . $last_modif);
     if (self::$translations != false) {
         return;
     }
     // If the translations cache doesn't exist, we create it
     $vars = '';
     try {
         $vars .= File::read(CF_DIR . 'locales/' . $language);
     } catch (Exception $e) {
         throw new Exception('The L10N file "' . $language . '" for Confeature was not found');
     }
     $vars .= "\n\n";
     try {
         $vars .= File::read(APP_DIR . 'locales/' . $language);
     } catch (Exception $e) {
         throw new Exception('The L10N file "' . $language . '" for the App was not found');
     }
     // Extraction of the variables and storage in the class
     self::$translations = self::parse($vars);
     Cache::write('translations_' . $last_modif, self::$translations, 3600 * 24);
 }
Example #11
0
 /**
  * テーマカラー設定を保存する
  * 
  * @param array $data
  * @return boolean
  */
 public function updateColorConfig($data)
 {
     $configPath = getViewPath() . 'css' . DS . 'config.css';
     if (!file_exists($configPath)) {
         return false;
     }
     $File = new File($configPath);
     $config = $File->read();
     $settings = array('MAIN' => 'color_main', 'SUB' => 'color_sub', 'LINK' => 'color_link', 'HOVER' => 'color_hover');
     $settingExists = false;
     foreach ($settings as $key => $setting) {
         if (empty($data['ThemeConfig'][$setting])) {
             $config = preg_replace("/\n.+?" . $key . ".+?\n/", "\n", $config);
         } else {
             $config = str_replace($key, '#' . $data['ThemeConfig'][$setting], $config);
             $settingExists = true;
         }
     }
     $File = new File(WWW_ROOT . 'files' . DS . 'theme_configs' . DS . 'config.css', true, 0666);
     $File->write($config);
     $File->close();
     if (!$settingExists) {
         unlink($configPath);
     }
     return true;
 }
 /**
  * Delete all values from the cache
  *
  * @param boolean $check Optional - only delete expired cache items
  * @return boolean True if the cache was succesfully cleared, false otherwise
  * @access public
  */
 function clear($check)
 {
     if (!$this->__init) {
         return false;
     }
     $dir = dir($this->settings['path']);
     if ($check) {
         $now = time();
         $threshold = $now - $this->settings['duration'];
     }
     while (($entry = $dir->read()) !== false) {
         if ($this->__setKey($entry) === false) {
             continue;
         }
         if ($check) {
             $mtime = $this->__File->lastChange();
             if ($mtime === false || $mtime > $threshold) {
                 continue;
             }
             $expires = $this->__File->read(11);
             $this->__File->close();
             if ($expires > $now) {
                 continue;
             }
         }
         $this->__File->delete();
     }
     $dir->close();
     return true;
 }
Example #13
0
 function read($dir = null, $recursive = false)
 {
     $notes = array();
     $path = CORE_PATH . APP_PATH . $dir;
     $folder = new Folder(APP_PATH . $dir);
     $fold = $recursive ? $folder->findRecursive('.*\\.php') : $folder->find('.*\\.php');
     foreach ($fold as $file) {
         $file = $recursive ? $file : $path . $file;
         $file_path = r(CORE_PATH . APP_PATH, '', $file);
         $handle = new File($file_path);
         $content = $handle->read();
         $lines = explode(PHP_EOL, $content);
         //$lines = file($file);
         $ln = 1;
         if (!empty($lines)) {
             foreach ($lines as $line) {
                 if ((is_null($this->type) || $this->type == 'TODO') && preg_match("/[#\\*\\/\\/]\\s*TODO\\s*(.*)/", $line, $match)) {
                     $this->notes[$file_path]['TODO'][$ln] = $match[1];
                 }
                 if ((is_null($this->type) || $this->type == 'OPTIMIZE') && preg_match("/[#\\*\\/\\/]\\s*OPTIMIZE|OPTIMISE\\s*(.*)/", $line, $match)) {
                     $this->notes[$file_path]['OPTIMIZE'][$ln] = $match[1];
                 }
                 if ((is_null($this->type) || $this->type == 'FIXME') && preg_match("/[#\\*\\/\\/]\\s*FIXME|BUG\\s*(.*)/", $line, $match)) {
                     $this->notes[$file_path]['FIXME'][$ln] = $match[1];
                 }
                 $ln++;
             }
         }
     }
     return $this->notes;
 }
 /**
  * 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 #15
0
 /**
  * Execute Config/cakegallery.sql to create the tables
  * Create the config File
  * @param $db
  */
 private function _setupDatabase($db)
 {
     # Execute the SQL to create the tables
     $sqlFile = new File(App::pluginPath('Gallery') . 'Config' . DS . 'cakegallery.sql', false);
     $db->rawQuery($sqlFile->read());
     $sqlFile->close();
 }
Example #16
0
 /**
  * undocumented function
  *
  * @return void
  */
 function main()
 {
     $result = $folder = null;
     $mainfiles = explode(',', $this->args[0]);
     $target = !empty($this->params['ext']) ? $this->args[0] . '.' . $this->params['ext'] : $this->args[0] . '.min';
     $jsroot = $this->params['working'] . DS . $this->params['webroot'] . DS . 'js' . DS;
     foreach ((array) $mainfiles as $mainfile) {
         $mainfile = strpos($mainfile, '/') === false ? $jsroot . $mainfile : $mainfile;
         $Pack = new File(str_replace('.js', '', $mainfile) . '.js');
         $result .= JsMin::minify($Pack->read());
     }
     if (!empty($this->args[1])) {
         $folder = $this->args[1] . DS;
         $Js = new Folder($jsroot . $folder);
         list($ds, $files) = $Js->read();
         foreach ((array) $files as $file) {
             $file = strpos($file, '/') === false ? $jsroot . $folder . $file : $file;
             $Pack = new File(str_replace('.js', '', $file) . '.js');
             $result .= JsMin::minify($Pack->read());
         }
     }
     $Packed = new File($jsroot . $target . '.js');
     if ($Packed->write($result, 'w', true)) {
         $this->out($Packed->name() . ' created');
     }
 }
 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 #18
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 #19
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));
 }
 /**
  * Returns an abstract of the file content.
  * 
  * @return	string
  */
 public function getContentPreview()
 {
     if ($this->contentPreview === null) {
         $this->contentPreview = '';
         if (ATTACHMENT_ENABLE_CONTENT_PREVIEW && !$this->isBinary && $this->attachmentSize != 0) {
             try {
                 $file = new File(WCF_DIR . 'attachments/attachment-' . $this->attachmentID, 'rb');
                 $this->contentPreview = $file->read(2003);
                 $file->close();
                 if (CHARSET == 'UTF-8') {
                     if (!StringUtil::isASCII($this->contentPreview) && !StringUtil::isUTF8($this->contentPreview)) {
                         $this->contentPreview = StringUtil::convertEncoding('ISO-8859-1', CHARSET, $this->contentPreview);
                     }
                     $this->contentPreview = StringUtil::substring($this->contentPreview, 0, 500);
                     if (strlen($this->contentPreview) < $file->filesize()) {
                         $this->contentPreview .= '...';
                     }
                 } else {
                     if (StringUtil::isUTF8($this->contentPreview)) {
                         $this->contentPreview = '';
                     } else {
                         $this->contentPreview = StringUtil::substring($this->contentPreview, 0, 500);
                         if ($file->filesize() > 500) {
                             $this->contentPreview .= '...';
                         }
                     }
                 }
             } catch (Exception $e) {
             }
             // ignore errors
         }
     }
     return $this->contentPreview;
 }
Example #21
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));
 }
 /**
  * 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);
             // The database import script does not support prefixes at this point
             $content = str_replace('{default_prefix}', '', $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));
         }
     }
 }
 /**
  * Verifica se os menus do banco estão atualizados com os do arquivo
  * @param $aDados- array de menus do banco
  * @return boolean
  */
 public function isUpToDate($aDados)
 {
     $aDados = Set::combine($aDados, "/Menu/id", "/Menu");
     App::import("Xml");
     App::import("Folder");
     App::import("File");
     $sCaminhosArquivos = Configure::read("Cms.CheckPoint.menus");
     $oFolder = new Folder($sCaminhosArquivos);
     $aConteudo = $oFolder->read();
     $aArquivos = Set::sort($aConteudo[1], "{n}", "desc");
     if (empty($aArquivos)) {
         return false;
     }
     $oFile = new File($sCaminhosArquivos . $aArquivos[0]);
     $oXml = new Xml($oFile->read());
     $aAntigo = $oXml->toArray();
     foreach ($aDados as &$aMenu) {
         $aMenu['Menu']['content'] = str_replace("\r\n", " ", $aMenu['Menu']['content']);
     }
     if (isset($aAntigo["menus"])) {
         $aAntigo["Menus"] = $aAntigo["menus"];
         unset($aAntigo["menus"]);
     }
     if (isset($aAntigo["Menus"])) {
         $aAntigo = Set::combine($aAntigo["Menus"], "/Menu/id", "/Menu");
         $aRetorno = Set::diff($aDados, $aAntigo);
     }
     return empty($aRetorno);
 }
Example #24
0
 /**
  * Determine the format of given database
  *
  * @param mixed $db
  */
 function format($db)
 {
     if (empty($db)) {
         return null;
     }
     if (is_array($db)) {
         return 'Array';
     }
     if (!is_string($db)) {
         return null;
     }
     $File = new File($db);
     if ($File->exists()) {
         if ($File->ext() === 'php') {
             return 'PHP';
         }
         $File->open('rb');
         $head = $File->read(4096);
         if (preg_match('/^(\\d{2}:)?[-\\w.+]*\\/[-\\w.+]+:[\\*\\.a-zA-Z0-9]*$/m', $head)) {
             return 'Freedesktop Shared MIME-info Database';
         } elseif (preg_match('/^[-\\w.+]*\\/[-\\w.+]+\\s+[a-zA-Z0-9]*$/m', $head)) {
             return 'Apache Module mod_mime';
         }
     }
     return null;
 }
Example #25
0
 /**
  * writeBootstrap
  * write bootstrap
  *
  * @param $code
  * @return
  */
 function writeBootstrap()
 {
     $this->out(__('Writeing bootstrap.php ', true) . '...');
     $bootstrapPath = APP_PATH . 'config/bootstrap.php';
     $fp = new File($bootstrapPath);
     $out = $fp->read();
     $imports = array();
     $imports[] = 'App::import(\'Vendor\', \'pear\' . DS . \'pear_init\');';
     if (!empty($this->args)) {
         foreach ($this->args as $value) {
             if (preg_match('/^[A-Z][a-zA-Z2]+[a-zA-Z_]*$/', $value)) {
                 $this->out(__('Set ' . $value, true) . '...');
                 $path = str_replace('_', DS, $value);
                 $imports[] = 'App::import(\'Vendor\', \'' . $value . '\', array(\'file\' => \'' . $path . '.php\'));';
             }
             if (preg_match('/^[a-zA-Z.-]+\\/[A-Z][a-zA-Z2]+[a-zA-Z_]*$/', $value)) {
                 $this->out(__('Set ' . $value, true) . '...');
                 $path = str_replace('_', DS, preg_replace('/^.*\\//', '', $value));
                 $imports[] = 'App::import(\'Vendor\', \'' . preg_replace('/^.*\\//', '', $value) . '\', array(\'file\' => \'' . $path . '.php\'));';
             }
         }
     }
     foreach ($imports as $code) {
         if (strpos($out, $code)) {
             continue;
         }
         if (preg_match('/\\?>/', $out)) {
             $out = preg_replace('/\\?>/', $code . ' // pear_local auto set' . "\n?>", $out);
             $fp->write($out);
         } else {
             $fp->append("\n" . $code . ' // pear_local auto set');
         }
     }
 }
 /**
  * Returns an abstract of the file content.
  * 
  * @param	array		$data
  * @return	string
  */
 protected static function getContentPreview($data)
 {
     if (!ATTACHMENT_ENABLE_CONTENT_PREVIEW || $data['isBinary'] || $data['attachmentSize'] == 0) {
         return '';
     }
     $content = '';
     try {
         $file = new File(WCF_DIR . 'attachments/attachment-' . $data['attachmentID'], 'rb');
         $content = $file->read(2003);
         $file->close();
         if (CHARSET == 'UTF-8') {
             if (!StringUtil::isASCII($content) && !StringUtil::isUTF8($content)) {
                 $content = StringUtil::convertEncoding('ISO-8859-1', CHARSET, $content);
             }
             $content = StringUtil::substring($content, 0, 500);
             if (strlen($content) < $file->filesize()) {
                 $content .= '...';
             }
         } else {
             if (StringUtil::isUTF8($content)) {
                 return '';
             }
             $content = StringUtil::substring($content, 0, 500);
             if ($file->filesize() > 500) {
                 $content .= '...';
             }
         }
     } catch (Exception $e) {
     }
     // ignore errors
     return $content;
 }
Example #27
0
 /**
  * Read Config
  *
  * Read the config from the disk.
  *
  * @return true
  * @throws Exception
  */
 private function read()
 {
     $this->config = json_decode(File::read(STORE . 'config.json'), true);
     if (!$this->config) {
         throw new Exception("Error decoding config Json. Please reset config by deleting the config.");
     }
     return true;
 }
Example #28
0
 public function get($key, $default = false)
 {
     if (is_file($this->path . $key)) {
         $cache = File::read($this->path . $key);
         return $cache === false ? null : unserialize($cache);
     }
     return $default;
 }
 /**
  * Reload from Disk
  *
  * Reloads the team configuration from the disk.
  *
  * @return true
  * @throws Exception
  */
 private function reload()
 {
     $this->config = json_decode(File::read($this->path), true);
     if (!is_array($this->config)) {
         throw new Exception("Decoded team configuration is not an array.");
     }
     return true;
 }
Example #30
0
 public function ingest($type = "meta")
 {
     if ($type == "meta") {
         $meta = new Folder('/Users/n00002621/Dropbox/Research - Cheminfo/OSDB/IS-DB/metadata');
         $files = $meta->find('.*\\.xml');
         foreach ($files as $file) {
             $file = new File($meta->pwd() . DS . $file);
             $text = $file->read();
             $xml = simplexml_load_string($text);
             $data = json_decode(json_encode($xml), true);
             $set = $data['data_set'];
             $sam = $data['sample'];
             $set['id'] = $set['DataSetId'];
             unset($set['DataSetId']);
             $set['author_id'] = $set['ContactAuthor'];
             unset($set['ContactAuthor']);
             $set['publication_id'] = $set['PublicationId'];
             unset($set['PublicationId']);
             $set['sample_id'] = $set['SampleId'];
             unset($set['SampleId']);
             $set['datatype'] = $set['DataType'];
             unset($set['DataType']);
             $set['dataformat'] = $set['DataFormat'];
             unset($set['DataFormat']);
             $set['description'] = $set['Description'];
             unset($set['Description']);
             if (isset($set['Instrument'])) {
                 $set['instrument'] = $set['Instrument'];
                 unset($set['Instrument']);
             } else {
                 $set['instrument'] = "";
             }
             if (isset($set['MeasurementTechnique'])) {
                 $set['measurement'] = $set['MeasurementTechnique'];
                 unset($set['MeasurementTechnique']);
             } else {
                 $set['measurement'] = "";
             }
             $set['oldfilename'] = $set['OldFileName'];
             unset($set['OldFileName']);
             $set['newfilename'] = $set['NewFileName'];
             unset($set['NewFileName']);
             $set['mimetype'] = $set['MimeType'];
             unset($set['MimeType']);
             $set['filesize'] = $set['FileSize'];
             unset($set['FileSize']);
             $set['submitted'] = $set['SubmissionDate'];
             unset($set['SubmissionDate']);
             $set['flags'] = $set['DataSetFlags'];
             unset($set['DataSetFlags']);
             debug($set);
             debug($sam);
             exit;
         }
         debug($files);
         exit;
     }
 }