public function users($app, $page) { $page = array_merge($page, array('title' => __('Users'), 'q' => $app->request()->params('q', ''))); $sort = $app->request()->params('sort', ''); $user = DatawrapperSession::getUser(); function getQuery($user) { global $app; $sort = $app->request()->params('sort', ''); $query = UserQuery::create()->leftJoin('User.Chart')->withColumn('COUNT(Chart.Id)', 'NbCharts')->groupBy('User.Id')->filterByDeleted(false); $q = $app->request()->params('q'); if ($q) { $query->where('email LIKE "%' . $q . '%" OR name LIKE "%' . $q . '%"'); } if (!$user->isSysAdmin()) { $query->filterByRole('sysadmin', Criteria::NOT_EQUAL); } switch ($sort) { case 'name': $query->orderByName('asc'); break; case 'email': $query->orderByEmail('asc'); break; case 'charts': $query->orderBy('NbCharts', 'desc'); break; case 'created_at': default: $query->orderBy('createdAt', 'desc'); break; } return $query; } $curPage = $app->request()->params('page', 0); $total = getQuery($user)->count(); $perPage = 50; $append = ''; if ($page['q']) { $append = '&q=' . $page['q']; } if (!empty($sort)) { $append .= '&sort=' . $sort; } add_pagination_vars($page, $total, $curPage, $perPage, $append); $page['users'] = getQuery($user)->limit($perPage)->offset($curPage * $perPage)->find(); $app->render('plugins/admin-users/admin-users.twig', $page); }
function fileSearch() { $wheres = array(); //input if ($_POST['filename'] != "") { $filenameValue = $_POST['filename']; $filenameQuery = "name LIKE '%" . $filenameValue . "%'"; array_push($wheres, $filenameQuery); } if ($_POST['startDate'] != "") { $startDateValue = strtotime($_POST['startDate']); $startDateQuery = "timestamp > '" . $startDateValue . "'"; array_push($wheres, $startDateQuery); } if ($_POST['endDate'] != "") { $endDateValue = strtotime($_POST['endDate']); $endDateQuery = "timestamp < '" . $endDateValue . "'"; array_push($wheres, $endDateQuery); } if (isset($_POST['uploader'])) { $uploaders = $_POST['uploader']; $uploaderArray = "("; for ($i = 0; $i < count($uploaders); $i++) { $uploaderArray .= $uploaders[$i] . ','; } $uploaderArray = substr($uploaderArray, 0, -1) . ')'; $uploaderQuery = "uploader IN " . $uploaderArray; array_push($wheres, $uploaderQuery); } //create query $searchQuery = "SELECT *, file.id AS fileId FROM file, user WHERE file.uploader = user.id"; for ($i = 0; $i < count($wheres); $i++) { $searchQuery .= " AND " . $wheres[$i]; } $searchQuery .= " ORDER BY file.id DESC"; $filesQuery = getQuery($searchQuery); $stringOfFiles = ""; while ($row = mysqli_fetch_assoc($filesQuery)) { $uploader = $row['uploader']; $name = $row['display_name']; $timestamp = $row['timestamp']; $date = date('d.m.Y H:i', $timestamp); $filename = $row['name']; $stringOfFiles .= getImageTags($filename) . '<a href="download.php?id=' . $row['fileId'] . '" target="_blank">' . $row['name'] . ' ' . getString("uploadedBy") . ' ' . $name . ' ' . $date . '</a>' . ' ' . '<a href="#" onClick= "shareFile(' . $row['fileId'] . ')">' . getString("shareFile") . '</a><br>'; } return $stringOfFiles; }
public function loginUser() { $o = new SaeTOAuthV2(WB_AKEY, WB_SKEY); $code = getQuery('code'); if (isset($code)) { $keys = array(); $keys['code'] = $code; $keys['redirect_uri'] = WB_CALLBACK_URL; try { $tokenData = $o->getAccessToken('code', $keys); } catch (OAuthException $e) { } } if ($tokenData) { $token = $tokenData['access_token']; $userData = $this->loadData($token); $data['uid'] = $this->userID; $data['nick'] = $this->userName; $data['pictureBig'] = $this->pictureBig; $data['pictureSmall'] = $this->pictureSmall; $data['access_token'] = $token; $data['mobile'] = $this->mobile; setMyCookie('weiboAuthToken', $data); //setcookie( 'weibojs_'.$o->client_id, http_build_query($tokenData)); return true; } else { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>UGG</title> </head> <body> <script type="text/javascript"> window.close(); </script> </body> </html> <?php } }
function mostUsedWordsAndEmoticons($user, $shortcuts) { if ($user == null) { $content = getQuery("SELECT content FROM message"); } else { $content = getQuery("SELECT content FROM message WHERE author = {$user}"); } $words = array(); $emoticons = array(); $numWords = 0; $numEmoticons = 0; while ($row = mysqli_fetch_assoc($content)) { $message = $row['content']; $exploded = preg_split('/\\s+/', $message); foreach ($exploded as $word) { if (isEmoticon($word, $shortcuts)) { $numEmoticons++; if (array_key_exists($word, $emoticons)) { $emoticons[$word] += 1; } else { $emoticons[$word] = 1; } } else { $word = str_replace('<br', '', $word); $stripped = preg_replace('/[^[:alnum:][:space:]]/u', '', strtolower($word)); if ($stripped != '') { $numWords++; if (array_key_exists($stripped, $words)) { $words[$stripped] += 1; } else { $words[$stripped] = 1; } } } } } asort($words); $words = array_reverse($words); asort($emoticons); $emoticons = array_reverse($emoticons); return array($words, $emoticons, $numWords, $numEmoticons); }
function addMetadata($data, &$Config, $types, $facets, $namespaces) { $datasetUri = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/'; $documentUri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $documentUri = array_shift(explode('?', $documentUri)); if ($query = getQuery()) { $documentUri .= '?' . $query; } if (isset($data[$documentUri])) { $documentUri .= '&_output=turtle'; } $DocumentGraph = new Graph($documentUri, $data); $count = 1; foreach ($data as $uri => $props) { $prop = rdf_ns . '_' . $count++; $DocumentGraph->setResource($prop, $uri); } if ($documentUri != $datasetUri) { $DocumentGraph->setResource(void_ns . 'inDataset', $datasetUri); } else { $DocumentGraph->setResource(rdf_ns . 'type', void_ns . 'Dataset'); foreach ($types as $type => $entities) { $classPartition = $DocumentGraph->setResource(void_ns . 'classPartition', $datasetUri . '?rdf:type=' . curie($type)); $classPartition->setResource(void_ns . 'class', $type); $classPartition->setLiteral(void_ns . 'entities', $entities); } foreach ($namespaces as $ns => $n) { $vocabUri = preg_replace('@#$@', '', $ns); $DocumentGraph->setResource(void_ns . 'vocabulary', $vocabUri); } } if (!empty($Config->license)) { $DocumentGraph->setResource(dcterms_ns . 'license', $Config->license); } if (!empty($Config->name)) { $DocumentGraph->setLiteral(dcterms_ns . 'title', $Config->name); } return $DocumentGraph->getIndex(); }
if ($condition1 != "none" && $condition2 == "dne") { $sql_query .= " AND it." . $condition1 . "!='" . $conditionval . "'"; } } $save_query = 'INSERT INTO REPORTS (user_id,query,report_name) VALUES ("' . $user . '","' . $sql_query . '","' . $fname . '")'; $result = mysql_query($sql_query, $database); if (mysql_num_rows($result) != 0 || $result) { $secondresult = mysql_query($save_query, $database); } if (!$result) { echo mysql_errno($database) . ": " . mysql_error($database) . "\n"; echo $sql_query; } return $result; } $result = getQuery($user, $column1, $column2, $column3, $condition1, $condition2, $conditionval, $fname, $database); $fields_num = mysql_num_fields($result); //echo "<h1>Table: {$table}</h1>"; echo "<table style='padding-left: 9cm' border='1'><tr>"; // printing table headers for ($i = 0; $i < $fields_num; $i++) { $field = mysql_fetch_field($result); echo "<td><b>{$field->name}</b></td>"; } echo "</tr>\n"; //echo "<table>"; while ($row = mysql_fetch_assoc($result)) { echo '<tr>'; foreach ($row as $field) { echo '<td>' . htmlspecialchars($field) . '</td>'; }
return encryptAES128CBC($data, $key, $key); } function isAdmin($query, $key) { $data = decryptAES128CBC($query, $key, $key); if (preg_match('/^[\\x{21}-\\x{7E}]*$/', $data)) { return strpos($data, ';admin=true;') !== false; } throw new Exception($data); } // don't output if we're included into another script. if (!debug_backtrace()) { $key = getRandomBytes(16); // 0..............f|0..............f|0..............f|0..............f // comment1=cooking|%20MCs;userdata= // | |userdata // ;comment|2=%20like%20a%20pound%20of%20bacon $query = getQuery('userdata', $key); $brokenQuery = substr($query, 0, 16) . str_repeat("", 16) . substr($query, 0, 16); try { isAdmin($brokenQuery, $key); } catch (Exception $e) { $error = $e->getMessage(); $recoveredKey = substr($error, 0, 16) ^ substr($error, 32); print "Keys match:\n"; print $key === $recoveredKey ? "Yes\n\n" : "No :(\n\n"; $query = encryptAES128CBC('comment1=cooking%20MCs;userdata=x;admin=true;comment2=%20like%20a%20pound%20of%20bacon', $recoveredKey, $recoveredKey); } print "Querystring has admin=true:\n"; print isAdmin($query, $key) ? "Yes\n\n" : "No :(\n\n"; }
$store->indexPredicates = false; } $title = ucwords($dataset); if (isset($_GET['_reload'])) { set_time_limit(0); $store->reset(); $data_file = $Config->{$dataset}->data; if (!is_file($data_file)) { throw new Exception("{$data_file} could not be found"); } $store->loadDataFile($data_file); // $store->loadData(file_get_contents($data_file)); // $this->createHierarchicalIndex(); } $types = $store->getTypes(); $query = getQuery(); $page = 1; $offset = isset($_GET['_page']) && ($page = $_GET['_page']) ? ($_GET['_page'] - 1) * 10 : 0; $showMap = strpos($query, '_near') !== false || isset($_GET['_near']) ? true : false; if (!empty($query)) { //query based title list($path, $value) = explode('=', $query); $value = curie($value); $title = local($value); if ($path == 'rdf:type') { $title = plural($title); } else { $title = local($path) . ': ' . $title; } $data = $store->query($query, 10, $offset); } else {
break; } //switch $trimCharlist = ".."; header("Content-Type: text/xml"); /* verify have enough to continue - set defaults for missing parameters as long as they are not mandatory At the moment, no required Fields - If all fields are null, a record will be inserted and the new userID returned. */ $link = mysqli_connect(Config::getDatabaseServer(), Config::getDatabaseUser(), Config::getDatabasePassword(), Config::getDatabase()); if (!$link) { // Server error mydie("Error connecting to Database"); } $sql = getQuery($operation, $link, $_REQUEST); if (Config::getDebug()) { $LOG->log("{$sql}", PEAR_LOG_INFO); } $rc = mysqli_multi_query($link, $sql); if (!$rc) { } if ($operation == 'updatebankbalance') { } else { } header('HTTP/1.1 200 OK'); $link->close(); /* Close Database */ //return xml $userSettings = new goUserSettings($userID); if (isset($userSettings)) {
function calcConnectionDirectConnection($first, $second, $startlimit, $maxdepth, $depth, $ignoredObjects, $ignoredPredicates, $fullconnection) { $time = microtime(true); mysql_connect($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['password']); mysql_select_db($GLOBALS['db']); //fuer alte Links if (isset($_GET['maxdepth'])) { $maxdepth = $_GET['maxdepth'] + 1; } $foundconnection = false; $limit = $startlimit; $idcounter = 0; $htmlcounter = 0; $saveRow = array(); //ignorierte Objekte/Praedikate kommen als Array an => Umrechnung in String fuer URL for ($i = 0; $i < count($ignoredObjects); $i++) { $permalinkIgnoreObjects .= '&ignoreObject_' . $i . '=' . $ignoredObjects[$i]; } for ($i = 0; $i < count($ignoredPredicates); $i++) { $permalinkIgnorePredicates .= '&ignorePredicate_' . $i . '=' . $ignoredPredicates[$i]; } //Ueberpruefung, ob gegebene Anfrage schon gespeichert ist include "queries.inc.php"; $savedIndex = isSaved($first, $second, $limit, $maxdepth, $depth, $ignoredObjects, $ignoredPredicates); //Falls gegebene Anfrage schon gespeichert ist=> Ausgeben if (is_int($savedIndex)) { $lastdepth = -1; for ($i = 0; $i < count($queries[$savedIndex]['savedResult']['row']); $i++) { echo $lastdepth != $queries[$savedIndex]['savedResult']['depth'][$i] ? '<table style="border:solid 1px #FF8040;margin-left:2px;"><tr><td style="background-color:#e4e4e4;border:1px solid #CFCFCF;">Distance: ' . ($queries[$savedIndex]['savedResult']['depth'][$i] + 1) . '</td></tr>' : ''; printResults($queries[$savedIndex]['savedResult']['row'][$i], $htmlcounter, $idcounter, $first, $second); echo $queries[$savedIndex]['savedResult']['depth'][$i] != $queries[$savedIndex]['savedResult']['depth'][$i + 1] || !isset($queries[$savedIndex]['savedResult']['depth'][$i + 1]) ? '</table><br>' : ''; $lastdepth = $queries[$savedIndex]['savedResult']['depth'][$i]; } echo 'This is a cached result. It was saved on ' . date('r', $queries[$savedIndex]['saveTime']) . '.<br>'; $queries[$savedIndex]['clickCount']++; file_put_contents('queries.inc.php', "<?\n\$queries=" . var_export($queries, true) . ";\n?>"); } else { if ($GLOBALS['usingClusterTable'] == true && $fullconnection == false) { $clusterConSwitch = calcConnectionCluster($first, $second, $maxdepth); if (is_Int($clusterConSwitch)) { $depth = $clusterConSwitch; echo 'We are now searching the complete data set for connections. Meanwhile, you may have a look at a preview result <a href="#" onclick="loadClusterConnection(\'ajax.php?f=6&first=' . str_replace("%", "__perc__", $first) . '&second=' . str_replace("%", "__perc__", $second) . $permalinkIgnoreObjects . $permalinkIgnorePredicates . '\')" title="Load Cluster Connection">here</a>.<br><br>'; echo '<div id="clusterCon" style="display:none;"></div>'; echo '<div id="ib_1000" style="position:absolute;top:500px;left:20%;width:200px;height:100px;"></div>'; #echo ', or maybe you want to <a href="'.substr($_SERVER['PHP_SELF'],0,-strlen($_SERVER['SCRIPT_NAME'])).'index.php?firstObject='.$first.'&secondObject='.$second.'&limit='.$startlimit.'&maxdistance='.$maxdepth.$permalinkIgnoreObjects.$permalinkIgnorePredicates.'&fullc=true&saved=saved">load the full Results</a>?<br><br>'; $fullconnection = true; } else { if ($clusterConSwitch == 'notenoughdistance') { echo 'For a Preview Result click <a href="#" onclick="loadClusterConnection(\'ajax.php?f=6&first=' . str_replace("%", "__perc__", $first) . '&second=' . str_replace("%", "__perc__", $second) . $permalinkIgnoreObjects . $permalinkIgnorePredicates . '\')" title="Load Cluster Connection">here</a>.<br>'; echo '<div id="clusterCon" style="display:none;"></div>'; echo '<div id="ib_0" style="position:absolute;top:500px;left:20%;width:200px;height:100px;"></div>'; } } } if ($fullconnection == true || $GLOBALS['usingClusterTable'] == false) { ob_flush(); flush(); do { //Berechnung der Verbindung, falls dieses moeglich ist $res = mysql_query(getQuery($depth, $first, $second, $limit, $ignoredObjects, $ignoredPredicates)) or die(mysql_error()); if (mysql_num_rows($res) > 0) { $limit = $limit - mysql_num_rows($res); $foundconnection = true; echo '<table style="border:solid 1px #FF8040;margin-left:2px;"><tr><td style="background-color:#e4e4e4;border:1px solid #CFCFCF;">Distance: ' . ($depth + 1) . '</td></tr>'; while ($row = mysql_fetch_row($res)) { printResults($row, $htmlcounter, $idcounter, $first, $second); $saveRow['row'][] = $row; $saveRow['depth'][] = $depth; } echo '</table><br>'; } else { if ($depth == $maxdepth - 1) { echo "No Connection Found at max. Distance {$maxdepth} !<br><br>"; //f�r maximale Tiefe Fehlschlag ausgeben #if ($GLOBALS['usingClusterTable']==true) #calcConnectionCluster($first,$second,$maxdepth,true); } } $depth++; } while ($depth < $maxdepth && $limit > 0); if ($foundconnection == true) { //Queries koennen abgespeichert werden, wenn eine Verbindung gefunden wurde echo '<span style="padding-left:2px;">Would you like to <a href="#" title="save Query" onmousedown="saveQuery(\'ajax.php?f=3&first=' . str_replace("%", "__perc__", $first) . '&second=' . str_replace("%", "__perc__", $second) . '&limit=' . $startlimit . '&maxdepth=' . $maxdepth . $permalinkIgnoreObjects . $permalinkIgnorePredicates . '&depth=' . $depth . '\',\'' . str_replace('%', '__perc__', str_replace('"', '__quot__', serialize($saveRow))) . '\');">save</a> your query?</span><br>'; echo '<span style="padding-left:2px;"><div id="save"> </div></span><br>'; } } } echo 'Result obtained in ' . round(microtime(true) - $time, 3) . ' seconds.<br>'; }
foreach ($result_img as $img) { $url = $modx->getOption("upload_dir") . $img['name']; $r['url'] = $url; if ($num_imgs == 1) { $stuff_images = $url; } else { $stuff_images .= getChunk($stuff_img_html, $r); } } if ($num_imgs == 1) { $stuff_images = "<div class=\"item-photo-one\"><img src=\"" . $stuff_images . "\" alt=\"" . htmlspecialchars($result[0]['name']) . "\" class=\"im\"></div>"; } else { $stuff_images = "<div class=\"item-photos\">" . $stuff_images . "</div>"; } $query_material = "SELECT `value` FROM `modx_items_prop` WHERE `key` = 'Материал' AND `item_code_1c`='" . $stuff_code_1c . "' "; $result_material = getQuery($query_material, $path); $keywords = htmlspecialchars($result[0]['keywords']); $description = htmlspecialchars($result[0]['description']); $title = $result[0]['title']; if (!$title) { $title = $result[0]['name']; } $title = htmlspecialchars($title); // TODO: Выполнить рефакторинг с использованием массива данных $props и $modx->setPlaceholders(array $props, $prefix); $modx->setPlaceholder("stuff_id", $stuff_code_1c); $modx->setPlaceholder("stuff_name", $result[0]['name']); $modx->setPlaceholder("stuff_h1", $result[0]['h1']); $modx->setPlaceholder("stuff_title", $title); $modx->setPlaceholder("stuff_description", $description); $modx->setPlaceholder("stuff_keywords", $keywords); $modx->setPlaceholder("imgalt_name", htmlspecialchars($result[0]['name']));
</table> <table id="results"> <?php // Only runs the following if user has selected something if (isset($_POST['movieID']) && $_POST['movieID'] != -1 || isset($_POST['director']) && $_POST['director'] != -1 || isset($_POST['genre']) && $_POST['genre'] != -1 || isset($_POST['rating']) && $_POST['rating'] != -1) { $searchMovie = $_POST['movieID']; $searchDirector = $_POST['director']; $searchGenre = $_POST['genre']; $searchRating = $_POST['rating']; echo "<tr><td class='center' colspan='100'>✰ Your Movie Results ✰</td></tr>"; echo "<tr><th>Movie Title</th>"; echo "<th>Director</th>"; echo "<th>Genre</th>"; echo "<th>Rating</th></tr>"; $results = getQuery($searchMovie, $searchDirector, $searchGenre, $searchRating); foreach ($results as $resultDisplay) { echo "<tr>"; echo "<td><a href='moreInfo.php?id=" . $resultDisplay['movieID'] . "'>" . $resultDisplay['title'] . "</a></td>"; echo "<td>" . $resultDisplay['director'] . "</td>"; echo "<td>" . $resultDisplay['genre'] . "</td>"; echo "<td>" . $resultDisplay['rating'] . "</td>"; echo "</tr>"; } // Puts search results into a table foreach ($results as $inputs) { $sql = "INSERT INTO temp_movie_length\n\t\t\t\t\t\tVALUES('" . $inputs['length'] . "')"; $stmt = $conn->prepare($sql); $stmt->execute(); } $maxYear = getMaxYear();
function renewSession() { if (isset($_COOKIE['usercookie'])) { $cookie = $_COOKIE['usercookie']; $cookieResult = mysqli_fetch_array(getQuery("SELECT id FROM user_session WHERE token ='{$cookie}'")); if (!empty($cookieResult)) { $id = $cookieResult['id']; $_SESSION['user'] = mysqli_fetch_array(getQuery("SELECT * FROM user WHERE id ='{$id}'")); } } }
function uploadUserOrChatImage($file, $uploader, $savePath, $maxSize, $type) { $originalFileName = $file["name"][0]; $uploadTime = time(); $fileSize = $file["size"][0]; //Create unique id for file $fileIdresult = getQuery("SELECT * FROM file WHERE id=(SELECT MAX(id) FROM file)"); $newFileIdAssoc = $fileIdresult->fetch_assoc(); $newFileId = $newFileIdAssoc["id"] + 1; //check if file is an image: $mime = mime_content_type($file['tmp_name'][0]); if (!strstr($mime, "image/")) { printJson('{"status": "failure", "message": " ' . $originalFileName . ' ' . getString('notAnImage') . '."}'); return; } //Format for filename 'id.fileExtension' $newFileName = $newFileId . substr($originalFileName, strrpos($originalFileName, '.')); if ($fileSize > $maxSize) { printJson('{"status": "failure", "message": " ' . $originalFileName . ' ' . getString('fileIsTooLarge') . '."}'); return; } //Add to database setQuery("INSERT INTO file (path, uploader, name, mime_type, timestamp) VALUES ('{$newFileName}', '{$uploader}', '{$originalFileName}','{$mime}', '{$uploadTime}')"); $success = move_uploaded_file($file['tmp_name'][0], $savePath . $newFileName); if ($success && $type == "userImage") { setUserImage($uploader, $newFileId); printJson('{"status": "success", "message": " ' . getString('theFile') . ' ' . $originalFileName . ' ' . getString('wasUploaded') . '."}'); } elseif ($success && $type == "chatImage") { setChatImage($newFileId, $uploader); printJson('{"status": "success", "message": " ' . getString('theFile') . ' ' . $originalFileName . ' ' . getString('wasUploaded') . '."}'); } else { printJson('{"status": "success", "message": "' . getString('uploadFailed') . '."}'); } }
$query = "SELECT `name`, `entry`.id, `coralId`, `year`, `month`, `day`, `avatar`, `coralDescription`, `description`, `rarity`, `venomous` FROM `entry` INNER JOIN `coral` ON `entry`.coralId =`coral`.id WHERE `entry`.id = " . $entryId; getQuery($query, $connect); break; case 'editEntry': $entryId = $_GET['entryId']; $description = $_GET['description']; $query = "UPDATE `entry` SET `description` = '" . $description . "' WHERE `id` = " . $entryId; mysqli_query($connect, $query); echo json_encode(["Edit success"]); break; case 'deleteEntry': $entryId = $_GET['entryId']; $query = "DELETE FROM `entry` WHERE `id` = " . $entryId; mysqli_query($connect, $query); echo json_encode(["Delete success"]); break; case 'getReviewEntries': $query = "SELECT `name`, `entry`.id, `year`, `month`, `day`, `time`, `avatarThumbnail` FROM `entry` INNER JOIN `coral` ON `entry`.coralId =`coral`.id WHERE `userId` = " . $userId . " AND `status` = 0 ORDER BY `entry`.id DESC;"; getQuery($query, $connect); break; } function getQuery($query, $connect) { $results = mysqli_query($connect, $query); $resultArray = []; while ($row = mysqli_fetch_assoc($results)) { $resultArray[] = $row; } echo json_encode($resultArray); exit; }
function checkURL() { foreach ($GLOBALS['typedata'] as $plural => $data) { if (($term = getQuery([$plural, $data[0]])) !== null) { $plural($plural, $term); } } }
<statuscode>403</statuscode> <statusmessage>Forbidden</statusmessage> <userdashboard> */ $LOG = Config::getLogObject(); //parse query parameters , called via HTTP GET //Filtering $params = array(); $params['userid'] = $_GET['userid']; //open connect to database $link = mysqli_connect(Config::getDatabaseServer(), Config::getDatabaseUser(), Config::getDatabasePassword(), Config::getDatabase()); if (!$link) { header('HTTP/1.1 500 Internal Server Error'); mydie("Error connecting to Database"); } $sql = getQuery($params); $LOG->log($sql, PEAR_DEBUG); $cursor = mysqli_query($link, $sql); if (!$cursor) { // Server error header('HTTP/1.1 500 Internal Server Error'); mydie(mysqli_error($link) . " executing {$sql}", $link); } header("content-type: text/xml"); echo '<?xml version="1.0"?>'; Utility::emitXML("", 'userdashboard', 0); Utility::emitXML("200", 'statuscode'); Utility::emitXML("OK", 'statusmessage'); $recordsEmitted = 0; $totalBets = 0; $totalBets = 0;
/** * Actualiza el perfil del usuario registrado en el sitio. Los datos * del perfil actualizados son: correo e idioma. */ public function updateProfile() { try { // se obtiene el correo del usuario $email = JUser::getInstance(JFactory::getUser()->id)->email; // se establece el valor del idioma $language = JFactory::getUser()->getParam('language'); if (strcmp($language, 'ca-ES') == 0) { $language = 'catalan'; } else { if (strcmp($language, 'es-ES') == 0) { $language = 'spanish'; } else { $language = 'english'; } } // se obtiene el nombre del usuario $username = $this->currentUser; // se actualiza el idioma $query = str_replace('%language%', $language, getQuery('updateLanguage')); $query = str_replace('%username%', $username, $query); $resultQuery = $this->proxyMySql->query($query); // se actualiza el correo $query = str_replace('%email%', $email, getQuery('updateEmail')); $query = str_replace('%username%', $username, $query); $resultQuery = $this->proxyMySql->query($query); } catch (Exception $e) { } }
function getNumbers() { global $stats; $stats['Key numbers'] = array(); $emoticonSql = getQuery("SELECT shortcut FROM emoticon"); $shortcuts = array(); while ($row = mysqli_fetch_assoc($emoticonSql)) { $emoticonShortcuts = $row['shortcut']; $exploded = explode(' ', $emoticonShortcuts); foreach ($exploded as $shortcut) { $shortcuts[] = $shortcut; } } $messagesTable = mysqli_fetch_assoc(getQuery("SELECT COUNT(*) FROM message")); $messages = $messagesTable['COUNT(*)']; $stats['Key numbers']['Number of messages'] = $messages; if ($messages > 0) { $usersQuery = getQuery("SELECT id, username FROM user"); $users = array(); while ($user = mysqli_fetch_assoc($usersQuery)) { $users[] = $user; } $stats['Key numbers']['Messages per user'] = array(); foreach (array_keys($users) as $user) { ////////////////////////////////////////////////////////////////////// HER VISES IKKE NAVNET I JSON-EN $id = $users[$user]['id']; $userMessagesTable = mysqli_fetch_assoc(getQuery("SELECT COUNT(*) FROM message WHERE author = {$id}")); $userMessages = $userMessagesTable['COUNT(*)']; $stats['Key numbers']['Messages per user'][$user] = array(); $stats['Key numbers']['Messages per user'][$user]['Total'] = $userMessages; $stats['Key numbers']['Messages per user'][$user]['Percentage'] = printPercentage($userMessages, $messages); } $skypeTable = mysqli_fetch_assoc(getQuery("SELECT COUNT(*) FROM message WHERE skype = 1")); $skype = $skypeTable['COUNT(*)']; $stats['Key numbers']['Messages from Skype'] = array(); $stats['Key numbers']['Messages from Skype']['Total'] = $skype; $stats['Key numbers']['Messages from Skype']['Percentage'] = printPercentage($skype, $messages); $notSkypeTable = mysqli_fetch_assoc(getQuery("SELECT COUNT(*) FROM message WHERE skype = 0")); $notSkype = $notSkypeTable['COUNT(*)']; $stats['Key numbers']['Messages not from Skype'] = array(); $stats['Key numbers']['Messages not from Skype']['Total'] = $notSkype; $stats['Key numbers']['Messages not from Skype']['Percentage'] = printPercentage($notSkype, $messages); $lengthTable = mysqli_fetch_assoc(getQuery("SELECT AVG(LENGTH(content)) FROM message")); $length = $lengthTable['AVG(LENGTH(content))']; $stats['Key numbers']['Average message length'] = round($length, 2); $stats['Key numbers']['Average message length per user'] = array(); foreach (array_keys($users) as $user) { ////////////////////////////////////////////////////////////////////// HER VISES IKKE NAVNET I JSON-EN $id = $users[$user]['id']; $userLengthTable = mysqli_fetch_assoc(getQuery("SELECT AVG(LENGTH(content)) FROM message WHERE author = {$id}")); $userLength = $userLengthTable['AVG(LENGTH(content))']; $stats['Key numbers']['Average message length per user'][$user] = array(); $stats['Key numbers']['Average message length per user'][$user]['Total'] = round($userLength, 2); } /* list($mostUsedWords, $mostUsedEmoticons, $numWordsTotal, $numEmoticonsTotal) = mostUsedWordsAndEmoticons(null, $shortcuts); $numWordsUnique = sizeof($mostUsedWords); $content[] = '<br>'.getString('totNoWords').': '.$numWordsTotal.'<br>'; $content[] = '<br>'.getString('totNoUniqueWords').': '.$numWordsUnique.'<br>'; $content[] = '<br>'.getString('mostUsedWords').':<br>'; printWordList($mostUsedWords, false); $numEmoticonsUnique = sizeof($mostUsedEmoticons); $content[] = '<br>'.getString('totNoEmoticons').': '.$numEmoticonsTotal.'<br>'; $content[] = '<br>'.getString('totNoUniqueEmoticons').': '.$numEmoticonsUnique.'<br>'; $content[] = '<br>'.getString('mostUsedEmoticons').':<br>'; printWordList($mostUsedEmoticons, false); foreach ($users as $user) { list($userWords, $userEmoticons, $numWordsUser, $numEmoticonsUser) = mostUsedWordsAndEmoticons($user['id'], $shortcuts); $numWordsUserUnique = sizeof($userWords); $content[] = '<br>'.getString('noWordsFor').' '.$user['username'].': '.$numWordsUser.'<br>'; $content[] = '<br>'.getString('noUniqueWordsFor').' '.$user['username'].': '.$numWordsUserUnique.'<br>'; $content[] = '<br>'.getString('mostUsedWordsFor').' '.$user['username'].':<br>'; printWordList($userWords, false); $numEmoticonsUserUnique = sizeof($userEmoticons); $content[] = '<br>'.getString('noEmoticonsFor').' '.$user['username'].': '.$numEmoticonsUser.'<br>'; $content[] = '<br>'.getString('noUniqueEmoticonsFor').' '.$user['username'].': '.$numEmoticonsUserUnique.'<br>'; $content[] = '<br>'.getString('mostUsedEmoticonsFor').' '.$user['username'].':<br>'; printWordList($userEmoticons, false); $content[] = '<br>'.getString('relMostUsedWordsFor').' '.$user['username'].':<br>'; $relWords = array(); foreach ($userWords as $k => $v) { if ($mostUsedWords[$k] >= 10) // To avoid words you've used 1-9 times and no one else uses to dominate the list $relWords[$k] = ($v / $numWordsUser) / ($mostUsedWords[$k] / $numWordsTotal); } asort($relWords); $relWords = array_reverse($relWords); printWordList($relWords, true); $content[] = '<br>'.getString('relMostUsedEmoticonsFor').' '.$user['username'].':<br>'; $relEmoticons = array(); foreach ($userEmoticons as $k => $v) { if ($mostUsedWords[$k] >= 10) // To avoid emoticons you've used 1-9 times and no one else uses to dominate the list $relEmoticons[$k] = ($v / $numEmoticonsUser) / ($mostUsedEmoticons[$k] / $numEmoticonsTotal); } asort($relEmoticons); $relEmoticons = array_reverse($relEmoticons); printWordList($relEmoticons, true); }*/ } }
function displayForm($feed) { $entries = $feed->getEntryIDs(); $add = getQuery('add', false); if ($add && !in_array($add, $entries)) { array_unshift($entries, $add); } $missing = false; foreach ($entries as $k => $v) { $path = '../content/' . $v . '.xml'; $entries[$k] = array('id' => $v, 'path' => $path, 'exists' => file_exists($path)); if (!$entries[$k]['exists']) { $missing = true; } } if ($missing) { ?> <div class="error"> <ol start="<?php echo $add ? 0 : 1; ?> "> <?php foreach ($entries as $e) { $x = $e['exists']; ?> <li class="xmlfile-<?php echo $x ? 'exists' : 'missing'; ?> "> <?php echo $x ? '✔' : '✘'; ?> <a href="<?php echo htmlspecialchars($e['path']); ?> "><?php echo htmlspecialchars($e['id']); ?> .xml</a> <?php if ($x) { $stat = stat($e['path']); echo $stat['size'] . ' bytes'; } else { echo 'Does not exist.'; } ?> </li> <?php } ?> </ol> <p> Make sure all xml files are uploaded to the content folder before downloading <?php echo $feed->getFilename(); ?> </p> </div> <?php } ?> <form action="index.php" method="post"> <h1><label for="lineup">Feature Line-up:</label></h1> <small>(Enter feature IDs, one per line)</small> <textarea id="lineup" name="lineup" rows="10" cols="60"><?php foreach ($entries as $entry) { echo $entry['id'] . "\n"; } ?> </textarea> <div class="actions"> <input type="Submit" class="action" value="Download <?php echo $feed->getFilename(); ?> " /> </div> </form> <?php }
break; default: $jsonError = ' - Unknown error'; break; } //not a valid json value found if (is_null($decoded)) { $response['status'] = array('type' => 'error', 'value' => 'Invalid JSON value found', 'error' => $jsonError); } else { require 'API.php'; /* adding API */ $peopleID; $responseArray; $queryProvided = $decoded["query"]; //sending user SMS code $queryResults = getQuery($queryProvided); if ($queryResults) { $responseArray = ["result" => $queryResults]; } else { if ($smsSendResults == 0) { $responseArray = ["message" => "database not responding", "responseType" => $smsSendResults]; } else { if ($smsSendResults == -1) { $responseArray = ["message" => "No results", "responseType" => $smsSendResults]; } } } /* reponse returns the following: results sends data results based on query 0 database not responding
} else { if (!empty($userID) && empty($userName)) { $userName = Utility::getUserIDOrName($userID, 'id'); } } if (empty($userID)) { mydie("Incomplete Parameters", 500); } //if $link = mysqli_connect(Config::getDatabaseServer(), Config::getDatabaseUser(), Config::getDatabasePassword(), Config::getDatabase()); if (!$link) { // Server error header('HTTP/1.1 500 Internal Server Error'); mydie("Error connecting to Database"); } $sql = getQuery($link, $userID); if (Config::getDebug()) { $LOG->log("{$sql}", PEAR_LOG_INFO); } $cursor = mysqli_query($link, $sql); if (!$cursor) { // Server error header('HTTP/1.1 500 Internal Server Error'); mydie(mysqli_error($link), 500, $link); } header('HTTP/1.1 200 OK'); header("Content-Type: text/xml"); echo '<?xml version="1.0" encoding="UTF-8"?>'; /* Fetch the results of the query */ Utility::emitXML("", 'game_invites', 0); Utility::emitXML('200', 'status_code');
$cookie = $_COOKIE['usercookie']; $cookieResult = mysqli_fetch_array(getQuery("SELECT id FROM user_session WHERE token ='{$cookie}'")); if (!empty($cookieResult)) { $id = $cookieResult['id']; $_SESSION['user'] = mysqli_fetch_array(getQuery("SELECT * FROM user WHERE id ='{$id}'")); mysqli_close($connection); header('Location: chat.php'); die; } } if (isset($_POST['username'])) { //Preprocess username and password $username = strtolower($connection->real_escape_string($_POST['username'])); $password = password_hash($connection->real_escape_string($_POST['password']), PASSWORD_DEFAULT); //Look for matching users $user = mysqli_fetch_array(getQuery("SELECT * FROM user WHERE username = '******'")); //If a matching user was found, redirect to chat if (password_verify($connection->real_escape_string($_POST['password']), $user['password'])) { $_SESSION['user'] = $user; $token = $_SESSION['user']['id'] . password_hash(strval(time()), PASSWORD_DEFAULT); $id = $_SESSION['user']['id']; setQuery("INSERT INTO user_session VALUES ({$id}, '{$token}')"); //Close connection to database mysqli_close($connection); setcookie('usercookie', $token, 86400 * 365 * 100); header('Location: chat.php'); die; } //Close connection to database mysqli_close($connection); //Store error message if login was unsuccessful
/* verify have enough to continue - set defaults for missing parameters as long as they are not mandatory */ if (!isset($userID)) { mydie("paramaters not complete"); } $params['userid'] = $userID; $params['operation'] = strtolower($operation); $params['query'] = $query; $link = mysqli_connect(Config::getDatabaseServer(), Config::getDatabaseUser(), Config::getDatabasePassword(), Config::getDatabase()); if (!$link) { // Server error header('HTTP/1.1 500 Internal Server Error'); mydie("Error connecting to Database"); } $sql = getQuery($params, $link); if (Config::getDebug()) { $LOG->log("{$sql}", PEAR_LOG_INFO); } $cursor = mysqli_query($link, $sql); if (!$cursor) { // Server error mydie(mysqli_error($link), "500", $link); } $numberOfFriends = $cursor->num_rows; header('HTTP/1.1 200 OK'); // Fetch the results of the query header("Cache-Control: no-cache, must-revalidate"); header("content-type: text/xml"); echo '<?xml version="1.0"?>'; Utility::emitXML("", 'go_friends', 0);
<table border=0> <tr><td></td><td></td></tr> <?php foreach ($data as $field => $val) { echo "<tr><td>{$field}</td><td> => </td><td> {$val}</td></tr>"; } ?> </table> <?php } else { p("User doesn't exists", 2); } } else { //Display random users $sql = "SELECT * \n\t\t\t\tFROM users\n\t\t\t\tWHERE activated=1\n\t\t\t\tORDER BY RAND()\n\t\t\t\tLIMIT 24\n\t\t\t"; $data = getQuery($sql); if ($data) { p("Fun Random Users :)", 2); foreach ($data as $u) { ?> <a href="?page=user&id=<?php echo $u['user_id']; ?> "> <img src="http://www.gravatar.com/avatar/<?php echo md5($u['email']); ?> ?d=monsterid"> <br> <?php echo $u['username'];
} else { $passwordMessage = "invalid password"; } } //Update page updateUserSession(); header('Location: chat.php'); die; } $languages = getQuery("SELECT * FROM language"); $languageOptions = ''; while ($lang = mysqli_fetch_assoc($languages)) { $selected = $lang['id'] == $user['language'] ? " selected" : ""; $languageOptions .= '<option value="' . $lang['id'] . '"' . $selected . '>' . $lang['local_name'] . '</option>'; } $styles = getQuery("SELECT * FROM style"); $styleOptions = ''; while ($style = mysqli_fetch_assoc($styles)) { $selected = $style['id'] == $user['style'] ? " selected" : ""; $styleOptions .= '<option value="' . $style['id'] . '"' . $selected . '>' . $style['name'] . '</option>'; } $checked = $user['mute_sounds'] == 1 ? ' checked' : ''; $checkbox = '<input type="checkbox" name="sound" id="muteSound" class="form-control" data-toggle="toggle" data-on="' . getString('on') . '" data-off="' . getString('off') . '" ' . $checked . '> '; ?> <h1 class="tab-header col-sm-12"><?php echo getString('settings'); ?> </h1> <form method="post" action=""> <div class="form-horizontal settings-form"> <div class="form-group dropdown-form-group">
if (!mysql_select_db($username, $database)) { die('Could not select database: ' . mysql_error()); } $reportname = $_POST["rn"]; function getQuery($reportname, $database) { //$find_query="SELECT query FROM REPORTS WHERE report_name='$reportname'"; $mysql_query = mysql_result(mysql_query("SELECT query FROM REPORTS WHERE report_name='{$reportname}'"), 0); $result = mysql_query($mysql_query, $database); if (!$result) { echo mysql_errno($database) . ": " . mysql_error($database) . "\n"; echo $sql_query; } return $result; } $result = getQuery($reportname, $database); $fields_num = mysql_num_fields($result); //echo "<h1>Table: {$table}</h1>"; echo "<table style='padding-left: 9cm' border='1'><tr>"; // printing table headers for ($i = 0; $i < $fields_num; $i++) { $field = mysql_fetch_field($result); echo "<td><b>{$field->name}</b></td>"; } echo "</tr>\n"; //echo "<table>"; while ($row = mysql_fetch_assoc($result)) { echo '<tr>'; foreach ($row as $field) { echo '<td>' . htmlspecialchars($field) . '</td>'; }
function doApiInTheFace($parameters, $method = 'POST') { $query = getQuery($parameters); $curl = curl_init(); if ($method === 'GET') { curl_setopt($curl, CURLOPT_URL, 'http://ws.audioscrobbler.com/2.0/?' . $query); curl_setopt($curl, CURLOPT_POST, false); } else { curl_setopt($curl, CURLOPT_URL, 'http://ws.audioscrobbler.com/2.0/'); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $query); } curl_exec($curl); curl_close($curl); }
*/ require_once '../utils/random-bytes.php'; require_once '10-implement-cbc-mode.php'; function getQuery($userData, $key, $iv) { $data = http_build_query(['comment1' => 'cooking MCs', 'userdata' => $userData, 'comment2' => ' lke a pound of bacon'], null, ';', PHP_QUERY_RFC3986); return encryptAES128CBC($data, $key, $iv); } function isAdmin($query, $key, $iv) { $data = decryptAES128CBC($query, $key, $iv); return strpos($data, ';admin=true;') !== false; } // don't output if we're included into another script. if (!debug_backtrace()) { $key = getRandomBytes(16); $iv = getRandomBytes(16); // 0..............f|0..............f|0..............f|0..............f|0..............f // comment1=cooking|%20MCs;userdata= // | |aaaaaaaaaaaaaaaa|bbbb;admin=true | // ;comment2=%20like%20a%20pound%20of%20bacon $badData = 'aaaaaaaaaaaaaaaabbbb;admin=true'; $goodData = 'aaaaaaaaaaaaaaaabbbbbbbbbbbbbbb'; $bitMask = substr($badData ^ $goodData, 16); $query = getQuery($goodData, $key, $iv); for ($i = 32; $i < 47; $i++) { $query[$i] = $query[$i] ^ $bitMask[$i - 32]; } print "Querystring has admin=true:\n"; print isAdmin($query, $key, $iv) ? "Yes\n\n" : "No :("; }
//a positive integer value of days into the future - 0 means today //Sorting //open connect to database $link = mysqli_connect(Config::getDatabaseServer(), Config::getDatabaseUser(), Config::getDatabasePassword(), Config::getDatabase()); if (!$link) { header('HTTP/1.1 500 Internal Server Error'); mydie("Error connecting to Database"); } //prep hash lookup tables $lookupHash = lookupHash($link); //$t=$params['team']; //echo("team " . $lookupHash[$t]); exit; //$teamID = array_search($params['team'],$lookupHash); //print_r($lookupHash); exit; //exit; $sql = getQuery($params, $lookupHash); $cursor = mysqli_query($link, $sql); if (!$cursor) { // Server error header('HTTP/1.1 500 Internal Server Error'); mydie(mysqli_error($link) . " executing {$sql}", $link); } header("content-type: text/xml"); echo '<?xml version="1.0"?>'; Utility::emitXML("", 'publicgames', 0); Utility::emitXML("200", 'statuscode'); Utility::emitXML("OK", 'statusmessage'); $recordsEmitted = 0; // while records to read/ retrieve and emit xml while ($row = mysqli_fetch_assoc($cursor)) { $recordsEmitted++;