Removed libpy2php files

This commit is contained in:
danogentili 2016-08-08 18:24:41 +02:00
parent 3a0a7179d4
commit 1eb730d281
8 changed files with 11 additions and 1597 deletions

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,5 @@
[App data]
api_id = 25628
api_hash = 1fe17cda7d355166cdaa71f04122873c
ip_address = 149.154.167.50
port = 443

View File

@ -143,7 +143,6 @@ class Session:
f = open(os.path.join(os.path.dirname(__file__), "rsa.pub"))
key = RSA.importKey(f.read())
print(getattr(key.key, 'n') . getattr(key.key, 'e'))
ResPQ = self.method_call('req_pq', nonce=nonce)
server_nonce = ResPQ['server_nonce']
# TODO: selecting RSA public key based on this fingerprint

View File

@ -219,14 +219,19 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
$this->log->log(sprintf('Factorization %s = %s * %s', $pq, $p, $q));
// Serialize object for req_DH_params
$p_bytes = $this->struct->pack('>Q', (string) $p);
$q_bytes = $this->struct->pack('>Q', (string) $q);
$new_nonce = \phpseclib\Crypt\Random::string(32);
$data = $this->tl->serialize_obj('p_q_inner_data', ['pq' => $pq_bytes, 'p' => $p_bytes, 'q' => $q_bytes, 'nonce' => $nonce, 'server_nonce' => $server_nonce, 'new_nonce' => $new_nonce]);
$sha_digest = sha1($data, true);
// Encrypt serialized object
$random_bytes = \phpseclib\Crypt\Random::string(255 - strlen($data) - strlen($sha_digest));
$to_encrypt = $sha_digest.$data.$random_bytes;
$encrypted_data = $this->key->encrypt($to_encrypt);
// req_DH_params
$this->log->log('Starting Diffie Hellman key exchange');
$server_dh_params = $this->method_call('req_DH_params', ['nonce' => $nonce, 'server_nonce' => $server_nonce, 'p' => $p_bytes, 'q' => $q_bytes, 'public_key_fingerprint' => $public_key_fingerprint, 'encrypted_data' => $encrypted_data]);
if ($nonce != $server_dh_params['nonce']) {

View File

@ -1,524 +0,0 @@
<?php
// Copyright 2006 James Tauber and contributors
//
// 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.
/**
* This call makes three things happen:.
*
* 1) a global error handler for php errors that causes an exception to be
* thrown instead of standard php error handling.
*
* 2) a global exception handler for any exceptions that are somehow not
* caught by the application code.
*
* 3) error_reporting is set to E_STRICT, so that even notices cause an
* exception to be thrown. This way we are forced to deal with even
* the minor issues during development, and hopefully fewer issues
*/
require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'strict_mode.php';
init_strict_mode();
// iteration from Bob Ippolito's Iteration in JavaScript
// pyjs_extend from Kevin Lindsey's Inteheritance Tutorial (http://www.kevlindev.com/tutorials/javascript/inheritance/)
// type functions from Douglas Crockford's Remedial Javascript: http://www.crockford.com/javascript/remedial.html
function pyjslib_isObject($a)
{
return is_object($a);
}
function pyjslib_isFunction($a)
{
return is_function($a);
}
function pyjslib_isString($a)
{
return is_string($a);
}
function pyjslib_isNull($a)
{
return is_null($a);
}
function pyjslib_isArray($a)
{
return is_array($a);
}
function pyjslib_isUndefined($a)
{
return !isset($a);
}
function pyjslib_isIteratable($a)
{
return $a instanceof Traversable;
}
function pyjslib_isNumber($a)
{
return is_numeric($a);
}
function pyjslib_int($a)
{
return (int) $a;
}
function pyjslib_str($val)
{
return (string) $val;
}
function pyjslib_del_slice(&$list, $from, $to, $step = 1)
{
if ($from <= 0) {
$from = 0;
}
if ($to === null) {
$to = count($list);
}
if ($step <= 0) {
$step = 1;
}
for ($i = $from; $i < $to; $i += $step) {
unset($list[$i]);
}
}
function pyjslib_array_slice($list, $from, $to, $step = 1)
{
$newlist = [];
if ($from <= 0) {
$from = 0;
}
if ($to === null) {
$to = count($list);
}
if ($step <= 0) {
$step = 1;
}
for ($i = $from; $i < $to; $i += $step) {
$newlist[] = $list[$i];
}
return $newlist;
}
// taken from mochikit: range( [start,] stop[, step] )
function pyjslib_range($start, $stop = null, $step = 1)
{
if ($stop === null) {
$stop = $start;
$start = 0;
}
if ($stop <= $start && $step < 0) {
$arr = range($stop, $start, -$step);
array_pop($arr);
return array_reverse($arr, false);
}
if ($step > 1 && $step > ($stop - $start)) {
$arr = [$start];
} else {
$arr = range($start, $stop, $step);
array_pop($arr);
}
return $arr;
}
function pyjslib_filter($callback, $iterable)
{
$a = [];
foreach ($iterable as $item) {
if (call_user_func($callback, $item)) {
$a[] = $item;
}
}
return $a;
}
function pyjslib_globals()
{
return $GLOBALS;
}
function pyjslib_map($callable)
{
$done = false;
$call_cnt = 0;
$results = [];
$params = func_get_args();
array_shift($params);
while (!$done) {
$func_args = [];
$found = false;
for ($i = 0; $i < count($params); $i++) {
$func_args[] = @$params[$i][$call_cnt];
if (count($params[$i]) > $call_cnt + 1) {
$found = true;
}
}
if (!$found) {
$done = true;
}
$results[] = call_user_func_array($callable, $func_args);
$call_cnt++;
}
return $results;
}
function pyjslib_zip()
{
$params = func_get_args();
if (count($params) === 1) { // this case could be probably cleaner
// single iterable passed
$result = [];
foreach ($params[0] as $item) {
$result[] = [$item];
}
return $result;
}
$result = call_user_func_array('array_map', array_merge([null], $params));
$length = min(array_map('count', $params));
return array_slice($result, 0, $length);
}
function pyjslib_is_assoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
function pyjslib_dict($arg = null)
{
if ($arg === null) {
return [];
}
if (pyjslib_is_assoc($arg)) {
return $arg;
}
$dict = [];
foreach ($arg as $a) {
if (count($a) == 2) {
$dict[$a[0]] = $a[1];
}
}
return $dict;
}
function pyjslib_printWorker($objs, $nl, $multi_arg, $depth = 1)
{
$buf = '';
if (is_array($objs) && $multi_arg && $depth == 1) {
$cnt = 0;
foreach ($objs as $obj) {
if ($cnt++ > 0) {
$buf .= ' ';
}
$buf .= pyjslib_printWorker($obj, $nl, $multi_arg, $depth + 1);
}
} elseif (is_bool($objs)) {
$buf = $objs ? 'True' : 'False';
} elseif (is_null($objs)) {
$buf = 'None';
} elseif (is_float($objs)) {
$buf = (int) $objs;
} elseif (is_string($objs) && ($multi_arg && $depth > 2 || (!$multi_arg && $depth > 1))) {
$buf = "'$objs'";
} elseif (is_array($objs)) {
$buf = '[';
$cnt = 0;
foreach ($objs as $obj) {
$val = pyjslib_printWorker($obj, $nl, false, $depth + 1);
if ($cnt++ > 0) {
$buf .= ', ';
}
$buf .= $val;
}
$buf .= ']';
// $buf = '[' . implode( ", ", $objs ) . ']';
} else {
$buf = $objs;
}
if ($depth == 1 && (!strlen($buf) || $buf[strlen($buf) - 1] != "\n")) {
$buf .= $nl ? "\n" : ' ';
}
return $buf;
}
function pyjslib_repr($obj)
{
return pyjslib_printWorker($obj, false, false);
}
function pyjslib_print($objs, $multi_arg = false)
{
echo pyjslib_printWorker($objs, false, $multi_arg);
}
function pyjslib_printnl($objs, $multi_arg = false)
{
echo pyjslib_printWorker($objs, true, $multi_arg);
}
function py2php_kwargs_function_call($funcname, $ordered, $named)
{
if ($funcname == 'array' || $funcname == 'pyjslib_dict') {
return $named;
}
$num_ordered = count($ordered);
$count = 1;
$refFunc = new ReflectionFunction($funcname);
foreach ($refFunc->getParameters() as $param) {
if ($param->isVariadic()) {
$ordered[$count - 1] = $named;
break;
}
//invokes ReflectionParameter::__toString
if ($count > $num_ordered) {
$name = $param->name;
$default = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;
$ordered[] = @$named[$name] ?: $default;
}
$count++;
}
//var_dump($ordered);
return call_user_func_array($funcname, $ordered);
}
function py2php_kwargs_method_call($obj, $method, $ordered, $named)
{
$num_ordered = count($ordered);
$count = 1;
$refFunc = new ReflectionMethod($obj, $method);
foreach ($refFunc->getParameters() as $param) {
//invokes ReflectionParameter::__toString
if ($count > $num_ordered) {
$name = $param->name;
$default = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;
$ordered[] = @$named[$name] ?: $default;
}
$count++;
}
$callable = [$obj, $method];
return call_user_func_array($callable, $ordered);
}
class IOError extends Exception
{
}
class ValueError extends Exception
{
}
function pyjslib_open($name, $mode = 'r', $buffering = null)
{
return new pyjslib_file($name, $mode, $buffering);
}
class pyjslib_file implements Iterator
{
private $fh = false;
private $current_line = null;
// public attributes of python file class.
public $closed = true;
public $encoding = null;
public $errors = [];
public $mode = null;
public $newlines = null;
public $softspace = false;
public function __construct($name_or_fd, $mode = 'r', $buffering = null)
{
if (is_resource($name_or_fd)) {
$this->fh = $name_or_fd;
$this->closed = false;
$meta = stream_get_meta_data($name_or_df);
$this->mode = $meta['mode'];
return;
}
$name = $name_or_fd;
try {
$this->fh = fopen($name, $mode);
if (!$this->fh) {
throw new Exception("Could not open $name");
}
$this->closed = false;
$this->mode = $mode;
} catch (Exception $e) {
throw new IOError($e->getMessage(), $e->getCode());
}
}
public function close()
{
if ($this->fh) {
fclose($this->fh);
$this->fh = null;
$this->closed = true;
}
}
public function flush()
{
if (!$this->fh) {
throw new ValueError('File is closed.');
}
fflush($this->fh);
}
public function fileno()
{
if (!$this->fh) {
throw new ValueError('File is closed.');
}
return $this->fh;
}
public function isatty()
{
if (!$this->fh) {
throw new ValueError('File is closed.');
}
return posix_isatty($this->fh);
}
/* ---
* Begin PHP Iterator implementation
* ---
*/
public function rewind()
{
fseek($this->fh, 0);
$this->line = 0;
}
public function current()
{
if (!$this->current_line) {
$this->current_line = fgets($this->fh);
}
return $this->current_line;
}
public function key()
{
return $this->line;
}
public function next()
{
$this->current(); // ensure current line has been retrieved.
$this->current_line = fgets($this->fh);
$this->line++;
return $this->current_line;
}
public function valid()
{
return $this->fh != false && !feof($this->fh);
}
/* ---
* End PHP Iterator implementation
* ---
*/
public function read($size = null)
{
if ($size !== null) {
return fread($this->fh, $size);
}
return stream_get_contents($this->fh);
}
public function readline($size = null)
{
return fgets($this->fh, $size);
}
public function readlines($sizehint = null)
{
$len = 0;
$lines = [];
while ($line = fgets($this->fh)) {
$len += strlen($line);
$lines[] = $line;
if ($sizehint && $len >= $sizehint) {
break;
}
}
return $lines;
}
public function seek($offset, $whence = SEEK_SET)
{
return fseek($this->fh, $offset, $whence);
}
public function tell()
{
return ftell($this->fh);
}
public function truncate($size)
{
$rc = ftruncate($this->fh, $size);
}
public function write($str)
{
fwrite($this->fh, $str);
}
public function writelines($sequence)
{
foreach ($sequence as $line) {
$this->write($line);
}
}
}

View File

@ -1,683 +0,0 @@
<?php
class OSError extends Exception
{
}
class os
{
const F_OK = 0x0001;
const R_OK = 0x0002;
const W_OK = 0x0004;
const X_OK = 0x0008;
const SEEK_SET = SEEK_SET;
const SEEK_CUR = SEEK_CUR;
const SEEK_END = SEEK_END;
const EX_OK = 0;
const EX_USAGE = 1;
const EX_DATAERR = 2;
const EX_NOINPUT = 3;
const EX_NOUSER = 4;
const EX_NOHOST = 5;
const EX_UNAVAILABLE = 6;
const EX_SOFTWARE = 7;
const EX_OSERR = 8;
const EX_OSFILE = 9;
const EX_CANTCREAT = 10;
const EX_IOERR = 11;
const EX_TEMPFAIL = 12;
const EX_PROTOCOL = 13;
const EX_NOPERM = 14;
const EX_CONFIG = 15;
const EX_NOTFOUND = 16;
const EX_ = 17;
const O_RDONLY = 0x0001;
const O_WRONLY = 0x0002;
const O_RDWR = 0x0004;
const O_APPEND = 0x0008;
const O_CREAT = 0x0010;
const O_EXCL = 0x0020;
const O_TRUNC = 0x0040;
const TMP_MAX = PHP_INT_MAX;
public $environ;
public $pathconf_names = [];
public static function ctermid()
{
return posix_ctermid();
}
public static function getegid()
{
return posix_getegid();
}
public static function geteuid()
{
return posix_geteuid();
}
public static function getgid()
{
return posix_getgid();
}
public static function getgroups()
{
return posix_getgroups();
}
public static function initgroups($username, $gid)
{
return posix_initgroups($username, $gid);
}
public static function getlogin()
{
return posix_getlogin();
}
public static function getpgid()
{
return posix_getpgid();
}
public static function getpgrp()
{
return posix_getpgrp();
}
public static function getpid()
{
return posix_getpid();
}
public static function getresuid()
{
self::_unimplemented();
}
public static function getresgid()
{
self::_unimplemented();
}
public static function getuid()
{
return posix_getuid();
}
public static function getenv($varname, $value = null)
{
return getenv($varname, $value);
}
public static function putenv($varname, $value)
{
putenv("$varname=$value");
}
public static function setegid($egid)
{
posix_setegid($egid);
}
public static function seteuid($euid)
{
posix_seteuid($euid);
}
public static function setgid($gid)
{
posix_setgid($gid);
}
public static function setgroups($groups)
{
self::_unimplemented();
}
public static function setpgrp()
{
self::_unimplemented();
}
public static function setpgid($pid, $pgrp)
{
posix_setpgid($pid, $pgrp);
}
public static function setregid($rgid, $egid)
{
self::_unimplemented();
}
public static function setresgid($rgid, $egid, $sgid)
{
self::_unimplemented();
}
public static function setresuid($ruid, $euid, $suid)
{
self::_unimplemented();
}
public static function setreuid($ruid, $euid)
{
self::_unimplemented();
}
public static function getsid($pid)
{
return posix_getsid();
}
public static function setsid()
{
posix_setsid();
}
public static function setuid($uid)
{
posix_setuid($uid);
}
public static function strerror($code)
{
self::_unimplemented();
}
public static function umask($mask)
{
umask($mask);
}
public static function uname()
{
return posix_uname();
}
public static function unsetenv($varname)
{
unset($_ENV[$varname]);
}
public static function fdopen($fd, $mode = null, $bufsize = null)
{
return new pyjslib_file($fd);
}
public static function popen($command, $mode = null, $bufsize = null)
{
self::_unimplemented();
}
public static function tmpfile()
{
return tmpfile();
}
public static function popen2($cmd, $mode = null, $bufsize = null)
{
self::_unimplemented();
}
public static function popen3($cmd, $mode = null, $bufsize = null)
{
self::_unimplemented();
}
public static function popen4($cmd, $mode = null, $bufsize = null)
{
self::_unimplemented();
}
public static function close($fd)
{
fclose($fd);
}
public static function closerange($fd_low, $fd_high)
{
self::_unimplemented();
}
public static function dup($fd)
{
self::_unimplemented();
}
public static function dup2($fd)
{
self::_unimplemented();
}
public static function fchmod($fd, $mode)
{
self::_unimplemented();
}
public static function fchown($fd, $uid, $gid)
{
self::_unimplemented();
}
public static function fdatasync($fd)
{
self::_unimplemented();
}
public static function fpathconf($fd, $name)
{
self::_unimplemented();
}
public static function fstat($fd)
{
$info = fstat($fd);
$obj = new stdClass();
foreach ($arr as $key => $v) {
$attr = 'st_'.$key;
$obj->$attr = $v;
}
return $obj;
}
public static function fstatvfs($fd)
{
self::_unimplemented();
}
public static function fsync($fd)
{
fsync($fd);
}
public static function ftruncate($fd, $length)
{
ftruncate($fd, $length);
}
public static function isatty($fd)
{
return posix_isatty($fd);
}
public static function lseek($fd, $pos, $how)
{
lseek($fd, $pos, $how);
}
public static function open($file, $flags, $mode = 0777)
{
// todo: define and map flag constants. See list at:
// https://docs.python.org/2/library/os.html#open-flag-constants
$fl = '';
if ($flags & self::O_RDONLY) {
$fl .= 'r';
}
if ($flags & self::O_WRONLY) {
$fl .= 'w';
}
if ($flags & self::O_RDWR) {
$fl .= 'rw';
}
if ($flags & self::O_APPEND) {
$fl .= 'a';
}
if ($flags & self::O_CREAT) {
$fl .= 'c';
}
if ($flags & self::O_EXCL) {
$fl .= 'x';
}
if ($flags & self::O_TRUNC) {
$fl .= 'w';
}
return fopen($file, $fl, false);
}
public static function pipe()
{
self::_unimplemented();
}
public static function read($fd, $n)
{
return fread($fd, $n);
}
public static function tcgetpgrp($fd)
{
self::_unimplemented();
}
public static function tcsetpgrp($fd, $pg)
{
self::_unimplemented();
}
public static function ttyname($fd)
{
return posix_ttyname($fd);
}
public static function write($fd, $str)
{
return fwrite($fd, $str);
}
public static function access($path, $mode)
{
return posix_access($path, $mode);
}
public static function chdir($path)
{
chdir($path);
}
public static function fchdir($path)
{
fchdir($path);
}
public static function getcwd()
{
return getcwd();
}
public static function getcwdu()
{
return getcwd();
}
public static function chflags($path, $flags)
{
self::_unimplemented();
}
public static function chroot($path)
{
chroot($path);
}
public static function chmode($path, $mode)
{
self::_unimplemented();
}
public static function chown($path, $uid, $gid)
{
chown($path, $uid, $gid);
}
public static function lchflags($path, $flags)
{
self::_unimplemented();
}
public static function lchmod($path, $mode)
{
self::_unimplemented();
}
public static function lchown($path, $uid, $gid)
{
self::_unimplemented();
}
public static function link($source, $link_name)
{
link($source, $link_name);
}
public static function listdir($path)
{
self::_unimplemented();
}
public static function lstat($path)
{
self::_unimplemented();
}
public static function mkfifo($path, $mode = 0666)
{
posix_mkfifo($path, $mode);
}
public static function mknod($filename, $mode = 0666, $device = 0)
{
return posix_mknod($filename, $mode);
}
public static function major($path, $flags)
{
self::_unimplemented();
}
public static function minor($path, $flags)
{
self::_unimplemented();
}
public static function makedev($major, $minor)
{
self::_unimplemented();
}
public static function mkdir($path, $mode = 0777)
{
mkdir($path, $mode, $recursive = false);
}
public static function makedirs($path, $mode = 0777)
{
mkdir($path, $mode, $recursive = true);
}
public static function pathconf($path, $name)
{
self::_unimplemented();
}
public static function readlink($path)
{
return readlink($path);
}
public static function remove($path)
{
if (!is_file($path)) {
throw new OSError("Path is not a file. $path");
}
try {
unlink($path);
} catch (Exception $e) {
throw new OSError($e->getMessage(), $e->getCode());
}
}
public static function removedirs($path)
{
self::_unimplemented();
}
public static function rename($src, $dst)
{
if (is_dir($dst)) {
throw new OSError("Destination is a directory. $dst");
}
rename($src, $dst);
}
public static function renames($old, $new)
{
self::makedirs(dirname($new));
self::rename($old, $new);
}
public static function rmdir($path)
{
rmdir($pat);
}
public static function stat($path)
{
$arr = stat($path);
if (!$arr) {
throw new OSError("Path does not exist. $path");
}
$obj = new stdClass();
foreach ($arr as $key => $v) {
$attr = 'st_'.$key;
$obj->$attr = $v;
}
return $obj;
}
public static function stat_float_times($newvalue = null)
{
self::_unimplemented();
}
public static function statvfs()
{
self::_unimplemented();
}
public static function symlink($source, $link_name)
{
symlink($source, $link_name);
}
public static function tempnam($dir = null, $prefix = '')
{
if (!$dir) {
$dir = sys_get_temp_dir();
}
$name = tempnam($dir, $prefix);
unlink($name);
return $name;
}
public static function tmpnam()
{
return self::tempnam();
}
public static function unlink($path)
{
unlink($path);
}
public static function utime($path, $times)
{
self::_unimplemented();
}
public static function walk($top, $topdown = true, $onerror = null, $followlinks = false)
{
self::_unimplemented();
}
/**
* Begin Process Management.
*/
public static function abort()
{
self::_unimplemented();
}
public static function execl($path, $arg0, $arg1)
{
self::_unimplemented();
}
public static function execle($path, $arg0, $arg1, $env)
{
self::_unimplemented();
}
public static function execlp($file, $arg0, $arg1)
{
self::_unimplemented();
}
public static function execlpe($file, $arg0, $arg1, $env)
{
self::_unimplemented();
}
public static function execv($path, $args)
{
self::_unimplemented();
}
public static function execve($path, $args, $env)
{
self::_unimplemented();
}
public static function execvp($file, $args)
{
self::_unimplemented();
}
public static function execvpe($file, $args, $env)
{
self::_unimplemented();
}
public static function _exit($n)
{
exit($n);
}
public static function fork()
{
return pcntl_fork();
}
public static function forkpty()
{
self::_unimplemented();
}
public static function kill($pid, $sig)
{
posix_kill($pid, $sig);
}
public static function killpg($pgid, $sig)
{
self::_unimplemented();
}
public static function nice($increment)
{
proc_nice($increment);
}
public static function plock($op)
{
self::_unimplemented();
}
private static function _unimplemented()
{
throw new Exception('Unimplemented. Please consider submitting a patch to py2php project on github.');
}
}

View File

@ -1,251 +0,0 @@
<?php
require_once dirname(__FILE__).'/os.php';
/**
* A class to emulate python's os.path.
*/
class os_path
{
const supports_unicode_filenames = true;
public static function abspath($path)
{
return self::normpath(self::join(getcwd(), $path));
}
public static function basename($path)
{
// is this right?
return basename($path);
}
public static function commonprefix($list)
{
$pl = 0; // common prefix length
$n = count($list);
$l = strlen($list[0]);
while ($pl < $l) {
$c = $list[0][$pl];
for ($i = 1; $i < $n; $i++) {
if ($list[$i][$pl] !== $c) {
break 2;
}
}
$pl++;
}
return substr($list[0], 0, $pl);
}
public static function dirname($path)
{
return dirname($path);
}
public static function exists($path)
{
return file_exists($path);
}
public static function lexists($path)
{
$rc = file_exists($path);
if (!$rc && is_link($path)) {
return true;
}
return $rc;
}
public static function expanduser($path)
{
if (strpos($path, '~') !== false) {
$info = posix_getpwuid(posix_getuid());
$path = str_replace('~', $info['dir'], $path);
}
return $path;
}
public static function expandvars($path)
{
$env = count($_ENV) ?: $_SERVER;
$map = [];
foreach ($env as $k => $v) {
if (!is_scalar($v)) {
continue;
}
$map['$'.$k] = $v;
$map['${'.$k.'}'] = $v;
}
return strtr($path, $map);
}
public static function getatime($path)
{
try {
$rc = fileatime($path);
return $rc;
} catch (Exception $e) {
throw new OSError($e->getMessage, $e->getCode());
}
}
public static function getmtime($path)
{
try {
$rc = filemtime($path);
return $rc;
} catch (Exception $e) {
throw new OSError($e->getMessage, $e->getCode());
}
}
public static function getctime($path)
{
try {
$rc = filectime($path);
return $rc;
} catch (Exception $e) {
throw new OSError($e->getMessage, $e->getCode());
}
}
public static function getsize($path)
{
try {
$rc = filesize($path);
return $rc;
} catch (Exception $e) {
throw new OSError($e->getMessage, $e->getCode());
}
}
public static function isabs($path)
{
// fixme: implement check for windows.
return $path[0] == '/';
}
public static function isfile($path)
{
return is_file($path);
}
public static function isdir($path)
{
return is_dir($path);
}
public static function islink($path)
{
return is_link($path);
}
public static function ismount($path)
{
self::_unimplemented();
}
public static function split($path)
{
$parts = explode(DIRECTORY_SEPARATOR, $path);
$first = implode(DIRECTORY_SEPARATOR, array_slice($parts, 0, count($parts) - 1));
$last = $parts[count($parts) - 1];
return [$first, $last];
}
public static function join($path, ...$paths)
{
$buf = rtrim($path, '/');
foreach ($paths as $p) {
$i = 0;
$p = trim($p, '/');
$buf .= DIRECTORY_SEPARATOR.$p;
}
return $buf;
}
public static function normcase($path)
{
// fixme: different behavior on windows.
return $path;
}
public static function normpath($path)
{
return realpath($path);
}
public static function realpath($path)
{
return realpath($path);
}
public static function relpath($path, $start)
{
self::_unimplemented();
}
public static function samefile($path1, $path2)
{
return fileinode($path1) == fileinode($path2);
}
public static function sameopenfile($fd1, $fd2)
{
$s1 = fstat($fd1);
$s2 = fstat($fd2);
return $s1['ino'] == $s2['ino'];
}
public static function samestat($stat1, $stat2)
{
return $stat1 == $stat2;
}
public static function splitdrive($path)
{
//fixme: implement windows case.
return ['', $path];
}
public static function splitext($path)
{
$first = $path;
$second = '';
$pos = strrpos($path, '.');
if ($pos !== false) {
$first = substr($path, 0, $pos);
$second = substr($path, $pos);
}
return [$first, $second];
}
public static function splitunc($path)
{
self::_unimplemented();
}
public static function walk($path, $visit, $arg)
{
// Note: deprecated in python 3 in favor of os.walk()
self::_unimplemented();
}
private static function _unimplemented()
{
throw new Exception('Unimplemented. Please consider submitting a patch to py2php project on github.');
}
}

View File

@ -1,138 +0,0 @@
<?php
/**
* This will initialize strict mode. It is safe to be called multiple times per process
* eg in the event that a 3rd party lib overrides an error or exception handler.
*
* It is called in this file; the parent php file(s) should use require_once and do
* not need to make any call.
*/
function init_strict_mode()
{
// these are safe to call multiple times per process without dups.
error_reporting(E_ALL | E_STRICT);
restore_strict_error_handler();
restore_strict_exception_handler();
// register_shutdown_function should only be called once per process to avoid dups.
static $called = false;
if (!$called) {
register_shutdown_function('shutdown_handler');
$called = true;
}
}
/**
* This function restores the error handler if it should get overridden
* eg by a 3rd party lib. Any error handlers that were registered after
* ours are removed.
*/
function restore_strict_error_handler()
{
$e_handler_name = function () {
$name = set_error_handler('restore_strict_error_handler'); // will never be used.
restore_error_handler();
return $name;
};
while (!in_array($e_handler_name(), ['_global_error_handler', null])) {
restore_error_handler();
}
if (!$e_handler_name()) {
set_error_handler('_global_error_handler');
}
}
/**
* This function restores the exception handler if it should get overridden
* eg by a 3rd party lib. Any error handlers that were registered after
* ours are removed.
*/
function restore_strict_exception_handler()
{
$exc_handler_name = function () {
$name = set_exception_handler('restore_strict_exception_handler'); // will never be used.
restore_exception_handler();
return $name;
};
while (!in_array($exc_handler_name(), ['_global_exception_handler', null])) {
restore_exception_handler();
}
if (!$exc_handler_name()) {
set_exception_handler('_global_exception_handler');
}
}
/***
* This error handler callback will be called for every type of PHP notice/warning/error.
*
* We aspire to write solid code. everything is an exception, even minor warnings.
*
* However, we allow the @operator in the code to override.
*/
function _global_error_handler($errno, $errstr, $errfile, $errline)
{
/* from php.net
* error_reporting() settings will have no effect and your error handler will
* be called regardless - however you are still able to read the current value of
* error_reporting and act appropriately. Of particular note is that this value will
* be 0 if the statement that caused the error was prepended by the @ error-control operator.
*/
if (!error_reporting()) {
return;
}
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
/***
* This exception handler callback will be called for any exceptions that the application code does not catch.
*/
function _global_exception_handler($e)
{
$msg = sprintf("\nUncaught Exception. code: %s, message: %s\n%s : %s\n\nStack Trace:\n%s\n", $e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
while (($e = $e->getPrevious())) {
$msg .= sprintf("\nPrevious Exception. code: %s, message: %s\n%s : %s\n\nStack Trace:\n%s\n", $e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
}
echo $msg;
// error_log( $msg );
strict_mode_mail_admin('Uncaught exception!', $msg);
echo "\n\nNow exiting. Please report this problem to the software author\n\n";
exit(1);
}
/**
* This shutdown handler callback prints a message and sends email on any PHP fatal error.
*/
function shutdown_handler()
{
$error = error_get_last();
$ignore = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_STRICT | E_DEPRECATED | E_USER_DEPRECATED;
if ($error && ($error['type'] & $ignore) == 0) {
// error keys: type, file, line, message
$msg = "Ouch! Encountered PHP Fatal Error. Shutting down.\n".print_r($error, true);
echo $msg;
strict_mode_mail_admin('PHP Fatal Error!', $msg);
}
}
/**
* email admin if defined.
*/
function strict_mode_mail_admin($subject, $msg)
{
$subject = sprintf('[%s] [%s] %s [pid: %s]', gethostname(), basename($_SERVER['PHP_SELF']), $subject, getmypid());
if (defined('ALERTS_MAIL_TO')) {
mail(ALERTS_MAIL_TO, $subject, $msg);
} else {
echo "\nWARNING: ALERTS_MAIL_TO not defined in environment. alert not sent with subject: $subject\n";
}
}