/** * PHP Errors (or warning/notices) will usually output something to the * console and then return some unexpected value like false. Here we cause it * to throw instead. */ static function handleError($level, $message, $file, $line, $context) { if ($level === E_NOTICE) { return false; } $err = Error::create($message, 1); $err->set('level', $level); throw new Ex($err); }
/** * @desc Create a new cache file * @param name, the name of the file * @param data, and array of data to cache * @return whether or not the file was created */ public static function create($name, $data) { if (is_array($data)) { $data['modified'] = time(); File::write($name, json_encode($data), false, TEMP_BASE . 'cache/'); return true; } Error::create('The second parameter must be an array. With keys : name, content and profile'); return false; }
static function assert($description, $condition = false) { if ($condition instanceof Closure) { $condition = $condition(); } if ($condition !== true) { $stack = array_slice(self::$stack, 0); array_push($stack, $description); throw new Ex(Error::create('Test Failure: ' . join(': ', $stack))); } }
function update($setting, $value) { if (!Config::isValidSetting($setting)) { return Error::create("Unrecognized setting: {$setting}"); } $q = "delete from Config where name = '{$setting}'"; $r = @mysql_query($q); if (!$r) { return Error::MySQL(); } $q = "insert into Config (name, value) values ('{$setting}', '" . db::sanitize_to_db($value) . "')"; $r = @mysql_query($q); if (!$r) { return Error::MySQL(); } return true; }
function init($args) { global $Buffer; list($subject, $encoding, $offset) = array_pad($args, 3, null); $type = gettype($subject); if ($type === 'integer' || $type === 'double') { $this->raw = str_repeat("", (int) $subject); } else { if ($type === 'string') { $encoding = $encoding === null ? 'utf8' : to_string($encoding); if ($encoding === 'hex') { $this->raw = hex2bin($subject); } else { if ($encoding === 'base64') { $this->raw = base64_decode($subject); } else { $this->raw = $subject; } } } else { if (_instanceof($subject, $Buffer)) { $this->raw = $subject->raw; } else { if ($subject instanceof Arr) { $this->raw = $util['arrToRaw']($subject); } else { throw new Ex(Error::create('Invalid parameters to construct Buffer')); } } } } $len = strlen($this->raw); //save an integer copy of length for performance $this->length = $len; $this->set('length', (double) $len); }
$args = array(); foreach ($matches as $match) { $args[] = $match[0]; } $result[] = substr($str, $offset, $matchIndex - $offset); //calculate multi-byte character index from match index $mbIndex = mb_strlen(substr($str, 0, $matchIndex)); array_push($args, $mbIndex); array_push($args, $str); $result[] = to_string($replace->apply(null, $args)); $offset = $matchIndex + strlen($args[0]); $count += 1; } if ($success === false) { //this can happen in the case of invalid utf8 sequences throw new Ex(Error::create('String.prototype.replace() failed')); } $result[] = substr($str, $offset); return join('', $result); } else { $matchIndex = strpos($str, $search); if ($matchIndex === false) { return $str; } $before = substr($str, 0, $matchIndex); $after = substr($str, $matchIndex + strlen($search)); //mb_strlen used to calculate multi-byte character index $args = array($search, mb_strlen($before), $str); return $before . to_string($replace->apply(null, $args)) . $after; } }
private function _store() { $name = $this->name['filename'] . '_' . join('x', $this->dimensions) . '.' . $this->name['extension']; if (!@file_put_contents(Config::get('image.cache') . $name, $this->_create())) { return Config::get('image.cache') . $name; } else { Error::create('Could not save image file. Please check the cache folder exists and is writable.'); } return false; }
return $reg; }); $RegExp->set('prototype', RegExp::$protoObject); $RegExp->setMethods(RegExp::$classMethods, true, false, true); return $RegExp; } } RegExp::$classMethods = array(); RegExp::$protoMethods = array('exec' => function ($str) { $self = Func::getContext(); $str = to_string($str); //todo $offset $offset = 0; $result = preg_match($self->toString(true), $str, $matches, PREG_OFFSET_CAPTURE, $offset); if ($result === false) { throw new Ex(Error::create('Error executing Regular Expression: ' . $self->toString())); } if ($result === 0) { return Object::$null; } $index = $matches[0][1]; $self->set('lastIndex', (double) ($index + strlen($matches[0][0]))); $arr = new Arr(); foreach ($matches as $match) { $arr->push($match[0]); } $arr->set('index', (double) $index); $arr->set('input', $str); return $arr; }, 'test' => function ($str) { $self = Func::getContext();
function getByUserID($userID) { if (is_numeric($userID) && $userID > 0) { $q = "select ID from Band_Members where user_id = {$userID}"; $r = mysql_query($q); if ($r) { $row = mysql_fetch_assoc($r); return BandMember::get($row['ID']); } else { return Error::MySQL(); } } else { return Error::create("Invalid user ID."); } }
function get($userID) { if ($userID > 0 && is_numeric($userID)) { $q = "select ID, firstname, lastname, birthdate, is_active, username, password, email, level from Users where ID = {$userID}"; $r = mysql_query($q); $row = mysql_fetch_assoc($r); if ($row['ID']) { $uo = new User(); $uo->ID = $row['ID']; $uo->username = $row['username']; $uo->lastname = db::sanitize_from_db($row['lastname']); $uo->password = $row['password']; $uo->firstname = db::sanitize_from_db($row['firstname']); $uo->birthdate = $row['birthdate']; $uo->is_active = $row['is_active']; $uo->email = $row['email']; $uo->level = $row['level']; return $uo; } } return Error::create("Invalid user ID."); }
function set_length($len) { $len = self::checkInt($len); if ($len === null) { throw new Ex(Error::create('Invalid array length')); } //when setting the length smaller than before, we need to delete elements $oldLen = $this->length; if ($oldLen > $len) { for ($i = $len; $i < $oldLen; $i++) { $this->remove($i); } } $this->length = $len; return (double) $len; }
function remove() { if ($this->canEdit()) { $r = @mysql_query("delete from Band_News where ID = " . $this->ID); if (!$r) { return Error::MySQL(); } } else { return Error::create('You may not remove a post that is not yours.'); } }
/** * @param string $key * @param Object $obj * @return bool * @throws Exception */ function _in($key, $obj) { if (!$obj instanceof Object) { throw new Ex(Error::create("Cannot use 'in' operator to search for '" . $key . "' in " . to_string($obj))); } return $obj->hasProperty($key); }
/** * Similar to callMethod, we can call "internal" methods (dynamically-attached * user functions) which are available in PHP land but not from JS * * @param string $name - method name * @param array $args - arguments with which method was called * @return mixed * @throws Ex */ function __call($name, $args) { if (isset($this->{$name})) { return call_user_func_array($this->{$name}, $args); } else { throw new Ex(Error::create('Internal method `' . $name . '` not found on ' . gettype($this))); } }
function add($postArray) { if (User::isAdmin()) { $db = new db(); $name = $db->sanitize_to_db($postArray['name']); $description = $db->sanitize_to_db($postArray['description']); $url = $db->sanitize_to_db($postArray['url']); $category_id = $postArray['category_id']; if (!$name) { $name = '(untitled link)'; } if (strlen($url) < 6) { return Error::create("Please enter a valid URL. A URL typically begins with \"http://\""); } $r = mysql_query("INSERT INTO Links (name, description, url, category_id, is_active) VALUES ('{$name}', '{$description}', '{$url}', '{$category_id}', " . DEFAULT_ACTIVE . ")"); if ($r) { $nl = Link::get(mysql_insert_id()); return $nl; } else { return Error::MySQL(); } } else { return Error::create("Only an administrator may add links."); } }
function update($postArray) { // Admin user can update all posts, otherwise user can only update his own if (!$this->canEdit()) { return Error::create("You may not update a venue you did not post."); } $db = new db(); $name = $db->sanitize_to_db($postArray['name']); $address1 = $db->sanitize_to_db($postArray['address1']); $address2 = $db->sanitize_to_db($postArray['address2']); $city = $db->sanitize_to_db($postArray['city']); $stateProvince = $db->sanitize_to_db($postArray['stateProvince']); $postalCode = $db->sanitize_to_db($postArray['postalCode']); $directions = $db->sanitize_to_db($postArray['directions']); $country = $db->sanitize_to_db($postArray['country']); $country = $country == null ? VENUE_DEFAULT_COUNTRY : $country; if ($stateProvince == "??") { $stateProvince = $db->sanitize_to_db($postArray['stateProvinceOther']); } if (!$name) { $name = '(untitled venue)'; } if (User::isAdmin()) { $uo = User::get($postArray['user_id']); if (db::isError($uo)) { $e->add($uo); } else { if (!$uo->isAdmin() && $uo->isBandMember()) { $e->add("Invalid user. User must be a band member or an administrator."); } } } else { $uo = User::getCurrent(); } $user_id = $uo->getID(); $r = @mysql_query("update Venues set country='{$country}', user_id = '{$user_id}', name='{$name}', address1='{$address1}', address2 = '{$address2}', city='{$city}', stateProvince = '{$stateProvince}', postalCode='{$postalCode}', directions='{$directions}' where ID = " . $this->ID); if ($r) { return Venue::get($this->ID); } else { return Error::MySQL(); } }
<?php $process = new Object(); // the type of interface between web server and PHP $process->set('sapi_name', php_sapi_name()); $process->set('exit', new Func(function ($code = 0) { $code = intval($code); exit($code); })); $process->set('binding', new Func(function ($name) { $module = Module::get($name); if ($module === null) { throw new Ex(Error::create("Binding `{$name}` not found.")); } return $module; })); //command line arguments $process->argv = isset(GlobalObject::$OLD_GLOBALS['argv']) ? GlobalObject::$OLD_GLOBALS['argv'] : array(); //first argument is path to script $process->argv = array_slice($process->argv, 1); $process->set('argv', Arr::fromArray($process->argv));
function remove() { if (User::isAdmin()) { $r = @mysql_query("delete from Band_Guest_Performers where ID = " . $this->ID); if (!$r) { return Error::MySQL(); } } else { return Error::create("Only an administrator may remove guest performers."); } }
$controller->createComment($url[2], $url[3]); exit; } else { require 'Controllers/error.php'; $controller = new Error(404); } } if ($url[0] == 'like' && $url[1] == 'createLike') { if (isset($url[2]) && isset($url[3])) { $controller->createLike($url[2], $url[3]); exit; } } if ($url[0] == 'post' && $url[1] != 'index') { if ($url[1] == 'create') { $controller->create(); exit; } if ($url[1] == 'search') { $controller->search(); exit; } if ($url[1] == 'show') { if (isset($url[2])) { $controller->show($url[2]); exit; } } if ($url[1] == "newsfeed") { $controller->newsFeed(); exit;
$type = str_contains($msg, "SQL") ? "mysql" : "php"; Error::create(array('url' => url($url), 'code' => $code, 'msg' => $msg, 'file' => $file, 'line' => $line, 'fatal' => $fatal, 'type' => $type)); } }); App::fatal(function ($exception) { $url = Request::url(); $code = $exception->getCode(); $msg = $exception->getMessage(); $file = $exception->getFile(); $line = $exception->getLine(); $file_in_db = $file; $line_in_db = $line; $fatal = 1; if (!Error::whereRaw("url = '{$url}' and code = '{$code}' and file = '{$file_in_db}' and line = {$line_in_db}")->exists()) { $type = str_contains($msg, "SQL") ? "mysql" : "php"; Error::create(array('url' => url($url), 'code' => $code, 'msg' => $msg, 'file' => $file, 'line' => $line, 'fatal' => $fatal, 'type' => $type)); } }); App::missing(function ($exception) { $page_title = "page 404 :("; $article = Article::where('name', '=', '404')->get()->first(); if (!$article) { return Response::view('frontend.article.alternative-404-page', compact('page_title'), 404); } return Response::view('frontend.article.index', compact('article', 'page_title'), 404); }); /* |-------------------------------------------------------------------------- | Maintenance Mode Handler |-------------------------------------------------------------------------- |
/** * Set internal error message. */ protected function error($id, $args = [], $domain = null) { $this->lastError = Error::create($id, $args, $domain); }
}, 'getHeaders' => function () use(&$SERVER, &$headers) { if ($headers === null) { $headers = new Object(); foreach ($SERVER as $key => $value) { if (substr($key, 0, 5) === 'HTTP_') { $key = strtolower(substr($key, 5)); $key = str_replace('_', '-', $key); $headers->set($key, $value); } } } return $headers; }, 'getRemoteAddress' => function () use(&$SERVER) { return isset($SERVER['REMOTE_ADDR']) ? $SERVER['REMOTE_ADDR'] : '127.0.0.1'; }, 'read' => function ($bytes) { throw new Ex(Error::create('not implemented: Request.read()')); }); $request = new Object(); $request->setMethods($methods, true, false, true); return $request; }); Module::define('response', function () { $methods = array('writeHead' => function ($statusCode, $statusReason, $headers) { http_response_code($statusCode); $keys = $headers->getOwnKeys(true); foreach ($keys as $key) { $value = $headers->get($key); header($key . ": " . $value); } }, 'write' => function ($data) { $data = $data instanceof Buffer ? $data->raw : to_string($data);
/** * Creates the global constructor used in user-land * @return Func */ static function getGlobalConstructor() { $Function = new Func(function ($fn) { throw new Ex(Error::create('Cannot construct function at runtime.')); }); $Function->set('prototype', Func::$protoObject); $Function->setMethods(Func::$classMethods, true, false, true); return $Function; }
function update($postArray) { $db = new db(); $e = new Error(); if (User::isAdmin()) { $genreID = $db->sanitize_to_db($postArray['genreID']); if (!$this->isValidGenreID($postArray['genreID'])) { $e->add("Invalid genre specified"); } $name = $db->sanitize_to_db($postArray['name']); if ($name == '' || $name == null) { $e->add("You must specify a name for your band."); } $managerName = $db->sanitize_to_db($postArray['managerName']); $address1 = $db->sanitize_to_db($postArray['address1']); $address2 = $db->sanitize_to_db($postArray['address2']); $city = $db->sanitize_to_db($postArray['city']); $stateProvince = $db->sanitize_to_db($postArray['stateProvince']); if ($stateProvince == "??") { $stateProvince = $db->sanitize_to_db($postArray['stateProvinceOther']); } $postalCode = $db->sanitize_to_db($postArray['postalCode']); $bio = $db->sanitize_to_db($postArray['bio']); $miscellaneous = $db->sanitize_to_db($postArray['miscellaneous']); $country = $db->sanitize_to_db($postArray['country']); $defaultStateProvince = $db->sanitize_to_db($postArray['defaultStateProvince']); if ($defaultStateProvince == "??") { $defaultStateProvince = $db->sanitize_to_db($postArray['defaultStateProvince']); } $defaultCountry = $db->sanitize_to_db($postArray['defaultCountry']); $defaultCity = $db->sanitize_to_db($postArray['defaultCity']); $description = $db->sanitize_to_db($postArray['description']); if ($e->hasErrors()) { return $e; } $q = "delete from Band_Information"; $r = mysql_query($q); if (!$r) { return Error::MySQL(); } $q = "insert into Band_Information (name, managerName, address1, address2, city, stateProvince, postalCode, bio, miscellaneous, country, defaultStateProvince, defaultCountry, defaultCity, genreID, description) "; $q .= "values ('{$name}', '{$managerName}', '{$address1}', '{$address2}', '{$city}', '{$stateProvince}', '{$postalCode}', '{$bio}', '{$miscellaneous}', '{$country}', '{$defaultStateProvince}', '{$defaultCountry}', '{$defaultCity}', '{$genreID}', '{$description}')"; $r = mysql_query($q); // ping auditionrocks.com // aborted attempt at creating an audition directory /* include_class('xmlrpc'); $xc = new xmlrpc_client("/ping/", "www.auditionrocks.com"); $message = new xmlrpcmsg("audition.pingBack", array( new xmlrpcval($_SERVER["HTTP_HOST"] . SITE_WEB_DIRECTORY, "string"), new xmlrpcval($name, "string"), new xmlrpcval($bio, "string"), new xmlrpcval($genreID, "int"), new xmlrpcval($city, "string"), new xmlrpcval($stateProvince, "string"), new xmlrpcval($postalCode, "string"), new xmlrpcval($country, "string")) ); $response = $xc->send($message, 5, "POST"); */ if ($r) { return true; } else { return Error::create("An unexplained error occurred when trying to update your information."); } } }
/** * @param Object $obj * @param string $name * @return mixed * @throws Exception */ function call_method($obj, $name) { if ($obj === null || $obj === Object::$null) { throw new Ex(Error::create("Cannot read property '" . $name . "' of " . to_string($obj))); } $obj = objectify($obj); $fn = $obj->get($name); if (!$fn instanceof Func) { throw new Ex(Error::create(_typeof($fn) . " is not a function")); } $args = array_slice(func_get_args(), 2); return $fn->apply($obj, $args); }
function validateMediaOperation($opType = "ADD", $mediaObject = null) { // called automatically by the m2 functions that add media, when passed the object // opType allows us to distinguish between adding, editing, updating, etc... but most times // the same check will work for all operation types if ($opType == "RESCAN") { // non-admins can't delete, only deactivate if (!User::isAdmin()) { return Error::create('Only an admin user may rescan media.'); } else { return true; } } else { if (!User::isAdmin()) { return Error::create('Only an admin user may add, delete, activate or deactivate show media.'); } else { return true; } } }
//fallback for if set_error_handler didn't do it's thing if ($result === false) { $helpers['throwError']('EIO', $fullPath); } }, 'createReadStream' => function ($path, $opts = null) use(&$helpers, &$ReadStream) { return $ReadStream->construct($path, $opts); }, 'createWriteStream' => function ($path, $opts = null) use(&$helpers, &$WriteStream) { return $WriteStream->construct($path, $opts); }); $helpers = array('basePath' => getcwd(), 'ERR_MAP' => array('EACCES' => "EACCES, permission denied", 'EBADF' => "EBADF, bad file descriptor", 'EEXIST' => "EEXIST, file already exists", 'EIO' => "EIO, input/output error", 'ENOENT' => "ENOENT, no such file or directory", 'ENOTDIR' => "ENOTDIR, not a directory", 'ENOTEMPTY' => "ENOTEMPTY, directory not empty", 'EPERM' => "EPERM, operation not permitted", 'EISDIR' => "EISDIR, is a directory"), 'throwError' => function ($code, $paths = array(), $framesToPop = 0) use(&$helpers) { $message = $helpers['ERR_MAP'][$code]; $paths = is_array($paths) ? $paths : array($paths); foreach ($paths as $path) { $message .= " '" . $helpers['reverseMapPath']($path) . "'"; } $err = Error::create($message, $framesToPop + 1); $err->set('code', $code); throw new Ex($err); }, 'handleException' => function ($ex, $paths = array()) use(&$helpers) { $message = $ex->getMessage(); $paths = is_array($paths) ? $paths : array($paths); //get the error message with the path(s) removed. this prevents words // in the path from effecting our parsing below. foreach ($paths as $path) { $message = str_replace($path, '', $message); } $message = trim(array_slice(explode(':', $message), -1)[0]); if (strpos($message, 'No such file or directory') !== false) { $helpers['throwError']('ENOENT', $paths, 1); } else { if (strpos($message, 'Permission denied') !== false) {
function setupStreaming() { include_class('config'); $conf = new Config(); $streamingAudioFilesPath = $conf->getSetting('streamingAudioFilesPath'); $streamingAudioServerURL = $conf->getSetting('streamingAudioServerURL'); $filename = $this->getProtectedFilename(); if ($filename && file_exists($streamingAudioFilesPath . '/' . $filename)) { return true; } if ($streamingAudioFilesPath && !file_exists($streamingAudioFilesPath . '/')) { return Error::create("Streaming audio directory either undefined or cannot be found."); } // Create a protected filename $prFilename = time() . $this->filename; $origPointer = SITE_FULL_DIRECTORY . MEDIA_ORIGINALS_DIRECTORY . '/' . date('Ymd', strtotime($this->date_time)) . '/' . $this->filename_original; $newPointer = $streamingAudioFilesPath . '/' . $prFilename; $res = @copy($origPointer, $newPointer); if (!$res) { return Error::create("Unable to copy audio file to streaming audio directory"); } $res2 = chmod($origPointer, "000"); // protect original file $q = "update DarkRoom_Media_to_Areas set protected_filename = '{$prFilename}' where ID = '{$this->ID}'"; $r = @mysql_query($q); if (!$r) { return Error::MySQL(); } else { return true; } }
function process($action, $force_ajax = false) { global $app; $language = APP_DEFAULT_LANGUAGE; if (!isset($action) || $action == "") { $action = ""; if (APP_USE_LANGUAGE && APP_USER_URL_LANGUAGE) { //$action .= APP_DEFAULT_LANGUAGE."/"; } $action .= APP_DEFAULT_ACTION; } if (APP_CONTROLLER) { import('core.Application'); //'application.controllers.'. import(strtolower(APP_CONTROLLER)); $appClass = APP_CONTROLLER . "Application"; $app = new $appClass(); // FIXME: Sacar template //if(isset($template)) $app->setTemplate($template); } if ($action) { if (APP_USE_SESSIONS) { import("persistence.Session"); if (APP_USE_CART) { import("data.Cart"); } Session::start(APP_INSTANCE_NAME); } $actionElements = explode(APP_PATH_SEPARATOR, APP_PATH_COMPONENTS); $actionArray = explode(APP_PATH_SEPARATOR, $action); for ($pe = 0; $pe < count($actionElements); $pe++) { $element = strtolower($actionElements[$pe]); if ($element == "*") { break; } if (count($actionArray) > 0) { ${$element} = array_shift($actionArray); //echo $element." = ".$$element."<br/>"; } } if (isset($language) && APP_USE_LANGUAGE) { $GLOBALS[APP_INSTANCE_NAME . ".LANGUAGE"] = $language; $app->setLanguage($language); } /*$controller = $actionArray[0]; //$className = $actionArray[0]; $class = $actionArray[0]."Controller"; $method = (count($actionArray)>1) ? $actionArray[1] : "index";*/ if ($controller == "") { $controller = APP_DEFAULT_ACTION; } $class = $controller . "Controller"; if (!isset($method)) { $method = "index"; } $params = array(); for ($i = 0; $i < count($actionArray); $i++) { array_push($params, $actionArray[$i]); } //'application.controllers.'. import(strtolower($controller)); // TODO: Sacar la referencia de template /*if(defined('APP_MASTER_VIEW') || true){ import("framework.view.Template"); $template = new Template(APP_MASTER_VIEW); }*/ // Start Application if (isset($app)) { $app->onAppStart(array($controller, $method, $params)); } if (class_exists($class)) { $process = new $class($app); // FIXME : en mac se necesita el & 4.1 // FIXME: sacar //if(isset($template) || true) $process->setTemplate($template); // Application security $canExecute = TRUE; if (APP_USE_SECURITY) { $securityMethod = "getCredentials"; if (APP_CUSTOM_SECURITY_HANDLER) { $securityMethod = APP_CUSTOM_SECURITY_HANDLER; } if (array_key_exists($method, $process->accessLevels)) { $access_level = $process->accessLevels[$method]; } else { if (array_key_exists("default", $process->accessLevels)) { $access_level = $process->accessLevels["default"]; } else { $access_level = APP_DEFAULT_SECURITY_LEVEL; } } $canExecute = $app->{$securityMethod}($access_level, $action); } if ($canExecute) { if (method_exists($class, $method)) { $render = call_user_func_array(array(&$process, $method), $params); } else { $render = "error404"; } } else { $accessDeniedMethod = APP_ACCESS_DENIED_HANDLER; //echo $accessDeniedMethod." - ".$action; $render = $app->{$accessDeniedMethod}($action); //,APP_ACCESS_DENIED_MESSAGE);//APP_ACCESS_DENIED_MESSAGE, //$render = TRUE; } } else { Error::create("No se encontro la Clase {$class}"); $render = "error404"; } // Exit Application MateApplication::$endTime = microtime(); if (isset($app)) { $app->onAppExit($render); } } /*$GLOBALS["application_endTime"] = Timer::get(); if(APP_DEBUG_MODE) $template->set("debug",Application::renderDebug());*/ //if(isset($template) && !$process->noRender) echo $template->render(); }