示例#1
0
 public function __construct()
 {
     $this->socket = socket_create(AF_INET, SOCK_STREAM, 0);
     if ($this->socket < 0) {
         sendError('socket_create() failed: reason: ' . socket_strerror($this->socket));
     }
 }
示例#2
0
function getConnection()
{
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if ($mysqli->connect_errno) {
        sendError("Error al intentar establecer la coneccion a la base");
    } else {
        $mysqli->query("SET NAMES 'utf8'");
        return $mysqli;
    }
}
示例#3
0
function listCategorias()
{
    $c = getConnection();
    $query = "SELECT * FROM categorias";
    $categorias = array();
    if ($resultado = $c->query($query)) {
        while ($fila = $resultado->fetch_assoc()) {
            $categorias[] = $fila;
        }
        $resultado->free();
        sendResult(array("categorias" => $categorias), "Ok");
    } else {
        sendError("No se encontraron resultados");
    }
}
示例#4
0
function mysql_session_write($SessionID, $val)
{
    #	dbg("writing session info for $SessionID");
    $SessionTableName = $GLOBALS["SessionTableName"];
    $SessionID = addslashes($SessionID);
    $val = addslashes($val);
    $SessionExists = sql_fetch_row_query("select count(*) from  {$SessionTableName} where sessionid = '{$SessionID}'");
    if ($SessionExists[0] == 0) {
        $retval = sql_query(sprintf('insert into %s (sessionid,lastactive,data) values("%s",UNIX_TIMESTAMP(NOW()),"%s")', $SessionTableName, $SessionID, $val));
    } else {
        $retval = sql_query(sprintf('update %s SET data = "%s", lastactive = UNIX_TIMESTAMP(NOW()) where sessionid = "%s"', $SessionTableName, $val, $SessionID));
        if (sql_affected_rows() < 0) {
            sendError("unable to update session data for session {$SessionID}");
        }
    }
    return $retval;
}
 public function onData($json, $client)
 {
     $data = json_decode($json, true);
     if ($data === NULL || !isset($data['type']) || !isset($this->clienId2room[$client->getId()]) && $data['type'] !== "participate") {
         $this->sendError("不正なデータを受信しました:無意味なメッセージ", $client);
         return;
     }
     try {
         switch ($data['type']) {
             case "participate":
                 if (!isset($data['roomId']) || !isset($data['userId'])) {
                     $this->sendError("ログインに必要な情報がたりません", $client);
                     return;
                 }
                 $data['roomId'] = trim($data['roomId']);
                 $data['userId'] = trim($data['userId']);
                 if (!isset($this->roomName2room[$data['roomId']])) {
                     $this->roomName2room[$data['roomId']] = new ChatRoom();
                 }
                 $this->clienId2room[$client->getId()] = $this->roomName2room[$data['roomId']];
                 $this->clienId2room[$client->getId()]->loginUser($client, $data['userId']);
                 break;
             case "message":
                 if (!isset($data['body'])) {
                     $this->sendError("不正なデータを受信しました:内容のないチャット送信", $client);
                     return;
                 }
                 $this->clienId2room[$client->getId()]->sendMessage($client, $data['body']);
                 break;
             case "logout":
                 $this->clienId2room[$client->getId()]->logoutUser($client);
                 unset($this->clienId2room[$client->getId()]);
                 break;
             default:
                 sendError("不正なデータを受信しました:無効な種類のメッセージ", $client);
                 return;
         }
     } catch (UserNotFoundException $e) {
         $this->sendError($e->getMessage(), $client);
         return;
     } catch (ConnectionAlreadyEstablishedException $e) {
         $this->sendError($e->getMessage(), $client);
         return;
     }
 }
示例#6
0
 /**
  * @return int
  */
 public static function verifyCurrentPathAccess()
 {
     if (!isset($_POST["path"]) || !is_numeric($_POST["path"])) {
         sendError(400);
     }
     $pathID = (int) $_POST["path"];
     $allowedPaths = self::getAllowedPaths();
     if (!isset($allowedPaths[$pathID])) {
         sendError(404);
     }
     return $pathID;
 }
            sendError('Your local password is not set. Use Create Account to set a new password.');
        }
        // Verify password.
        if (!empty($user_password) && check_encrypted_password($dbHandle, $username, $password)) {
            $result = $dbHandle->query("SELECT userID,permissions FROM users WHERE username="******"DELETE FROM logins" . " WHERE sessionID={$session_id_q} AND userID={$user_id_q}");
示例#8
0
            $error = 'Le numéro de poste doit être composé de 5 chiffres et commencé par 5 ou 9';
            break;
        case 'idPavillon':
            $pavillon = verifyPavillon(substr($info, 0, 1));
            $etage = verifyEtage(substr($info, 1));
            $boolError = $pavillon && $etage;
            $error = "Le pavillon ou l'étage est incorrect";
            break;
        case 'idLogiciel':
            $boolError = verifySoft($info);
            $error = "Le nom du logiciel ne peut pas contenir d'accents, ni de caractères spéciaux";
            break;
        default:
            throw new Exception("ID NON VALIDE");
    }
    if ($boolError === false) {
        sendError($error);
    }
} else {
    sendError("Le champs est vide");
}
/*
 * Cette fonction permet de retourner les erreurs
 */
function sendError($message)
{
    header("Content-Type : application/json");
    $erreur = array();
    $erreur["description"] = $message;
    echo json_encode($erreur);
}
示例#9
0
    if (isset($_POST['check-3'])) {
        $content .= '<li>Vinduespudsning</li>';
    }
    if (isset($_POST['check-4'])) {
        $content .= '<li>Havearbejde</li>';
    }
    if (isset($_POST['check-5'])) {
        $content .= '<li>Snerydning</li>';
    }
    if (isset($_POST['check-6'])) {
        $content .= '<li>Skadeservice</li>';
    }
    $content .= '</ul>';
}
if (isset($message) && !empty($message)) {
    $content .= '<p><strong>Tilføjet besked: </strong></p><hr>';
    $content .= nl2br($message);
    $content .= '<hr>';
}
$content .= '<p style="font-size:10px;color:#888;">(' . $name . ' er sat som afsender af denne email, så du kan svare direkte tilbage på den.)</p>';
require 'mail_footer.php';
$new_post_array = array('post_content' => $content_header_white . $content, 'post_title' => $new_post_title, 'post_status' => 'private', 'post_type' => 'email');
$new = wp_insert_post($new_post_array, true);
if (is_wp_error($new)) {
    sendError($new->get_error_message());
} else {
    $response['success'] = 'oprettet med id: ' . $new;
    echo json_encode($response);
}
sendEmail($email, $receiver, 'Ny besked fra kontaktformular', $content_header_white . $content);
sendEmail('*****@*****.**', $email, 'Tak for din henvendelse', $content_header . $content_extra . $content);
示例#10
0
function saveUserAttribute($userid, $attid, $data)
{
    global $usertable_prefix, $tables;
    # workaround for integration webbler/phplist
    if (!isset($usertable_prefix)) {
        $usertable_prefix = '';
    }
    if (!empty($tables["attribute"])) {
        $att_table = $usertable_prefix . $tables["attribute"];
        $user_att_table = $usertable_prefix . $tables["user_attribute"];
    } else {
        $att_table = $usertable_prefix . "attribute";
        $user_att_table = $usertable_prefix . "user_attribute";
    }
    if ($data["nodbsave"]) {
        dbg("Not saving {$attid}");
        return;
    }
    if (strtolower($data) == 'invalid attribute index') {
        return;
    }
    if ($attid == "emailcheck" || $attid == "passwordcheck") {
        dbg("Not saving {$attid}");
        return;
    }
    if (!$data["type"]) {
        $data["type"] = "textline";
    }
    if ($data["type"] == "static" || $data["type"] == "password" || $data['type'] == 'htmlpref') {
        Sql_Query(sprintf('update user set %s = "%s" where id = %d', $attid, $data["value"], $userid));
        if ($data["type"] == "password") {
            Sql_Query(sprintf('update user set passwordchanged = now() where id = %d', $userid));
        }
        return 1;
    }
    $attid_req = Sql_Fetch_Row_Query(sprintf('
    select id,type,tablename from %s where id = %d', $att_table, $attid));
    if (!$attid_req[0]) {
        $attid_req = Sql_Fetch_Row_Query(sprintf('
      select id,type,tablename from %s where name = "%s"', $att_table, $data["name"]));
        if (!$attid_req[0]) {
            if ($GLOBALS["config"]["autocreate_attributes"]) {
                Dbg("Creating new Attribute: " . $data["name"]);
                sendError("creating new attribute " . $data["name"]);
                $atttable = getNewAttributeTablename($data["name"]);
                Sql_Query(sprintf('insert into %s (name,type,tablename) values("%s","%s","%s")', $att_table, $data["name"], $data["type"], $atttable));
                $attid = Sql_Insert_Id();
            } else {
                dbg("Not creating new Attribute: " . $data["name"]);
                # sendError("Not creating new attribute ".$data["name"]);
            }
        } else {
            $attid = $attid_req[0];
            $atttable = $attid_req[2];
        }
    } else {
        $attid = $attid_req[0];
        $atttable = $attid_req[2];
    }
    if (!$atttable) {
        $atttable = getNewAttributeTablename($data["name"]);
        # fix attribute without tablename
        Sql_Query(sprintf('update %s set tablename ="%s" where id = %d', $att_table, $atttable, $attid));
        #   sendError("Attribute without Tablename $attid");
    }
    switch ($data["type"]) {
        case "static":
        case "password":
            Sql_Query(sprintf('update user set %s = "%s" where id = %d', $attid, $data["value"], $userid));
            break;
        case "select":
            $curval = Sql_Fetch_Row_Query(sprintf('select id from phplist_listattr_%s
        where name = "%s"', $atttable, $data["displayvalue"]), 1);
            if (!$curval[0] && $data['displayvalue'] && $data['displayvalue'] != '') {
                Sql_Query(sprintf('insert into phplist_listattr_%s (name) values("%s")', $atttable, $data["displayvalue"]));
                sendError("Added " . $data["displayvalue"] . " to {$atttable}");
                $valid = Sql_Insert_id();
            } else {
                $valid = $curval[0];
            }
            Sql_Query(sprintf('replace into %s (userid,attributeid,value)
        values(%d,%d,"%s")', $user_att_table, $userid, $attid, $valid));
            break;
        case 'avatar':
            if (is_array($_FILES)) {
                ## only avatars are files
                $formfield = 'attribute' . $attid . '_file';
                ## the name of the fileupload element
                if (!empty($_FILES[$formfield]['name'])) {
                    $tmpnam = $_FILES[$formfield]['tmp_name'];
                    move_uploaded_file($tmpnam, '/tmp/avatar' . $userid . '.jpg');
                    if (function_exists('resizeImageFile')) {
                        resizeImageFile('/tmp/avatar' . $userid . '.jpg', 250, 1);
                    }
                    $size = filesize('/tmp/avatar' . $userid . '.jpg');
                    #          dbg('New size: '.$size);
                    if ($size < MAX_AVATAR_SIZE) {
                        $avatar = file_get_contents('/tmp/avatar' . $userid . '.jpg');
                        Sql_Query(sprintf('replace into %s (userid,attributeid,value)
              values(%d,%d,"%s")', $user_att_table, $userid, $attid, base64_encode($avatar)));
                        unlink('/tmp/avatar' . $userid . '.jpg');
                    }
                }
            }
            break;
        default:
            Sql_Query(sprintf('replace into %s (userid,attributeid,value)
        values(%d,%d,"%s")', $user_att_table, $userid, $attid, $data["value"]));
            break;
    }
    return 1;
}
示例#11
0
function routeRequest($gpio)
{
    $method = $_SERVER['REQUEST_METHOD'];
    $request_uri = $_SERVER['REQUEST_URI'];
    $root = $_SERVER['DOCUMENT_ROOT'];
    $script = $_SERVER['SCRIPT_FILENAME'];
    $path = pathinfo($script);
    $context = substr($path['dirname'], strlen($root));
    $uri = substr($request_uri, strlen($context));
    $vars = explode('/', $uri);
    global $SERVER_VERSION;
    header("Server: " + $SERVER_VERSION);
    if ($method == "GET") {
        doGET($gpio, $vars);
    } else {
        if ($method == "POST") {
            doPOST($gpio, $vars);
        } else {
            sendError(405, "Not Allowed");
        }
    }
}
示例#12
0
    sendError(3);
}
//linkstats = 1 mean old link
if ($linkstatus == 1) {
    sendError(4);
}
//linkstats = 2 mean used link
if ($linkstatus == 2) {
    sendError(5);
}
//check if linktime has expiered i.e a day old
$curtime = time();
$cmptime = $linktime + 24 * 60 * 60;
if ($curtime > $cmptime) {
    snapUpdateLinkStatus($snapDbConn, $linkid, 1);
    sendError(3);
}
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>MeetOn SNAP - Reset Password</title>
	<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
	<link href="common/css/bootstrap.css" rel="stylesheet" type="text/css" />
	<link href="common/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
	<link href="postlogin/css/ionicons.min.css" rel="stylesheet" type="text/css" />
	<link href="prelogin/css/AdminLTE.css" rel="stylesheet" type="text/css" />
	<link href="common/css/skin-blue-light.min.css" rel="stylesheet" type="text/css" />
</head>
<body class="skin-blue-light" data-target="#scrollspy">
示例#13
0
 public function searchTextLayer($term)
 {
     $text_hits = array();
     // Convert wildcards.
     $term = str_replace('<?>', '_', $term);
     $term = str_replace('<*>', '%', $term);
     // Temporary SQLite storage.
     $temp_db = $this->pdf_cache_path . DIRECTORY_SEPARATOR . $this->file_name . '.sq3';
     /**
      * Database text storage is created by extractXMLText(), when a PDF is open
      * first time. When a PDF is being extracted, the PDF filename is written
      * in a log. This code checks if a PDF is not being extracted at this
      * moment, and delays the execution so that it continues after the database
      * storage has been created.
      */
     if (!is_file($temp_db)) {
         // Is it being created?
         if ($this->checkPDFLog($this->file_name . '.sq3')) {
             // Wait up to 30 sec.
             for ($i = 1; $i <= 60; $i++) {
                 if ($this->checkPDFLog($this->file_name . '.sq3')) {
                     usleep(500000);
                 }
             }
         } else {
             // File might have been deleted. Re-create it.
             $this->extractXMLText();
         }
     }
     // At this point, the database must exist.
     if (!file_exists($temp_db)) {
         sendError('Text storage not found.');
     }
     // Fetch text from the database (8 PDF pages).
     $dbHandle = database_connect($this->pdf_cache_path, $this->file_name);
     $term_q = $dbHandle->quote('%' . $term . '%');
     $result = $dbHandle->query("SELECT top,left,height,width,text,page_number" . " FROM texts WHERE text LIKE {$term_q} ORDER BY page_number ASC");
     // Compile search results.
     while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
         extract($row);
         $text_hits[] = array('p' => $page_number, 't' => $top, 'l' => $left, 'h' => $height, 'w' => $width, 'tx' => $text);
     }
     // If the result set is empty, check if there is any text at all.
     if (empty($text_hits)) {
         $result = $dbHandle->query("SELECT count(*) FROM texts");
         $count = $result->fetchColumn();
         if ($count == 0) {
             sendError('This PDF has no searchable text.');
         }
     }
     // If the result set is empty, the PDF has no text layer. It is allowed.
     return json_encode($text_hits);
 }
示例#14
0
文件: user.php 项目: riston/grid
<?php

// Detect if there was XHR request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $fields = array('row', 'column', 'text');
    $sqlFields = array('name', 'age', 'location');
    foreach ($fields as $field) {
        if (!isset($_POST[$field]) || strlen($_POST[$field]) <= 0) {
            sendError('No correct data');
            exit;
        }
    }
    $db = new mysqli('localhost', 'root', '', 'grid');
    $db->set_charset('utf8');
    if ($db->connect_errno) {
        sendError('Connect error');
        exit;
    }
    $userQuery = sprintf("UPDATE user SET %s='%s' WHERE user_id=%d", $sqlFields[intval($_POST['column'])], $db->real_escape_string($_POST['text']), $db->real_escape_string(intval($_POST['row'])));
    $stmt = $db->query($userQuery);
    if (!$stmt) {
        sendError('Update failed');
        exit;
    }
}
header('Location: index.php');
function sendError($message)
{
    header($_SERVER['SERVER_PROTOCOL'] . ' 320 ' . $message);
}
示例#15
0
文件: contact.php 项目: 72juju/Luna
    } else {
        $strHeaders = "From: " . $strUsername . "<" . $strEmail . ">\n";
        $strHeaders .= "Reply-To: " . $strUsername . "<" . $strEmail . ">\n";
        $strHeaders .= "Cc: " . $strUsername . "<" . $strEmail . ">\n";
        $strHeaders .= "X-Sender: " . $strUsername . "<" . $strEmail . ">\n";
        $strHeaders .= "X-Mailer: PHP/" . phpversion();
        $strHeaders .= "X-Priority: 1\n";
        $strHeaders .= "Return-Path: " . $strEmail . "\n";
        $strHeaders .= "MIME-Version: 1.0\r\n";
        $strHeaders .= "Content-Type: text/html; charset=iso-8859-1\n";
        $strMessage = wordwrap($strMessage, 70);
        $blnSent = mail($strContactEmail, $strSubject, $strMessage, $strHeaders);
        if ($blnSent) {
            echo "<center><h2>Thank you for contacting us, you will receive an email from us within the next 48 hours</h2></center>";
        } else {
            sendError('Failed to send email');
        }
    }
} else {
    ?>
	
<center>
<form class="form" name="form" method="post" action="<?php 
    echo $_SERVER['PHP_SELF'];
    ?>
">
       <input type="text" name="username" maxlength="10" placeholder="Enter Your Username">
       <input type="text" name="email" maxlength="25" placeholder="Enter A Valid Email">
       <input type="text" name="subject" maxlength="20" placeholder="Enter Your Subject">
       <textarea  name="comments" maxlength="500" cols="25" rows="6" placeholder="Enter Your Message"></textarea>
       <!--edit the site key to match yours for the captcha -->
示例#16
0
function signUp($db)
{
    if (!(isset($_GET['username']) || !isset($_GET['password']))) {
        //missing argument
        sendError("Missing either username or password");
        return;
    }
    $username = $_GET['username'];
    $returnArr = [];
    $pwHash = hash("md5", $_GET['password']);
    //Find out if the username already exists
    if (!($stmt = $db->prepare("SELECT userId FROM cs290_final_users WHERE userId = ?"))) {
        sendError("Prepare failed: (" . $db->errno . ") " . $db->error);
    }
    $result;
    $stmt->bind_param('s', $username);
    $stmt->bind_result($result);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        //username already exists
        $returnArr['usernameTaken'] = 1;
        echo json_encode($returnArr);
        return;
    }
    $stmt->close();
    //store the new username to the database
    if (!($stmt = $db->prepare("INSERT INTO cs290_final_users VALUES (?, ?)"))) {
        sendError("Prepare failed: (" . $db->errno . ") " . $db->error);
    }
    $stmt->bind_param('ss', $username, $pwHash);
    $stmt->execute();
    $stmt->close();
    $returnArr['signupSuccess'] = 1;
    $_SESSION['username'] = $username;
    echo json_encode($returnArr);
    return;
}
    $pdfHandler->createPageImage($_GET['page']);
} elseif (isset($_GET['renderthumbs']) && !empty($_GET['from'])) {
    // Create thumbs.
    $pdfHandler->createPageThumbs($_GET['from']);
} elseif (isset($_GET['renderbookmarks'])) {
    // Extract bookmarks.
    echo $pdfHandler->extractBookmarks();
} elseif (isset($_GET['rendertext'])) {
    // Extract text into database.
    $pdfHandler->extractXMLText();
} elseif (isset($_GET['gettextlayer']) && !empty($_GET['from'])) {
    // Get text from the database.
    echo $pdfHandler->getTextLayer($_GET['from']);
} elseif (isset($_GET['searchtextlayer'])) {
    if (empty($_GET['search_term'])) {
        sendError('No search term provided');
    }
    // Search text in the database.
    echo $pdfHandler->searchTextLayer($_GET['search_term']);
} elseif (isset($_GET['deleteannotation']) && !empty($_GET['type'])) {
    $dbids = array();
    if (!empty($_GET['dbids'])) {
        $dbids = $_GET['dbids'];
    }
    // Delete annotation.
    echo $pdfHandler->deletePDFAnnotation($_GET['type'], $dbids);
} elseif (isset($_GET['editannotation']) && !empty($_GET['dbid'])) {
    // Edit PDF note text.
    echo $pdfHandler->editPDFNote($_GET['dbid'], $_GET['text']);
} elseif (isset($_GET['savepdfnote']) && !empty($_GET['page']) && !empty($_GET['top']) && !empty($_GET['left'])) {
    // Save new PDF note.
示例#18
0
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
    # whats the point of a user handler when it only
    # passes notices. unfortunaltey other errors dont get passed
    # so this wont be called too often
    # 	dbg("User error: $errno, $errmsg");
    global $config;
    $time = date("d M Y H:i:s");
    // Get the error type from the error number
    $errortype = array(1 => "Error", 2 => "Warning", 4 => "Parsing Error", 8 => "Notice", 16 => "Core Error", 32 => "Core Warning", 64 => "Compile Error", 128 => "Compile Warning", 256 => "User Error", 512 => "User Warning", 1024 => "User Notice");
    $errlevel = $errortype[$errno];
    //Write error to log file (CSV format)
    if (!isset($config["error_log"])) {
        $config["error_log"] = '/tmp/' . $config["name"] . "_errors.csv";
    }
    if ($errno != 2 && $errno != 8) {
        //Terminate script if fatal error
        print "Sorry an error occurred: ({$errno})" . $errmsg;
        $errfile = fopen($config["error_log"], "a");
        fputs($errfile, "{$time}\t{$filename}\t{$linenum}\t({$errlevel})\t{$errmsg}\n");
        fclose($errfile);
        sendError($errno . " " . $errmsg . '
      	File: ' . $filename . '
        Line: ' . $linenum . '
        Vars: ' . $vars);
        #			LogError($errno." ".$errmsg);
        die("A fatal error has occured. Script execution has been aborted");
    }
    return 1;
}
示例#19
0
<?php

$page = "plugin";
$page_title = "Plugin Page";
$auth_name = 'login';
$b3_conn = true;
// this page needs to connect to the B3 database
$pagination = false;
// this page requires the pagination part of the footer
$query_normal = false;
require 'inc.php';
if (!isset($_GET['pl']) || $_GET['pl'] == '') {
    sendError('plug');
    // send to error page with no plugin specified error
    exit;
}
$plugin = addslashes(cleanvar($_GET['pl']));
$varible = NULL;
if (isset($_GET['v'])) {
    $varible = cleanvar($_GET['v']);
}
$page = $plugin;
// name of the page is the plugin name
$Cplug = $plugins_class["{$plugin}"];
$page_title = $Cplug->getTitle();
// get the page title from the title of the plugin
$_SERVER['SCRIPT_NAME'] = $_SERVER['SCRIPT_NAME'] . '?pl=' . $_GET['pl'];
## Require Header ##
require 'inc/header.php';
if ($mem->reqLevel($Cplug->getPagePerm())) {
    // name of the plugin is also the name of the premission associated with it
示例#20
0
function listProductosPorCategoria()
{
    $c = getConnection();
    $id = (int) $c->real_escape_string(request('categoria_id'));
    $query = "SELECT * FROM productos WHERE categoria_id = {$id}";
    $productos = array();
    if ($resultado = $c->query($query)) {
        while ($fila = $resultado->fetch_assoc()) {
            $productos[] = array_map('utf8_encode', $fila);
        }
        $resultado->free();
        sendResult(array("productos" => $productos), "Ok");
    } else {
        sendError("No se encontraron resultados");
    }
}
示例#21
0
    exit;
}
if ($arg['loggedIn']) {
    if (!$_REQUEST['file']) {
        sendError($twig, '403');
    } else {
        if (!file_exists($fpath)) {
            sendError($twig, '404');
        } else {
            $filetime = filemtime($fpath);
            $etag = MD5(filemtime($fpath));
            header('Cache-Control: public, max-age=31536000');
            $notChanged = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $filetime || isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag;
            if ($notChanged) {
                sendError($twig, '304');
                exit;
            } else {
                $nextmonth = time() + 2419200;
                header('Content-Type: ' . mime_content_type($fpath));
                header('Content-Length: ' . filesize($fpath));
                header('Expires: ' . date('r', $nextmonth));
                header('Last-Modified: ' . date('r', $filetime));
                header('etag: ' . $etag);
                readfile($fpath);
                exit;
            }
        }
    }
} else {
    sendError($twig, '401');
}
示例#22
0
function smamo_ajax_signup()
{
    $response = array();
    if (!isset($_POST['name']) || $_POST['name'] === '') {
        sendError($response, 'Indtast venligst et navn');
    }
    if (!isset($_POST['email']) || $_POST['email'] === '') {
        sendError($response, 'Indtast venligst en email');
    }
    if (!isset($_POST['work']) || $_POST['work'] === '') {
        sendError($response, 'Vælg en arbejdsplads');
    }
    if (!isset($_POST['position']) || $_POST['position'] === '') {
        sendError($response, 'Vælg en stilling');
    }
    if (!isset($_POST['work_since']) || $_POST['work_since'] === '') {
        sendError($response, 'Indtast ansat siden');
    }
    if (!isset($_POST['birthday']) || $_POST['birthday'] === '') {
        sendError($response, 'Indtast din fødselsdag');
    }
    if (!isset($_POST['phone']) || $_POST['phone'] === '') {
        sendError($response, 'Skriv dit telefonnummer');
    }
    if (!isset($_POST['address']) || $_POST['address'] === '') {
        sendError($response, 'Indtast din adresse');
    }
    if (!isset($_POST['post']) || $_POST['post'] === '') {
        sendError($response, 'Indtast dit postnummer');
    }
    if (!isset($_POST['by']) || $_POST['by'] === '') {
        sendError($response, 'Indtast by');
    }
    $name = wp_strip_all_tags($_POST['name']);
    $email = wp_strip_all_tags($_POST['email']);
    $work = wp_strip_all_tags($_POST['work']);
    $position = wp_strip_all_tags($_POST['position']);
    $ean = isset($_POST['ean']) ? wp_strip_all_tags($_POST['ean']) : '';
    $cpr = isset($_POST['cpr']) ? wp_strip_all_tags($_POST['cpr']) : '';
    $user_id = isset($_POST['user_id']) ? wp_strip_all_tags($_POST['user_id']) : '';
    $work_since = strtotime(wp_strip_all_tags($_POST['work_since']));
    $birthday = strtotime(wp_strip_all_tags($_POST['birthday']));
    $phone = strtotime(wp_strip_all_tags($_POST['phone']));
    $address = wp_strip_all_tags($_POST['address']);
    $post = wp_strip_all_tags($_POST['post']);
    $by = wp_strip_all_tags($_POST['by']);
    $remarks = isset($_POST['remarks']) ? wp_strip_all_tags($_POST['remarks']) : '';
    $new = wp_insert_post(array('post_title' => $name, 'post_type' => 'medlem', 'post_status' => 'draft'), true);
    if (is_wp_error($new)) {
        $response['error'] = 'Kunne ikke oprette medlemsskab på grund af en teknisk fejl: ' . $new->get_error_message;
        echo json_encode($response);
        exit;
    }
    update_post_meta($new, 'medlem_name', $name);
    update_post_meta($new, 'medlem_email', $email);
    update_post_meta($new, 'medlem_work', $work);
    update_post_meta($new, 'medlem_position', $position);
    update_post_meta($new, 'medlem_ean', $ean);
    update_post_meta($new, 'medlem_cpr', $cpr);
    update_post_meta($new, 'medlem_user_id', $user_id);
    update_post_meta($new, 'medlem_work_since', $work_since);
    update_post_meta($new, 'medlem_birthday', $birthday);
    update_post_meta($new, 'medlem_phone', $phone);
    update_post_meta($new, 'medlem_address', $address);
    update_post_meta($new, 'medlem_post', $post);
    update_post_meta($new, 'medlem_by', $by);
    update_post_meta($new, 'medlem_remarks', $remarks);
    update_post_meta($new, 'medlem_type', '99');
    // Send notifikation
    $members = get_posts(array('posts_per_page' => -1, 'meta_key' => 'notify_new_member', 'meta_value' => 1));
    $emails = array();
    foreach ($members as $member) {
        $emails[] = get_post_meta($member->ID, 'medlem_email', true);
    }
    $message_head = '<html><head><meta name="charset" content="UTF-8"</head><body>';
    $message_copy_notice = '<p><strong>Kære ' . $name . '</strong></p>';
    $message_copy_notice .= '<p>Tak for din anmodning om medlemsskab i FSD. Du kan se en kopi af de sendte data herunder. FSD vil hurtigst muligt vende tilbage, når medlemsskabet er gennemført. </p><br/><br/>';
    $message = '<h3>' . $name . ' har anmodet om medlemsskab i FSD</h3>';
    $message .= '<p><strong>Oplysninger</strong></p><ul>';
    $message .= '<li>Navn: ' . $name . '</li>';
    $message .= '<li>Email: ' . $email . '</li>';
    $message .= '<li>Telefonnummer: ' . $phone . '</li>';
    $message .= '<li>Ansat hos: ' . $work . '</li>';
    $message .= '<li>Stilling: ' . $position . '</li>';
    $message .= '<li>EAN: ' . $ean . '</li>';
    $message .= '<li>Bruger ID: ' . $user_id . '</li>';
    $message .= '<li>Ansat siden: ' . $work_since . '</li>';
    $message .= '<li>Fødselsdato: ' . $birthday . '</li>';
    $message .= '<li>Adresse: ' . $address . '</li>';
    $message .= '<li>Postnummer: ' . $post . '</li>';
    $message .= '<li>By: ' . $by . '</li>';
    $message .= '<li>CPR: ' . $cpr . '</li>';
    $message .= '<li>Bemærkninger: ' . $remarks . '</li>';
    $message_footer = '</ul><br/><br/><p>Venlig hilsen FSD</p></body></html>';
    $notify_header = "From: FSD <*****@*****.**>\r\n";
    $notify_header .= "MIME-Version: 1.0\r\n";
    $notify_header .= "Content-Type: text/html; charset=utf-8\r\n";
    $notify_header .= "X-Priority: 1\r\n";
    $email = wp_mail($emails, 'Nyt medlemsskab i FSD', $message_head . $message . $message_footer, $notify_header);
    $confirm = wp_mail($email, 'Tak for din henvendelse', $message_head . $message_copy_notice . $message . $message_footer, $notify_header);
    $confirm_copy = wp_mail('*****@*****.**', 'Tak for din henvendelse', $message_head . $message_copy_notice . $message . $message_footer, $notify_header);
    $response['success'] = '<h2>Tjek din email</h2><p>Tak for din registrering. FSD vil hurtigst muligt vende tilbage, når medlemsskabet er gennemført.</p>';
    echo json_encode($response);
    exit;
}
示例#23
0
<?php

if (empty($_POST["filename"])) {
    sendError(400);
}
$filename = loadPicFile("helpers/filenamereject.php", array("filename" => $_POST["filename"]));
$path = Access::getCurrentPath();
$fullFilename = $path->path . $filename;
if (!is_file($fullFilename)) {
    sendError(404);
}
if ($path->hasPermission("nsfw") === false) {
    $nsfwRegexPathTest = preg_match("/.*\\/NSFW\\/.*/", $fullFilename);
    if ($nsfwRegexPathTest === 1 || $nsfwRegexPathTest === false) {
        sendError(404);
    }
    $nsfwRegexPathTest = preg_match("/NSFW\\/.*/", $fullFilename);
    if ($nsfwRegexPathTest === 1 || $nsfwRegexPathTest === false) {
        sendError(404);
    }
}
return $fullFilename;
示例#24
0
 * This file handles requests to local.users.com/users
 */
$requestUri = $_SERVER['REQUEST_URI'];
$handledPath = '/users';
if (strpos($requestUri, $handledPath) === false) {
    sendError();
}
$userId = str_replace($handledPath, '', $requestUri);
$userId = str_replace('/', '', $userId);
if ($userId) {
    try {
        $userData = getUserData($userId);
        // Handle requests to /users/{userId}
        sendSuccess($userData);
    } catch (Exception $e) {
        sendError();
    }
} else {
    sendSuccess(getAllUsers());
    // Handle requests to /users
}
function getUserData($userId)
{
    $users = getAllUsers();
    if (isset($users[$userId])) {
        $userData = $users[$userId];
        return [$userId => $userData];
    } else {
        throw new Exception('Unable to fetch user');
    }
}
示例#25
0
 private function getContact($uid)
 {
     $qry = "Select ContactId From SelfServiceUser Where Id = '{$uid}'";
     $result = $this->query($qry);
     $sobj = $this->unpackSObjects($result);
     $cid = $sobj[0]->ContactId;
     if (is_null($cid)) {
         return null;
     }
     $qry = "Select Id, AccountId, Account.Name, FirstName, LastName, Phone, Email, Title, Department From Contact Where Id = '{$cid}'";
     $result = $this->query($qry);
     if (count($result->records) == 1) {
         $cont = $this->unpackSObjects($result);
         return $cont[0];
     } else {
         sendError($result, "Error retrieving contact information for {$uid}");
     }
 }
示例#26
0
            $fields['Response__c'] = floatval($resp);
            $fields['Response_Provided__c'] = 'true';
        } else {
            $fields['Response__c'] = 0.0;
            $fields['Response_Provided__c'] = 'false';
        }
        $item->fields = $fields;
        array_push($answers, $item);
        if ($log) {
            fwrite($log, date('c') . ' - Answer: ' . $key . '-' . $idx . '-' . $_POST[$idx] . ' stored as ' . $resp . "\n");
        }
    }
    try {
        $response = $sforce->create($answers);
    } catch (Exception $ex) {
        sendError($ex, $_POST["company"]);
        exit;
    }
    if ($log) {
        fwrite($log, date('c') . ' - Answers: ' . count($response) . "\n");
        fclose($log);
    }
    header('Location: http://www.anitaborg.org/TopCompany/form_ack.html');
}
function sendError($error, $company)
{
    global $ERRORS_TO;
    global $log;
    $message = "A Top Company form submission error occurred at " . date('c') . "\r\n";
    $message .= "Company Name: {$company} \r\n";
    $message .= $error->getFile() . ': ' . $error->getLine() . "\r\n";
示例#27
0
function saveUserAttribute($userid, $attid, $data)
{
    global $usertable_prefix, $table_prefix, $tables;
    # workaround for integration webbler/phplist
    if (!isset($usertable_prefix)) {
        $usertable_prefix = '';
    }
    if (!isset($table_prefix)) {
        $table_prefix = 'phplist_';
    }
    if (!empty($tables["attribute"])) {
        $att_table = $usertable_prefix . $tables["attribute"];
        $user_att_table = $usertable_prefix . $tables["user_attribute"];
    } else {
        $att_table = $usertable_prefix . "attribute";
        $user_att_table = $usertable_prefix . "user_attribute";
    }
    if (!is_array($data)) {
        $tmp = $data;
        $data = Sql_Fetch_Assoc_Query(sprintf('select * from %s where id = %d', $att_table, $attid));
        $data['value'] = $tmp;
        $data['displayvalue'] = $tmp;
    }
    # dbg($data,'$data to store for '.$userid.' '.$attid);
    if ($data["nodbsave"]) {
        #   dbg($attid, "Not saving, nodbsave");
        return;
    }
    if ($attid == "emailcheck" || $attid == "passwordcheck") {
        #   dbg($attid, "Not saving, emailcheck/passwordcheck");
        return;
    }
    if (!$data["type"]) {
        $data["type"] = "textline";
    }
    if ($data["type"] == "static" || $data["type"] == "password" || $data['type'] == 'htmlpref') {
        if (!empty($GLOBALS['config']['dontsave_userpassword']) && $data['type'] == 'password') {
            $data["value"] = 'not authoritative';
        }
        Sql_Query(sprintf('update user set %s = "%s" where id = %d', $attid, $data["value"], $userid));
        dbg('Saving', $data['value'], DBG_TRACE);
        if ($data["type"] == "password") {
            Sql_Query(sprintf('update user set passwordchanged = now(),password="******" where id = %d', hash('sha256', $data['value']), $userid));
        }
        return 1;
    }
    $attributetype = $data['type'];
    $attid_req = Sql_Fetch_Row_Query(sprintf('
    select id,type,tablename from %s where id = %d', $att_table, $attid));
    if (!$attid_req[0]) {
        $attid_req = Sql_Fetch_Row_Query(sprintf('
      select id,type,tablename from %s where name = "%s"', $att_table, $data["name"]));
        if (!$attid_req[0]) {
            if (!empty($data["name"]) && $GLOBALS["config"]["autocreate_attributes"]) {
                #      Dbg("Creating new Attribute: ".$data["name"]);
                sendError("creating new attribute " . $data["name"]);
                $atttable = getNewAttributeTablename($data["name"]);
                Sql_Query(sprintf('insert into %s (name,type,tablename) values("%s","%s","%s")', $att_table, $data["name"], $data["type"], $atttable));
                $attid = Sql_Insert_Id();
            } else {
                #     dbg("Not creating new Attribute: ".$data["name"]);
                # sendError("Not creating new attribute ".$data["name"]);
            }
        } else {
            $attid = $attid_req[0];
            if (empty($attributetype)) {
                $attributetype = $attid_req[1];
            }
            $atttable = $attid_req[2];
        }
    } else {
        $attid = $attid_req[0];
        if (empty($attributetype)) {
            $attributetype = $attid_req[1];
        }
        $atttable = $attid_req[2];
    }
    if (!$atttable && !empty($data['name'])) {
        $atttable = getNewAttributeTablename($data["name"]);
        # fix attribute without tablename
        Sql_Query(sprintf('update %s set tablename ="%s" where id = %d', $att_table, $atttable, $attid));
        #   sendError("Attribute without Tablename $attid");
    }
    switch ($attributetype) {
        case "static":
        case "password":
            #  dbg('SAVING STATIC OR  PASSWORD');
            if (!empty($GLOBALS['config']['dontsave_userpassword']) && $data['type'] == 'password') {
                $data["value"] = 'not authoritative';
            }
            Sql_Query(sprintf('update user set %s = "%s" where id = %d', $attid, $data["value"], $userid));
            break;
        case "select":
            $curval = Sql_Fetch_Row_Query(sprintf('select id from ' . $table_prefix . 'listattr_%s
        where name = "%s"', $atttable, $data["displayvalue"]), 1);
            if (!$curval[0] && $data['displayvalue'] && $data['displayvalue'] != '') {
                Sql_Query(sprintf('insert into ' . $table_prefix . 'listattr_%s (name) values("%s")', $atttable, $data["displayvalue"]));
                sendError("Added " . $data["displayvalue"] . " to {$atttable}");
                $valid = Sql_Insert_id();
            } else {
                $valid = $curval[0];
            }
            Sql_Query(sprintf('replace into %s (userid,attributeid,value)
        values(%d,%d,"%s")', $user_att_table, $userid, $attid, $valid));
            break;
        case 'avatar':
            if (is_array($_FILES)) {
                ## only avatars are files, for now
                if (!defined('MAX_AVATAR_SIZE')) {
                    define('MAX_AVATAR_SIZE', 100000);
                }
                $formfield = 'attribute' . $attid . '_file';
                ## the name of the fileupload element
                if (!empty($_FILES[$formfield]['name']) && !empty($_FILES[$formfield]['tmp_name'])) {
                    $tmpnam = $_FILES[$formfield]['tmp_name'];
                    move_uploaded_file($tmpnam, '/tmp/avatar' . $userid . '.jpg');
                    $size = filesize('/tmp/avatar' . $userid . '.jpg');
                    #          dbg('New size: '.$size);
                    if ($size < MAX_AVATAR_SIZE) {
                        $avatar = file_get_contents('/tmp/avatar' . $userid . '.jpg');
                        Sql_Query(sprintf('replace into %s (userid,attributeid,value)
              values(%d,%d,"%s")', $user_att_table, $userid, $attid, base64_encode($avatar)));
                        unlink('/tmp/avatar' . $userid . '.jpg');
                    }
                }
            }
            break;
        default:
            Sql_Query(sprintf('replace into %s (userid,attributeid,value)
        values(%d,%d,"%s")', $user_att_table, $userid, $attid, $data["value"]));
            break;
    }
    return 1;
}
示例#28
0
 /**
  * PHP >= 5.4.0<br/>
  * Write session data
  * @link http://php.net/manual/en/sessionhandlerinterafce.write.php
  * @param string $session_id The session id.
  * @param string $session_data <p>
  * The encoded session data. This data is the
  * result of the PHP internally encoding
  * the $_SESSION superglobal to a serialized
  * string and passing it as this parameter.
  * Please note sessions use an alternative serialization method.
  * </p>
  * @return bool <p>
  * The return value (usually TRUE on success, FALSE on failure).
  * Note this value is returned internally to PHP for processing.
  * </p>
  */
 public function write($session_id, $session_data)
 {
     $session_id = addslashes($session_id);
     $session_data = addslashes($session_data);
     $session_exists = phpList::DB()->query(sprintf('SELECT COUNT(*) FROM  %s
             WHERE sessionid = \'%s\'', Config::SESSION_TABLENAME, addslashes($session_id)))->fetchColumn(0);
     if ($session_exists <= 0) {
         $retval = phpList::DB()->query(sprintf('INSERT INTO %s (sessionid,lastactive,data)
                 VALUES("%s",UNIX_TIMESTAMP(NOW()),"%s")', Config::SESSION_TABLENAME, $session_id, $session_data));
     } else {
         $retval = phpList::DB()->query(sprintf('UPDATE %s
                 SET data = "%s", lastactive = UNIX_TIMESTAMP(NOW())
                 WHERE sessionid = "%s"', Config::SESSION_TABLENAME, $session_id, $session_data));
         if ($retval->rowCount() <= 0) {
             //TODO: correct error handling
             phpList::log()->notice('unable to update session data for session ' . $session_id);
             sendError('unable to update session data for session ' . $session_id);
         }
     }
     return $retval;
 }
示例#29
0
function saveUserAttribute($userid,$attid,$data) {
	if ($data["nodbsave"]) {
  	dbg("Not saving $attid");
  	return;
 	}
  if ($attid == "emailcheck" || $attid == "passwordcheck") {
  	dbg("Not saving $attid");
  	return;
	}

	if (!$data["type"])
  	$data["type"] = "textline";

  if ($data["type"] == "static" || $data["type"] == "password") {
   	Sql_Query(sprintf('update user set %s = "%s" where id = %d',
    	$attid,$data["value"],$userid));
    return 1;
  }

  $attid_req = Sql_Fetch_Row_Query(sprintf('
    select id,type,tablename from attribute where id = %d',$attid));
  if (!$attid_req[0]) {
    $attid_req = Sql_Fetch_Row_Query(sprintf('
      select id,type,tablename from attribute where name = "%s"',$data["name"]));
    if (!$attid_req[0]) {
    	if ($GLOBALS["config"]["autocreate_attributes"]) {
        Dbg("Creating new Attribute: ".$data["name"]);
        sendError("creating new attribute ".$data["name"]);
        $atttable= getNewAttributeTablename($data["name"]);
        Sql_Query(sprintf('insert into attribute (name,type,tablename) values("%s","%s","%s")',$data["name"],$data["type"],$atttable));
        $attid = Sql_Insert_Id();
      } else {
        dbg("Not creating new Attribute: ".$data["name"]);
       # sendError("Not creating new attribute ".$data["name"]);
			}
    } else {
      $attid = $attid_req[0];
      $atttable = $attid_req[2];
  	}
	} else {
    $attid = $attid_req[0];
    $atttable = $attid_req[2];
  }

  if (!$atttable) {
  	$atttable = getNewAttributeTablename($data["name"]);
  	# fix attribute without tablename
    Sql_Query(sprintf('update attribute set tablename ="%s" where id = %d',
    	$atttable,$attid));
#  	sendError("Attribute without Tablename $attid");
  }

  switch ($data["type"]) {
  	case "static":
    case "password":
    	Sql_Query(sprintf('update user set %s = "%s" where id = %d',
      	$attid,$data["value"],$userid));
			break;
    case "select":
    	$curval = Sql_Fetch_Row_Query(sprintf('select id from phplist_listattr_%s
      	where name = "%s"',$atttable,$data["displayvalue"]),1);
      if (!$curval[0]) {
      	Sql_Query(sprintf('insert into phplist_listattr_%s (name) values("%s")',$atttable,
        	$data["displayvalue"]));
        sendError("Added ".$data["displayvalue"]." to $atttable");
        $valid = Sql_Insert_id();
      } else {
      	$valid = $curval[0];
      }
    	Sql_Query(sprintf('replace into user_attribute (userid,attributeid,value)
		  	values(%d,%d,"%s")',$userid,$attid,$valid));

			break;
   	default:
    	Sql_Query(sprintf('replace into user_attribute (userid,attributeid,value)
		  	values(%d,%d,"%s")',$userid,$attid,$data["value"]));
     	break;
 	}
  return 1;
}
示例#30
0
文件: inc.php 项目: Gammelbob/echelon
}
// default to login required
if ($auth_user_here != false) {
    // some pages do not need auth but include this file so this following line is optional
    $mem->auth($auth_name);
}
// see if user has the right access level is not on the BL and has not got a hack counter above 3
## remove tokens from 2 pages ago to stop build up
if (!isLogin()) {
    // stop login page from using this and moving the vars
    $tokens = array();
    $num_tokens = count($_SESSION['tokens']);
    if ($num_tokens > 0) {
        foreach ($_SESSION['tokens'] as $key => $value) {
            $tokens[$key] = $value;
        }
        $_SESSION['tokens'] = array();
    }
}
## if no time zone set display error ##
if (NO_TIME_ZONE) {
    // if no time zoneset show warning message
    set_warning("Setup Error: The website's time zone is not set, defaulting to use Europe/London (GMT)");
}
## Block Internet Explorer ###
if ($allow_ie == 0) {
    if (detectIE() && !isError()) {
        // alow IE on the pubbans page aswell as the error page
        sendError('ie');
    }
}