/** * Save an uploaded file to a new location. * * @param mixed name of $_FILE input or array of upload data * @param string new filename * @param string new directory * @param integer chmod mask * @return string full path to new file */ public static function save($file, $filename = NULL, $directory = NULL, $chmod = 0755) { // Load file data from FILES if not passed as array $file = is_array($file) ? $file : $_FILES[$file]; if ($filename === NULL) { // Use the default filename, with a timestamp pre-pended $filename = time() . $file['name']; } // Remove spaces from the filename $filename = preg_replace('/\\s+/', '_', $filename); if ($directory === NULL) { // Use the pre-configured upload directory $directory = WWW_ROOT . 'files/'; } // Make sure the directory ends with a slash $directory = rtrim($directory, '/') . '/'; if (!is_dir($directory)) { // Create the upload directory mkdir($directory, 0777, TRUE); } //if ( ! is_writable($directory)) //throw new exception; if (is_uploaded_file($file['tmp_name']) and move_uploaded_file($file['tmp_name'], $filename = $directory . $filename)) { if ($chmod !== FALSE) { // Set permissions on filename chmod($filename, $chmod); } //$all_file_name = array(FILE_INFO => $filename); // Return new file path return $filename; } return FALSE; }
function check_for_directory() { if (!file_exists($this->directory_name)) { mkdir($this->directory_name, 0777); } @chmod($this->directory_name, 0777); }
/** * Initializes this logger. * * Available options: * * - file: The file path or a php wrapper to log messages * You can use any support php wrapper. To write logs to the Apache error log, use php://stderr * - format: The log line format (default to %time% %type% [%priority%] %message%%EOL%) * - time_format: The log time strftime format (default to %b %d %H:%M:%S) * - dir_mode: The mode to use when creating a directory (default to 0777) * - file_mode: The mode to use when creating a file (default to 0666) * * @param sfEventDispatcher $dispatcher A sfEventDispatcher instance * @param array $options An array of options. * * @return Boolean true, if initialization completes successfully, otherwise false. */ public function initialize(sfEventDispatcher $dispatcher, $options = array()) { if (!isset($options['file'])) { throw new sfConfigurationException('You must provide a "file" parameter for this logger.'); } if (isset($options['format'])) { $this->format = $options['format']; } if (isset($options['time_format'])) { $this->timeFormat = $options['time_format']; } if (isset($options['type'])) { $this->type = $options['type']; } $dir = dirname($options['file']); if (!is_dir($dir)) { mkdir($dir, isset($options['dir_mode']) ? $options['dir_mode'] : 0777, true); } $fileExists = file_exists($options['file']); if (!is_writable($dir) || $fileExists && !is_writable($options['file'])) { throw new sfFileException(sprintf('Unable to open the log file "%s" for writing.', $options['file'])); } $this->fp = fopen($options['file'], 'a'); if (!$fileExists) { chmod($options['file'], isset($options['file_mode']) ? $options['file_mode'] : 0666); } return parent::initialize($dispatcher, $options); }
function save($overwrite = true) { global $messageStack; if (!$overwrite and file_exists($this->destination . $this->filename)) { $messageStack->add_session(TEXT_IMAGE_OVERWRITE_WARNING . $this->filename, 'caution'); return true; } else { if (substr($this->destination, -1) != '/') { $this->destination .= '/'; } if (move_uploaded_file($this->file['tmp_name'], $this->destination . $this->filename)) { chmod($this->destination . $this->filename, $this->permissions); if ($this->message_location == 'direct') { $messageStack->add(sprintf(SUCCESS_FILE_SAVED_SUCCESSFULLY, $this->filename), 'success'); } else { $messageStack->add_session(sprintf(SUCCESS_FILE_SAVED_SUCCESSFULLY, $this->filename), 'success'); } return true; } else { if ($this->message_location == 'direct') { $messageStack->add(ERROR_FILE_NOT_SAVED, 'error'); } else { $messageStack->add_session(ERROR_FILE_NOT_SAVED, 'error'); } return false; } } }
/** * Write Log File * * Generally this function will be called using the global log_message() function * * @param string the error level * @param string the error message * @param bool whether the error is a native PHP error * @return bool */ public function write_log($level = 'error', $msg, $php_error = FALSE) { if ($this->_enabled === FALSE) { return FALSE; } $level = strtoupper($level); if (!isset($this->_levels[$level]) or $this->_levels[$level] > $this->_threshold) { return FALSE; } $filepath = $this->_log_path . 'log-' . date('Y-m-d') . '.php'; $message = ''; if (!file_exists($filepath)) { $message .= "<" . "?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?" . ">\n\n"; } if (!($fp = @fopen($filepath, FOPEN_WRITE_CREATE))) { return FALSE; } $message .= $level . ' ' . ($level == 'INFO' ? ' -' : '-') . ' ' . date($this->_date_fmt) . ' --> ' . $msg . "\n"; flock($fp, LOCK_EX); fwrite($fp, $message); flock($fp, LOCK_UN); fclose($fp); @chmod($filepath, FILE_WRITE_MODE); return TRUE; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $remoteFilename = 'http://get.insight.sensiolabs.com/insight.phar'; $localFilename = $_SERVER['argv'][0]; $tempFilename = basename($localFilename, '.phar') . '-temp.phar'; try { copy($remoteFilename, $tempFilename); if (md5_file($localFilename) == md5_file($tempFilename)) { $output->writeln('<info>insight is already up to date.</info>'); unlink($tempFilename); return; } chmod($tempFilename, 0777 & ~umask()); // test the phar validity $phar = new \Phar($tempFilename); // free the variable to unlock the file unset($phar); rename($tempFilename, $localFilename); $output->writeln('<info>insight updated.</info>'); } catch (\Exception $e) { if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) { throw $e; } unlink($tempFilename); $output->writeln('<error>The download is corrupt (' . $e->getMessage() . ').</error>'); $output->writeln('<error>Please re-run the self-update command to try again.</error>'); } }
function chmod_r($path, $filemode) { if (!is_dir($path)) { return chmod($path, $filemode); } $dh = opendir($path); while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..') { $fullpath = $path . '/' . $file; if (is_link($fullpath)) { return FALSE; } elseif (!is_dir($fullpath)) { if (!chmod($fullpath, $filemode)) { return FALSE; } elseif (!chmod_r($fullpath, $filemode)) { return FALSE; } } } } closedir($dh); if (chmod($path, $filemode)) { return TRUE; } else { return FALSE; } }
/** * Create Icinga Web 2's configuration directory * * USAGE: * * icingacli setup config directory [options] * * OPTIONS: * * --config=<directory> Path to Icinga Web 2's configuration files [/etc/icingaweb2] * * --mode=<mode> The access mode to use [2770] * * --group=<group> Owner group for the configuration directory [icingaweb2] * * EXAMPLES: * * icingacli setup config directory * * icingacli setup config directory --mode=2775 --config=/opt/icingaweb2/etc */ public function directoryAction() { $configDir = trim($this->params->get('config', $this->app->getConfigDir())); if (strlen($configDir) === 0) { $this->fail($this->translate('The argument --config expects a path to Icinga Web 2\'s configuration files')); } $group = trim($this->params->get('group', 'icingaweb2')); if (strlen($group) === 0) { $this->fail($this->translate('The argument --group expects a owner group for the configuration directory')); } $mode = trim($this->params->get('mode', '2770')); if (strlen($mode) === 0) { $this->fail($this->translate('The argument --mode expects an access mode for the configuration directory')); } if (!file_exists($configDir) && !@mkdir($configDir)) { $e = error_get_last(); $this->fail(sprintf($this->translate('Can\'t create configuration directory %s: %s'), $configDir, $e['message'])); } if (!@chmod($configDir, octdec($mode))) { $e = error_get_last(); $this->fail(sprintf($this->translate('Can\'t change the mode of the configuration directory to %s: %s'), $mode, $e['message'])); } if (!@chgrp($configDir, $group)) { $e = error_get_last(); $this->fail(sprintf($this->translate('Can\'t change the group of %s to %s: %s'), $configDir, $group, $e['message'])); } printf($this->translate('Successfully created configuration directory %s') . PHP_EOL, $configDir); }
public function write(Collection $items) { $path = $this->_getPath(); $this->items = $items; if (defined('JSON_PRETTY_PRINT')) { //PHP >= 5.4 $json = json_encode($items, JSON_PRETTY_PRINT); //JSON_PRETTY_PRINT: for debugging issues } else { $json = json_encode($items); } if ($json === false) { throw new \RuntimeException('Cannot encode data to JSON'); } $parentPath = dirname($path); if (!is_dir($parentPath)) { mkdir($parentPath, 0777, true); chmod($parentPath, 0777); } $alreadyExists = file_exists($path); $result = file_put_contents($path, $json); if ($result === false) { throw new \RuntimeException('Cannot open data file "' . $this->index . '" ("' . $path . '" : error while writing)'); } if (!$alreadyExists) { chmod($path, 0777); } }
protected function rmDir($dir) { if (is_dir($dir)) { chmod($dir, 0777); rmdir($dir); } }
/** * Renders the Thumbnail for given source * * * @param string $source Absolute path to source imagefile * @param string $target Absolute thumbnail filepath * @param array $params Phpthumb params * @throws NotFoundException * @throws CakeException */ public static function createThumbnail($source, $target = null, $params = array()) { if (!file_exists($source)) { throw new NotFoundException(__d('media', "File %s not found", $source)); } //@todo use dependency injection $phpThumb = new phpthumb(); $params = array_merge(array('watermark' => null, 'useImageMagick' => false, 'imageMagickPath' => '/usr/bin/convert', 'config_temp_directory' => MEDIA_CACHE_DIR, 'config_cache_directory' => MEDIA_CACHE_DIR, 'config_output_format' => 'jpg', 'config_error_die_on_error' => false, 'config_document_root' => ROOT, 'config_allow_src_above_docroot' => true, 'config_cache_disable_warning' => true, 'config_disable_debug' => true, 'config_cache_prefix' => 'phpthumb_', 'sia' => "thumbnail"), $params); // Configuring thumbnail settings self::_applyParams($phpThumb, $params); // Set source path $phpThumb->setSourceFilename($source); // Creating thumbnail if ($phpThumb->GenerateThumbnail()) { //@todo Duplicate code. See getThumbnail() $target = self::target($source, $target, $params); if (!$phpThumb->RenderToFile($target)) { throw new CakeException('Could not render image to: ' . $target); } @chmod($target, 0644); //TODO check if this is necessary } //debug($phpThumb->phpThumbDebug()); return $target; }
public static function minifyTemplateFile($mTimeFile, $fileToMinify, $targetMinifiedFile, $ext) { file_put_contents($targetMinifiedFile, $ext == 'js' ? static::minifyJs($fileToMinify) : static::minifyCss($fileToMinify)); chmod($targetMinifiedFile, 0775); file_put_contents($mTimeFile, filemtime($fileToMinify)); chmod($mTimeFile, 0775); }
function chmod_recursive($path, $mode) { umask(00); if (!is_dir($path)) { return chmod($path, $mode); } $dh = opendir($path); while ($file = readdir($dh)) { if ($file != '.' && $file != '..') { $fullpath = $path . '/' . $file; if (!is_dir($fullpath)) { if (!chmod($fullpath, $mode)) { return false; } else { if (!chmod_recursive($fullpath, $mode)) { return false; } } } } } closedir($dh); if (chmod($path, $mode)) { return true; } return false; }
/** * * Function sort out paramaters * This function creates folders needed when duplicating a template * @param number $folder_name_id - the id of this template * @param number $tutorial_id_from_post - the parent template name for the new tutorial * @version 1.0 * @author Patrick Lockley */ function create_new_template($folder_name_id, $parent_template_name) { global $dir_path, $new_path, $temp_dir_path, $temp_new_path, $xerte_toolkits_site; $row_framework = db_query_one("SELECT template_framework from {$xerte_toolkits_site->database_table_prefix}originaltemplatesdetails WHERE template_name = ?", array($parent_template_name)); // I think this is wrong, currently looking like : /home/david/src/xerteonlinetoolkits/modules//templates/0 should presumably be home/david/src/xerteonlinetoolkits/modules/xerte/templates/Nottingham $dir_path = $xerte_toolkits_site->basic_template_path . $row_framework['template_framework'] . "/templates/" . $parent_template_name; /** * Get the id of the folder we are looking to copy into */ _debug("Creating new template : {$folder_name_id}, {$parent_template_name}"); $new_path = $xerte_toolkits_site->users_file_area_full . $folder_name_id . "-" . $_SESSION['toolkits_logon_username'] . "-" . $parent_template_name; $path = $xerte_toolkits_site->users_file_area_full . $folder_name_id . "-" . $_SESSION['toolkits_logon_username'] . "-" . $parent_template_name; if (is_dir($path)) { _debug("Trying to create new template at location - {$path} - it's already in use. Aborting"); die("Template directory already exists; will not overwrite/re-create."); } if (mkdir($path)) { _debug("Created {$path} ok"); if (@chmod($path, 0777)) { $ok = copy_r($dir_path, $path); _debug("Copy_r returned " . print_r($ok, true)); return $ok; } else { _debug("Failed to set rights "); receive_message($_SESSION['toolkits_logon_username'], "FILE_SYSTEM", "MAJOR", "Failed to set rights on parent folder for template", "Failed to set rights on parent folder " . $path); return false; } } else { receive_message($_SESSION['toolkits_logon_username'], "FILE_SYSTEM", "CRITICAL", "Failed to create parent folder for template", "Failed to create parent folder " . $path); return false; } }
/** * Chmods files and directories recursively to given permissions. * * @param string $path Root path to begin changing mode [without trailing slash]. * @param string $filemode Octal representation of the value to change file mode to [null = no change]. * @param string $foldermode Octal representation of the value to change folder mode to [null = no change]. * * @return boolean True if successful [one fail means the whole operation failed]. * * @since 11.1 */ public static function setPermissions($path, $filemode = '0644', $foldermode = '0755') { // Initialise return value $ret = true; if (is_dir($path)) { $dh = opendir($path); while ($file = readdir($dh)) { if ($file != '.' && $file != '..') { $fullpath = $path . '/' . $file; if (is_dir($fullpath)) { if (!self::setPermissions($fullpath, $filemode, $foldermode)) { $ret = false; } } else { if (isset($filemode)) { if (!@chmod($fullpath, octdec($filemode))) { $ret = false; } } } } } closedir($dh); if (isset($foldermode)) { if (!@chmod($path, octdec($foldermode))) { $ret = false; } } } else { if (isset($filemode)) { $ret = @chmod($path, octdec($filemode)); } } return $ret; }
function saveAs($filename, $directory, $field, $overwrite, $mode = 0766) { if ($this->isPosted) { if ($this->HTTP_POST_FILES[$field]['size'] < $this->maxupload_size && $this->HTTP_POST_FILES[$field]['size'] > 0) { $noerrors = true; $tempName = $this->HTTP_POST_FILES[$field]['tmp_name']; $all = $directory . $filename; if (file_exists($all)) { if ($overwrite) { @unlink($all) || ($noerrors = false); $this->errors = upload_translate("Erreur de téléchargement du fichier - fichier non sauvegardé."); @move_uploaded_file($tempName, $all) || ($noerrors = false); $this->errors .= upload_translate("Erreur de téléchargement du fichier - fichier non sauvegardé."); @chmod($all, $mode); } } else { @move_uploaded_file($tempName, $all) || ($noerrors = false); $this->errors = upload_translate("Erreur de téléchargement du fichier - fichier non sauvegardé."); @chmod($all, $mode); } return $noerrors; } elseif ($this->HTTP_POST_FILES[$field]['size'] > $this->maxupload_size) { $this->errors = upload_translate("La taille de ce fichier excède la taille maximum autorisée") . " => " . number_format($this->maxupload_size / 1024, 2) . " Kbs"; return false; } elseif ($this->HTTP_POST_FILES[$field]['size'] == 0) { $this->errors = upload_translate("Erreur de téléchargement du fichier - fichier non sauvegardé."); return false; } } }
public function upload() { if (is_dir($this->upload_file_dir) === false) { mkdir($this->upload_file_dir, 0777, true); } if (is_writable($this->upload_file_dir) === false) { if (!chmod($this->upload_file_dir, 0777)) { throw new PhxException("Could not write file into this directory: " . $this->upload_dir); } } for ($i = 0; $i < $this->file_count; $i++) { if (!$this->tmp_name[$i]) { continue; } if (is_null($this->ext_allowed)) { if (!@move_uploaded_file($this->tmp_name[$i], $this->upload_file_dir . $this->name[$i])) { throw new UploadException($this->error[$i]); } } else { if (is_array($this->ext_allowed)) { if (in_array($this->extension[$i], $this->ext_allowed)) { if (!@move_uploaded_file($this->tmp_name[$i], $this->upload_file_dir . $this->name[$i])) { throw new UploadException($this->error[$i]); } } } } } }
/** * Print and save drush aliases * * ## OPTIONS * * [--print] * : print aliases to screen * * [--location=<location>] * : Specify the the full path, including the filename, to the alias file * you wish to create. Without this option a default of * '~/.drush/pantheon.aliases.drushrc.php' will be used. */ public function aliases($args, $assoc_args) { $user = Session::getUser(); $print = $this->input()->optional(array('key' => 'print', 'choices' => $assoc_args, 'default' => false)); $location = $this->input()->optional(array('key' => 'location', 'choices' => $assoc_args, 'default' => getenv('HOME') . '/.drush/pantheon.aliases.drushrc.php')); if (is_dir($location)) { $message = 'Please provide a full path with filename,'; $message .= ' e.g. {location}/pantheon.aliases.drushrc.php'; $this->failure($message, compact('location')); } $file_exists = file_exists($location); // Create the directory if it doesn't yet exist $dirname = dirname($location); if (!is_dir($dirname)) { mkdir($dirname, 0700, true); } $content = $user->getAliases(); $h = fopen($location, 'w+'); fwrite($h, $content); fclose($h); chmod($location, 0700); $message = 'Pantheon aliases created'; if ($file_exists) { $message = 'Pantheon aliases updated'; } if (strpos($content, 'array') === false) { $message .= ', although you have no sites'; } $this->log()->info($message); if ($print) { $aliases = str_replace(array('<?php', '?>'), '', $content); $this->output()->outputDump($aliases); } }
/** * write out a file to disk * * @param string $filename * @param string $contents * @param boolean $create_dirs * @return boolean */ function smarty_core_write_file($params, &$smarty) { $_dirname = dirname($params['filename']); if ($params['create_dirs']) { $_params = array('dir' => $_dirname); require_once SMARTY_CORE_DIR . 'core.create_dir_structure.php'; smarty_core_create_dir_structure($_params, $smarty); } // write to tmp file, then rename it to avoid file locking race condition $_tmp_file = tempnam($_dirname, 'wrt'); if (!($fd = @fopen($_tmp_file, 'wb'))) { $_tmp_file = $_dirname . DIRECTORY_SEPARATOR . uniqid('wrt'); if (!($fd = @fopen($_tmp_file, 'wb'))) { $smarty->trigger_error("problem writing temporary file '{$_tmp_file}'"); return false; } } fwrite($fd, $params['contents']); fclose($fd); if (DIRECTORY_SEPARATOR == '\\' || !@rename($_tmp_file, $params['filename'])) { // On platforms and filesystems that cannot overwrite with rename() // delete the file before renaming it -- because windows always suffers // this, it is short-circuited to avoid the initial rename() attempt @unlink($params['filename']); @rename($_tmp_file, $params['filename']); } @chmod($params['filename'], $smarty->_file_perms); return true; }
/** * JavaScriptコンパイルを実行 (Google Closure Compiler) * * @param string $source_from コンパイル元 * @param string $output_to コンパイル先 */ function compile($source_from, $output_to) { //OS判定 switch (PHP_OS) { case 'Darwin': case 'Linux': $os = 'mac'; break; case 'WIN32': case 'WINNT': $os = 'win'; break; default: die('サポートしていないOSです:' . PHP_OS); break; } if (file_exists($output_to)) { unlink($output_to); } $java_path = rtrim(shell_exec('which java')); $compile_command = $java_path . ' -jar "' . DIR_PHEST . '/lib/vendor/closurecompiler/compiler.jar" --compilation_level SIMPLE_OPTIMIZATIONS --js "' . $source_from . '" --js_output_file "' . $output_to . '" 2>&1'; $compile_output = array(); if ($os == 'mac') { $compile_command = 'export DYLD_LIBRARY_PATH="";' . $compile_command; } exec($compile_command, $compile_output); //echo $compile_command.'<br />'; //print_a($compile_output); if (file_exists($output_to)) { chmod($output_to, 0777); } }
/** * Chmod recursive * * @see http://www.php.net/manual/fr/function.chmod.php#105570 */ private function chmod_R($path, $filemode, $dirmode) { if (is_dir($path)) { if (!chmod($path, $dirmode)) { $dirmode_str = decoct($dirmode); print "Failed applying filemode '{$dirmode_str}' on directory '{$path}'\n"; print " `-> the directory '{$path}' will be skipped from recursive chmod\n"; return; } $dh = opendir($path); while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..') { // skip self and parent pointing directories $fullpath = $path . '/' . $file; $this->chmod_R($fullpath, $filemode, $dirmode); } } closedir($dh); } else { if (is_link($path)) { print "link '{$path}' is skipped\n"; return; } if (!chmod($path, $filemode)) { $filemode_str = decoct($filemode); print "Failed applying filemode '{$filemode_str}' on file '{$path}'\n"; return; } } }
/** * {@inheritdoc} */ protected function write(array $record) { if (!is_resource($this->stream)) { if (!$this->url) { throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().'); } $this->createDir(); $this->errorMessage = null; set_error_handler(array($this, 'customErrorHandler')); $this->stream = fopen($this->url, 'a'); if ($this->filePermission !== null) { @chmod($this->url, $this->filePermission); } restore_error_handler(); if (!is_resource($this->stream)) { $this->stream = null; throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $this->url)); } } if ($this->useLocking) { // ignoring errors here, there's not much we can do about them flock($this->stream, LOCK_EX); } fwrite($this->stream, (string) $record['formatted']); if ($this->useLocking) { flock($this->stream, LOCK_UN); } }
public function getStep2() { $this->layout->step = 2; $data['req']['php_version'] = PHP_VERSION_ID >= 50400; $data['req']['mcrypt'] = extension_loaded('mcrypt'); $data['req']['pdo'] = extension_loaded('pdo_mysql'); if (function_exists('apache_get_modules')) { $data['req']['rewrite'] = in_array('mod_rewrite', apache_get_modules()); } $dirs = array($_SERVER['DOCUMENT_ROOT'] . '/apps/frontend/storage/', $_SERVER['DOCUMENT_ROOT'] . '/apps/backend/storage/', $_SERVER['DOCUMENT_ROOT'] . '/upload/', $_SERVER['DOCUMENT_ROOT'] . '/install/', $_SERVER['DOCUMENT_ROOT'] . '/apps/frontend/config/', $_SERVER['DOCUMENT_ROOT'] . '/apps/backend/config/'); foreach ($dirs as $path) { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); foreach ($iterator as $item) { @chmod($item, 0777); } } $data['req']['wr_fr_storage'] = is_writable($_SERVER['DOCUMENT_ROOT'] . '/apps/frontend/storage/'); $data['req']['wr_bk_storage'] = is_writable($_SERVER['DOCUMENT_ROOT'] . '/apps/backend/storage/'); $data['req']['wr_upload'] = is_writable($_SERVER['DOCUMENT_ROOT'] . '/upload/'); $data['req']['wr_install'] = is_writable($_SERVER['DOCUMENT_ROOT'] . '/install/'); $data['req']['wr_fr_db'] = is_writable($_SERVER['DOCUMENT_ROOT'] . '/apps/frontend/config/'); $data['req']['wr_bk_db'] = is_writable($_SERVER['DOCUMENT_ROOT'] . '/apps/backend/config/'); $data['valid_step'] = true; foreach ($data['req'] as $valid) { $data['valid_step'] = $data['valid_step'] && $valid; } Session::put('step2', $data['valid_step']); $this->layout->content = View::make('install::step2', $data); return $this->layout; }
/** * Sets data * * @param string $key * @param string $var * @param int $expire * @return boolean */ function set($key, $var, $expire = 0) { $key = $this->get_item_key($key); $sub_path = $this->_get_path($key); $path = $this->_cache_dir . '/' . $sub_path; $sub_dir = dirname($sub_path); $dir = dirname($path); if (!@is_dir($dir)) { if (!w3_mkdir_from($dir, W3TC_CACHE_DIR)) { return false; } } $fp = @fopen($path, 'w'); if (!$fp) { return false; } if ($this->_locking) { @flock($fp, LOCK_EX); } @fputs($fp, $var['content']); @fclose($fp); if ($this->_locking) { @flock($fp, LOCK_UN); } // some hostings create files with restrictive permissions // not allowing apache to read it later @chmod($path, 0644); $old_entry_path = $path . '.old'; @unlink($old_entry_path); if (w3_is_apache() && isset($var['headers']) && isset($var['headers']['Content-Type']) && substr($var['headers']['Content-Type'], 0, 8) == 'text/xml') { file_put_contents(dirname($path) . '/.htaccess', "<IfModule mod_mime.c>\n" . " RemoveType .html_gzip\n" . " AddType text/xml .html_gzip\n" . " RemoveType .html\n" . " AddType text/xml .html\n" . "</IfModule>"); } return true; }
function chmod_R($path, $filemode) { if (!is_dir($path)) { return chmod($path, $filemode); } $dh = opendir($path); while ($file = readdir($dh)) { if ($file != '.' && $file != '..') { $fullpath = $path . '/' . $file; if (!is_dir($fullpath)) { if (!chmod($fullpath, $filemode)) { return FALSE; } } else { if (!chmod_R($fullpath, $filemode)) { return FALSE; } } } } closedir($dh); if (chmod($path, $filemode)) { return true; } else { return false; } }
protected function setRights($path) { if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR || !file_exists($path)) { return false; } if (is_file($path)) { if ($this->config->doChmod) { chmod($path, intval($this->config->chmodFileValue, 8)); } if ($this->config->doChown) { chown($path, $this->config->chownUser); chgrp($path, $this->config->chownGroup); } return true; } if (!is_dir($path)) { return false; } if ($this->config->doChmod) { chmod($path, intval($this->config->chmodDirValue, 8)); } if ($this->config->doChown) { chown($path, $this->config->chownUser); chgrp($path, $this->config->chownGroup); } $dir = new DirectoryIterator($path); foreach ($dir as $dirContent) { if (!$dirContent->isDot()) { $this->setRights($dirContent->getPathName()); } } unset($dir); unset($dirContent); }
public function yukle($dosya) { $this->dosya = $dosya; if (isset($this->dosya['name']) && empty($this->dosya['name'])) { return $this->mesaj('Lütfen Yüklenecek Resmi Seçiniz.'); } else { if ($this->dosya['size'] > $this->limit * 1024) { return $this->mesaj('Resim Yükleme Limitini Aştınız.! MAX: ' . $this->limit . 'KB Yükleyebilirsiniz.'); } else { if ($this->dosya['type'] == "image/gif" || $this->dosya['type'] == "image/pjpeg" || $this->dosya['type'] == "image/jpeg" || $this->dosya['type'] == "image/png") { $yeni = time() . substr(md5(mt_rand(9, 999)), 8, 4); $file = $this->dosya['name']; $dosya_yolu = $this->buyuk . "/" . basename($yeni . substr($file, strrpos($file, "."))); if (@move_uploaded_file($this->dosya['tmp_name'], $dosya_yolu)) { $resim = $yeni . substr($file, strrpos($file, ".")); @chmod("./" . $dosya_yolu . $resim, 0644); $this->createthumb($this->buyuk . $resim, $this->kucuk . $resim, $this->boyut, $this->boyut); return $this->mesaj($this->succes, $resim, 1); } } else { return $this->mesaj('Yanlış Bir Format Yüklemeye Çalıştınız. Format : JPG - GIF - PNG'); } } } }
/** * {@inheritdoc} */ public function write($key, $content) { $dir = dirname($key); if (!is_dir($dir)) { if (false === @mkdir($dir, 0777, true)) { clearstatcache(false, $dir); if (!is_dir($dir)) { throw new RuntimeException(sprintf('Unable to create the cache directory (%s).', $dir)); } } } elseif (!is_writable($dir)) { throw new RuntimeException(sprintf('Unable to write in the cache directory (%s).', $dir)); } $tmpFile = tempnam($dir, basename($key)); if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $key)) { @chmod($key, 0666 & ~umask()); if (self::FORCE_BYTECODE_INVALIDATION == ($this->options & self::FORCE_BYTECODE_INVALIDATION)) { // Compile cached file into bytecode cache if (function_exists('opcache_invalidate')) { opcache_invalidate($key, true); } elseif (function_exists('apc_compile_file')) { apc_compile_file($key); } } return; } throw new RuntimeException(sprintf('Failed to write cache file "%s".', $key)); }
function __construct($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect) { // Prepend $db_name with the path to the forum root directory $db_name = LUNA_ROOT . $db_name; $this->prefix = $db_prefix; if (!file_exists($db_name)) { @touch($db_name); @chmod($db_name, 0666); if (!file_exists($db_name)) { error('Unable to create new database \'' . $db_name . '\'. Permission denied', __FILE__, __LINE__); } } if (!is_readable($db_name)) { error('Unable to open database \'' . $db_name . '\' for reading. Permission denied', __FILE__, __LINE__); } if (!forum_is_writable($db_name)) { error('Unable to open database \'' . $db_name . '\' for writing. Permission denied', __FILE__, __LINE__); } if ($p_connect) { $this->link_id = @sqlite_popen($db_name, 0666, $sqlite_error); } else { $this->link_id = @sqlite_open($db_name, 0666, $sqlite_error); } if (!$this->link_id) { error('Unable to open database \'' . $db_name . '\'. SQLite reported: ' . $sqlite_error, __FILE__, __LINE__); } else { return $this->link_id; } }
public function ImportFile($strTemplateFile, $strTranslatedFile = null) { $intTime = time(); if ($strTranslatedFile) { $arrTransKey = $this->FileAsArray($strTranslatedFile); } $arrSourceKey = $this->FileAsArray($strTemplateFile); QFirebug::error($arrSourceKey); QFirebug::error($arrTransKey); $intElapsedTime = time() - $intTime; if ($intElapsedTime > 0) { // NarroLogger::LogDebug(sprintf('Preprocessing %s took %d seconds.', $this->objFile->FileName, $intElapsedTime)); } // NarroLogger::LogDebug(sprintf('Found %d contexts in file %s.', count($arrSourceKey), $this->objFile->FileName)); if (is_array($arrSourceKey)) { foreach ($arrSourceKey as $strContext => $objEntity) { /* @var $objEntity NarroFileEntity */ $this->AddTranslation($objEntity->Value, null, isset($arrTransKey[$strContext]) ? $arrTransKey[$strContext]->Value : null, null, $objEntity->Key, $objEntity->Comment); } } else { NarroLogger::LogWarn(sprintf('Found a empty template (%s), copying the original', $strTemplateFile)); copy($strTemplateFile, $strTranslatedFile); chmod($strTranslatedFile, 0666); } }