/** * Write a file from an array * * @param array $data A PhpBaker style array * @return boolean */ public function write($data = array()) { $data = Set::merge($this->data, $data); $data['class'] = Set::merge(array('doc' => "/**\n * " . $this->class . "\n * \n */", 'class' => '', 'uses' => ''), $data['class']); $code = '<?php' . "\n"; if (!empty($data['class']['uses'])) { $uses = array_unique($data['class']['uses']); $code .= implode("\n", $uses) . "\n\n"; } $code .= $data['class']['doc'] . "\n"; $code .= $data['class']['class'] . " {\n"; foreach ($data['properties'] as $prop => $arr) { $type = is_array($arr['value']) ? 'array' : 'string'; $arr = Set::merge(array('doc' => "/**\n * {$prop}\n * \n * @var {$type}\n */", 'value' => '', 'access' => 'public'), $arr); $code .= $arr['doc'] . "\n"; if (is_array($arr['value'])) { $val = $this->arrayToCode($arr['value'], 2); } else { $val = "'" . $arr['value'] . "'"; } $code .= "\t" . $arr['access'] . " \${$prop} = {$val};\n\n"; } foreach ($data['methods'] as $meth => $arr) { $arr = Set::merge(array('doc' => "/**\n * {$meth}\n * \n */", 'value' => "\tpublic function {$meth}() {\n\t\t\n\t}"), $arr); $code .= $arr['doc'] . "\n"; $code .= $arr['value'] . "\n"; } $code .= '}'; file_put_contents($this->_File->pwd(), $code); return true; }
/** * 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); }
/** * Create the rendered view cache file * * @param string $file The view file path * * @return string The file path */ protected function _createRenderedView($file) { $content = $this->_renderHaml($file); $tmpFile = new File($this->_cacheFileName(), true); $tmpFile->write($content); $tmpFile->close(); return $tmpFile->pwd(); }
/** * Get absolute file for a given key * * @param string $key The key * @return mixed Absolute cache file for the given key or false if erroneous * @access private */ function _setKey($key) { $this->_File->Folder->cd($this->settings['path']); if ($key !== $this->_File->name) { $this->_File->name = $key; $this->_File->path = null; } if (!$this->_File->Folder->inPath($this->_File->pwd(), true)) { return false; } }
function upload_file() { $file = $this->getNextParam(null, 'file'); $container = $this->getNextParam(null, 'container'); if (empty($file) || empty($container)) { $this->errorAndExit('File and Container required'); } $File = new File($file); $file_path = $File->pwd(); CloudFiles::upload($file_path, $container, $this->params['type']); $this->out($File->name . " uploaded to {$container}"); }
function testCommit() { $Svn = new Svn($this->__repos[1]); $File = new File($Svn->working . '/branches/demo_1.0.x.x/index.php', true); $File->write("this is a new php file with plain text"); $result = $Svn->run('add', array(dirname($File->pwd()))); //var_dump($result); $result = $Svn->run('commit', array($Svn->working, '--message "Adding index.php"')); //var_dump($result); $result = $Svn->info('/branches/demo_1.0.x.x/index.php'); //var_dump($result); }
private function createLayoutFile($name, $layout_type, $override = false) { $layout_file = new File('' . $this->layout_folder . '' . $name . '.ctp'); $template_file = new File($this->layout_files['' . $layout_type . '']); if ($this->layoutFileExists($name) && $override == true) { $layout_file->delete(); } $this->hr(); $this->out(__d('cake_console', '<yellow>Creating layout file `' . $layout_file->pwd() . '`:</yellow>')); if ($layout_file->create()) { $content = $template_file->read(); if ($layout_file->write($content)) { $this->out(__d('cake_console', '<green>SUCCESS!</green>')); } else { $this->out(__d('cake_console', 'Could not write contents to `' . $layout_file->pwd() . '`')); } } else { $this->error(__d('cake_console', 'Could not create file!')); } }
/** * Create or update the installed.php file with version details * * @return void */ function _writeInstalled($schema = SCHEMA_VERSION) { $file = new File(CONFIGS . 'installed.php', true); $date = date('r'); $version = ZULURU_MAJOR . '.' . ZULURU_MINOR . '.' . ZULURU_REVISION; $installed = <<<CONFIG <?php \$config['installed'] = array( \t'date' => '{$date}', \t'ip' => '{$_SERVER['REMOTE_ADDR']}', \t'version' => '{$version}', \t'schema_version' => {$schema}, ); ?> CONFIG; if (!$file->write($installed)) { $this->set('config_file', $file->pwd()); $this->set('config_contents', $installed); return false; } return true; }
/** * Retrieve (cached) metadata of a file * * @param Model $Model * @param string $file An absolute path to a file * @param integer $level level of amount of info to add, `0` disable, `1` for basic, `2` for detailed info * @return mixed Array with results or false if file is not readable */ function metadata(&$Model, $file, $level = 1) { if ($level < 1) { return array(); } extract($this->settings[$Model->alias]); $File = new File($file); if (!$File->readable()) { return false; } $checksum = $File->md5(true); if (isset($this->__cached[$Model->alias][$checksum])) { $data = $this->__cached[$Model->alias][$checksum]; } if ($level > 0 && !isset($data[1])) { $data[1] = array('size' => $File->size(), 'mime_type' => MimeType::guessType($File->pwd()), 'checksum' => $checksum); } if ($level > 1 && !isset($data[2])) { $Media = Media::factory($File->pwd()); if ($Media->name === 'Audio') { $data[2] = array('artist' => $Media->artist(), 'album' => $Media->album(), 'title' => $Media->title(), 'track' => $Media->track(), 'year' => $Media->year(), 'length' => $Media->duration(), 'quality' => $Media->quality(), 'sampling_rate' => $Media->samplingRate(), 'bit_rate' => $Media->bitRate()); } elseif ($Media->name === 'Image') { $data[2] = array('width' => $Media->width(), 'height' => $Media->height(), 'ratio' => $Media->ratio(), 'quality' => $Media->quality(), 'megapixel' => $Media->megapixel()); } elseif ($Media->name === 'Text') { $data[2] = array('characters' => $Media->characters(), 'syllables' => $Media->syllables(), 'sentences' => $Media->sentences(), 'words' => $Media->words(), 'flesch_score' => $Media->fleschScore(), 'lexical_density' => $Media->lexicalDensity()); } elseif ($Media->name === 'Video') { $data[2] = array('title' => $Media->title(), 'year' => $Media->year(), 'length' => $Media->duration(), 'width' => $Media->width(), 'height' => $Media->height(), 'ratio' => $Media->ratio(), 'quality' => $Media->quality(), 'bit_rate' => $Media->bitRate()); } else { $data[2] = array(); } } for ($i = $level, $result = array(); $i > 0; $i--) { $result = array_merge($result, $data[$i]); } $this->__cached[$Model->alias][$checksum] = $data; return Set::filter($result); }
/** * Protects the transfer directory * * @access public * @return void */ function protect() { if (MEDIA_TRANSFER_URL === false) { $this->out('The content of the transfer directory is not served.'); return true; } $file = MEDIA_TRANSFER . '.htaccess'; if (is_file($file)) { $this->err($this->shortPath($file) . ' is already present.'); return true; } $this->out('Your transfer directory is missing a htaccess file to block requests.'); if ($this->in('Do you want to create it now?', 'y,n', 'n') == 'n') { return false; } $File = new File($file); $File->append("Order deny,allow\n"); $File->append("Deny from all\n"); $File->close(); $this->out($this->shortPath($File->pwd()) . ' created.'); $this->out(); return true; }
/** * admin_edit method * * @param mixed $id * @access public * @return void */ public function admin_edit($id) { if ($this->data) { $file = new File(TMP . rand()); $file->write('<?php $this->data["MiEmail"]["data"] = ' . $this->data['MiEmail']['data'] . ';'); include $file->pwd(); $file->delete(); if ($this->MiEmail->save($this->data)) { return $this->_back(); } } parent::admin_edit($id); $this->data['MiEmail']['data'] = var_export($this->data['MiEmail']['data'], true); }
/** * htmlTidy method * * Disabled for windows * * @param mixed $Model * @param string $string '' * @param array $params array() * @return string * @access public */ function htmlTidy(&$Model, $string = '', $params = array()) { if (DS === '\\') { return true; } extract(am($this->settings[$Model->alias]['methods']['htmlTidy'], $params)); $string = $prefix . $string . $suffix; $File = new File(TMP . 'tidy' . DS . rand() . '.html', true); $File->write($string); $path = $File->pwd(); $errors = $path . '.err'; $args = implode($args, ' '); $this->_exec("tidy {$args} -f {$errors} {$path}", $out); $result = $File->read(); $File->delete(); if ($result && $bodyOnly) { preg_match("@<body[^>]*>(.*)</body>@s", $result, $matches); if ($matches) { $result = trim($matches[1]); } } if (file_exists($errors)) { $Error = new File($errors); $errors = $Error->read(); $Error->delete(); } else { $errors = false; } if ($return === 'result') { return $result; } elseif ($return === 'errors') { return $errors; } return $string === $result; }
/** * Tests that no path is being set for passed file paths that * do not exist. * * @return void * @covers ::pwd */ public function testNoPartialPathBeingSetForNonExistentPath() { $tmpFile = new File('/non/existent/file'); $this->assertNull($tmpFile->pwd()); $this->assertNull($tmpFile->path); }
/** * 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; }
function importAnnotationsAndDocuments() { $this->Round = $this->Project->Round; $this->Document = $this->Project->Document; $this->UsersRound = $this->Project->User->UsersRound; $this->AnnotatedDocument = $this->Round->AnnotatedDocument; $this->Type = $this->Project->Type; $this->Annotation = $this->Type->Annotation; $maxAnnotation = $this->Annotation->find('first', array('recursive' => -1, 'fields' => 'id', 'order' => 'id DESC')); if (isset($maxAnnotation['Annotation']['id'])) { $maxAnnotation = $maxAnnotation['Annotation']['id']; } else { $maxAnnotation = 0; } $maxType = $this->Project->Type->find('first', array('recursive' => -1, 'fields' => 'id', 'order' => 'id DESC')); if (isset($maxType['Type']['id'])) { $maxType = $maxType['Type']['id']; } else { $maxType = 0; } if ($this->request->is('post') || $this->request->is('put')) { $maxAnnotation++; App::uses('Folder', 'Utility'); App::uses('File', 'Utility'); App::uses('CakeTime', 'Utility'); $scriptTimeLimit = Configure::read('scriptTimeLimit'); set_time_limit($scriptTimeLimit); $users = $this->request->data['User']['User']; //App::import('Vendor', 'htmLawed', array('file' => 'htmLawed' . DS . 'htmLawed.php')); $zipFile = new File($this->request->data['Project']['File']['tmp_name'], false, 0777); $projectName = ucwords(pathinfo($this->request->data['Project']['File']['name'], PATHINFO_FILENAME)); if ($zipFile->exists() && !empty($users)) { $filesAllowed = Configure::read('filesAllowed'); $zip = new ZipArchive(); if (!$zip->open($zipFile->pwd(), ZipArchive::CREATE)) { $zipFile->remove(); throw new Exception("Failed to open Zip archive\n"); } $path = Configure::read('uploadFolder'); $path = $path . uniqid(); //creamos la carpeta de descarga para el usuario si no existe $extractFolder = new Folder($path, true, 0700); $zip->extractTo($extractFolder->pwd()); $zip->close(); $zipFile->delete(); // I am deleting this file $rounds = array(); $db = $this->Project->getDataSource(); $db->query("ALTER TABLE annotations AUTO_INCREMENT = {$maxAnnotation}"); $db->execute("LOCK TABLES " . $this->Annotation->table . " " . $this->Type->table . " WRITE"); $db->begin(); $db->useNestedTransactions = false; $this->Project->create(); if ($this->Project->save(array('Project' => array("title" => $projectName, "description" => ""), "User" => array('User' => $users)))) { //creamos round de anotacion automatica $this->Round->create(); if (!$this->Round->save(array('Round' => array("title" => "Round for job " . date("Y/m/d"), "project_id" => $this->Project->id, "description" => "-", 'ends_in_date' => date("Y-m-d", strtotime("+30 day")), 'trim_helper' => true, 'whole_word_helper' => true, 'punctuation_helper' => true, 'start_document' => 0, 'end_document' => 0, 'is_visible' => 0)))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("Round work can not be saved"); } array_push($rounds, $this->Round->id); foreach ($users as $user) { foreach ($rounds as $round) { $this->UsersRound->create(); if (!$this->UsersRound->save(array('state' => 0, 'round_id' => $round, 'user_id' => $user))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("This UsersRound can not be save:" . $fileName); } } } $typesText = new File($extractFolder->pwd() . DS . 'types.txt', false, 0644); if (!$typesText->exists()) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("types.txt not exist in zip file"); } $count = new File($extractFolder->pwd() . DS . 'count.txt', false, 0644); if (!$count->exists()) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("count.txt not exist in zip filer"); } $typesText = $typesText->read(); $count = $count->read(); $count = intval($count) + 1; //buscamos la anotacion final con dicho Id si ya existe no se puede crear el proyecto $existLastId = $this->Annotation->find('count', array('recursive' => -1, 'conditions' => array('id' => $count))); $existInitialId = $this->Annotation->find('count', array('recursive' => -1, 'conditions' => array('id' => $count - ($count - $maxAnnotation)))); if ($existInitialId > 0) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("the first id already exist in Marky"); } if ($existLastId > 0) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("the last id already exist in Marky"); } $types = preg_split("/[\r\n]+/", trim($typesText)); $typesMap = array(); $defaultColors = Configure::read('defaultColors'); $colorCont = 0; foreach ($types as $type) { //debug($types); $type = explode("\t", $type); if (sizeof($type) > 1) { $typeName = $type[0]; $typeId = $type[1]; $typeName = str_replace(' ', '_', $typeName); if (!empty($defaultColors[$colorCont])) { $color = $defaultColors[$colorCont]; $colorCont++; } else { $color = array(rand(50, 255), rand(50, 255), rand(50, 255)); } $this->Type->create(); if ($this->Type->save(array('Type' => array('id' => $typeId, 'name' => $typeName, 'project_id' => $this->Project->id, 'colour' => $color[0] . ',' . $color[1] . ',' . $color[2] . ',1'), 'Round' => array('Round' => $rounds)))) { $typesMap[$typeName] = $this->Type->id; } else { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); // debug($types); // debug($this->Project->Type->validationErrors); throw new Exception("This type can not be save" . $type); } } else { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); // debug($types); // debug($this->Project->Type->validationErrors); throw new Exception("This type can not be save" . $type); } } $files = $extractFolder->find('.*.html', true); if (empty($files)) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("The html documents can not be read"); } //$config = array('cdata' => 1, 'safe' => 1, 'keep_bad' => 6, 'no_depreca ted_attr' => 2, 'valid_xhtml' => 1, 'abs_url' => 1); $annotationsAcumulate = array(); foreach ($files as $file) { //sleep(5); $fileName = substr($file, 0, strrpos($file, '.')); $file = new File($extractFolder->pwd() . DS . $file); if ($file->readable()) { //$content = '<p>' . preg_replace("/\.\s*\n/", '.</p><p>', $file->read()) . '</p>'; $content = $file->read(); if (strlen($content) > 1) { $file->close(); $date = date("Y-m-d H:i:s"); $document = $this->Document->find('first', array('recursive' => -1, 'conditions' => array('external_id' => $fileName))); if (empty($document)) { $this->Document->create(); if (!$this->Document->save(array('Document' => array('external_id' => $fileName, 'title' => $fileName, 'html' => strip_tags($content), 'created' => $date), 'Project' => array('Project' => $this->Project->id)))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("This Document can not be save:" . $fileName); } } else { $this->Document->id = $document['Document']['id']; if (!$this->Document->save(array('Document' => array('id' => $this->Document->id), 'Project' => array('Project' => $this->Project->id)))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("This Document - Project can not be save"); } } $annotations = $this->getAnnotations($content, $typesMap, $this->Document->id); $tam = count($annotations); $modes = Configure::read('annotationsModes'); // $results = gzdeflate($content, 9); foreach ($users as $user) { foreach ($rounds as $round) { $this->AnnotatedDocument->create(); if (!$this->AnnotatedDocument->save(array('text_marked' => $content, 'document_id' => $this->Document->id, 'mode' => $modes["AUTOMATIC"], 'round_id' => $round, 'user_id' => $user))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("This UsersRound can not be save:" . $fileName); } if (!empty($annotations)) { for ($index = 0; $index < $tam; $index++) { $annotations[$index]['user_id'] = $user; $annotations[$index]['round_id'] = $round; //// if ($round == $this->Round->id) { ////// $annotations[$index]['id'] = $maxAnnotation; ////// $maxAnnotation++; //// } } $annotationsAcumulate = array_merge($annotationsAcumulate, $annotations); } } } if (count($annotationsAcumulate) > 500) { if (!$this->Project->Type->Annotation->saveMany($annotationsAcumulate)) { //debug($annotations); debug($this->Project->Type->Annotation->validationErrors[0]); debug($fileName); $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("Annotations can not be save"); } $annotationsAcumulate = array(); } } } } if (count($annotationsAcumulate) > 0) { if (!$this->Annotation->saveMany($annotationsAcumulate)) { //debug($annotations); debug($this->Project->Type->Annotation->validationErrors[0]); debug($fileName); $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("Annotations can not be save"); } } // throw new Exception; $extractFolder->delete(); $db->commit(); $db->execute("UNLOCK TABLES"); $this->Session->setFlash(__('Project has been created with documents imported'), 'success'); $this->redirect(array('action' => 'index')); } $extractFolder->delete(); } else { $this->Session->setFlash(__('Choose almost one user and one file')); } } $userConditions = array('group_id' => 2); $users = $this->Project->User->find('list', array('conditions' => $userConditions)); $this->set(compact('users', 'maxAnnotation', 'maxType')); }
/** * get output file path */ function getOutputPath() { return $this->File->pwd(); }
public function configureCity() { $options['group'] = 'city'; $options['fields'] = array('jiscode', 'city'); $results = $this->Zipcode->find('all', $options); foreach ($results as $item) { $array[$item['Zipcode']['jiscode']] = $item['Zipcode']['city']; } $array = var_export($array, true); $code = "<?php\n\$config['city'] = {$array};"; $target = realpath(APP . '/config/city.php'); $file = new File(TMP . 'city_' . time() . '.php', true); $file->write($code); if (file_exists($target)) { $this->out(__d('zipcode', 'city.php exists already at...', true)); $this->out($target, 2); $this->out(__d('zipcode', 'File for Configure is written.', true)); $this->out(__d('zipcode', 'You can rename and move this file...', true)); $this->out($file->pwd()); } else { if (false === rename($file->pwd(), $target)) { $this->out(__d('zipcode', 'Something wrong to move a file', true)); return; } $this->out(__d('zipcode', 'city.php is written to...', true)); $this->out($target); } }
/** * undocumented function * * @param string $data * @return void */ function createShell($data = array()) { $template = CONFIGS . 'templates' . DS; $chaw = Configure::read('Content.base'); if (file_exists($template . 'chaw') && !file_exists($chaw . 'chaw')) { $console = array_pop(Configure::corePaths('cake')) . 'console' . DS; ob_start(); include $template . 'chaw'; $data = ob_get_clean(); $File = new File($chaw . 'chaw', true, 0775); @chmod($File->pwd(), 0775); return $File->write($data); } return true; }
/** * update method * * @return void * @access public */ public function update() { if (!file_exists(CAKE . 'config' . DS . 'sources.txt')) { $File = new File(CAKE . 'config' . DS . 'sources.txt', true); $File->write('file://' . dirname(__FILE__) . DS . 'packages.txt'); } $sources = file(CAKE . 'config' . DS . 'sources.txt'); $packages = array(); App::import('Core', 'HttpSocket'); $Socket = new HttpSocket(); foreach ($sources as &$source) { $source = trim($source); if (!$source || $source[0] === '#') { $source = false; continue; } if (strpos($source, 'file://') !== false) { $data = file($source); } else { $data = $Socket->get($source); if (!$data) { $source .= ' (no response)'; continue; } $data = explode("\n", $data); } $packages = array_merge($packages, MiInstall::_parsePackages($data)); } $File = new File(CAKE . 'config' . DS . 'packages.php', true); $File->write("<?php\n\$config = " . var_export($packages, true) . ';'); $return[] = Debugger::trimPath($File->pwd()) . ' updated'; $return['sources checked:'] = array_filter($sources); return $return; }
/** * Dump Schema object to sql file * Use the `write` param to enable and control SQL file output location. * Simply using -write will write the sql file to the same dir as the schema file. * If -write contains a full path name the file will be saved there. If -write only * contains no DS, that will be used as the file name, in the same dir as the schema file. * * @access public */ function dump() { $write = false; $Schema = $this->Schema->load(); if (!$Schema) { $this->err(__('Schema could not be loaded', true)); $this->_stop(); } if (isset($this->params['write'])) { if ($this->params['write'] == 1) { $write = Inflector::underscore($this->Schema->name); } else { $write = $this->params['write']; } } $db = ConnectionManager::getDataSource($this->Schema->connection); $contents = "#" . $Schema->name . " sql generated on: " . date('Y-m-d H:i:s') . " : " . time() . "\n\n"; $contents .= $db->dropSchema($Schema) . "\n\n" . $db->createSchema($Schema); if ($write) { if (strpos($write, '.sql') === false) { $write .= '.sql'; } if (strpos($write, DS) !== false) { $File = new File($write, true); } else { $File = new File($this->Schema->path . DS . $write, true); } if ($File->write($contents)) { $this->out(sprintf(__('SQL dump file created in %s', true), $File->pwd())); $this->_stop(); } else { $this->err(__('SQL dump could not be created', true)); $this->_stop(); } } $this->out($contents); return $contents; }
/** * Generates filesystem and model maps * * @access protected * @return void */ function _generateMaps() { $fsFiles = $this->_Folder->findRecursive(); $results = $this->_Model->find('all'); $fsMap = array(); $dbMap = array(); foreach ($fsFiles as $value) { $File = new File($value); $fsMap[] = array('file' => $File->pwd(), 'checksum' => $File->md5(true)); } foreach ($results as $result) { $dbMap[] = array('id' => $result[$this->_Model->name]['id'], 'file' => $this->_baseDirectory . $result[$this->_Model->name]['dirname'] . DS . $result[$this->_Model->name]['basename'], 'checksum' => $result[$this->_Model->name]['checksum']); } return array($fsMap, $dbMap); }
/** * Creates a file with contents from base64 encoded string. * * TestData::getFile('image-png.png'); * TestData::getFile(array('image-png.png' => TMP . 'other-name.png')); * TestData::getFile(array('image-png.png' => 'other-name.png')); * TestData::getFile('file.txt', 'I am the content'); * * @param mixed $key * @param string $string * @return string Absolute path to the created file */ public function getFile($key = null, $string = '') { if (is_array($key)) { $file = current($key); $key = key($key); if (!Folder::isAbsolute($file)) { $file = $this->settings['base'] . $file; } $alias = $file; } else { $alias = $key; $file = $this->settings['base'] . $key; } if ($string === '') { $string = $this->getString($key); } $File = new File($file); if ($File->exists()) { $File->delete(); } $File->write($string); $File->offset(0); $File->close(); $this->Files[$alias] =& $File; return $File->pwd(); }
/** * Dump Schema object to sql file * Use the `write` param to enable and control SQL file output location. * Simply using -write will write the sql file to the same dir as the schema file. * If -write contains a full path name the file will be saved there. If -write only * contains no DS, that will be used as the file name, in the same dir as the schema file. * * @return string */ public function dump() { $write = false; $Schema = $this->Schema->load(); if (!$Schema) { $this->err(__d('cake_console', 'Schema could not be loaded')); $this->_stop(); } if (!empty($this->params['write'])) { if ($this->params['write'] == 1) { $write = Inflector::underscore($this->Schema->name); } else { $write = $this->params['write']; } } $db = ConnectionManager::getDataSource($this->Schema->connection); $contents = "\n\n" . $db->dropSchema($Schema) . "\n\n" . $db->createSchema($Schema); if ($write) { if (strpos($write, '.sql') === false) { $write .= '.sql'; } if (strpos($write, DS) !== false) { $File = new File($write, true); } else { $File = new File($this->Schema->path . DS . $write, true); } if ($File->write($contents)) { $this->out(__d('cake_console', 'SQL dump file created in %s', $File->pwd())); $this->_stop(); } else { $this->err(__d('cake_console', 'SQL dump could not be created')); $this->_stop(); } } $this->out($contents); return $contents; }
/** * Retrieve (cached) metadata of a file * * @param Model $Model * @param string $file An absolute path to a file * @param integer $level level of amount of info to add, `0` disable, `1` for basic, `2` for detailed info * @return mixed Array with results or false if file is not readable */ function metadata(&$Model, $file, $level = 1) { if ($level < 1) { return array(); } extract($this->settings[$Model->alias]); $File = new File($file); if (!$File->readable()) { return false; } $checksum = $File->md5(true); if (isset($this->__cached[$Model->alias][$checksum])) { $data = $this->__cached[$Model->alias][$checksum]; } if ($level > 0 && !isset($data[1])) { $data[1] = array('size' => $File->size(), 'mime_type' => Mime_Type::guessType($File->pwd()), 'checksum' => $checksum); } if ($level > 1 && !isset($data[2])) { $data[2] = array(); try { $Info = Media_Info::factory(array('source' => $File->pwd())); foreach ($Info->all() as $key => $value) { $data[2][Inflector::underscore($key)] = $value; } } catch (Exception $E) { } } for ($i = $level, $result = array(); $i > 0; $i--) { $result = array_merge($result, $data[$i]); } $this->__cached[$Model->alias][$checksum] = $data; return $result; }
/** * "makes" a file * * @param string $file Absolute path to a file * @access protected * @return boolean */ function _make($file) { $File = new File($file); $name = Medium::name($file); $subdir = array_pop(explode(DS, dirname($this->source))); if ($name === 'Icon' || strpos($file, 'ico' . DS) !== false) { return true; } if ($this->version) { $configString = 'Media.filter.' . strtolower($name) . '.' . $this->version; $filter = array(Configure::read($configString)); } else { $configString = 'Media.filter.' . strtolower($name); $filter = Configure::read($configString); } foreach ($filter as $version => $instructions) { $directory = Folder::slashTerm(rtrim($this->destination . $version . DS . $subdir, '.')); $Folder = new Folder($directory, $this->_createDirectories); if (!$Folder->pwd()) { $this->err($directory . ' could not be created or is not writable.'); $this->err('Please check your permissions.'); return false; } $Medium = Medium::make($File->pwd(), $instructions); if (!$Medium) { $this->err('Failed to make version ' . $version . ' of medium.'); return false; } $Medium->store($Folder->pwd() . $File->name, $this->overwrite); } return true; }
/** * Creates a hook * * @param string $name * GIT * applypatch-msg, commit-message, post-commit, post-receive, post-update, * pre-applypatch, pre-commit, pre-rebase, update) * * SVN * post-commit, post-lock, post-revprop-change, post-unlock, pre-commit, pre-lock, * pre-revprop-change, pre-unlock, start-commit * * @param string $data location of the repository * @return boolean */ function _hook($name, $data = null, $options = array()) { extract($this->config); $Hook = new File($path . DS . 'hooks' . DS . $name, true, $chmod); chmod($Hook->pwd(), $chmod); if (!is_string($data) || $data === null) { extract((array) $data); if (file_exists(CONFIGS . 'templates' . DS . $type . DS . 'hooks' . DS . $name)) { ob_start(); include CONFIGS . 'templates' . DS . $type . DS . 'hooks' . DS . $name; $data = ob_get_clean(); } } if (empty($data)) { return false; } if ($Hook->append($data)) { return true; } return false; }
/** * Deals with collisions of destination files * * @param array $mapped An array where the key is the source and the value the destination file * @access protected * @return array */ function _handleCollision($mapped) { $Left = new File(array_search(current($mapped), $this->_map)); $Right = new File(key($mapped)); $this->out('Collision:'); $this->out(''); $this->out(sprintf('%s', $this->shortPath($Left->pwd()))); $this->out(sprintf('| %s', $this->shortPath($Right->pwd()))); $this->out(sprintf('| | ')); $this->out(sprintf('V V ')); $this->out(sprintf('%s', $this->shortPath(current($mapped)))); $this->out(''); if ($Left->md5() == $Right->md5()) { $this->out('Both files have the same checksum.'); } $answer = $this->in('Would you like to [r]ename or [s]kip?', 'r,s', 's'); if ($answer == 's') { return array(); } return array($Right->pwd() => $this->_rename($Right->pwd())); }
function profile($Media, $type, $data = null) { if (!$data) { return $this->_execute(':command: :source: :format::-', array('command' => 'convert', 'format' => $type, 'source' => $Media->files['temporary'])); } $File = new File(TMP . uniqid('media_')); if (!$File->write($data)) { $File->delete(); return false; } /* It assumed that the image already has a profile */ $result = $this->_execute(':command: :source: -profile :profile: :destination:', array('command' => 'convert', 'profile' => $File->pwd(), 'source' => $Media->files['temporary'], 'destination' => $Media->files['temporary'])); $File->delete(); if (!$result) { return $this->strip($Media, $type) && $this->profile($Media, $type, $data); } return true; }
/** * Test mime() * * @return void */ public function testMime() { $this->skipIf(!function_exists('finfo_open') && !function_exists('mime_content_type'), 'Not able to read mime type'); $path = CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif'; $file = new File($path); $expected = 'image/gif'; if (function_exists('mime_content_type') && false === mime_content_type($file->pwd())) { $expected = false; } $this->assertEquals($expected, $file->mime()); }
/** * Protects the transfer directory * * @return boolean */ public function protect() { if (MEDIA_TRANSFER_URL === false) { $this->out(__d('media_console', 'The content of the transfer directory is not served.')); return true; } $file = MEDIA_TRANSFER . '.htaccess'; if (is_file($file)) { $this->err(__d('media_console', '%s is already present.', $this->shortPath($file))); return true; } if (strpos(MEDIA_TRANSFER, WWW_ROOT) === false) { $this->err(__d('media_console', '%s is not in your webroot.', $this->shortPath($file))); return true; } $this->out(__d('media_console', 'Your transfer directory is missing a htaccess file to block requests.')); if ($this->in(__d('media_console', 'Do you want to create it now?'), 'y,n', 'n') == 'n') { return false; } $File = new File($file); $File->append("Order deny,allow\n"); $File->append("Deny from all\n"); $File->close(); $this->out(__d('media_console', '%s created.', $this->shortPath($File->pwd()))); $this->out(''); return true; }