function printmessages() { //Print error messages initialise_messages(); $messages = $_SESSION['messages']; // move from session to local $log_to_file = false; // true will start writing to a file if (!empty($messages)) { //if messages exist //first part of message if (!empty($messages['success'])) { //if success messages exist. foreach ($messages['success'] as $value) { if ($log_to_file) { log_to_file("Success", $value); } echo '<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Success!</strong> ' . $value . '</div>'; } } if (!empty($messages['alerts'])) { //if alert messages exist. foreach ($messages['alert'] as $value) { if ($log_to_file) { log_to_file("Alert", $value); } echo '<div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Alert!</strong> ' . $value . '</div>'; } } if (!empty($messages['errors'])) { //if error messages exist. foreach ($messages['errors'] as $value) { if ($log_to_file) { log_to_file("Error", $value); } echo '<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> <strong>Warning!</strong> ' . $value . '</div>'; } } //end of message clear_messages(); //clear message and start again. } }
function ResultadoDetalleExtendido($Resultado) { if (!$this->user || !$this->password) { $ret = generate_error("Autenticacion", "", "ResultadoDetalleExtendido"); } else { $payload = file_get_contents("php://input"); log_to_file("wsSeguimiento XMLrequest: " . $payload); log_to_file("wsSeguimiento request: " . serialize($Resultado)); $ret = get_ResultadoDetalleExtendido($Resultado->ResultadoExtendido, $this->user, $this->password); } log_to_file("wsSeguimiento response: " . serialize($ret)); return $ret; }
function saveimage() { log_to_file('snyggve', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'File saved in snyggve by ' . $_SESSION['login']['id'] . ' and file ' . $_FILES['image']['tmp_name'], ''); if (!is_numeric(str_replace('_', '', $_POST['image_id']))) { die('Error (Visst är det skönt med felmeddelanden utan förklaring?) #' . __LINE__); } $query = 'INSERT INTO snyggve(title, owner, timestamp) VALUES("' . htmlspecialchars($_POST['title']) . '", ' . $_SESSION['login']['id'] . ', ' . time() . ')'; mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); $id = mysql_insert_id(); system('cp ' . SNYGGVE_TEMP_PATH . 'thumb/' . $_POST['image_id'] . '.jpg ' . SNYGGVE_PERM_PATH . 'thumb/' . $id . '.jpg'); system('cp ' . SNYGGVE_TEMP_PATH . 'full/' . $_POST['image_id'] . '.jpg ' . SNYGGVE_PERM_PATH . 'full/' . $id . '.jpg'); return $id; }
function load_config() { $filename = "/var/xenoblade/config.txt"; $mysql_user = ""; $mysql_host = ""; $mysql_pass = ""; $mysql_database = ""; $settings = array(); if (fopen($filename, "r") == false) { $log_message = "CRITICAL: Unable to load config file! Webpages will not load at all without it."; log_to_file($log_message); } $handle = fopen($filename, "r") or die("Error loading config file! Please contact a system administrator to get this fixed! Webservices are non-functional without it."); while (($line = fgets($handle)) !== false) { // Fetch config information line-by-line if (strcmp(stristr($line, "mysql_user:"******"mysql_user:"******"", $line)); } if (strcmp(stristr($line, "mysql_host:"), $line) == 0) { $mysql_host = trim(str_ireplace("mysql_host:", "", $line)); } if (strcmp(stristr($line, "mysql_pass:"******"mysql_pass:"******"", $line)); } if (strcmp(stristr($line, "mysql_database:"), $line) == 0) { $mysql_database = trim(str_ireplace("mysql_database:", "", $line)); } } fclose($handle); $settings[0] = $mysql_user; $settings[1] = $mysql_host; $settings[2] = $mysql_pass; $settings[3] = $mysql_database; // Check to see if any of the settings are empty. If they are, // that means that there is a typo in one of the settings // ie "myr_rpc_uer: " instead of "myr_rpc_user: "******"CRITICAL: Unable to load config file due to a damaged setting! Please go through the config file to correct the error. Webpages will not load at all without the config file."; log_to_file($log_message); die("Error loading config file! Please contact a system administrator to get this fixed! Webservices are non-functional without it."); } } return $settings; }
function admin_action_count($admin_id, $event) { switch ($event) { case 'post_removed': $query_insert = 'INSERT INTO admin_counts (user_id, posts_removed) VALUES ("' . $admin_id . '", 1)'; $query_update = 'UPDATE admin_counts SET posts_removed = posts_removed + 1 WHERE user_id="' . $admin_id . '"'; break; case 'avatar_denied': $query_insert = 'INSERT INTO admin_counts (user_id, avatars_denied) VALUES ("' . $admin_id . '", 1)'; $query_update = 'UPDATE admin_counts SET avatars_denied = avatars_denied + 1 WHERE user_id="' . $admin_id . '"'; break; case 'avatar_approved': $query_insert = 'INSERT INTO admin_counts (user_id, avatars_approved) VALUES ("' . $admin_id . '", 1)'; $query_update = 'UPDATE admin_counts SET avatars_approved = avatars_approved + 1 WHERE user_id="' . $admin_id . '"'; break; } log_to_file('admin', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'admin_action_count ' . $event, $query_insert); mysql_query($query_insert) or mysql_query($query_update) or die(report_sql_error($query_update, __FILE__, __LINE__)); }
function send_mail() { $email_text = ''; // Useful data from $_SERVER $email_text .= 'Client IP: ' . $_SERVER[REMOTE_ADDR] . '<br/>'; $email_text .= 'Client User Agent: ' . $_SERVER[HTTP_USER_AGENT] . '<br/>'; //$email_text .= 'Client IP: '. $_SERVER[CONTENT_TYPE] => application/x-www-form-urlencoded .'<br/>'; $email_text .= 'Referer: ' . $_SERVER[HTTP_REFERER] . '<br/>'; $email_text .= 'Languages Accepted: ' . $_SERVER[HTTP_ACCEPT_LANGUAGE] . '<br/>'; $email_text .= '<br/>'; $email_text .= 'Contact Name: ' . $_POST['name'] . '<br/>'; $email_text .= 'Contact Email: ' . $_POST['email'] . '<br/>'; $email_text .= 'Subject: ' . $_POST['subject'] . '<br/>'; $email_text .= 'Message: ' . $_POST['message']; $body = "<h2>Contacto desde BarcaraCardozo.com</h2>"; $body .= $email_text; $headers = "From: " . $_POST['email'] . " <" . $_POST['email'] . ">\r\n"; //optional headerfields $headers .= "Return-Path:<" . $_POST['email'] . ">\r\n"; // avoid ending in spam folder http://php.net/manual/en/function.mail.php // To send HTML mail, the Content-type header must be set $headers .= 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; ini_set('sendmail_from', $_POST['email']); // TODO: los errores logueados a disco // Por si no tengo servidor de email try { // bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] ) if (!mail('*****@*****.**', 'Contacto desde BarcaraCardozo.com', $body, $headers)) { log_to_file('logs/' . date("YmdHis") . '.log', 'No se pudo enviar el correo: ' . $email_text); return false; } else { return true; } } catch (Exception $e) { // Por problemas técnicos no se pudo enviar notificacion log_to_file('logs/' . date("YmdHis") . '.log', 'No se pudo enviar el correo: ' . $email_text . ' (' . $e->getMessage() . ')'); return false; } }
function distribute_server_get($options) { /* Use this function to retrieve a list of servers to distribute items to or to retrieve a server that hosts an item options explenation ------------------------------------------------------- types array of required types status required status (not implemented, defaults to 'active') item_handle only servers holding a copy of this item item_type item type return array key value ------------------------------------------------------- server_id server id address valid internet host name */ global $entertain_types; if (isset($options['item_handle'])) { //find servers hosting this item $query = 'SELECT ds.server_id server_id, ds.address address FROM distributed_items di, distribute_servers ds, entertain_items items' . ' WHERE di.server_id = ds.server_id ' . ' AND items.id = di.item_id ' . ' AND items.handle = "' . $options['item_handle'] . '"' . ' AND di.type = "' . $options['type'] . '"' . ' AND di.status = "ok"' . ' AND ds.status = "active"' . ' ORDER BY RAND() LIMIT 1'; log_to_file('distribute', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'fetching server', $query); $result = mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); if ($data = mysql_fetch_assoc($result)) { $server['server_id'] = $data['server_id']; $server['address'] = $data['address']; } log_to_file('distribute', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'server fetched', print_r($server, true)); return $server; } elseif (isset($options['types'])) { $query = 'SELECT ds.server_id as server_id, ds.address as address' . ' FROM distribute_servers ds, distribute_servers_types dst' . ' WHERE ds.server_id = dst.server_id AND ds.status = "active"' . ' AND type IN ("' . implode('", "', $options['types']) . '")'; $result = mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); log_to_file('distribute', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'servers fetched', $query); while ($data = mysql_fetch_assoc($result)) { $servers[] = $data; } return $servers; } }
function cache_update_forum_reported() { log_to_file('deprecated', LOGLEVEL_INFO, __FILE__, __LINE__, 'cache_update_forum_reported()'); }
// We wait for all the fork child to finish while ($fork_num > 0) { $status = null; pcntl_waitpid(-1, $status); $fork_num--; } //end } //end if break; } //end switch & thread //}//end foreach } //end while log_to_file('======================= Finished Regenerating Metadata ' . date('d-m-Y h:i:s') . ' =======================', LOG_FILE); if (file_exists(SYNCH_FILE)) { unlink(SYNCH_FILE); } //end if exit(0); /** * Prints the specified prompt message and returns the line from stdin * * @param string $prompt the message to display to the user * * @return string * @access public */ function get_line($prompt = '') {
function tips_send($options) { /* options kommentar reciever e-mail sender_id user_id sender_name full name (a regular string) subject email subject string message html message string */ // check if reciever has recieved before, how many times and if reciever accepts tip e-mail if (check_email($options['reciever'])) { return 'not a valid e-mail address'; } $query = 'SELECT * FROM tips_recievers WHERE reciever="' . $options['reciever'] . '"'; $result = mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); if ($data = mysql_fetch_assoc($result)) { $has_recieved = true; $status = $data['status']; $hash = $data['hash']; } else { $has_recieved = false; $status = 'first_time'; } if ($has_recieved) { if ($status == 'accepts') { // if reciever has recieved before and accepts, send e-mail with standard pre-message - "accepted" } else { // if reciever has recieved before but not (yet) accepted, do nothing and return error return 'denies'; } } else { // if reciever has not recived before, send e-mail with standard pre-message - "first time" and save to database $hash = md5(rand()); $query = 'INSERT INTO tips_recievers (reciever, hash) VALUES ("' . $options['reciever'] . '", "' . $hash . '")'; mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); } if (isset($options['sender_id'])) { $query = 'SELECT username FROM login WHERE id="' . $options['sender_id'] . '"'; $result = mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); if ($data = mysql_fetch_assoc($result)) { $sender = $data['username']; if ($sender == 'Borttagen') { return 'false_sender'; } } else { return 'false_sender'; } } else { $sender = $options['sender_name']; } if ($status == 'first_time') { $message = 'Hej, någon som säger sig heta ' . $sender . ' vill tipsa dig om en kul grej på Hamsterpaj!' . "\n" . 'Eftersom vi hatar spam har vi spärrat din mailadress från fler tips, du kommer inte få fler tips eller utmaningar från hamsterpajare om du inte tackar ja till det.' . "\n" . "\n" . $options['message'] . "\n" . "\n" . 'För att kolla in tipset och tacka ja till fler tips och utmaningar, använd den här länken: ' . "\n" . 'http://www.hamsterpaj.net/tips.php?action=accept&link=' . $options['link'] . '&hash=' . $hash . "\n" . "\n" . 'För att kolla in tipset, men inte tacka ja till fler tips och utmaningar, använd den här länken:' . "\n" . 'http://www.hamsterpaj.net/tips.php?action=view&link=' . $options['link'] . '&hash=' . $hash . "\n"; } elseif ($status == 'accepts') { $message = 'Hej igen, nu vill någon som säger sig heta ' . $sender . ' tipsa dig om en grej på Hamsterpaj!' . "\n" . "\n" . $options['message'] . "\n" . "\n" . 'Kolla in tipset här:' . "\n" . 'http://www.hamsterpaj.net/tips.php?action=view&link=' . $options['link'] . '&hash=' . $hash . "\n" . 'Du får det här tipset eftersom du tidigare tackat ja till att ta emot tips och utmaningar från användare på Hamsterpaj.' . "\n" . "\n" . 'Om du vill spärra din e-postadress från fler tips och utmaningar, använd den här länken:' . "\n" . 'http://www.hamsterpaj.net/tips.php?action=deny&link=' . $options['link'] . '&hash=' . $hash . "\n"; } $headers = 'From: tips@hamsterpaj.net' . "\r\n"; mail($options['reciever'], $options['subject'], $message, $headers); log_to_file('tips', LOGLEVEL_DEBUG, __FILE__, __LINE__, $reciever . ' recieved message: (subject: ' . $options['subject'] . ') ' . $message); return 'ok'; }
/** returns an array of results $return[' */ function quality_get_array($text) { // these are the weights for all factors affecting the final score $options['weight']['capital_post'] = 0.3; $options['weight']['capital_sentence'] = 0.8; $options['weight']['short_sentence'] = 1; $options['weight']['comma'] = 1; $options['weight']['spelling'] = 0.6; $options['weight']['rubbish'] = 1; $options['weight']['repetition'] = 1; $options['weight']['long_sentence'] = 0.5; $options['weight']['long_sentence_no_comma'] = 1; $options['weight']['length'] = 3; // settings // sentence length boundaries $options['words_in_short_sentence'] = 4; $options['words_in_long_sentence'] = 45; // post length boundaries in words $options['post_length']['limit_a'] = 3; //from -1 to 0 $options['post_length']['limit_b'] = 30; // 0 $options['post_length']['limit_c'] = 100; //from 0 to 1 $options['post_length']['limit_d'] = 400; // 1 $options['post_length']['limit_e'] = 1000; //from 1 to -1 $options['post_length']['limit_f'] = 1500; // rubbish words and expressions $options['rubbish'] = array('o', 'lol', 'lr', 'Elr'); // word lengths $options['words']['limit_long'] = 11; //remove all html tags log_to_file('henrik', LOGLEVEL_DEBUG, __FILE__, __LINE__, $text); $text = strip_tags($text); // remove qouted text $text = preg_replace('/\\[citat:[\\w-åäö]+=\\d+\\](.*)\\[\\/citat\\]/m', '', $text); // remove answer tags $text = preg_replace('/\\[svar:[\\w-åäö]+=\\d+\\]/', '', $text); $text = preg_replace('/\\[\\/svar\\]/', '', $text); // replace dots in host names $text = preg_replace('/((\\w+)\\.)+(com|net|nu|se|org|eu)/', 'hostname', $text); // remove propritary tags $text = preg_replace('/\\[.*\\]/', '', $text); // count words and words length $words = preg_split('/[\\s,\\.\\?!:;]+/', trim($text)); // $result['words']['words'] = $words; $result['words']['count'] = count($words); $result['words']['long'] = 0; foreach ($words as $word) { if (count($word) > $options['words']['limit_long']) { $result['words']['long']++; } } $result['words']['long_fraction'] = $result['words']['long'] / $result['words']['count']; //Hitta upprepningar av ord $uniq = array_unique($words); $result['words']['repetition'] = count($words) - count($uniq); // sentence length // the avarage length of sentences and count of short and long sentences $result['sentence']['count'] = 0; $result['sentence']['short'] = 0; $result['sentence']['long'] = 0; // split text into sentences $sentences = preg_split('/[\\.!\\?\\n]+/', trim($text)); $result['commas']['long_sentence_no_comma'] = 0; foreach ($sentences as $sentence) { $sentence = trim($sentence); if (strlen($sentence) > 8) { // count the words in each sentence $words = preg_split('/[ ,\\.!\\?\\t#\\*_\\n:;]+/', trim($sentence)); $result['sentence']['wordcount'] += count($words); if (count($words) < $options['words_in_short_sentence'] && count(trim($sentence)) > 0) { $result['sentence']['short']++; $result['sentence']['short_sentences'][] = $sentence; } if (count($words) > $options['words_in_long_sentence']) { $result['sentence']['long']++; $commas = preg_match_all('/([\\wåäö], [\\wåäö])/', $text, $matches); if ($commas < 1) { $result['commas']['long_sentence_no_comma']++; } $result['sentence']['long_sentences'][] = $sentence; } if (preg_match('/^\\s*[A-ZÅÄÖ]/', $sentence, $matches)) { $result['sentence']['starters'][] = $matches[0]; $result['capital']['sentence']++; } $result['sentence']['sentences'][] = $sentence; } } $result['sentence']['count'] = count($result['sentence']['sentences']); $result['sentence']['avarage'] = $result['words']['count'] / $result['sentence']['count']; // points for short and long sentences $result['score']['short_sentence'] = -$options['weight']['short_sentence'] * ($result['sentence']['short'] / $result['sentence']['count']); $result['score']['long_sentence'] = -$options['weight']['long_sentence'] * ($result['sentence']['long'] / $result['sentence']['count']); // post length // points given for post length in words and in these intervals /* limits are named from limit_a to limit_f, x = count($words), s = score x < a => s = -1 a < x < b => s = from -1 at a to 0 at b b < x < c => s = 0 c < x < d => s = from 0 at c to 1 at d d < x < e => s = 1 e < x < f => s = from 1 at e to -1 at f f < x => s = -1 */ $result['length'] = $result['words']['count']; //limit - 0 if ($result['length'] < $options['post_length']['limit_a']) { $result['score']['length'] = -1; } elseif ($result['length'] < $options['post_length']['limit_b']) { $result['score']['length'] = -($options['post_length']['limit_b'] - $result['length']) / ($options['post_length']['limit_b'] - $options['post_length']['limit_a']); } else { if ($result['length'] < $options['post_length']['limit_c']) { $result['score']['length'] = 0; } else { if ($result['length'] < $options['post_length']['limit_d']) { $result['score']['length'] = ($result['length'] - $options['post_length']['limit_c']) / ($options['post_length']['limit_d'] - $options['post_length']['limit_c']); } else { if ($result['length'] < $options['post_length']['limit_e']) { $result['score']['length'] = 1; } else { if ($result['length'] < $options['post_length']['limit_f']) { $result['score']['length'] = 1 - ($result['length'] - $options['post_length']['limit_e']) / (($options['post_length']['limit_f'] - $options['post_length']['limit_e']) / 2); } else { $result['score']['length'] = -1; } } } } } // kommatecken // antalet kommatecken i texten. // poäng ges för antalet kommatecken i förhållande till antalet meningar $result['comma']['count'] = 0; $result['comma']['count'] = preg_match_all('/([\\wåäö], [\\wåäö])/', $text, $matches); $result['comma']['comma_per_sentence'] = $result['comma']['count'] / $result['sentence']['count']; // Versal i början på inlägg // Boolean, om inlägget börjar med versal $matches = array(); $result['capital']['post'] = preg_match_all('/^[A-Z]/', trim($text), $matches); //Förekomst av uttryck och tecken som ger minuspoäng $intersect = array_intersect($rubbish, $words); $result['rubbish']['rubbish_per_sentence'] = count($intersect) / $result['sentences']['count']; $result['rubbish']['rubbish_per_sentence'] = $result['rubbish']['rubbish_per_sentence'] > 0 ? $result['rubbish']['rubbish_per_sentence'] : 0; //todo! Kör stavningskontroll via shell_exec. Poäng för antal felstavningar i förhållande till antalet ord. $words_string = preg_replace('/[^[:alpha:]åäö]/i', ' ', strip_tags(html_entity_decode($text))); preg_match_all('/& ([[:alpha:]åäö]+) \\d+ \\d+: ((([[:alpha:]åäö]+),?\\s?)+)/mi', shell_exec('echo "' . $words_string . '" | aspell --lang=sv -a --sug-mode=ultra'), $matches); $result['spelling']['words_misspelled'] = count($matches[1]); // övriga poäng //length har redan räknats ut ovan $result['score']['long_sentence'] = -$result['sentence']['long'] / $result['sentence']['count']; $result['score']['short_sentence'] = -max($result['sentence']['short'] - $result['sentence']['count'] / 4, 0) / $result['sentence']['count']; $result['score']['comma'] = $result['comma']['comma_per_sentence']; $result['score']['long_sentence_no_comma'] = $result['comma']['long_sentence_no_comma'] / ($result['sentence']['count'] * 2); $result['score']['spelling'] = -$result['spelling']['words_misspelled'] / $result['sentence']['count']; $result['score']['capital_post'] = $result['capital']['post'] ? 1 : -1; // A sentence without initial capital is -2, a sentence with an initial capital is +1 // w = sentences with initial capital // o = sentences without initial capital // t = total number of sentences // score = w/t - 2(o/t) = (w - 2o)/t = (w - 2(t - w))/t = (w - 2t + 2w)/t = (3w - 2t)/t = 3(w/t) - 2 // -1 is minimum score $result['score']['capital_sentence'] = max(3 * $result['capital']['sentence'] / $result['sentence']['count'] - 2, -1); $result['score']['repetition'] = $result['repetition'] / count($words); $result['score']['rubbish'] = $result['rubbish']['rubbish_per_sentence']; $total = 0; $totalweight = 0; foreach ($result['score'] as $key => $score) { if ($score != 0) { $totalweight += $options['weight'][$key]; $total += $score * $options['weight'][$key]; } } $q = $total / $totalweight; $result['quality_rank'] = $q > 0 ? sqrt($q) : -sqrt(abs($q)); $points = $result['score']; $suggestions['short_sentences'] = 'undvik väldigt korta meningar'; $suggestions['long_sentences'] = 'skriv inte för långa meningar'; $suggestions['length'] = 'skriva ett längre inlägg'; $suggestions['comma'] = 'använda komma för att få en mer lättläst text'; $suggestions['long_sentence_no_comma'] = 'använd komma i långa meningar för att få texten mer lättläst'; $suggestions['capital'] = 'börja ny mening med stor bokstav (versal)'; $suggestions['rubbish'] = 'undvika chatt-språk och förkortningar'; $suggestions['spelling'] = 'stava rätt'; $suggestions['repetition'] = 'försök att variera ditt ordval'; unset($quality_suggestions); if ($points['long_sentence'] < 0) { $quality_suggestions[] = $suggestions['long_sentences']; } if ($points['short_sentence'] < 0) { $quality_suggestions[] = $suggestions['short_sentences']; } if ($points['length'] < 0) { $quality_suggestions[] = $suggestions['length']; } if ($points['comma'] < 0) { $quality_suggestions[] = $suggestions['comma']; } if ($points['long_sentence_no_comma'] < 0) { $quality_suggestions[] = $suggestions['long_sentence_no_comma']; } if ($points['capital_sentence'] < 0) { $quality_suggestions[] = $suggestions['capital']; } if ($points['rubbish'] < 0) { $quality_suggestions[] = $suggestions['rubbish']; } if ($points['spelling'] < 0) { $quality_suggestions[] = $suggestions['spelling']; } if ($points['capital'] < 0) { $quality_suggestions[] = $suggestions['capital']; } if ($points['repetition'] < 0) { $quality_suggestions[] = $suggestions['repetition']; } $result['quality_suggestions'] = $quality_suggestions; return $result; }
function discussions_create_handle($title) { $handle = url_secure_string($title); for ($i = 0; $i < 50; $i++) { $new_handle = $i == 0 ? $handle : $handle . '_' . $i; $query = 'SELECT id FROM discussions WHERE handle LIKE "' . $new_handle . '" LIMIT 1'; $result = mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); if (mysql_num_rows($result) == 0) { return $new_handle; } } /* If no free handle could be found */ log_to_file('forum', LOGLEVEL_ERROR, __FILE__, __LINE__, 'Could not find any free discussion handles, giving up', serialize(array($title))); return md5(rand(0, 99999999999)); }
function updateMetas($metas) { global $site; $dbh = $site->getDatabase(); $ret = false; if ($metas && is_array($metas)) { try { $dbh->query('START TRANSACTION'); $sql = "INSERT INTO {$this->meta_table} (id, {$this->meta_id}, value, name) VALUES (0, :meta_id, :value, :name) ON DUPLICATE KEY UPDATE value = :value"; $stmt = $dbh->prepare($sql); foreach ($metas as $name => $value) { if (is_array($value) || is_object($value)) { $value = serialize($value); } $stmt->bindValue(':meta_id', $this->id); $stmt->bindValue(':value', $value); $stmt->bindValue(':name', $name); $stmt->execute(); } $dbh->query('COMMIT'); $ret = true; } catch (PDOException $e) { log_to_file("Database error: {$e->getCode()} (Line {$e->getLine()}) in {$this->singular_class_name}::" . __FUNCTION__ . ": {$e->getMessage()}.", 'crood'); } } return $ret; }
/** * Saves a film from POST form to database * options new a new film update update an existing film * @return handle, the films handle */ function films_film_save($options) { if ($_POST['film_type'] == 'bilder') { unset($_SESSION['new_film_temp']); } global $film_categories; // Make handle from title $handle = isset($_POST['handle']) ? $_POST['handle'] : url_secure_string($_POST['title']); $release = isset($_POST['release_now']) ? time() : strtotime($_POST['release']); $film_type = $_POST['film_type']; if (isset($options['new'])) { $query = 'INSERT INTO film (handle, title, film_type, category_id, `release`, extension, use_special_code, html, trailer_id)'; $query .= ' VALUES ("' . $handle . '", "' . $_POST['title'] . '", "' . $film_type . '", "' . $_POST['film_category'] . '", "' . $release . '", "' . (isset($_SESSION['new_film_temp']['extension']) ? $_SESSION['new_film_temp']['extension'] : '') . '", "' . (isset($_POST['use_special_code']) ? '1' : '0') . '", "' . addslashes(html_entity_decode($_POST['special_code'])) . '", "' . $_POST['trailer_id'] . '")'; $schedule['type'] = 'new_' . $film_type; $_POST['url'] = '/' . $film_type . '/' . $film_categories[$_POST['film_category']]['handle'] . '/' . $handle . '.html'; $schedule['data'] = serialize($_POST); $schedule['release'] = $release; schedule_event_add($schedule); } elseif (isset($options['update'])) { $query = 'UPDATE film SET title = "' . $_POST['title'] . '"'; $query .= ', film_type = "' . $film_type . '"'; $query .= ', `release` = "' . $release . '"'; $query .= ', trailer_id = "' . $_POST['trailer_id'] . '"'; $query .= ', category_id = "' . $_POST['film_category'] . '"'; $query .= isset($_SESSION['new_film_temp']['extension']) ? ', extension = "' . $_SESSION['new_film_temp']['extension'] . '"' : ''; $query .= ', use_special_code = "' . (isset($_POST['use_special_code']) ? '1' : '0') . '"'; $query .= isset($_POST['use_special_code']) ? ', html="' . addslashes(html_entity_decode($_POST['special_code'])) . '"' : ''; $query .= ' WHERE handle = "' . $handle . '"'; } // echo '<p>' . $query . '</p>'; log_to_file('films', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'query: ' . $query); mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); $query = 'SELECT id, handle FROM film WHERE handle = "' . $handle . '"'; $result = mysql_query($query) or die(report_sql_error($query)); if ($data = mysql_fetch_assoc($result)) { $film_id = $data['id']; $film_handle = $data['handle']; } unset($save); $save['item_id'] = $game_id; $save['object_type'] = 'film'; $save['add'] = true; foreach (explode(',', $_POST['tags']) as $keyword) { $keyword = trim($keyword); $save['tag_label'][] = $keyword; } tag_set_wrap($save); /* Resize, convert and save the uploaded thumbnail */ if (strlen($_FILES['thumbnail']['tmp_name']) > 1) { system('convert ' . $_FILES['thumbnail']['tmp_name'] . ' -resize 120!x90! ' . IMAGE_PATH . 'film/' . $film_handle . '.png'); } if ($film_type == 'bilder') { system('convert ' . $_FILES['thumbnail']['tmp_name'] . ' -resize 460x345 ' . IMAGE_PATH . 'fun_images/' . $film_handle . '.jpg'); } // echo '<p>Nu är filmen sparad och filmens handle är: ' . $film_handle . '</p>' . "\n"; // echo '<p>Direktlänken blir då <a href="http://www.hamsterpaj.net/' . $film_type . '/' . $film_categories[$_POST['film_category']]['handle'] . '/' . $film_handle . '.html">' . // 'http://www.hamsterpaj.net/' . $film_type . '/' . $film_categories[$_POST['film_category']]['handle'] . '/' . $film_handle . '.html</a' . "\n"; $film['handle'] = $handle; $film['extension'] = $_SESSION['new_film_temp']['extension']; $film['url'] = 'http://www.hamsterpaj.net/' . $film_type . '/' . $film_categories[$_POST['film_category']]['handle'] . '/' . $film_handle . '.html'; return $film; }
// { // If there are previous votes including one from current user $queryupdate = 'UPDATE item_ranks SET' . ' average = "' . $average . '", ' . ' count = "' . $count . '"' . ' WHERE item_id="' . $_GET['item_id'] . '"' . ' AND item_type="' . $_GET['item_type'] . '"'; /* } else { // If there are previous votes but none from this user $queryupdate = 'UPDATE item_ranks SET' . ' count = count + 1,' . ' average = average + ("' . $_GET['rank'] . '" / (count + 1))' . ' WHERE item_id="' . $_GET['item_id'] . '"' . ' AND item_type="' . $_GET['item_type'] . '"'; } */ log_to_file('rank', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'rank new item', $queryinsert); log_to_file('rank', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'update item rank', $queryupdate); mysql_query($queryinsert) or mysql_query($queryupdate) or die(report_sql_error($queryupdate, __FILE__, __LINE__)); if (!isset($old_rank)) { $query = 'INSERT INTO user_ranks (item_id, item_type, rank, user_id) VALUES ("' . $_GET['item_id'] . '", "' . $_GET['item_type'] . '", "' . $_GET['rank'] . '", "' . $_SESSION['login']['id'] . '")'; } else { $query = 'UPDATE user_ranks SET' . ' rank="' . $_GET['rank'] . '"' . ' WHERE user_id="' . $_SESSION['login']['id'] . '"' . ' AND item_id="' . $_GET['item_id'] . '"' . ' AND item_type="' . $_GET['item_type'] . '"'; } log_to_file('rank', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'set user rank', $query); mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); log_to_file('rank', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'rank_set, ' . $_GET['rank'] . ' stars for ' . $_GET['item_type'] . ' ' . $_GET['item_id'] . ' from user ' . $_SESSION['login']['id']); } else { /* Varning, haxors försöker skicka icke godkända poängsummor, aktivera laserskölden! */ die('Oh no, somebody set up us the bomb! Men med dina leeta mirkk-haxx0r-elite-skillz så sätter du väl bara upp en cURL som floodar kontodatabasen och fläskar in röster?'); } }
<?php require '../include/core/common.php'; require_once PATHS_INCLUDE . 'libraries/movie_compability.lib.php'; require_once PATHS_INCLUDE . 'libraries/entertain.lib.php'; require_once PATHS_INCLUDE . 'libraries/schedule.lib.php'; require_once PATHS_INCLUDE . 'libraries/rank.lib.php'; require_once PATHS_INCLUDE . 'libraries/comments.lib.php'; log_to_file('entertain', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'ajax call registered'); if (count($_GET) > 0) { switch ($_GET['action']) { case 'cancel_upload': log_to_file('entertain', LOGLEVEL_INFO, __FILE__, __LINE__, 'upload canceled'); unset($_SESSION['new_entertain_temp']); break; } }
function aptget($arr, $forceInteraction = False, $force_unattended = False) { /* this was like: apt-get install build-essential dpkg-dev fakeroot debhelper libdb4.2-dev libgdbm-dev libldap2-dev libpcre3-dev libmysqlclient10-dev libssl-dev libsasl2-dev postgresql-dev po-debconf dpatch but, when one package is not found, whole apt-get install was cancelling. to avoid this, each is installed separately. tr: herbirisi teker teker kuruluyor. yoksa hata verme ihtimali var. iki tip kurulum uygulanabilir, biri hizli, tum apt ler tek seferde, digeri yavas, tek tek... ilk basta sorabilir.. * */ global $noapt, $unattended; passthru("killall update-manager > /dev/null 2>&1"); passthru("killall update-notifier > /dev/null 2>&1"); # these cause other apt-get commands fail because of dpkg lock if ($noapt != '') { echo "apt-get install of these skipped because of noapt parameter:"; print_r($arr); return true; } foreach ($arr as $prog) { # # first install try # assumes yes, do not remove anything, allow any unauthenticated packages, # do not remove: this is a security concern $cmd = "apt-get -y --no-remove --allow-unauthenticated install {$prog}"; # If unattended, don't show configuration options if ($unattended && $forceInteraction == FALSE or $force_unattended) { $cmd = "DEBIAN_FRONTEND=noninteractive " . $cmd; } log_to_file($cmd); cizgi(); echo "Starting apt-get install for: {$prog}\n(cmd: {$cmd})\n\n"; passthru($cmd, $ret); writeoutput("ehcp-apt-get-install.log", $cmd, "a", false); if ($ret == 0) { continue; } # second install try, if first fails : # usefull if first one has failed, for reason such as a package has to be removed, if first apt-get exited for any reason, this one executes apt-get with not options, so that user can decide... # if first is successfull, this actually does nothing... only prints that those packages are already installed... # this way a bit slower, calls apt-get twice, but most "secure and avoids user intervention" $cmd = "apt-get install {$prog}"; echo "\nTrying second installation type for: {$prog} (cmd: {$cmd})\n"; passthru($cmd); writeoutput("ehcp-apt-get-install.log", $cmd, "a", false); } }
$GLOBALS['SQ_SYSTEM']->restoreRunLevel(); // Disconnect from DB _disconnectFromMatrixDatabase(); exit(0); break; default: $status = null; pcntl_waitpid(-1, $status); break; } //end switch //}//end foreach } //end while echo "Done\n"; log_to_file('======================= Finished updating lookups ' . date('d-m-Y h:i:s') . ' =======================', LOG_FILE); if (file_exists(SYNCH_FILE)) { unlink(SYNCH_FILE); } //end if exit(0); /** * Prints the usage statement. * * @return void */ function usage() { echo "\n"; echo "Usage: php {$_SERVER['argv'][0]} <system_root> [assetid[,assetid]] [--batch-size <num>] [--verbose]\n"; echo "\n";
function go_desktop() { global $MOBIFY_COOKIE_NAME; global $MOBIFY_COOKIE_EXPIRE; $cookie_domain = get_cookie_domain(); log_to_file('set mobify cookie for domain ' . $cookie_domain . " cookie name: " . $MOBIFY_COOKIE_NAME . ' to value 0'); setcookie($MOBIFY_COOKIE_NAME, '0', $MOBIFY_COOKIE_EXPIRE, '/', $cookie_domain); }
<?php require '../include/core/common.php'; require_once PATHS_INCLUDE . 'libraries/comments.lib.php'; require_once PATHS_INCLUDE . 'libraries/photos.lib.php'; log_to_file('comments', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'comment'); if (login_checklogin() && (isset($_POST['comment']) || $_POST['update'] == true) && isset($_POST['item_id']) && isset($_POST['item_type'])) { log_to_file('comments', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'comment', $_POST['item_id'] . ', ' . $_POST['item_type'] . ', ' . $_SESSION['login']['id'] . ', ' . $_POST['comment']); if (!isset($_POST['update'])) { $content_check = content_check($_POST['comment']); $output = ''; if ($content_check === 1) { comments_new($_POST['item_id'], $_POST['item_type'], $_SESSION['login']['id'], $_POST['comment']); } else { $output .= 'Vår server tyckte att ditt meddelande bröt mot våra regler, så det sparades inte. Kommentar: ' . $content_check . "\n"; } } if (isset($_POST['return_list'])) { $output .= comments_list($_POST['item_id'], $_POST['item_type']); echo $output; } } elseif ($_GET['action'] == 'comments_list_all') { echo '<style type="text/css">@import url(\'/stylesheets/ui.css.php?\');</style>' . "\n"; echo '<div id="content">' . "\n"; echo comments_list($_GET['item_id'], $_GET['item_type'], array('list_style' => 'compact', 'limit' => 'no_limit')); echo '</div>'; } elseif ($_GET['action'] == 'comment_remove') { if (is_numeric($_GET['id'])) { comments_remove($_GET['id']); } else { echo 'You h4xx0r...';
function forum_get_action($url) { if (644314 == $_SESSION['login']['id']) { log_to_file('forum', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'forum_get_action', $url); } $actions['ny_diskussion'] = 'discussion_create'; $actions['ny_post'] = 'post_create'; $actions['redigera'] = 'post_edit'; $actions['notiser'] = 'notices_view'; $actions['instaellningar'] = 'settings'; $actions['admin_check'] = 'admin_check'; $tab_actions = array('intressanta', 'laesta', 'dina_diskussioner', 'nya', 'nya_inlaegg', 'dar_du_har_svarat'); $url = preg_replace('/#.*$/', '', $url); $url = preg_replace('/([^(php)(html)\\/])$/', '$0/', $url); $return = array('action' => 'unknown'); $return['modified_url'] = $url; //Forum index // /forum // /forum/ if (preg_match('/^\\/forum\\/?$/', $url, $matches)) { $return['action'] = 'index'; } else { if (preg_match('/^\\/forum\\/((\\w+)\\/)*(\\w+)\\.php$/', $url, $matches)) { $return['action'] = $actions[$matches[3]]; } //Action - catch action //Index-view // /forum/index/tab-handle/ if (preg_match('/^\\/forum\\/index\\/((\\w+)\\/)/', $url, $matches)) { $return['debug'] = $matches; $return['forum_tab'] = $matches[2]; $return['action'] = 'index'; } elseif (preg_match('/^\\/forum\\/((\\w+)\\.php)/', $url, $matches)) { $return['debug'] = $matches; $return['action'] = $actions[$matches[2]]; } elseif (preg_match('/^\\/forum\\/index\\/((\\w+)\\.php)/', $url, $matches)) { $return['debug'] = $matches; $return['action'] = 'index'; if (in_array($matches[2], $tab_actions)) { $return['forum_tab'] = $matches[2]; } else { $return['action'] = $matches[2]; } } elseif (preg_match('/^\\/forum\\/((\\w+)\\/)(\\w+)\\.php$/', $url, $matches)) { $return['debug'] = $matches; $return['action'] = $actions[$matches[3]]; $return['discussion_handle'] = $matches[2]; if (in_array($matches[3], $tab_actions)) { $return['forum_tab'] = $matches[3]; $return['action'] = 'category_view'; $return['category_main'] = $matches[2]; } } elseif (preg_match('/^\\/forum\\/((\\w+)\\/)((\\w+)\\/)*(\\w+)\\.php$/', $url, $matches)) { $return['debug'] = $matches; $return['action'] = $actions[$matches[5]]; $return['discussion_handle'] = $matches[4]; if (in_array($matches[5], $tab_actions)) { $return['forum_tab'] = $matches[5]; $return['action'] = 'category_view'; $return['category_main'] = $matches[2]; $return['category_sub'] = $matches[4]; } } elseif (preg_match('/^\\/forum\\/\\w+\\/\\w+\\/((\\w+)\\/)+sida_(\\d+)\\.html$/', $url, $matches)) { $return['debug'] = $matches; $return['discussion_handle'] = $matches[2]; $return['page_number'] = array_pop($matches); $return['action'] = 'discussion_view'; } elseif (preg_match('/^\\/forum\\/\\w+\\/\\w+\\/((\\w+)\\/)+$/', $url, $matches)) { $return['debug'] = $matches; $return['action'] = 'discussion_view'; $return['discussion_handle'] = $matches[2]; } elseif (preg_match('/^\\/forum\\/((\\w+)\\/)((\\w+)\\/)/', $url, $matches)) { $return['debug'] = $matches; $return['category_main'] = $matches[2]; $return['category_sub'] = $matches[4]; $return['action'] = 'category_view'; } elseif (preg_match('/^\\/forum\\/((\\w+)\\/)/', $url, $matches)) { $return['debug'] = $matches; $return['category_main'] = array_pop($matches); $return['action'] = 'category_view'; } } //preint_r($return); return $return; }
function games_challenge_send($options) { log_to_file('games', LOGLEVEL_DEBUG, __FILE__, __LINE__, $options['reciever_name'] . ' challenged by ' . $options['sender_id'] . ' in a game of ' . $options['game_handle'] . ' with the message ' . $options['message']); $message = '<div class="challenge">' . '<div class="challenge_message" >Jag utmanar dig i <a href="/spel/' . $options['game_handle'] . '.html">' . $options['game_title'] . '</a></p>' . '<p>' . $options['message'] . '</p>' . '</div>' . '<a href="/spel/' . $options['game_handle'] . '.html"><img alt="' . $options['game_title'] . '" class="left" ' . ' src="' . IMAGE_URL . 'games/' . $options['game_handle'] . '.png" /></a>' . '</div><br style="clear: both;" />'; foreach ($options['reciever'] as $reciever) { if (strlen($reciever) > 2) { if ($options['method'] == 'guestbook') { $query = 'SELECT id FROM login WHERE username="******"'; $result = mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); if ($data = mysql_fetch_assoc($result)) { $recipient = $data['id']; new_entry($recipient, $options['sender_id'], $message); $output = '<p>Din utmaning och en länk till spelet finns nu i gästboken hos ' . $reciever . '.</p>' . "\n"; } else { $output = '<p>Den användaren (' . $reciever . ') finns inte. Kolla namnet och försök igen.</p>'; } } elseif ($options['method'] == 'mail') { $result = tips_send(array('sender_name' => $options['sender_name'], 'reciever' => $reciever, 'message' => $options['message'], 'link' => '/spel/' . $options['game_handle'] . '.html', 'subject' => 'Tips från Hamsterpaj.net')); switch ($result) { case 'ok': $output .= '<p>Din utmaning har nu skickats med e-post.</p>'; break; case 'denies': $output .= '<p class="challenge_error">Inget meddelande skickades eftersom ' . $reciever . ' vill inte ha några tips från Hamsterpaj.</p>'; break; case 'false_sender': $output .= '<p class="challenge_error">Ett fel uppstod då ett meddelande skulle skickas från en användare som inte finns.<p>'; break; } } } } echo utf8_encode($output); }
function schedule_release_get($options) { /* returns a random time within the next free slot for type option comment type give me a free slot for this type after give me the first free slot after this timestamp */ global $schedule_slots; if (!array_key_exists($options['type'], $schedule_slots)) { return false; } $type = $options['type']; $slots = $schedule_slots[$type]; $num_of_slots = count($slots); $slot = 0; $day = 0; /* Offset, days counting from today */ $midnight = strtotime(date('Y-m-d')); $time = max($options['after'], time()); unset($free_slot); $debug = 'time: ' . $time . ' ' . date('Y-m-d H:i', $time) . "\n"; $debug .= 'after: ' . $options['after'] . ' ' . date('Y-m-d H:i', $options['after']) . "\n"; $debug .= 'type: ' . $type . "\n"; $debug .= date('Y-m-d H:i', $slots[$slot]['end'] + $day * 86400) . "\n"; /* Find the next slot, regardless if it's occupied or not */ while ($slots[$slot]['start'] + $day * 86400 <= $time) { $debug .= 'slot before time <br />'; $slot++; if ($slot >= $num_of_slots) { $day++; $slot = 0; } } $debug .= 'Find nearest slot after day #' . $day . ', slot #' . $slot . "\n"; $query = 'SELECT `release` FROM scheduled_events WHERE type="' . $type . '" AND `release` > "' . $time . '" ORDER BY `release` ASC'; $result = mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); $debug .= 'Items in qeue: ' . mysql_num_rows($result) . "\n"; if ($data = mysql_fetch_assoc($result)) { $release = $data['release']; $debug .= 'before loop, release: ' . $release . ' ' . date('Y-m-d H:i', $release) . "\n"; while (!isset($free_slot)) { if ($release < $slots[$slot]['start'] + $day * 86400) { $debug .= 'Released before current slot' . "\n"; if ($data = mysql_fetch_assoc($result)) { $release = $data['release']; } else { $free_slot = $slot; } } elseif ($release < $slots[$slot]['end'] + $day * 86400) { $slot++; if ($slot >= $num_of_slots) { $day++; $slot = 0; } if ($data = mysql_fetch_assoc($result)) { $release = $data['release']; } else { $free_slot = $slot; } } else { $free_slot = $slot; } } } // preint_r($slots); $debug .= 'slot: ' . $slot . "\n"; $debug .= 'day: ' . $day . "\n"; log_to_file('schedule', LOGLEVEL_DEBUG, __FILE__, __LINE__, $debug); return $slots[$slot]['start'] + $day * 86400 + rand(0, $slots[$slot]['end'] - $slots[$slot]['start']); }
function rcommon_ws_error($function, $message, $module = 'rcommon', $cmid = 0, $course = false) { global $USER, $COURSE, $DB; $error_message = 'Error ' . $function . ': ' . $message; log_to_file($error_message); try { $record = new stdClass(); $record->time = time(); $record->userid = isset($USER->id) ? $USER->id : 0; $record->ip = $_SERVER['REMOTE_ADDR']; $record->module = $module; $course = $course ? $course : isset($COURSE->id) ? $COURSE->id : 0; $record->course = $course != SITEID ? $course : 0; $record->cmid = $cmid ? $cmid : 0; $record->action = $function . '_error'; $record->url = $_SERVER['REQUEST_URI']; $record->info = $error_message; $DB->insert_record('rcommon_errors_log', $record); } catch (Exception $e) { log_to_file("function rcommon_ws_error - Exception = " . $e->getMessage()); } return $error_message; }
// IECISA -> MPS ********** ADDED -> cron to clean log /// load libraries include_once '../../../config.php'; /// truncate log table if (!delete_records('log')) { add_error_log(4, '4-1', serialize(time()), true); log_to_file("Action 4-1 KO!"); } else { log_to_file("Action 4-1 OK!"); } /// truncate sessions table if (!delete_records('sessions')) { add_error_log(4, '4-2', serialize(time()), true); log_to_file("Action 4-2 KO!"); } else { log_to_file("Action 4-2 OK!"); } function log_to_file($info) { global $CFG; $directorio_log = $CFG->dirroot . "/application/admin/log"; //Escribimos en un fichero de textos los mensajes de errores if (!is_dir($directorio_log)) { mkdir($directorio_log); } if ($handle = @fopen($directorio_log . "/cron.log", "a")) { $content = "\r\n" . date("Y-m-d H:i:s") . " - Succes: " . $info; @fwrite($handle, $content); @fclose($handle); } }
/** * Retrieve all the elements from the database depending the conditions * @param array $options List of options intended to modify the query behavior * @return array Array with User objects, False on error */ public static function all($options = array()) { global $site; $dbh = $site->getDatabase(); $ret = array(); #Generals $table = static::$table; $table_fields = static::$table_fields; $class_name = static::$plural_class_name; $query_fields = static::querify(get_item($options, 'query_fields', $table_fields)); #Default variables $show = get_item($options, 'show', 1000); $page = get_item($options, 'page', 1); $sort = get_item($options, 'sort', 'asc'); $by = get_item($options, 'by', 'id'); $group = get_item($options, 'group', ''); $conditions = get_item($options, 'conditions', ''); $pdoargs = get_item($options, 'pdoargs', array()); $debug = get_item($options, 'debug', false); $code = get_item($options, 'code', false); $query = get_item($options, 'query', false); $offset = $show * ($page - 1); # Sanity checks $by = in_array($by, $table_fields) ? $by : false; $sort = in_array($sort, array('asc', 'desc')) ? $sort : false; $sort = strtoupper($sort); $offset = is_numeric($offset) ? $offset : false; $show = is_numeric($show) ? $show : false; $group = in_array($group, $table_fields) ? $group : false; if ($group === false || $by === false || $sort === false || $offset === false || $show === false) { log_to_file('Parameter Error: by, group, sort, offset or show not well defined. (Line' . __FILE__ . ')', 'norm'); return $ret; } $group = $group ? "GROUP BY {$group}" : ''; $conditions = $conditions ? "WHERE {$conditions}" : ''; try { $sql = $query ? $query : "SELECT {$query_fields} FROM {$table} {$conditions} {$group} ORDER BY {$by} {$sort} LIMIT {$offset}, {$show}"; if ($debug) { echo $sql; } if ($code) { return $sql; } $stmt = $dbh->prepare($sql); $stmt->execute(); $stmt->setFetchMode(PDO::FETCH_CLASS, static::$singular_class_name, $pdoargs); $ret = $stmt->fetchAll(); } catch (PDOException $e) { log_to_file("Database error: {$e->getCode()} (Line {$e->getLine()}) in {$class_name}::all(): {$e->getMessage()}", 'norm'); } return $ret; }
function comments_new($item_id, $item_type, $user_id, $comment) { $content_check = content_check($comment); if ($content_check === 1) { $insertquery = 'INSERT INTO user_comments (item_type, item_id, timestamp, user_id, comment) VALUES ("'; $insertquery .= $item_type . '", "'; $insertquery .= $item_id . '", "'; $insertquery .= time() . '", "'; $insertquery .= $user_id . '", "'; $insertquery .= $comment . '")'; $updatequery = 'UPDATE user_comments SET' . ' timestamp = "' . time() . '", ' . ' comment = "' . $comment . '",' . ' removed = 0 ' . ' WHERE item_type = "' . $item_type . '" ' . ' AND item_id = "' . $item_id . '"' . ' AND user_id = "' . $user_id . '"' . ' LIMIT 1'; log_to_file('comments', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'new_comment', $insertquery); log_to_file('comments', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'new_comment', $updatequery); if (mysql_query($insertquery)) { $query = 'UPDATE item_ranks SET comment_count = comment_count + 1 WHERE item_type = "' . $item_type . '" ' . ' AND item_id = "' . $item_id . '"'; } else { mysql_query($updatequery); } if ($item_type == 'photos') { $query = 'UPDATE user_photos SET unread_comments = unread_comments + 1 WHERE id = "' . $item_id . '" LIMIT 1'; mysql_query($query) or report_sql_error($query, __FILE__, __LINE__); } } else { die('<p style="margin: 0px;">' . $content_check . '</p>'); } }
/** * Web Service to access digital content SM * @param none * @return obj -> web service response */ function get_book_structure($publisher, $isbn) { global $DB; // echo "<br>Indice Libro: ".$wsurl_contenido."<br>"; $book = $DB->get_record('rcommon_books', array('isbn' => $isbn)); if (!$book) { throw new Exception('Book not found'); } try { $client = get_marsupial_ws_client($publisher); $isbnparam = @new SoapVar($isbn, XSD_STRING, "string", "http://www.w3.org/2001/XMLSchema"); $response = $client->ObtenerEstructura(array('ISBN' => $isbnparam)); log_to_file("get_book_structure Request: " . $client->__getLastRequest()); log_to_file("get_book_structure Response: " . $client->__getLastResponse()); } catch (Exception $fault) { log_to_file("wsBookStructure: get_book_structure - Exception = " . $fault->getMessage()); $message = rcommon_ws_error('get_book_structure', $fault->getMessage()); throw new Exception($message); } $response = rcommon_object_to_array_lower($response, true); $response = isset($response['obtenerestructuraresult']) ? $response['obtenerestructuraresult'] : false; if (!$response) { $message = get_string('empty_response_error', 'local_rcommon'); print_object($client->__getLastRequest()); print_object($client->__getLastResponse()); debugging('<pre>' . htmlentities($client->__getLastResponse()) . '</pre>'); $message = rcommon_ws_error('get_book_structure', $message); die; throw new Exception(get_string('empty_response_error', 'local_rcommon')); } else { if (isset($response['codigo']) && $response['codigo'] <= 0) { $text = array('code' => $response['codigo'], 'description' => $response['descripcion']); $message = get_string('wserror', 'local_rcommon', $text); if (isset($response['url'])) { $message .= ', URL: ' . test_ws_url($response['url']); } $message = rcommon_ws_error('get_book_structure', $message); throw new Exception($message); } else { save_book_structure($response, $book); } } }
include "augment_functions.php"; include "general_functions.php"; include "material_functions.php"; // Load database settings from config file $settings = array(); $settings = load_config(); $mysql_user = $settings[0]; $mysql_host = $settings[1]; $mysql_pass = $settings[2]; $mysql_database = $settings[3]; // Establish connection to the database $con = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_database); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); $log_message = "CRITICAL: Failed to connect to database while attempting to update the database tables! Please check your database and database settings!"; log_to_file($log_message); } mysqli_query($con, "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'"); $augment_raw_data = get_augment_data($con); // $augment_raw_data[0] contains all augment names $search_result = binary_search($augment_raw_data[0], $_GET["search_term"]); ?> <head> <meta charset="ISO-8859-1"> <title> <?php // Print out the current augment as the page title. if ($_SERVER["REQUEST_METHOD"] == "GET") { if (empty($_GET["search_term"])) { print "Augment Search"; } else {
function posts_fetch($options) { /* Parameter Data-type Array-support Comment X post_id int yes - X limit int no Maximum number of rows to return X offset int no X order array yes May contain multiple keys holding arrays with both field and direction, ex: (field => id direction => desc) flags ENUM-array yes array('removed' => 'ok', 'private' => 'force'). Values: exclude, ok, force X freetext_search text no Search string X discussion_id int yes fetch posts from one of theese discussions X author int yes fetch posts written by one of theeese authors time_min int no time_max int no id_max int no - id_max int no - */ if (isset($options['time_min'])) { log_to_file('johan', LOGLEVEL_DEBUG, __FILE__, __LINE__, print_r(debug_backtrace(), true)); return false; } $options['order'] = is_array($options['order']) ? $options['order'] : array(array('field' => 'post_id', 'direction' => 'asc')); $options['limit'] = is_numeric($options['limit']) ? $options['limit'] : POSTS_DEFAULT_LIMIT; $options['offset'] = is_numeric($options['offset']) ? $options['offset'] : 0; /* Make sure that some entries are hidden by default */ $default_exclude_flags = array('private_gb'); foreach ($default_exclude_flags as $flag) { if (!isset($options['flags'][$flag])) { $options['flags'][$flag] = 'exclude'; } } if (isset($options['post_id'])) { $options['post_id'] = is_array($options['post_id']) ? $options['post_id'] : array($options['post_id']); } if (isset($options['author'])) { $options['author'] = is_array($options['author']) ? $options['author'] : array($options['author']); } if (isset($options['tag'])) { $options['tag'] = is_array($options['tag']) ? $options['tag'] : array($options['tag']); } $query = 'SELECT p.id AS post_id, p.timestamp, p.author, p.length, p.content, p.discussion_id, p.quality_rank, p.spelling_grammar, p.no_smilies'; $query .= ', l.username, l.lastaction, l.lastrealaction, l.userlevel, u.image'; $query .= ', u.gender, u.birthday, u.zip_code, u.forum_signature, u.user_status'; $query .= ', z.spot, z.x_rt90, z.y_rt90, GROUP_CONCAT(flag) as flags'; $query .= ' FROM login AS l, userinfo AS u, zip_codes AS z, posts AS p'; $query .= ' LEFT OUTER JOIN flags ON p.id = flags.object_id'; $query .= ' WHERE l.id = p.author'; $query .= ' AND u.userid = p.author'; $query .= ' AND z.zip_code = u.zip_code'; foreach ($options['flags'] as $flag => $action) { $query .= ' AND ' . ($action == 'force' ? 'EXISTS' : 'NOT EXISTS') . ' (SELECT * FROM flags AS fs'; $query .= ' WHERE p.id = fs.object_id'; $query .= ' AND fs.flag = "' . $flag . '"'; $query .= ' AND fs.object_type = "post")'; } if (isset($options['discussion_id']) && !is_numeric($options['discussion_id'])) { log_to_file('forum', LOGLEVEL_ERROR, __FILE__, __LINE__, 'post_fetch() called with non numeric discussion_id set', print_r(debug_backtrace(), true)); } if (!isset($options['discussion_id'])) { log_to_file('forum', LOGLEVEL_INFO, __FILE__, __LINE__, 'post_fetch() called without discussion_id', print_r(debug_backtrace(), true)); } $query .= isset($options['discussion_id']) ? ' AND p.discussion_id = "' . $options['discussion_id'] . '"' : ''; $query .= isset($options['post_id']) ? ' AND p.id IN("' . implode('", "', $options['post_id']) . '")' : ''; $query .= isset($options['author']) ? ' AND p.author IN("' . implode('", "', $options['author']) . '")' : ''; $query .= isset($options['freetext_search']) ? ' MATCH(p.content) AGAINST("' . $options['freetext_search'] . '")' : ''; $query .= isset($options['time_min']) ? ' AND p.timestamp >= "' . $options['time_min'] . '"' : ''; $query .= isset($options['time_max']) ? ' AND p.timestamp <= "' . $options['time_max'] . '"' : ''; $query .= isset($options['id_min']) ? ' AND p.id >= "' . $options['id_min'] . '"' : ''; $query .= isset($options['id_max']) ? ' AND p.id <= "' . $options['id_max'] . '"' : ''; $query .= "\n"; $query .= ' GROUP BY post_id'; $query .= ' ORDER BY'; for ($i = 0; $current = array_shift($options['order']); $i++) { $query .= $i != 0 ? ',' : ''; $query .= ' ' . $current['field'] . ' ' . $current['direction']; } $query .= "\n"; $query .= ' LIMIT ' . $options['offset'] . ', ' . $options['limit']; $query .= "\n"; log_to_file('forum', LOGLEVEL_DEBUG, __FILE__, __LINE__, 'posts_fetch_query', $query); $result = mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); while ($data = mysql_fetch_assoc($result)) { $return[$data['post_id']] = $data; $return[$data['post_id']]['flags'] = explode(',', $return[$data['post_id']]['flags']); } /* $query = 'SELECT object_id, flag FROM flags WHERE object_id IN("' . implode(array_keys($return), '", "') . '") AND object_type = "post"'; $result = mysql_query($query) or die(report_sql_error($query, __FILE__, __LINE__)); while($data = mysql_fetch_assoc($result)) { if(strlen($data['flag']) > 0) { $return[$data['object_id']]['flags'][] = $data['flag']; } } */ return $return; }