Ejemplo n.º 1
0
 function controller_settings(&$args, $output = "inline")
 {
     $cfg = $this->root->cfg->FlattenConfig($this->root->cfg->LoadServers($this->root->locations["config"] . "/servers.ini", false));
     $vars["tfdev"] = !empty($_COOKIE["tf-dev"]) ? json_decode($_COOKIE["tf-dev"], true) : array();
     if (!empty($args["clear"])) {
         Logger::Info("Cleared dev settings");
         setcookie("tf-dev", NULL, 0, "/");
         $vars["tfdev"] = array();
         $this->root->cfg->servers = $cfg;
     }
     if (!empty($args["settings"])) {
         $diff_orig = array_diff_assoc_recursive($args["settings"], $cfg);
         $diff_curr = array_diff_assoc_recursive($args["settings"], $this->root->cfg->FlattenConfig($this->root->cfg->servers));
         $vars["tfdev"]["serveroverrides"] = $diff_orig;
         setcookie("tf-dev", json_encode($vars["tfdev"]), time() + 86400 * 365, "/");
         // dev cookie persists for a year
         if (!empty($diff_curr)) {
             foreach ($diff_curr as $setting => $value) {
                 Logger::Info("Override setting: {$setting} = '{$value}'");
                 $this->root->cfg->AppendSetting($this->root->cfg->servers, $setting, $value);
             }
         } else {
             Logger::Error("No config differences!");
         }
     }
     $vars["settings"] = $this->root->cfg->FlattenConfig($this->root->cfg->servers);
     $vars["container"] = $output == "html";
     $ret = $this->GetComponentResponse("./settings.tpl", $vars);
     if ($output == "ajax") {
         $ret = array("tf_debug_tab_settings" => $ret);
     }
     return $ret;
 }
Ejemplo n.º 2
0
 static function LoadModel($model)
 {
     if (isset($this) && $this instanceof OrmManager) {
         $me = $this;
     } else {
         $me = self::singleton();
     }
     if (!$me->outlet) {
         return;
     }
     $models = explode(",", $model);
     //print_pre($models);
     $ret = array();
     foreach ($models as $model) {
         $ormmodel = new OrmModel($model);
         $ormmodel->LoadModel();
         $ret[$model] = $ormmodel;
         if (!empty($ormmodel->classes)) {
             $foo = object_to_array($ormmodel->classes);
             try {
                 $me->outlet->getConfig()->addEntities($foo);
             } catch (Exception $e) {
                 Logger::Error("OrmManager: " . $e->GetMessage());
             }
         }
     }
     $me->outlet->createClasses();
     $me->outlet->createProxies();
     return $ret;
 }
Ejemplo n.º 3
0
 public function setContents($value)
 {
     System::ensureDir(dirname($this->filename_cache));
     if (!$this->isWritable()) {
         Logger::Error($this->filename_cache . " is not writable");
         return;
     }
     Logger::Debug("Write cache {$this->filename_cache}");
     file_put_contents($this->filename_cache, $value);
 }
Ejemplo n.º 4
0
 function lock($f3)
 {
     if ($f3->exists('GET.newLockStatus')) {
         try {
             $db = $f3->get('db');
             $newLockStatus = $f3->get('GET.newLockStatus');
             Logger::Info($f3, "AdminGet.lock", "Setting lock setting to {$newLockStatus}");
             DbWrapper::updateEinstellung($db, 'isLocked', $newLockStatus);
         } catch (Exception $e) {
             Logger::Error($f3, "AdminGet.lock", "Error: {$e->getMessage()}");
         }
     }
     $f3->reroute('/admin/index');
 }
Ejemplo n.º 5
0
 function remove($f3, $params)
 {
     $this->ensureAdmin($f3);
     $lehrerId = $params['id'];
     if ($f3->exists('POST.zeitId')) {
         try {
             $zeitId = $f3->get('POST.zeitId');
             Logger::Info($f3, "AdminPost.remove", "Lehrer: {$lehrerId}, Zeit: {$zeitId}");
             DbWrapper::deleteSperrung($f3->get('db'), $lehrerId, $zeitId);
         } catch (Exception $e) {
             Logger::Error($f3, "AdminPost.remove", "Error: {$e->getMessage()}");
         }
     }
     $f3->reroute('/admin/absences/' . $lehrerId);
 }
Ejemplo n.º 6
0
 function release($f3, $params)
 {
     $lehrerId = $params['id'];
     if ($f3->exists('POST.zeitId')) {
         try {
             $zeitId = $f3->get('POST.zeitId');
             $userId = $f3->get('COOKIE.user_id');
             Logger::Info($f3, "LehrerPost.release", "Lehrer: {$lehrerId}, Zeit: {$zeitId}, User: {$userId}");
             DbWrapper::deleteReservation($f3->get('db'), $lehrerId, $zeitId, $userId);
         } catch (Exception $e) {
             Logger::Error($f3, "LehrerPost.release", "Lehrer: {$lehrerId}, Error: {$e->getMessage()}");
         }
     }
     $f3->reroute('/lehrer/' . $lehrerId);
 }
Ejemplo n.º 7
0
 function login($f3)
 {
     if ($f3->exists('POST.schueler_name')) {
         $schuelerName = $f3->get('POST.schueler_name');
         try {
             $schuelerId = DbWrapper::getSchuelerIdByName($f3->get('db'), $schuelerName);
             Logger::Info($f3, "UserPost.login", "Name: {$schuelerName}, Id: {$schuelerId}");
             $f3->set('COOKIE.user_id', $schuelerId);
             $f3->set('COOKIE.user_name', $schuelerName);
             $f3->reroute('/');
         } catch (Exception $e) {
             Logger::Error($f3, "UserPost.login", "Name: {$schuelerName}, Error: {$e->getMessage()}");
             $f3->reroute('/login');
         }
     } else {
         $f3->reroute('/login');
     }
 }
Ejemplo n.º 8
0
 function Query($querid, $query, $postfields = NULL, $extras = NULL)
 {
     if (!empty($query) && preg_match("/^https?:\\/\\//", $query)) {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $query);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         if ($postfields) {
             #        $custom_request="POST /boomsvc30/SimpleTxEmail.asmx HTTP/1.1";
             #        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $custom_request);
             curl_setopt($ch, CURLOPT_POST, 1);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
         } else {
             curl_setopt($ch, CURLOPT_HTTPGET, 1);
         }
         if ($extras['timeout']) {
             curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $extras['timeout']);
         }
         if ($extras['headers']) {
             curl_setopt($ch, CURLOPT_HEADER, 1);
             curl_setopt($ch, CURLOPT_HTTPHEADER, array($extras['headers']));
         } else {
             curl_setopt($ch, CURLOPT_HEADER, 0);
         }
         #echo "[QUERY]".$query."[QUERY]";
         #echo "[POSTFIELDS]".$postfields ."[POSTFIELDS]";
         #echo "[HEADERS]".$extras['headers']."[HEADERS]";
         Logger::Notice("Remotefile Wrapper requesting URL: {$query}");
         if (!empty($postfields)) {
             Logger::Debug($postfields);
         }
         if (!empty($extras['headers'])) {
             Logger::Debug($extras['headers']);
         }
         $ret = curl_exec($ch);
         if (curl_errno($ch)) {
             $ret = curl_errno($ch) . "<br />" . curl_error($ch);
             Logger::Error($ret);
         }
         curl_close($ch);
     }
     #echo "[RETURN]".($ret)."[RETURN]";
     return $ret;
 }
Ejemplo n.º 9
0
 public function handleCallback()
 {
     if ($this->getLocalAccessToken()) {
         return true;
     }
     if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {
         try {
             $consumer = new Zend_Oauth_Consumer($this->config);
             $token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
             $this->accessToken = serialize($token);
             $_SESSION['TWITTER_ACCESS_TOKEN'] = $this->accessToken;
             unset($_SESSION['TWITTER_REQUEST_TOKEN']);
             return true;
         } catch (Exception $e) {
             Logger::Error('Twitter: handleCallback failed: ' . $e->getMessage());
             return false;
         }
     }
     return false;
 }
Ejemplo n.º 10
0
 public function Query($queryid, $query, $args = array())
 {
     Profiler::StartTimer("TwitterWrapper::Query()", 1);
     Profiler::StartTimer("TwitterWrapper::Query({$query})", 2);
     $method = $responseType = $authNeeded = $twitterCallback = null;
     if (array_key_exists('method', $args)) {
         $method = $args['method'];
         unset($args['method']);
     }
     if (array_key_exists('responseType', $args)) {
         $responseType = $args['responseType'];
         unset($args['responseType']);
     }
     if (array_key_exists('authNeeded', $args)) {
         $responseType = $args['authNeeded'];
         unset($args['authNeeded']);
     }
     try {
         if ($responseType && $authNeeded && $method) {
             $response = $this->twitter->api($query, $args, $responseType, $authNeeded, $method);
         } else {
             if ($responseType && $authNeeded) {
                 $response = $this->twitter->api($query, $args, $responseType, $authNeeded);
             } else {
                 if ($responseType) {
                     $response = $this->twitter->api($query, $args, $responseType);
                 } else {
                     $response = $this->twitter->api($query, $args);
                 }
             }
         }
     } catch (Exception $e) {
         Logger::Error($e->getMessage());
     }
     Profiler::StopTimer("TwitterWrapper::Query()");
     Profiler::StopTimer("TwitterWrapper::Query({$query})");
     return $response;
 }
Ejemplo n.º 11
0
 /**
  * Load a specific config from the database, without walking the heirarchy
  *
  * @param string $name name of config to load
  * @return array
  */
 public function Load($name, $role)
 {
     Profiler::StartTimer("Config::Load()");
     $data = DataManager::singleton();
     $ret = array();
     $this->name = $name;
     $this->role = $role;
     $ret = $this->GetCobrandidAndRevision();
     if (!empty($ret)) {
         $result_config = DataManager::Query("db.config.cobrand_config.{$name}.{$role}", "SELECT name,value FROM config.cobrand_config WHERE cobrandid=:cobrandid and role=:role ORDER BY name", array(":cobrandid" => $ret["cobrandid"], ":role" => $role));
         if ($result_config && count($result_config->rows) > 0) {
             $settings = array();
             foreach ($result_config->rows as $config_obj) {
                 $settings[$config_obj->name] = $config_obj->value;
             }
             array_set_multi($ret, $settings);
             $this->config = $ret;
         }
     } else {
         Logger::Error("Could not find config '{$name}'");
     }
     Profiler::StopTimer("Config::Load()");
     //print_pre($ret);
     return $ret;
 }
Ejemplo n.º 12
0
 function CacheFlush()
 {
     if ($this->caches["memcache"]["data"]) {
         Logger::Error("Flushing all memcache data");
         $this->caches["memcache"]["data"]->flush();
         return true;
     }
     return false;
 }
Ejemplo n.º 13
0
 function &QueryFetch($queryid, $table, $where = NULL, $extra = NULL)
 {
     $key = $table;
     if ($where !== NULL) {
         $key .= "." . $where;
     }
     $cachedresult = $this->cache->get($key);
     if ($cachedresult) {
         if (is_string($cachedresult)) {
             $ret = unserialize($cachedresult);
         } else {
             if (is_array($cachedresult)) {
                 foreach ($cachedresult as $k => $v) {
                     $ret[$k] = unserialize($v);
                 }
             } else {
                 Logger::Error("Invalid datatype for '%s' in memcache - expected serialized string, found %s", $key, gettype($cachedresult));
             }
         }
     }
     return $ret;
 }
Ejemplo n.º 14
0
 /**
  * @param id_problema int el id del problema a resolver
  * @param id_concurso int el id del concurso si es que este run pertenece a un concurso
  * @param lang String el identificador del lenguaje ( c,cpp,java,py,php,pl)
  * @param plain_source String 
  *
  * */
 public static function nuevo($request)
 {
     if (!c_sesion::isLoggedIn()) {
         Logger::warn("Se intento enviar una ejecucion sin sesion");
         return array("result" => "error", "reason" => "Debes iniciar sesion para poder enviar problemas.");
     }
     if (!(isset($request['id_problema']) && isset($request['lang']))) {
         return array("result" => "error", "reason" => "Faltan parametros (id_problema y lang)");
     }
     if (empty($_FILES) && !isset($request["plain_source"])) {
         return array("result" => "error", "reason" => "No se envio el codigo fuente.");
     }
     $usuarioArray = c_sesion::usuarioActual();
     $usuario = $usuarioArray["userID"];
     $id_problema = stripslashes($request["id_problema"]);
     $lang = stripslashes($request["lang"]);
     if (isset($request["id_concurso"])) {
         $id_concurso = stripslashes($request["id_concurso"]);
     } else {
         $id_concurso = null;
     }
     // Revisar que pueda escribir el codigo fuente
     if (!is_dir(PATH_TO_CODIGOS)) {
         Logger::error("El directorio : " . PATH_TO_CODIGOS . ", no existe");
         return array("result" => "error", "reason" => "El directorio de codigos no existe.");
     }
     if (!is_writable(PATH_TO_CODIGOS)) {
         Logger::error("El directorio " . PATH_TO_CODIGOS . ", no esta accesible (writtable)");
         return array("result" => "error", "reason" => "No se puede escribir en el directorio de codigos.");
     }
     global $db;
     $sql = "select probID from Problema where BINARY ( probID = ?) ";
     $inputarray = array($request["id_problema"]);
     $resultado = $db->Execute($sql, $inputarray);
     if ($resultado->RecordCount() == 0) {
         return array("result" => "error", "reason" => "El problema no existe.");
     }
     // si el concurso no es publico, solo un admin puede enviar problemas
     $lang_desc = null;
     switch ($lang) {
         case "java":
             $lang_desc = "JAVA";
             break;
         case "c":
             $lang_desc = "C";
             break;
         case "cpp":
             $lang_desc = "C++";
             break;
         case "py":
             $lang_desc = "Python";
             break;
         case "cs":
             $lang_desc = "C#";
             break;
         case "pl":
             $lang_desc = "Perl";
             break;
         case "php":
             $lang_desc = "Php";
             break;
         default:
             return array("result" => "error", "reason" => "\"" . $lang . "\" no es un lenguaje reconocido por Teddy.");
     }
     if (isset($_SERVER["REMOTE_ADDR"])) {
         $ip = $_SERVER["REMOTE_ADDR"];
     } else {
         $ip = "0.0.0.0";
     }
     /**
      * @todo
      * - insertar un nuevo run y obtener el id insertado, como estado, hay que ponerle uploading
      **/
     if ($id_concurso === null) {
         $sql = "INSERT INTO Ejecucion (`userID`, `status`, `probID` , `remoteIP`, `LANG`, `fecha`  ) \n\t\t\t\t\t\t\t\t\tVALUES (?, 'WAITING', ?, ?, ?, ?);";
         $inputarray = array($usuario, $id_problema, $ip, $lang_desc, date("Y-m-d H:i:s", mktime(date("H"), date("i"))));
     } else {
         // vamos a verificar que el concurso este activo
         $sql = "SELECT CID FROM teddy.Concurso WHERE CID = ? AND NOW() between Inicio AND Final;";
         $inputarray = array($id_concurso);
         $resultado = $db->Execute($sql, $inputarray);
         if ($resultado->RecordCount() == 0) {
             return array("result" => "error", "reason" => "El concurso no esta activo.");
         }
         // vamos a verificar que el problema sea parte de este concurso
         $sql = "SELECT CID FROM teddy.Concurso WHERE CID = ? AND Problemas like ?;";
         $inputarray = array($id_concurso, "%{$id_problema}%");
         $resultado = $db->Execute($sql, $inputarray);
         if ($resultado->RecordCount() == 0) {
             return array("result" => "error", "reason" => "El problema no es parte del concurso.");
         }
         $sql = "INSERT INTO Ejecucion (`userID` ,`status`, `probID` , `remoteIP`, `LANG`, `Concurso`, `fecha`  ) \n\t\t\t\t\t\t\t\t\tVALUES (?, 'WAITING', ?, ?, ?, ?, ?);";
         $inputarray = array($usuario, $id_problema, $ip, $lang_desc, $id_concurso, date("Y-m-d H:i:s", mktime(date("H"), date("i"))));
     }
     $result = $db->Execute($sql, $inputarray);
     // Si hacemos esto $execID = $db->Insert_ID( ); hay un Overflow porque los ids son muy grandes
     $sql = "select execID from Ejecucion where ( userId = ? ) order by fecha DESC LIMIT 1";
     $inputarray = array($usuario);
     try {
         $resultado = $db->Execute($sql, $inputarray)->GetArray();
         $execID = $resultado[0]["execID"];
     } catch (exception $e) {
         Logger::error($e);
         return array("result" => "error", "reason" => "Error al hacer la consulta");
     }
     if (!empty($_FILES)) {
         if (!move_uploaded_file($_FILES['Filedata']['tmp_name'], PATH_TO_CODIGOS . $execID . "." . $lang)) {
             return array("result" => "error", "reason" => "Error al subir el archivo");
         }
     } else {
         // Crear un archivo y escribir el contenido
         if (file_put_contents(PATH_TO_CODIGOS . "/" . $execID . "." . $lang, $request['plain_source']) === false) {
             Logger::Error("file_put_contents() fallo, tal vez no puedo escribir en  :" . PATH_TO_CODIGOS);
             return array("result" => "error");
         }
     }
     Logger::info("Nueva ejecucion " . $execID);
     return array("result" => "ok", "execID" => $execID);
 }
Ejemplo n.º 15
0
 /**
  * Returns the memcache key value.
  *
  * @param string $key
  * @return mixed
  */
 protected function getData($key)
 {
     $diskcache = $this->getCachePaths($key);
     $ret = false;
     if (file_exists($diskcache["fullpath"])) {
         if (filemtime($diskcache["fullpath"]) < $this->lifetime) {
             Logger::Warn("Unlinking stale cachefile '" . $diskcache["fullpath"] . "'");
             unlink($diskcache["fullpath"]);
         } else {
             $fp = fopen($diskcache["fullpath"], "r");
             if (flock($fp, LOCK_SH)) {
                 //$cachedresult = file_get_contents($diskcache["fullpath"]);
                 $cachedresult = fread($fp, filesize($diskcache["fullpath"]));
                 flock($fp, LOCK_UN);
                 if (!empty($cachedresult)) {
                     Profiler::StartTimer("DataManager::Query() - load from cachefile");
                     Logger::Info("Loaded cached result for '%s' from file: '%s'", $key, $diskcache["fullpath"]);
                     $result = unserialize(gzdecode($cachedresult));
                     if ($result !== false) {
                         $ret = $result;
                     }
                     Profiler::StopTimer("DataManager::Query() - load from cachefile");
                 }
             } else {
                 Logger::Error("Failed to get shared lock for '%s' (%s)", $key, $diskcache["fullpath"]);
             }
         }
     }
     return $ret;
 }
Ejemplo n.º 16
0
if (($path = file_exists_in_path("smarty3/Smarty.class.php")) !== false) {
    // Smarty 3, global install
    $path .= "/smarty3";
    include_once "smarty3/Smarty.class.php";
} else {
    if (($path = file_exists_in_path("smarty/libs/Smarty.class.php")) !== false) {
        // Smarty 2, global install
        $path .= "/smarty/libs";
        include_once "smarty/libs/Smarty.class.php";
    } else {
        if (($path = file_exists_in_path("include/smarty/Smarty.class.php")) !== false) {
            // local install
            $path .= "/include/smarty";
            include_once "include/smarty/Smarty.class.php";
        } else {
            Logger::Error("Couldn't find Smarty include file");
            // Define a dummy Smarty class just so we don't die
            class Smarty
            {
                function assign()
                {
                }
                function assign_by_ref()
                {
                }
                function template_exists()
                {
                }
            }
        }
    }
Ejemplo n.º 17
0
 /**
  * Downloads a file from the folder uploads
  * @param string $file
  * @return void
  */
 public static function DownloadFile($file)
 {
     //This condition restricts downloads only for the uploads folder
     if (strpos($file, "/uploads/") !== false) {
         $finfo = finfo_open(FILEINFO_MIME_TYPE);
         $mime = finfo_file($finfo, $file);
         finfo_close($finfo);
         header("Content-Type: " . $mime);
         header('Content-Disposition: attachment; filename="' . basename($file) . '"');
         header('Content-Transfer-Encoding: binary');
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Pragma: no-cache');
         header('Content-Length: ' . filesize($file));
         ob_clean();
         flush();
         readfile($file);
     } else {
         Logger::Error("Error downloading a file. The file url is " . $file);
         RequestManager::RequestError();
         //Error on download, posible hacker attack...
     }
 }
Ejemplo n.º 18
0
 /**
  * Returns the memcache key value.
  *
  * @param string $key
  * @return mixed
  */
 protected function getData($key)
 {
     $ret = NULL;
     Profiler::StartTimer("MemcacheCache::getData()");
     Profiler::StartTimer("MemcacheCache::getData({$key})", 4);
     if (!empty($this->cache_obj)) {
         $cachedresult = $this->cache_obj->get($key);
         if ($cachedresult) {
             if (is_string($cachedresult)) {
                 $ret = unserialize($cachedresult);
             } else {
                 if (is_array($cachedresult)) {
                     foreach ($cachedresult as $k => $v) {
                         $ret[$k] = unserialize($v);
                     }
                 } else {
                     Logger::Error("Invalid datatype for '%s' in memcache - expected serialized string, found %s", $key, gettype($cachedresult));
                 }
             }
         }
     }
     Profiler::StopTimer("MemcacheCache::getData()");
     Profiler::StopTimer("MemcacheCache::getData({$key})");
     return $ret;
 }
Ejemplo n.º 19
0
 public function controller_content($args)
 {
     $tplfile = "./content.tpl";
     $content = $args["content"];
     if ($content instanceof ComponentResponse) {
         if ($content->data instanceof Component) {
             Logger::Error("html.content - unexpected Component in content argument");
             $content = array();
         } else {
             if (!empty($content->data["content"])) {
                 $content = $content->data["content"];
             } else {
                 $vars = $content->data;
                 $tplfile = $content->getTemplate();
                 $content = NULL;
             }
         }
     }
     if (!empty($content)) {
         if (is_array($content)) {
             if (!empty($content["component"])) {
                 $vars["contentcomponent"] = $content["component"];
                 $vars["contentargs"] = any($content["args"], array());
             } else {
                 if (!empty($content["template"])) {
                     $vars = any($content["data"], array());
                     $tplfile = $content["template"];
                 }
             }
         } else {
             $vars["content"] = $content;
         }
     }
     return $this->GetTemplate($tplfile, $vars);
 }
Ejemplo n.º 20
0
 function array_set_multi(&$arr, $values, $keys = NULL)
 {
     Profiler::StartTimer("array_set_multi");
     if ($keys === NULL) {
         $tmp = array_keys($values);
         $keys = array_combine($tmp, $tmp);
     }
     asort($keys, SORT_STRING);
     //print_pre($keys);
     $subelements = array();
     foreach ($keys as $key => $fullkey) {
         list($topkey, $subkey) = explode(".", $key, 2);
         if (empty($subkey)) {
             // If we're already at a leaf, just set it
             //print "set $topkey<br />";
             $arr[$topkey] = $values[$fullkey];
         } else {
             if (isset($arr[$topkey]) && !is_array($arr[$topkey])) {
                 //print "skip $topkey<br />";
                 Logger::Error("array_set_multi: Failed to set {$fullkey}: already a node?");
                 continue;
             } else {
                 if (!isset($arr[$topkey])) {
                     $arr[$topkey] = array();
                 }
                 if (strpos($subkey, ".") === FALSE) {
                     // Shortcut for leaf nodes to cut down on recursion (same effect as leaf case above)
                     $arr[$topkey][$subkey] = $values[$fullkey];
                 } else {
                     $subelements[$topkey][$subkey] = $fullkey;
                 }
             }
         }
     }
     foreach ($subelements as $k => $v) {
         array_set_multi($arr[$k], $values, $v);
     }
     Profiler::StopTimer("array_set_multi");
 }
Ejemplo n.º 21
0
 /**
  * Invokes the class method stored on database
  * @param $Request The request object
  * @return void
  */
 private static function InvokeMethod($Request)
 {
     //Check if the class exist in a file inside the controllers folder
     //Note the class_name must be same has the file name to prevent security issues
     $FileDirectory = dirname(dirname(__FILE__)) . "/controllers/" . $Request->Get->class_name . ".php";
     if (file_exists($FileDirectory)) {
         require_once $FileDirectory;
         if (method_exists($Request->Get->class_name, $Request->Get->function_name)) {
             call_user_func(array($Request->Get->class_name, $Request->Get->function_name));
         } else {
             Logger::Error("Request error: The requested function doesn't exist. Requested class_name:" . $Request->Get->class_name . " - function_name:" . $Request->Get->function_name);
             Dialog::RequestClassOrMethodNotExist();
         }
     } else {
         $class = json_decode(json_encode(SystemQueries::GetClass($Request->Get->class_name)));
         if (count($class) === 0) {
             Logger::Error("Request error: The requested class_name doesn't exist. Requested class_name:" . $Request->Get->class_name . " - function_name:" . $Request->Get->function_name);
             Dialog::RequestClassOrMethodNotExist();
         } else {
             if (is_callable(array($class->class_name, $Request->Get->function_name), true)) {
                 try {
                     eval("?>" . $class->class_code);
                     if (method_exists($class->class_name, $Request->Get->function_name)) {
                         call_user_func(array($class->class_name, $Request->Get->function_name));
                     } else {
                         Logger::Error("Request error: The requested function doesn't exist. Requested class_name:" . $Request->Get->class_name . " - function_name:" . $Request->Get->function_name);
                         Dialog::RequestClassOrMethodNotExist();
                     }
                 } catch (Exception $e) {
                     Logger::Error("Request error: The class code could not be interpreted at runtime. Please check that your code is free of errors. Requested class_name:" . $Request->Get->class_name . " - function_name:" . $Request->Get->function_name);
                     Dialog::RequestRuntimeErrorOnCompilingCode();
                 }
             } else {
                 Logger::Error("Request error: The requested function name can't be used to call a method. Requested class_name:" . $Request->Get->class_name . " - function_name:" . $Request->Get->function_name);
                 Dialog::RequestClassOrMethodNotExist();
             }
         }
     }
 }
Ejemplo n.º 22
0
 /**
  * Checks if the datatype is a double, float, decimal
  * @param input The input object
  * @return boolean
  */
 public static function DoubleFloat($input)
 {
     if ($input->input_data_type == "DECIMAL" || $input->input_data_type == "DEC" || $input->input_data_type == "FLOAT" || $input->input_data_type == "DOUBLE" || $input->input_data_type == "NUMERIC" || $input->input_data_type == "DOUBLE PRECISION" || $input->input_data_type == "REAL") {
         if (!is_float((double) $_POST[$input->input_name])) {
             Logger::Request();
             Logger::Error($input->input_name . " is not a float or double. " . $input->input_name . " = " . $_POST[$input->input_name]);
             Dialog::RequestUnexpectedValueTypeOrFormat();
         }
         return true;
     }
     return false;
 }
Ejemplo n.º 23
0
 /**
  * This method is used to do a select query with bind variables.
  * This is the preferred method to use when talking to the DB for
  * queries to help aleviate sql injection issues.  If the mysqli
  * interface is loaded, then it will speed things up a bit.
  *
  * Instead of manually placing values in the query, use a ?
  * and then pass in the values in the bind_vars array.
  *
  * ie.
  *   select * from foo where blah='test1' and blah2='test2';
  *
  *   is replaced by
  *
  *   select * from foo where blah=? and blah2=?
  *   $bind_vars = array('test1', 'test2');
  *
  * @param string the sql query with the bind vars
  * @param array the array of bind vars
  * @return DataBaseStatement
  */
 public function queryBind($sql, $bind_vars = array())
 {
     if (!empty($this->db)) {
         // Prepare the query and bind all of the values.
         try {
             $stmt = $this->db->prepare($sql);
             $stmt->setFetchMode(PDO::FETCH_OBJ);
         } catch (PDOException $e) {
             //throw new DataBaseException($e->getMessage(), $e->getCode(), $sql, $bind_vars=array());
             Logger::Error($e->getMessage());
             throw $e;
         }
         // bind the parameters
         if (!empty($bind_vars)) {
             $i = 1;
             foreach ($bind_vars as $key => $value) {
                 // determine if this is binding by ? or by :name
                 $key = $key[0] == ":" ? $key : $i;
                 $stmt->bindValue($key, $value);
                 $i++;
             }
         }
         // and now execute it!
         if (!empty($stmt)) {
             try {
                 $stmt->execute();
             } catch (PDOException $e) {
                 // must have been something wrong in the constructed SQL
                 //throw new DataBaseException($e->getMessage(), DataBaseException::QUERY_EXECUTE_FAILED, $sql, $bind_vars);
                 throw $e;
             }
         }
     }
     return $stmt;
 }
Ejemplo n.º 24
0
 /**
  * Returns the memcache key value.
  *
  * @param string $key
  * @return mixed
  */
 protected function getData($key)
 {
     $ret = false;
     if (!$this->enabled) {
         return;
     }
     $cachedresult = apc_fetch($key);
     if ($cachedresult !== false) {
         if (is_string($cachedresult)) {
             $ret = unserialize($cachedresult);
         } else {
             if (is_array($cachedresult)) {
                 foreach ($cachedresult as $k => $v) {
                     $ret[$k] = unserialize($v);
                 }
             } else {
                 Logger::Error("Invalid datatype for '%s' in APC - expected serialized string, found %s", $key, gettype($cachedresult));
             }
         }
     }
     return $ret;
 }