Example #1
1
 /**
  *
  */
 public function testChmod()
 {
     $cache = new FileAdapter(self::$dir, new NoneSerializer(), 0777);
     $cache->set('item', 'content');
     $perms = fileperms(self::$dir . '/' . md5('item'));
     $this->assertEquals('0777', substr(sprintf('%o', $perms), -4));
 }
 /**
  * Записать файл
  * @param $name
  * @param $content
  * @throws \Exception
  */
 public function writeFile($name, $content)
 {
     // Проыеряем, что название не пустое
     if (empty($name)) {
         return;
     }
     // Проверяем существование файла
     $file_path = $this->get('kernel')->getRootDir() . $this->web_dir . $name;
     if (!file_exists($file_path)) {
         try {
             touch($file_path);
         } catch (\Exception $e) {
             throw new \Exception('Не удалось создать файл ' . $name);
         }
     }
     // Проверяем права
     $file_perms = fileperms($file_path);
     if ($file_perms & 0777 !== 0666) {
         try {
             chmod($file_path, '0666');
         } catch (\Exception $e) {
             throw new \Exception('Не удалось отредактировать права на файл ' . $name);
         }
     }
     // Записываем содержимое
     try {
         file_put_contents($file_path, $content, LOCK_EX);
     } catch (\Exception $e) {
         throw new \Exception('Не удалось отредактировать файл ' . $name);
     }
 }
Example #3
0
 /**
  *	声明模板用法
  */
 function ETCoreStart($set = array('ID' => '1', 'TplType' => 'htm', 'CacheDir' => 'cache', 'TemplateDir' => 'template', 'AutoImage' => 'on', 'LangDir' => 'language', 'Language' => 'default', 'Copyright' => 'off', 'MemCache' => ''))
 {
     $this->TplID = (defined('TemplateID') ? TemplateID : ((int) @$set['ID'] <= 1 ? 1 : (int) $set['ID'])) . '_';
     $this->CacheDir = (defined('NewCache') ? NewCache : (trim($set['CacheDir']) != '' ? $set['CacheDir'] : 'cache')) . '/';
     $this->TemplateDir = (defined('NewTemplate') ? NewTemplate : (trim($set['TemplateDir']) != '' ? $set['TemplateDir'] : 'template')) . '/';
     $this->Ext = @$set['TplType'] != '' ? $set['TplType'] : 'htm';
     $this->AutoImage = @$set['AutoImage'] == 'off' ? 0 : 1;
     $this->Copyright = @$set['Copyright'] == 'off' ? 0 : 1;
     $this->Server = is_array($GLOBALS['_SERVER']) ? $GLOBALS['_SERVER'] : $_SERVER;
     $this->version = trim($_GET['EaseTemplateVer']) ? die('Ease Templae E3!') : '';
     //载入语言文件
     $this->LangDir = (defined('LangDir') ? LangDir : (@$set['LangDir'] != 'language' && @$set['LangDir'] ? $set['LangDir'] : 'language')) . '/';
     if (is_dir($this->LangDir)) {
         $this->Language = defined('Language') ? Language : ($set['Language'] != 'default' && $set['Language'] ? $set['Language'] : 'default');
         if (@is_file($this->LangDir . $this->Language . '.php')) {
             $lang = array();
             @(include_once $this->LangDir . $this->Language . '.php');
             $this->LangData = $lang;
         }
     } else {
         $this->Language = 'default';
     }
     //缓存目录检测以及运行模式
     if (@ereg(':', $set['MemCache'])) {
         $this->RunType = 'MemCache';
         $memset = explode(":", $set['MemCache']);
         $this->Emc = memcache_connect($memset[0], $memset[1]) or die("Could not connect!");
     } else {
         $this->RunType = @substr(@sprintf('%o', @fileperms($this->CacheDir)), -3) == 777 && is_dir($this->CacheDir) ? 'Cache' : 'Replace';
     }
     $CompileBasic = array('/(\\{\\s*|<!--\\s*)inc_php:([a-zA-Z0-9_\\[\\]\\.\\,\\/\\?\\=\\#\\:\\;\\-\\|\\^]{5,200})(\\s*\\}|\\s*-->)/eis', '/<!--\\s*DEL\\s*-->/is', '/<!--\\s*IF(\\[|\\()(.+?)(\\]|\\))\\s*-->/is', '/<!--\\s*ELSEIF(\\[|\\()(.+?)(\\]|\\))\\s*-->/is', '/<!--\\s*ELSE\\s*-->/is', '/<!--\\s*END\\s*-->/is', '/<!--\\s*([a-zA-Z0-9_\\$\\[\\]\'\\"]{2,60})\\s*(AS|as)\\s*(.+?)\\s*-->/', '/<!--\\s*while\\:\\s*(.+?)\\s*-->/is', '/(\\{\\s*|<!--\\s*)lang\\:(.+?)(\\s*\\}|\\s*-->)/eis', '/(\\{\\s*|<!--\\s*)row\\:(.+?)(\\s*\\}|\\s*-->)/eis', '/(\\{\\s*|<!--\\s*)color\\:\\s*([\\#0-9A-Za-z]+\\,[\\#0-9A-Za-z]+)(\\s*\\}|\\s*-->)/eis', '/(\\{\\s*|<!--\\s*)dir\\:([^\\{\\}]{1,100})(\\s*\\}|\\s*-->)/eis', '/(\\{\\s*|<!--\\s*)run\\:(\\}|\\s*-->)\\s*(.+?)\\s*(\\{|<!--\\s*)\\/run(\\s*\\}|\\s*-->)/is', '/(\\{\\s*|<!--\\s*)run\\:(.+?)(\\s*\\}|\\s*-->)/is', '/\\{([a-zA-Z0-9_\'\\"\\[\\]\\$]{1,100})\\}/');
     $this->Compile = is_array($this->Compile) ? array_merge($this->Compile, $CompileBasic) : $CompileBasic;
     $AnalysisBasic = array('$this->inc_php("\\2")', '";if($ET_Del==true){echo"', '";if(\\2){echo"', '";}elseif(\\2){echo"', '";}else{echo"', '";}echo"', '";\\$_i=0;foreach((array)\\1 AS \\3){\\$_i++;echo"', '";\\$_i=0;while(\\1){\\$_i++;echo"', '$this->lang("\\2")', '$this->Row("\\2")', '$this->Color("\\2")', '$this->Dirs("\\2")', '";\\3;echo"', '";\\2;echo"', '";echo \\$\\1;echo"');
     $this->Analysis = is_array($this->Analysis) ? array_merge($this->Analysis, $AnalysisBasic) : $AnalysisBasic;
 }
Example #4
0
 /**
  * Copies a file.
  *
  * If the target file is older than the origin file, it's always overwritten.
  * If the target file is newer, it is overwritten only when the
  * $overwriteNewerFiles option is set to true.
  *
  * @param string $originFile          The original filename
  * @param string $targetFile          The target filename
  * @param bool   $overwriteNewerFiles If true, target files newer than origin files are overwritten
  *
  * @throws FileNotFoundException When originFile doesn't exist
  * @throws IOException           When copy fails
  */
 public function copy($originFile, $targetFile, $overwriteNewerFiles = false)
 {
     if (stream_is_local($originFile) && !is_file($originFile)) {
         throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
     }
     $this->mkdir(dirname($targetFile));
     $doCopy = true;
     if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) {
         $doCopy = filemtime($originFile) > filemtime($targetFile);
     }
     if ($doCopy) {
         // https://bugs.php.net/bug.php?id=64634
         if (false === ($source = @fopen($originFile, 'r'))) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
         }
         // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
         if (false === ($target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true)))))) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
         }
         $bytesCopied = stream_copy_to_stream($source, $target);
         fclose($source);
         fclose($target);
         unset($source, $target);
         if (!is_file($targetFile)) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
         }
         // Like `cp`, preserve executable permission bits
         @chmod($targetFile, fileperms($targetFile) | fileperms($originFile) & 0111);
         if (stream_is_local($originFile) && $bytesCopied !== ($bytesOrigin = filesize($originFile))) {
             throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile);
         }
     }
 }
Example #5
0
 /**
  * Load properties from a given file properties
  * 
  * @param $file string The filename to scan
  * @param $contents boolean Load the contents
  * @param $loadId boolean Load id from database
  * @return boolean result
  */
 function loadFromFile($file, $contents = false, $loadId = false)
 {
     if (!JFile::exists($file) && !JFolder::exists($file . DS)) {
         return false;
     }
     $info = @stat($file);
     $this->scandate = $this->_db->getNullDate();
     $this->filename = basename($file);
     $this->fullpath = $file;
     $this->permission = fileperms($file) & 0777;
     $this->size = filesize($file);
     $ctime =& JFactory::getDate($info['ctime']);
     $mtime =& JFactory::getDate($info['mtime']);
     $this->ctime = $ctime->toMySQL();
     $this->mtime = $mtime->toMySQL();
     $this->uid = $info['uid'];
     $this->gid = $info['gid'];
     $this->type = '';
     if (is_file($file)) {
         $this->type = 'file';
         $this->hash_md = md5_file($file);
         if ($contents) {
             $f = new JD_File($file);
             $this->contents = $f->read();
         }
     } elseif (is_dir($file)) {
         $this->type = 'dir';
     }
     if ($loadId) {
         $this->_db->setQuery('SELECT id FROM #__jdefender_filesystem WHERE fullpath = ' . $this->fullpath . ' LIMIT 1');
         $this->id = $this->_db->loadResult();
     }
     return true;
 }
 /**
  * collect all fileinformations of given file and
  * save them to the global fileinformation array
  *
  * @param string $file
  * @return boolean is valid file?
  */
 protected function setFileInformations($file)
 {
     $this->fileInfo = array();
     // reset previously information to have a cleaned object
     $this->file = $file instanceof \TYPO3\CMS\Core\Resource\File ? $file : NULL;
     if (is_string($file) && !empty($file)) {
         $this->fileInfo = TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($file);
         $this->fileInfo['mtime'] = filemtime($file);
         $this->fileInfo['atime'] = fileatime($file);
         $this->fileInfo['owner'] = fileowner($file);
         $this->fileInfo['group'] = filegroup($file);
         $this->fileInfo['size'] = filesize($file);
         $this->fileInfo['type'] = filetype($file);
         $this->fileInfo['perms'] = fileperms($file);
         $this->fileInfo['is_dir'] = is_dir($file);
         $this->fileInfo['is_file'] = is_file($file);
         $this->fileInfo['is_link'] = is_link($file);
         $this->fileInfo['is_readable'] = is_readable($file);
         $this->fileInfo['is_uploaded'] = is_uploaded_file($file);
         $this->fileInfo['is_writeable'] = is_writeable($file);
     }
     if ($file instanceof \TYPO3\CMS\Core\Resource\File) {
         $pathInfo = \TYPO3\CMS\Core\Utility\PathUtility::pathinfo($file->getName());
         $this->fileInfo = array('file' => $file->getName(), 'filebody' => $file->getNameWithoutExtension(), 'fileext' => $file->getExtension(), 'realFileext' => $pathInfo['extension'], 'atime' => $file->getCreationTime(), 'mtime' => $file->getModificationTime(), 'owner' => '', 'group' => '', 'size' => $file->getSize(), 'type' => 'file', 'perms' => '', 'is_dir' => FALSE, 'is_file' => $file->getStorage()->getDriverType() === 'Local' ? is_file($file->getForLocalProcessing(FALSE)) : TRUE, 'is_link' => $file->getStorage()->getDriverType() === 'Local' ? is_link($file->getForLocalProcessing(FALSE)) : FALSE, 'is_readable' => TRUE, 'is_uploaded' => FALSE, 'is_writeable' => FALSE);
     }
     return $this->fileInfo !== array();
 }
Example #7
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);
 }
 private static function relocateShortcut()
 {
     $WshShell = new COM('WScript.Shell');
     $desktop = $WshShell->SpecialFolders('Desktop');
     $startmenu = $WshShell->SpecialFolders('Programs');
     $startmenu .= DIRECTORY_SEPARATOR . 'XAMPP for Windows';
     $links = array();
     $links[realpath($desktop . DIRECTORY_SEPARATOR . 'XAMPP Control Panel.lnk')] = array('TargetPath' => self::$xampppath . DIRECTORY_SEPARATOR . 'xampp-control.exe', 'WorkingDirectory' => self::$xampppath, 'WindowStyle' => 1, 'IconLocation' => self::$xampppath . DIRECTORY_SEPARATOR . 'xampp-control.exe', 'Description' => 'XAMPP Control Panel');
     $links[realpath($startmenu . DIRECTORY_SEPARATOR . 'XAMPP Control Panel.lnk')] = array('TargetPath' => self::$xampppath . DIRECTORY_SEPARATOR . 'xampp-control.exe', 'WorkingDirectory' => self::$xampppath, 'WindowStyle' => 1, 'IconLocation' => self::$xampppath . DIRECTORY_SEPARATOR . 'xampp-control.exe', 'Description' => 'XAMPP Control Panel');
     $links[realpath($startmenu . DIRECTORY_SEPARATOR . 'XAMPP Setup.lnk')] = array('TargetPath' => self::$xampppath . DIRECTORY_SEPARATOR . 'xampp_setup.bat', 'WorkingDirectory' => self::$xampppath, 'WindowStyle' => 1, 'IconLocation' => self::$xampppath . DIRECTORY_SEPARATOR . 'xampp_cli.exe', 'Description' => 'XAMPP Setup');
     $links[realpath($startmenu . DIRECTORY_SEPARATOR . 'XAMPP Shell.lnk')] = array('TargetPath' => self::$xampppath . DIRECTORY_SEPARATOR . 'xampp_shell.bat', 'WorkingDirectory' => self::$xampppath, 'WindowStyle' => 1, 'IconLocation' => self::$xampppath . DIRECTORY_SEPARATOR . 'xampp_cli.exe', 'Description' => 'XAMPP Shell');
     $links[realpath($startmenu . DIRECTORY_SEPARATOR . 'XAMPP Uninstall.lnk')] = array('TargetPath' => self::$xampppath . DIRECTORY_SEPARATOR . 'uninstall_xampp.bat', 'WorkingDirectory' => self::$xampppath, 'WindowStyle' => 1, 'IconLocation' => self::$xampppath . DIRECTORY_SEPARATOR . 'xampp_cli.exe', 'Description' => 'XAMPP Uninstall');
     foreach ($links as $shortcut => $value) {
         if (is_int($shortcut)) {
             continue;
         }
         $oldfileperm = fileperms($shortcut);
         if (!chmod($shortcut, 0666) && !is_writable($shortcut)) {
             throw new XAMPPException('File \'' . $shortcut . '\' is not writable.');
         }
         $ShellLink = $WshShell->CreateShortcut($shortcut);
         $ShellLink->TargetPath = $value['TargetPath'];
         $ShellLink->WorkingDirectory = $value['WorkingDirectory'];
         $ShellLink->WindowStyle = $value['WindowStyle'];
         $ShellLink->IconLocation = $value['IconLocation'];
         $ShellLink->Description = $value['Description'];
         $ShellLink->Save();
         $ShellLink = null;
         chmod($shortcut, $oldfileperm);
     }
     $WshShell = null;
     return;
 }
Example #9
0
 public function addHeader($size, $name)
 {
     $size = decoct($size);
     $info = stat($this->path);
     $uid = sprintf('%6s ', decoct($info[4]));
     $gid = sprintf('%6s ', decoct($info[5]));
     $mode = sprintf('%6s ', decoct(fileperms($this->path)));
     $mtime = sprintf('%11s', decoct(filemtime($this->path)));
     // Compute the "before" & "after" checksum chunks.
     $before = pack('a100a8a8a8a12A12', $name, $mode, $uid, $gid, $size, $mtime);
     $after = pack('a1a100a6a2a32a32a8a8a155a12', '', '', '', '', '', '', '', '', '', '');
     // Compute checksum
     $checksum = 0;
     for ($i = 0; $i < 148; $i++) {
         $checksum += ord(substr($before, $i, 1));
     }
     for ($i = 148; $i < 156; $i++) {
         $checksum += ord(' ');
     }
     for ($i = 156, $j = 0; $i < 512; $i++, $j++) {
         $checksum += ord(substr($after, $j, 1));
     }
     $checksum = sprintf('%6s ', decoct($checksum));
     $checksum = pack('a8', $checksum);
     $this->write($before . $checksum . $after);
 }
Example #10
0
 private function addFileInfo($filename)
 {
     $this->total[] = "#name:" . $filename . "\n";
     $this->total[] = "#perm:" . fileperms($filename) . "\n";
     $this->total[] = "#size:" . filesize($filename) . "\n";
     $this->total[] = "\n!#start#!\n";
 }
Example #11
0
function permission($filename)
{
    $perms = fileperms($filename);
    if (($perms & 0xc000) == 0xc000) {
        $info = 's';
    } elseif (($perms & 0xa000) == 0xa000) {
        $info = 'l';
    } elseif (($perms & 0x8000) == 0x8000) {
        $info = '-';
    } elseif (($perms & 0x6000) == 0x6000) {
        $info = 'b';
    } elseif (($perms & 0x4000) == 0x4000) {
        $info = 'd';
    } elseif (($perms & 0x2000) == 0x2000) {
        $info = 'c';
    } elseif (($perms & 0x1000) == 0x1000) {
        $info = 'p';
    } else {
        $info = 'u';
    }
    $info .= $perms & 0x100 ? 'r' : '-';
    $info .= $perms & 0x80 ? 'w' : '-';
    $info .= $perms & 0x40 ? $perms & 0x800 ? 's' : 'x' : ($perms & 0x800 ? 'S' : '-');
    $info .= $perms & 0x20 ? 'r' : '-';
    $info .= $perms & 0x10 ? 'w' : '-';
    $info .= $perms & 0x8 ? $perms & 0x400 ? 's' : 'x' : ($perms & 0x400 ? 'S' : '-');
    $info .= $perms & 0x4 ? 'r' : '-';
    $info .= $perms & 0x2 ? 'w' : '-';
    $info .= $perms & 0x1 ? $perms & 0x200 ? 't' : 'x' : ($perms & 0x200 ? 'T' : '-');
    return $info;
}
Example #12
0
function birth_setSave($arr, $modId)
{
    global $DMC, $DBPrefix;
    for ($i = 1; $i <= count($arr) / 3; $i++) {
        setPlugSet($modId, "birthTitle{$i}", $arr["birthTitle{$i}"]);
        setPlugSet($modId, "birthDate{$i}", $arr["birthDate{$i}"]);
        setPlugSet($modId, "textColor{$i}", $arr["textColor{$i}"]);
    }
    //Check file visit access
    $xmlFile = "../plugins/birth/birth.xml";
    $os = strtoupper(substr(PHP_OS, 0, 3));
    $fileAccess = intval(substr(sprintf('%o', fileperms($xmlFile)), -4));
    if ($fileAccess < 777 and $os != "WIN") {
        $ActionMessage = "<b><font color='red'>birth.xml => Please change the CHMOD as 777.</font></b>";
    } else {
        $filecontent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        $filecontent .= "<birth>\n";
        for ($i = 0; $i < count($arr) / 3; $i++) {
            $num = $i + 1;
            if ($arr["birthTitle{$num}"]) {
                $filecontent .= "\t<item>\n";
                $filecontent .= "\t\t<birthTitle>" . $arr["birthTitle{$num}"] . "</birthTitle>\n";
                $filecontent .= "\t\t<birthDate>" . $arr["birthDate{$num}"] . "</birthDate>\n";
                $filecontent .= "\t\t<textColor>" . $arr["textColor{$num}"] . "</textColor>\n";
                $filecontent .= "\t</item>\n";
            }
        }
        $filecontent .= "</birth>\n";
        $fp = fopen($xmlFile, "wb");
        @fwrite($fp, $filecontent);
        @fclose($fp);
        $ActionMessage = "";
    }
    return $ActionMessage;
}
 /**
  * @param string $type
  * @return KalturaTypeReflector
  */
 static function get($type)
 {
     if (!self::$_enabled) {
         return new KalturaTypeReflector($type);
     }
     if (!array_key_exists($type, self::$_loadedTypeReflectors)) {
         $cachedDir = KAutoloader::buildPath(kConf::get("cache_root_path"), "api_v3", "typeReflector");
         if (!is_dir($cachedDir)) {
             mkdir($cachedDir);
             chmod($cachedDir, 0755);
         }
         $cachedFilePath = $cachedDir . DIRECTORY_SEPARATOR . $type . ".cache";
         $typeReflector = null;
         if (file_exists($cachedFilePath)) {
             $cachedData = file_get_contents($cachedFilePath);
             $typeReflector = unserialize($cachedData);
         }
         if (!$typeReflector) {
             $typeReflector = new KalturaTypeReflector($type);
             $cachedData = serialize($typeReflector);
             $bytesWritten = kFile::safeFilePutContents($cachedFilePath, $cachedData);
             if (!$bytesWritten) {
                 $folderPermission = substr(decoct(fileperms(dirname($cachedFilePath))), 2);
                 error_log("Kaltura type reflector could not be saved to path [{$cachedFilePath}] type [{$type}] folder permisisons [{$folderPermission}]");
             }
         }
         self::$_loadedTypeReflectors[$type] = $typeReflector;
     }
     return self::$_loadedTypeReflectors[$type];
 }
Example #14
0
function nfo_setSave($arr, $modId)
{
    global $DMC, $DBPrefix;
    $fieldList = array("bgcolor", "txtcolor", "imgtype");
    for ($i = 0; $i < count($fieldList); $i++) {
        $name = $fieldList[$i];
        setPlugSet($modId, $name, $arr[$name]);
    }
    //Check file visit access
    $configFile = "../plugins/nfo/nfo_config.php";
    $os = strtoupper(substr(PHP_OS, 0, 3));
    $fileAccess = intval(substr(sprintf('%o', fileperms($configFile)), -4));
    if ($fileAccess < 777 and $os != "WIN") {
        $ActionMessage = "<b><font color='red'>nfo_config.php => Please change the CHMOD as 777.</font></b>";
    } else {
        $fp = @fopen($configFile, 'r');
        $filecontent = @fread($fp, @filesize($configFile));
        @fclose($fp);
        $filecontent = preg_replace("/[\$]imgtype\\s*\\=\\s*[\"'].*?[\"']/is", "\$imgtype = \"" . $arr['imgtype'] . "\"", $filecontent);
        $filecontent = preg_replace("/[\$]bgcolor\\s*\\=\\s*[\"'].*?[\"']/is", "\$bgcolor = \"" . $arr['bgcolor'] . "\"", $filecontent);
        $filecontent = preg_replace("/[\$]txtcolor\\s*\\=\\s*[\"'].*?[\"']/is", "\$txtcolor = \"" . $arr['txtcolor'] . "\"", $filecontent);
        $fp = @fopen($configFile, 'wbt');
        @fwrite($fp, trim($filecontent));
        @fclose($fp);
        $ActionMessage = "";
    }
    return $ActionMessage;
}
Example #15
0
 /**
  * Tests the recursively changing of filemodes.
  */
 public function testRecursiveChmod()
 {
     # Compile a directory name
     $dir = sys_get_temp_dir() . '/wadelib';
     # Delete directory from earlier runs:
     FileSystemManager::rrmdir($dir);
     # Create a directory
     $rc = mkdir($dir);
     # Create a bunch of subfiles
     $files = array();
     for ($i = 0; $i < 3; $i++) {
         $files[] = tempnam($dir, 'wl');
     }
     # Switch modes
     $newperm = 0777;
     $rc = WadeLib::changeFilemode($dir, $newperm, true);
     $this->assertEquals(true, $rc);
     # Clear file status cache.
     # Otherwise, during some testruns
     # problems may occur with invalid
     # file-permissions cached by PHP:
     clearstatcache();
     # Loop through created files to check filemode
     foreach ($files as $f) {
         $rc = fileperms($f);
         echo $f, PHP_EOL;
         printf('Expecting %s, got %s' . PHP_EOL, substr(sprintf('%o', $newperm), -4), substr(sprintf('%o', $rc), -4));
         $this->assertEquals(substr(sprintf('%o', $newperm), -4), substr(sprintf('%o', $rc), -4));
         # Unlink files
         unlink($f);
     }
 }
Example #16
0
/**
 * Checks permissions of files and directories.
 * @param sFileName - file's name.
 */
function checkPermissions($sFileName)
{
    $sPermissions = "";
    $sFilePath = trim($sFileName);
    clearstatcache();
    if (!file_exists($sFilePath)) {
        $sResult = "";
    } else {
        clearstatcache();
        $iPermissions = fileperms($sFilePath);
        for ($i = 0, $offset = 0; $i < 3; $i++, $offset += 3) {
            $iPerm = 0;
            for ($j = 0; $j < 3; $j++) {
                $iPermissions >> $j + $offset & 1 ? $iPerm += pow(2, $j) : "";
            }
            $sPermissions = $iPerm . $sPermissions;
        }
        $sResult = $sPermissions;
    }
    $sResult = "";
    $bDir = is_dir($sFilePath);
    if (is_readable($sFilePath)) {
        $sResult = $bDir ? "755" : "644";
    }
    if (is_writable($sFilePath)) {
        $sResult = $bDir ? "777" : "666";
    }
    if (!$bDir && is_executable($sFilePath)) {
        $sResult = "777";
    }
    return $sResult;
}
Example #17
0
 public function read($absolutePath, $relativePath, $sortName = 'filename', $sortOrder = SORT_ASC)
 {
     for ($list = array(), $handle = opendir($absolutePath); FALSE !== ($file = readdir($handle));) {
         if ($file != '.' && $file != '..' && $file != 'webint' && file_exists($path = $absolutePath . DIRECTORY_SEPARATOR . $file)) {
             $entry = array('filename' => $file, 'permission' => substr(sprintf('%o', fileperms($path)), -4));
             $entry['modtime'] = filemtime($path);
             do {
                 if (!is_dir($path)) {
                     $entry['size'] = filesize($path);
                     $entry['mode'] = 'file';
                     $entry['dirpath'] = $relativePath . DIRECTORY_SEPARATOR . $file;
                     break;
                 } else {
                     $entry['size'] = '';
                     $entry['mode'] = 'folder';
                     $entry['dirpath'] = urlencode($relativePath . DIRECTORY_SEPARATOR . $file);
                     break;
                 }
             } while (FALSE);
             $list[] = $entry;
         }
     }
     closedir($handle);
     $list = $this->sortArray($list, 'mode', 'desc', $sortName, $sortOrder);
     return $list;
 }
Example #18
0
function show_perms($file)
{
    $in_Perms = fileperms($file);
    $sP = "<b>";
    if ($in_Perms & 0x1000) {
        $sP .= 'p';
    } elseif ($in_Perms & 0x2000) {
        $sP .= 'c';
    } elseif ($in_Perms & 0x4000) {
        $sP .= 'd';
    } elseif ($in_Perms & 0x6000) {
        $sP .= 'b';
    } elseif ($in_Perms & 0x8000) {
        $sP .= '&minus;';
    } elseif ($in_Perms & 0xa000) {
        $sP .= 'l';
    } elseif ($in_Perms & 0xc000) {
        $sP .= 's';
    } else {
        $sP .= 'u';
    }
    // UNKNOWN
    $sP .= "</b>";
    // owner - group - others
    $sP .= ($in_Perms & 0x100 ? 'r' : '&minus;') . ($in_Perms & 0x80 ? 'w' : '&minus;') . ($in_Perms & 0x40 ? $in_Perms & 0x800 ? 's' : 'x' : ($in_Perms & 0x800 ? 'S' : '&minus;'));
    $sP .= ($in_Perms & 0x20 ? 'r' : '&minus;') . ($in_Perms & 0x10 ? 'w' : '&minus;') . ($in_Perms & 0x8 ? $in_Perms & 0x400 ? 's' : 'x' : ($in_Perms & 0x400 ? 'S' : '&minus;'));
    $sP .= ($in_Perms & 0x4 ? 'r' : '&minus;') . ($in_Perms & 0x2 ? 'w' : '&minus;') . ($in_Perms & 0x1 ? $in_Perms & 0x200 ? 't' : 'x' : ($in_Perms & 0x200 ? 'T' : '&minus;'));
    return $sP;
}
Example #19
0
 /**
  * Verify that the Unix permissions can be set.
  *
  * @covers \KHerGe\File\permissions
  */
 public function testSetUnixPermissions()
 {
     $file = tempnam(sys_get_temp_dir(), 'fm-');
     $permissions = 0777;
     self::assertEquals($permissions, permissions(__FILE__, $permissions), 'The Unix permissions were not returned.');
     self::assertNotEquals($permissions, fileperms($file) & $permissions, 'The Unix permissions were not set.');
 }
 /**
  * Wraps copy and is able to copy directories
  * @param string $from Source location
  * @param string $to   Target location
  * @throws \Exception
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @return bool
  */
 public function copy($from, $to)
 {
     if ($this->isFile($from)) {
         if (@copy($from, $to)) {
             return true;
         }
         throw new \Exception("Could not copy file '{$from}' to '{$to}'");
     }
     if ($this->isDirectory($from)) {
         $returnValue = true;
         // Does the "to" directory need to be created
         $makingDirectory = !$this->isDirectory($to);
         if ($makingDirectory) {
             if (!$this->makeDirectory($to, 0777, true)) {
                 throw new \Exception("Could not create directory '{$to}'");
             }
         }
         // Step through the directory
         $fromDirectory = opendir($from);
         while (false !== ($file = readdir($fromDirectory))) {
             if ($file != '.' && $file != '..') {
                 $returnValue = $returnValue && $this->copy("{$from}/{$file}", "{$to}/{$file}");
             }
         }
         closedir($fromDirectory);
         // Fix permissions
         if ($makingDirectory) {
             $returnValue = $returnValue && $this->changeMode($to, fileperms($from));
         }
         return $returnValue;
     }
     throw new \Exception("'{$from}' does not exist or is not accessible");
 }
Example #21
0
 /**
  * Copy all files recursively from source to destination
  *
  * @param  string $source
  * @param  string $dest
  * @return boolean
  */
 public static function copyFiles($source, $dest)
 {
     if (!file_exists($source)) {
         return false;
     }
     if (!file_exists($dest)) {
         mkdir($dest);
     }
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
     foreach ($iterator as $item) {
         $destName = $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName();
         if ($item->isDir()) {
             if (!file_exists($destName)) {
                 if (!@mkdir($destName)) {
                     return false;
                 }
             }
         } else {
             if (!@copy($item, $destName)) {
                 return false;
             }
             chmod($destName, fileperms($item));
         }
     }
     return true;
 }
function folderPermissions($folder)
{
    global $chmod, $f;
    $curdir = getcwd();
    chdir($folder);
    $files = safe_glob('*.*');
    chdir($curdir);
    foreach ($files as $file) {
        $path = $folder . '/' . $file;
        if (is_dir($path)) {
            if ($file != '.' && $file != '..') {
                @chmod($path, $chmod);
                clearstatcache();
                if ((fileperms($path) & 0777) == $chmod) {
                    if (!folderPermissions($path)) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        } else {
            @chmod($path, 0666 & $chmod);
            clearstatcache();
            if ((fileperms($path) & 0777) != (0666 & $chmod)) {
                return false;
            }
        }
    }
    return true;
}
Example #23
0
 /**
  * Test local directory handling functions.
  */
 function testFileCheckLocalDirectoryHandling()
 {
     $site_path = $this->container->get('site.path');
     $directory = $site_path . '/files';
     // Check a new recursively created local directory for correct file system
     // permissions.
     $parent = $this->randomMachineName();
     $child = $this->randomMachineName();
     // Files directory already exists.
     $this->assertTrue(is_dir($directory), t('Files directory already exists.'), 'File');
     // Make files directory writable only.
     $old_mode = fileperms($directory);
     // Create the directories.
     $parent_path = $directory . DIRECTORY_SEPARATOR . $parent;
     $child_path = $parent_path . DIRECTORY_SEPARATOR . $child;
     $this->assertTrue(drupal_mkdir($child_path, 0775, TRUE), t('No error reported when creating new local directories.'), 'File');
     // Ensure new directories also exist.
     $this->assertTrue(is_dir($parent_path), t('New parent directory actually exists.'), 'File');
     $this->assertTrue(is_dir($child_path), t('New child directory actually exists.'), 'File');
     // Check that new directory permissions were set properly.
     $this->assertDirectoryPermissions($parent_path, 0775);
     $this->assertDirectoryPermissions($child_path, 0775);
     // Check that existing directory permissions were not modified.
     $this->assertDirectoryPermissions($directory, $old_mode);
     // Check creating a directory using an absolute path.
     $absolute_path = drupal_realpath($directory) . DIRECTORY_SEPARATOR . $this->randomMachineName() . DIRECTORY_SEPARATOR . $this->randomMachineName();
     $this->assertTrue(drupal_mkdir($absolute_path, 0775, TRUE), 'No error reported when creating new absolute directories.', 'File');
     $this->assertDirectoryPermissions($absolute_path, 0775);
 }
Example #24
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 #25
0
 /**
  * Class process method which is used to execute this component.
  */
 public function process()
 {
     if (substr(decoct(fileperms('./file/achievements/')), 1) != "0777") {
         $this->template()->assign(array('bError' => true))->setTitle('Konsort.org Achievements')->setBreadcrumb('Konsort.org Achievements')->setHeader('cache', array('pager.css' => 'style_css'));
     } else {
         if ($this->request()->get('setHighest', false)) {
             if (Phpfox::getService('achievements.process')->setHighest($this->request()->get('id', 0), $this->request()->get('category', 0))) {
                 $this->url()->send('admincp.achievements.list', null, 'Successfully made the selected acheivement the highest achievement for the category.');
             } else {
                 $this->url()->send('admincp.achievements.list', null, 'There was an error processing your request');
             }
         } elseif ($this->request()->get('unsetHighest', false)) {
             if (Phpfox::getService('achievements.process')->unsetHighest($this->request()->get('id', 0), $this->request()->get('category', 0))) {
                 $this->url()->send('admincp.achievements.list', null, 'Successfully unmade the selected acheivement the highest achievement for the category.');
             } else {
                 $this->url()->send('admincp.achievements.list', null, 'There was an error processing your request');
             }
         }
         $sLimit = 10;
         $iPage = $this->request()->get('page', 0);
         if ($iPage > 0) {
             $iPage--;
         }
         list($iCnt, $aAchievements) = Phpfox::getService('achievements')->getList($iPage, $sLimit);
         Phpfox::getLib('pager')->set(array('page' => $iPage + 1, 'size' => $sLimit, 'count' => $iCnt));
         $this->template()->assign(array('bError' => false, 'iCnt' => $iCnt, 'aAchievements' => $aAchievements))->setTitle('Konsort.org Achievements')->setBreadcrumb('Konsort.org Achievements')->setHeader('cache', array('pager.css' => 'style_css'));
     }
 }
Example #26
0
 public function set_file_path($dir)
 {
     $dir = rtrim($dir, '/') . '/';
     if (is_file($dir)) {
         log_message('debug', 'Qrcode: Set File Path to a file.');
     } else {
         if (!is_dir($dir)) {
             $parent_dir = $dir;
             do {
                 $parent_dir = dirname($parent_dir);
             } while (!is_dir($parent_dir));
             $perms = '0' . substr(sprintf('%o', fileperms($parent_dir)), -3);
             if (@mkdir($dir, $perms, TRUE)) {
                 @chmod($dir, $perms);
             } else {
                 log_message('debug', 'Qrcode: Can not make new dir.');
             }
         }
         if (!is_dir($dir) || !is_really_writable($dir)) {
             log_message('debug', 'Qrcode: Set to a unwritable dir.');
         } else {
             $this->_dir_path = $dir;
         }
     }
     return $this;
 }
Example #27
0
 /**
  * __construct - Prepares a file for upload
  * 
  * @param string $name The form name value to post
  * @param string $directory The directory to save to
  * @param string $required Is this file required
  * @param string $saveAs (Default: false) Set a name to save it as a custom name (Extension will be automatically added)
  * 
  * @return boolean
  * 
  * @throws \Exception 
  */
 public function __construct($name, $directory, $saveAs = false, $overwrite = true)
 {
     /**
      * Set the class-wide properties 
      */
     $this->_name = $name;
     $this->_directory = trim($directory, '/') . '/';
     $this->_saveAs = $saveAs == true ? $saveAs : $name;
     $this->_overwrite = $overwrite;
     /**
      * Make sure the pathSave is a directory
      */
     if (!is_dir($this->_directory)) {
         throw new \Exception("must be a directory: {$this->_directory}");
     }
     /**
      * Get the octal permission of the directory, eg: 0777
      * Note: This turns the permission into a (string)
      */
     $writable = substr(sprintf('%o', fileperms($this->_directory)), -4);
     if ($writable != "0777") {
         throw new \Exception("directory is not writable: {$this->_directory}");
     }
     if ($overwrite == false && file_exists($this->_directory . $this->_saveAs)) {
         throw new \Exception("file already exists and cannot be overwritten: {$this->_directory}{$this->_saveAs}");
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function failureDescription($other)
 {
     if (!is_string($other)) {
         if (is_object($other)) {
             $type = sprintf('%s#%s', get_class($other), method_exists($other, '__toString') ? $other->__toString() : '');
         } elseif (null === $other) {
             $type = 'null';
         } else {
             $type = gettype($other) . '#' . $other;
         }
         return $type . ' ' . $this->toString();
     }
     if (!file_exists($other)) {
         return 'not file or directory#' . $other . ' ' . $this->toString();
     }
     if (is_link($other)) {
         $type = 'link';
         $perms = lstat($other);
         $perms = $perms['mode'];
     } else {
         $type = is_file($other) ? 'file' : (is_dir($other) ? 'directory' : 'other');
         $perms = fileperms($other);
     }
     return sprintf('%s#%s %o %s %o', $type, $other, $perms, $this->toString(), $this->mask);
 }
Example #29
0
function check_perms($filename)
{
    global $strPermissionInvalide;
    if (!file_exists($filename)) {
        return false;
    }
    $fileperms = fileperms($filename);
    $isreadable = $fileperms & 4;
    if (is_file($filename)) {
        // pictures, thumbnails, config files and comments only need to be readable
        if (!$isreadable) {
            show_warning("{$strPermissionInvalide} : {$filename}");
        }
        return $isreadable;
    } elseif (is_dir($filename)) {
        // galleries need to be both readable and executable
        $isexecutable = $fileperms & 1;
        if (!$isreadable || !$isexecutable) {
            show_warning("{$strPermissionInvalide} : {$filename}");
        }
        return $isreadable && $isexecutable;
        // ($dirperms & 5) == 5 ?
    }
    // default behavior: the filename does not exist
    return false;
}
 public static function addPhpCsToPreCommitHook(Event $event)
 {
     $extra = $event->getComposer()->getPackage()->getExtra();
     $dependencyToResolve = self::arrayResolvePath("codesniffer:standard:dependency", $extra);
     if (is_null($dependencyToResolve)) {
         $event->getIO()->writeError("Cannot install pre-commit hooks. No CodeSniffer standard configured at extra->codesniffer->standard.");
         return;
     }
     if (is_array($dependencyToResolve)) {
         $event->getIO()->writeError("Cannot install pre-commit hooks. Configuration of extra->codesniffer->standard->dependency is invalid.");
         return;
     }
     $originFile = getcwd() . '/.git/hooks/pre-commit';
     if (!is_dir(dirname($originFile))) {
         mkdir(dirname($originFile), 0777, true);
     }
     $templateContent = file_get_contents(__DIR__ . '/templates/git/hooks/pre-commit-phpcs');
     $originContent = '';
     if (file_exists($originFile)) {
         $originContent = file_get_contents($originFile);
     }
     if (strpos($originContent, '# BEGIN:metasyntactical/composer-codesniffer-hooks') !== false) {
         return;
     }
     $newContent = $originContent;
     if (mb_strlen($originContent)) {
         $newContent .= "\n";
     }
     $newContent .= str_replace(array("{STANDARDPATH}"), array($event->getComposer()->getConfig()->get("vendor-dir", Config::RELATIVE_PATHS) . "/{$dependencyToResolve}/ruleset.xml"), $templateContent);
     file_put_contents($originFile, $newContent);
     $perms = fileperms($originFile);
     chmod($originFile, $perms | 0x40 | 0x8 | 0x1);
     clearstatcache(null, $originFile);
 }