Refactor PHP files.

This commit is contained in:
Lars Jung 2014-09-06 01:02:38 +02:00
parent 6cd3cf0cb5
commit 9bbee262f9
12 changed files with 773 additions and 333 deletions

View file

@ -16,8 +16,8 @@ class Api {
public function apply() {
$action = use_request_param("action");
json_fail(100, "unsupported request", !in_array($action, $this->actions));
$action = Util::use_request_param("action");
Util::json_fail(100, "unsupported request", !in_array($action, $this->actions));
$methodname = "on_${action}";
$this->$methodname();
@ -26,16 +26,16 @@ class Api {
private function on_login() {
$pass = use_request_param("pass");
$pass = Util::use_request_param("pass");
$_SESSION[AS_ADMIN_SESSION_KEY] = sha1($pass) === PASSHASH;
json_exit(array("as_admin" => $_SESSION[AS_ADMIN_SESSION_KEY]));
Util::json_exit(array("as_admin" => $_SESSION[AS_ADMIN_SESSION_KEY]));
}
private function on_logout() {
$_SESSION[AS_ADMIN_SESSION_KEY] = false;
json_exit(array("as_admin" => $_SESSION[AS_ADMIN_SESSION_KEY]));
Util::json_exit(array("as_admin" => $_SESSION[AS_ADMIN_SESSION_KEY]));
}
@ -43,63 +43,63 @@ class Api {
$response = array();
if (has_request_param("setup")) {
if (Util::has_request_param("setup")) {
use_request_param("setup");
Util::use_request_param("setup");
$response["setup"] = $this->app->get_setup();
}
if (has_request_param("options")) {
if (Util::has_request_param("options")) {
use_request_param("options");
Util::use_request_param("options");
$response["options"] = $this->app->get_options();
}
if (has_request_param("types")) {
if (Util::has_request_param("types")) {
use_request_param("types");
Util::use_request_param("types");
$response["types"] = $this->app->get_types();
}
if (has_request_param("theme")) {
if (Util::has_request_param("theme")) {
use_request_param("theme");
Util::use_request_param("theme");
$response["theme"] = $this->app->get_theme();
}
if (has_request_param("langs")) {
if (Util::has_request_param("langs")) {
use_request_param("langs");
Util::use_request_param("langs");
$response["langs"] = $this->app->get_l10n_list();
}
if (has_request_param("l10n")) {
if (Util::has_request_param("l10n")) {
use_request_param("l10n");
$iso_codes = use_request_param("l10nCodes");
Util::use_request_param("l10n");
$iso_codes = Util::use_request_param("l10nCodes");
$iso_codes = explode(":", $iso_codes);
$response["l10n"] = $this->app->get_l10n($iso_codes);
}
if (has_request_param("custom")) {
if (Util::has_request_param("custom")) {
use_request_param("custom");
$url = use_request_param("customHref");
Util::use_request_param("custom");
$url = Util::use_request_param("customHref");
$response["custom"] = $this->app->get_customizations($url);
}
if (has_request_param("items")) {
if (Util::has_request_param("items")) {
use_request_param("items");
$url = use_request_param("itemsHref");
$what = use_request_param("itemsWhat");
Util::use_request_param("items");
$url = Util::use_request_param("itemsHref");
$what = Util::use_request_param("itemsWhat");
$what = is_numeric($what) ? intval($what, 10) : 1;
$response["items"] = $this->app->get_items($url, $what);
}
if (has_request_param("all_items")) {
if (Util::has_request_param("all_items")) {
use_request_param("all_items");
Util::use_request_param("all_items");
$response["all_items"] = $this->app->get_all_items();
}
@ -107,36 +107,36 @@ class Api {
$response["unused"] = $_REQUEST;
}
json_exit($response);
Util::json_exit($response);
}
private function on_getThumbHref() {
json_fail(1, "thumbnails disabled", !$this->options["thumbnails"]["enabled"]);
json_fail(2, "thumbnails not supported", !HAS_PHP_JPG);
Util::json_fail(1, "thumbnails disabled", !$this->options["thumbnails"]["enabled"]);
Util::json_fail(2, "thumbnails not supported", !HAS_PHP_JPG);
$type = use_request_param("type");
$src_url = use_request_param("href");
$mode = use_request_param("mode");
$width = use_request_param("width");
$height = use_request_param("height");
$type = Util::use_request_param("type");
$src_url = Util::use_request_param("href");
$mode = Util::use_request_param("mode");
$width = Util::use_request_param("width");
$height = Util::use_request_param("height");
$thumb = new Thumb($this->app);
$thumb_url = $thumb->thumb($type, $src_url, $mode, $width, $height);
json_fail(3, "thumbnail creation failed", $thumb_url === null);
Util::json_fail(3, "thumbnail creation failed", $thumb_url === null);
json_exit(array("absHref" => $thumb_url));
Util::json_exit(array("absHref" => $thumb_url));
}
private function on_download() {
json_fail(1, "downloads disabled", !$this->options["download"]["enabled"]);
Util::json_fail(1, "downloads disabled", !$this->options["download"]["enabled"]);
$as = use_request_param("as");
$type = use_request_param("type");
$hrefs = use_request_param("hrefs");
$as = Util::use_request_param("as");
$type = Util::use_request_param("type");
$hrefs = Util::use_request_param("hrefs");
$archive = new Archive($this->app);
@ -148,7 +148,7 @@ class Api {
header("Connection: close");
$rc = $archive->output($type, $hrefs);
json_fail(2, "packaging failed", $rc !== 0);
Util::json_fail(2, "packaging failed", $rc !== 0);
exit;
}
}

View file

@ -12,7 +12,7 @@ class App {
public function __construct() {
$this->options = load_commented_json(APP_PATH . "/conf/options.json");
$this->options = Util::load_commented_json(APP_PATH . "/conf/options.json");
}
@ -47,7 +47,7 @@ class App {
public function get_types() {
return load_commented_json(APP_PATH . "/conf/types.json");
return Util::load_commented_json(APP_PATH . "/conf/types.json");
}
@ -85,14 +85,14 @@ class App {
}
}
return normalize_path(ROOT_HREF . implode("/", $encoded_parts), $trailing_slash);
return Util::normalize_path(ROOT_HREF . implode("/", $encoded_parts), $trailing_slash);
}
public function to_path($url) {
$rel_url = substr($url, strlen(ROOT_HREF));
return normalize_path(ROOT_PATH . "/" . rawurldecode($rel_url));
return Util::normalize_path(ROOT_PATH . "/" . rawurldecode($rel_url));
}
@ -158,7 +158,7 @@ class App {
if (@is_dir($path . "/_h5ai/server")) {
return false;
}
$parent_path = normalize_path(dirname($path));
$parent_path = Util::normalize_path(dirname($path));
if ($parent_path === $path) {
return false;
}
@ -303,8 +303,8 @@ class App {
if (is_dir($l10n_path)) {
if ($dir = opendir($l10n_path)) {
while (($file = readdir($dir)) !== false) {
if (ends_with($file, ".json")) {
$translations = load_commented_json($l10n_path . "/" . $file);
if (Util::ends_with($file, ".json")) {
$translations = Util::load_commented_json($l10n_path . "/" . $file);
$langs[basename($file, ".json")] = $translations["lang"];
}
}
@ -326,7 +326,7 @@ class App {
foreach ($iso_codes as $iso_code) {
if ($iso_code !== "") {
$file = APP_PATH . "/conf/l10n/" . $iso_code . ".json";
$results[$iso_code] = load_commented_json($file);
$results[$iso_code] = Util::load_commented_json($file);
$results[$iso_code]["isoCode"] = $iso_code;
}
}
@ -381,7 +381,7 @@ class App {
if ($path === ROOT_PATH) {
break;
}
$parent_path = normalize_path(dirname($path));
$parent_path = Util::normalize_path(dirname($path));
if ($parent_path === $path) {
break;
}

View file

@ -52,7 +52,7 @@ class Archive {
$cmd = str_replace("[DIRS]", count($this->dirs) ? implode(" ", array_map("escapeshellarg", $this->dirs)) : "", $cmd);
$cmd = str_replace("[FILES]", count($this->files) ? implode(" ", array_map("escapeshellarg", $this->files)) : "", $cmd);
try {
passthru_cmd($cmd);
Util::passthru_cmd($cmd);
} catch (Exeption $err) {
return 500;
}
@ -100,7 +100,7 @@ class Archive {
private function php_tar_header($filename, $size, $mtime, $type) {
$name = substr(basename($filename), -99);
$prefix = substr(normalize_path(dirname($filename)), -154);
$prefix = substr(Util::normalize_path(dirname($filename)), -154);
if ($prefix === '.') {
$prefix = '';
}
@ -153,13 +153,13 @@ class Archive {
continue;
}
$d = normalize_path(dirname($href), true);
$d = Util::normalize_path(dirname($href), true);
$n = basename($href);
if ($this->app->is_managed_url($d) && !$this->app->is_hidden($n)) {
$real_file = $this->app->to_path($href);
$archived_file = preg_replace("!^" . preg_quote(normalize_path(CURRENT_PATH, true)) . "!", "", $real_file);
$archived_file = preg_replace("!^" . preg_quote(Util::normalize_path(CURRENT_PATH, true)) . "!", "", $real_file);
if (is_dir($real_file)) {
$this->add_dir($real_file, $archived_file);

View file

@ -0,0 +1,446 @@
<?php
/**
* Copyright 2010-2013 Craig Campbell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Server Side Chrome PHP debugger class
*
* @package ChromePhp
* @author Craig Campbell <iamcraigcampbell@gmail.com>
*/
class ChromePhp
{
/**
* @var string
*/
const VERSION = '4.1.0';
/**
* @var string
*/
const HEADER_NAME = 'X-ChromeLogger-Data';
/**
* @var string
*/
const BACKTRACE_LEVEL = 'backtrace_level';
/**
* @var string
*/
const LOG = 'log';
/**
* @var string
*/
const WARN = 'warn';
/**
* @var string
*/
const ERROR = 'error';
/**
* @var string
*/
const GROUP = 'group';
/**
* @var string
*/
const INFO = 'info';
/**
* @var string
*/
const GROUP_END = 'groupEnd';
/**
* @var string
*/
const GROUP_COLLAPSED = 'groupCollapsed';
/**
* @var string
*/
const TABLE = 'table';
/**
* @var string
*/
protected $_php_version;
/**
* @var int
*/
protected $_timestamp;
/**
* @var array
*/
protected $_json = array(
'version' => self::VERSION,
'columns' => array('log', 'backtrace', 'type'),
'rows' => array()
);
/**
* @var array
*/
protected $_backtraces = array();
/**
* @var bool
*/
protected $_error_triggered = false;
/**
* @var array
*/
protected $_settings = array(
self::BACKTRACE_LEVEL => 1
);
/**
* @var ChromePhp
*/
protected static $_instance;
/**
* Prevent recursion when working with objects referring to each other
*
* @var array
*/
protected $_processed = array();
/**
* constructor
*/
private function __construct()
{
$this->_php_version = phpversion();
$this->_timestamp = $this->_php_version >= 5.1 ? $_SERVER['REQUEST_TIME'] : time();
$this->_json['request_uri'] = $_SERVER['REQUEST_URI'];
}
/**
* gets instance of this class
*
* @return ChromePhp
*/
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* logs a variable to the console
*
* @param mixed $data,... unlimited OPTIONAL number of additional logs [...]
* @return void
*/
public static function log()
{
$args = func_get_args();
return self::_log('', $args);
}
/**
* logs a warning to the console
*
* @param mixed $data,... unlimited OPTIONAL number of additional logs [...]
* @return void
*/
public static function warn()
{
$args = func_get_args();
return self::_log(self::WARN, $args);
}
/**
* logs an error to the console
*
* @param mixed $data,... unlimited OPTIONAL number of additional logs [...]
* @return void
*/
public static function error()
{
$args = func_get_args();
return self::_log(self::ERROR, $args);
}
/**
* sends a group log
*
* @param string value
*/
public static function group()
{
$args = func_get_args();
return self::_log(self::GROUP, $args);
}
/**
* sends an info log
*
* @param mixed $data,... unlimited OPTIONAL number of additional logs [...]
* @return void
*/
public static function info()
{
$args = func_get_args();
return self::_log(self::INFO, $args);
}
/**
* sends a collapsed group log
*
* @param string value
*/
public static function groupCollapsed()
{
$args = func_get_args();
return self::_log(self::GROUP_COLLAPSED, $args);
}
/**
* ends a group log
*
* @param string value
*/
public static function groupEnd()
{
$args = func_get_args();
return self::_log(self::GROUP_END, $args);
}
/**
* sends a table log
*
* @param string value
*/
public static function table()
{
$args = func_get_args();
return self::_log(self::TABLE, $args);
}
/**
* internal logging call
*
* @param string $type
* @return void
*/
protected static function _log($type, array $args)
{
// nothing passed in, don't do anything
if (count($args) == 0 && $type != self::GROUP_END) {
return;
}
$logger = self::getInstance();
$logger->_processed = array();
$logs = array();
foreach ($args as $arg) {
$logs[] = $logger->_convert($arg);
}
$backtrace = debug_backtrace(false);
$level = $logger->getSetting(self::BACKTRACE_LEVEL);
$backtrace_message = 'unknown';
if (isset($backtrace[$level]['file']) && isset($backtrace[$level]['line'])) {
$backtrace_message = $backtrace[$level]['file'] . ' : ' . $backtrace[$level]['line'];
}
$logger->_addRow($logs, $backtrace_message, $type);
}
/**
* converts an object to a better format for logging
*
* @param Object
* @return array
*/
protected function _convert($object)
{
// if this isn't an object then just return it
if (!is_object($object)) {
return $object;
}
//Mark this object as processed so we don't convert it twice and it
//Also avoid recursion when objects refer to each other
$this->_processed[] = $object;
$object_as_array = array();
// first add the class name
$object_as_array['___class_name'] = get_class($object);
// loop through object vars
$object_vars = get_object_vars($object);
foreach ($object_vars as $key => $value) {
// same instance as parent object
if ($value === $object || in_array($value, $this->_processed, true)) {
$value = 'recursion - parent object [' . get_class($value) . ']';
}
$object_as_array[$key] = $this->_convert($value);
}
$reflection = new ReflectionClass($object);
// loop through the properties and add those
foreach ($reflection->getProperties() as $property) {
// if one of these properties was already added above then ignore it
if (array_key_exists($property->getName(), $object_vars)) {
continue;
}
$type = $this->_getPropertyKey($property);
if ($this->_php_version >= 5.3) {
$property->setAccessible(true);
}
try {
$value = $property->getValue($object);
} catch (ReflectionException $e) {
$value = 'only PHP 5.3 can access private/protected properties';
}
// same instance as parent object
if ($value === $object || in_array($value, $this->_processed, true)) {
$value = 'recursion - parent object [' . get_class($value) . ']';
}
$object_as_array[$type] = $this->_convert($value);
}
return $object_as_array;
}
/**
* takes a reflection property and returns a nicely formatted key of the property name
*
* @param ReflectionProperty
* @return string
*/
protected function _getPropertyKey(ReflectionProperty $property)
{
$static = $property->isStatic() ? ' static' : '';
if ($property->isPublic()) {
return 'public' . $static . ' ' . $property->getName();
}
if ($property->isProtected()) {
return 'protected' . $static . ' ' . $property->getName();
}
if ($property->isPrivate()) {
return 'private' . $static . ' ' . $property->getName();
}
}
/**
* adds a value to the data array
*
* @var mixed
* @return void
*/
protected function _addRow(array $logs, $backtrace, $type)
{
// if this is logged on the same line for example in a loop, set it to null to save space
if (in_array($backtrace, $this->_backtraces)) {
$backtrace = null;
}
// for group, groupEnd, and groupCollapsed
// take out the backtrace since it is not useful
if ($type == self::GROUP || $type == self::GROUP_END || $type == self::GROUP_COLLAPSED) {
$backtrace = null;
}
if ($backtrace !== null) {
$this->_backtraces[] = $backtrace;
}
$row = array($logs, $backtrace, $type);
$this->_json['rows'][] = $row;
$this->_writeHeader($this->_json);
}
protected function _writeHeader($data)
{
header(self::HEADER_NAME . ': ' . $this->_encode($data));
}
/**
* encodes the data to be sent along with the request
*
* @param array $data
* @return string
*/
protected function _encode($data)
{
return base64_encode(utf8_encode(json_encode($data)));
}
/**
* adds a setting
*
* @param string key
* @param mixed value
* @return void
*/
public function addSetting($key, $value)
{
$this->_settings[$key] = $value;
}
/**
* add ability to set multiple settings in one call
*
* @param array $settings
* @return void
*/
public function addSettings(array $settings)
{
foreach ($settings as $key => $value) {
$this->addSetting($key, $value);
}
}
/**
* gets a setting
*
* @param string key
* @return mixed
*/
public function getSetting($key)
{
if (!isset($this->_settings[$key])) {
return null;
}
return $this->_settings[$key];
}
}

View file

@ -62,7 +62,7 @@ class Item {
if ($options["foldersize"]["enabled"]) {
if (HAS_CMD_DU && $options["foldersize"]["type"] === "shell-du") {
$cmdv = array("du", "-sk", $path);
$size = intval(preg_replace("#\s.*$#", "", exec_cmdv($cmdv)), 10) * 1024;
$size = intval(preg_replace("#\s.*$#", "", Util::exec_cmdv($cmdv)), 10) * 1024;
} else {
$size = 0;
foreach ($app->read_dir($path) as $name) {
@ -79,8 +79,7 @@ class Item {
public static function get($app, $path, &$cache) {
if (!starts_with($path, ROOT_PATH)) {
err_log("ILLEGAL REQUEST: " . $path . ", " . ROOT_PATH);
if (!Util::starts_with($path, ROOT_PATH)) {
return null;
}
@ -108,7 +107,7 @@ class Item {
$this->app = $app;
$this->path = normalize_path($path, false);
$this->path = Util::normalize_path($path, false);
$this->is_folder = is_dir($this->path);
$this->url = $app->to_url($this->path, $this->is_folder);
$this->date = @filemtime($this->path);
@ -151,8 +150,8 @@ class Item {
public function get_parent(&$cache) {
$parent_path = normalize_path(dirname($this->path), false);
if ($parent_path !== $this->path && starts_with($parent_path, ROOT_PATH)) {
$parent_path = Util::normalize_path(dirname($this->path), false);
if ($parent_path !== $this->path && Util::starts_with($parent_path, ROOT_PATH)) {
return Item::get($this->app, $parent_path, $cache);
}
return null;

View file

@ -0,0 +1,32 @@
<?php
class Logger {
private static $start;
private static $prev;
public static function init() {
self::$start = self::time();
self::$prev = self::$start;
register_shutdown_function(function () { Logger::log('shutdown'); });
Logger::log('--------------------------------');
}
private static function time() {
return microtime(true) * 1000; // sec * 1000 = ms
}
public static function log($message=null, $obj=null) {
$now = self::time();
$message = number_format($now - self::$start, 3) . " " . number_format($now - self::$prev, 3) . " " . $message;
@error_log($message . " " . var_export($obj, true));
@ChromePhp::log($message, $obj);
self::$prev = $now;
}
}
Logger::init();

View file

@ -0,0 +1,110 @@
<?php
class Setup {
public static function init() {
// MISC
putenv("LANG=en_US.UTF-8");
setlocale(LC_CTYPE, "en_US.UTF-8");
date_default_timezone_set("UTC");
define("NAME", "{{pkg.name}}");
define("VERSION", "{{pkg.version}}");
define("BACKEND", "PHP");
define("API", true);
define("FILE_PREFIX", "_{{pkg.name}}");
// ADMIN
session_start();
define("AS_ADMIN_SESSION_KEY", "__H5AI_AS_ADMIN__");
define("AS_ADMIN", isset($_SESSION[AS_ADMIN_SESSION_KEY]) && $_SESSION[AS_ADMIN_SESSION_KEY] === true);
define("HAS_CUSTOM_PASSHASH", PASSHASH !== "da39a3ee5e6b4b0d3255bfef95601890afd80709");
// PHP
define("MIN_PHP_VERSION", "5.3.0");
define("HAS_PHP_VERSION", version_compare(PHP_VERSION, MIN_PHP_VERSION) >= 0);
define("HAS_PHP_EXIF", function_exists("exif_thumbnail"));
$has_php_jpg = false;
if (function_exists("gd_info")) {
$infos = gd_info();
$has_php_jpg = array_key_exists("JPG Support", $infos) && $infos["JPG Support"] || array_key_exists("JPEG Support", $infos) && $infos["JPEG Support"];
}
define("HAS_PHP_JPG", $has_php_jpg);
// SERVER
$server_name = null;
$server_version = null;
$server_software = getenv("SERVER_SOFTWARE");
if ($server_software && preg_match("#^(.*?)(?:/(.*?))?(?: |$)#", strtolower($server_software), $matches)) {
$server_name = $matches[1];
$server_version = count($matches) > 2 ? $matches[2] : '';
}
define("SERVER_NAME", $server_name);
define("SERVER_VERSION", $server_version);
define("HAS_SERVER", in_array($server_name, array("apache", "lighttpd", "nginx", "cherokee")));
define("HAS_WIN_OS", strtolower(substr(PHP_OS, 0, 3)) === "win");
// PATHS
$script_name = getenv("SCRIPT_NAME");
if (SERVER_NAME === "lighttpd") {
$script_name = preg_replace("#^.*?//#", "/", $script_name);
}
define("APP_HREF", Util::normalize_path(dirname(dirname(dirname($script_name))), true));
define("APP_PATH", Util::normalize_path(dirname(dirname(dirname(dirname(__FILE__)))), false));
define("ROOT_HREF", Util::normalize_path(dirname(APP_HREF), true));
define("ROOT_PATH", Util::normalize_path(dirname(APP_PATH), false));
$uri_parts = parse_url(getenv("REQUEST_URI"));
$current_href = Util::normalize_path($uri_parts["path"], true);
$rel_href = substr($current_href, strlen(ROOT_HREF));
$current_path = Util::normalize_path(ROOT_PATH . "/" . rawurldecode($rel_href));
if (!is_dir($current_path)) {
$current_href = Util::normalize_path(dirname($current_href), true);
$current_path = Util::normalize_path(dirname($current_path), false);
}
define("CURRENT_HREF", $current_href);
define("CURRENT_PATH", $current_path);
$index_href = null;
if (@is_readable(Util::normalize_path(APP_PATH . "/server/php/index.php", false))) {
$index_href = Util::normalize_path(APP_HREF . "/server/php/index.php", false);
}
define("INDEX_HREF", $index_href);
define("CACHE_HREF", Util::normalize_path(APP_HREF . "/cache", true));
define("CACHE_PATH", Util::normalize_path(APP_PATH . "/cache", false));
define("HAS_WRITABLE_CACHE", @is_writable(CACHE_PATH));
define("CMDS_PATH", Util::normalize_path(CACHE_PATH . "/cmds.json", false));
// EXTERNAL COMMANDS
$cmds = Util::load_commented_json(CMDS_PATH);
if (sizeof($cmds) === 0 || Util::has_request_param("updatecmds")) {
$cmds["command"] = Util::exec_0("command -v command");
$cmds["which"] = Util::exec_0("which which");
$cmd = false;
if ($cmds["command"]) {
$cmd = "command -v";
} else if ($cmds["which"]) {
$cmd = "which";
}
foreach (array("tar", "zip", "convert", "ffmpeg", "avconv", "du") as $c) {
$cmds[$c] = ($cmd !== false) && Util::exec_0($cmd . " " . $c);
}
Util::safe_json(CMDS_PATH, $cmds);
}
foreach ($cmds as $c => $has) {
define("HAS_CMD_" . strtoupper($c), $has);
}
}
}

View file

@ -26,7 +26,7 @@ class Thumb {
public function thumb($type, $source_url, $mode, $width, $height) {
$source_path = $this->app->to_path($source_url);
if (!file_exists($source_path) || starts_with($source_path, CACHE_PATH)) {
if (!file_exists($source_path) || Util::starts_with($source_path, CACHE_PATH)) {
return null;
}
@ -96,7 +96,7 @@ class Thumb {
$arg = str_replace("[DEST]", $capture_path, $arg);
}
exec_cmdv($cmdv);
Util::exec_cmdv($cmdv);
}
return file_exists($capture_path) ? $capture_path : null;

View file

@ -0,0 +1,117 @@
<?php
class Util {
public static function normalize_path($path, $trailing_slash = false) {
$path = preg_replace("#[\\\\/]+#", "/", $path);
return preg_match("#^(\w:)?/$#", $path) ? $path : (rtrim($path, "/") . ($trailing_slash ? "/" : ""));
}
public static function json_exit($obj = array()) {
if (!isset($obj["code"])) {
$obj["code"] = 0;
}
header("Content-type: application/json;charset=utf-8");
echo json_encode($obj);
exit;
}
public static function json_fail($code, $msg = "", $cond = true) {
if ($cond) {
Util::json_exit(array("code" => $code, "msg" => $msg));
}
}
public static function has_request_param($key) {
return array_key_exists($key, $_REQUEST);
}
public static function use_request_param($key, $default = null) {
if (!array_key_exists($key, $_REQUEST)) {
Util::json_fail(101, "parameter '$key' is missing", $default === null);
return $default;
}
$value = $_REQUEST[$key];
unset($_REQUEST[$key]);
return $value;
}
public static function starts_with($sequence, $head) {
return substr($sequence, 0, strlen($head)) === $head;
}
public static function ends_with($sequence, $tail) {
return substr($sequence, -strlen($tail)) === $tail;
}
public static function load_commented_json($path) {
if (!file_exists($path)) {
return array();
}
$content = file_get_contents($path);
// remove comments to get pure json
$content = preg_replace("/\/\*.*?\*\/|\/\/.*?(\n|$)/s", "", $content);
return json_decode($content, true);
}
public static function safe_json($path, $obj) {
$json = json_encode($obj);
return file_put_contents($path, $json) !== false;
}
public static function passthru_cmd($cmd) {
$rc = null;
passthru($cmd, $rc);
return $rc;
}
public static function exec_cmdv($cmdv) {
if (!is_array($cmdv)) {
$cmdv = func_get_args();
}
$cmd = implode(" ", array_map("escapeshellarg", $cmdv));
$lines = array();
$rc = null;
exec($cmd, $lines, $rc);
return implode("\n", $lines);
}
public static function exec_0($cmd) {
$lines = array();
$rc = null;
try {
@exec($cmd, $lines, $rc);
return $rc === 0;
} catch (Exception $e) {}
return false;
}
}

View file

@ -1,108 +0,0 @@
<?php
function setup() {
// MISC
putenv("LANG=en_US.UTF-8");
setlocale(LC_CTYPE, "en_US.UTF-8");
date_default_timezone_set("UTC");
define("NAME", "{{pkg.name}}");
define("VERSION", "{{pkg.version}}");
define("BACKEND", "PHP");
define("API", true);
define("FILE_PREFIX", "_{{pkg.name}}");
// ADMIN
session_start();
define("AS_ADMIN_SESSION_KEY", "__H5AI_AS_ADMIN__");
define("AS_ADMIN", isset($_SESSION[AS_ADMIN_SESSION_KEY]) && $_SESSION[AS_ADMIN_SESSION_KEY] === true);
define("HAS_CUSTOM_PASSHASH", PASSHASH !== "da39a3ee5e6b4b0d3255bfef95601890afd80709");
// PHP
define("MIN_PHP_VERSION", "5.3.0");
define("HAS_PHP_VERSION", version_compare(PHP_VERSION, MIN_PHP_VERSION) >= 0);
define("HAS_PHP_EXIF", function_exists("exif_thumbnail"));
$has_php_jpg = false;
if (function_exists("gd_info")) {
$infos = gd_info();
$has_php_jpg = array_key_exists("JPG Support", $infos) && $infos["JPG Support"] || array_key_exists("JPEG Support", $infos) && $infos["JPEG Support"];
}
define("HAS_PHP_JPG", $has_php_jpg);
// SERVER
$server_name = null;
$server_version = null;
$server_software = getenv("SERVER_SOFTWARE");
if ($server_software && preg_match("#^(.*?)(?:/(.*?))?(?: |$)#", strtolower($server_software), $matches)) {
$server_name = $matches[1];
$server_version = count($matches) > 2 ? $matches[2] : '';
}
define("SERVER_NAME", $server_name);
define("SERVER_VERSION", $server_version);
define("HAS_SERVER", in_array($server_name, array("apache", "lighttpd", "nginx", "cherokee")));
define("HAS_WIN_OS", strtolower(substr(PHP_OS, 0, 3)) === "win");
// PATHS
$script_name = getenv("SCRIPT_NAME");
if (SERVER_NAME === "lighttpd") {
$script_name = preg_replace("#^.*?//#", "/", $script_name);
}
define("APP_HREF", normalize_path(dirname(dirname(dirname($script_name))), true));
define("APP_PATH", normalize_path(dirname(dirname(dirname(dirname(__FILE__)))), false));
define("ROOT_HREF", normalize_path(dirname(APP_HREF), true));
define("ROOT_PATH", normalize_path(dirname(APP_PATH), false));
$uri_parts = parse_url(getenv("REQUEST_URI"));
$current_href = normalize_path($uri_parts["path"], true);
$rel_href = substr($current_href, strlen(ROOT_HREF));
$current_path = normalize_path(ROOT_PATH . "/" . rawurldecode($rel_href));
if (!is_dir($current_path)) {
$current_href = normalize_path(dirname($current_href), true);
$current_path = normalize_path(dirname($current_path), false);
}
define("CURRENT_HREF", $current_href);
define("CURRENT_PATH", $current_path);
$index_href = null;
if (@is_readable(normalize_path(APP_PATH . "/server/php/index.php", false))) {
$index_href = normalize_path(APP_HREF . "/server/php/index.php", false);
}
define("INDEX_HREF", $index_href);
define("CACHE_HREF", normalize_path(APP_HREF . "/cache", true));
define("CACHE_PATH", normalize_path(APP_PATH . "/cache", false));
define("HAS_WRITABLE_CACHE", @is_writable(CACHE_PATH));
define("CMDS_PATH", normalize_path(CACHE_PATH . "/cmds.json", false));
// EXTERNAL COMMANDS
$cmds = load_commented_json(CMDS_PATH);
if (sizeof($cmds) === 0 || has_request_param("updatecmds")) {
$cmds["command"] = exec_0("command -v command");
$cmds["which"] = exec_0("which which");
$cmd = false;
if ($cmds["command"]) {
$cmd = "command -v";
} else if ($cmds["which"]) {
$cmd = "which";
}
foreach (array("tar", "zip", "convert", "ffmpeg", "avconv", "du") as $c) {
$cmds[$c] = ($cmd !== false) && exec_0($cmd . " " . $c);
}
safe_json(CMDS_PATH, $cmds);
}
foreach ($cmds as $c => $has) {
define("HAS_CMD_" . strtoupper($c), $has);
}
}

View file

@ -1,153 +0,0 @@
<?php
function normalize_path($path, $trailing_slash = false) {
$path = preg_replace("#[\\\\/]+#", "/", $path);
return preg_match("#^(\w:)?/$#", $path) ? $path : (rtrim($path, "/") . ($trailing_slash ? "/" : ""));
}
function json_exit($obj = array()) {
if (!isset($obj["code"])) {
$obj["code"] = 0;
}
header("Content-type: application/json;charset=utf-8");
echo json_encode($obj);
exit;
}
function json_fail($code, $msg = "", $cond = true) {
if ($cond) {
json_exit(array("code" => $code, "msg" => $msg));
}
}
function has_request_param($key) {
return array_key_exists($key, $_REQUEST);
}
function use_request_param($key, $default = null) {
if (!array_key_exists($key, $_REQUEST)) {
json_fail(101, "parameter '$key' is missing", $default === null);
return $default;
}
$value = $_REQUEST[$key];
unset($_REQUEST[$key]);
return $value;
}
function starts_with($sequence, $head) {
return substr($sequence, 0, strlen($head)) === $head;
}
function ends_with($sequence, $tail) {
return substr($sequence, -strlen($tail)) === $tail;
}
function load_commented_json($path) {
if (!file_exists($path)) {
return array();
}
$content = file_get_contents($path);
// remove comments to get pure json
$content = preg_replace("/\/\*.*?\*\/|\/\/.*?(\n|$)/s", "", $content);
return json_decode($content, true);
}
function safe_json($path, $obj) {
$json = json_encode($obj);
return file_put_contents($path, $json) !== false;
}
function passthru_cmd($cmd) {
$rc = null;
passthru($cmd, $rc);
return $rc;
}
function exec_cmdv($cmdv) {
if (!is_array($cmdv)) {
$cmdv = func_get_args();
}
$cmd = implode(" ", array_map("escapeshellarg", $cmdv));
$lines = array();
$rc = null;
exec($cmd, $lines, $rc);
return implode("\n", $lines);
}
function exec_0($cmd) {
$lines = array();
$rc = null;
try {
@exec($cmd, $lines, $rc);
return $rc === 0;
} catch (Exception $e) {}
return false;
}
/*********************************************************************
Debug Tools
*********************************************************************/
function err_log($message, $obj = null) {
error_log($message . ": " . var_export($obj, true));
}
function scr_log($message, $obj = null) {
echo("<pre>" . $message . ": " . var_export($obj, true) . "</pre>\n");
}
global $__TIMER_START, $__TIMER_PREV;
$__TIMER_START = microtime(true);
$__TIMER_PREV = $__TIMER_START;
function time_log($message) {
global $__TIMER_START, $__TIMER_PREV;
$now = microtime(true);
if ($__TIMER_START === $__TIMER_PREV) {
error_log("------------------------------");
register_shutdown_function(function () { time_log('ex'); });
}
error_log($message . " DT " . number_format($now - $__TIMER_PREV, 5) . " TT " . number_format($now - $__TIMER_START, 5));
$__TIMER_PREV = $now;
}

View file

@ -16,18 +16,15 @@ function normalized_require_once($lib) {
require_once(preg_replace("#[\\\\/]+#", "/", dirname(__FILE__) . "/inc/${lib}.php"));
}
normalized_require_once("util");
normalized_require_once("setup");
normalized_require_once("class-api");
normalized_require_once("class-app");
normalized_require_once("class-archive");
normalized_require_once("class-item");
normalized_require_once("class-thumb");
function __autoload($class_name) {
setup();
normalized_require_once("class-" . strtolower($class_name));
}
Setup::init();
$app = new App();
if (has_request_param("action")) {
if (Util::has_request_param("action")) {
$api = new Api($app);
$api->apply();
} else {