Exemple #1
0
function convert_posts($message)
{
    $message = convert_to_utf8($message);
    $message = str_replace("\n", '', $message);
    $pattern = array('#<!--b--><span class="b">#i', '#</span><!--/b-->#i', '#<!--i--><span class="i">#i', '#</span><!--/i-->#i', '#<!--u--><span class="u">#i', '#</span><!--/u-->#i', '#<!--s--><span class="s">#i', '#</span><!--/u-->#i', '#<!--center--><span class="center">#i', '#</span><!--/center-->#i', '#<!--list(num)?--><(ul|ol)>#i', '#</(ul|ol)><!--/list(num)?-->#i', '#<li><span class="nodisplay">\\[\\*\\]</span>#i', '#</li>#i', '#<!--color=--><span style="color:\\s*(.*?);?">#i', '#</span><!--/color=-->#i', '#<!--img--><img src="#i', '#" alt="Posted Image" />(<!--/img-->)?#i', '#<img src="smileys\\/.*?" alt="(.*?)" class="smiley" />#i', '#<!--url=--><a href="(.*?)">#i', '#(<!--url-->)?<a href="(.*?)">#i', '#<!--email--><a href="mailto:(.*?)">#i', '#</a>(<!--/url=?-->)?#i', '#</a><!--/email-->#i', '#<!--flash--><object type="application/x-shockwave-flash" data="(.*?)" width="560" height="436"><param name="quality" value="high" /><param name="movie" value="(.*?)" /></object><span class="nodisplay">\\[flash\\]\\[/flash\\]</span><!--/flash-->#i', '#<!--youtube--><object width="425" height="350"><param name="movie" value="(.*?)"></param><param name="wmode" value="transparent"></param><embed src="(.*?)" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object><!--/youtube-->#i', '#<!--size=--><span style="font-size:[0-9]{1,2}px;?">#i', '#</span><!--/(size|font)=-->#i', '#<!--font=--><span style="font-family:(.*?)">#i', '#<!--quote=?--><blockquote class="citationb?">(<p><span class="u">(.*?)</span></p>)?<p>#i', '#</p></blockquote><!--/quote=?-->#i', '#<!--(code|php)--><span class="code">(<p>)?<code>#i', '#</code>(</p>)?</span><!--/(code|php)-->#i', '#<!--spoil--><span class="spoil"><span class="spoil_info" onclick="hideAndShow\\(\'spoil[0-9a-f]{32}\'\\);">Spoiler</span><span class="spoil_spoiler" id="spoil[0-9a-f]{32}">#i', '#</span></span><script type="text/javascript">hideAndShow\\(\'spoil[0-9a-f]{32}\'\\);</script><!--/spoil-->#i', '#<br />#i');
    $replace = array('[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]', '[s]', '[/s]', '', '', '[list]', '[/list]', '[*]', '[/*]', '[color=$1]', '[/color]', '[img]', '[/img]', '$1', '[url=$1]', '[url]', '[email=$1]', '[/url]', '[/email]', '[url]$1[/url]', '[url]$1[/url]', '', '', '', '[quote]', '[/quote]', '[code]', '[/code]', '[quote]', '[/quote]', "\n");
    $errors = array();
    return preparse_bbcode(preg_replace($pattern, $replace, $message), $errors);
}
Exemple #2
0
/**
 * List up by category
 */
function categories_name_array_plus()
{
    global $cfg, $log_table, $row;
    $sql = "SELECT `category` FROM `{$log_table}` WHERE `draft` = '0'";
    $res = mysql_query($sql);
    $rowArray = array();
    while ($row = mysql_fetch_array($res)) {
        $row = convert_to_utf8($row);
        $token = strtok($row['category'], ",");
        while ($token) {
            array_push($rowArray, trim($token));
            $token = strtok(",");
        }
    }
    $rowArray = array_count_values($rowArray);
    ksort($rowArray, SORT_STRING);
    return $rowArray;
}
 /**
  * Load / fetch a class
  * @since Version 3.2
  * @param boolean $recurse
  */
 public function fetch($recurse)
 {
     if (!$this->id) {
         throw new Exception("Cannot fetch loco class - no class ID given");
         return false;
     }
     if (!filter_var($this->id, FILTER_VALIDATE_INT)) {
         $this->id = $this->db->fetchOne("SELECT id FROM loco_class WHERE slug = ?", $this->id);
     }
     $this->mckey = "railpage:locos.class_id=" . $this->id;
     $key = "id";
     if ($row = $this->getCache($this->mckey)) {
         // Do nothing
     } elseif ($this->db instanceof \sql_db) {
         $query = "SELECT c.id, c.asset_id, c.slug, c.download_id, c.date_added, c.date_modified, c.model, c.axle_load, c.tractive_effort, c.weight, c.length, c.parent AS parent_class_id, c.source_id AS source, c.id AS class_id, c.flickr_tag, c.flickr_image_id, c.introduced AS class_introduced, c.name AS class_name, c.loco_type_id AS loco_type_id, c.desc AS class_desc, c.manufacturer_id AS class_manufacturer_id, m.manufacturer_name AS class_manufacturer, w.arrangement AS wheel_arrangement, w.id AS wheel_arrangement_id, t.title AS loco_type\r\n\t\t\t\t\t\t\tFROM loco_class AS c\r\n\t\t\t\t\t\t\tLEFT JOIN loco_type AS t ON c.loco_type_id = t.id\r\n\t\t\t\t\t\t\tLEFT JOIN wheel_arrangements AS w ON c.wheel_arrangement_id = w.id\r\n\t\t\t\t\t\t\tLEFT JOIN loco_manufacturer AS m ON m.manufacturer_id = c.manufacturer_id\r\n\t\t\t\t\t\t\tWHERE c." . $key . " = " . $this->db->real_escape_string($this->id);
         if ($rs = $this->db->query($query)) {
             $row = $rs->fetch_assoc();
             $this->setCache($this->mckey, $row, strtotime("+24 hours"));
         }
     } else {
         if (RP_DEBUG) {
             global $site_debug;
             $debug_timer_start = microtime(true);
         }
         $query = "SELECT c.id, c.meta, c.asset_id, c.slug, c.download_id, c.date_added, c.date_modified, c.model, c.axle_load, c.tractive_effort, c.weight, c.length, c.parent AS parent_class_id, c.source_id AS source, c.id AS class_id, c.flickr_tag, c.flickr_image_id, c.introduced AS class_introduced, c.name AS class_name, c.loco_type_id AS loco_type_id, c.desc AS class_desc, c.manufacturer_id AS class_manufacturer_id, m.manufacturer_name AS class_manufacturer, w.arrangement AS wheel_arrangement, w.id AS wheel_arrangement_id, t.title AS loco_type\r\n\t\t\t\t\t\t\tFROM loco_class AS c\r\n\t\t\t\t\t\t\tLEFT JOIN loco_type AS t ON c.loco_type_id = t.id\r\n\t\t\t\t\t\t\tLEFT JOIN wheel_arrangements AS w ON c.wheel_arrangement_id = w.id\r\n\t\t\t\t\t\t\tLEFT JOIN loco_manufacturer AS m ON m.manufacturer_id = c.manufacturer_id\r\n\t\t\t\t\t\t\tWHERE c." . $key . " = ?";
         $row = $this->db->fetchRow($query, $this->id);
         if (RP_DEBUG) {
             if ($row === false) {
                 $site_debug[] = "Zend_DB: FAILED select loco class ID/slug " . $this->id . " in " . round(microtime(true) - $debug_timer_start, 5) . "s";
             } else {
                 $site_debug[] = "Zend_DB: SUCCESS select loco class ID/slug " . $this->id . " in " . round(microtime(true) - $debug_timer_start, 5) . "s";
             }
         }
         foreach ($row as $key => $val) {
             $row[$key] = convert_to_utf8($val);
         }
         $this->setCache($this->mckey, $row, strtotime("+24 hours"));
     }
     if (isset($row) && is_array($row)) {
         if (!isset($row['id'])) {
             deleteMemcacheObject($this->mckey);
         } else {
             $this->id = $row['id'];
         }
         // Populate the class objects
         $this->slug = $row['slug'];
         $this->name = $row['class_name'];
         $this->desc = $row['class_desc'];
         $this->type = $row['loco_type'];
         $this->type_id = $row['loco_type_id'];
         $this->introduced = $row['class_introduced'];
         $this->manufacturer = $row['class_manufacturer'];
         $this->manufacturer_id = $row['class_manufacturer_id'];
         $this->wheel_arrangement = $row['wheel_arrangement'];
         $this->wheel_arrangement_id = $row['wheel_arrangement_id'];
         $this->flickr_tag = $row['flickr_tag'];
         $this->flickr_image_id = $row['flickr_image_id'];
         $this->axle_load = $row['axle_load'];
         $this->tractive_effort = $row['tractive_effort'];
         $this->weight = $row['weight'];
         $this->length = $row['length'];
         $this->model = $row['model'];
         $this->date_added = $row['date_added'];
         $this->date_modified = $row['date_modified'];
         $this->download_id = $row['download_id'];
         if (empty($this->slug) || $this->slug === "1") {
             $this->createSlug();
             if (RP_DEBUG) {
                 global $site_debug;
                 $site_debug[] = __CLASS__ . "::" . __FUNCTION__ . "() : Creating url slug for loco class ID " . $this->id;
             }
             $this->commit();
         }
         $this->url = new Url($this->makeClassURL($this->slug));
         $this->url->view = $this->url->url;
         $this->url->edit = sprintf("%s?mode=class.edit&id=%d", $this->Module->url, $this->id);
         $this->url->addLoco = sprintf("%s?mode=loco.edit&class_id=%d", $this->Module->url, $this->id);
         $this->url->sightings = sprintf("%s/sightings", $this->url->url);
         $this->url->bulkadd = sprintf("%s?mode=loco.bulkadd&class_id=%d", $this->Module->url, $this->id);
         $this->url->bulkedit = sprintf("%s?mode=class.bulkedit&id=%d", $this->Module->url, $this->id);
         $this->url->bulkedit_operators = sprintf("%s?mode=class.bulkedit.operators&id=%d", $this->Module->url, $this->id);
         $this->url->bulkedit_buildersnumbers = sprintf("%s?mode=class.bulkedit.buildersnumbers&id=%d", $this->Module->url, $this->id);
         $this->url->bulkedit_status = sprintf("%s?mode=class.bulkedit.status&id=%d", $this->Module->url, $this->id);
         $this->url->bulkedit_gauge = sprintf("%s?mode=class.bulkedit.gauge&id=%d", $this->Module->url, $this->id);
         /**
          * Set the meta data
          */
         if (isset($row['meta'])) {
             $this->meta = json_decode($row['meta'], true);
         } else {
             $this->meta = array();
         }
         /**
          * If an asset ID exists and is greater than 0, create the asset object
          */
         if (isset($row['asset_id']) && $row['asset_id'] > 0) {
             try {
                 $this->Asset = new \Railpage\Assets\Asset($row['asset_id']);
             } catch (Exception $e) {
                 global $Error;
                 $Error->save($e);
             }
         }
         /**
          * Try to load the Image object
          */
         if (filter_var($row['flickr_image_id'], FILTER_VALIDATE_INT)) {
             $Images = new \Railpage\Images\Images();
             $this->Image = $Images->findImage("flickr", $row['flickr_image_id']);
             $this->Image->addLink($this->namespace, $this->id);
         }
         /** 
          * Create the fwlink object
          */
         try {
             #var_dump($this->url);die;
             $this->fwlink = new \Railpage\fwlink($this->url);
             if (empty($this->fwlink->url) && !empty(trim($this->name))) {
                 $this->fwlink->url = $this->url;
                 $this->fwlink->title = $this->name;
                 $this->fwlink->commit();
             }
         } catch (Exception $e) {
             // Do nothing
         }
         // Parent object
         if ($row['parent_class_id'] > 0) {
             try {
                 $this->parent = new LocoClass($row['parent_class_id'], false);
             } catch (Exception $e) {
                 // Re-throw the error
                 throw new Exception($e->getMessage());
             }
         }
         // Data source object
         if ($row['source'] > 0 && class_exists("Source")) {
             try {
                 $this->source = new \Source($row['source']);
             } catch (Exception $e) {
                 // Re-throw the error
                 throw new Exception($e->getMessage());
             }
         }
         /**
          * Set the StatsD namespaces
          */
         $this->StatsD->target->view = sprintf("%s.%d.view", $this->namespace, $this->id);
         $this->StatsD->target->edit = sprintf("%s.%d.view", $this->namespace, $this->id);
         /*
         // Child classes
         if ($this->db instanceof \sql_db) {	
         	$query = "SELECT c.id AS child_class_id, c.name AS child_class_name FROM loco_class AS c WHERE c.parent = ".$this->db->real_escape_string($this->id);
         	
         	if ($rs = $this->db->query($query)) {
         		while ($row = $rs->fetch_assoc()) {
         			$this->children[$row['child_class_id']] = $row['child_class_name'];
         		}
         	} else {
         		throw new Exception($this->db->error);
         	}
         } else {
         	$query = "SELECT c.id AS child_class_id, c.name AS child_class_name FROM loco_class AS c WHERE c.parent = ?";
         	
         	foreach ($this->db->fetchAll($query, $this->id) as $row) {
         		$this->children[$row['child_class_id']] = $row['child_class_name'];
         	}
         }
         */
         /*
         if (RP_PLATFORM != "API" && !filter_var($this->download_id, FILTER_VALIDATE_INT)) {
         	// Create a new download for this class' datasheet
         	if (RP_DEBUG) {
         		global $site_debug; 
         		$site_debug[] = __CLASS__ . "::" . __FUNCTION__ . "() : No download ID for class ID " . $this->id;
         	}
         	
         	try {
         		$Download = new \Railpage\Downloads\Download(); 
         		
         		if (!empty($this->name) && strlen($this->name) > 1) {
         			$Download->name			= $this->name." data sheet"; 
         			$Download->url			= "http://www.railpage.com.au/modules.php?name=Locos&mode=exportclass&id=".$this->id."&format=xlsx";
         			$Download->desc			= "Data sheet for the ".$this->name." class, formatted as a Microsoft Excel spreadsheet";
         			$Download->date			= time(); 
         			$Download->mime			= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
         			$Download->active		= 1;
         			$Download->approved		= 1;
         			$Download->Category	 	= new \Railpage\Downloads\Category("23");
         			$Download->cat_id		= "23";
         			$Download->extra_data	= array("Class name" => $this->name, "Class ID" => $this->id);
         			$Download->filename		= 'Railpage-Locodata-'.$this->name.'.xlsx';
         			$Download->user_id		= 45;
         			$Download->filepath		= "/";
         			
         			$Download->commit(); 
         			
         			$this->download_id = $Download->id; 
         			
         			if (RP_DEBUG) {
         				global $site_debug; 
         				$site_debug[] = __CLASS__ . "::" . __FUNCTION__ . "() : committing changes to download ID for loco ID " . $this->id;
         			}
         			
         			$this->commit(); 
         		}
         	} catch (Exception $e) {
         		// Discard the error
         	}
         }
         */
     }
 }
 function _conv_users($cur_item, $old_charset)
 {
     global $lang_update;
     echo sprintf($lang_update['Converting item'], $lang_update['user'], $cur_item['id']) . '<br />' . "\n";
     convert_to_utf8($cur_item['username'], $old_charset);
     convert_to_utf8($cur_item['title'], $old_charset);
     convert_to_utf8($cur_item['realname'], $old_charset);
     convert_to_utf8($cur_item['location'], $old_charset);
     convert_to_utf8($cur_item['signature'], $old_charset);
     convert_to_utf8($cur_item['admin_note'], $old_charset);
     return $cur_item;
 }
     unset($_mime, $_act, $_name, $match);
 }
 if ($do_content_extraction) {
     $html = $response['body'];
     //echo "[" . $html .  "]";
     // remove strange things
     $html = str_replace('</[>', '', $html);
     $html = convert_to_utf8($html, $response['headers']);
     //echo "[" . $html .  "]";
     if ($auto_extract) {
         // check site config for single page URL - fetch it if found
         if ($single_page_response = getSinglePage($item, $html, $effective_url)) {
             $html = $single_page_response['body'];
             // remove strange things
             $html = str_replace('</[>', '', $html);
             $html = convert_to_utf8($html, $single_page_response['headers']);
             $effective_url = $single_page_response['effective_url'];
             unset($single_page_response);
         }
         $extract_result = $extractor->process($html, $effective_url);
         $readability = $extractor->readability;
         $content_block = $extract_result ? $extractor->getContent() : null;
         //echo "content_block: [" . $content_block->innerHTML . "] \n\n";
         $title = $extract_result ? $extractor->getTitle() : '';
     } else {
         $readability = new Readability($html, $effective_url);
         // content block is entire document (for now...)
         $content_block = $readability->dom;
         //echo $content_block->innerHTML;
         //TODO: get title
         $title = '';
function insertdata($table, $todb, $file = __FILE__, $line = __LINE__)
{
    global $db;
    // Put together the query
    $names = $vars = array();
    foreach ($todb as $name => $var) {
        if ($var != '') {
            $names[] = $name;
            $vars[] = $var == 'null' ? $var : '\'' . $db->escape(convert_to_utf8($var)) . '\'';
        }
    }
    $db->query('INSERT INTO ' . $db->prefix . $table . ' (' . implode(',', $names) . ') VALUES(' . implode(',', $vars) . ')') or myerror('Unable to save to database.<br><br><b>Query:</b> ' . $query . '<br>', $file, $line, $db->error());
}
Exemple #7
0
     $rownr++;
     $erste_spalte = 0;
 }
 $d .= '<td valign="top" class="small" nowrap="nowrap">';
 $divstart = '<div' . ($tdcompact == 1 ? ' class="tdcompact" ' : ' class="tdnormal"') . '>';
 $divend = '</div>';
 if ($bb == $spalte) {
     $data = convert_to_utf8(simple_bbcode_conversion($rowval));
 } else {
     if ($showtables == 0) {
         if (isset($fdesc[$rowkey]['type'])) {
             $data = $fdesc[$rowkey]['type'] == 'string' || $fdesc[$rowkey]['type'] == 'blob' ? convert_to_utf8($rowval) : $rowval;
         }
     } else {
         if (isset($temp[$i][$rowkey])) {
             $data = $fdesc[$rowkey]['type'] == 'string' || $fdesc[$rowkey]['type'] == 'blob' ? convert_to_utf8($temp[$i][$rowkey]) : $temp[$i][$rowkey];
         } else {
             $data = '';
         }
         if (in_array($rowkey, $byte_output)) {
             $data = byte_output($data);
         }
     }
 }
 //v($fdesc[$rowkey]);
 if ($showtables == 0) {
     if (is_null($rowval)) {
         $data = '<i>NULL</i>';
     } else {
         $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
     }
Exemple #8
0
<?php

// Check if AutoPoll is installed
if ($start == 0 && !$db->table_exists('polls')) {
    next_step();
}
$result = $fdb->query('SELECT vote_id,topic_id,vote_text,vote_start FROM ' . $fdb->prefix . $_SESSION['phpnuke'] . 'vote_desc WHERE vote_id>' . $start . ' ORDER BY vote_id LIMIT ' . $_SESSION['limit']) or myerror('Unable to fetch poll info', __FILE__, __LINE__, $fdb->error());
$last_id = -1;
while ($ob = $fdb->fetch_assoc($result)) {
    $last_id = $ob['vote_id'];
    echo htmlspecialchars($ob['vote_text']) . ' (' . $ob['vote_id'] . ")<br>\n";
    flush();
    $answers = null;
    $results = null;
    $vote_results = $fdb->query('SELECT vote_option_text,vote_result FROM ' . $fdb->prefix . $_SESSION['phpnuke'] . 'vote_results WHERE vote_id=' . $ob['vote_id'] . ' ORDER BY vote_option_id') or myerror("Unable to get poll answers.", __FILE__, __LINE__, $fdb->error());
    while (list($vote_option_text, $vote_result) = $fdb->fetch_row($vote_results)) {
        $answers[] = htmlspecialchars($vote_option_text, ENT_QUOTES);
        $results[] = $vote_result;
    }
    $voter_ids = null;
    $vote_results = $fdb->query('SELECT vote_user_id FROM ' . $fdb->prefix . $_SESSION['phpnuke'] . 'vote_voters WHERE vote_id=' . $ob['vote_id']) or myerror("PhpBB: Unable to get poll voters.", __FILE__, __LINE__, $fdb->error());
    while (list($voters) = $fdb->fetch_row($vote_results)) {
        $voter_ids[] = $voters;
    }
    $db->query('UPDATE ' . $db->prefix . 'topics SET question=\'' . $db->escape(convert_to_utf8($ob['vote_text'])) . '\' WHERE id=' . $ob['topic_id']) or myerror("PhpBB: Unable to get poll voters.", __FILE__, __LINE__, $fdb->error());
    // Dataarray
    $todb = array('id' => $ob['vote_id'], 'pollid' => $ob['topic_id'], 'ptype' => 1, 'options' => serialize($answers), 'voters' => serialize($voter_ids), 'votes' => serialize($results), 'created' => $ob['vote_start']);
    // Save data
    insertdata('polls', $todb, __FILE__, __LINE__);
}
convredirect('vote_id', $_SESSION['phpnuke'] . 'vote_desc', $last_id);
Exemple #9
0
/**
 * Article Box
 */
function display_forum_log_box($row)
{
    global $cfg, $keys, $lang, $log_table, $comment_class, $forum_table, $cd, $row, $tid, $session_status, $rrow, $case, $i, $keys, $request_uri, $p, $pn;
    $row['title'] = sanitize($row['title']);
    $row['comment'] = sanitize($row['comment']);
    $row['user_name'] = sanitize($row['user_name']);
    $row['user_uri'] = sanitize($row['user_uri']);
    $row['date'] = sanitize($row['date']);
    $row['parent_key'] = sanitize(intval($row['parent_key']));
    hit_key_highlight();
    // Check the ID of the latest post
    $check_latest_sql = "SELECT `id` FROM `{$forum_table}` WHERE `tid` = '{$row['tid']}' AND `parent_key` = '0' AND `trash` = '0' ORDER BY `mod` DESC LIMIT 1";
    $check_latest_res = mysql_query($check_latest_sql);
    $check_latest_row = mysql_fetch_array($check_latest_res);
    if ($check_latest_row[0] == $row['id']) {
        $check_latest = ' id="latest"';
    } else {
        $check_latest = '';
    }
    if ($row['parent_key'] == 1) {
        if (isset($row['refer_id']) && $row['refer_id'] != 0) {
            $rsql = "SELECT `name` FROM `{$log_table}` WHERE `id` = '{$row['refer_id']}'";
            $rres = mysql_query($rsql);
            $rrow = mysql_fetch_array($rres);
            $rrow = convert_to_utf8($rrow);
            $anchor = '<h2>' . '&#187; ' . '<a href="../article.php?id=' . $row['refer_id'] . '"> ' . $rrow['name'] . " </a></h2>\n";
            $top_title = '<div class="comments">' . "\n" . '<h3>' . $row['title'] . "</h3>\n";
        } else {
            $anchor = '';
            $top_title = '<div class="comments"' . $check_latest . '>' . "\n" . '<h2 id="topic-title">' . $row['title'] . "</h2>\n";
            // Parent post title
        }
        $comment = $anchor . $top_title;
    } else {
        $comment = '<div class="comments"' . $check_latest . '>' . "\n" . '<h3>' . $row['title'] . "</h3>\n";
    }
    // in case ">" is posted...convert ">" to "&gt;"
    //$row['comment'] = htmlspecialchars($row['comment']);
    // auto line-breaks
    $row['comment'] = nl2p($row['comment']);
    // generate URI
    if (isset($row['user_uri']) && preg_match('/([^=^\\"]|^)(http\\:[\\w\\.\\~\\-\\/\\?\\&\\+\\=\\:\\@\\%\\;\\#\\%]+)/', $row['user_uri'])) {
        $author = '<a href="' . $row['user_uri'] . '">' . $row['user_name'] . '</a>';
    } else {
        $author = $row['user_name'];
    }
    $comment .= '<p class="author">' . 'From : ' . $author . ' @ ' . $row['date'] . ' ' . '<span class="edit"><a href="./modify.php?tid=' . $row['tid'] . '&amp;id=' . $row['id'] . '">' . $lang['edit'] . "</a></span>\n" . '<span class="quote"><a href="./topic.php?tid=' . $row['tid'] . '&amp;p=' . $p . '&amp;pn=' . $pn . '&amp;pm=' . $cfg['pagemax'] . '&amp;qid=' . $row['id'] . '#addform">' . $lang['quote'] . "</a></span></p>\n";
    $class_order = array_keys($comment_class);
    $color_class = $class_order[$row['color']];
    $comment .= '<div class="' . $color_class . '">' . "\n" . $row['comment'] . "</div>\n";
    if (preg_match('/forum\\/search.php/', $request_uri)) {
        $comment .= '<div class="a-footer"><a href="./topic.php?tid=' . $row['tid'] . '">' . $lang['topic'] . '</a></div>';
    }
    // Display "Update" and "Delete" button while admin is logged-in.
    if ($session_status == 'on') {
        $comment .= '<form action="./admin/modify.php" method="post">' . "\n" . '<div class="submit-button">' . "\n" . '<input type="hidden" name="id" value="' . $row['id'] . '" />' . "\n" . '<input type="hidden" name="tid" value="' . $row['tid'] . '" />' . "\n" . '<input type="submit" value="' . $lang['mod'] . '" />' . "\n" . "</div>\n" . "</form>\n" . '<form method="post" action="./admin/delete.php">' . "\n" . '<div class="submit-button">' . "\n" . '<input type="hidden" name="id" value="' . $row['id'] . '" />' . "\n" . '<input type="hidden" name="tid" value="' . $row['tid'] . '" />' . "\n" . '<input type="submit" value="' . $lang['delete'] . '" />' . "\n" . "</div>\n" . '</form>' . "\n";
    } else {
        $comment .= '';
    }
    $comment .= "</div>\n";
    $comment = smiley($comment);
    return $comment;
}
Exemple #10
0
function convert_to_utf8($arr)
{
    if (is_array($arr)) {
        $temp = array();
        foreach ($arr as $i => $rs) {
            if (is_array($rs)) {
                $temp[$i] = convert_to_utf8($rs);
            } else {
                $temp[$i] = utf8_decode($rs);
            }
        }
        return $temp;
    } else {
        return utf8_decode($arr);
    }
}
Exemple #11
0
 /**
  * Load / fetch a class
  * @since Version 3.2
  * @param boolean $recurse
  */
 private function fetch($recurse)
 {
     if (!filter_var($this->id, FILTER_VALIDATE_INT)) {
         $this->id = Utility\LocomotiveUtility::getClassId($this->id);
     }
     $this->mckey = sprintf("railpage:locos.class_id=%d", $this->id);
     $key = "id";
     if (!($row = $this->Memcached->fetch($this->mckey))) {
         $timer = Debug::getTimer();
         $query = "SELECT c.id, c.meta, c.asset_id, c.slug, c.download_id, c.date_added, c.date_modified, c.model, c.axle_load, c.tractive_effort, c.weight, c.length, c.parent AS parent_class_id, c.source_id AS source, c.id AS class_id, c.flickr_tag, c.flickr_image_id, c.introduced AS class_introduced, c.name AS class_name, c.loco_type_id AS loco_type_id, c.desc AS class_desc, c.manufacturer_id AS class_manufacturer_id, m.manufacturer_name AS class_manufacturer, w.arrangement AS wheel_arrangement, w.id AS wheel_arrangement_id, t.title AS loco_type\r\n                        FROM loco_class AS c\r\n                        LEFT JOIN loco_type AS t ON c.loco_type_id = t.id\r\n                        LEFT JOIN wheel_arrangements AS w ON c.wheel_arrangement_id = w.id\r\n                        LEFT JOIN loco_manufacturer AS m ON m.manufacturer_id = c.manufacturer_id\r\n                        WHERE c." . $key . " = ?";
         $row = $this->db->fetchRow($query, $this->id);
         Debug::logEvent(__METHOD__, $timer);
         /** 
          * Normalise some items
          */
         if (function_exists("convert_to_utf8")) {
             foreach ($row as $key => $val) {
                 $row[$key] = convert_to_utf8($val);
             }
         }
         $this->Memcached->save($this->mckey, $row, strtotime("+1 year"));
     }
     // Get out early if we don't have a valid data source
     if (!isset($row) || !is_array($row)) {
         return;
     }
     $timer = Debug::getTimer();
     if (isset($row['id'])) {
         $this->id = $row['id'];
     }
     if (!isset($row['id'])) {
         deleteMemcacheObject($this->mckey);
     }
     // Populate the class objects
     $this->slug = $row['slug'];
     $this->name = $row['class_name'];
     $this->desc = $row['class_desc'];
     $this->type = $row['loco_type'];
     $this->type_id = $row['loco_type_id'];
     $this->introduced = $row['class_introduced'];
     $this->manufacturer = $row['class_manufacturer'];
     $this->manufacturer_id = $row['class_manufacturer_id'];
     $this->wheel_arrangement = $row['wheel_arrangement'];
     $this->wheel_arrangement_id = $row['wheel_arrangement_id'];
     $this->flickr_tag = $row['flickr_tag'];
     $this->flickr_image_id = $row['flickr_image_id'];
     $this->axle_load = $row['axle_load'];
     $this->tractive_effort = $row['tractive_effort'];
     $this->weight = $row['weight'];
     $this->length = $row['length'];
     $this->model = $row['model'];
     $this->date_added = $row['date_added'];
     $this->date_modified = $row['date_modified'];
     $this->download_id = $row['download_id'];
     if (empty($this->slug) || $this->slug === "1") {
         $this->createSlug();
         $this->commit();
     }
     $this->url = Utility\LocoClassUtility::buildUrls($this);
     /**
      * Set the meta data
      */
     $this->meta = array();
     if (isset($row['meta'])) {
         $this->meta = json_decode($row['meta'], true);
     }
     /**
      * If an asset ID exists and is greater than 0, create the asset object
      */
     if (isset($row['asset_id']) && $row['asset_id'] > 0) {
         try {
             $this->Asset = new Asset($row['asset_id']);
         } catch (Exception $e) {
             global $Error;
             $Error->save($e);
         }
     }
     /** 
      * Create the fwlink object
      */
     try {
         $this->fwlink = new fwlink($this->url);
         if (empty($this->fwlink->url) && !empty(trim($this->name))) {
             $this->fwlink->url = $this->url;
             $this->fwlink->title = $this->name;
             $this->fwlink->commit();
         }
     } catch (Exception $e) {
         // Do nothing
     }
     /*
     // Parent object
     if ($row['parent_class_id'] > 0) {
         try {
             $this->parent = new LocoClass($row['parent_class_id'], false);
         } catch (Exception $e) {
             // Re-throw the error
             throw new Exception($e->getMessage()); 
         }
     }
     
     // Data source object
     if ($row['source'] > 0 && class_exists("Source")) {
         try {
             $this->source = new \Source($row['source']);
         } catch (Exception $e) {
             // Re-throw the error
             throw new Exception($e->getMessage());
         }
     }
     */
     /**
      * Set the StatsD namespaces
      */
     $this->StatsD->target->view = sprintf("%s.%d.view", $this->namespace, $this->id);
     $this->StatsD->target->edit = sprintf("%s.%d.view", $this->namespace, $this->id);
     Debug::logEvent(__METHOD__, $timer);
 }
 function save_review($req, $rrow, $prow, $contact, &$tf = null)
 {
     global $Conf, $Opt;
     $newsubmit = @$req["ready"] && !@$req["unready"] && (!$rrow || !$rrow->reviewSubmitted);
     $submit = $newsubmit || $rrow && $rrow->reviewSubmitted;
     $admin = $contact->allow_administer($prow);
     if (!$contact->timeReview($prow, $rrow) && (!isset($req['override']) || !$admin)) {
         return Conf::msg_error("The <a href='" . hoturl("deadlines") . "'>deadline</a> for entering this review has passed." . ($admin ? "  Select the “Override deadlines” checkbox and try again if you really want to override the deadline." : ""));
     }
     $q = array();
     $diff_view_score = VIEWSCORE_FALSE;
     $wc = 0;
     foreach ($this->forder as $field => $f) {
         if (isset($req[$field]) && (!$f->round_mask || $f->is_round_visible($rrow))) {
             $fval = $req[$field];
             if ($f->has_options) {
                 if ($f->parse_is_empty($fval)) {
                     $fval = 0;
                 } else {
                     if (!($fval = $f->parse_value($fval, false))) {
                         continue;
                     }
                 }
             } else {
                 $fval = rtrim($fval);
                 if ($fval != "") {
                     $fval .= "\n";
                 }
                 // Check for valid UTF-8; re-encode from Windows-1252 or Mac OS
                 $fval = convert_to_utf8($fval);
                 if ($f->include_word_count()) {
                     $wc += count_words($fval);
                 }
             }
             if ($rrow && strcmp($rrow->{$field}, $fval) != 0 && strcmp(cleannl($rrow->{$field}), cleannl($fval)) != 0) {
                 $diff_view_score = max($diff_view_score, $f->view_score);
             }
             $q[] = "{$field}='" . sqlq($fval) . "'";
         }
     }
     // get the current time
     $now = time();
     if ($rrow && $rrow->reviewModified && $rrow->reviewModified > $now) {
         $now = $rrow->reviewModified + 1;
     }
     // potentially assign review ordinal (requires table locking since
     // mySQL is stupid)
     $locked = false;
     if ($newsubmit) {
         $diff_view_score = max($diff_view_score, VIEWSCORE_AUTHOR);
         $q[] = "reviewSubmitted={$now}, reviewNeedsSubmit=0";
         if (!$rrow || !$rrow->reviewOrdinal) {
             $result = $Conf->qe("lock tables PaperReview write");
             if (!$result) {
                 return $result;
             }
             $locked = true;
             $result = $Conf->qe("select coalesce(max(reviewOrdinal), 0) from PaperReview where paperId={$prow->paperId} group by paperId");
             if ($result) {
                 $crow = edb_row($result);
                 $q[] = "reviewOrdinal=coalesce(reviewOrdinal, " . ($crow[0] + 1) . ")";
             }
             Dbl::free($result);
             $q[] = "timeDisplayed={$now}";
         }
     }
     // check whether used a review token
     $usedReviewToken = $contact->review_token_cid($prow, $rrow);
     // blind? reviewer type? edit version?
     $reviewBlind = $Conf->is_review_blind(!!@$req["blind"]);
     if ($rrow && $reviewBlind != $rrow->reviewBlind) {
         $diff_view_score = max($diff_view_score, VIEWSCORE_ADMINONLY);
     }
     $q[] = "reviewBlind=" . ($reviewBlind ? 1 : 0);
     if ($rrow && $rrow->reviewType == REVIEW_EXTERNAL && $contact->contactId == $rrow->contactId && $contact->isPC && !$usedReviewToken) {
         $q[] = "reviewType=" . REVIEW_PC;
     }
     if ($rrow && $diff_view_score > VIEWSCORE_FALSE && isset($req["version"]) && ctype_digit($req["version"]) && $req["version"] > defval($rrow, "reviewEditVersion")) {
         $q[] = "reviewEditVersion=" . ($req["version"] + 0);
     }
     if ($diff_view_score > VIEWSCORE_FALSE && $Conf->sversion >= 98) {
         $q[] = "reviewWordCount=" . $wc;
     }
     if (isset($req["reviewFormat"]) && $Conf->sversion >= 104 && @$Opt["formatInfo"]) {
         $fmt = null;
         foreach ($Opt["formatInfo"] as $k => $f) {
             if (@$f["name"] && strcasecmp($f["name"], $req["reviewFormat"]) == 0) {
                 $fmt = (int) $k;
             }
         }
         if (!$fmt && $req["reviewFormat"] && preg_match('/\\A(?:plain\\s*)?(?:text)?\\z/i', $f["reviewFormat"])) {
             $fmt = 0;
         }
         $q[] = "reviewFormat=" . ($fmt === null ? "null" : $fmt);
     }
     // notification
     $notification_bound = $now - 10800;
     $notify = $notify_author = false;
     if (!$rrow || $diff_view_score > VIEWSCORE_FALSE) {
         $q[] = "reviewModified=" . $now;
         // do not notify on updates within 3 hours
         if ($submit && $diff_view_score > VIEWSCORE_ADMINONLY) {
             if (!$rrow || !$rrow->reviewNotified || $rrow->reviewNotified < $notification_bound) {
                 $q[] = $notify = "reviewNotified=" . $now;
             }
             if ((!$rrow || !$rrow->reviewAuthorNotified || $rrow->reviewAuthorNotified < $notification_bound) && $diff_view_score >= VIEWSCORE_AUTHOR && Contact::can_some_author_view_submitted_review($prow)) {
                 $q[] = $notify_author = "reviewAuthorNotified=" . $now;
             }
         }
     }
     // actually affect database
     if ($rrow) {
         $result = $Conf->qe("update PaperReview set " . join(", ", $q) . " where reviewId={$rrow->reviewId}");
         $reviewId = $rrow->reviewId;
         $contactId = $rrow->contactId;
     } else {
         $result = Dbl::qe_raw("insert into PaperReview set paperId={$prow->paperId}, contactId={$contact->contactId}, reviewType=" . REVIEW_PC . ", requestedBy={$contact->contactId}, reviewRound=" . $Conf->current_round() . ", " . join(", ", $q));
         $reviewId = $result ? $result->insert_id : null;
         $contactId = $contact->contactId;
     }
     // unlock tables even if problem
     if ($locked) {
         $Conf->qe("unlock tables");
     }
     if (!$result) {
         return $result;
     }
     // update caches
     Contact::update_rights();
     // look up review ID
     if (!$reviewId) {
         return $reviewId;
     }
     $req['reviewId'] = $reviewId;
     // log updates -- but not if review token is used
     if (!$usedReviewToken && $diff_view_score > VIEWSCORE_FALSE) {
         $text = "Review {$reviewId} ";
         if ($rrow && $contact->contactId != $rrow->contactId) {
             $text .= "by {$rrow->email} ";
         }
         $text .= $newsubmit ? "submitted" : ($submit ? "updated" : "saved draft");
         $contact->log_activity($text, $prow);
     }
     // potentially email chair, reviewers, and authors
     if ($submit) {
         $rrow = $Conf->reviewRow(["reviewId" => $reviewId]);
     }
     if ($submit && ($notify || $notify_author) && $rrow) {
         $tmpl = $newsubmit ? "@reviewsubmit" : "@reviewupdate";
         $submitter = $contact;
         if ($contactId != $submitter->contactId) {
             $submitter = Contact::find_by_id($contactId);
         }
         // construct mail
         $this->mailer_info = array("template" => $tmpl, "rrow" => $rrow, "reviewer_contact" => $submitter, "reviewNumber" => $prow->paperId . unparseReviewOrdinal($rrow->reviewOrdinal), "check_function" => "HotCRPMailer::check_can_view_review", "diff_view_score" => $diff_view_score);
         $this->mailer_preps = array();
         if ($Conf->timeEmailChairAboutReview()) {
             HotCRPMailer::send_manager($tmpl, $prow, $this->mailer_info);
         }
         $prow->notify(WATCHTYPE_REVIEW, array($this, "review_watch_callback"), $contact);
         if (count($this->mailer_preps)) {
             HotCRPMailer::send_combined_preparations($this->mailer_preps);
         }
         unset($this->mailer_info, $this->mailer_preps);
     }
     // if external, forgive the requestor from finishing their review
     if ($rrow && $rrow->reviewType < REVIEW_SECONDARY && $rrow->requestedBy && $submit) {
         $Conf->q("update PaperReview set reviewNeedsSubmit=0 where paperId={$prow->paperId} and contactId={$rrow->requestedBy} and reviewType=" . REVIEW_SECONDARY . " and reviewSubmitted is null");
     }
     if ($tf !== null) {
         $what = "#{$prow->paperId}" . ($rrow && $rrow->reviewSubmitted ? unparseReviewOrdinal($rrow->reviewOrdinal) : "");
         if ($newsubmit) {
             $tf["newlySubmitted"][] = $what;
         } else {
             if ($diff_view_score > VIEWSCORE_FALSE && $submit) {
                 $tf["updated"][] = $what;
             } else {
                 if ($diff_view_score > VIEWSCORE_FALSE) {
                     $tf["savedDraft"][] = $what;
                 } else {
                     $tf["unchanged"][] = $what;
                 }
             }
         }
         if ($notify_author) {
             $tf["authorNotified"][] = $what;
         }
     }
     return $result;
 }
 public function extractContentBlock($permalink)
 {
     $extractor = new ContentExtractor(dirname(__FILE__) . '/site_config/custom', dirname(__FILE__) . '/site_config/standard');
     //$extractor = $this;
     $extractor->next_page_deep_count = $this->next_page_deep_count + 1;
     $extractor->next_pages = $this->next_pages;
     if (in_array($permalink, $extractor->next_pages)) {
         return FALSE;
     }
     $extractor->next_pages[] = $permalink;
     if ($extractor->next_page_deep_count > 3) {
         return FALSE;
     }
     $extractor->fingerprints = $this->options->fingerprints;
     $elem = new ContentExtractor($this->path, $this->fallback);
     $extractor->fingerprints = $this->fingerprints;
     $http = new HumbleHttpAgent();
     $response = $http->get($permalink, true);
     //echo 'status_code: '. $response['status_code'] . "\n\n";
     if ($permalink && ($response = $http->get($permalink, true)) && ($response['status_code'] < 300 || $response['status_code'] > 400)) {
         $html = $response['body'];
         //echo "html: " .$html;
         // remove strange things
         $html = str_replace('</[>', '', $html);
         $html = convert_to_utf8($html, $response['headers']);
         if (function_exists('mb_convert_encoding')) {
             $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
         }
         $extract_result = $extractor->process($html, $permalink);
         //$readability = $extractor->readability;
         $content_block = $extract_result ? $extractor->getContent() : null;
         //echo "content_block->innerHTML: ". $content_block->innerHTML . "\n\n";
         //$this->body->appendChild($elem);
     }
     $doc = new DOMDocument();
     if (@$doc->loadHTML($content_block->innerHTML)) {
         $doc->saveHTML();
         //$content = $this->readability->dom->loadHTML($content_block->innerHTML);
         $content = $this->readability->dom->createElement('div', $content_block->innerHTML);
         $content = $this->readability->dom->importNode($content_block, true);
         return $content;
     } else {
         return FALSE;
     }
     return FALSE;
     //return $content_block;
 }
Exemple #14
0
 /**
  * Convert specified data to the UTF-8 charset
  *
  * @param string $str
  */
 function convert_to_utf8($str)
 {
     return convert_to_utf8($str, $this->db_config['charset']);
 }
Exemple #15
0
 /**
  * List the contents of this folder
  * @since Version 3.3
  * @version 3.3
  * @return array
  * @param object $User
  * @param int $page
  * @param int $items_per_page
  */
 public function getContents($User = false, $page = 1, $items_per_page = 25)
 {
     if (empty($this->folder)) {
         throw new \Exception("Cannot get folder contents - no folder specified");
     }
     if (!$User || !is_object($User)) {
         throw new \Exception("Cannot get folder contents - User object not provided");
     }
     if (!$User->id) {
         throw new \Exception("No user ID available");
     }
     if (!$User->enable_privmsg) {
         throw new \Exception("Private messages not available to this user");
     }
     // Store the user object
     $this->user = $User;
     // Fetch message IDs that have been "deleted" by this user
     $deleted = $this->getDeleted($User->id);
     if (count($deleted)) {
         $exclude_sql = " AND privmsgs_id NOT IN ('" . implode("', '", $deleted) . "') ";
     } else {
         $exclude_sql = "";
     }
     if ($this->folder == PM_INBOX) {
         $pm_folder_sql = "pm.privmsgs_to_userid = " . $this->user->id . " AND (pm.privmsgs_type = " . PRIVMSGS_READ_MAIL . " OR pm.privmsgs_type = " . PRIVMSGS_NEW_MAIL . " OR pm.privmsgs_type = " . PRIVMSGS_UNREAD_MAIL . " )";
     } elseif ($this->folder == PM_OUTBOX) {
         $pm_folder_sql = "pm.privmsgs_from_userid = " . $this->user->id . " AND (pm.privmsgs_type = " . PRIVMSGS_NEW_MAIL . " OR pm.privmsgs_type = " . PRIVMSGS_UNREAD_MAIL . ")";
     } elseif ($this->folder == PM_SENTBOX) {
         $pm_folder_sql = "pm.privmsgs_from_userid = " . $this->user->id . " AND (pm.privmsgs_type = " . PRIVMSGS_READ_MAIL . " OR pm.privmsgs_type = " . PRIVMSGS_SENT_MAIL . ")";
     } elseif ($this->folder == PM_SAVEBOX) {
         $pm_folder_sql = "((pm.privmsgs_to_userid = " . $this->user->id . " AND pm.privmsgs_type = " . PRIVMSGS_SAVED_IN_MAIL . ") OR (pm.privmsgs_from_userid = " . $this->user->id . " AND pm.privmsgs_type = " . PRIVMSGS_SAVED_OUT_MAIL . "))";
     }
     // Which "page" is this?
     if ($page == 1) {
         $start = 0;
     } else {
         $start = $page * $items_per_page;
     }
     // Done checking - get the PMs - sort by date ASC because the uasort() function will fix them up properly
     $query = "SELECT pm.*, pmt.*, ufrom.username AS username_from, ufrom.user_id AS user_id_from, ufrom.user_avatar AS user_avatar_from, uto.username AS username_to, uto.user_id AS user_id_from, uto.user_avatar AS user_avatar_to\r\n\t\t\t\t\t\tFROM nuke_bbprivmsgs AS pm\r\n\t\t\t\t\t\tLEFT JOIN nuke_bbprivmsgs_text AS pmt ON pm.privmsgs_id = pmt.privmsgs_text_id\r\n\t\t\t\t\t\tLEFT JOIN nuke_users AS ufrom ON ufrom.user_id = privmsgs_from_userid\r\n\t\t\t\t\t\tLEFT JOIN nuke_users AS uto ON uto.user_id = privmsgs_to_userid\r\n\t\t\t\t\t\tWHERE " . $pm_folder_sql . "\r\n\t\t\t\t\t\t" . $exclude_sql . "\r\n\t\t\t\t\t\tORDER BY pm.privmsgs_date ASC";
     #LIMIT ".$start.", ".$this->db->real_escape_string($items_per_page);
     #echo $query;
     if ($this->db instanceof \sql_db) {
         if ($rs = $this->db->query($query)) {
             #$total = $this->db->query("SELECT FOUND_ROWS() AS total");
             #$total = $total->fetch_assoc();
             $return = array();
             $return['stat'] = "ok";
             #$return['total'] = $total['total'];
             $return['page'] = $page;
             $return['perpage'] = $items_per_page;
             $return['messages'] = array();
             while ($row = $rs->fetch_assoc()) {
                 // Fix up the sodding non-UTF8 characters
                 $row['privmsgs_text'] = convert_to_utf8($row['privmsgs_text']);
                 $row['privmsgs_subject'] = str_replace("Re: ", "", $row['privmsgs_subject']);
                 if ($row['privmsgs_from_userid'] == $this->user->id) {
                     $pm_from = $row['privmsgs_to_userid'];
                 } else {
                     $pm_from = $row['privmsgs_from_userid'];
                 }
                 $id = md5($row['privmsgs_subject'] . $pm_from);
                 if (function_exists("format_avatar")) {
                     $row['user_avatar_from'] = format_avatar($row['user_avatar_from'], 40, 40);
                     $row['user_avatar_to'] = format_avatar($row['user_avatar_to'], 40, 40);
                 }
                 $return['messages'][$id] = $row;
             }
             // Sort by loco number
             uasort($return['messages'], function ($a, $b) {
                 return strnatcmp($b['privmsgs_date'], $a['privmsgs_date']);
             });
         } else {
             throw new \Exception($this->db->error);
             $return['stat'] = "error";
             $return['error'] = $this->db->error;
         }
         $return['total'] = count($return['messages']);
         $return['messages'] = array_slice($return['messages'], $start, $items_per_page);
         return $return;
     } else {
         $return = array();
         $return['stat'] = "ok";
         $return['page'] = $page;
         $return['perpage'] = $items_per_page;
         $return['messages'] = array();
         foreach ($this->db->fetchAll($query) as $row) {
             $row['privmsgs_text'] = convert_to_utf8($row['privmsgs_text']);
             $row['privmsgs_subject'] = str_replace("Re: ", "", $row['privmsgs_subject']);
             if ($row['privmsgs_from_userid'] == $this->user->id) {
                 $pm_from = $row['privmsgs_to_userid'];
             } else {
                 $pm_from = $row['privmsgs_from_userid'];
             }
             $id = md5($row['privmsgs_subject'] . $pm_from);
             if (function_exists("format_avatar")) {
                 $row['user_avatar_from'] = @format_avatar($row['user_avatar_from'], 40, 40);
                 $row['user_avatar_to'] = @format_avatar($row['user_avatar_to'], 40, 40);
             }
             $return['messages'][$id] = $row;
         }
         // Sort by loco number
         uasort($return['messages'], function ($a, $b) {
             return strnatcmp($b['privmsgs_date'], $a['privmsgs_date']);
         });
         $return['total'] = count($return['messages']);
         $return['messages'] = array_slice($return['messages'], $start, $items_per_page);
         return $return;
     }
 }
Exemple #16
0
/**
 * Trackback
 *
 * 2004/05/09 first implementation. 
 * @author   : imksoo / Kajiya Takeshi
 * @modified : kaz
 *
 * $Id: fnc_trackback.inc.php, 2006-08-12 23:23:07 Exp $
 */
function display_trackback($row)
{
    global $trackback_table, $cfg, $lang, $id, $cd, $session_status, $trackbacks, $row, $article_addition, $email_link;
    $tb_query = 'SELECT * FROM `' . $trackback_table . "` WHERE `blog_id` = '" . $row['id'] . "' ORDER BY `id`";
    $tb_res = mysql_query($tb_query);
    if (!$tb_res) {
        return ' Trackback : Off';
        exit;
    }
    $tb_rows = mysql_num_rows($tb_res);
    if ($tb_rows == '0') {
        $tb_str = 'Trackback';
    } elseif ($tb_rows == '1') {
        $tb_str = $tb_rows . ' Trackback';
    } else {
        $tb_str = $tb_rows . ' Trackbacks';
    }
    // Article Addition
    if (empty($article_addition)) {
        $article_addition = '';
    }
    // "View Trackback" popup title
    $view_tb_title = $lang['view_tb_title_1'] . htmlspecialchars(strip_tags($row['name'])) . $lang['view_tb_title_2'];
    if ($tb_rows != 0) {
        // When there are some trackbacks...
        $trackbacks = '';
        while ($tb_row = mysql_fetch_array($tb_res)) {
            $tb_row = convert_to_utf8($tb_row);
            $tb_id = sanitize($tb_row['id']);
            $tb_title = sanitize($tb_row['title']);
            $tb_excerpt = sanitize($tb_row['excerpt']);
            $tb_url = sanitize($tb_row['url']);
            $tb_name = sanitize($tb_row['name']);
            $tb_date = sanitize($tb_row['date']);
            if ($session_status == 'on') {
                // When session status is on, display "Delete Ping" button.
                $delete_button = '<form action="' . $cd . '/trackback/admin/delete_ping.php" method="post">' . "\n" . '<div class="submit-button">' . "\n" . '<input type="hidden" name="id" value="' . $row['id'] . '" />' . "\n" . '<input type="hidden" name="ping_id" value="' . $tb_row['id'] . '" />' . "\n" . '<input tabindex="1" accesskey="d" type="submit" value="' . $lang['delete'] . '" />' . "\n" . '</div>' . "\n" . '</form>';
            } else {
                $delete_button = '';
            }
            $trackbacks .= '<h5 id="tb' . $tb_id . '"><a href="' . $tb_url . '">' . $tb_title . '</a></h5>' . "\n" . '<p>' . $tb_excerpt . "</p>\n" . '<p class="author">From : ' . $tb_name . ' @ ' . $tb_date . "</p>\n" . $delete_button;
            $tb_status = ' class="status-on"';
        }
    } else {
        // When No Trackbacks ....
        $trackbacks = '<p class="gray-out">No Trackbacks</p>';
        $tb_status = '';
    }
    $tb_alert = file_exists($cd . '/include/user_include/plugins/plg_trackback_spam_blocker.inc.php') ? '<br />(言及リンクのないトラックバックは無視されます)' : '';
    $trackback_list = <<<EOD
<!-- Begin #trackback-list -->
<div id="trackback-list">
<h4 id="trackbacks">{$tb_str}</h4>
{$trackbacks}
<h5>Track from Your Website</h5>
<p class="trackback-uri">http://{$_SERVER['HTTP_HOST']}{$cfg['root_path']}trackback/tb.php?id={$row['id']}{$tb_alert}</p>
</div>
<!-- End #trackback-list -->

EOD;
    if (!empty($id)) {
        // When Permalink
        $trackback = $trackback_list;
    } else {
        $trackback = '<a href="./article.php?id=' . $row['id'] . '#trackbacks" title="' . $view_tb_title . '"' . $tb_status . '>' . $tb_str . '</a> ';
    }
    return $trackback;
}
Exemple #17
0
 if ($start_at == 0) {
     // Get the first post ID from the db
     $query = array('SELECT' => 'id', 'FROM' => 'posts', 'ORDER BY' => 'id', 'LIMIT' => '1');
     $result = $forum_db->query_build($query) or error(__FILE__, __LINE__);
     $start_at = $forum_db->result($result);
     if (is_null($start_at) || $start_at === false) {
         $start_at = 0;
     }
 }
 $end_at = $start_at + PER_PAGE;
 // Fetch posts to process this cycle
 $query = array('SELECT' => 'id, poster, message, edited_by', 'FROM' => 'posts', 'WHERE' => 'id >= ' . $start_at . ' AND id < ' . $end_at, 'ORDER BY' => 'id');
 $result = $forum_db->query_build($query) or error(__FILE__, __LINE__);
 while ($cur_item = $forum_db->fetch_assoc($result)) {
     echo 'Converting post ' . $cur_item['id'] . '…<br />' . "\n";
     if (convert_to_utf8($cur_item['poster'], $old_charset) | convert_to_utf8($cur_item['message'], $old_charset) | convert_to_utf8($cur_item['edited_by'], $old_charset)) {
         $cur_item['edited_by'] = $cur_item['edited_by'] != '' ? '\'' . $forum_db->escape($cur_item['edited_by']) . '\'' : 'NULL';
         $query = array('UPDATE' => 'posts', 'SET' => 'poster = \'' . $forum_db->escape($cur_item['poster']) . '\', message = \'' . $forum_db->escape($cur_item['message']) . '\', edited_by = ' . $cur_item['edited_by'], 'WHERE' => 'id = ' . $cur_item['id']);
         $forum_db->query_build($query) or error(__FILE__, __LINE__);
     }
 }
 // Check if there is more work to do
 $query = array('SELECT' => 'id', 'FROM' => 'posts', 'WHERE' => 'id >= ' . $end_at, 'ORDER BY' => 'id ASC', 'LIMIT' => '1');
 $result = $forum_db->query_build($query) or error(__FILE__, __LINE__);
 $start_id = $forum_db->result($result);
 if (is_null($start_id) || $start_id === false) {
     $query_str = '?stage=conv_tables';
 } else {
     $query_str = '?stage=conv_posts&req_old_charset=' . $old_charset . '&req_per_page=' . PER_PAGE . '&start_at=' . $start_id;
 }
 unset($start_id);
 /**
  * Parse singlepart message
  *
  * @param integer $message_id
  * @param stdObj $structure
  * @param MailboxManagerEmail $email
  * @return MailboxManagerEmail
  */
 function parseMessageSinglepartBody($message_id, &$structure, &$email)
 {
     $content_type = $this->getContentType($structure);
     $type = $this->getMainContentType($structure->type);
     $sub_type = $this->getSubContentType($structure->subtype);
     $charset = strtoupper($this->getPartParameter($structure, 'charset'));
     $encoding = $this->getBodyEncodingString($structure->encoding);
     $content = imap_body($this->getConnection(), $message_id);
     switch ($encoding) {
         case 'base64':
             $content = imap_base64($content);
             break;
         case 'quoted-printable':
             $content = imap_qprint($content);
             break;
     }
     // switch
     $content = $charset == 'UTF-8' ? $content : convert_to_utf8($content, $charset);
     $email->addBody('0', $content_type, $content);
     return $email;
 }
 public function jsonSerialize()
 {
     $x = array();
     foreach (get_object_vars($this) as $k => $v) {
         if ($k === "content" && $v !== null) {
             $v = strlen($v) < 50 ? $v : substr($v, 0, 50) . "...";
             $x[$k] = convert_to_utf8($v);
         } else {
             if ($v !== null) {
                 $x[$k] = $v;
             }
         }
     }
     return $x;
 }
Exemple #20
0
 /**
  * Process and format each conversation in this folder, in this page
  * @since Version 3.9.1
  * @param array $row
  * @return array
  */
 private function processConversations($conversations)
 {
     foreach ($conversations as $id => $row) {
         $row['privmsgs_text'] = function_exists("convert_to_utf8") ? convert_to_utf8($row['privmsgs_text']) : $row['privmsgs_text'];
         $row['user_avatar_from'] = function_exists("format_avatar") ? format_avatar($row['user_avatar_from'], 40, 40) : $row['user_avatar_from'];
         $row['user_avatar_to'] = function_exists("format_avatar") ? format_avatar($row['user_avatar_to'], 40, 40) : $row['user_avatar_to'];
         $conversations[$id] = $row;
     }
     return $conversations;
 }
Exemple #21
0
// Check if AutoPoll is installed
if ($start == 0 && !$db->table_exists('polls')) {
    next_step();
}
//Look for poll infos
$result = $fdb->query('SELECT * FROM ' . $fdb->prefix . 'polls WHERE poll_id>' . $start . ' ORDER BY poll_id LIMIT ' . $_SESSION['limit']) or myerror('Unable to fetch poll info', __FILE__, __LINE__, $fdb->error());
$last_id = -1;
while ($ob = $fdb->fetch_assoc($result)) {
    $last_id = $ob['poll_id'];
    echo htmlspecialchars($ob['poll_question']) . ' (' . $ob['poll_id'] . ")<br>\n";
    flush();
    $answers = null;
    //Look for poll answers
    $vote_results = $fdb->query('SELECT poss_name FROM ' . $fdb->prefix . 'pollpossibilities WHERE poss_pollid=' . $ob['poll_id'] . ' ORDER BY poss_id') or myerror("Unable to get poll answers.", __FILE__, __LINE__, $fdb->error());
    while (list($poss_name) = $fdb->fetch_row($vote_results)) {
        $answers[] = convert_to_utf8($poss_name);
    }
    //Look for the topic associated to the poll
    $topic_result = $fdb->query('SELECT topic_id FROM ' . $fdb->prefix . 'topics WHERE topic_poll=' . $ob['poll_id']) or myerror('Unable to get poll topic', __FILE__, __LINE__, $fdb->error());
    list($topic_id) = $fdb->fetch_row($topic_result);
    $db->query('UPDATE ' . $db->prefix . 'topics SET question=\'' . $db->escape(convert_to_utf8($ob['poll_question'])) . '\' WHERE id=' . $topic_id) or myerror("Connectix Boards: Unable to set poll question.", __FILE__, __LINE__, $fdb->error());
    //Look for the poll start time
    $time_result = $fdb->query('SELECT msg_timestamp FROM ' . $fdb->prefix . 'messages WHERE msg_topicid=' . $topic_id . ' ORDER BY msg_id LIMIT 0,1') or myerror('Unable to get topic start time', __FILE__, __LINE__, $fdb->error());
    list($poll_start) = $fdb->fetch_row($time_result);
    // Dataarray
    $todb = array('id' => $ob['poll_id'], 'pollid' => $topic_id, 'ptype' => 1, 'options' => serialize($answers), 'created' => $poll_start);
    // Save data
    insertdata('polls', $todb, __FILE__, __LINE__);
}
convredirect('poll_id', 'polls', $last_id);
 while (@ob_end_flush()) {
     /* do nothing */
 }
 if (fileUploaded($_FILES["bulk"])) {
     $text = file_get_contents($_FILES["bulk"]["tmp_name"]);
     $filename = $_FILES["bulk"]["name"];
 } else {
     $text = $_POST["bulkentry"];
     $filename = "";
 }
 if ($text === false) {
     Conf::msg_error("Internal error: cannot read file.");
 } else {
     $assignset = new AssignmentSet($Me, false);
     $defaults = assignment_defaults();
     $text = convert_to_utf8($text);
     $assignset->parse($text, $filename, $defaults, "keep_browser_alive");
     finish_browser_alive();
     if ($assignset->has_errors()) {
         $assignset->report_errors();
     } else {
         if ($assignset->is_empty()) {
             $Conf->warnMsg("That assignment file makes no changes.");
         } else {
             $atype = $assignset->type_description();
             echo '<h3>Proposed ', $atype ? $atype . " " : "", 'assignment</h3>';
             $Conf->infoMsg("Select “Apply changes” if this looks OK. (You can always alter the assignment afterwards.)");
             list($atypes, $apids) = $assignset->types_and_papers(true);
             echo Ht::form_div(hoturl_post("bulkassign", ["saveassignment" => 1, "assigntypes" => join(" ", $atypes), "assignpids" => join(" ", $apids)]));
             $assignset->echo_unparse_display();
             echo '<div class="g"></div>', '<div class="aahc"><div class="aa">', Ht::submit("Apply changes"), ' &nbsp;', Ht::submit("cancel", "Cancel"), Ht::hidden("default_action", $defaults["action"]), Ht::hidden("rev_roundtag", $defaults["round"]), Ht::hidden("file", $text), Ht::hidden("assignment_size_estimate", $csv_lineno), Ht::hidden("filename", $filename), Ht::hidden("requestreview_notify", req("requestreview_notify")), Ht::hidden("requestreview_subject", req("requestreview_subject")), Ht::hidden("requestreview_body", req("requestreview_body")), Ht::hidden("bulkentry", req("bulkentry")), '</div></div></div></form>', "\n";
Exemple #23
0
} else {
    $Html = download("{$Host}/{$FormAction}", "POST", "{$Host}/bets.php?line_id[]={$Sport}", $PostHash);
}
function extract_bet($Html)
{
    $Html = extract_tags($Html, '<table cellSpacing=2 cellPadding=1', '</table>', "\r\n");
    $Html = kill_space($Html);
    $Html = kill_tag_bound($Html, 'b|a|br|font|img');
    $Html = str_ireplace(' nowrap', '', $Html);
    $Html = kill_property($Html, 'onmouseover|onclick|align|id|style|width|cellspacing');
    //  Убираем строки без ставок
    $Html = delete_all($Html, '<tr>', '</tr>', 'class="t_comment"');
    $Html = delete_all($Html, '<tr>', '</tr>', 'class="t_comment1"');
    $Html = str_ireplace(' class=date', ' @lass=date', $Html);
    $Html = kill_property($Html, 'class');
    $Html = str_ireplace(' @lass=date', ' class=date', $Html);
    return $Html;
}
$Result = extract_bet(convert_to_utf8($Html));
if ($debug) {
    file_put_contents($Lines . 'bets.txt', $Result);
}
if ($debug) {
    file_put_contents($Lines . 'bets.txt.html', $Result);
}
print $Result;
?>
</body>
</html>

/**
 * Alternative imap_utf8 function
 *
 * @param string $something_to_decode
 */
function imap_utf8_alt($something_to_decode)
{
    if (!trim($something_to_decode)) {
        return null;
    }
    // if
    // if function exists we will try to use it in order to decode subject, otherwise we use buggy imap_utf8
    if (function_exists('imap_mime_header_decode')) {
        $decoded = imap_mime_header_decode($something_to_decode);
        if (is_foreachable($decoded)) {
            $decoded_string = '';
            foreach ($decoded as $element) {
                if (strtoupper($element->charset) != 'UTF-8' && strtoupper($element->charset) != 'DEFAULT') {
                    $decoded_string .= convert_to_utf8($element->text, $element->charset);
                } else {
                    $decoded_string .= $element->text;
                }
                // if
            }
            // foreach
            $decoded_string = trim($decoded_string);
            if ($decoded_string) {
                return $decoded_string;
            }
            // if
        }
        // if
    }
    // if
    $decoded_string = trim(imap_utf8($something_to_decode));
    if (strlen_utf($decoded_string) > 0) {
        return $decoded_string;
    }
    // if
    return $something_to_decode;
}
Exemple #25
0
function cat_name_array($table)
{
    global $cfg, $log_table, $info_table, $cat_num, $row;
    if ($table == $log_table) {
        $sql = "SELECT `category` FROM `{$log_table}` WHERE `draft` = '0'";
        $cat_num = $cfg['show_cat_num'];
    } elseif ($table == $info_table) {
        $sql = "SELECT `bin_category` FROM `{$info_table}` WHERE `draft` = '0'";
        $cat_num = $cfg['show_bin_cat_num'];
    }
    $res = mysql_query($sql);
    $rowArray = array();
    while ($row = mysql_fetch_array($res)) {
        $row = convert_to_utf8($row);
        if ($table == $log_table) {
            $cat_row = $row['category'];
        } elseif ($table == $info_table) {
            $cat_row = $row['bin_category'];
        }
        $token = strtok($cat_row, ",");
        while ($token) {
            array_push($rowArray, trim($token));
            $token = strtok(",");
        }
    }
    if ($cat_num == 'yes') {
        $rowArray = array_count_values($rowArray);
        ksort($rowArray, SORT_STRING);
    } else {
        $rowArray = array_unique($rowArray);
        sort($rowArray, SORT_STRING);
    }
    return $rowArray;
}
Exemple #26
0
/**
 * Recent Trackbacks
 */
function display_recent_trackbacks()
{
    global $cfg, $lang, $trackback_table, $row;
    if ($cfg['show_recent_trackback'] == 'yes') {
        $trackback_list = '';
        $sql = 'SELECT' . " `id`, `blog_id`, `title`, `name`, DATE_FORMAT(`date`, '%Y/%m/%d %T') as `date`" . ' FROM `' . $trackback_table . '`' . " ORDER BY `date` DESC LIMIT " . $cfg['recent_trackback_max'];
        $res = mysql_query($sql);
        $rows = mysql_num_rows($res);
        if ($rows != '0') {
            while ($row = mysql_fetch_array($res)) {
                $row = convert_to_utf8($row);
                $trackback_title = htmlspecialchars($row['title']);
                $trackback_list .= '<li><a href="article.php?id=' . $row['blog_id'] . '#tb' . $row['id'] . '" title="&quot;' . $trackback_title . '&quot;">' . 'From ' . htmlspecialchars($row['name']) . '<br />@' . $row['date'] . '</a>' . "</li>\n";
            }
        } else {
            $trackback_list .= '<li>-</li>';
        }
        //////////////// Presentation! /////////////////
        $recent_trackbacks = <<<EOD
<div class="menu" id="recent-trackbacks">
<h2>{$lang['recent_trackbacks']}</h2>
<ul>
{$trackback_list}</ul>
</div>
EOD;
    } else {
        $recent_trackbacks = '';
    }
    return $recent_trackbacks;
}
Exemple #27
0
against_xss();
if ($session_status == 'on') {
    if (isset($_POST['draft'], $_POST['id'], $_POST['bin_mod']) && intval($_POST['draft']) == 0) {
        $id = $_POST['id'];
        $bin_mod = $_POST['bin_mod'];
        $sql = 'UPDATE ' . $info_table . " SET `draft` = '0', `bin_mod` = '" . $bin_mod . "' WHERE `id` = '" . $id . "'";
        $res = mysql_query($sql) or die("<h2>MySQL error</h2> " . mysql_errno() . " : " . mysql_error());
        if ($res) {
            $contents = '<div class="section">' . "\n" . '<h2 class="archive-title">' . $lang['file_published'] . "</h2>\n" . "</div>\n";
        }
        // Next, pull out the data and display the preview.
        $sql = 'SELECT ' . "`id`, `bin_title`, `bintype`, `binname`, `binsize`, `bindate`, " . "DATE_FORMAT(`bin_mod`, '%Y-%m-%d %T') as `bin_mod`, `bin_category`, `bincomment`, `bin_count`, `draft`" . ' FROM ' . $info_table . " WHERE `id` = '{$id}'";
        $res = mysql_query($sql);
        $row = mysql_fetch_array($res);
        // Generate XHTML
        $row = convert_to_utf8($row);
        format_date($row_name = 'bindate');
        $title_date = $formatted_date;
        $contents .= '<div class="section">' . "\n" . '<h2 class="date-title">' . $title_date . "</h2>\n";
        $contents .= display_binary_box($row);
        $contents .= file_uploaded();
        $contents .= "</div><!-- End .section -->\n";
        xhtml_output('');
    } else {
        // if user auth failed...
        header('Location: ' . $http . '://' . $_SERVER['HTTP_HOST'] . $cfg['root_path'] . 'index.php');
        exit;
    }
} else {
    header('Location: ' . $http . '://' . $_SERVER['HTTP_HOST'] . $cfg['root_path'] . 'index.php');
    exit;
 function save_paper_json($pj)
 {
     global $Conf, $Now;
     assert(!$this->hide_docids);
     $paperid = null;
     if (isset($pj->pid) && is_int($pj->pid) && $pj->pid > 0) {
         $paperid = $pj->pid;
     } else {
         if (!isset($pj->pid) && isset($pj->id) && is_int($pj->id) && $pj->id > 0) {
             $paperid = $pj->id;
         } else {
             if (isset($pj->pid) || isset($pj->id)) {
                 $key = isset($pj->pid) ? "pid" : "id";
                 $this->set_error_html($key, "Format error [{$key}]");
                 return false;
             }
         }
     }
     if (get($pj, "error") || get($pj, "error_html")) {
         $this->set_error_html("error", "Refusing to save paper with error");
         return false;
     }
     $this->prow = $old_pj = null;
     $this->paperid = $paperid ?: -1;
     if ($paperid) {
         $this->prow = $Conf->paperRow(["paperId" => $paperid, "topics" => true, "options" => true], $this->contact);
     }
     if ($this->prow) {
         $old_pj = $this->paper_json($this->prow, ["forceShow" => true]);
     }
     if ($pj && $old_pj && $paperid != $old_pj->pid) {
         $this->set_error_html("pid", "Saving paper with different ID");
         return false;
     }
     $this->normalize($pj, $old_pj);
     if ($old_pj) {
         $this->normalize($old_pj, null);
     }
     if ($this->nerrors) {
         return false;
     }
     $this->check_invariants($pj, $old_pj);
     // store documents (options already stored)
     if (isset($pj->submission) && $pj->submission) {
         $this->upload_document($pj->submission, PaperOption::find_document(DTYPE_SUBMISSION));
     }
     if (isset($pj->final) && $pj->final) {
         $this->upload_document($pj->final, PaperOption::find_document(DTYPE_FINAL));
     }
     // create contacts
     foreach (self::contacts_array($pj) as $c) {
         $c->only_if_contactdb = !get($c, "contact");
         $c->disabled = !!$this->disable_users;
         if (!Contact::create($c, !$this->no_email) && get($c, "contact")) {
             $this->set_error_html("contacts", "Could not create an account for contact " . Text::user_html($c) . ".");
         }
     }
     // catch errors
     if ($this->nerrors) {
         return false;
     }
     // update Paper table
     $q = array();
     foreach (array("title", "abstract", "collaborators") as $k) {
         $v = convert_to_utf8((string) get($pj, $k));
         if (!$old_pj || get($pj, $k) !== null && $v !== (string) get($old_pj, $k)) {
             $q[] = "{$k}='" . sqlq($v) . "'";
         }
     }
     if (!$old_pj || get($pj, "authors") !== null) {
         $autext = convert_to_utf8(self::author_information($pj));
         $old_autext = self::author_information($old_pj);
         if ($autext !== $old_autext || !$old_pj) {
             $q[] = "authorInformation='" . sqlq($autext) . "'";
         }
     }
     if ($Conf->submission_blindness() == Conf::BLIND_OPTIONAL && (!$old_pj || get($pj, "nonblind") !== null && !$pj->nonblind != !$old_pj->nonblind)) {
         $q[] = "blind=" . (get($pj, "nonblind") ? 0 : 1);
     }
     if (!$old_pj || get($pj, "submission") !== null) {
         $new_id = get($pj, "submission") ? $pj->submission->docid : 1;
         $old_id = $old_pj && get($old_pj, "submission") ? $old_pj->submission->docid : 1;
         if (!$old_pj || $new_id != $old_id) {
             $q[] = "paperStorageId={$new_id}";
         }
     }
     if (!$old_pj || get($pj, "final") !== null) {
         $new_id = get($pj, "final") ? $pj->final->docid : 0;
         $old_id = $old_pj && get($old_pj, "final") ? $old_pj->final->docid : 0;
         if (!$old_pj || $new_id != $old_id) {
             $q[] = "finalPaperStorageId={$new_id}";
         }
     }
     if (get($pj, "withdrawn") !== null || get($pj, "submitted") !== null || get($pj, "draft") !== null) {
         if (get($pj, "submitted") !== null) {
             $submitted = $pj->submitted;
         } else {
             if (get($pj, "draft") !== null) {
                 $submitted = !$pj->draft;
             } else {
                 if ($old_pj) {
                     $submitted = get($old_pj, "submitted_at") > 0;
                 } else {
                     $submitted = false;
                 }
             }
         }
         if (get($pj, "withdrawn")) {
             if (!$old_pj || !get($old_pj, "withdrawn")) {
                 $q[] = "timeWithdrawn=" . (get($pj, "withdrawn_at") ?: $Now);
                 $q[] = "timeSubmitted=" . ($submitted ? -100 : 0);
             } else {
                 if (get($old_pj, "submitted_at") > 0 !== $submitted) {
                     $q[] = "timeSubmitted=" . ($submitted ? -100 : 0);
                 }
             }
         } else {
             if ($submitted) {
                 if (!$old_pj || !get($old_pj, "submitted")) {
                     $q[] = "timeSubmitted=" . (get($pj, "submitted_at") ?: $Now);
                 }
                 if ($old_pj && get($old_pj, "withdrawn")) {
                     $q[] = "timeWithdrawn=0";
                 }
             } else {
                 if ($old_pj && (get($old_pj, "withdrawn") || get($old_pj, "submitted"))) {
                     $q[] = "timeSubmitted=0";
                     $q[] = "timeWithdrawn=0";
                 }
             }
         }
     }
     if (get($pj, "final_submitted") !== null) {
         if ($pj->final_submitted) {
             $time = get($pj, "final_submitted_at") ?: $Now;
         } else {
             $time = 0;
         }
         if (!$old_pj || get($old_pj, "final_submitted_at") != $time) {
             $q[] = "timeFinalSubmitted={$time}";
         }
     }
     if (!empty($q)) {
         if ($Conf->submission_blindness() == Conf::BLIND_NEVER) {
             $q[] = "blind=0";
         } else {
             if ($Conf->submission_blindness() != Conf::BLIND_OPTIONAL) {
                 $q[] = "blind=1";
             }
         }
         $joindoc = $old_joindoc = null;
         if (get($pj, "final")) {
             $joindoc = $pj->final;
             $old_joindoc = $old_pj ? get($old_pj, "final") : null;
         } else {
             if (get($pj, "submission")) {
                 $joindoc = $pj->submission;
                 $old_joindoc = $old_pj ? get($old_pj, "submission") : null;
             }
         }
         if ($joindoc && (!$old_joindoc || $old_joindoc->docid != $joindoc->docid) && get($joindoc, "size") && get($joindoc, "timestamp")) {
             $q[] = "size=" . $joindoc->size;
             $q[] = "mimetype='" . sqlq($joindoc->mimetype) . "'";
             $q[] = "sha1='" . sqlq($joindoc->sha1) . "'";
             $q[] = "timestamp=" . $joindoc->timestamp;
         } else {
             if (!$joindoc) {
                 $q[] = "size=0,mimetype='',sha1='',timestamp=0";
             }
         }
         if ($paperid) {
             $result = Dbl::qe_raw("update Paper set " . join(",", $q) . " where paperId={$paperid}");
             if ($result && $result->affected_rows === 0 && edb_nrows(Dbl::qe_raw("select paperId from Paper where paperId={$paperid}")) === 0) {
                 $result = Dbl::qe_raw("insert into Paper set paperId={$paperid}, " . join(",", $q));
             }
         } else {
             $result = Dbl::qe_raw("insert into Paper set " . join(",", $q));
             if (!$result || !($paperid = $pj->pid = $result->insert_id)) {
                 return $this->set_error_html(false, "Could not create paper.");
             }
             if (!empty($this->uploaded_documents)) {
                 Dbl::qe_raw("update PaperStorage set paperId={$paperid} where paperStorageId in (" . join(",", $this->uploaded_documents) . ")");
             }
         }
         // maybe update `papersub` settings
         $is_submitted = !get($pj, "withdrawn") && get($pj, "submitted");
         $was_submitted = $old_pj && !get($old_pj, "withdrawn") && get($old_pj, "submitted");
         if ($is_submitted != $was_submitted) {
             $Conf->update_papersub_setting($is_submitted);
         }
     }
     // update PaperTopics
     if (get($pj, "topics")) {
         $topics = self::topics_sql($pj, $paperid);
         $old_topics = self::topics_sql($old_pj, $paperid);
         if ($topics !== $old_topics) {
             $result = Dbl::qe_raw("delete from PaperTopic where paperId={$paperid}");
             if ($topics) {
                 $result = Dbl::qe_raw("insert into PaperTopic (topicId,paperId) values {$topics}");
             }
         }
     }
     // update PaperOption
     if (get($pj, "options")) {
         $options = convert_to_utf8(self::options_sql($pj, $paperid));
         $old_options = self::options_sql($old_pj, $paperid);
         if ($options !== $old_options) {
             $result = Dbl::qe("delete from PaperOption where paperId={$paperid} and optionId?a", array_keys($pj->parsed_options));
             if ($options) {
                 $result = Dbl::qe_raw("insert into PaperOption (paperId,optionId,value,data) values {$options}");
             }
         }
     }
     // update PaperConflict
     $conflict = $this->conflicts_array($pj, $old_pj);
     $old_conflict = $this->conflicts_array($old_pj, null);
     if (join(",", array_keys($conflict)) !== join(",", array_keys($old_conflict)) || join(",", array_values($conflict)) !== join(",", array_values($old_conflict))) {
         $q = array();
         foreach ($conflict as $email => $type) {
             $q[] = "'" . sqlq($email) . "'";
         }
         $ins = array();
         if (!empty($q)) {
             $result = Dbl::qe_raw("select contactId, email from ContactInfo where email in (" . join(",", $q) . ")");
             while ($row = edb_row($result)) {
                 $ins[] = "({$paperid},{$row['0']}," . $conflict[strtolower($row[1])] . ")";
             }
         }
         $result = Dbl::qe_raw("delete from PaperConflict where paperId={$paperid}");
         if (!empty($ins)) {
             $result = Dbl::qe_raw("insert into PaperConflict (paperId,contactId,conflictType) values " . join(",", $ins));
         }
     }
     return $paperid;
 }
 debug('Processing next page: ' . $next_page_url);
 // If we've got URL, resolve against $url
 if ($next_page_url = makeAbsoluteStr($effective_url, $next_page_url)) {
     // check it's not what we have already!
     if (!in_array($next_page_url, $multi_page_urls)) {
         // it's not, so let's attempt to fetch it
         $multi_page_urls[] = $next_page_url;
         $_prev_ref = $http->referer;
         if (($response = $http->get($next_page_url, true)) && $response['status_code'] < 300) {
             // make sure mime type is not something with a different action associated
             $page_mime_info = get_mime_action_info($response['headers']);
             if (!isset($page_mime_info['action'])) {
                 $html = $response['body'];
                 // remove strange things
                 $html = str_replace('</[>', '', $html);
                 $html = convert_to_utf8($html, $response['headers']);
                 if ($extractor->process($html, $next_page_url)) {
                     $multi_page_content[] = $extractor->getContent();
                     continue;
                 } else {
                     debug('Failed to extract content');
                 }
             } else {
                 debug('MIME type requires different action');
             }
         } else {
             debug('Failed to fetch URL');
         }
     } else {
         debug('URL already processed');
     }
/**
 * LZH 形式の郵便番号データが更新されていたらダウンロードして所定のフォーマットに変換する。
 */
function capture($page, $url, $name, $utf8)
{
    if (!check($page, "{$name}_html_hash")) {
        return false;
    }
    if (!check($url, "{$name}_lzh_hash")) {
        return false;
    }
    if (!download($url, "{$name}.lzh")) {
        return false;
    }
    if (!extract_lzh("{$name}.lzh", "{$name}.csv")) {
        return false;
    }
    if (!convert_to_utf8("{$name}.csv", $utf8)) {
        return false;
    }
    return true;
}