Example #1
0
 protected function doChmod($remote_file, $chmod_code)
 {
     // try to chmod
     $chmod_code = octdec(str_pad($chmod_code, 4, '0', STR_PAD_LEFT));
     $chmod_code = (int) $chmod_code;
     return ftp_chmod($this->getConnection(), $chmod_code, $remote_file);
 }
Example #2
0
 /**
  * Parses a DNUMBER token like PHP would.
  *
  * @param string $str A string number
  *
  * @return float The parsed number
  */
 public static function parse($str)
 {
     // if string contains any of .eE just cast it to float
     if (false !== strpbrk($str, '.eE')) {
         return (double) $str;
     }
     // otherwise it's an integer notation that overflowed into a float
     // if it starts with 0 it's one of the special integer notations
     if ('0' === $str[0]) {
         // hex
         if ('x' === $str[1] || 'X' === $str[1]) {
             return hexdec($str);
         }
         // bin
         if ('b' === $str[1] || 'B' === $str[1]) {
             return bindec($str);
         }
         // oct
         // substr($str, 0, strcspn($str, '89')) cuts the string at the first invalid digit (8 or 9)
         // so that only the digits before that are used
         return octdec(substr($str, 0, strcspn($str, '89')));
     }
     // dec
     return (double) $str;
 }
 /**
  * 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);
 }
Example #4
0
    /**
     * Constructor.
     *
     * $filePath File path. If specified, file metadata is fetched in the constructor.
     */
    function __construct( $filePath = false )
    {
        $filePath = eZDBFileHandler::cleanPath( $filePath );
        eZDebugSetting::writeDebug( 'kernel-clustering', "db::ctor( '$filePath' )" );

        if ( self::$dbbackend === null )
        {
            $optionArray = array( 'iniFile'     => 'file.ini',
                                  'iniSection'  => 'ClusteringSettings',
                                  'iniVariable' => 'DBBackend' );

            $options = new ezpExtensionOptions( $optionArray );

            self::$dbbackend = eZExtension::getHandlerClass( $options );
            self::$dbbackend->_connect( false );

            // connection failed
            if( self::$dbbackend->db === false )
                throw new eZClusterHandlerDBNoConnectionException( self::$dbbackend->dbparams['host'], self::$dbbackend->dbparams['user'], self::$dbbackend->dbparams['pass'] );
        }

        $this->filePath = $filePath;

        if ( !isset( $GLOBALS['eZDBFileHandler_Settings'] ) )
        {
            $fileINI = eZINI::instance( 'file.ini' );
            $GLOBALS['eZDBFileHandler_Settings']['NonExistantStaleCacheHandling'] = $fileINI->variable( "ClusteringSettings", "NonExistantStaleCacheHandling" );
            unset( $fileINI );
        }
        $this->nonExistantStaleCacheHandling = $GLOBALS['eZDBFileHandler_Settings']['NonExistantStaleCacheHandling'];
        $this->filePermissionMask = octdec( eZINI::instance()->variable( 'FileSettings', 'StorageFilePermissions' ) );
    }
Example #5
0
 /**
  * @return array  Tar file data:
  * <pre>
  * KEY: Position in the array
  * VALUES:
  *   attr - File attributes
  *   data - Raw file contents
  *   date - File modification time
  *   name - Filename
  *   size - Original file size
  *   type - File type
  * </pre>
  *
  * @throws Horde_Compress_Exception
  */
 public function decompress($data, array $params = array())
 {
     $data_len = strlen($data);
     $position = 0;
     $return_array = array();
     while ($position < $data_len) {
         if (version_compare(PHP_VERSION, '5.5', '>=')) {
             $info = @unpack('Z100filename/Z8mode/Z8uid/Z8gid/Z12size/Z12mtime/Z8checksum/Ctypeflag/Z100link/Z6magic/Z2version/Z32uname/Z32gname/Z8devmajor/Z8devminor', substr($data, $position));
         } else {
             $info = @unpack('a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/Ctypeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor', substr($data, $position));
         }
         if (!$info) {
             throw new Horde_Compress_Exception(Horde_Compress_Translation::t("Unable to decompress data."));
         }
         $position += 512;
         $contents = substr($data, $position, octdec($info['size']));
         $position += ceil(octdec($info['size']) / 512) * 512;
         if ($info['filename']) {
             $file = array('attr' => null, 'data' => null, 'date' => octdec($info['mtime']), 'name' => trim($info['filename']), 'size' => octdec($info['size']), 'type' => isset($this->_types[$info['typeflag']]) ? $this->_types[$info['typeflag']] : null);
             if ($info['typeflag'] == 0 || $info['typeflag'] == 0x30 || $info['typeflag'] == 0x35) {
                 /* File or folder. */
                 $file['data'] = $contents;
                 $mode = hexdec(substr($info['mode'], 4, 3));
                 $file['attr'] = ($info['typeflag'] == 0x35 ? 'd' : '-') . ($mode & 0x400 ? 'r' : '-') . ($mode & 0x200 ? 'w' : '-') . ($mode & 0x100 ? 'x' : '-') . ($mode & 0x40 ? 'r' : '-') . ($mode & 0x20 ? 'w' : '-') . ($mode & 0x10 ? 'x' : '-') . ($mode & 0x4 ? 'r' : '-') . ($mode & 0x2 ? 'w' : '-') . ($mode & 0x1 ? 'x' : '-');
             }
             $return_array[] = $file;
         }
     }
     return $return_array;
 }
Example #6
0
 function put_gallery($gallery)
 {
     $csvpath = $this->config->base_path . $this->config->pathto_galleries . $gallery->id . "/metadata.csv";
     if (!is_writeable($csvpath) && file_exists($csvpath)) {
         // this is the fix for a fubared metadata file
         $perms = substr(sprintf('%o', fileperms($csvpath)), -4);
         if ($perms == '0000') {
             @chmod($csvpath, octdec($this->config->chmod_value));
         }
     }
     $fp = fopen($csvpath, "w");
     // throw an error if necessary
     if (!$fp) {
         if (file_exists($csvpath)) {
             echo 'Please fix permissions on ' . realpath($this->config->base_path . $this->config->pathto_galleries . $gallery->id);
         } else {
             echo "PhotoStack can't open your metadata file to write to it.";
         }
         return false;
     } else {
         // write csv header
         $success = (bool) fwrite($fp, "filename/thumbnail,image_name,description,long_description,date,sort");
         // write csv data
         $success &= (bool) fwrite($fp, "\n\"" . $gallery->filename . "\",\"" . $gallery->name . '","' . $gallery->desc . '","' . $gallery->long_desc . '","' . $gallery->date . '"');
         for ($i = 0; $i < count($gallery->images); $i++) {
             $success &= (bool) fwrite($fp, "\n\"" . $gallery->images[$i]->filename . "\",\"" . str_replace('"', '""', $gallery->images[$i]->name) . '","' . str_replace('"', '""', $gallery->images[$i]->desc) . '","' . str_replace('"', '""', $gallery->images[$i]->long_desc) . '",' . str_replace('"', '""', $gallery->images[$i]->date) . ',"' . str_replace('"', '""', $gallery->images[$i]->sort) . '"');
         }
         $success &= (bool) fclose($fp);
         @chmod($csvpath, octdec($this->config->chmod_value));
         return $success;
     }
 }
Example #7
0
 function CreateDatabase(&$db, $name)
 {
     if (!function_exists("sqlite_open")) {
         return $db->SetError("Connect", "SQLite support is not available in this PHP configuration");
     }
     $database_file = $db->GetDatabaseFile($name);
     if (@file_exists($database_file)) {
         return $db->SetError("Create database", "database already exists");
     }
     @touch($database_file);
     if (!@file_exists($database_file)) {
         return $db->SetError("Create database", "Unable to create new database. Permission denied");
     }
     $mode = isset($db->options["AccessMode"]) ? strcmp($db->options["AccessMode"][0], "0") ? intval($db->options["AccessMode"]) : octdec($db->options["AccessMode"]) : 0640;
     @chmod($database_file, $mode);
     if (!is_readable($database_file)) {
         @unlink($database_file);
         return $db->SetError("Create database", "Unable to open database for Reading. Permission denied");
     }
     if (!is_writable($database_file)) {
         @unlink($database_file);
         return $db->SetError("Create database", "Unable to open database for Writing. Permission denied");
     }
     $handle = @sqlite_open($database_file, $mode);
     if (!$handle) {
         @unlink($database_file);
         return $db->SetError("Create database", isset($php_errormsg) ? $php_errormsg : "could not create the database file");
     }
     sqlite_close($handle);
     return 1;
 }
Example #8
0
 /**
  * Tries to change a folder/file's permissions using direct access or FTP
  *
  * @param   string  $path  The full path to the folder/file to chmod
  * @param   int     $mode  New permissions
  *
  * @return  bool  True on success
  */
 private function chmod($path, $mode)
 {
     if (is_string($mode)) {
         $mode = octdec($mode);
         $trustMeIKnowWhatImDoing = 500 + 10 + 1;
         // working around overzealous scanners written by bozos
         $ohSixHundred = 386 - 2;
         $ohSevenFiveFive = 500 - 7;
         if ($mode < $ohSixHundred || $mode > $trustMeIKnowWhatImDoing) {
             $mode = $ohSevenFiveFive;
         }
     }
     // Initialize variables
     JLoader::import('joomla.client.helper');
     $ftpOptions = JClientHelper::getCredentials('ftp');
     // Check to make sure the path valid and clean
     $path = JPath::clean($path);
     if (@chmod($path, $mode)) {
         $ret = true;
     } elseif ($ftpOptions['enabled'] == 1) {
         // Connect the FTP client
         JLoader::import('joomla.client.ftp');
         $ftp = JClientFtp::getInstance($ftpOptions['host'], $ftpOptions['port'], array(), $ftpOptions['user'], $ftpOptions['pass']);
         // Translate path and delete
         $path = JPath::clean(str_replace(JPATH_ROOT, $ftpOptions['root'], $path), '/');
         // FTP connector throws an error
         $ret = $ftp->chmod($path, $mode);
     } else {
         $ret = false;
     }
     return $ret;
 }
Example #9
0
    function parseFile( $fileName )
    {
        $binaryINI = eZINI::instance( 'binaryfile.ini' );

        $textExtractionTool = $binaryINI->variable( 'WordHandlerSettings', 'TextExtractionTool' );

        $tmpName = "var/cache/" . md5( time() ) . '.txt';
        $handle = fopen( $tmpName, "w" );
        fclose( $handle );

        $perm = octdec( eZINI::instance()->variable( 'FileSettings', 'StorageFilePermissions' ) );
        chmod( $tmpName, $perm );

        exec( "$textExtractionTool $fileName > $tmpName", $ret );

        $metaData = "";
        if ( file_exists( $tmpName ) )
        {
            $fp = fopen( $tmpName, "r" );
            $metaData = fread( $fp, filesize( $tmpName ) );
            $metaData = strip_tags( $metaData );
            fclose( $fp );
            unlink( $tmpName );
        }

        return $metaData;
    }
Example #10
0
 public function pathChmod()
 {
     if ($_SERVER['HTTP_REFERER'] != $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]) {
         if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
             $info_list = json_decode($this->in['list'], true);
             $mod = octdec('0' . $this->in['mod']);
             $success = 0;
             $error = 0;
             foreach ($info_list as $val) {
                 $path = _DIR($val['path']);
                 if (chmod_path($path, $mod)) {
                     $success++;
                 } else {
                     $error++;
                 }
             }
             $state = $error == 0 ? true : false;
             $info = $success . ' success,' . $error . ' error';
             if (count($info_list) == 1 && $error == 0) {
                 $info = $this->L['success'];
             }
             show_json($info, $state);
         }
     } else {
         header('Location: 403.php');
     }
 }
Example #11
0
 /**
  * Initiates the sync by exchanging file lists
  * @param $url string URL to remote sync server script
  */
 public function run($url)
 {
     $this->curl = curl_init($url);
     //send client file list to server
     $localFiles = $this->getFileList($this->path);
     $request = array('action' => self::ACTION_FILELIST, 'data' => $localFiles);
     $response = $this->post($request);
     if (isset($response['error'])) {
         echo $response['error'];
         return;
     }
     //process modified files
     foreach ($response['data'] as $relativePath => $info) {
         //fetch file contents
         $response = $this->post(array('action' => self::ACTION_FETCH, 'file' => $relativePath));
         //save file
         $absolutePath = $this->path . $relativePath;
         if (!file_exists(dirname($absolutePath))) {
             mkdir(dirname($absolutePath), 0777, true);
         }
         file_put_contents($absolutePath, $response);
         //update modified time to match server
         touch($absolutePath, $info['timestamp']);
         //update permissions to match server
         chmod($absolutePath, octdec(intval($info['fileperm'])));
     }
 }
Example #12
0
 protected function _getTarInfo(&$data)
 {
     $position = 0;
     $return_array = array();
     while ($position < strlen($data)) {
         $info = @unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/Ctypeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor", substr($data, $position));
         if (!$info) {
             $this->set('error.message', 'Unable to decompress data');
             return false;
         }
         $position += 512;
         $contents = substr($data, $position, octdec($info['size']));
         $position += ceil(octdec($info['size']) / 512) * 512;
         if ($info['filename']) {
             $file = array('attr' => null, 'data' => null, 'date' => octdec($info['mtime']), 'name' => trim($info['filename']), 'size' => octdec($info['size']), 'type' => isset($this->_types[$info['typeflag']]) ? $this->_types[$info['typeflag']] : null);
             if ($info['typeflag'] == 0 || $info['typeflag'] == 0x30 || $info['typeflag'] == 0x35) {
                 /* File or folder. */
                 $file['data'] = $contents;
                 $mode = hexdec(substr($info['mode'], 4, 3));
                 $file['attr'] = ($info['typeflag'] == 0x35 ? 'd' : '-') . ($mode & 0x400 ? 'r' : '-') . ($mode & 0x200 ? 'w' : '-') . ($mode & 0x100 ? 'x' : '-') . ($mode & 0x40 ? 'r' : '-') . ($mode & 0x20 ? 'w' : '-') . ($mode & 0x10 ? 'x' : '-') . ($mode & 0x4 ? 'r' : '-') . ($mode & 0x2 ? 'w' : '-') . ($mode & 0x1 ? 'x' : '-');
             } else {
                 /* Some other type. */
             }
             $return_array[] = $file;
         }
     }
     $this->_metadata = $return_array;
     return true;
 }
	/**
	 * Folder will be created and Permissions will be set to the specified permissions.
	 *
	 * If the folder exists just the permissions will be set.
	 * See FileSystemNode::setPermissions() on how to specify the permissions correctly.
	 * This function will also return false if the chmod are not set correctly.
	 * Folders are created recursively.
	 *
	 * This function implements the ftp fallback!
	 *
	 * @see Folder::setPermissions()
	 * @param int Permissions to set for the directory (default is 777)
	 * @return boolean Returns TRUE on success or FALSE on failure.
	 */
	public function create($permissions = 777) {
		$chmodResult = false;
		if ($this->exists() == false) {
			if (mkdir($this->path, octdec($permissions), true) == false && $this->ftp == true) {
				$ftp = FileSystem::initializeFTP();
				// Make sure the dir is created recursively as this is not natively supported by ftp
				$folders = preg_split('~[\\/]+~', $this->ftpPath(), -1, PREG_SPLIT_NO_EMPTY);
				$root = self::SEPARATOR;
				foreach ($folders as $folder) {
					$root .= $folder.self::SEPARATOR;
					if ($ftp->exists($root) == false) {
						$ftp->mkdir($root);
					}
				}
				$chmodResult = $this->setPermissions($permissions);
			}
		}
		else {
			$chmodResult = $this->setPermissions($permissions);
		}

		/*
		 * We should check the permissions like below, but windows does not support chmods properly
		 * and therefore this condition would fail always for chmods other than 666 and 777.
		 * return ($this->exists() && $this->getPermissions() == $permissions);
		 */
		return ($this->exists() && $chmodResult);
	}
Example #14
0
 /**
  * cria estrutura
  * @param string $path
  * @return string
  */
 private static function createStructPersist($path)
 {
     $year = date('Y');
     $month = date('m');
     $path .= Registry::get('bootstrap')->config()->get('app.file.repository');
     $system = Registry::get('bootstrap')->request()->getModule();
     $permission = octdec(self::$_permission);
     # obtenho a permissao do diretorio
     $repoSystem = $path . DIRECTORY_SEPARATOR . $system;
     # destino onde os arquivos serao salvos
     $repoCreate = $repoSystem . DIRECTORY_SEPARATOR . $year . DIRECTORY_SEPARATOR . $month;
     #@todo lancar exception se não poder efetuar a escrita is_writable
     $owner = self::whoIsOwner($path);
     $permDir = self::pathPermissions($path);
     //dump("SEM PERMISSAO PARA ESCRITA, PERMISSAO NA PASTA É {$permDir} E O DONO É {$owner}" ,1);
     # listo os diretorios e procuro na lista de diretorios pelo sistema informado
     if (!array_search($system, scandir($path))) {
         # cria repositorio e sub-diretorios referente ao Mes
         mkdir($repoCreate, $permission, TRUE);
     } else {
         # a pasta do sistema existe, agora faz a valizadacao da estrutura
         if (!array_search($year, scandir($repoSystem))) {
             mkdir($repoCreate, $permission, TRUE);
         } else {
             # Ultima verificacao caso o sub referente ao mes nao foi criado
             $listDir = scandir($repoSystem . DIRECTORY_SEPARATOR . $year);
             if (!array_search($month, $listDir)) {
                 mkdir($repoCreate, $permission, TRUE);
             }
         }
     }
     return base64_encode($repoCreate);
 }
Example #15
0
 private function processTemplatesData(array $templates, $data)
 {
     $commands = array();
     foreach ($templates as $template) {
         $document = $this->extractFrontMatter($template);
         $meta = $document->getConfig();
         // validate meta data variables
         $this->validate($meta, $this->schemaMeta);
         // use a new dummy loader whose sole responsibilty is mapping template name to contents
         // this allows us to reference the template by name (and receive according error messages)
         $this->twig->setLoader(new Twig_Loader_Array(array($template => $document->getContent())));
         // create resulting configuration file by processing template
         $contents = $this->processTemplateContents($template, array('data' => $data, 'meta' => $meta));
         // chmod is either unset or convert decimal to octal notation
         $meta['chmod'] = isset($meta['chmod']) ? octdec($meta['chmod']) : null;
         // target file name can either be given or defaults to template name without ".twig" extension
         $target = isset($meta['target']) ? $meta['target'] : $this->fs->basename($template, '.twig');
         // write resulting configuration to target path and apply
         if (!$this->fs->fileContains($target, $contents)) {
             $this->fs->fileReplace($target, $contents, $meta['chmod']);
             // template has a command definition to reload this file
             if (isset($meta['reload'])) {
                 $commands[] = $meta['reload'];
             }
         }
     }
     // let's reload all the files after (successfully) writing all of them
     foreach ($commands as $command) {
         $this->execute($command);
     }
 }
Example #16
0
 /**
  * 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);
     /**
      * @link http://codeigniter.com/forums/viewthread/214796/
      */
     if (octdec(substr(sprintf('%o', fileperms($filepath)), -4)) != FILE_WRITE_MODE) {
         @chmod($filepath, FILE_WRITE_MODE);
     }
     return TRUE;
 }
Example #17
0
 protected function onBrowse($tpl = null)
 {
     // Default permissions
     if (interface_exists('JModel')) {
         $params = JModelLegacy::getInstance('Storage', 'AdmintoolsModel');
     } else {
         $params = JModel::getInstance('Storage', 'AdmintoolsModel');
     }
     $dirperms = '0' . ltrim(trim($params->getValue('dirperms', '0755')), '0');
     $fileperms = '0' . ltrim(trim($params->getValue('fileperms', '0644')), '0');
     $dirperms = octdec($dirperms);
     if ($dirperms < 0600 || $dirperms > 0777) {
         $dirperms = 0755;
     }
     $this->dirperms = '0' . decoct($dirperms);
     $fileperms = octdec($fileperms);
     if ($fileperms < 0600 || $fileperms > 0777) {
         $fileperms = 0755;
     }
     $this->fileperms = '0' . decoct($fileperms);
     // File lists
     $model = $this->getModel();
     $listing = $model->getListing();
     $this->listing = $listing;
     $relpath = $model->getState('filter_path', '');
     $this->path = $relpath;
 }
Example #18
0
 /**
  * @param   string $path The path of the Folder
  * @param   int $permission The permission to create the folder with.
  *
  * @return  Folder The domain object for further usage
  *
  * @author  Nicolas Pecher
  * @version Version 0.1, 01.05.2012
  * @version Version 0.2, 14.08.2012 (Bug-fix: default permissions are now set to ug+rwx; using PHP's built in recursive path creation)
  */
 public function create($path, $permission = 0770)
 {
     if (!is_dir($path)) {
         // due to a potential PHP bug with directly passing the permissions
         // we have to initiate a workaround containing explicit formatting as
         // well as umask setting to create the folders with correct permissions
         // to provide a common API, octal numbers must be convert to the
         // internal string representation. otherwise we will get wrong
         // permissions with octal numbers!
         if (is_int($permission)) {
             $permission = decoct($permission);
         }
         // now the correct string representation must be created to ensure
         // correct permissions (leading zero is important!)
         $oct = sprintf('%04u', $permission);
         // to be able to pass the argument as an octal number, the string must
         // be correctly formatted
         $permission = octdec($oct);
         // on some boxes, the current umask prevents correct permission appliance.
         // thus, the umask is set to 0000 to avoid permission shifts. this maybe
         // a PHP bug but umasks unlike 0000 lead to wrong permissions, however.
         $oldUmask = umask(0);
         // the last parameter allows the creation of nested directories
         mkdir($path, $permission, true);
         umask($oldUmask);
     }
     $this->open($path);
     return $this;
 }
Example #19
0
    /**
     * Atomically dump content into a file.
     *
     * @param string  $filename  Path of file to store
     * @param string  $content   Content to store
     * @param int  $mode  File mode to set 
     * @return void
     */
    public static function put($filename, $content, $mode = null)
    {
        Debug::increment('files', 'written');
        $fs = new Filesystem();
        
        // custom umask and file mode
//        $custom_umask  = Config::get('_umask', false);
        $custom_mode   = Config::get('_mode', false);
        $old_umask     = null;
        
        // Dipper accurately recognizes octal numbers, where the others don't
        if (Config::get('yaml_mode') !== 'quick') {
//            $custom_umask = octdec($custom_umask);
            $custom_mode  = octdec($custom_mode);
        }
        
        // if a custom umask was set, set it and remember the old one
//        if ($custom_umask !== false) {
//            $old_umask = umask($custom_umask);
//        }
        
        if (File::exists($filename)) {
            $mode = intval(substr(sprintf('%o', fileperms($filename)), -4), 8);
        } elseif (is_null($mode)) {
            $mode = ($custom_mode !== false) ? $custom_mode : 0755;
        }
        
        $fs->dumpFile($filename, $content, $mode);
        
        // if a custom umask was set, replace the old value
//        if ($custom_umask !== false) {
//            umask($old_umask);
//        }
    }
 /**
  * @param string $permissions
  * @return int
  * @throws UrlResolveException
  */
 private static function parsePermissions($permissions)
 {
     if (ctype_digit($permissions) && $permissons[0] === '0') {
         return octdec($permissions);
     }
     throw new UrlResolveException("Invalid file permissions specification: '{$permissions}'");
 }
Example #21
0
 public static function installAssets($event)
 {
     $options = self::getOptions($event);
     $webDir = $options['bolt-web-dir'];
     $dirMode = $options['bolt-dir-mode'];
     if (is_string($dirMode)) {
         $dirMode = octdec($dirMode);
     }
     if (!is_dir($webDir)) {
         echo 'The bolt-web-dir (' . $webDir . ') specified in composer.json was not found in ' . getcwd() . ', can not install assets.' . PHP_EOL;
         return;
     }
     $targetDir = $webDir . '/bolt-public/';
     $filesystem = new Filesystem();
     $filesystem->remove($targetDir);
     $filesystem->mkdir($targetDir, $dirMode);
     //$filesystem->mkdir($targetDir, $dirMode);
     foreach (array('css', 'font', 'img', 'js', 'lib') as $dir) {
         $filesystem->mirror(__DIR__ . '/../../../view/' . $dir, $targetDir . '/view/' . $dir);
     }
     $filesystem->mirror(__DIR__ . '/../../../classes/upload', $targetDir . '/classes/upload');
     $filesystem->copy(__DIR__ . '/../../../classes/timthumb.php', $targetDir . '/classes/timthumb.php');
     if (!$filesystem->exists($webDir . '/files/')) {
         $filesystem->mirror(__DIR__ . '/../../../../files', $webDir . '/files');
     }
 }
Example #22
0
 public function checkWritePermissions()
 {
     $writable = array('cache', 'storage', 'public.cache', 'public.upload');
     $failed = array();
     foreach ($writable as $dir) {
         $path = ClassLoader::getRealPath($dir);
         $testFile = $path . '/test.txt';
         // try a couple of permissions
         foreach (array(0, 755, 777) as $mode) {
             if ($mode) {
                 @chmod($path, octdec($mode));
             }
             $res = @file_put_contents($testFile, 'test');
             if ($res) {
                 break;
             }
         }
         if (!file_exists($testFile)) {
             $failed[] = $path;
         } else {
             unlink($testFile);
         }
     }
     return 0 == count($failed) ? true : $failed;
 }
Example #23
0
 private function make_child_dir($path)
 {
     // No need to continue if the directory already exists
     if (is_dir($path)) {
         return true;
     }
     // Make sure parent exists
     $parent = dirname($path);
     if (!is_dir($parent)) {
         $this->make_child_dir($parent);
     }
     $created = false;
     $old = umask(0);
     // Try to create new directory with parent directory's permissions
     $permissions = substr(sprintf('%o', fileperms($parent)), -4);
     if (is_dir($path) || mkdir($path, octdec($permissions), true)) {
         $created = true;
     } else {
         if ($permissions == '0755' && chmod($parent, 0777) && mkdir($path, 0777, true)) {
             $created = true;
         }
     }
     umask($old);
     return $created;
 }
Example #24
0
 public function __set($varname, $value)
 {
     switch ($varname) {
         case 'uploadelementname':
             $this->uploadelementname = $value;
             break;
         case 'destination':
             $this->destination = $value;
             break;
         case 'permissions':
             $this->permissions = octdec($value);
             break;
         case 'allowed_extensions':
             if (tep_not_null($value)) {
                 if (is_array($value)) {
                     $this->allowed_extensions = $value;
                 } else {
                     $this->allowed_extensions = array($value);
                 }
             } else {
                 $this->allowed_extensions = array();
             }
             break;
     }
 }
Example #25
0
 /**
  * Set globally writable permissions on the "tmp" and "logs" directory.
  *
  * This is not the most secure default, but it gets people up and running quickly.
  *
  * @param string $dir The application's root directory.
  * @param \Composer\IO\IOInterface $io IO interface to write to console.
  *
  * @return void
  */
 public static function setFolderPermissions($dir, $io)
 {
     // Change the permissions on a path and output the results.
     $changePerms = function ($path, $perms, $io) {
         // Get current permissions in decimal format so we can bitmask it.
         $currentPerms = octdec(substr(sprintf('%o', fileperms($path)), -4));
         if (($currentPerms & $perms) == $perms) {
             return;
         }
         $res = chmod($path, $currentPerms | $perms);
         if ($res) {
             $io->write('Permissions set on ' . $path);
         } else {
             $io->write('Failed to set permissions on ' . $path);
         }
     };
     $walker = function ($dir, $perms, $io) use(&$walker, $changePerms) {
         $files = array_diff(scandir($dir), ['.', '..']);
         foreach ($files as $file) {
             $path = $dir . '/' . $file;
             if (!is_dir($path)) {
                 continue;
             }
             $changePerms($path, $perms, $io);
             $walker($path, $perms, $io);
         }
     };
     $worldWritable = bindec('0000000111');
     $walker($dir . '/tmp', $worldWritable, $io);
     $changePerms($dir . '/tmp', $worldWritable, $io);
     $changePerms($dir . '/logs', $worldWritable, $io);
 }
Example #26
0
 public function _connect()
 {
     if (isset($this->_profile['storage_dir']) && $this->_profile['storage_dir'] != '') {
         $this->_storage_dir = str_replace(array('var:', 'temp:'), array(jApp::varPath(), jApp::tempPath()), $this->_profile['storage_dir']);
         $this->_storage_dir = rtrim($this->_storage_dir, '\\/') . DIRECTORY_SEPARATOR;
     } else {
         $this->_storage_dir = jApp::varPath('kvfiles/');
     }
     jFile::createDir($this->_storage_dir);
     if (isset($this->_profile['file_locking'])) {
         $this->_file_locking = $this->_profile['file_locking'] ? true : false;
     }
     if (isset($this->_profile['automatic_cleaning_factor'])) {
         $this->automatic_cleaning_factor = $this->_profile['automatic_cleaning_factor'];
     }
     if (isset($this->_profile['directory_level']) && $this->_profile['directory_level'] > 0) {
         $this->_directory_level = $this->_profile['directory_level'];
         if ($this->_directory_level > 16) {
             $this->_directory_level = 16;
         }
     }
     if (isset($this->_profile['directory_umask']) && is_string($this->_profile['directory_umask']) && $this->_profile['directory_umask'] != '') {
         $this->_directory_umask = octdec($this->_profile['directory_umask']);
     }
     if (isset($this->_profile['file_umask']) && is_string($this->_profile['file_umask']) && $this->_profile['file_umask'] != '') {
         $this->file_umask = octdec($this->_profile['file_umask']);
     }
 }
Example #27
0
 /**
  * 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;
 }
Example #28
0
function getChmod($dir = false)
{
    if (USE_CHMOD === false) {
        return false;
    }
    global $ADMIN_CONF;
    $mode = $ADMIN_CONF->get("chmodnewfilesatts");
    if (is_numeric($mode) and strlen($mode) == 3) {
        if ($dir === true) {
            // X-Bit setzen, um Verzeichniszugriff zu garantieren
            if (substr($mode, 0, 1) >= 2 and substr($mode, 0, 1) <= 6) {
                $mode = $mode + 100;
            }
            if (substr($mode, 1, 1) >= 2 and substr($mode, 1, 1) <= 6) {
                $mode = $mode + 10;
            }
            if (substr($mode, 2, 1) >= 2 and substr($mode, 2, 1) <= 6) {
                $mode = $mode + 1;
            }
        }
        return octdec($mode);
    }
    # Der server Vergibt die Rechte
    return false;
}
Example #29
0
public function __construct ($configs)
{
	parent::__construct($configs);

	if (!coren::depend('_path_normalizer_0'))
		throw new exception("Tool '_path_normalizer_0' missed.");

	if(isset($configs['lock_relax'])) $this->lock_relax = $configs['lock_relax'];
	if(isset($configs['lock_count'])) $this->lock_count = $configs['lock_count'];
	if(isset($configs['lock_sleep'])) $this->lock_sleep = $configs['lock_sleep'];

	if(isset($configs['chunk_size'])) $this->chunk_size = $configs['chunk_size'];
	$this->chink_size = (integer) $this->chunk_size;
	if ($this->chunk_size <= 0) $this->chunk_size = 1024;

	if(isset($configs['dir_path'    ])) $this->dir_path     = $configs['dir_path'    ];
	if(isset($configs['dir_absolute'])) $this->dir_absolute = $configs['dir_absolute'];
	if(isset($configs['dir_required'])) $this->dir_required = $configs['dir_required'];
	if(isset($configs['dir_automake'])) $this->dir_automake = $configs['dir_automake'];
	if(isset($configs['dir_umask'   ])) $this->dir_umask    = $configs['dir_umask'   ];
	$this->dir = _path_normalizer_0::normalize_dir($this->dir_path, $this->dir_absolute ? null : SITEPATH);
	if ($this->dir_automake && !file_exists($this->dir))
	{
		$old_umask = umask(octdec($this->dir_umask));
		mkdir($this->dir, 0777, true);
		umask($old_umask);
	}
	if ($this->dir_required && !is_dir($this->dir))
	{
		throw new exception("Required directory '{$this->dir}' does not exist.");
	}
}
Example #30
0
 /**
  * Returns the original value of the string (unenclosed by quotes).
  *
  * @return string
  */
 public function toValue()
 {
     $text = $this->getText();
     $quote_char = $text[0];
     $text = substr($text, 1, -1);
     if ($quote_char === '"') {
         $rules = array(preg_quote('\\\\') => '\\', preg_quote('\\n') => "\n", preg_quote('\\t') => "\t", preg_quote('\\"') => '"', preg_quote('\\$') => '$', preg_quote('\\r') => "\r", preg_quote('\\v') => "\v", preg_quote('\\f') => "\f", preg_quote('\\e') => "", '\\\\[0-7]{1,3}' => '__octal__', '\\\\x[0-9A-Fa-f]{1,2}' => '__hex__');
     } else {
         $rules = array(preg_quote('\\\\') => '\\', preg_quote("\\'") => "'");
     }
     $replacements = array_values($rules);
     $regex = '@(' . implode(')|(', array_keys($rules)) . ')@';
     return preg_replace_callback($regex, function ($matches) use($replacements) {
         // find the first non-empty element (but skipping $matches[0]) using a quick for loop
         for ($i = 1; '' === $matches[$i]; ++$i) {
         }
         $match = $matches[0];
         $replacement = $replacements[$i - 1];
         if ($replacement === '__octal__') {
             $replacement = chr(octdec(substr($match, 1)));
         } elseif ($replacement === '__hex__') {
             $replacement = chr(hexdec(substr($match, 2)));
         }
         return $replacement;
     }, $text);
 }