/** * Compile the Less file in $origin to the CSS $destination file * * @param string $origin Input Less path * @param string $destination Output CSS path * @throws \ErrorException * @throws \Exception */ public static function compile($origin, $destination) { $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $command = static::$_node_bin . ' ' . static::$_node_script . ' ' . escapeshellarg($origin) . ' ' . escapeshellarg($destination); $process = proc_open($command, $descriptorspec, $pipes, getcwd(), null, array('bypass_shell' => true)); if (is_resource($process)) { // $pipes now looks like this: // 0 => writeable handle connected to child stdin // 1 => readable handle connected to child stdout // 2 => readable handle connected to child stderr fclose($pipes[0]); $raw_css = stream_get_contents($pipes[1]); fclose($pipes[1]); $errors = stream_get_contents($pipes[2]); fclose($pipes[2]); proc_close($process); if ($errors) { $json = json_decode(trim($errors)); if (isset($json->message, $json->filename, $json->line)) { throw new \ErrorException($json->message, 0, E_ERROR, $json->filename, $json->line); } else { throw new \Exception('Error while trying to compile with nodejs: ' . $errors); } } $destination = pathinfo($destination); \File::update($destination['dirname'], $destination['basename'], $raw_css); } else { throw new \Exception('Could not open nodejs instance!'); } }
public static function config($args, $build = true) { $args = self::_clear_args($args); $file = strtolower(array_shift($args)); $config = array(); // load the config if ($paths = \Finder::search('config', $file, '.php', true)) { // Reverse the file list so that we load the core configs first and // the app can override anything. $paths = array_reverse($paths); foreach ($paths as $path) { $config = \Fuel::load($path) + $config; } } unset($path); // We always pass in fields to a config, so lets sort them out here. foreach ($args as $conf) { // Each paramater for a config is seperated by the : character $parts = explode(":", $conf); // We must have the 'name:value' if nothing else! if (count($parts) >= 2) { $config[$parts[0]] = $parts[1]; } } $overwrite = \Cli::option('o') or \Cli::option('overwrite'); $content = <<<CONF <?php /** * Fuel is a fast, lightweight, community driven PHP5 framework. * * @package\t\tFuel * @version\t\t1.0 * @author\t\tFuel Development Team * @license\t\tMIT License * @copyright\t2011 Fuel Development Team * @link\t\thttp://fuelphp.com */ CONF; $content .= 'return ' . str_replace(' ', "\t", var_export($config, true)) . ';'; $content .= <<<CONF /* End of file {$file}.php */ CONF; $path = APPPATH . 'config' . DS . $file . '.php'; if (!$overwrite and is_file($path)) { throw new Exception("APPPATH/config/{$file}.php already exist, please use -overwrite option to force update"); } $path = pathinfo($path); try { \File::update($path['dirname'], $path['basename'], $content); \Cli::write("Created config: APPPATH/config/{$file}.php", 'green'); } catch (\InvalidPathException $e) { throw new Exception("Invalid basepath, cannot update at " . APPPATH . "config" . DS . "{$file}.php"); } catch (\FileAccessException $e) { throw new Exception(APPPATH . "config" . DS . $file . ".php could not be written."); } }
public static function save($file, $config) { if (!is_array($config)) { if (!isset(static::$items[$config])) { return false; } $config = static::$items[$config]; } $content = <<<CONF <?php /** * Fuel * * Fuel is a fast, lightweight, community driven PHP5 framework. * * @package\t\tFuel * @version\t\t1.0 * @author\t\tFuel Development Team * @license\t\tMIT License * @copyright\t2011 Fuel Development Team * @link\t\thttp://fuelphp.com */ CONF; $content .= 'return ' . str_replace(' ', "\t", var_export($config, true)) . ';'; $content .= <<<CONF /* End of file {$file}.php */ CONF; $path = \Fuel::find_file('config', $file, '.php') or $path[0] = APPPATH . 'config' . DS . $file . '.php'; $path = pathinfo($path[0]); return File::update($path['dirname'], $path['basename'], $content); }
/** * Compile the Less file in $origin to the CSS $destination file * * @param string $origin Input Less path * @param string $destination Output CSS path */ public static function compile($origin, $destination) { $less = new \lessc(); $less->indentChar = \Config::get('asset.indent_with'); $less->setImportDir(array(dirname($origin), dirname($destination))); $raw_css = $less->compile(file_get_contents($origin)); $destination = pathinfo($destination); \File::update($destination['dirname'], $destination['basename'], $raw_css); }
function testPersonHasBeenUpdated() { $this->unlinkOldTestFile(); $person[] = array("firstname" => "Francesco R.", "surname" => "Di Caprio"); $file = new File($this->testfile); $file->insert($person); $oldperson = new Person("Francesco R.", "Di Caprio"); $newperson = new Person("Francesco", "DC"); $file->update($oldperson, $newperson); $this->assertFalse($file->search($oldperson)); $this->assertInternalType("int", $file->search($newperson)); }
<?php include "includes.php"; $id = $_POST['id']; $filePath = $_POST['filePath']; $name = isset($_POST['name']) ? $_POST['name'] : null; $description = isset($_POST['description']) ? $_POST['description'] : null; $preview = $_POST['preview']; $thumb = $_POST['thumb']; $downloads = $_POST['downloads']; $path; if (!$id) { $file = $_FILES['upload']; $fileUploader = new FileUploader($file, $name, $description); $id = $fileUploader->uploadFile(); } else { $file = new File($filePath, $name, $description, $downloads, $preview, $thumb, $id); $file->update(); header("Location: /admin/files/" . $id); exit; }
/** * Formats the output and saved it to disc. * * @param string $identifier filename * @param $contents $contents config array to save * @return bool \File::update result */ public function save($identifier, $contents) { // get the formatted output $output = $this->export_format($contents); if (!$output) { return false; } if (!($path = \Finder::search('config', $identifier))) { if ($pos = strripos($identifier, '::')) { // get the namespace path if ($path = \Autoloader::namespace_path('\\' . ucfirst(substr($identifier, 0, $pos)))) { // strip the namespace from the filename $identifier = substr($identifier, $pos + 2); // strip the classes directory as we need the module root $path = substr($path, 0, -8) . 'config' . DS . $identifier; } else { // invalid namespace requested return false; } } } // absolute path requested? if ($identifier[0] === '/' or isset($identifier[1]) and $identifier[1] === ':') { $path = $identifier; } // make sure we have a fallback $path or $path = APPPATH . 'config' . DS . $identifier; $path = pathinfo($path); if (!is_dir($path['dirname'])) { mkdir($path['dirname'], 0777, true); } return \File::update($path['dirname'], $path['basename'], $output); }
/** * Install configuration file * * @static * @access protected * @return void */ protected static function install_config($file = 'autho') { $path = APPPATH . 'config' . DS . $file . '.php'; $content = file_get_contents(PKGPATH . 'hybrid/config/' . $file . '.php'); switch (true) { case true === is_file($path) and 'y' === \Cli::prompt("Overwrite APPPATH/config/{$file}.php?", array('y', 'n')): case false === is_file($path): $path = pathinfo($path); try { \File::update($path['dirname'], $path['basename'], $content); \Cli::write("Created config: APPPATH/config/{$file}.php", 'green'); } catch (\File_Exception $e) { throw new Exception("APPPATH/config/{$file}.php could not be written."); } break; default: break; } }
public function update($basepath, $name, $new_content) { return \File::update($basepath, $name, $new_content, $this); }
public function generate_model($table_name, $db = null) { $table_class = \Inflector::classify($table_name); // Generate the full path for the model $file_path = APPPATH . 'classes' . DS . 'model' . DS; $file_path .= str_replace('_', '/', strtolower($table_class)) . '.php'; if (file_exists($file_path)) { \Cli::error('Model already found for database table ' . $table_name); $answer = \Cli::prompt('Overwrite model?', array('y', 'n')); if ($answer == 'n') { \Cli::write('Existing model not overwritten.'); return false; } } $columns = \DB::list_columns($table_name, null, $db); \Cli::write('Found ' . count($columns) . " columns for the {$table_name} database table.", 'green'); $model_properties = array(); foreach ($columns as $column) { // Process some of the column info to allow easier detection list($column_type, $column_unsigned) = explode(' ', $column['data_type'] . ' '); // Concatenated space stops an error happening when data_type has no spaces // A hack to detect Bool data types if ($column_type == 'tinyint' and $column['display'] == 1) { $column_type = 'bool'; } // Basic Properties $column_properties = array('data_type' => in_array($column_type, static::$data_typing_types) ? $column_type : 'string', 'label' => \Inflector::humanize($column['name']), 'null' => $column['null']); $column['default'] and $column_properties['default'] = $column['default']; // Validation // TODO: Add thresholds rather than having rediculously high max values $column_validation = array(); $column['null'] or $column_validation[] = 'required'; if ($column_type == 'bool') { $column_validation = array('required'); } elseif (key_exists($column_type, static::$string_max_lengths)) { $column_validation['max_length'] = array((int) min($column['character_maximum_length'], static::$string_max_lengths[$column_type])); } elseif ($column['type'] == 'int') { $display_max = (int) str_repeat(9, $column['display']); $column_validation['numeric_min'] = array((int) $column['min']); $column_validation['numeric_max'] = array((int) min($column['max'], $display_max)); } elseif ($column['type'] == 'float') { $max = (double) (str_repeat(9, $column['numeric_precision'] - $column['numeric_scale']) . '.' . str_repeat(9, $column['numeric_scale'])); $min = substr($column['data_type'], -8) == 'unsigned' ? 0 : $max * -1; $column_validation['numeric_min'] = array($min); $column_validation['numeric_max'] = array($max); } // Form $column_form = array('type' => 'text'); if (in_array($column['name'], array('id', 'created_at', 'updated_at'))) { $column_form['type'] = false; } else { $column['default'] and $column_form['value'] = $column['default']; switch ($column_type) { case 'char': case 'varchar': case 'tinytext': case 'tinyblob': isset($column_validation['max_length']) and $column_form['maxlength'] = $column_validation['max_length'][0]; break; case 'text': case 'blob': case 'mediumtext': case 'mediumblob': case 'longtext': case 'longblob': $column_form['type'] = 'textarea'; break; case 'enum': case 'set': $column_form['type'] = 'select'; $column_form['options'] = array(); break; case 'bool': $column_form['type'] = 'radio'; $column_form['options'] = array(1 => 'Yes', 0 => 'No'); break; case 'decimal': case 'double': case 'float': $column_form['step'] = floatval('0.' . str_repeat(9, $column['numeric_scale'])); // break is intentionally missing // break is intentionally missing case 'tinyint': case 'smallint': case 'int': case 'mediumint': case 'bigint': $column_form['type'] = 'number'; isset($column_validation['numeric_min']) and $column_form['min'] = $column_validation['numeric_min'][0]; isset($column_validation['numeric_max']) and $column_form['max'] = $column_validation['numeric_max'][0]; break; /* @TODO case 'date': case 'datetime': case 'time': case 'timestamp': break;*/ } } $column_properties['validation'] = $column_validation; $column_properties['form'] = $column_form; $model_properties[$column['name']] = $column_properties; } $model_properties_str = str_replace(array("\n", ' ', 'array ('), array("\n\t", "\t", 'array('), \Format::forge($model_properties)->to_php()); $model_properties_str = preg_replace('/=>\\s+array/m', '=> array', $model_properties_str); $model_str = <<<MODEL <?php class Model_{$table_class} extends \\Orm\\Model { protected static \$_table_name = '{$table_name}'; protected static \$_properties = {$model_properties_str}; protected static \$_observers = array( 'Orm\\Observer_Validation' => array( 'events' => array('before_save'), ), 'Orm\\Observer_Typing' => array( 'events' => array('before_save', 'after_save', 'after_load'), ), MODEL; if (isset($model_properties['created_at'])) { $model_str .= <<<MODEL 'Orm\\Observer_CreatedAt' => array( 'events' => array('before_insert'), 'mysql_timestamp' => false, 'property' => 'created_at', ), MODEL; } if (isset($model_properties['updated_at'])) { $model_str .= <<<MODEL 'Orm\\Observer_UpdatedAt' => array( 'events' => array('before_save'), 'mysql_timestamp' => false, 'property' => 'updated_at', ), MODEL; } $model_str .= <<<MODEL ); } MODEL; // Make sure the directory exists is_dir(dirname($file_path)) or mkdir(dirname($file_path), 0775, true); // Show people just how clever FuelPHP can be \File::update(dirname($file_path), basename($file_path), $model_str); return true; }
function setFilehashOnLocalFiles() { printfnq('Ensuring all local files have the filehash field set...'); $file = new File(); $file->whereAdd('filename IS NOT NULL'); // local files $file->whereAdd('filehash IS NULL', 'AND'); // without filehash value if ($file->find()) { while ($file->fetch()) { try { $orig = clone $file; $file->filehash = hash_file(File::FILEHASH_ALG, $file->getPath()); $file->update($orig); } catch (FileNotFoundException $e) { echo "\n WARNING: file ID {$file->id} does not exist on path '{$e->path}'. If there is no file system error, run: php scripts/clean_file_table.php"; } } } printfnq("DONE.\n"); }
public static function beforeSchemaUpdate() { $table = strtolower(get_called_class()); $schema = Schema::get(); $schemadef = $schema->getTableDef($table); // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) { // We already have the urlhash field, so no need to migrate it. return; } echo "\nFound old {$table} table, upgrading it to contain 'urlhash' field..."; $file = new File(); $file->query(sprintf('SELECT id, LEFT(url, 191) AS shortenedurl, COUNT(*) AS c FROM %1$s WHERE LENGTH(url)>191 GROUP BY shortenedurl HAVING c > 1', $schema->quoteIdentifier($table))); print "\nFound {$file->N} URLs with too long entries in file table\n"; while ($file->fetch()) { // We've got a URL that is too long for our future file table // so we'll cut it. We could save the original URL, but there is // no guarantee it is complete anyway since the previous max was 255 chars. $dupfile = new File(); // First we find file entries that would be duplicates of this when shortened // ... and we'll just throw the dupes out the window for now! It's already so borken. $dupfile->query(sprintf('SELECT * FROM file WHERE LEFT(url, 191) = "%1$s"', $file->shortenedurl)); // Leave one of the URLs in the database by using ->find(true) (fetches first entry) if ($dupfile->find(true)) { print "\nShortening url entry for {$table} id: {$file->id} ["; $orig = clone $dupfile; $dupfile->url = $file->shortenedurl; // make sure it's only 191 chars from now on $dupfile->update($orig); print "\nDeleting duplicate entries of too long URL on {$table} id: {$file->id} ["; // only start deleting with this fetch. while ($dupfile->fetch()) { print "."; $dupfile->delete(); } print "]\n"; } else { print "\nWarning! URL suddenly disappeared from database: {$file->url}\n"; } } echo "...and now all the non-duplicates which are longer than 191 characters...\n"; $file->query('UPDATE file SET url=LEFT(url, 191) WHERE LENGTH(url)>191'); echo "\n...now running hacky pre-schemaupdate change for {$table}:"; // We have to create a urlhash that is _not_ the primary key, // transfer data and THEN run checkSchema $schemadef['fields']['urlhash'] = array('type' => 'varchar', 'length' => 64, 'not null' => false, 'description' => 'sha256 of destination URL (url field)'); $schemadef['fields']['url'] = array('type' => 'text', 'description' => 'destination URL after following possible redirections'); unset($schemadef['unique keys']); $schema->ensureTable($table, $schemadef); echo "DONE.\n"; $classname = ucfirst($table); $tablefix = new $classname(); // urlhash is hash('sha256', $url) in the File table echo "Updating urlhash fields in {$table} table..."; // Maybe very MySQL specific :( $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;', $schema->quoteIdentifier($table), 'urlhash', 'SHA2(url, 256)')); echo "DONE.\n"; echo "Resuming core schema upgrade..."; }
/** * Save a config array to disc. * * @param string $file desired file name * @param string|array $config master config array key or config array * @return bool false when config is empty or invalid else \File::update result */ public static function save($file, $config) { if (!is_array($config)) { if (!isset(static::$items[$config])) { return false; } $config = static::$items[$config]; } $content = <<<CONF <?php CONF; $content .= 'return ' . str_replace(array(' ', 'array (', '\'' . APPPATH, '\'' . DOCROOT, '\'' . COREPATH, '\'' . PKGPATH), array("\t", 'array(', 'APPPATH.\'', 'DOCROOT.\'', 'COREPATH.\'', 'PKGPATH.\''), var_export($config, true)) . ";\n"; if (!($path = \Finder::search('config', $file, '.php'))) { if ($pos = strripos($file, '::')) { // get the namespace path if ($path = \Autoloader::namespace_path('\\' . ucfirst(substr($file, 0, $pos)))) { // strip the namespace from the filename $file = substr($file, $pos + 2); // strip the classes directory as we need the module root // and construct the filename $path = substr($path, 0, -8) . 'config' . DS . $file . '.php'; } else { // invalid namespace requested return false; } } } // absolute path requested? if ($file[0] === '/' or isset($file[1]) and $file[1] === ':') { $path = $file; } // make sure we have a fallback $path or $path = APPPATH . 'config' . DS . $file . '.php'; $path = pathinfo($path); if (!is_dir($path['dirname'])) { mkdir($path['dirname'], 0777, true); } return \File::update($path['dirname'], $path['basename'], $content); }
public static function save($file, $config) { if (!is_array($config)) { if (!isset(static::$items[$config])) { return false; } $config = static::$items[$config]; } $content = <<<CONF <?php /** * Fuel is a fast, lightweight, community driven PHP5 framework. * * @package\t\tFuel * @version\t\t1.0 * @author\t\tFuel Development Team * @license\t\tMIT License * @copyright\t2011 Fuel Development Team * @link\t\thttp://fuelphp.com */ CONF; $content .= 'return ' . str_replace(' ', "\t", var_export($config, true)) . ';'; if (!($path = \Fuel::find_file('config', $file, '.php'))) { if ($pos = strripos($file, '::')) { // get the namespace path if ($path = \Autoloader::namespace_path('\\' . ucfirst(substr($file, 0, $pos)))) { // strip the namespace from the filename $file = substr($file, $pos + 2); // strip the classes directory as we need the module root // and construct the filename $path = substr($path, 0, -8) . 'config' . DS . $file . '.php'; } else { // invalid namespace requested return false; } } } $content .= <<<CONF CONF; // make sure we have a fallback $path or $path = APPPATH . 'config' . DS . $file . '.php'; $path = pathinfo($path); return File::update($path['dirname'], $path['basename'], $content); }
/** * attachmentで出力する * @param File $file 出力するファイル */ public static function attach(File $file) { Log::disable_display(); if (is_file($file->fullname()) || $file->value() !== null) { if ($file->update() > 0) { if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $file->update() <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { self::status_header(304); exit; } header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $file->update()) . ' GMT'); } header(sprintf('Content-Type: ' . $file->mime() . '; name=%s', $file->name())); header(sprintf('Content-Disposition: attachment; filename=%s', $file->name())); if ($file->size() > 0) { header(sprintf('Content-length: %u', $file->size())); } $file->output(); } self::status_header(404); exit; }
public static function config($args) { $file = strtolower(array_shift($args)); if (empty($file)) { throw new Exception('No config filename has been provided.'); } $config = array(); // load the config if ($paths = \Finder::search('config', $file, '.php', true)) { // Reverse the file list so that we load the core configs first and // the app can override anything. $paths = array_reverse($paths); foreach ($paths as $path) { $config = \Fuel::load($path) + $config; } } unset($path); // We always pass in fields to a config, so lets sort them out here. foreach ($args as $conf) { // Each paramater for a config is seperated by the : character $parts = explode(":", $conf); // We must have the 'name:value' if nothing else! if (count($parts) >= 2) { $config[$parts[0]] = $parts[1]; } } $overwrite = (\Cli::option('o') or \Cli::option('overwrite')); // strip whitespace and add tab $export = str_replace(array(' ', 'array ('), array("\t", 'array('), var_export($config, true)); $content = '<?php' . PHP_EOL . PHP_EOL . 'return ' . $export . ';'; $content .= <<<CONF /* End of file {$file}.php */ CONF; $module = \Cli::option('module', \Cli::option('m')); // add support for `php oil g config module::file arg1:value1` if (strpos($file, '::') !== false) { list($module, $file) = explode('::', $file); } // get the namespace path (if available) if (!empty($module) and $path = \Autoloader::namespace_path('\\' . ucfirst($module))) { // strip the classes directory as we need the module root // and construct the filename $path = substr($path, 0, -8) . 'config' . DS . $file . '.php'; $path_name = "\\" . ucfirst($module) . '::'; } elseif (!empty($module)) { throw new Exception("{$module} need to be loaded first, please use config always_load.modules."); } else { $path = APPPATH . 'config' . DS . $file . '.php'; $path_name = 'APPPATH/'; } if (!$overwrite and is_file($path)) { throw new Exception("{$path_name}/config/{$file}.php already exist, please use --overwrite option to force update"); } $path = pathinfo($path); try { \File::update($path['dirname'], $path['basename'], $content); \Cli::write("Created config: {$path_name}config/{$file}.php", 'green'); } catch (\InvalidPathException $e) { throw new Exception("Invalid basepath, cannot update at " . $path_name . "config" . DS . "{$file}.php"); } catch (\FileAccessException $e) { throw new Exception($path_name . "config" . DS . $file . ".php could not be written."); } }
/** * Formats the output and saved it to disc. * * @param $contents $contents config array to save * @return bool \File::update result */ public function save($contents) { // get the formatted output $output = $this->export_format($contents); if (!$output) { return false; } if (!($path = \Finder::search('config', $this->file, $this->ext))) { if ($pos = strripos($this->file, '::')) { // get the namespace path if ($path = \Autoloader::namespace_path('\\' . ucfirst(substr($this->file, 0, $pos)))) { // strip the namespace from the filename $this->file = substr($this->file, $pos + 2); // strip the classes directory as we need the module root $path = substr($path, 0, -8) . 'config' . DS . $this->file . $this->ext; } else { // invalid namespace requested return false; } } } // absolute path requested? if ($this->file[0] === '/' or isset($this->file[1]) and $this->file[1] === ':') { $path = $this->file; } // make sure we have a fallback $path or $path = APPPATH . 'config' . DS . $this->file . $this->ext; $path = pathinfo($path); if (!is_dir($path['dirname'])) { mkdir($path['dirname'], 0777, true); } $return = \File::update($path['dirname'], $path['basename'], $output); if ($return) { try { \Config::load('file', true); chmod($path['dirname'] . DS . $path['basename'], \Config::get('file.chmod.files', 0666)); } catch (\PhpErrorException $e) { // if we get something else then a chmod error, bail out if (substr($e->getMessage(), 0, 8) !== 'chmod():') { throw new $e(); } } } return $return; }
$people = $_POST["people"]; $file = new File("data.txt"); $json["result"] = $file->insert($people) !== false ? true : false; if (!$json["result"]) { $json["error"] = "Controller was unable to insert data."; } break; case "update": $oldFirstName = filter_input(INPUT_POST, "oldFirstName", FILTER_SANITIZE_STRING); $oldSurName = filter_input(INPUT_POST, "oldSurName", FILTER_SANITIZE_STRING); $newFirstName = filter_input(INPUT_POST, "newFirstName", FILTER_SANITIZE_STRING); $newSurName = filter_input(INPUT_POST, "newSurName", FILTER_SANITIZE_STRING); $personToUpdate = new Person($oldFirstName, $oldSurName); $newPerson = new Person($newFirstName, $newSurName); $file = new File("data.txt"); $json["result"] = $file->update($personToUpdate, $newPerson) !== false ? true : false; if (!$json["result"]) { $json["error"] = "Controller was unable to update {$oldFirstName} {$newFirstName}. Maybe it has been deleted."; } break; case "delete": $firstName = filter_input(INPUT_POST, "firstName", FILTER_SANITIZE_STRING); $surName = filter_input(INPUT_POST, "surName", FILTER_SANITIZE_STRING); $person = new Person($firstName, $surName); $file = new File("data.txt"); $json["result"] = $file->delete($person) !== false ? true : false; if (!$json["result"]) { $json["error"] = "Controller was unable to delete {$firstName} {$surName}, it doesn't exists in archive"; } break; default: