function downloadOutput($output) { /* // function for force downloading files */ // Must be fresh start if (headers_sent()) { die('Headers Sent'); } // Required for some browsers if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } // CHECK IF THE output EXISTS if ($output != '') { // Read output to standard out header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private", false); // required for certain browsers header("Content-Type: application/force-download"); header("Content-Disposition: attachment; filename=user-result-summary.xls;"); header("Content-Transfer-Encoding: binary"); header("Content-Length: " . strlen($output)); ob_clean(); flush(); echo $output; } else { // Output does not exist, maybe the run failed, or is still running? $msg = array(); $msg['MESSAGE'] = "Error: No resuts was found for your user!"; respond("NORESULTS", $msg, true); } }
public function testBasic() { $this->expectOutputString('x'); respond('/', function () { echo 'x'; }); respond('/something', function () { echo 'y'; }); dispatch('/'); }
function subscribe($publisher, $path, $callback) { global $subscription_file; $key = "{$publisher} {$path}"; $id = md5($key); $subscriptions = file($subscription_file) ?: array(); $subscriptions = array_map(rtrim, $subscriptions); array_push($subscriptions, "{$key} {$callback}"); $subscriptions = array_unique($subscriptions); file_put_contents($subscription_file, join("\n", $subscriptions)); respond($id); }
function sendMails($maildata) { $me = '*****@*****.**'; $them = $maildata["email"]; $subjectMe = 'New enquiry'; $subjectThem = 'Thanks for the enquiry!'; $messageMe = $maildata["message"]; $messageThem = 'Hi! Thanks for the enquiry. We will respond as soon as we can!'; $headersMe = 'From: ' . $me . "\n" . 'Reply-To: ' . $them . "\n" . 'X-Mailer: PHP/' . phpversion(); $headersThem = 'From: ' . $me . "\n" . 'Reply-To: ' . $me . "\n" . 'X-Mailer: PHP/' . phpversion(); mail($me, $subjectMe, $messageMe, $headersMe); mail($them, $subjectThem, $messageThem, $headersThem); respond($maildata); }
function generate_slug($length = 4) { global $db; $values = serialize($_POST); $length = 4; $slug = substr(md5($values . time()), 0, $length); $exists = $db->value("\n SELECT COUNT(id)\n FROM shift\n WHERE url_slug = '{$slug}'\n "); if ($length == 32) { respond(0, "Could not generate URL slug."); } if ($exists) { return generate_slug($length + 1); } else { return $slug; } }
function consulta($tabla, $columnas = array(), $filtros = array(), $singleRecord = false) { $sqlColumnas = empty($columnas) ? '*' : implode(', ', $columnas); $sqlFiltros = array(); foreach ($filtros as $index => $element) { array_push($sqlFiltros, $index . ' = ' . quoteDb($element)); } $sqlFiltros = !empty($sqlFiltros) ? 'WHERE ' . implode(' AND ', $sqlFiltros) : ''; $link = connect(); $result = mysql_query("SELECT {$sqlColumnas} FROM {$tabla} {$sqlFiltros}", $link) or respond(400, mysql_error()); $arrayResult = array(); while ($row = mysql_fetch_assoc($result)) { array_push($arrayResult, $row); } if (!empty($singleRecord) && !empty($arrayResult)) { $arrayResult = $arrayResult[0]; } return $arrayResult; }
public static function resume() { function respond($err, $resume = null, $fname = null) { $data = ['error' => $err, 'resume' => $resume, 'fname' => $fname]; echo toJSON($data); } if (!isset($_FILES['file'])) { return respond('no file selected'); } switch ($_FILES['file']['error']) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_FORM_SIZE: return respond('max file size exceeded'); case UPLOAD_ERR_NO_FILE: return respond('no file selected'); case UPLOAD_ERR_INI_SIZE: return respond('file too large'); } if ($_FILES['file']['size'] > 10 * 1024 * 1024) { return respond('max file size exceeded'); } $filename = $_FILES['file']["name"]; $ext = pathinfo($filename, PATHINFO_EXTENSION); $allowed = array("doc", "docx", "rtf", "pdf"); if (!in_array($ext, $allowed)) { return respond('bad file extension'); } require_once $GLOBALS['dirpre'] . 'includes/S3/s3_config.php'; $fname = $_FILES['file']["tmp_name"]; $actualFilename = time() . '.' . $ext; $res = $s3->putObjectFile($fname, $bucket, $actualFilename, S3::ACL_PUBLIC_READ); if (!$res) { return respond('upload failed'); } $link = 'http://' . $bucket . '.s3.amazonaws.com/' . $actualFilename; return respond(null, $link, $filename); }
function setUserReported($contentOriginTable, $contentID, $isAdmin) { // get the ID of the user who was reported $reportedUserID = Database::selectFirst("SELECT user_id FROM " . $contentOriginTable . " WHERE id = " . intval($contentID)); $reportedUserID = $reportedUserID['user_id']; // get the ID of the message thread that the user was reported in if ($contentOriginTable == 'messages') { $messageID = $contentID; } elseif ($contentOriginTable == 'comments') { $messageID = Database::selectFirst("SELECT message_id FROM comments WHERE id = " . $contentID); $messageID = $messageID['message_id']; } else { // we can't handle this request respond(array('status' => 'bad_request')); // prevent IDE warnings exit; } // mark the user as reported and possibly ban them temporarily $possibleWriteLockEnd = time() + 3600 * 24 * 5; $timesReported = $isAdmin ? 2 : 1; Database::update("UPDATE users SET reported_count = reported_count+" . $timesReported . ", write_lock_until = IF(reported_count >= 3, " . intval($possibleWriteLockEnd) . ", write_lock_until), reported_count = IF(reported_count >= 3, 1, reported_count) WHERE id = " . $reportedUserID); // send a notice to the violating user Database::insert("INSERT INTO subscriptions (message_id, user_id, degree, reasonForBan, counter) VALUES (" . intval($messageID) . ", " . $reportedUserID . ", 3, 1, 1) ON DUPLICATE KEY UPDATE reasonForBan = 1, counter = 1"); }
<?php // Generic response (don't force the trailing slash: this should catch any accidental laziness) respond('/?', function ($request, $response, $app) { // Let's create a session variable, so we know where to redirect back to $redirect_to = $request->param('redirect_to'); // Let's log the user out IDMObject::unauthN($redirect_to); }); // Let's create a success page respond('/logout-success/?', function ($request, $response, $app) { // Display the template $app->tpl->assign('show_page', 'logout-success'); $app->tpl->display('_wrapper.tpl'); }); // Let's create a cute little message page... so that PhoneGap users just see a flashing page respond('/logout-message/?', function ($request, $response, $app) { // Display the template $app->tpl->assign('show_page', 'logout-message'); $app->tpl->display('_wrapper.tpl'); });
respond('POST', '/[i:sgs_id]/[*]', function ($request, $response, $app) { $response->deny_to_readonly(); $sgs_id = $request->param('sgs_id'); if ('teacher' === $request->param('target')) { $action = $request->param('action'); if ('add-teacher' === $action) { $ss_id = $request->param('student_school_id'); $app->populate('student_school', TeacherCert\Student\School::get($ss_id)); $app->populate_constituents(); $app->teacher_model->form($request->params()); $app->teacher_model->student_gate_system_id = $sgs_id; $teacher = new TeacherCert\Student\CooperatingTeacher($app->teacher_model->form()); } else { // update existing teacher $teacher_id = $request->param('id'); $teacher = new TeacherCert\Student\CooperatingTeacher($teacher_id); if ('Add Voucher' === $action) { $teacher->add_voucher(); } elseif ('Remove Voucher' === $action) { $teacher->remove_voucher(); } elseif ('Remove Teacher' === $action) { $teacher->delete(); } } if ($teacher->save()) { $_SESSION['successes'][] = 'Your changes have been saved.'; } else { $_SESSION['errors'][] = 'An error occured saving your changes: ' . htmlentities(PSU::db('banner')->ErrorMsg()); } $response->refresh(); } $app->school_model->form($request->params()); if ($id = $request->param('id')) { $action = 'edit'; $school = TeacherCert\Student\School::get($id); // dump the incoming form data back into the School $fields = $app->school_model->form(); // read-only fields unset($fields['school_id']); foreach ($fields as $key => $value) { $school->{$key} = $value; } } else { $action = 'add'; $school = new TeacherCert\Student\School($app->school_model->form()); $school->student_gate_system_id = $sgs_id; } $uri = sprintf("%s/student-school/%d/edit/%d", $GLOBALS['BASE_URL'], $app->student_gate_system->id, $school->id); if ($success = $school->save()) { if ('edit' === $action) { $_SESSION['successes'][] = 'Your changes have been saved.'; } else { $_SESSION['successes'][] = 'The school has been added to this gate system.'; // need to populate new id into url $uri = sprintf("%s/student-school/%d/edit/%d", $GLOBALS['BASE_URL'], $app->student_gate_system->id, $school->id); } unset($_SESSION['tcert-student-school-save']); } else { $_SESSION['errors'][] = 'Your changes could not be saved: ' . PSU::db('banner')->ErrorMsg(); $_SESSION['tcert-student-school-save'] = $app->school_model->form(); // Operation failed; might need to return the user back to // the "add a school" screen. if ('edit' !== $action) { $uri = sprintf("%s/student-school/%d/add", $GLOBALS['BASE_URL'], $app->student_gate_system->id, $school->id); } } $response->redirect($uri); });
<?php session_start(); require_once 'funcs.php'; require_once 'db.php'; if (!isset($_SESSION['user']) || !isset($_SESSION['user']['username'])) { header('Location: index.php'); die; } $mysqli = dbConnect(); $query = 'SELECT leave_type as title, start_date as start, end_date as end FROM `leaves_taken` WHERE `person_id` = ' . $_SESSION['user']['person_id'] . ''; $result = $mysqli->query($query); if ($result->num_rows > 0) { $data = []; while ($row = $result->fetch_assoc()) { $data[] = $row; } respond(false, "got it", $data); } ?>
*/ require_once __DIR__ . '/../base.php'; if ($_SERVER['REQUEST_METHOD'] === 'POST') { // initialization $user = init($_POST); // force authentication $userID = auth($user['username'], $user['password'], false); // check if required parameters are set if (isset($_POST['contentType']) && isset($_POST['contentID'])) { $contentID = intval(base64_decode(trim($_POST['contentID']))); if ($_POST['contentType'] == 'message') { $authorID = Database::selectFirst("SELECT user_id FROM messages WHERE id = " . intval($contentID)); if (isset($authorID['user_id']) && $authorID['user_id'] != $userID) { Database::insert("INSERT INTO connections (from_user, type, to_user, time_inserted) VALUES (" . intval($userID) . ", 'block', " . intval($authorID['user_id']) . ", " . time() . ") ON DUPLICATE KEY UPDATE type = VALUES(type)"); } respond(array('status' => 'ok')); } elseif ($_POST['contentType'] == 'comment') { $authorID = Database::selectFirst("SELECT user_id FROM comments WHERE id = " . intval($contentID)); if (isset($authorID['user_id']) && $authorID['user_id'] != $userID) { Database::insert("INSERT INTO connections (from_user, type, to_user, time_inserted) VALUES (" . intval($userID) . ", 'block', " . intval($authorID['user_id']) . ", " . time() . ") ON DUPLICATE KEY UPDATE type = VALUES(type)"); } respond(array('status' => 'ok')); } else { respond(array('status' => 'bad_request')); } } else { respond(array('status' => 'bad_request')); } } else { respond(array('status' => 'bad_request')); }
/** * Handles the actual XML between the <template/> tags. * * Recognises the different tags, access the different functions to process each individual tag. Notes by the original developer: <br/> * Why isn't this a huge switch statement? Because it has to do more comlicated checking than just string comparison to figure out what it should do. <br/> * How can I organize this better? Good question. * * @todo It seems to me that this function could modelled similarly to the custom tag system. Where there is a seperate function for each tag. * * @uses getid() * @uses getfdate() * @uses getsize() * @uses upperkeysarray() * @uses debugger() * @uses recursechildren() * @uses respond() * @uses botget() * @uses gender() * @uses getinput() * @uses bset() * @uses insertgossip() * @uses firstthird() * @uses firstsecond() * @uses getthat() * @uses realchild() * * @param mixed $xmlnode Getting either a string or an array from recursechildren() func. * @param array $inputstar If a matched pattern includes *'s then what is covere by the * is found here. * @param array $thatstar if a used that contains a star, then what is covered by the * is found here. * @param array $topicstar if a used topic contains a star, then what is covered by the * is found here. * * @return string The bot's response. */ function handlenode($xmlnode, $inputstar, $thatstar, $topicstar) { if (!is_array($xmlnode)) { return $xmlnode; } elseif (strtoupper($xmlnode["tag"]) == "ID") { return getid(); } elseif (strtoupper($xmlnode["tag"]) == "DATE") { // return getfdate(); // deprecated $mynode = upperkeysarray($xmlnode["attributes"]); // Get the value of an attribute $date_format = $mynode["FORMAT"]; return getfdate($date_format); } elseif (strtoupper($xmlnode["tag"]) == "VERSION") { return PROGRAMEVERSION; } elseif (strtoupper($xmlnode["tag"]) == "SIZE") { return getsize(); } elseif (strtoupper($xmlnode["tag"]) == "STAR") { $mynode = upperkeysarray($xmlnode["attributes"]); //$starindex=$xmlnode["attributes"]["INDEX"]; if (!(is_array($mynode) && isset($mynode["INDEX"]))) { $mynode["INDEX"] = ""; } $starindex = $mynode["INDEX"]; if ($starindex == "") { $starindex = "1"; } debugger("starindex: {$starindex}", 3); //print_r($inputstar); return $inputstar[$starindex - 1]; } elseif (strtoupper($xmlnode["tag"]) == "THATSTAR") { $mynode = upperkeysarray($xmlnode["attributes"]); //$starindex=$xmlnode["attributes"]["INDEX"]; if (!(is_array($mynode) && isset($mynode["INDEX"]))) { $mynode["INDEX"] = ""; } $starindex = $mynode["INDEX"]; if ($starindex == "") { $starindex = "1"; } debugger("starindex: {$starindex}", 3); //print_r($inputstar); return $thatstar[$starindex - 1]; } elseif (strtoupper($xmlnode["tag"]) == "TOPICSTAR") { $mynode = upperkeysarray($xmlnode["attributes"]); //$starindex=$xmlnode["attributes"]["INDEX"]; if (!(is_array($mynode) && isset($mynode["INDEX"]))) { $mynode["INDEX"] = ""; } $starindex = $mynode['INDEX']; if ($starindex == "") { $starindex = "1"; } debugger("starindex: {$starindex}", 3); //print_r($inputstar); return $topicstar[$starindex - 1]; } elseif (strtoupper($xmlnode["tag"]) == "SRAI") { // Build up a new response inside of here (using recursechildren function and then call response with it. $newresponse = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); debugger("newresponts: {$newresponse}", 3); return respond($newresponse); } elseif (strtoupper($xmlnode["tag"]) == "SR") { return respond($inputstar[0]); } elseif (strtoupper($xmlnode["tag"]) == "RANDOM") { $liarray = array(); $children = $xmlnode["children"]; for ($randomc = 0; $randomc < sizeof($children); $randomc++) { if (strtoupper($children[$randomc]["tag"]) == "LI") { $liarray[] = $randomc; } } // Pick a random number from 0 to sizeof($liarray)-1 mt_srand((double) microtime() * 1000000); $lirandom = mt_rand(0, sizeof($liarray) - 1); return recursechildren(realchild($children[$liarray[$lirandom]]), $inputstar, $thatstar, $topicstar); } elseif (strtoupper($xmlnode["tag"]) == "THINK") { recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); return ""; } elseif (strtoupper($xmlnode["tag"]) == "BOT") { $mynode = upperkeysarray($xmlnode["attributes"]); //$name=$xmlnode["attributes"]["NAME"]; $name = $mynode["NAME"]; return botget($name); } elseif (strtoupper($xmlnode["tag"]) == "GET") { $mynode = upperkeysarray($xmlnode["attributes"]); //$name=$xmlnode["attributes"]["NAME"]; $name = $mynode["NAME"]; return bget($name); } elseif (strtoupper($xmlnode["tag"]) == "SET") { //$name=$xmlnode["attributes"]["NAME"]; $mynode = upperkeysarray($xmlnode["attributes"]); $name = $mynode["NAME"]; $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); bset($name, $value); return $value; } elseif (strtoupper($xmlnode["tag"]) == "UPPERCASE") { $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); return strtoupper($value); } elseif (strtoupper($xmlnode["tag"]) == "FORMAL") { $nvalue = ""; $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); $value = strtolower($value); $words = split(" ", $value); for ($x = 0; $x < sizeof($words); $x++) { if ($x != 0) { $nvalue .= " "; } $nvalue .= ucfirst($words[$x]); } return $nvalue; } elseif (strtoupper($xmlnode["tag"]) == "LOWERCASE") { $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); return strtolower($value); } elseif (strtoupper($xmlnode["tag"]) == "GENDER") { $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); return gender($value); } elseif (strtoupper($xmlnode["tag"]) == "SENTENCE") { $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); return ucfirst($value); } elseif (strtoupper($xmlnode["tag"]) == "INPUT") { $mynode = upperkeysarray($xmlnode["attributes"]); //$index = $xmlnode["attributes"]["INDEX"]; if (!(is_array($mynode) && isset($mynode["INDEX"]))) { $mynode["INDEX"] = ""; } $index = $mynode["INDEX"]; if ($index == "") { $index = 1; } $index = $index - 1; return getinput($index); } elseif (strtoupper($xmlnode["tag"]) == "GOSSIP") { $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); insertgossip($value); return $value; } elseif (strtoupper($xmlnode["tag"]) == "PERSON") { $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); if ($value == "") { $value = $inputstar[0]; } return firstthird($value); } elseif (strtoupper($xmlnode["tag"]) == "PERSON2") { $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); if ($value == "") { $value = $inputstar[0]; } return firstsecond($value); } elseif (strtoupper($xmlnode["tag"]) == "THAT") { $mynode = upperkeysarray($xmlnode["attributes"]); //$indexes = $xmlnode["attributes"]["INDEX"]; if (is_array($mynode) && isset($mynode["INDEX"])) { $indexes = $mynode["INDEX"]; } else { $indexes = ""; } $indexes = split(",", $indexes); if (sizeof($indexes) < 2) { $indexes = array(); $indexes[] = 1; $indexes[] = 1; } return getthat($indexes[0], $indexes[1]); } elseif (strtoupper($xmlnode["tag"]) == "CONDITION") { $mynode = upperkeysarray($xmlnode["attributes"]); // First do multi condition name=value if (is_array($mynode) && isset($mynode["NAME"])) { $condname = $mynode["NAME"]; } else { $condname = ""; } if (is_array($mynode) && isset($mynode["VALUE"])) { $condvalue = $mynode["VALUE"]; } else { $condvalue = ""; } if (is_array($mynode) && isset($mynode["CONTAINS"])) { $condcontains = $mynode["CONTAINS"]; } else { $condcontains = ""; } if (is_array($mynode) && isset($mynode["EXISTS"])) { $condexists = $mynode["EXISTS"]; } else { $condexists = ""; } /* $condname=$mynode["NAME"]; $condvalue=$mynode["VALUE"]; $condcontains=$mynode["CONTAINS"]; $condexists=$mynode["EXISTS"]; */ // If this is a multi condition if ($condname != "" && $condvalue != "") { if ($condvalue != "") { $condtype = "VALUE"; } elseif ($condcontains != "") { $condtype = "CONTAINS"; } elseif ($condexists != "") { $condtype = "EXISTS"; } if ($condtype == "VALUE") { $condvalue = "^" . str_replace("*", "(.*)", $condvalue); //if ((bget($condname))==$condvalue){ # if (eregi($condvalue,bget($condname))){ if (stripos(bget($condname), $condvalue) !== false) { return recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); } } } elseif ($condname != "" && $condvalue == "") { $children = $xmlnode["children"]; $checkval = bget($condname); // After a match break. If no match then execute last if no name or val for ($randomc = 0; $randomc < sizeof($children); $randomc++) { if (strtoupper($children[$randomc]["tag"]) == "LI") { $mynode = upperkeysarray($children[$randomc]["attributes"]); //$condvalue=$children[$randomc]["attributes"]["VALUE"]; if (!(is_array($mynode) && isset($mynode["VALUE"]))) { $mynode["VALUE"] = ""; } $condvalue = $mynode["VALUE"]; $condvalue = "^" . str_replace("*", "(.*)", $condvalue) . "\$"; # if ((eregi($condvalue,$checkval))||($condvalue=="^\$")){ if (preg_match("/" . $condvalue . "/i", $checkval) || $condvalue == "^\$") { return recursechildren(realchild($children[$randomc]), $inputstar, $thatstar, $topicstar); } } } } elseif ($condname == "" && $condvalue == "") { $children = $xmlnode["children"]; // After a match break. If no match then execute last if no name or val for ($randomc = 0; $randomc < sizeof($children); $randomc++) { if (strtoupper($children[$randomc]["tag"]) == "LI") { $mynode = upperkeysarray($children[$randomc]["attributes"]); if (is_array($mynode) && isset($mynode["NAME"])) { $condname = $mynode["NAME"]; } else { $condname = ""; } if (is_array($mynode) && isset($mynode["VALUE"])) { $condvalue = $mynode["VALUE"]; } else { $condvalue = ""; } $condvalue = "^" . str_replace("*", "(.*)", $condvalue) . "\$"; # if ((eregi($condvalue,bget($condname))) || (($condvalue=="^\$")&&($condname==""))){ if (preg_match("/" . $condvalue . "/i", bget($condname)) || $condvalue == "^\$" && $condname == "") { return recursechildren(realchild($children[$randomc]), $inputstar, $thatstar, $topicstar); } } } } } elseif (strtoupper($xmlnode["tag"]) == "SYSTEM") { $command = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); exec($command, $execoutput); for ($x = 0; $x < sizeof($execoutput); $x++) { $allout = $allout . $execoutput[$x]; } return $allout; } elseif (strtoupper($xmlnode["tag"]) == "PHP") { $phpcode = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); ob_start(); eval($phpcode); $evaled = ob_get_contents(); ob_end_clean(); return $evaled; } elseif (strtoupper($xmlnode["tag"]) == "JUSTBEFORETHAT") { $indexes = array(); $indexes[] = 2; $indexes[] = 1; return getthat($indexes[0], $indexes[1]); } elseif (strtoupper($xmlnode["tag"]) == "JUSTTHAT") { $index = 2; $index = $index - 1; return getinput($index); } elseif (strtoupper($xmlnode["tag"]) == "BEFORETHAT") { $index = 3; $index = $index - 1; return getinput($index); } elseif (strtoupper($xmlnode["tag"]) == "GET_IP") { return getid(); } elseif (strtoupper($xmlnode["tag"]) == "GETNAME") { $name = "NAME"; return bget($name); } elseif (strtoupper($xmlnode["tag"]) == "GETSIZE") { return getsize(); } elseif (strtoupper($xmlnode["tag"]) == "GETTOPIC") { $name = "TOPIC"; return bget($name); } elseif (strtoupper($xmlnode["tag"]) == "GETVERSION") { return PROGRAMEVERSION; } elseif (substr(strtoupper($xmlnode["tag"]), 0, 4) == "GET_") { $name = substr($xmlnode["tag"], 4); return bget($name); } elseif (strtoupper($xmlnode["tag"]) == "SETNAME") { $name = "NAME"; $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); bset($name, $value); return $value; } elseif (strtoupper($xmlnode["tag"]) == "SETTOPIC") { $name = "TOPIC"; $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); bset($name, $value); return $value; } elseif (substr(strtoupper($xmlnode["tag"]), 0, 4) == "SET_") { $name = substr($xmlnode["tag"], 4); $value = recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar); bset($name, $value); return $value; } elseif (isdeprecated(strtoupper($xmlnode["tag"]), $ttag)) { $name = $ttag; return botget($name); } elseif (iscustomtag(strtoupper($xmlnode["tag"]), $ctfunction)) { return $ctfunction($xmlnode, $inputstar, $thatstar, $topicstar); } else { $name = $xmlnode["tag"]; $atts = $xmlnode["attributes"]; $atttext = ""; if ($atts != NULL) { foreach ($atts as $key => $value) { $atttext .= " {$key}=\"{$value}\""; } } $value = "<{$name}" . $atttext; if (isset($xmlnode["children"]) || strcmp($xmlnode["value"], "") != 0) { $value .= ">" . recursechildren(realchild($xmlnode), $inputstar, $thatstar, $topicstar) . "</{$name}>"; } else { $value .= "/>"; } return $value; } }
public function test405Routes() { $resultArray = array(); $this->expectOutputString('_'); respond(function () { echo '_'; }); respond('GET', null, function () { echo 'fail'; }); respond(array('GET', 'POST'), null, function () { echo 'fail'; }); respond(405, function ($a, $b, $c, $d, $methods) use(&$resultArray) { $resultArray = $methods; }); dispatch('/sure', 'DELETE'); $this->assertCount(2, $resultArray); $this->assertContains('GET', $resultArray); $this->assertContains('POST', $resultArray); }
$GLOBALS['TEMPLATES'] = PSU_BASE_DIR . '/app/%CUSTDIR%/templates'; if (file_exists(PSU_BASE_DIR . '/debug/%CUSTDIR%-debug.php')) { include PSU_BASE_DIR . '/debug/%CUSTDIR%-debug.php'; } IDMObject::authN(); $response->denied = function () use($app) { $app->tpl->display('access-denied.tpl'); // Is it ok to die here, or do we need a way to skip // future routes? (For example, if there is a final cleanup // routine.) die; }; $app->tpl = new \PSU\Template(); $app->user = PSUPerson::get($_SESSION['wp_id']); /** * Not all apps need this cool breadcrumb * functionality, so delete it if you aren't going to * use it. If you are, then uncomment it. * * $app->breadcrumbs = new \PSU\Template\Breadcrumbs; * $app->breadcrumbs->push( new \PSU\Template\Breadcrumb( 'Home', $app->config->get( '%CUSTDIR', 'base_url' ) . '/' ) ); */ $app->tpl->assign('user', $app->user); $app->tpl->assign('back_url', $_SERVER['HTTP_REFERER']); }); // // Nothing specific requested; show list of gatesystems // respond('GET', '/', function ($request, $response, $app) { $app->tpl->display('index.tpl'); });
<?php // Generic response (don't force the trailing slash: this should catch any accidental laziness) respond('/?', function ($request, $response, $app) { // Let's create a session variable, so we know where to redirect back to $app->params['called_url'] = $request->param('redirect_to'); $app->params['back_button_url'] = $request->param('came_from'); // Authenticate the user IDMObject::authN(); // If we got here, we must be authenticated // Redirect by changing the URL to send a success Flag to the JavaScript onLocationChange API $response->redirect('login-success/'); }); // Let's make sure to redirect them to the originally called URL if they requested to respond('/login-success/?', function ($request, $response, $app) { if (!empty($app->params['called_url'])) { // Redirect to the originally intended authentication url $response->redirect($app->params['called_url']); } });
if ($app->rave_user->unsubscribeFromGroup($ugroup)) { $_SESSION['successes'][] = 'Successfully unsubscribed from group: ' . $app->groups[$ugroup]['name']; unset($app->user_groups[$key]); } else { $_SESSION['errors'][] = 'Failed to unsubscribe from group: ' . $app->groups[$ugroup]['name']; } //end else } //end if } //end foreach }); // klein catch-all respond('/', function ($request, $response, $app) { if (isset($app->rave_user)) { foreach ($app->groups as &$group) { $group['subscribed'] = in_array($group['id'], $app->user_groups) ? 'checked="checked"' : ''; } //end foreach $app->tpl->assign('groups', $app->groups); $app->tpl->assign('rave_user', $app->rave_user); } //end if $app->tpl->display('index.tpl'); }); $app_routes = array(); foreach ($app_routes as $base) { with("/{$base}", $GLOBALS['BASE_DIR'] . "/routes/{$base}.php"); } //end foreach dispatch($_SERVER['PATH_INFO']);
<?php // Make sure user is logged in require_login(); // Load shift from storage $url_slug = $db->escape($_POST['id']); $shift = $db->row("\n SELECT id, user_id\n FROM shift\n WHERE url_slug = '{$url_slug}'\n"); // Sanity checks if (empty($shift)) { respond(0, "Shift not found."); } else { if ($shift->user_id != $user->id) { respond(0, "You don't have permission to delete that shift."); } } // Delete the shift $db->query("\n DELETE\n FROM shift\n WHERE id = {$shift->id}\n"); // Done respond(1, "Success.");
}); // Generic request respond('/', function ($request, $response, $app) { // Grab a couple of the request parameters $app->params['phonegap'] = $request->param('phonegap'); $app->params['cordova'] = $request->param('cordova'); $app->params['client_app'] = $request->param('client-app'); // Remove the variables if they're null if (is_null($app->params['phonegap'])) { unset($app->params['phonegap']); } if (is_null($app->params['cordova'])) { unset($app->params['cordova']); } if (is_null($app->params['client_app'])) { unset($app->params['client_app']); } // Show the index on a generic request $app->tpl->display('_wrapper.tpl'); }); $app_routes = array('newsfeed', 'campusmap', 'feedback', 'clusters', 'directory', 'events', 'login', 'logout', 'schedule', 'upgrade'); foreach ($app_routes as $base) { with("/{$base}", $GLOBALS['BASE_DIR'] . "/routes/{$base}.php"); } //end foreach // Let's do some cleanup respond(function ($request, $response, $app) { // Remove our "back button url" session var. It was only needed for a reload. unset($app->params['back_button_url']); }); dispatch($_SERVER['PATH_INFO']);
$stmt = $mysqli->prepare("DELETE s, f\n FROM services s\n LEFT OUTER JOIN files f ON s.id = f.service_id\n WHERE s.id = ?\n AND s.owner = ?\n ;"); $stmt->bind_param('ss', $SID, $uid); // EXECUTE AND CLOSE STATEMENT $stmt->execute(); $stmt->close(); $msg = array(); if (strlen($ifolder) > 3 and strlen($sfolder) > 3) { $path = "{$ifolder}/Services/{$sfolder}"; //$path = str_replace("'", "", "$ifolder/$sfolder")); // CHECK FILE EXISTS if (is_dir($path)) { // DELETE FOLDER AND FILES $cmd = "rm -rf " . escapeshellarg($path); system($cmd); $msg['CMD'] = $cmd; } else { $status = 'NOFOLDER'; $msg['FOLDER'] = $path; } } // RESPOND WITH SUCCES respond($status, $msg); } else { // RESPOND WITH REJECTION respond($status, ''); } // CLOSING CONNECTION $mysqli->close(); } else { echo "<html><head><title>Unauthorized Usage!</title></head><body>Get Lost!!!</body></html>"; }
$default->log->error("Cannot upload file '{$filename}'. Temp location: '{$tempfile}'. " . $lastMessage); $failed++; continue; } if ($result !== false) { $file['tmp_name'] = $result; $added[$key] = $file; } else { $failed++; } } } if ($failed) { respond(7, 'Could not add files to the system. Please inspect the log file. ' . $lastMessage); } else { respond(0, '', $added); } function respond($code, $msg, $uploads = array()) { global $output; $response = array('status_code' => $code, 'msg' => $msg, 'upload_status' => $uploads); switch ($output) { case 'xml': $xml = "<response>\n"; $xml .= "\t<status_code>{$code}</status_code>\n"; $xml .= "\t<msg>{$msg}</msg>\n"; $xml .= "\t<upload_status>\n"; $i = 0; foreach ($uploads as $key => $value) { $servername = $value['tmp_name']; $filesize = $value['size'];
function ejecutarAccion($data) { switch ($data['accion']) { case 'crear': crearInscripcion($data); break; case 'actualizar': actualizarInscripcion($data); break; case 'eliminar': eliminarInscripcion($data); break; case 'consultar': consultarInscripcion($data); break; case 'listar': listarInscripciones($data); break; case 'listadeestudiantes': listaDeEstudiantes($data); break; case 'listademenciones': listaDeMenciones($data); break; default: respond(400, 'Accion no definida'); break; } }
makeOrderDetailPizza($orderId, $detail[1], $pizzaId); //orderId, Quantity, pizzaId break; case 1: //Specialty Pizza makeOrderDetailPizza($orderId, $detail[1], $detail[2]); //orderId, Quantity, pizzaId break; case 2: //Item makeOrderDetailItem($orderId, $detail[1], $detail[2]); //orderId, Quantity, pizzaId break; } } respond(0, $orderId); //echo $message; if ($removeData) { mysqli_query($GLOBALS["conn"], "TRUNCATE TABLE Pizza_Toppings;"); mysqli_query($GLOBALS["conn"], "TRUNCATE TABLE Order_Details;"); mysqli_query($GLOBALS["conn"], "TRUNCATE TABLE Pizza_Toppings;"); mysqli_query($GLOBALS["conn"], "DELETE FROM Pizza WHERE pizzaId > 9"); mysqli_query($GLOBALS["conn"], "TRUNCATE TABLE Orders;"); mysqli_query($GLOBALS["conn"], "TRUNCATE TABLE Student;"); } /** * Status Codes: * 0: Success. No issues. * 1: Student already has an order. * */
function auth($username, $password, $requiresWrite) { $u = Database::escape(makeHash($username)); $pUnescaped = makeHash($password); Database::insert("INSERT INTO users (username, password, time_last_active, time_registered) VALUES (" . $u . ", " . Database::escape($pUnescaped) . ", " . time() . ", " . time() . ") ON DUPLICATE KEY UPDATE time_registered = IF(time_registered IS NULL, VALUES(time_registered), time_registered), password = IF(password IS NULL, VALUES(password), password), time_last_active = VALUES(time_last_active)"); $res = Database::selectFirst("SELECT id, password, write_lock_until, login_throttled_until FROM users WHERE username = "******"SELECT action_count FROM throttling WHERE username = "******" AND date_str = " . $date_str . " AND action_type = 'failed_login'"); // if the number of failed attempts has reached the critical threshold if (isset($throttling['action_count']) && $throttling['action_count'] >= CONFIG_THROTTLING_LOGIN_ATTEMPTS) { // throttle the user's login for some time $throttlingTimeout = intval(time() + 3600 * CONFIG_THROTTLING_LOGIN_HOURS); Database::update("UPDATE users SET login_throttled_until = " . $throttlingTimeout . " WHERE username = "******"INSERT INTO throttling (username, date_str, action_type) VALUES (" . $u . ", " . $date_str . ", 'failed_login') ON DUPLICATE KEY UPDATE action_count = action_count+1"); } respond(array('status' => 'not_authorized')); } } } else { respond(array('status' => 'not_authorized')); } return NULL; // suppress IDE warnings }
respond('/?', function ($request, $response, $app) { // Get the available clusters with the PSU REST API $clusters = (array) \PSU::api('backend')->get('clusters'); // Sort the returned clusters array /* This sort's the clusters array by this priority: * Number of computer's free * Building name * Cluster name */ usort($clusters, function ($a, $b) { // If the number of computers free are the same if ($a->num_computers_free == $b->num_computers_free) { // If the buildings are the same if ($a->building == $b->building) { // If the cluster name is the same if ($a->name == $b->name) { // Return 0. They're equal return 0; } else { // Return the name in alphabetical order return $a->name < $b->name ? -1 : 1; } //end else } else { // Return the name of the building in alphabetical order return $a->building < $b->building ? -1 : 1; } //end else } else { // Return the number of computers free, descending from the highest return $a->num_computers_free > $b->num_computers_free ? -1 : 1; } //end else }); // Assign the clusters array to the template $app->tpl->assign('clusters', $clusters); // Display the template $app->tpl->assign('show_page', 'clusters'); $app->tpl->display('_wrapper.tpl'); });
// Bring up a detail page for each computer of a certain model // respond('/item/model/[:model]/list/?', function ($request, $response, $app) { $items = ITSurplusAPI::by_model(array('model' => array($request->model))); $app->tpl->assign('items', $items[$request->model]['machines']); $app->tpl->display('item-list.tpl'); }); respond('/item/price/[:price]/?', function ($request, $response, $app) { if (strpos($request->price, 'to')) { $price = str_replace('to', '-', $request->price); } else { $price = $request->price . ' - ' . $request->price; } unset($_SESSION['messages']); $response->redirect($GLOBALS['BASE_URL'] . "/?price=" . $price); }); // // Bring up a detail page for a particular model // respond('/item/[:item]/?', function ($request, $response, $app) { $items = ITSurplusAPI::items(array('search_term' => $request->item)); $app->tpl->assign('item', $items[0]); $app->tpl->display('item.tpl'); }); // // Bring up a detail page for a particular model // respond('/howto/?', function ($request, $response, $app) { $app->tpl->display('howto.tpl'); }); dispatch($_SERVER['PATH_INFO']);
$op = $cl->load("storage.upload", ECROOT); $model['filekey'] = 'stgfile'; $model['rename'] = $storage['filename']; $model['savepath'] = $storage['filepath']; $model = $kernel->run($op, $model); if(!$model['valid']){ respond('<p class="error">'.$model['msg'].'</p>'); } $op = $cl->load("storage.update", ECROOT); $model['stgid'] = $storage['stgid']; $model['mime'] = $_POST['stgmime']; $model = $kernel->run($op, $model); if(!$model['valid']){ respond('<p class="error">'.$model['msg'].'</p>'); } $op = $cl->load("space.edit", ECROOT); $model['spvfname'] = $model['filename']; $model = $kernel->run($op, $model); if($model['valid']){ respond('<p class="success">File successfully uploaded</p>'); } else { respond('<p class="error">'.$model['msg'].'</p>'); } ?>
<?php PSU::get()->banner = PSU::db('psc1'); respond('/?', function ($request, $response, $app) { $ecommerce_running = shell_exec('ps ef | grep ecommerce_process.php | grep -v grep'); if ($ecommerce_running) { $_SESSION['messages'][] = 'The ECommerce processing script is currently running. Reload to check the status.'; $app->tpl->assign('ecommerce_processing', true); } //end if $app->tpl->assign('ecommerce_pending_files', \PSU\Ecommerce::pending_files()); $app->tpl->assign('ecommerce_pending', \PSU\Ecommerce::pending()); $app->tpl->assign('ecommerce_files', \PSU\Ecommerce::file_info()); $app->tpl->assign('ecommerce_report', \PSU\Ecommerce::report()); $app->tpl->display('ecommerce.tpl'); }); respond('/process', function ($request, $response, $app) { $user = PSU::isDev() ? 'nrporter' : 'webguru'; if (PSU::isDev() && !IDMObject::authN('mis')) { return; } //end if $command = '~' . $user . '/scripts/ecommerce_process.php --instance=' . strtolower(PSU::db('banner')->database) . ' &'; exec($command); $_SESSION['successes'][] = 'The ECommerce processing script has begun. Please check back shortly.'; PSU::redirect($GLOBALS['BASE_URL']); });
/* * 74cms 支付响应页面 * ============================================================================ * 版权所有: 骑士网络,并保留所有权利。 * 网站地址: http://www.74cms.com; * ---------------------------------------------------------------------------- * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和 * 使用;不允许对程序代码以任何形式任何目的的再发布。 * ============================================================================ */ define('IN_QISHI', true); require_once dirname(__FILE__) . '/../common.inc.php'; require_once QISHI_ROOT_PATH . 'include/mysql.class.php'; $db = new mysql($dbhost, $dbuser, $dbpass, $dbname); $funtype = array('1' => 'include/fun_company.php'); require_once QISHI_ROOT_PATH . $funtype[$_SESSION['utype']]; require_once QISHI_ROOT_PATH . "include/payment/alipay.php"; if (respond()) { $orderurl = array('1' => 'company_service.php?act=order_list'); $link[0]['text'] = "查看订单"; $link[0]['href'] = get_member_url($_SESSION['utype'], true) . $orderurl[$_SESSION['utype']]; $link[1]['text'] = "会员中心"; $link[1]['href'] = url_rewrite('QS_login'); $link[2]['text'] = "网站首页"; $link[2]['href'] = $_CFG['site_dir']; showmsg("付款成功!", 2, $link, false); } else { $link[0]['text'] = "会员中心"; $link[0]['href'] = get_member_url($_SESSION['utype']); showmsg("付款失败!请联系网站管理员", 0, $link); }
respond('POST', '/[:user]/[:id]', function ($request, $response) { $categoryid = $request->id; $userid = $request->user; $list = new UserList(); $save = $list->addUserCategory($categoryid, $userid); }); }); with('/api/usercategories/delete', function () { respond('POST', '/[:user]/[:id]', function ($request, $response) { $categoryid = $request->id; $userid = $request->user; $list = new UserList(); $save = $list->deleteUserCategory($categoryid, $userid); }); }); with('/api/usercategories/list', function () { respond('GET', '/[:user]', function ($request, $response) { $userid = $request->user; $list = new UserList(); $save = $list->getUserCategories($userid); $output = json_encode($save, JSON_PRETTY_PRINT); echo $output; }); }); with('/api', function () { respond('GET', '/', function ($request, $response) { header('Content-Type: text/html; charset=utf8'); require_once 'api.html'; }); }); dispatch();