From 1cfe5afa8ed5f189fdf6e4f12426f6c1dac01e2d Mon Sep 17 00:00:00 2001 From: mikelittle Date: Mon, 21 Apr 2003 21:37:11 +0000 Subject: [PATCH] Populating missing files from this 'branch'. git-svn-id: http://svn.automattic.com/wordpress/trunk@8 1a063a9b-81f0-0310-95a4-ce76da25c4cd --- b2-include/b2.css | 99 +++ b2-include/b2edit.form.php | 148 ++++ b2-include/b2edit.showposts.php | 380 ++++++++ b2-include/b2footer.php | 23 + b2-include/b2functions.php | 1264 +++++++++++++++++++++++++++ b2-include/b2menutop.php | 67 ++ b2-include/b2menutop.txt | 14 + b2-include/b2quicktags.js | 190 ++++ b2-include/b2quicktags.php | 33 + b2-include/b2template.functions.php | 1219 ++++++++++++++++++++++++++ b2-include/b2vars.php | 276 ++++++ b2-include/b2verifauth.php | 55 ++ b2-include/class.POP3.php | 680 ++++++++++++++ b2-include/xmlrpc.inc | 1149 ++++++++++++++++++++++++ b2-include/xmlrpcs.inc | 309 +++++++ 15 files changed, 5906 insertions(+) create mode 100644 b2-include/b2.css create mode 100644 b2-include/b2edit.form.php create mode 100644 b2-include/b2edit.showposts.php create mode 100644 b2-include/b2footer.php create mode 100644 b2-include/b2functions.php create mode 100644 b2-include/b2menutop.php create mode 100644 b2-include/b2menutop.txt create mode 100644 b2-include/b2quicktags.js create mode 100644 b2-include/b2quicktags.php create mode 100644 b2-include/b2template.functions.php create mode 100644 b2-include/b2vars.php create mode 100644 b2-include/b2verifauth.php create mode 100644 b2-include/class.POP3.php create mode 100644 b2-include/xmlrpc.inc create mode 100644 b2-include/xmlrpcs.inc diff --git a/b2-include/b2.css b/b2-include/b2.css new file mode 100644 index 0000000000..23e8993dfb --- /dev/null +++ b/b2-include/b2.css @@ -0,0 +1,99 @@ +body { + margin-top: 0px; + margin-left: 0px; + margin-right: 0px; + margin-bottom: 0px; + background-color: #FFFFFF} +body, td { + color: #000000; + font-family: Verdana, Geneva, Arial, Helvetica; + font-size: 10pt; +} +a { + background-color: transparent; + color: #0000FF; + text-decoration: none; + font-weight: bold; +} +a:hover { + color: #FF3300; + text-decoration: underline; + font-weight: bold; +} + +.panelbody { + /* empty style - for you to customize it. + this style applies to b2's interface, the part where the sections are displayed */ +} +.table { + color: #000000; + font-family: Verdana, Geneva, Arial, Helvetica; + font-size: 10pt; +} +.tabletoprow { + background-color: #ffffff; + color: #000000; + font-family: Verdana, Geneva, Arial, Helvetica; + font-size: 12px; + font-style: italic; +} +.search { + font-family: Arial, Helvetica, sans-serif; + font-size: 12px; + color: #000066; + background-color: #ffeecc; + background-image: url("../b2-img/b2button.gif"); +} +.quicktags { + font-family: Arial, Helvetica, sans-serif; + font-size: 12px; + color: #000000; + background-color: #cccccc; + background-image: url("../b2-img/b2button2.gif"); +} + +.menutop { + color: #999999; + font-family: Verdana, Geneva, Arial, Helvetica; + font-size: 10px; + background-color: #DDEEFF; +} +a.menutop { + background-color: transparent; + color: #3366CC; + font-weight: normal; + border-width: 0px; +} +a.menutop:hover { + color: #FF9900; + text-decoration: underline; + font-weight: normal; +} + +.menutoptitle { + font-family: Arial, Verdana, Geneva, Arial, Helvetica; + color: #BBCCDD; + font-size: 14px; + font-weight: bold; + } + +.b2menutop { + color: #333333; + font-family: Verdana, Geneva, Arial, Helvetica; + font-size: 10px; +} +a.b2menutop { + background-color: transparent; + color: #0066ff; + font-weight: lighter; +} +a.b2menutop:hover { + color: #ff9900; + font-weight: bold; + text-decoration: none; +} +xmp { /* Just in case */ + font-family: Verdana, Geneva, Arial, Helvetica; + font-size: 10pt; +} +form { margin: 0; padding: 0; } /* thanks #mozilla */ \ No newline at end of file diff --git a/b2-include/b2edit.form.php b/b2-include/b2edit.form.php new file mode 100644 index 0000000000..8f024f8855 --- /dev/null +++ b/b2-include/b2edit.form.php @@ -0,0 +1,148 @@ +
'; + } else { + $form_pingback = ''; + } + if ($use_trackback) { + $form_trackback = '


'; + } else { + $form_trackback = ''; + } + $colspan = 3; + break; + case "edit": + $submitbutton_text ="Edit this !"; + $toprow_title = "Editing Post #".$postdata["ID"]; + $form_action = "editpost"; + $form_extra = "\" />\n\n\n + +
+ + + + + + > +
+ + +
+
+ +
+
+
+ colspan="2">  + + + + +
+ " tabindex="1" id="name" /> + +
+ " tabindex="2" id="email" /> + +
+ " tabindex="3" id="URL" /> + + + + + + + + +
+Post :'; +} else { + echo '
'; +} +?> +
+ +
+ +
+ + tabindex="7" id="autobr" />
+ + + + + + + + + + + + + + += $fileupload_minlevel) && ((ereg(" ".$user_login." ", $fileupload_allowedusers)) || (trim($fileupload_allowedusers)=="")) ) { ?> + + 4) && ($action != "post")) +if ($user_level > 4) { + touch_time(($action=="edit")); +} +?> + + + + + +
\ No newline at end of file diff --git a/b2-include/b2edit.showposts.php b/b2-include/b2edit.showposts.php new file mode 100644 index 0000000000..7f3bcbe2cb --- /dev/null +++ b/b2-include/b2edit.showposts.php @@ -0,0 +1,380 @@ + + + + + + + + + + + + +
+Show posts: + + + +
+
0) { +?> + + +
+ + +
+
+
+
+ +  +
+
+
+ to   
+
+ + +
+ + + + + + + +
+
+ + + +
+
+
+ + +
+
+
+ "; + $arc_sql="SELECT DISTINCT YEAR(post_date), MONTH(post_date) FROM $tableposts ORDER BY post_date DESC"; + $querycount++; + $arc_result=mysql_query($arc_sql) or die($arc_sql."
".mysql_error()); + while($arc_row = mysql_fetch_array($arc_result)) { + $arc_year = $arc_row["YEAR(post_date)"]; + $arc_month = $arc_row["MONTH(post_date)"]; + echo "\n"; + } + } elseif ($archive_mode == "daily") { + echo ""; + if (!isset($start_of_week)) { + $start_of_week = 1; + } + $archive_week_start_date_format = "Y/m/d"; + $archive_week_end_date_format = "Y/m/d"; + $archive_week_separator = " - "; + $arc_sql="SELECT DISTINCT YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date), WEEK(post_date) FROM $tableposts ORDER BY post_date DESC"; + $querycount++; + $arc_result=mysql_query($arc_sql) or die($arc_sql."
".mysql_error()); + $arc_w_last = ''; + while($arc_row = mysql_fetch_array($arc_result)) { + $arc_year = $arc_row["YEAR(post_date)"]; + $arc_w = $arc_row["WEEK(post_date)"]; + if ($arc_w != $arc_w_last) { + $arc_w_last = $arc_w; + $arc_ymd = $arc_year."-".zeroise($arc_row["MONTH(post_date)"],2)."-" .zeroise($arc_row["DAYOFMONTH(post_date)"],2); + $arc_week = get_weekstartend($arc_ymd, $start_of_week); + $arc_week_start = date($archive_week_start_date_format, $arc_week['start']); + $arc_week_end = date($archive_week_end_date_format, $arc_week['end']); + echo "\n"; + } + } + } elseif ($archive_mode == "postbypost") { + echo ''; + echo '"; + ?> + +
+
+
+ + + + + + + +
+

+ [ + $authordata[13]) or ($user_login == $authordata[1])) { + echo " - Edit"; + echo " - post_title."\'\\n \'Cancel\' to stop, \'OK\' to delete.')\">Delete "; + } + ?> + ] +
+ by (), in
+ + "; + the_content(); + if ($safe_mode) + echo ""; + ?> +

+ + + +

:: comments

+ + comment_ID); + ?> + + +

+ ( / ) (IP: ) +
+ +
+ @
+ $authordata[13]) or ($user_login == $authordata[1])) { + echo "[ Edit"; + echo " - Delete ]"; + } + ?> +

+ + + + Error: please fill the required fields (name & comment)

"; + ?> + +

:: leave a comment

+ + + + +
+ + " /> +
+
+
+
+ Auto-BR (line-breaks become <br> tags)
+ + +
+ + + + + + +
+
+ +
+ + + + + + + + + + + +
+Show posts: + + + +
+
-1) { +?> + + +
+ + +
+
+
+
+ +  +
+
+
+ to   
+
+ \ No newline at end of file diff --git a/b2-include/b2footer.php b/b2-include/b2footer.php new file mode 100644 index 0000000000..d6822c4088 --- /dev/null +++ b/b2-include/b2footer.php @@ -0,0 +1,23 @@ + + +$querycount queries - ".number_format(timer_stop(),3)." seconds"; +} +?> +

 

+
b2 - ©2001-2002 michel v - tidakada.com
+ + +
+ + + + + + + +
+ + + \ No newline at end of file diff --git a/b2-include/b2functions.php b/b2-include/b2functions.php new file mode 100644 index 0000000000..7ed9204ba1 --- /dev/null +++ b/b2-include/b2functions.php @@ -0,0 +1,1264 @@ +".mysql_error()); + $connexionbase = mysql_select_db("$base") or die("Can't connect to the database $base. MySQL said:
".mysql_error()); + return(($connexion && $connexionbase)); +} + + +function mysql_oops($query) { + $error = '

Oops, MySQL error!

Your query:
'.$query; + $error .= '

MySQL said:
'.mysql_error().'

'; + die($error); +} + + +/***** Formatting functions *****/ + +function autobrize($content) { + $content = preg_replace("/
\n/", "\n", $content); + $content = preg_replace("/
\n/", "\n", $content); + $content = preg_replace("/(\015\012)|(\015)|(\012)/", "
\n", $content); + return($content); + } +function unautobrize($content) { + $content = preg_replace("/
\n/", "\n", $content); //for PHP versions before 4.0.5 + $content = preg_replace("/
\n/", "\n", $content); + return($content); + } + + +function format_to_edit($content) { + global $autobr; + $content = stripslashes($content); + if ($autobr) { $content = unautobrize($content); } + $content = htmlspecialchars($content); + return($content); + } +function format_to_post($content) { + global $post_autobr,$comment_autobr; + $content = addslashes($content); + if ($post_autobr || $comment_autobr) { $content = autobrize($content); } + return($content); + } + + +function zeroise($number,$threshold) { // function to add leading zeros when necessary + $l=strlen($number); + if ($l<$threshold) + for ($i=0; $i<($threshold-$l); $i=$i+1) { $number='0'.$number; } + return($number); + } + + +function backslashit($string) { + $string = preg_replace('/([a-z])/i', '\\\\\1', $string); + return $string; +} + + +function mysql2date($dateformatstring, $mysqlstring, $use_b2configmonthsdays = 1) { + global $month, $weekday; + $m = $mysqlstring; + if (empty($m)) { + return false; + } + $i = mktime(substr($m,11,2),substr($m,14,2),substr($m,17,2),substr($m,5,2),substr($m,8,2),substr($m,0,4)); + if (!empty($month) && !empty($weekday) && $use_b2configmonthsdays) { + $datemonth = $month[date('m', $i)]; + $dateweekday = $weekday[date('w', $i)]; + $dateformatstring = ' '.$dateformatstring; + $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit(substr($dateweekday, 0, 3)), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit(substr($datemonth, 0, 3)), $dateformatstring); + $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1); + } + $j = @date($dateformatstring, $i); + if (!$j) { +# // for debug purposes +# echo $i." ".$mysqlstring; + } + return $j; +} + +function addslashes_gpc($gpc) { + if (!get_magic_quotes_gpc()) { + $gpc = addslashes($gpc); + } + return($gpc); +} + +function date_i18n($dateformatstring, $unixtimestamp) { + global $month, $weekday; + $i = $unixtimestamp; + if ((!empty($month)) && (!empty($weekday))) { + $datemonth = $month[date('m', $i)]; + $dateweekday = $weekday[date('w', $i)]; + $dateformatstring = ' '.$dateformatstring; + $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit(substr($dateweekday, 0, 3)), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit(substr($datemonth, 0, 3)), $dateformatstring); + $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1); + } + $j = @date($dateformatstring, $i); + return $j; + } + + + +function get_weekstartend($mysqlstring, $start_of_week) { + $my = substr($mysqlstring,0,4); + $mm = substr($mysqlstring,8,2); + $md = substr($mysqlstring,5,2); + $day = mktime(0,0,0, $md, $mm, $my); + $weekday = date('w',$day); + $i = 86400; + while ($weekday > $start_of_week) { + $weekday = date('w',$day); + $day = $day - 86400; + $i = 0; + } + $week['start'] = $day + 86400 - $i; + $week['end'] = $day + 691199; + return ($week); +} + +function convert_chars($content,$flag="html") { // html/unicode entities output, defaults to html + $newcontent = ""; + + global $convert_chars2unicode, $convert_entities2unicode, $leavecodealone, $use_htmltrans; + global $b2_htmltrans, $b2_htmltranswinuni; + + ### this is temporary - will be replaced by proper config stuff + $convert_chars2unicode = 1; + if (($leavecodealone) || (!$use_htmltrans)) { + $convert_chars2unicode = 0; + } + ### + + + // converts HTML-entities to their display values in order to convert them again later + + $content = preg_replace("/(.+?)<\/title>/","",$content); + $content = preg_replace("/<category>(.+?)<\/category>/","",$content); + +# $content = str_replace("&","&",$content); + $content = strtr($content, $b2_htmltrans); + + for ($i=0; $i<strlen($content); $i=$i+1) { + $j = substr($content,$i,1); + $jnext = substr($content,$i+1,1); + $jord = ord($j); + if ($convert_chars2unicode) { + switch($flag) { + case "unicode": + // $j = str_replace("&","&",$j); + if (($jord>=128) || ($j == "&") || (($jord>=128) && ($jord<=159))) { + $j = "&#".$jord.";"; + } + break; + case "html": + if (($jord>=128) || (($jord>=128) && ($jord<=159))) { + $j = "&#".$jord.";"; // $j = htmlentities($j); + } elseif (($j == "&") && ($jnext != "#")) { + $j = "&"; + } + break; + case "xml": + if ($jord>=128) { + $j = "&#".$jord.";"; // $j = htmlentities($j); + // $j = htmlentities($j); + } elseif (($j == "&") && ($jnext != "#")) { + $j = "&"; + } + break; + } + } + + $newcontent .= $j; + } + + // now converting: Windows CP1252 => Unicode (valid HTML) + // (if you've ever pasted text from MSWord, you'll understand) + + $newcontent = strtr($newcontent, $b2_htmltranswinuni); + + // you can delete these 2 lines if you don't like <br /> and <hr /> + $newcontent = str_replace("<br>","<br />",$newcontent); + $newcontent = str_replace("<hr>","<hr />",$newcontent); + + return($newcontent); +} + +function convert_bbcode($content) { + global $b2_bbcode, $use_bbcode; + if ($use_bbcode) { + $content = preg_replace($b2_bbcode["in"], $b2_bbcode["out"], $content); + } + $content = convert_bbcode_email($content); + return ($content); +} + +function convert_bbcode_email($content) { + global $use_bbcode; + $bbcode_email["in"] = array( + '#\[email](.+?)\[/email]#eis', + '#\[email=(.+?)](.+?)\[/email]#eis' + ); + $bbcode_email["out"] = array( + "'<a href=\"mailto:'.antispambot('\\1').'\">'.antispambot('\\1').'</a>'", // E-mail + "'<a href=\"mailto:'.antispambot('\\1').'\">\\2</a>'" + ); + + $content = preg_replace($bbcode_email["in"], $bbcode_email["out"], $content); + return ($content); +} + +function convert_gmcode($content) { + global $b2_gmcode, $use_gmcode; + if ($use_gmcode) { + $content = preg_replace($b2_gmcode["in"], $b2_gmcode["out"], $content); + } + return ($content); +} + +function convert_smilies($content) { + global $smilies_directory, $use_smilies; + global $b2_smiliessearch, $b2_smiliesreplace; + if ($use_smilies) { + $content = str_replace($b2_smiliessearch, $b2_smiliesreplace, $content); + } + return ($content); +} + +function antispambot($emailaddy, $mailto=0) { + $emailNOSPAMaddy = ''; + srand ((float) microtime() * 1000000); + for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) { + $j = floor(rand(0, 1+$mailto)); + if ($j==0) { + $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';'; + } elseif ($j==1) { + $emailNOSPAMaddy .= substr($emailaddy,$i,1); + } elseif ($j==2) { + $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2); + } + } + $emailNOSPAMaddy = str_replace('@','@',$emailNOSPAMaddy); + return $emailNOSPAMaddy; +} + +function make_clickable($text) { // original function: phpBB, extended here for AIM & ICQ + $ret = " " . $text; + $ret = preg_replace("#([\n ])([a-z]+?)://([^, <>{}\n\r]+)#i", "\\1<a href=\"\\2://\\3\" target=\"_blank\">\\2://\\3</a>", $ret); + $ret = preg_replace("#([\n ])aim:([^,< \n\r]+)#i", "\\1<a href=\"aim:goim?screenname=\\2\\3&message=Hello\">\\2\\3</a>", $ret); + $ret = preg_replace("#([\n ])icq:([^,< \n\r]+)#i", "\\1<a href=\"http://wwp.icq.com/scripts/search.dll?to=\\2\\3\">\\2\\3</a>", $ret); + $ret = preg_replace("#([\n ])www\.([a-z0-9\-]+)\.([a-z0-9\-.\~]+)((?:/[^,< \n\r]*)?)#i", "\\1<a href=\"http://www.\\2.\\3\\4\" target=\"_blank\">www.\\2.\\3\\4</a>", $ret); + $ret = preg_replace("#([\n ])([a-z0-9\-_.]+?)@([^,< \n\r]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret); + $ret = substr($ret, 1); + return($ret); +} + + +function is_email($user_email) { + $chars = "/^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}\$/i"; + if(strstr($user_email, '@') && strstr($user_email, '.')) { + if (preg_match($chars, $user_email)) { + return true; + } else { + return false; + } + } else { + return false; + } +} + + +function phpcurlme($string, $language = 'en') { + // by Matt - http://www.photomatt.net/scripts/phpcurlme + + // This should take care of the single quotes + $string = preg_replace("/'([dmst])([ .,?!\)\/<])/i","’$1$2",$string); + $string = preg_replace("/'([lrv])([el])([ .,?!\)\/<])/i","’$1$2$3",$string); + $string = preg_replace("/([^=])(\s+)'([^ >])?(.*?)([^=])'(\s*)([^>&])/S","$1$2‘$3$4$5’$6$7",$string); + + // time for the doubles + $string = preg_replace('/([^=])(\s+)"([^ >])?(.*?)([^=])"(\s*)([^>&])/S',"$1$2“$3$4$5”$6$7",$string); + // multi-paragraph + $string = preg_replace('/<p>"(.*)<\/p>/U',"<p>“$1</p>",$string); + + // not a quote, but whatever + $string = str_replace('---','—',$string); + $string = str_replace('--','–',$string); + return $string; +} + + +function strip_all_but_one_link($text, $mylink) { + $match_link = '#(<a.+?href.+?'.'>)(.+?)(</a>)#'; + preg_match_all($match_link, $text, $matches); + $count = count($matches[0]); + for ($i=0; $i<$count; $i++) { + if (!strstr($matches[0][$i], $mylink)) { + $text = str_replace($matches[0][$i], $matches[2][$i], $text); + } + } + return $text; +} + + +/***** // Formatting functions *****/ + + + +function get_lastpostdate() { + global $tableposts, $cache_lastpostdate, $use_cache, $time_difference, $pagenow; + if ((!isset($cache_lastpostdate)) OR (!$use_cache)) { + $now = date("Y-m-d H:i:s",(time() + ($time_difference * 3600))); + if ($pagenow != 'b2edit.php') { + $showcatzero = 'post_category > 0 AND'; + } else { + $showcatzero = ''; + } + $sql = "SELECT * FROM $tableposts WHERE $showcatzero post_date <= '$now' ORDER BY post_date DESC LIMIT 1"; + $result = mysql_query($sql) or die("Your SQL query: <br />$sql<br /><br />MySQL said:<br />".mysql_error()); + $querycount++; + $myrow = mysql_fetch_object($result); + $lastpostdate = $myrow->post_date; + $cache_lastpostdate = $lastpostdate; +// echo $lastpostdate; + } else { + $lastpostdate = $cache_lastpostdate; + } + return($lastpostdate); +} + +function user_pass_ok($user_login,$user_pass) { + global $cache_userdata,$use_cache; + if ((empty($cache_userdata[$user_login])) OR (!$use_cache)) { + $userdata = get_userdatabylogin($user_login); + } else { + $userdata = $cache_userdata[$user_login]; + } + return ($user_pass == $userdata['user_pass']); +} + +function get_userdata($userid) { + global $tableusers,$querycount,$cache_userdata,$use_cache; + if ((empty($cache_userdata[$userid])) OR (!$use_cache)) { + $sql = "SELECT * FROM $tableusers WHERE ID = '$userid'"; + $result = mysql_query($sql) or die("Your SQL query: <br />$sql<br /><br />MySQL said:<br />".mysql_error()); + $myrow = mysql_fetch_array($result); + $querycount++; + $cache_userdata[$userid] = $myrow; + } else { + $myrow = $cache_userdata[$userid]; + } + return($myrow); +} + +function get_userdata2($userid) { // for team-listing + global $tableusers,$row; + $user_data['ID'] = $userid; + $user_data['user_login'] = $row->user_login; + $user_data['user_firstname'] = $row->user_firstname; + $user_data['user_lastname'] = $row->user_lastname; + $user_data['user_nickname'] = $row->user_nickname; + $user_data['user_level'] = $row->user_level; + $user_data['user_email'] = $row->user_email; + $user_data['user_url'] = $row->user_url; + return($user_data); +} + +function get_userdatabylogin($user_login) { + global $tableusers,$querycount,$cache_userdata,$use_cache; + if ((empty($cache_userdata["$user_login"])) OR (!$use_cache)) { + $sql = "SELECT * FROM $tableusers WHERE user_login = '$user_login'"; + $result = mysql_query($sql) or die("Your SQL query: <br />$sql<br /><br />MySQL said:<br />".mysql_error()); + if (!$result) die($sql."<br /><br />".mysql_error()); + $myrow = mysql_fetch_array($result); + $querycount++; + $cache_userdata["$user_login"] = $myrow; + } else { + $myrow = $cache_userdata["$user_login"]; + } + return($myrow); +} + +function get_userid($user_login) { + global $tableusers,$querycount,$cache_userdata,$use_cache; + if ((empty($cache_userdata["$user_login"])) OR (!$use_cache)) { + $sql = "SELECT ID FROM $tableusers WHERE user_login = '$user_login'"; + $result = mysql_query($sql) or die("No user with the login <i>$user_login</i>"); + $myrow = mysql_fetch_array($result); + $querycount++; + $cache_userdata["$user_login"] = $myrow; + } else { + $myrow = $cache_userdata["$user_login"]; + } + return($myrow[0]); +} + +function get_usernumposts($userid) { + global $tableusers,$tablesettings,$tablecategories,$tableposts,$tablecomments,$querycount; + $sql = "SELECT * FROM $tableposts WHERE post_author = $userid"; + $result = mysql_query($sql) or die("Your SQL query: <br />$sql<br /><br />MySQL said:<br />".mysql_error()); + $querycount++; + return mysql_num_rows($result); +} + +function get_settings($setting) { + global $tablesettings,$querycount,$cache_settings,$use_cache; + if ((empty($cache_settings)) OR (!$use_cache)) { + $sql = "SELECT * FROM $tablesettings"; + $result = mysql_query($sql) or die("Your SQL query: <br />$sql<br /><br />MySQL said:<br />".mysql_error()); + $querycount++; + $myrow = mysql_fetch_object($result); + $cache_settings = $myrow; + } else { + $myrow = $cache_settings; + } + return($myrow->$setting); +} + +function get_postdata($postid) { + global $tableusers,$tablesettings,$tablecategories,$tableposts,$tablecomments,$querycount; + $sql = "SELECT * FROM $tableposts WHERE ID = $postid"; + $result = mysql_query($sql) or die("Your SQL query: <br />$sql<br /><br />MySQL said:<br />".mysql_error()); + $querycount++; + if (mysql_num_rows($result)) { + $myrow = mysql_fetch_object($result); + $postdata = array ( + 'ID' => $myrow->ID, + 'Author_ID' => $myrow->post_author, + 'Date' => $myrow->post_date, + 'Content' => $myrow->post_content, + 'Title' => $myrow->post_title, + 'Category' => $myrow->post_category, + ); + return($postdata); + } else { + return false; + } +} + +function get_postdata2($postid=0) { // less flexible, but saves mysql queries + global $row; + $postdata = array ( + 'ID' => $row->ID, + 'Author_ID' => $row->post_author, + 'Date' => $row->post_date, + 'Content' => $row->post_content, + 'Title' => $row->post_title, + 'Category' => $row->post_category, +# 'Notify' => $row->post_notifycomments, +# 'Clickable' => $row->post_make_clickable, + 'Karma' => $row->post_karma // this isn't used yet + ); + return($postdata); +} + +function get_commentdata($comment_ID,$no_cache=0) { // less flexible, but saves mysql queries + global $rowc,$id,$commentdata,$tablecomments,$querycount; + if ($no_cache) { + $query="SELECT * FROM $tablecomments WHERE comment_ID = $comment_ID"; + $result=mysql_query($query); + $querycount++; + $myrow = mysql_fetch_array($result); + } else { + $myrow['comment_ID']=$rowc->comment_ID; + $myrow['comment_post_ID']=$rowc->comment_post_ID; + $myrow['comment_author']=$rowc->comment_author; + $myrow['comment_author_email']=$rowc->comment_author_email; + $myrow['comment_author_url']=$rowc->comment_author_url; + $myrow['comment_author_IP']=$rowc->comment_author_IP; + $myrow['comment_date']=$rowc->comment_date; + $myrow['comment_content']=$rowc->comment_content; + $myrow['comment_karma']=$rowc->comment_karma; + if (strstr($myrow['comment_content'], '<trackback />')) { + $myrow['comment_type'] = 'trackback'; + } elseif (strstr($myrow['comment_content'], '<pingback />')) { + $myrow['comment_type'] = 'pingback'; + } else { + $myrow['comment_type'] = 'comment'; + } + } + return($myrow); +} + +function get_catname($cat_ID) { + global $tablecategories,$cache_catnames,$use_cache,$querycount; + if ((!$cache_catnames) || (!$use_cache)) { + $sql = "SELECT * FROM $tablecategories"; + $result = mysql_query($sql) or die('Oops, couldn\'t query the db for categories.'); + $querycount; + while ($row = mysql_fetch_object($result)) { + $cache_catnames[$row->cat_ID] = $row->cat_name; + } + } + $cat_name = $cache_catnames[$cat_ID]; + return($cat_name); +} + +function profile($user_login) { + global $user_data; + echo "<a href=\"#\" OnClick=\"javascript:window.open('b2profile.php?user=".$user_data["user_login"]."','Profile','toolbar=0,status=1,location=0,directories=0,menuBar=1,scrollbars=1,resizable=0,width=480,height=320,left=100,top=100');\">$user_login</a>"; +} + +function dropdown_categories($blog_ID=1) { + global $postdata,$tablecategories,$mode,$querycount; + $query="SELECT * FROM $tablecategories"; + $result=mysql_query($query); + $querycount++; + $width = ($mode=="sidebar") ? "100%" : "170px"; + echo '<select name="post_category" style="width:'.$width.';" tabindex="2" id="category">'; + while($row = mysql_fetch_object($result)) { + echo "<option value=\"".$row->cat_ID."\""; + if ($row->cat_ID == $postdata["Category"]) + echo " selected"; + echo ">".$row->cat_name."</option>"; + } + echo "</select>"; +} + +function touch_time($edit=1) { + global $month, $postdata, $time_difference; + echo $postdata['Date']; + echo '<br /><br /><input type="checkbox" class="checkbox" name="edit_date" value="1" id="timestamp" /><label for="timestamp"> Edit timestamp</label><br />'; + + $time_adj = time() + ($time_difference * 3600); + $jj = ($edit) ? mysql2date('d', $postdata['Date']) : date('d', $time_adj); + $mm = ($edit) ? mysql2date('m', $postdata['Date']) : date('m', $time_adj); + $aa = ($edit) ? mysql2date('Y', $postdata['Date']) : date('Y', $time_adj); + $hh = ($edit) ? mysql2date('H', $postdata['Date']) : date('H', $time_adj); + $mn = ($edit) ? mysql2date('i', $postdata['Date']) : date('i', $time_adj); + $ss = ($edit) ? mysql2date('s', $postdata['Date']) : date('s', $time_adj); + + echo '<input type="text" name="jj" value="'.$jj.'" size="2" maxlength="2" />'."\n"; + echo "<select name=\"mm\">\n"; + for ($i=1; $i < 13; $i=$i+1) { + echo "\t\t\t<option value=\"$i\""; + if ($i == $mm) + echo " selected"; + if ($i < 10) { + $ii = "0".$i; + } else { + $ii = "$i"; + } + echo ">".$month["$ii"]."</option>\n"; + } ?> +</select> +<input type="text" name="aa" value="<?php echo $aa ?>" size="4" maxlength="5" /> @ +<input type="text" name="hh" value="<?php echo $hh ?>" size="2" maxlength="2" /> : +<input type="text" name="mn" value="<?php echo $mn ?>" size="2" maxlength="2" /> : +<input type="text" name="ss" value="<?php echo $ss ?>" size="2" maxlength="2" /> + <?php +} + +function gzip_compression() { + global $gzip_compressed; + if (!$gzip_compressed) { + $phpver = phpversion(); //start gzip compression + if($phpver >= "4.0.4pl1") { + if(extension_loaded("zlib")) { ob_start("ob_gzhandler"); } + } else if($phpver > "4.0") { + if(strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip')) { + if(extension_loaded("zlib")) { $do_gzip_compress = TRUE; ob_start(); ob_implicit_flush(0); header("Content-Encoding: gzip"); } + } + } //end gzip compression - that piece of script courtesy of the phpBB dev team + $gzip_compressed=1; + } +} + +function alert_error($msg) { // displays a warning box with an error message (original by KYank) + global $$HTTP_SERVER_VARS; + ?> + <html> + <head> + <script language="JavaScript"> + <!-- + alert("<?php echo $msg ?>"); + history.back(); + //--> + </script> + </head> + <body> + <!-- this is for non-JS browsers (actually we should never reach that code, but hey, just in case...) --> + <?php echo $msg; ?><br /> + <a href="<?php echo $HTTP_SERVER_VARS["HTTP_REFERER"]; ?>">go back</a> + </body> + </html> + <?php + exit; +} + +function alert_confirm($msg) { // asks a question - if the user clicks Cancel then it brings them back one page + ?> + <script language="JavaScript"> + <!-- + if (!confirm("<?php echo $msg ?>")) { + history.back(); + } + //--> + </script> + <?php +} + +function redirect_js($url,$title="...") { + ?> + <script language="JavaScript"> + <!-- + function redirect() { + window.location = "<?php echo $url; ?>"; + } + setTimeout("redirect();", 100); + //--> + </script> + <p>Redirecting you : <b><?php echo $title; ?></b><br /> + <br /> + If nothing happens, click <a href="<?php echo $url; ?>">here</a>.</p> + <?php + exit(); +} + +// functions to count the page generation time (from phpBB2) +// ( or just any time between timer_start() and timer_stop() ) + + function timer_start() { + global $timestart; + $mtime = microtime(); + $mtime = explode(" ",$mtime); + $mtime = $mtime[1] + $mtime[0]; + $timestart = $mtime; + return true; + } + + function timer_stop($display=0,$precision=3) { //if called like timer_stop(1), will echo $timetotal + global $timestart,$timeend; + $mtime = microtime(); + $mtime = explode(" ",$mtime); + $mtime = $mtime[1] + $mtime[0]; + $timeend = $mtime; + $timetotal = $timeend-$timestart; + if ($display) + echo number_format($timetotal,$precision); + return($timetotal); + } + + +// pings Weblogs.com +function pingWeblogs($blog_ID = 1) { + // original function by Dries Buytaert for Drupal + global $use_weblogsping, $blogname,$siteurl,$blogfilename; + if ((!(($blogname=="my weblog") && ($siteurl=="http://example.com") && ($blogfilename=="b2.php"))) && (!preg_match("/localhost\//",$siteurl)) && ($use_weblogsping)) { + $client = new xmlrpc_client("/RPC2", "rpc.weblogs.com", 80); + $message = new xmlrpcmsg("weblogUpdates.ping", array(new xmlrpcval($blogname), new xmlrpcval($siteurl."/".$blogfilename))); + $result = $client->send($message); + if (!$result || $result->faultCode()) { + return(false); + } + return(true); + } else { + return(false); + } +} + +// pings Weblogs.com/rssUpdates +function pingWeblogsRss($blog_ID = 1, $rss_url) { + global $use_weblogsrssping, $blogname, $rss_url; + if ($blogname != 'my weblog' && $rss_url != 'http://example.com/b2rdf.php' && $use_weblogsrssping) { + $client = new xmlrpc_client('/RPC2', 'rssrpc.weblogs.com', 80); + $message = new xmlrpcmsg('rssUpdate', array(new xmlrpcval($blogname), new xmlrpcval($rss_url))); + $result = $client->send($message); + if (!$result || $result->faultCode()) { + return(false); + } + return(true); + } else { + return(false); + } +} + +// pings CaféLog.com +function pingCafelog($cafelogID,$title='',$p='') { + global $use_cafelogping, $blogname, $siteurl, $blogfilename; + if ((!(($blogname=="my weblog") && ($siteurl=="http://example.com") && ($blogfilename=="b2.php"))) && (!preg_match("/localhost\//",$siteurl)) && ($use_cafelogping) && ($cafelogID != '')) { + $client = new xmlrpc_client("/xmlrpc.php", "cafelog.tidakada.com", 80); + $message = new xmlrpcmsg("b2.ping", array(new xmlrpcval($cafelogID), new xmlrpcval($title), new xmlrpcval($p))); + $result = $client->send($message); + if (!$result || $result->faultCode()) { + return(false); + } + return(true); + } else { + return(false); + } +} + +// pings Blo.gs +function pingBlogs($blog_ID="1") { + global $use_blodotgsping, $blodotgsping_url, $use_rss, $blogname, $siteurl, $blogfilename; + if ((!(($blogname=='my weblog') && ($siteurl=='http://example.com') && ($blogfilename=='b2.php'))) && (!preg_match('/localhost\//',$siteurl)) && ($use_blodotgsping)) { + $url = ($blodotgsping_url == 'http://example.com') ? $siteurl.'/'.$blogfilename : $blodotgsping_url; + $client = new xmlrpc_client('/', 'ping.blo.gs', 80); + if ($use_rss) { + $message = new xmlrpcmsg('weblogUpdates.extendedPing', array(new xmlrpcval($blogname), new xmlrpcval($url), new xmlrpcval($url), new xmlrpcval($siteurl.'/b2rss.xml'))); + } else { + $message = new xmlrpcmsg('weblogUpdates.ping', array(new xmlrpcval($blogname), new xmlrpcval($url))); + } + $result = $client->send($message); + if (!$result || $result->faultCode()) { + return(false); + } + return(true); + } else { + return(false); + } +} + + +// trackback - send +function trackback($trackback_url, $title, $excerpt, $ID) { + global $siteurl, $blogfilename, $blogname; + global $querystring_start, $querystring_equal; + $title = urlencode($title); + $excerpt = urlencode(stripslashes($excerpt)); + $blog_name = urlencode($blogname); + $url = urlencode($siteurl.'/'.$blogfilename.$querystring_start.'p'.$querystring_equal.$ID); + $query_string = "title=$title&url=$url&blog_name=$blog_name&excerpt=$excerpt"; + if (strstr($trackback_url, '?')) { + $trackback_url .= "&".$query_string;; + $fp = @fopen($trackback_url, 'r'); + $result = @fread($fp, 4096); + @fclose($fp); +/* debug code + $debug_file = 'trackback.log'; + $fp = fopen($debug_file, 'a'); + fwrite($fp, "\n*****\nTrackback URL query:\n\n$trackback_url\n\nResponse:\n\n"); + fwrite($fp, $result); + fwrite($fp, "\n\n"); + fclose($fp); +*/ + } else { + $trackback_url = parse_url($trackback_url); + $http_request = 'POST '.$trackback_url['path']." HTTP/1.0\r\n"; + $http_request .= 'Host: '.$trackback_url['host']."\r\n"; + $http_request .= 'Content-Type: application/x-www-form-urlencoded'."\r\n"; + $http_request .= 'Content-Length: '.strlen($query_string)."\r\n"; + $http_request .= "\r\n"; + $http_request .= $query_string; + $fs = @fsockopen($trackback_url['host'], 80); + @fputs($fs, $http_request); +/* debug code + $debug_file = 'trackback.log'; + $fp = fopen($debug_file, 'a'); + fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n"); + while(!@feof($fs)) { + fwrite($fp, @fgets($fs, 4096)); + } + fwrite($fp, "\n\n"); + fclose($fp); +*/ + @fclose($fs); + } + return $result; +} + +// trackback - reply +function trackback_response($error = 0, $error_message = '') { + if ($error) { + echo '<?xml version="1.0" encoding="iso-8859-1"?'.">\n"; + echo "<response>\n"; + echo "<error>1</error>\n"; + echo "<message>$error_message</message>\n"; + echo "</response>"; + } else { + echo '<?xml version="1.0" encoding="iso-8859-1"?'.">\n"; + echo "<response>\n"; + echo "<error>0</error>\n"; + echo "</response>"; + } + die(); +} + +// updates the RSS feed ! +function rss_update($blog_ID, $num_posts="", $file="./b2rss.xml") { + + global $use_rss, $b2_version, $querystring_start, $querystring_equal, $querystring_separator; + global $admin_email,$blogname,$siteurl,$blogfilename,$blogdescription,$posts_per_rss,$rss_language; + global $tableposts,$postdata,$row; + + if ($rss_language == '') { + $rss_language = 'en'; + } + + if ($use_rss) { + + $num_posts = ($num_posts=="") ? $posts_per_rss : 5; + + $date_now = gmdate("D, d M Y H:i:s")." GMT"; + + # let's build the rss file + $rss = ''; + + $rss .= '<?xml version="1.0"?'.">\n"; + $rss .= "<!-- generator=\"b2/$b2_version\" -->\n"; + $rss .= "<rss version=\"0.92\">\n"; + $rss .= "\t<channel>\n"; + $rss .= "\t\t<title>".convert_chars(strip_tags(get_bloginfo("name")),"unicode")."\n"; + $rss .= "\t\t".convert_chars(strip_tags(get_bloginfo("url")),"unicode")."\n"; + $rss .= "\t\t".convert_chars(strip_tags(get_bloginfo("description")),"unicode")."\n"; + $rss .= "\t\t$date_now\n"; + $rss .= "\t\thttp://backend.userland.com/rss092\n"; + $rss .= "\t\t$admin_email\n"; + $rss .= "\t\t$admin_email\n"; + $rss .= "\t\t$rss_language\n"; + + $now = date('Y-m-d H:i:s',(time() + ($time_difference * 3600))); + $sql = "SELECT * FROM $tableposts WHERE post_date <= '$now' AND post_category > 0 ORDER BY post_date DESC LIMIT $num_posts"; + $result = mysql_query($sql) or die("Your SQL query:
$sql

MySQL said:
".mysql_error()); + + while($row = mysql_fetch_object($result)) { + + $id = $row->ID; + $postdata=get_postdata2($id); + + $rss .= "\t\t\n"; + $rss .= "\t\t\t".convert_chars(strip_tags(get_the_title()),"unicode")."\n"; + +// we could add some specific RSS here, but not yet. uncomment if you wish, it's functionnal +// $rss .= "\t\t\t".convert_chars(strip_tags(get_the_category()),"unicode")."\n"; + + $content = stripslashes($row->post_content); + $content = explode("",$content); + $content = $content[0]; + $rss .= "\t\t\t".convert_chars(make_url_footnote($content),"unicode")."\n"; + + $rss .= "\t\t\t".htmlentities("$siteurl/$blogfilename".$querystring_start.'p'.$querystring_equal.$row->ID.$querystring_separator.'c'.$querystring_equal.'1')."\n"; + $rss .= "\t\t\n"; + + } + + $rss .= "\t\n"; + $rss .= ""; + + $f=@fopen("$file","w+"); + if ($f) { + @fwrite($f,$rss); + @fclose($f); + + return(true); + } else { + return(false); + } + } else { + return(false); + } +} + +function make_url_footnote($content) { + global $siteurl; + preg_match_all('/(.+?)<\/a>/', $content, $matches); + $j = 0; + for ($i=0; $i(.+?)<\/title>/is', $content, $matchtitle)) { + $post_title = $matchtitle[0]; + $post_title = preg_replace('//si', '', $post_title); + $post_title = preg_replace('/<\/title>/si', '', $post_title); + } else { + $post_title = $post_default_title; + } + return($post_title); +} + +function xmlrpc_getpostcategory($content) { + global $post_default_category; + if (preg_match('/<category>(.+?)<\/category>/is', $content, $matchcat)) { + $post_category = $matchcat[0]; + $post_category = preg_replace('/<category>/si', '', $post_category); + $post_category = preg_replace('/<\/category>/si', '', $post_category); + + } else { + $post_category = $post_default_category; + } + return($post_category); +} + +function xmlrpc_removepostdata($content) { + $content = preg_replace('/<title>(.+?)<\/title>/si', '', $content); + $content = preg_replace('/<category>(.+?)<\/category>/si', '', $content); + $content = trim($content); + return($content); +} + +function debug_fopen($filename, $mode) { + global $debug; + if ($debug == 1) { + $fp = fopen($filename, $mode); + return $fp; + } else { + return false; + } +} + +function debug_fwrite($fp, $string) { + global $debug; + if ($debug == 1) { + fwrite($fp, $string); + } +} + +function debug_fclose($fp) { + global $debug; + if ($debug == 1) { + fclose($fp); + } +} + +function pingback($content, $post_ID) { + // original code by Mort (http://mort.mine.nu:8080) + global $siteurl, $blogfilename, $b2_version; + $log = debug_fopen('./pingback.log', 'a'); + $post_links = array(); + debug_fwrite($log, 'BEGIN '.time()."\n"); + + // Variables + $ltrs = '\w'; + $gunk = '/#~:.?+=&%@!\-'; + $punc = '.:?\-'; + $any = $ltrs.$gunk.$punc; + $pingback_str_dquote = 'rel="pingback"'; + $pingback_str_squote = 'rel=\'pingback\''; + $x_pingback_str = 'x-pingback: '; + $pingback_href_original_pos = 27; + + // Step 1 + // Parsing the post, external links (if any) are stored in the $post_links array + // This regexp comes straigth from phpfreaks.com + // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php + preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp); + + // Debug + debug_fwrite($log, 'Post contents:'); + debug_fwrite($log, $content."\n"); + + // Step 2. + // Walking thru the links array + // first we get rid of links pointing to sites, not to specific files + // Example: + // http://dummy-weblog.org + // http://dummy-weblog.org/ + // http://dummy-weblog.org/post.php + // We don't wanna ping first and second types, even if they have a valid <link/> + + foreach($post_links_temp[0] as $link_test){ + $test = parse_url($link_test); + if (isset($test['query'])) { + $post_links[] = $link_test; + } elseif(($test['path'] != '/') && ($test['path'] != '')) { + $post_links[] = $link_test; + } + } + + foreach ($post_links as $pagelinkedto){ + debug_fwrite($log, 'Processing -- '.$pagelinkedto."\n\n"); + + $bits = parse_url($pagelinkedto); + if (!isset($bits['host'])) { + debug_fwrite($log, 'Couldn\'t find a hostname for '.$pagelinkedto."\n\n"); + continue; + } + $host = $bits['host']; + $path = isset($bits['path']) ? $bits['path'] : ''; + if (isset($bits['query'])) { + $path .= '?'.$bits['query']; + } + if (!$path) { + $path = '/'; + } + $port = isset($bits['port']) ? $bits['port'] : 80; + + // Try to connect to the server at $host + $fp = fsockopen($host, $port, $errno, $errstr, 30); + if (!$fp) { + debug_fwrite($log, 'Couldn\'t open a connection to '.$host."\n\n"); + continue; + } + + // Send the GET request + $request = "GET $path HTTP/1.1\r\nHost: $host\r\nUser-Agent: b2/$b2_version PHP/" . phpversion() . "\r\n\r\n"; + ob_end_flush(); + fputs($fp, $request); + + // Start receiving headers and content + $contents = ''; + $headers = ''; + $gettingHeaders = true; + $found_pingback_server = 0; + while (!feof($fp)) { + $line = fgets($fp, 4096); + if (trim($line) == '') { + $gettingHeaders = false; + } + if (!$gettingHeaders) { + $contents .= trim($line)."\n"; + $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote); + $pingback_link_offset_squote = strpos($contents, $pingback_str_squote); + } else { + $headers .= trim($line)."\n"; + $x_pingback_header_offset = strpos(strtolower($headers), $x_pingback_str); + } + if ($x_pingback_header_offset) { + preg_match('#x-pingback: (.+)#is', $headers, $matches); + $pingback_server_url = trim($matches[1]); + debug_fwrite($log, "Pingback server found from X-Pingback header @ $pingback_server_url\n"); + $found_pingback_server = 1; + break; + } + if ($pingback_link_offset_dquote || $pingback_link_offset_squote) { + $quote = ($pingback_link_offset_dquote) ? '"' : '\''; + $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote; + $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset); + $pingback_href_start = $pingback_href_pos+6; + $pingback_href_end = @strpos($contents, $quote, $pingback_href_start); + $pingback_server_url_len = $pingback_href_end-$pingback_href_start; + $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len); + debug_fwrite($log, "Pingback server found from Pingback <link /> tag @ $pingback_server_url\n"); + $found_pingback_server = 1; + break; + } + } + + if (!$found_pingback_server) { + debug_fwrite($log, "Pingback server not found\n\n*************************\n\n"); + @fclose($fp); + } else { + debug_fwrite($log,"\n\nPingback server data\n"); + + // Assuming there's a "http://" bit, let's get rid of it + $host_clear = substr($pingback_server_url, 7); + + // the trailing slash marks the end of the server name + $host_end = strpos($host_clear, '/'); + + // Another clear cut + $host_len = $host_end-$host_start; + $host = substr($host_clear, 0, $host_len); + debug_fwrite($log, 'host: '.$host."\n"); + + // If we got the server name right, the rest of the string is the server path + $path = substr($host_clear,$host_end); + debug_fwrite($log, 'path: '.$path."\n\n"); + + // Now, the RPC call + $method = 'pingback.ping'; + debug_fwrite($log, 'Page Linked To: '.$pagelinkedto."\n"); + debug_fwrite($log, 'Page Linked From: '); + $pagelinkedfrom = $siteurl.'/'.$blogfilename.'?p='.$post_ID.'&c=1'; + debug_fwrite($log, $pagelinkedfrom."\n"); + + $client = new xmlrpc_client($path, $host, 80); + $message = new xmlrpcmsg($method, array(new xmlrpcval($pagelinkedfrom), new xmlrpcval($pagelinkedto))); + $result = $client->send($message); + if ($result){ + if (!$result->value()){ + debug_fwrite($log, $result->faultCode().' -- '.$result->faultString()); + } else { + $value = xmlrpc_decode($result->value()); + if (is_array($value)) { + $value_arr = ''; + foreach($value as $blah) { + $value_arr .= $blah.' |||| '; + } + debug_fwrite($log, $value_arr); + } else { + debug_fwrite($log, $value); + } + } + } + @fclose($fp); + } + } + + debug_fwrite($log, "\nEND: ".time()."\n****************************\n\r"); + debug_fclose($log); +} + + +/* + balanceTags + + Balances Tags of string using a modified stack. + + @param text Text to be balanced + @return Returns balanced text + @author Leonard Lin (leonard@acm.org) + @version v1.1 + @date November 4, 2001 + @license GPL v2.0 + @notes + @changelog + 1.2 ***TODO*** Make better - change loop condition to $text + 1.1 Fixed handling of append/stack pop order of end text + Added Cleaning Hooks + 1.0 First Version +*/ + +function balanceTags($text, $is_comment = 0) { + global $use_balanceTags; + if ($use_balanceTags == 0) { + return($text); + } + + $tagstack = array(); + $stacksize = 0; + $tagqueue = ''; + $newtext = ''; + + # b2 bug fix for comments - in case you REALLY meant to type '< !--' + $text = str_replace('< !--', '< !--', $text); + + # b2 bug fix for LOVE <3 (and other situations with '<' before a number) + $text = preg_replace('#<([0-9]{1})#', '<$1', $text); + + + while (preg_match("/<(\/?\w*)\s*([^>]*)>/",$text,$regex)) { + $newtext = $newtext . $tagqueue; + + $i = strpos($text,$regex[0]); + $l = strlen($tagqueue) + strlen($regex[0]); + + // clear the shifter + $tagqueue = ''; + + // Pop or Push + if ($regex[1][0] == "/") { // End Tag + $tag = strtolower(substr($regex[1],1)); + + // if too many closing tags + if($stacksize <= 0) { + $tag = ''; + //or close to be safe $tag = '/' . $tag; + } + // if stacktop value = tag close value then pop + else if ($tagstack[$stacksize - 1] == $tag) { // found closing tag + $tag = '</' . $tag . '>'; // Close Tag + // Pop + array_pop ($tagstack); + $stacksize--; + } else { // closing tag not at top, search for it + for ($j=$stacksize-1;$j>=0;$j--) { + if ($tagstack[$j] == $tag) { + // add tag to tagqueue + for ($k=$stacksize-1;$k>=$j;$k--){ + $tagqueue .= '</' . array_pop ($tagstack) . '>'; + $stacksize--; + } + break; + } + } + $tag = ''; + } + } else { // Begin Tag + $tag = strtolower($regex[1]); + + // Tag Cleaning + + // Push if not img or br or hr + if($tag != 'br' && $tag != 'img' && $tag != 'hr') { + $stacksize = array_push ($tagstack, $tag); + } + + // Attributes + // $attributes = $regex[2]; + $attributes = $regex[2]; + if($attributes) { + // fix to avoid CSS defacements + if ($is_comment) { + $attributes = str_replace('style=', 'title=', $attributes); + $attributes = str_replace('class=', 'title=', $attributes); + $attributes = str_replace('id=', 'title=', $attributes); + } + $attributes = ' '.$attributes; + } + + $tag = '<'.$tag.$attributes.'>'; + } + + $newtext .= substr($text,0,$i) . $tag; + $text = substr($text,$i+$l); + } + + // Clear Tag Queue + $newtext = $newtext . $tagqueue; + + // Add Remaining text + $newtext .= $text; + + // Empty Stack + while($x = array_pop($tagstack)) { + $newtext = $newtext . '</' . $x . '>'; // Add remaining tags to close + } + + # b2 fix for the bug with HTML comments + $newtext = str_replace("< !--","<!--",$newtext); + $newtext = str_replace("< !--","< !--",$newtext); + + return $newtext; +} + +?> \ No newline at end of file diff --git a/b2-include/b2menutop.php b/b2-include/b2menutop.php new file mode 100644 index 0000000000..8771d93f5a --- /dev/null +++ b/b2-include/b2menutop.php @@ -0,0 +1,67 @@ +<img src="b2-img/blank.gif" width="1" height="5" alt="" border="0" /> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr height="15"> + +<td height="15" width="20"><img src="b2-img/blank.gif" width="1" height="1" alt="" /></td> + +<td rowspan="3" width="50" valign="top"><a href="http://cafelog.com/"><img src="b2-img/b2minilogo.png" width="50" height="50" border="0" alt="visit b2's website" style="border-width:1px; border-color: #999999; border-style: dashed" /></a></td> + +<td><img src="b2-img/blank.gif" width="1" height="1" alt="" /></td> +<td width="150" style="text-align: right; padding-rightt: 6px;"> +<span style="color: #b0b0b0; font-family: verdana, arial, helvetica; font-size: 10px;">logged in as : <b><?php echo $user_login; ?></b></span> +</td> + +</tr> +<tr> + +<td class="menutop" width="20">  +</td> + +<td class="menutop"<?php if ($is_NS4) { echo " width=\"500\""; } ?>> +<div class="menutop"<?php if ($is_NS4) { echo " width=\"500\""; } ?>> + + +<?php if ($is_NS4) { echo $HTTP_USER_AGENT; } ?> + + +<?php $sep = "  |  "; ?> + <a href="b2edit.php" class="menutop" style="-font-weight: bold;">Post / Edit</a><?php echo $sep ?><a href="javascript:profile(<?php echo $user_ID ?>)" class="menutop">My Profile</a><?php echo $sep ?><a href="b2team.php" class="menutop">Team</a><?php + +if ($pagenow != "b2profile.php") { + +$menu = file($b2inc."/b2menutop.txt"); +$i=0; +$j=$menu[0]; +while ($j != "") { + $k = explode("\t",$j); + if ($user_level >= $k[0]) { + echo "$sep<a href=\"".$k[1]."\" class=\"menutop\">".trim($k[2])."</a>"; + } + $i=$i+1; + $j=$menu[$i]; + if (trim($j) == "***") + $j=""; +} + +} +?> + +</div> +</td> + +<td width="150" class="menutop" align="right" bgcolor="#FF9900"> +<a href="<?php echo $siteurl."/".$blogfilename; ?>" class="menutop">View site</a> +<?php echo $sep; ?> +<a href="b2login.php?action=logout" class="menutop">Logout</a> +</td> + +</tr> +<tr> + +<td> </td> +<td style="padding-left: 6px;"><span class="menutoptitle">:: <?php echo $title; ?></span></td> +<td> </td> + +</tr> + +</table> \ No newline at end of file diff --git a/b2-include/b2menutop.txt b/b2-include/b2menutop.txt new file mode 100644 index 0000000000..9d9f330fd9 --- /dev/null +++ b/b2-include/b2menutop.txt @@ -0,0 +1,14 @@ +3 b2options.php Options +3 b2categories.php Categories +3 b2template.php Template +*** +(Everything after the '***' is a comment.) + + +To add sections to the menu, use this syntax: + + the minimum level the user needs to access the section: between 0 and 10 ++tab ++the URL of the section's file ++tab ++the title of this section \ No newline at end of file diff --git a/b2-include/b2quicktags.js b/b2-include/b2quicktags.js new file mode 100644 index 0000000000..6574a5ae12 --- /dev/null +++ b/b2-include/b2quicktags.js @@ -0,0 +1,190 @@ +// b2 quick tags +// - authorized adaptation of the 'bbCode control code' by subBlue design ( www.subBlue.com ) + +// Define the quick tags +bbcode = new Array(); +bbtags = new Array('<b>','</b>','<i>','</i>','<u>','</u>','<strike>','</strike>','<blockquote>','</blockquote>','<p>','</p>','<li>','</li>','<img src="" border="0" alt="" />','','<a href="">','</a>'); +imageTag = false; + +// Replacement for arrayname.length property +function getarraysize(thearray) { + for (i = 0; i < thearray.length; i++) { + if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null)) + return i; + } + return thearray.length; +} + +// Replacement for arrayname.push(value) not implemented in IE until version 5.5 +// Appends element to the array +function arraypush(thearray,value) { + thearray[ getarraysize(thearray) ] = value; +} + +// Replacement for arrayname.pop() not implemented in IE until version 5.5 +// Removes and returns the last element of an array +function arraypop(thearray) { + thearraysize = getarraysize(thearray); + retval = thearray[thearraysize - 1]; + delete thearray[thearraysize - 1]; + return retval; +} + + +function checkForm(formObj) { + + formErrors = false; + + if (formObj.content.value.length < 2) { + formErrors = "You must enter a message!"; + } + + if (formErrors) { + alert(formErrors); + return false; + } else { + bbstyle(formObj, -1); + //formObj.preview.disabled = true; + //formObj.submit.disabled = true; + return true; + } +} + + +function emoticon(theSmilie) { + if ((parseInt(navigator.appVersion) >= 4) && (navigator.appName == "Microsoft Internet Explorer")) + theSelection = document.selection.createRange().text; // Get text selection + + if (theSelection) { + // Add tags around selection + document.selection.createRange().text = theSelection + theSmilie + ' '; + formObj.content.focus(); + theSelection = ''; + return; + } + + + document.post.content.value += ' ' + theSmilie + ' '; + document.post.content.focus(); +} + + +function bbfontstyle(formObj, bbopen, bbclose) { + if ((parseInt(navigator.appVersion) >= 4) && (navigator.appName == "Microsoft Internet Explorer")) { + theSelection = document.selection.createRange().text; + if (!theSelection) { + formObj.content.value += bbopen + bbclose; + formObj.content.focus(); + return; + } + document.selection.createRange().text = bbopen + theSelection + bbclose; + formObj.content.focus(); + return; + } else { + formObj.content.value += bbopen + bbclose; + formObj.content.focus(); + return; + } +} + + +function bbstyle(formObj, bbnumber) { + + donotinsert = false; + theSelection = false; + bblast = 0; + + if (bbnumber == -1) { // Close all open tags & default button names + while (bbcode[0]) { + butnumber = arraypop(bbcode) - 1; + formObj.content.value += bbtags[butnumber + 1]; + buttext = eval('formObj.addbbcode' + butnumber + '.value'); + eval('formObj.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"'); + } + formObj.content.focus(); + return; + } + + if ((parseInt(navigator.appVersion) >= 4) && (navigator.appName == "Microsoft Internet Explorer")) + theSelection = document.selection.createRange().text; // Get text selection + + if (theSelection) { + // Add tags around selection + document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1]; + formObj.content.focus(); + theSelection = ''; + return; + } + + // Find last occurance of an open tag the same as the one just clicked + for (i = 0; i < bbcode.length; i++) { + if (bbcode[i] == bbnumber+1) { + bblast = i; + donotinsert = true; + } + } + + if (donotinsert) { // Close all open tags up to the one just clicked & default button names + while (bbcode[bblast]) { + butnumber = arraypop(bbcode) - 1; + formObj.content.value += bbtags[butnumber + 1]; + buttext = eval('formObj.addbbcode' + butnumber + '.value'); + eval('formObj.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"'); + imageTag = false; + } + formObj.content.focus(); + return; + } else { // Open tags + + if (imageTag && (bbnumber != 14)) { // Close image tag before adding another + formObj.content.value += bbtags[15]; + lastValue = arraypop(bbcode) - 1; // Remove the close image tag from the list + formObj.addbbcode14.value = "image"; // Return button back to normal state + imageTag = false; + } + + // Open tag + formObj.content.value += bbtags[bbnumber]; + if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag + arraypush(bbcode,bbnumber+1); + eval('formObj.addbbcode'+bbnumber+'.value += "*"'); + formObj.content.focus(); + return; + } + +} + +// swirlee's bblink hack, slightly corrected +function bblink(formObj, bbnumber) { + current_url = prompt("URL:","http://"); + var re = new RegExp ('http%3A//', 'gi') ; + var current_url = current_url.replace(re, 'http://') ; + if((current_url == 'null') || (current_url == "http://")) { + current_url = ""; + exit; + } + if(bbnumber == 16) { + current_link_text = unescape(prompt("Link text:","link")); + if((current_link_text == null) || (current_link_text == "") || (current_link_text == "link")) { + link_text = 'link'; + } else { + link_text = current_link_text; + } + final_link = '<a href="' + current_url + '">' + current_link_text + '</a>'; + if (final_link != '<a href="">null</a>') { + formObj.content.value += final_link; + } + } + if(bbnumber == 14) { + current_alt = prompt("ALTernate text:","ALT"); + if((current_alt == null) || (current_alt == "") || (current_alt == "ALT")) { + alttag = ' alt=""'; + } else { + alttag = ' alt="' + current_alt + '"'; + } + final_image = '<img src="' + current_url + '" border="0"' + alttag + ' />'; + if (final_image != '<img src="" border="0" alt="" />') { + formObj.content.value += final_image; + } + } +} \ No newline at end of file diff --git a/b2-include/b2quicktags.php b/b2-include/b2quicktags.php new file mode 100644 index 0000000000..7f1ef714a5 --- /dev/null +++ b/b2-include/b2quicktags.php @@ -0,0 +1,33 @@ +<script src="<?php echo $b2inc ?>/b2quicktags.js" language="JavaScript" type="text/javascript"> +</script><table border="0" cellspacing="0" cellpadding="0"> +<tr align="center" valign="middle"> +<td> +<input type="button" class="quicktags" accesskey="b" name="addbbcode0" value=" B " style="font-weight:bold; width: 30px" onClick="bbstyle(this.form,0)" /> +</td> +<td> +<input type="button" class="quicktags" accesskey="i" name="addbbcode2" value=" i " style="font-style:italic; width: 30px" onClick="bbstyle(this.form,2)" /> +</td> +<td> +<input type="button" class="quicktags" accesskey="u" name="addbbcode4" value=" u " style="text-decoration: underline; width: 30px" onClick="bbstyle(this.form,4)" /> +</td> +<td> +<input type="button" class="quicktags" accesskey="s" name="addbbcode6" value="strike" style="text-decoration: line-through;width: 50px" onClick="bbstyle(this.form,6)" /> +</td> +<td> +<input type="button" class="quicktags" accesskey="p" name="addbbcode10" value="<p>" style="width: 40px" onClick="bbstyle(this.form,10)" /> +</td> +<?php if (basename($HTTP_SERVER_VARS["SCRIPT_FILENAME"]) != "b2bookmarklet.php") { ?><td> +<input type="button" class="quicktags" accesskey="l" name="addbbcode12" value="<li>" style="width: 40px" onClick="bbstyle(this.form,12)" /> +</td><?php } ?> +<?php if (basename($HTTP_SERVER_VARS["SCRIPT_FILENAME"]) != "b2bookmarklet.php") { ?><td> +<input type="button" class="quicktags" accesskey="q" name="addbbcode8" value="b-quote" style="width: 60px" onClick="bbstyle(this.form,8)" /> +</td><?php } ?> +<td> +<input type="button" class="quicktags" accesskey="m" name="addbbcode14" value="image" title="insert an image" style="width: 40px" onClick="bblink(this.form,14)" /> +</td> +<td> +<input type="button" class="quicktags" accesskey="h" name="addbbcode16" value="link" title="insert a link" style="text-decoration: underline; width: 40px" onClick="bblink(this.form,16)" /> +</td><td> +<input type="button" class="quicktags" accesskey="c" name="closetags" value="X" title="Close all tags" style="width: 30px; font-weigh: bolder;" onClick="bbstyle(document.post,-1)" /></td> +</tr> +</table> \ No newline at end of file diff --git a/b2-include/b2template.functions.php b/b2-include/b2template.functions.php new file mode 100644 index 0000000000..cf0696c7d8 --- /dev/null +++ b/b2-include/b2template.functions.php @@ -0,0 +1,1219 @@ +<?php + +/* new and improved ! now with more querystring stuff ! */ + +if (!isset($querystring_start)) { + $querystring_start = '?'; + $querystring_equal = '='; + $querystring_separator = '&'; +} + + + +/* template functions... */ + + +// @@@ These are template tags, you can edit them if you know what you're doing... + + + +/***** About-the-blog tags *****/ +/* Note: these tags go anywhere in the template */ + +function bloginfo($show='') { + $info = get_bloginfo($show); + $info = convert_bbcode($info); + $info = convert_gmcode($info); + $info = convert_smilies($info); + $info = apply_filters('bloginfo', $info); + echo convert_chars($info, 'html'); +} + +function bloginfo_rss($show='') { + $info = strip_tags(get_bloginfo($show)); + echo convert_chars($info, 'unicode'); +} + +function bloginfo_unicode($show='') { + $info = get_bloginfo($show); + echo convert_chars($info, 'unicode'); +} + +function get_bloginfo($show='') { + global $siteurl, $blogfilename, $blogname, $blogdescription, $pathserver, $admin_email; + switch($show) { + case "url": + $output = $siteurl."/".$blogfilename; + break; + case "description": + $output = $blogdescription; + break; + case "rdf_url": + $output = $siteurl.'/b2rdf.php'; + break; + case "rss_url": + $output = $siteurl.'/b2rss.php'; + break; + case "rss2_url": + $output = $siteurl.'/b2rss2.php'; + break; + case "pingback_url": + $output = $pathserver.'/xmlrpc.php'; + break; + case "admin_email": + $output = $admin_email; + break; + case "name": + default: + $output = $blogname; + break; + } + return($output); +} + +function single_post_title($prefix = '', $display = 1) { + global $p; + if (intval($p)) { + $post_data = get_postdata($p); + $title = $post_data['Title']; + $title = apply_filters('single_post_title', $title); + if ($display) { + echo $prefix.strip_tags(stripslashes($title)); + } else { + return strip_tags(stripslashes($title)); + } + } +} + +function single_cat_title($prefix = '', $display = 1 ) { + global $cat; + if(!empty($cat) && !(strtoupper($cat) == 'ALL')) { + $my_cat_name = get_the_category_by_ID($cat); + if(!empty($my_cat_name)) { + if ($display) + echo $prefix.strip_tags(stripslashes($my_cat_name)); + else + return strip_tags(stripslashes($my_cat_name)); + } + } +} + +function single_month_title($prefix = '', $display = 1 ) { + global $m, $month; + if(!empty($m)) { + $my_year = substr($m,0,4); + $my_month = $month[substr($m,4,2)]; + if ($display) + echo $prefix.$my_month.$prefix.$my_year; + else + return $m; + } +} + +/***** // About-the-blog tags *****/ + + + + +/***** Date/Time tags *****/ + +function the_date($d='', $before='', $after='', $echo = 1) { + global $id, $postdata, $day, $previousday,$dateformat,$newday; + $the_date = ''; + if ($day != $previousday) { + $the_date .= $before; + if ($d=='') { + $the_date .= mysql2date($dateformat, $postdata['Date']); + } else { + $the_date .= mysql2date($d, $postdata['Date']); + } + $the_date .= $after; + $previousday = $day; + } + $the_date = apply_filters('the_date', $the_date); + if ($echo) { + echo $the_date; + } else { + return $the_date; + } +} + +function the_time($d='', $echo = 1) { + global $id,$postdata,$timeformat; + if ($d=='') { + $the_time = mysql2date($timeformat, $postdata['Date']); + } else { + $the_time = mysql2date($d, $postdata['Date']); + } + $the_time = apply_filters('the_time', $the_time); + if ($echo) { + echo $the_time; + } else { + return $the_time; + } +} + +function the_weekday() { + global $weekday,$id,$postdata; + $the_weekday = $weekday[mysql2date('w', $postdata['Date'])]; + $the_weekday = apply_filters('the_weekday', $the_weekday); + echo $the_weekday; +} + +function the_weekday_date($before='',$after='') { + global $weekday,$id,$postdata,$day,$previousweekday; + $the_weekday_date = ''; + if ($day != $previousweekday) { + $the_weekday_date .= $before; + $the_weekday_date .= $weekday[mysql2date('w', $postdata['Date'])]; + $the_weekday_date .= $after; + $previousweekday = $day; + } + $the_weekday_date = apply_filters('the_weekday_date', $the_weekday_date); + echo $the_weekday_date; +} + +/***** // Date/Time tags *****/ + + + + +/***** Author tags *****/ + +function the_author() { + global $id,$authordata; + $i = $authordata['user_idmode']; + if ($i == 'nickname') echo $authordata['user_nickname']; + if ($i == 'login') echo $authordata['user_login']; + if ($i == 'firstname') echo $authordata['user_firstname']; + if ($i == 'lastname') echo $authordata['user_lastname']; + if ($i == 'namefl') echo $authordata['user_firstname'].' '.$authordata['user_lastname']; + if ($i == 'namelf') echo $authordata['user_lastname'].' '.$authordata['user_firstname']; + if (!$i) echo $authordata['user_nickname']; +} + +function the_author_login() { + global $id,$authordata; echo $authordata['user_login']; +} + +function the_author_firstname() { + global $id,$authordata; echo $authordata['user_firstname']; +} + +function the_author_lastname() { + global $id,$authordata; echo $authordata['user_lastname']; +} + +function the_author_nickname() { + global $id,$authordata; echo $authordata['user_nickname']; +} + +function the_author_ID() { + global $id,$authordata; echo $authordata['ID']; +} + +function the_author_email() { + global $id,$authordata; echo antispambot($authordata['user_email']); +} + +function the_author_url() { + global $id,$authordata; echo $authordata['user_url']; +} + +function the_author_icq() { + global $id,$authordata; echo $authordata['user_icq']; +} + +function the_author_aim() { + global $id,$authordata; echo str_replace(' ', '+', $authordata['user_aim']); +} + +function the_author_yim() { + global $id,$authordata; echo $authordata['user_yim']; +} + +function the_author_msn() { + global $id,$authordata; echo $authordata['user_msn']; +} + +function the_author_posts() { + global $id,$postdata; $posts=get_usernumposts($postdata['Author_ID']); echo $posts; +} + +/***** // Author tags *****/ + + + + +/***** Post tags *****/ + +function the_ID() { + global $id; + echo $id; +} + +function the_title($before='',$after='') { + $title = get_the_title(); + $title = convert_bbcode($title); + $title = convert_gmcode($title); + $title = convert_smilies($title); + $title = apply_filters('the_title', $title); + if ($title) { + echo convert_chars($before.$title.$after, 'html'); + } +} +function the_title_rss() { + $title = get_the_title(); + $title = convert_bbcode($title); + $title = convert_gmcode($title); + $title = strip_tags($title); + if (trim($title)) { + echo convert_chars($title, 'unicode'); + } +} +function the_title_unicode($before='',$after='') { + $title = get_the_title(); + $title = convert_bbcode($title); + $title = convert_gmcode($title); + $title = apply_filters('the_title_unicode', $title); + if (trim($title)) { + echo convert_chars($before.$title.$after, 'unicode'); + } +} +function get_the_title() { + global $id,$postdata; + $output = stripslashes($postdata['Title']); + $output = apply_filters('the_title', $output); + return($output); +} + +function the_content($more_link_text='(more...)', $stripteaser=0, $more_file='') { + $content = get_the_content($more_link_text,$stripteaser,$more_file); + $content = convert_bbcode($content); + $content = convert_gmcode($content); + $content = convert_smilies($content); + $content = convert_chars($content, 'html'); + $content = apply_filters('the_content', $content); + echo $content; +} +function the_content_rss($more_link_text='(more...)', $stripteaser=0, $more_file='', $cut = 0, $encode_html = 0) { + $content = get_the_content($more_link_text,$stripteaser,$more_file); + $content = convert_bbcode($content); + $content = convert_gmcode($content); + $content = convert_chars($content, 'unicode'); + if ($cut && !$encode_html) { + $encode_html = 2; + } + if ($encode_html == 1) { + $content = htmlspecialchars($content); + $cut = 0; + } elseif ($encode_html == 0) { + $content = make_url_footnote($content); + } elseif ($encode_html == 2) { + $content = strip_tags($content); + } + if ($cut) { + $blah = explode(' ', $content); + if (count($blah) > $cut) { + $k = $cut; + $use_dotdotdot = 1; + } else { + $k = count($blah); + $use_dotdotdot = 0; + } + for ($i=0; $i<$k; $i++) { + $excerpt .= $blah[$i].' '; + } + $excerpt .= ($use_dotdotdot) ? '...' : ''; + $content = $excerpt; + } + echo $content; +} +function the_content_unicode($more_link_text='(more...)', $stripteaser=0, $more_file='') { + $content = get_the_content($more_link_text,$stripteaser,$more_file); + $content = convert_bbcode($content); + $content = convert_gmcode($content); + $content = convert_smilies($content); + $content = convert_chars($content, 'unicode'); + $content = apply_filters('the_content_unicode', $content); + echo $content; +} +function get_the_content($more_link_text='(more...)', $stripteaser=0, $more_file='') { + global $id,$postdata,$more,$c,$withcomments,$page,$pages,$multipage,$numpages; + global $HTTP_SERVER_VARS, $preview; + global $querystring_start, $querystring_equal, $querystring_separator; + global $pagenow; + $output = ''; + if ($more_file != '') { + $file=$more_file; + } else { + $file=$pagenow; //$HTTP_SERVER_VARS['PHP_SELF']; + } + $content=$pages[$page-1]; + $content=explode('<!--more-->', $content); + if ((preg_match('/<!--noteaser-->/', $postdata['Content']) && ((!$multipage) || ($page==1)))) + $stripteaser=1; + $teaser=$content[0]; + if (($more) && ($stripteaser)) + $teaser=''; + $output .= $teaser; + if (count($content)>1) { + if ($more) { + $output .= '<a name="more'.$id.'"></a>'.$content[1]; + } else { + $output .= ' <a href="'.$file.$querystring_start.'p'.$querystring_equal.$id.$querystring_separator.'more'.$querystring_equal.'1#more'.$id.'">'.$more_link_text.'</a>'; + } + } + if ($preview) { // preview fix for javascript bug with foreign languages + $output = preg_replace('/\%u([0-9A-F]{4,4})/e', "'&#'.base_convert('\\1',16,10).';'", $output); + } + return($output); +} + +function link_pages($before='<br />', $after='<br />', $next_or_number='number', $nextpagelink='next page', $previouspagelink='previous page', $pagelink='%', $more_file='') { + global $id,$page,$numpages,$multipage,$more; + global $pagenow; + global $querystring_start, $querystring_equal, $querystring_separator; + if ($more_file != '') { + $file = $more_file; + } else { + $file = $pagenow; + } + if (($multipage)) { // && ($more)) { + if ($next_or_number=='number') { + echo $before; + for ($i = 1; $i < ($numpages+1); $i = $i + 1) { + $j=str_replace('%',"$i",$pagelink); + echo " "; + if (($i != $page) || ((!$more) && ($page==1))) + echo '<a href="'.$file.$querystring_start.'p'.$querystring_equal.$id. + $querystring_separator.'more'.$querystring_equal.'1'. + $querystring_separator.'page'.$querystring_equal.$i.'">'; + echo $j; + if (($i != $page) || ((!$more) && ($page==1))) + echo '</a>'; + } + echo $after; + } else { + if ($more) { + echo $before; + $i=$page-1; + if ($i && $more) + echo ' <a href="'.$file.$querystring_start.'p'.$querystring_equal.$id. + $querystring_separator.'more'.$querystring_equal.'1'. + $querystring_separator.'page'.$querystring_equal.$i.'">'. + $previouspagelink.'</a>'; + $i=$page+1; + if ($i<=$numpages && $more) + echo ' <a href="'.$file.$querystring_start.'p'.$querystring_equal.$id. + $querystring_separator.'more'.$querystring_equal.'1'. + $querystring_separator.'page'.$querystring_equal.$i.'">'. + $nextpagelink.'</a>'; + echo $after; + } + } + } +} + + +function previous_post($format='%', $previous='previous post: ', $title='yes', $in_same_cat='no', $limitprev=1, $excluded_categories='') { + global $tableposts, $id, $postdata, $siteurl, $blogfilename, $querycount; + global $p, $posts, $posts_per_page, $s; + global $querystring_start, $querystring_equal, $querystring_separator; + + if(($p) || ($posts_per_page==1)) { + + $current_post_date = $postdata['Date']; + $current_category = $postdata['Category']; + + $sqlcat = ''; + if ($in_same_cat != 'no') { + $sqlcat = " AND post_category='$current_category' "; + } + + $sql_exclude_cats = ''; + if (!empty($excluded_categories)) { + $blah = explode('and', $excluded_categories); + foreach($blah as $category) { + $category = intval($category); + $sql_exclude_cats .= " AND post_category != $category"; + } + } + + $limitprev--; + $sql = "SELECT ID,post_title FROM $tableposts WHERE post_date < '$current_post_date' AND post_category > 0 $sqlcat $sql_exclude_cats ORDER BY post_date DESC LIMIT $limitprev,1"; + + $query = @mysql_query($sql); + $querycount++; + if (($query) && (mysql_num_rows($query))) { + $p_info = mysql_fetch_object($query); + $p_title = $p_info->post_title; + $p_id = $p_info->ID; + $string = '<a href="'.$blogfilename.$querystring_start.'p'.$querystring_equal.$p_id.$querystring_separator.'more'.$querystring_equal.'1'.$querystring_separator.'c'.$querystring_equal.'1">'.$previous; + if (!($title!='yes')) { + $string .= stripslashes($p_title); + } + $string .= '</a>'; + $format = str_replace('%',$string,$format); + echo $format; + } + } +} + +function next_post($format='%', $next='next post: ', $title='yes', $in_same_cat='no', $limitnext=1, $excluded_categories='') { + global $tableposts, $p, $posts, $id, $postdata, $siteurl, $blogfilename, $querycount; + global $time_difference; + global $querystring_start, $querystring_equal, $querystring_separator; + if(($p) || ($posts==1)) { + + $current_post_date = $postdata['Date']; + $current_category = $postdata['Category']; + + $sqlcat = ''; + if ($in_same_cat != 'no') { + $sqlcat = " AND post_category='$current_category' "; + } + + $sql_exclude_cats = ''; + if (!empty($excluded_categories)) { + $blah = explode('and', $excluded_categories); + foreach($blah as $category) { + $category = intval($category); + $sql_exclude_cats .= " AND post_category != $category"; + } + } + + $now = date('Y-m-d H:i:s',(time() + ($time_difference * 3600))); + + $limitnext--; + $sql = "SELECT ID,post_title FROM $tableposts WHERE post_date > '$current_post_date' AND post_date < '$now' AND post_category > 0 $sqlcat $sql_exclude_cats ORDER BY post_date ASC LIMIT $limitnext,1"; + + $query = @mysql_query($sql); + $querycount++; + if (($query) && (mysql_num_rows($query))) { + $p_info = mysql_fetch_object($query); + $p_title = $p_info->post_title; + $p_id = $p_info->ID; + $string = '<a href="'.$blogfilename.$querystring_start.'p'.$querystring_equal.$p_id.$querystring_separator.'more'.$querystring_equal.'1'.$querystring_separator.'c'.$querystring_equal.'1">'.$next; + if ($title=='yes') { + $string .= stripslashes($p_title); + } + $string .= '</a>'; + $format = str_replace('%',$string,$format); + echo $format; + } + } +} + + + + + +function next_posts($max_page = 0) { // original by cfactor at cooltux.org + global $HTTP_SERVER_VARS, $siteurl, $blogfilename, $p, $paged, $what_to_show, $pagenow; + global $querystring_start, $querystring_equal, $querystring_separator; + if (empty($p) && ($what_to_show == 'paged')) { + $qstr = $HTTP_SERVER_VARS['QUERY_STRING']; + if (!empty($qstr)) { + $qstr = preg_replace("/&paged=\d{0,}/","",$qstr); + $qstr = preg_replace("/paged=\d{0,}/","",$qstr); + } elseif (stristr($HTTP_SERVER_VARS['REQUEST_URI'], $HTTP_SERVER_VARS['SCRIPT_NAME'] )) { + if ('' != $qstr = str_replace($HTTP_SERVER_VARS['SCRIPT_NAME'], '', + $HTTP_SERVER_VARS['REQUEST_URI']) ) { + $qstr = preg_replace("/^\//", "", $qstr); + $qstr = preg_replace("/paged\/\d{0,}\//", "", $qstr); + $qstr = preg_replace("/paged\/\d{0,}/", "", $qstr); + $qstr = preg_replace("/\/$/", "", $qstr); + } + } + if (!$paged) $paged = 1; + $nextpage = intval($paged) + 1; + if (!$max_page || $max_page >= $nextpage) { + echo $pagenow.$querystring_start. + ($qstr == '' ? '' : $qstr.$querystring_separator) . + 'paged'.$querystring_equal.$nextpage; + } + } +} + +function next_posts_link($label='Next Page >>', $max_page=0) { + global $p, $paged, $result, $request, $posts_per_page, $what_to_show; + if ($what_to_show == 'paged') { + if (!$max_page) { + $nxt_request = $request; + if ($pos = strpos(strtoupper($request), 'LIMIT')) { + $nxt_request = substr($request, 0, $pos); + } + $nxt_result = mysql_query($nxt_request); + $numposts = mysql_num_rows($nxt_result); + $max_page = ceil($numposts / $posts_per_page); + } + if (!$paged) $paged = 1; + $nextpage = intval($paged) + 1; + if (empty($p) && (empty($paged) || $nextpage <= $max_page)) { + echo '<a href="'; + echo next_posts($max_page); + echo '">'. htmlspecialchars($label) .'</a>'; + } + } +} + + +function previous_posts() { // original by cfactor at cooltux.org + global $HTTP_SERVER_VARS, $siteurl, $blogfilename, $p, $paged, $what_to_show, $pagenow; + global $querystring_start, $querystring_equal, $querystring_separator; + if (empty($p) && ($what_to_show == 'paged')) { + $qstr = $HTTP_SERVER_VARS['QUERY_STRING']; + if (!empty($qstr)) { + $qstr = preg_replace("/&paged=\d{0,}/","",$qstr); + $qstr = preg_replace("/paged=\d{0,}/","",$qstr); + } elseif (stristr($HTTP_SERVER_VARS['REQUEST_URI'], $HTTP_SERVER_VARS['SCRIPT_NAME'] )) { + if ('' != $qstr = str_replace($HTTP_SERVER_VARS['SCRIPT_NAME'], '', + $HTTP_SERVER_VARS['REQUEST_URI']) ) { + $qstr = preg_replace("/^\//", "", $qstr); + $qstr = preg_replace("/paged\/\d{0,}\//", "", $qstr); + $qstr = preg_replace("/paged\/\d{0,}/", "", $qstr); + $qstr = preg_replace("/\/$/", "", $qstr); + } + } + $nextpage = intval($paged) - 1; + if ($nextpage < 1) $nextpage = 1; + echo $pagenow.$querystring_start. + ($qstr == '' ? '' : $qstr.$querystring_separator) . + 'paged'.$querystring_equal.$nextpage; + } +} + +function previous_posts_link($label='<< Previous Page') { + global $p, $paged, $what_to_show; + if (empty($p) && ($paged > 1) && ($what_to_show == 'paged')) { + echo '<a href="'; + echo previous_posts(); + echo '">'. htmlspecialchars($label) .'</a>'; + } +} + +function posts_nav_link($sep=' :: ', $prelabel='<< Previous Page', $nxtlabel='Next Page >>') { + global $p, $what_to_show, $request, $posts_per_page; + if (empty($p) && ($what_to_show == 'paged')) { + $nxt_request = $request; + if ($pos = strpos(strtoupper($request), 'LIMIT')) { + $nxt_request = substr($request, 0, $pos); + } + $nxt_result = mysql_query($nxt_request); + $numposts = mysql_num_rows($nxt_result); + $max_page = ceil($numposts / $posts_per_page); + if ($max_page > 1) { + previous_posts_link($prelabel); + echo htmlspecialchars($sep); + next_posts_link($nxtlabel, $max_page); + } + } +} + +/***** // Post tags *****/ + + + + +/***** Category tags *****/ + +function the_category() { + $category = get_the_category(); + $category = apply_filters('the_category', $category); + echo convert_chars($category, 'html'); +} +function the_category_rss() { + echo convert_chars(strip_tags(get_the_category()), 'xml'); +} +function the_category_unicode() { + $category = get_the_category(); + $category = apply_filters('the_category_unicode', $category); + echo convert_chars($category, 'unicode'); +} +function get_the_category() { + global $id,$postdata,$tablecategories,$querycount,$cache_categories,$use_cache; + $cat_ID = $postdata['Category']; + if ((empty($cache_categories[$cat_ID])) OR (!$use_cache)) { + $query="SELECT cat_name FROM $tablecategories WHERE cat_ID = '$cat_ID'"; + $result=mysql_query($query); + $querycount++; + $myrow = mysql_fetch_array($result); + $cat_name = $myrow[0]; + $cache_categories[$cat_ID] = $cat_name; + } else { + $cat_name = $cache_categories[$cat_ID]; + } + return(stripslashes($cat_name)); +} + +function get_the_category_by_ID($cat_ID) { + global $id,$tablecategories,$querycount,$cache_categories,$use_cache; + if ((!$cache_categories[$cat_ID]) OR (!$use_cache)) { + $query="SELECT cat_name FROM $tablecategories WHERE cat_ID = '$cat_ID'"; + $result=mysql_query($query); + $querycount++; + $myrow = mysql_fetch_array($result); + $cat_name = $myrow[0]; + $cache_categories[$cat_ID] = $cat_name; + } else { + $cat_name = $cache_categories[$cat_ID]; + } + return(stripslashes($cat_name)); +} + +function the_category_ID() { + global $id,$postdata; echo $postdata['Category']; +} + +function the_category_head($before='',$after='') { + global $id, $postdata, $currentcat, $previouscat,$dateformat,$newday; + $currentcat = $postdata['Category']; + if ($currentcat != $previouscat) { + echo $before; + echo get_the_category_by_ID($currentcat); + echo $after; + $previouscat = $currentcat; + } +} + +// out of the b2 loop +function dropdown_cats($optionall = 1, $all = 'All') { + global $cat, $tablecategories, $querycount; + $query="SELECT * FROM $tablecategories"; + $result=mysql_query($query); + $querycount++; + echo "<select name=\"cat\" class=\"postform\">\n"; + if (intval($optionall) == 1) { + echo "\t<option value=\"all\">$all</option>\n"; + } + while($row = mysql_fetch_object($result)) { + echo "\t<option value=\"".$row->cat_ID."\""; + if ($row->cat_ID == $cat) + echo ' selected="selected"'; + echo '>'.stripslashes($row->cat_name)."</option>\n"; + } + echo "</select>\n"; +} + +// out of the b2 loop +function list_cats($optionall = 1, $all = 'All', $sort_column = 'ID', $sort_order = 'asc', $file = 'blah') { + global $tablecategories,$querycount; + global $pagenow; + global $querystring_start, $querystring_equal, $querystring_separator; + $file = ($file == 'blah') ? $pagenow : $file; + $sort_column = 'cat_'.$sort_column; + $query="SELECT * FROM $tablecategories WHERE cat_ID > 0 ORDER BY $sort_column $sort_order"; + $result=mysql_query($query); + $querycount++; + if (intval($optionall) == 1) { + $all = apply_filters('list_cats', $all); + echo "\t<a href=\"".$file.$querystring_start.'cat'.$querystring_equal.'all">'.$all."</a><br />\n"; + } + while($row = mysql_fetch_object($result)) { + $cat_name = $row->cat_name; + $cat_name = apply_filters('list_cats', $cat_name); + echo "\t<a href=\"".$file.$querystring_start.'cat'.$querystring_equal.$row->cat_ID.'">'; + echo stripslashes($cat_name)."</a><br />\n"; + } +} + +/***** // Category tags *****/ + + + + +/***** <Link> tags *****/ + + + +/***** // <Link> tags *****/ + + + + +/***** Comment tags *****/ + +// generic comments/trackbacks/pingbacks numbering +function generic_ctp_number($post_id, $mode = 'comments') { + global $postdata, $tablecomments, $querycount, $cache_ctp_number, $use_cache; + if (!isset($cache_ctp_number[$post_id]) || (!$use_cache)) { + $post_id = intval($post_id); + $query = "SELECT * FROM $tablecomments WHERE comment_post_ID = $post_id"; + $result = mysql_query($query) or die('SQL query: '.$query.'<br />MySQL Error: '.mysql_error()); + $querycount++; + $ctp_number = array(); + while($row = mysql_fetch_object($result)) { + if (substr($row->comment_content, 0, 13) == '<trackback />') { + $ctp_number['trackbacks']++; + } elseif (substr($row->comment_content, 0, 12) == '<pingback />') { + $ctp_number['pingbacks']++; + } else { + $ctp_number['comments']++; + } + $ctp_number['ctp']++; + } + $cache_ctp_number[$post_id] = $ctp_number; + } else { + $ctp_number = $cache_ctp_number[$post_id]; + } + if (($mode != 'comments') && ($mode != 'trackbacks') && ($mode != 'pingbacks') && ($mode != 'ctp')) { + $mode = 'ctp'; + } + return $ctp_number[$mode]; +} + +function comments_number($zero='no comment', $one='1 comment', $more='% comments') { + // original hack by dodo@regretless.com + global $id,$postdata,$tablecomments,$c,$querycount,$cache_commentsnumber,$use_cache; + $number = generic_ctp_number($id, 'comments'); + if ($number == 0) { + $blah = $zero; + } elseif ($number == 1) { + $blah = $one; + } elseif ($number > 1) { + $n = $number; + $more=str_replace('%', $n, $more); + $blah = $more; + } + echo $blah; +} + +function comments_link($file='') { + global $id,$pagenow; + global $querystring_start, $querystring_equal, $querystring_separator; + if ($file == '') $file = $pagenow; + if ($file == '/') $file = ''; + echo $file.$querystring_start.'p'.$querystring_equal.$id.$querystring_separator.'c'.$querystring_equal.'1#comments'; +} + +function comments_popup_script($width=400, $height=400, $file='b2commentspopup.php', $trackbackfile='b2trackbackpopup.php', $pingbackfile='b2pingbackspopup.php') { + global $b2commentspopupfile, $b2trackbackpopupfile, $b2pingbackpopupfile, $b2commentsjavascript; + $b2commentspopupfile = $file; + $b2trackbackpopupfile = $trackbackfile; + $b2pingbackpopupfile = $pingbackfile; + $b2commentsjavascript = 1; + $javascript = "<script language=\"javascript\" type=\"text/javascript\">\n<!--\nfunction b2open (macagna) {\n window.open(macagna, '_blank', 'width=$width,height=$height,scrollbars=yes,status=yes');\n}\n//-->\n</script>\n"; + echo $javascript; +} + +function comments_popup_link($zero='no comment', $one='1 comment', $more='% comments', $CSSclass='') { + global $id, $b2commentspopupfile, $b2commentsjavascript; + global $querystring_start, $querystring_equal, $querystring_separator, $siteurl; + echo '<a href="'.$siteurl.'/'; + if ($b2commentsjavascript) { + echo $b2commentspopupfile.$querystring_start.'p'.$querystring_equal.$id.$querystring_separator.'c'.$querystring_equal.'1'; + echo '" onclick="b2open(this.href); return false"'; + } else { + // if comments_popup_script() is not in the template, display simple comment link + comments_link(); + echo '"'; + } + if (!empty($CSSclass)) { + echo ' class="'.$CSSclass.'"'; + } + echo '>'; + comments_number($zero, $one, $more); + echo '</a>'; +} + +function comment_ID() { + global $commentdata; echo $commentdata['comment_ID']; +} + +function comment_author() { + global $commentdata; echo stripslashes($commentdata['comment_author']); +} + +function comment_author_email() { + global $commentdata; echo antispambot(stripslashes($commentdata['comment_author_email'])); +} + +function comment_author_url() { + global $commentdata; + $url = trim(stripslashes($commentdata['comment_author_url'])); + $url = (!stristr($url, '://')) ? 'http://'.$url : $url; + // convert & into & + $url = preg_replace('#&([^amp\;])#is', '&$1', $url); + if ($url != 'http://url') { + echo $url; + } +} + +function comment_author_email_link($linktext='', $before='', $after='') { + global $commentdata; + $email=$commentdata['comment_author_email']; + if ((!empty($email)) && ($email != '@')) { + $display = ($linktext != '') ? $linktext : antispambot(stripslashes($email)); + echo $before; + echo '<a href="mailto:'.antispambot(stripslashes($email)).'">'.$display.'</a>'; + echo $after; + } +} + +function comment_author_url_link($linktext='', $before='', $after='') { + global $commentdata; + $url = trim(stripslashes($commentdata['comment_author_url'])); + $url = preg_replace('#&([^amp\;])#is', '&$1', $url); + $url = (!stristr($url, '://')) ? 'http://'.$url : $url; + if ((!empty($url)) && ($url != 'http://') && ($url != 'http://url')) { + $display = ($linktext != '') ? $linktext : stripslashes($url); + echo $before; + echo '<a href="'.stripslashes($url).'" target="_blank">'.$display.'</a>'; + echo $after; + } +} + +function comment_author_IP() { + global $commentdata; echo stripslashes($commentdata['comment_author_IP']); +} + +function comment_text() { + global $commentdata; + $comment = stripslashes($commentdata['comment_content']); + $comment = str_replace('<trackback />', '', $comment); + $comment = str_replace('<pingback />', '', $comment); + $comment = convert_chars($comment); + $comment = convert_bbcode($comment); + $comment = convert_gmcode($comment); + $comment = convert_smilies($comment); + $comment = make_clickable($comment); + $comment = balanceTags($comment); + $comment = apply_filters('comment_text', $comment); + echo $comment; +} + +function comment_date($d='') { + global $commentdata,$dateformat; + if ($d == '') { + echo mysql2date($dateformat, $commentdata['comment_date']); + } else { + echo mysql2date($d, $commentdata['comment_date']); + } +} + +function comment_time($d='') { + global $commentdata,$timeformat; + if ($d == '') { + echo mysql2date($timeformat, $commentdata['comment_date']); + } else { + echo mysql2date($d, $commentdata['comment_date']); + } +} + +/***** // Comment tags *****/ + + + +/***** TrackBack tags *****/ + +function trackback_url($display = 1) { + global $pathserver, $id; + $tb_url = $pathserver.'/b2trackback.php/'.$id; + if ($display) { + echo $tb_url; + } else { + return $tb_url; + } +} + +function trackback_number($zero='no trackback', $one='1 trackback', $more='% trackbacks') { + global $id, $tablecomments, $tb, $querycount, $cache_trackbacknumber, $use_cache; + $number = generic_ctp_number($id, 'trackbacks'); + if ($number == 0) { + $blah = $zero; + } elseif ($number == 1) { + $blah = $one; + } elseif ($number > 1) { + $n = $number; + $more=str_replace('%', $n, $more); + $blah = $more; + } + echo $blah; +} + +function trackback_link($file='') { + global $id,$pagenow; + global $querystring_start, $querystring_equal, $querystring_separator; + if ($file == '') $file = $pagenow; + if ($file == '/') $file = ''; + echo $file.$querystring_start.'p'.$querystring_equal.$id.$querystring_separator.'tb'.$querystring_equal.'1#trackback'; +} + +function trackback_popup_link($zero='no trackback', $one='1 trackback', $more='% trackbacks', $CSSclass='') { + global $id, $b2trackbackpopupfile, $b2commentsjavascript; + global $querystring_start, $querystring_equal, $querystring_separator, $siteurl; + echo '<a href="'.$siteurl.'/'; + if ($b2commentsjavascript) { + echo $b2trackbackpopupfile.$querystring_start.'p'.$querystring_equal.$id.$querystring_separator.'tb'.$querystring_equal.'1'; + echo '" onclick="b2open(this.href); return false"'; + } else { + // if comments_popup_script() is not in the template, display simple comment link + trackback_link(); + echo '"'; + } + if (!empty($CSSclass)) { + echo ' class="'.$CSSclass.'"'; + } + echo '>'; + trackback_number($zero, $one, $more); + echo '</a>'; +} + +function trackback_rdf($timezone=0) { + global $pathserver, $id, $HTTP_SERVER_VARS; + if (!stristr($HTTP_SERVER_VARS['HTTP_USER_AGENT'], 'W3C_Validator')) { + echo '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" '."\n"; + echo ' xmlns:dc="http://purl.org/dc/elements/1.1/"'."\n"; + echo ' xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">'."\n"; + echo '<rdf:Description'."\n"; + echo ' rdf:about="'; + permalink_single(); + echo '"'."\n"; + echo ' dc:identifier="'; + permalink_single(); + echo '"'."\n"; + echo ' dc:title="'.addslashes(get_the_title()).'"'."\n"; + echo ' trackback:ping="'.trackback_url(0).'"'." />\n"; + echo '</rdf:RDF>'; + } +} + +/***** // TrackBack tags *****/ + + + +/***** PingBack tags *****/ + +function pingback_number($zero='no pingback', $one='1 pingback', $more='% pingbacks') { + global $id, $tablecomments, $tb, $querycount, $cache_pingbacknumber, $use_cache; + $number = generic_ctp_number($id, 'pingbacks'); + if ($number == 0) { + $blah = $zero; + } elseif ($number == 1) { + $blah = $one; + } elseif ($number > 1) { + $n = $number; + $more=str_replace('%', $n, $more); + $blah = $more; + } + echo $blah; +} + +function pingback_link($file='') { + global $id,$pagenow; + global $querystring_start, $querystring_equal, $querystring_separator; + if ($file == '') $file = $pagenow; + if ($file == '/') $file = ''; + echo $file.$querystring_start.'p'.$querystring_equal.$id.$querystring_separator.'pb'.$querystring_equal.'1#pingbacks'; +} + +function pingback_popup_link($zero='no pingback', $one='1 pingback', $more='% pingbacks', $CSSclass='') { + global $id, $b2pingbackpopupfile, $b2commentsjavascript; + global $querystring_start, $querystring_equal, $querystring_separator, $siteurl; + echo '<a href="'.$siteurl.'/'; + if ($b2commentsjavascript) { + echo $b2pingbackpopupfile.$querystring_start.'p'.$querystring_equal.$id.$querystring_separator.'pb'.$querystring_equal.'1'; + echo '" onclick="b2open(this.href); return false"'; + } else { + // if comments_popup_script() is not in the template, display simple comment link + pingback_link(); + echo '"'; + } + if (!empty($CSSclass)) { + echo ' class="'.$CSSclass.'"'; + } + echo '>'; + pingback_number($zero, $one, $more); + echo '</a>'; +} + + + +/***** // PingBack tags *****/ + + + +/***** Permalink tags *****/ + +function permalink_anchor($mode = 'id') { + global $id, $postdata; + switch(strtolower($mode)) { + case 'title': + $title = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', $postdata['Title']); + echo '<a name="'.$title.'"></a>'; + break; + case 'id': + default: + echo '<a name="'.$id.'"></a>'; + break; + } +} + +function permalink_link($file='', $mode = 'id') { + global $id, $postdata, $pagenow, $cacheweekly; + global $querystring_start, $querystring_equal, $querystring_separator; + $file = ($file=='') ? $pagenow : $file; + switch(strtolower($mode)) { + case 'title': + $title = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', $postdata['Title']); + $anchor = $title; + break; + case 'id': + default: + $anchor = $id; + break; + } + $archive_mode = get_settings('archive_mode'); + switch($archive_mode) { + case 'daily': + echo $file.$querystring_start.'m'.$querystring_equal.substr($postdata['Date'],0,4).substr($postdata['Date'],5,2).substr($postdata['Date'],8,2).'#'.$anchor; + break; + case 'monthly': + echo $file.$querystring_start.'m'.$querystring_equal.substr($postdata['Date'],0,4).substr($postdata['Date'],5,2).'#'.$anchor; + break; + case 'weekly': + if((!isset($cacheweekly)) || (empty($cacheweekly[$postdata['Date']]))) { + $sql = "SELECT WEEK('".$postdata['Date']."')"; + $result = mysql_query($sql); + $row = mysql_fetch_row($result); + $cacheweekly[$postdata['Date']] = $row[0]; + } + echo $file.$querystring_start.'m'.$querystring_equal.substr($postdata['Date'],0,4).$querystring_separator.'w'.$querystring_equal.$cacheweekly[$postdata['Date']].'#'.$anchor; + break; + case 'postbypost': + echo $file.$querystring_start.'p'.$querystring_equal.$id; + break; + } +} + +function permalink_single($file='') { + global $id,$postdata,$pagenow; + global $querystring_start, $querystring_equal, $querystring_separator; + if ($file=='') + $file=$pagenow; + echo $file.$querystring_start.'p'.$querystring_equal.$id.$querystring_separator.'more'.$querystring_equal.'1'.$querystring_separator.'c'.$querystring_equal.'1'; +} + +function permalink_single_rss($file='b2rss.xml') { + global $id,$postdata,$pagenow,$siteurl,$blogfilename; + global $querystring_start, $querystring_equal, $querystring_separator; + echo $siteurl.'/'.$blogfilename.$querystring_start.'p'.$querystring_equal.$id.$querystring_separator.'c'.$querystring_equal.'1'; +} + +/***** // Permalink tags *****/ + + + + +// @@@ These aren't template tags, do not edit them + +function start_b2() { + global $row, $id, $postdata, $authordata, $day, $preview, $page, $pages, $multipage, $more, $numpages; + global $preview_userid,$preview_date,$preview_content,$preview_title,$preview_category,$preview_notify,$preview_make_clickable,$preview_autobr; + global $pagenow; + global $HTTP_GET_VARS; + if (!$preview) { + $id = $row->ID; + $postdata=get_postdata2($id); + } else { + $id = 0; + $postdata = array ( + 'ID' => 0, + 'Author_ID' => $HTTP_GET_VARS['preview_userid'], + 'Date' => $HTTP_GET_VARS['preview_date'], + 'Content' => $HTTP_GET_VARS['preview_content'], + 'Title' => $HTTP_GET_VARS['preview_title'], + 'Category' => $HTTP_GET_VARS['preview_category'], + 'Notify' => 1, + 'Clickable' => 1, + 'Karma' => 0 // this isn't used yet + ); + if (!empty($HTTP_GET_VARS['preview_autobr'])) { + $postdata['Content'] = autobrize($postdata['Content']); + } + } + $authordata = get_userdata($postdata['Author_ID']); + $day = mysql2date('d.m.y',$postdata['Date']); + $currentmonth = mysql2date('m',$postdata['Date']); + $numpages=1; + if (!$page) + $page=1; + if (isset($p)) + $more=1; + $content = $postdata['Content']; + if (preg_match('/<!--nextpage-->/', $postdata['Content'])) { + if ($page > 1) + $more=1; + $multipage=1; + $content=stripslashes($postdata['Content']); + $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content); + $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content); + $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content); + $pages=explode('<!--nextpage-->', $content); + $numpages=count($pages); + } else { + $pages[0]=stripslashes($postdata['Content']); + $multipage=0; + } + return true; +} + +function is_new_day() { + global $day, $previousday; + if ($day != $previousday) { + return(1); + } else { + return(0); + } +} + +function apply_filters($tag, $string) { + global $b2_filter; + if (isset($b2_filter['all'])) { + $b2_filter['all'] = (is_string($b2_filter['all'])) ? array($b2_filter['all']) : $b2_filter['all']; + $b2_filter[$tag] = array_merge($b2_filter['all'], $b2_filter[$tag]); + $b2_filter[$tag] = array_unique($b2_filter[$tag]); + } + if (isset($b2_filter[$tag])) { + $b2_filter[$tags] = (is_string($b2_filter[$tag])) ? array($b2_filter[$tag]) : $b2_filter[$tag]; + $functions = $b2_filter[$tag]; + foreach($functions as $function) { + $string = $function($string); + } + } + return $string; +} + +function add_filter($tag, $function_to_add) { + global $b2_filter; + if (isset($b2_filter[$tag])) { + $functions = $b2_filter[$tag]; + if (is_array($functions)) { + foreach($functions as $function) { + $new_functions[] = $function; + } + } elseif (is_string($functions)) { + $new_functions[] = $functions; + } +/* this is commented out because it just makes PHP die silently + for no apparent reason + if (is_array($function_to_add)) { + foreach($function_to_add as $function) { + if (!in_array($function, $b2_filter[$tag])) { + $new_functions[] = $function; + } + } + } else */if (is_string($function_to_add)) { + if (!@in_array($function_to_add, $b2_filter[$tag])) { + $new_functions[] = $function_to_add; + } + } + $b2_filter[$tag] = $new_functions; + } else { + $b2_filter[$tag] = array($function_to_add); + } + return true; +} + +?> diff --git a/b2-include/b2vars.php b/b2-include/b2vars.php new file mode 100644 index 0000000000..cca5ffe6a1 --- /dev/null +++ b/b2-include/b2vars.php @@ -0,0 +1,276 @@ +<?php + +/* This file sets various arrays and variables for use in b2 */ + +#b2 version +$b2_version = '0.6.1'; + +#BBcode search and replace arrays +$b2_bbcode['in'] = array( + '#\[b](.+?)\[/b]#is', // Formatting tags + '#\[i](.+?)\[/i]#is', + '#\[u](.+?)\[/u]#is', + '#\[s](.+?)\[/s]#is', + '#\[color=(.+?)](.+?)\[/color]#is', + '#\[size=(.+?)](.+?)\[/size]#is', + '#\[font=(.+?)](.+?)\[/font]#is', + '#\[img](.+?)\[/img]#is', // Image + '#\[url](.+?)\[/url]#is', // URL + '#\[url=(.+?)](.+?)\[/url]#is', +# '#\[email](.+?)\[/email]#eis', // E-mail +# '#\[email=(.+?)](.+?)\[/email]#eis' +); +$b2_bbcode['out'] = array( + '<strong>$1</strong>', // Formatting tags + '<em>$1</em>', + '<span style="text-decoration:underline">$1</span>', + '<span style="text-decoration:line-through">$1</span>', + '<span style="color:$1">$2</span>', + '<span style="font-size:$1px">$2</span>', + '<span style="font-family:$1">$2</span>', + '<img src="$1" alt="" />', // Image + '<a href="$1">$1</a>', // URL + '<a href="$1" title="$2">$2</a>', +# "'<a href=\"mailto:'.antispambot('\\1').'\">'.antispambot('\\1').'</a>'", // E-mail +# '<a href="mailto:$1">$2</a>' +); + +#GreyMatter formatting search and replace arrays +$b2_gmcode['in'] = array( + '#\\*\*(.+?)\\*\*#is', // **bold** + '#\\\\(.+?)\\\\#is', // \\italic\\ + '#\__(.+?)\__#is' // __underline__ +); +$b2_gmcode['out'] = array( + '<strong>$1</strong>', + '<em>$1</em>', + '<span style="text-decoration:underline">$1</span>' +); + +#Translation of HTML entities and special characters +$b2_htmltrans = array_flip(get_html_translation_table(HTML_ENTITIES)); +$b2_htmltrans['<'] = '<'; # preserve HTML +$b2_htmltrans['>'] = '>'; # preserve HTML +$b2_htmltransbis = array( + '–' => '–', '—' => '—', '‘' => '‘', '’' => '’', + '“' => '“', '”' => '”', '•' => '•', '€' => '€', + '<' => '<', # preserve fake HTML + '>' => '>', # preserve fake HTML + '&sp;' => ' ', '!' => '!', '"' => '"', '#' => '#', '$' => '$', '%' => '%', '&' => '&', ''' => ''', '(' => '(', ')' => ')', + '*' => '*', '+' => '+', ',' => ',', '‐' => '-', '−' => '-', '.' => '.', '/' => '/', ':' => ':', ';' => ';', '<' => '<', + '=' => '=', '>' => '>', '?' => '?', '@' => '@', '[' => '[', '\' => '\', ']' => ']', 'ˆ' => '^', '_' => '_', '―' => '_', + '`' => '`', '{' => '{', '|' => '|', '}' => '}', '˜' => '~', '‚' => '‚', '„' => '„', + '&ldots;' => '…', 'Š' => 'Š', '‹' => '‹', 'Œ' => 'Œ', '‘' => '‘', '’' => '‘', '’' => '’', + '“' => '“', '”' => '“', '”' => '”', '•' => '•', '–' => '–', '&endash;' => '–', '—' => '—', '&emdash;' => '—', '˜' => '˜', '™' => '™', + 'š' => 'š', '›' => '›', 'œ' => 'œ', 'Ÿ' => 'Ÿ', ' ' => ' ', '¡' => '¡', '¢' => '¢', '£' => '£', '¤' => '¤', '¥' => '¥', + '¦' => '¦', '&brkbar;' => '¦', '§' => '§', '¨' => '¨', '¨' => '¨', '©' => '©', 'ª' => 'ª', '«' => '«', '¬' => '¬', '­' => '­', + '®' => '®', '¯' => '¯', '&hibar;' => '¯', '°' => '°', '±' => '±', '²' => '²', '³' => '³', '´' => '´', 'µ' => 'µ', '¶' => '¶', + '·' => '·', '¸' => '¸', '¹' => '¹', 'º' => 'º', '»' => '»', '¼' => '¼', '½' => '½', '½' => '½', '¾' => '¾', '¿' => '¿', + 'À' => 'À', 'Á' => 'Á', 'Â' => 'Â', 'Ã' => 'Ã', 'Ä' => 'Ä', 'Å' => 'Å', 'Æ' => 'Æ', 'Ç' => 'Ç', 'È' => 'È', 'É' => 'É', + 'Ê' => 'Ê', 'Ë' => 'Ë', 'Ì' => 'Ì', 'Í' => 'Í', 'Î' => 'Î', 'Ï' => 'Ï', 'Ð' => 'Ð', 'Ñ' => 'Ñ', 'Ò' => 'Ò', 'Ó' => 'Ó', + 'Ô' => 'Ô', 'Õ' => 'Õ', 'Ö' => 'Ö', '×' => '×', 'Ø' => 'Ø', 'Ù' => 'Ù', 'Ú' => 'Ú', 'Û' => 'Û', 'Ü' => 'Ü', 'Ý' => 'Ý', + 'Þ' => 'Þ', 'ß' => 'ß', 'à' => 'à', 'á' => 'á', 'â' => 'â', 'ã' => 'ã', 'ä' => 'ä', 'å' => 'å', 'æ' => 'æ', 'ç' => 'ç', + 'è' => 'è', 'é' => 'é', 'ê' => 'ê', 'ë' => 'ë', 'ì' => 'ì', 'í' => 'í', 'î' => 'î', 'ï' => 'ï', 'ð' => 'ð', 'ñ' => 'ñ', + 'ò' => 'ò', 'ó' => 'ó', 'ô' => 'ô', 'õ' => 'õ', 'ö' => 'ö', '÷' => '÷', 'ø' => 'ø', 'ù' => 'ù', 'ú' => 'ú', 'û' => 'û', + 'ü' => 'ü', 'ý' => 'ý', 'þ' => 'þ', 'ÿ' => 'ÿ', 'Œ' => 'Œ', 'œ' => 'œ', 'Š' => 'Š', 'š' => 'š', 'Ÿ' => 'Ÿ', 'ƒ' => 'ƒ', + 'ˆ' => 'ˆ', '˜' => '˜', 'Α' => 'Α', 'Β' => 'Β', 'Γ' => 'Γ', 'Δ' => 'Δ', 'Ε' => 'Ε', 'Ζ' => 'Ζ', 'Η' => 'Η', 'Θ' => 'Θ', + 'Ι' => 'Ι', 'Κ' => 'Κ', 'Λ' => 'Λ', 'Μ' => 'Μ', 'Ν' => 'Ν', 'Ξ' => 'Ξ', 'Ο' => 'Ο', 'Π' => 'Π', 'Ρ' => 'Ρ', 'Σ' => 'Σ', + 'Τ' => 'Τ', 'Υ' => 'Υ', 'Φ' => 'Φ', 'Χ' => 'Χ', 'Ψ' => 'Ψ', 'Ω' => 'Ω', 'α' => 'α', 'β' => 'β', 'γ' => 'γ', 'δ' => 'δ', + 'ε' => 'ε', 'ζ' => 'ζ', 'η' => 'η', 'θ' => 'θ', 'ι' => 'ι', 'κ' => 'κ', 'λ' => 'λ', 'μ' => 'μ', 'ν' => 'ν', 'ξ' => 'ξ', + 'ο' => 'ο', 'π' => 'π', 'ρ' => 'ρ', 'ς' => 'ς', 'σ' => 'σ', 'τ' => 'τ', 'υ' => 'υ', 'φ' => 'φ', 'χ' => 'χ', 'ψ' => 'ψ', + 'ω' => 'ω', 'ϑ' => 'ϑ', 'ϒ' => 'ϒ', 'ϖ' => 'ϖ', ' ' => ' ', ' ' => ' ', ' ' => ' ', '‌' => '‌', '‍' => '‍', '‎' => '‎', + '‏' => '‏', '–' => '–', '—' => '—', '‘' => '‘', '’' => '’', '‚' => '‚', '“' => '“', '”' => '”', '„' => '„', '†' => '†', + '‡' => '‡', '•' => '•', '…' => '…', '‰' => '‰', '′' => '′', '″' => '″', '‹' => '‹', '›' => '›', '‾' => '‾', '⁄' => '⁄', + '€' => '€', 'ℑ' => 'ℑ', '℘' => '℘', 'ℜ' => 'ℜ', '™' => '™', 'ℵ' => 'ℵ', '←' => '←', '↑' => '↑', '→' => '→', '↓' => '↓', + '↔' => '↔', '↵' => '↵', '⇐' => '⇐', '⇑' => '⇑', '⇒' => '⇒', '⇓' => '⇓', '⇔' => '⇔', '∀' => '∀', '∂' => '∂', '∃' => '∃', + '∅' => '∅', '∇' => '∇', '∈' => '∈', '∉' => '∉', '∋' => '∋', '∏' => '∏', '∑' => '∑', '−' => '−', '∗' => '∗', '√' => '√', + '∝' => '∝', '∞' => '∞', '∠' => '∠', '∧' => '∧', '∨' => '∨', '∩' => '∩', '∪' => '∪', '∫' => '∫', '∴' => '∴', '∼' => '∼', + '≅' => '≅', '≈' => '≈', '≠' => '≠', '≡' => '≡', '≤' => '≤', '≥' => '≥', '⊂' => '⊂', '⊃' => '⊃', '⊄' => '⊄', '⊆' => '⊆', + '⊇' => '⊇', '⊕' => '⊕', '⊗' => '⊗', '⊥' => '⊥', '⋅' => '⋅', '⌈' => '⌈', '⌉' => '⌉', '⌊' => '⌊', '⌋' => '⌋', '⟨' => '〈', + '⟩' => '〉', '◊' => '◊', '♠' => '♠', '♣' => '♣', '♥' => '♥', '♦' => '♦' +); +$b2_htmltrans = array_merge($b2_htmltrans,$b2_htmltransbis); + +#Translation of invalid Unicode references range to valid range +$b2_htmltranswinuni = array( + '€' => '€', // the Euro sign + '' => '', + '‚' => '‚', // these are Windows CP1252 specific characters + 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers + '„' => '„', + '…' => '…', + '†' => '†', + '‡' => '‡', + 'ˆ' => 'ˆ', + '‰' => '‰', + 'Š' => 'Š', + '‹' => '‹', + 'Œ' => 'Œ', + '' => '', + 'Ž' => 'ž', + '' => '', + '' => '', + '‘' => '‘', + '’' => '’', + '“' => '“', + '”' => '”', + '•' => '•', + '–' => '–', + '—' => '—', + '˜' => '˜', + '™' => '™', + 'š' => 'š', + '›' => '›', + 'œ' => 'œ', + '' => '', + 'ž' => '', + 'Ÿ' => 'Ÿ' +); + +# these are used for b2's interface design +$tabletop = "\t<table cellspacing=\"0\" cellpadding=\"1\" width=\"85%\" border=\"0\" bgcolor=\"#cccccc\" align=\"center\">\n\t<td align=\"left\">\n\t\t<table cellspacing=\"0\" cellpadding=\"15\" width=\"100%\" border=\"0\"bgcolor=\"#ffffff\" align=\"center\">\n\t\t<td align=\"left\">\n"; +$tablebottom = "\t\t</td>\n\t</table>\n\t</td>\n\t</table>\n"; +$blankline = '<img src="b2-img/blank.gif" width="10" height="5" border="0" /><br />'; + +# on which page are we ? +$PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF']; +$pagenow = explode('/', $PHP_SELF); +$pagenow = trim($pagenow[(sizeof($pagenow)-1)]); +$pagenow = explode('?', $pagenow); +$pagenow = $pagenow[0]; +if (($querystring_start == '/') && ($pagenow != 'b2edit.php')) { + $pagenow = $siteurl.'/'.$blogfilename; +} + +# browser detection +$is_lynx = 0; $is_gecko = 0; $is_winIE = 0; $is_macIE = 0; $is_opera = 0; $is_NS4 = 0; +if (!isset($HTTP_USER_AGENT)) { + $HTTP_USER_AGENT = $HTTP_SERVER_VARS['HTTP_USER_AGENT']; +} +if (preg_match('/Lynx/', $HTTP_USER_AGENT)) { + $is_lynx = 1; +} elseif (preg_match('/Gecko/', $HTTP_USER_AGENT)) { + $is_gecko = 1; +} elseif ((preg_match('/MSIE/', $HTTP_USER_AGENT)) && (preg_match('/Win/', $HTTP_USER_AGENT))) { + $is_winIE = 1; +} elseif ((preg_match('/MSIE/', $HTTP_USER_AGENT)) && (preg_match('/Mac/', $HTTP_USER_AGENT))) { + $is_macIE = 1; +} elseif (preg_match('/Opera/', $HTTP_USER_AGENT)) { + $is_opera = 1; +} elseif ((preg_match('/Nav/', $HTTP_USER_AGENT) ) || (preg_match('/Mozilla\/4\./', $HTTP_USER_AGENT))) { + $is_NS4 = 1; +} +$is_IE = (($is_macIE) || ($is_winIE)); + +# browser-specific javascript corrections +$b2_macIE_correction['in'] = array( + '/\%uFFD4/', '/\%uFFD5/', '/\%uFFD2/', '/\%uFFD3/', + '/\%uFFA5/', '/\%uFFD0/', '/\%uFFD1/', '/\%uFFBD/', + '/\%uFF83%uFFC0/', '/\%uFF83%uFFC1/', '/\%uFF83%uFFC6/', '/\%uFF83%uFFC9/', + '/\%uFFB9/', '/\%uFF81%uFF8C/', '/\%uFF81%uFF8D/', '/\%uFF81%uFFDA/', + '/\%uFFDB/' +); +$b2_macIE_correction['out'] = array( + '‘', '’', '“', '”', + '•', '–', '—', 'Ω', + 'β', 'γ', 'θ', 'λ', + 'π', '′', '″', '∠', + '€' +); +$b2_gecko_correction['in'] = array( + '/\â€/', '/\’/', '/\“/', '/\”/', + '/\•/', '/\–/', '/\—/', '/\Ω/', + '/\β/', '/\Îł/', '/\θ/', '/\λ/', + '/\Ď€/', '/\′/', '/\″/', '/\â/', + '/\€/', '/\ /' +); +$b2_gecko_correction['out'] = array( + '&8216;', '’', '“', '”', + '•', '–', '—', 'Ω', + 'β', 'γ', 'θ', 'λ', + 'π', '′', '″', '∠', + '€', ' ' +); + +# server detection +$is_Apache = strstr($HTTP_SERVER_VARS['SERVER_SOFTWARE'], 'Apache') ? 1 : 0; +$is_IIS = strstr($HTTP_SERVER_VARS['SERVER_SOFTWARE'], 'Microsoft-IIS') ? 1 : 0; + +# if the config file does not provide the smilies array, let's define it here +if (!isset($b2smiliestrans)) { + $b2smiliestrans = array( + ':)' => 'icon_smile.gif', + ':D' => 'icon_biggrin.gif', + ':-D' => 'icon_biggrin.gif', + ':grin:' => 'icon_biggrin.gif', + ':)' => 'icon_smile.gif', + ':-)' => 'icon_smile.gif', + ':smile:' => 'icon_smile.gif', + ':(' => 'icon_sad.gif', + ':-(' => 'icon_sad.gif', + ':sad:' => 'icon_sad.gif', + ':o' => 'icon_surprised.gif', + ':-o' => 'icon_surprised.gif', + ':eek:' => 'icon_surprised.gif', + '8O' => 'icon_eek.gif', + '8-O' => 'icon_eek.gif', + ':shock:' => 'icon_eek.gif', + ':?' => 'icon_confused.gif', + ':-?' => 'icon_confused.gif', + ':???:' => 'icon_confused.gif', + '8)' => 'icon_cool.gif', + '8-)' => 'icon_cool.gif', + ':cool:' => 'icon_cool.gif', + ':lol:' => 'icon_lol.gif', + ':x' => 'icon_mad.gif', + ':-x' => 'icon_mad.gif', + ':mad:' => 'icon_mad.gif', + ':P' => 'icon_razz.gif', + ':-P' => 'icon_razz.gif', + ':razz:' => 'icon_razz.gif', + ':oops:' => 'icon_redface.gif', + ':cry:' => 'icon_cry.gif', + ':evil:' => 'icon_evil.gif', + ':twisted:' => 'icon_twisted.gif', + ':roll:' => 'icon_rolleyes.gif', + ':wink:' => 'icon_wink.gif', + ';)' => 'icon_wink.gif', + ';-)' => 'icon_wink.gif', + ':!:' => 'icon_exclaim.gif', + ':?:' => 'icon_question.gif', + ':idea:' => 'icon_idea.gif', + ':arrow:' => 'icon_arrow.gif', + ':|' => 'icon_neutral.gif', + ':-|' => 'icon_neutral.gif', + ':neutral:' => 'icon_neutral.gif', + ':mrgreen:' => 'icon_mrgreen.gif', + ); +} + +# sorts the smilies' array +if (!function_exists('smiliescmp')) { + function smiliescmp ($a, $b) { + if (strlen($a) == strlen($b)) { + return strcmp($a, $b); + } + return (strlen($a) > strlen($b)) ? -1 : 1; + } +} +uksort($b2smiliestrans, 'smiliescmp'); + +# generates smilies' search & replace arrays +foreach($b2smiliestrans as $smiley => $img) { + $b2_smiliessearch[] = $smiley; + $smiley_masked = ''; + for ($i = 0; $i < strlen($smiley); $i = $i + 1) { + $smiley_masked .= substr($smiley, $i, 1).chr(160); + } + $b2_smiliesreplace[] = "<img src='$smilies_directory/$img' alt='$smiley_masked' />"; +} + +# sets curly quotes on or off from the config +if (isset($use_smartquotes) && ($use_smartquotes)) { + add_filter('all', 'phpcurlme'); +} + +?> \ No newline at end of file diff --git a/b2-include/b2verifauth.php b/b2-include/b2verifauth.php new file mode 100644 index 0000000000..3996d7c615 --- /dev/null +++ b/b2-include/b2verifauth.php @@ -0,0 +1,55 @@ +<?php + +require_once('b2config.php'); + +/* connecting the db */ +$connexion = @mysql_connect($server,$loginsql,$passsql) or die("Can't connect to the database<br>".mysql_error()); +mysql_select_db("$base"); + +/* checking login & pass in the database */ +function veriflog() { + global $HTTP_COOKIE_VARS; + global $tableusers,$tablesettings,$tablecategories,$tableposts,$tablecomments; + + if (!empty($HTTP_COOKIE_VARS["cafeloguser"])) { + $user_login = $HTTP_COOKIE_VARS["cafeloguser"]; + $user_pass_md5 = $HTTP_COOKIE_VARS["cafelogpass"]; + } else { + return false; + } + + if (!($user_login != "")) + return false; + if (!$user_pass_md5) + return false; + + $query = " SELECT user_login, user_pass FROM $tableusers WHERE user_login = '$user_login' "; + $result = @mysql_query($query) or die("Query: $query<br /><br />Error: ".mysql_error()); + + $lines = mysql_num_rows($result); + if ($lines<1) { + return false; + } else { + $res=mysql_fetch_row($result); + if ($res[0]==$user_login && md5($res[1])==$user_pass_md5) { + return true; + } else { + return false; + } + } +} +#if ( $user_login!="" && $user_pass!="" && $id_session!="" && $adresse_ip==$REMOTE_ADDR) { +# if ( !(veriflog()) AND !(verifcookielog()) ) { + if (!(veriflog())) { + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header("Cache-Control: no-cache, must-revalidate"); + header("Pragma: no-cache"); + if (!empty($HTTP_COOKIE_VARS["cafeloguser"])) { + $error="<b>Error</b>: wrong login or password"; + } + include("b2login.php"); + exit(); + } +#} +?> \ No newline at end of file diff --git a/b2-include/class.POP3.php b/b2-include/class.POP3.php new file mode 100644 index 0000000000..a8691c54e6 --- /dev/null +++ b/b2-include/class.POP3.php @@ -0,0 +1,680 @@ +<?php + + /** + * mail_fetch/setup.php + * + * Copyright (c) 1999-2002 The SquirrelMail Project Team + * + * Copyright (c) 1999 CDI (cdi@thewebmasters.net) All Rights Reserved + * Modified by Philippe Mingo 2001 mingo@rotedic.com + * An RFC 1939 compliant wrapper class for the POP3 protocol. + * + * Licensed under the GNU GPL. For full terms see the file COPYING. + * + * pop3 class + * + * $Id$ + */ + +class POP3 { + var $ERROR = ''; // Error string. + + var $TIMEOUT = 60; // Default timeout before giving up on a + // network operation. + + var $COUNT = -1; // Mailbox msg count + + var $BUFFER = 512; // Socket buffer for socket fgets() calls. + // Per RFC 1939 the returned line a POP3 + // server can send is 512 bytes. + + var $FP = ''; // The connection to the server's + // file descriptor + + var $MAILSERVER = ''; // Set this to hard code the server name + + var $DEBUG = FALSE; // set to true to echo pop3 + // commands and responses to error_log + // this WILL log passwords! + + var $BANNER = ''; // Holds the banner returned by the + // pop server - used for apop() + + var $RFC1939 = TRUE; // Set by noop(). See rfc1939.txt + // + + var $ALLOWAPOP = FALSE; // Allow or disallow apop() + // This must be set to true + // manually + + function POP3 ( $server = '', $timeout = '' ) { + settype($this->BUFFER,"integer"); + if( !empty($server) ) { + // Do not allow programs to alter MAILSERVER + // if it is already specified. They can get around + // this if they -really- want to, so don't count on it. + if(empty($this->MAILSERVER)) + $this->MAILSERVER = $server; + } + if(!empty($timeout)) { + settype($timeout,"integer"); + $this->TIMEOUT = $timeout; + set_time_limit($timeout); + } + return true; + } + + function update_timer () { + set_time_limit($this->TIMEOUT); + return true; + } + + function connect ($server, $port = 110) { + // Opens a socket to the specified server. Unless overridden, + // port defaults to 110. Returns true on success, false on fail + + // If MAILSERVER is set, override $server with it's value + + if(!empty($this->MAILSERVER)) + $server = $this->MAILSERVER; + + if(empty($server)){ + $this->ERROR = _("POP3 connect:") . ' ' . _("No server specified"); + unset($this->FP); + return false; + } + + $fp = fsockopen("$server", $port, $errno, $errstr); + + if(!$fp) { + $this->ERROR = _("POP3 connect:") . ' ' . _("Error ") . "[$errno] [$errstr]"; + unset($this->FP); + return false; + } + + socket_set_blocking($fp,-1); + $this->update_timer(); + $reply = fgets($fp,$this->BUFFER); + $reply = $this->strip_clf($reply); + if($this->DEBUG) + error_log("POP3 SEND [connect: $server] GOT [$reply]",0); + if(!$this->is_ok($reply)) { + $this->ERROR = _("POP3 connect:") . ' ' . _("Error ") . "[$reply]"; + unset($this->FP); + return false; + } + $this->FP = $fp; + $this->BANNER = $this->parse_banner($reply); + $this->RFC1939 = $this->noop(); + if($this->RFC1939) { + $this->ERROR = _("POP3: premature NOOP OK, NOT an RFC 1939 Compliant server"); + $this->quit(); + return false; + } else + return true; + } + + function noop () { + + if(!isset($this->FP)) { + $this->ERROR = _("POP3 noop:") . ' ' . _("No connection to server"); + return false; + } else { + $cmd = "NOOP"; + $reply = $this->send_cmd( $cmd ); + return( $this->is_ok( $reply ) ); + } + } + + function user ($user = "") { + // Sends the USER command, returns true or false + + if( empty($user) ) { + $this->ERROR = _("POP3 user:") . ' ' . _("no login ID submitted"); + return false; + } elseif(!isset($this->FP)) { + $this->ERROR = _("POP3 user:") . ' ' . _("connection not established"); + return false; + } else { + $reply = $this->send_cmd("USER $user"); + if(!$this->is_ok($reply)) { + $this->ERROR = _("POP3 user:") . ' ' . _("Error ") . "[$reply]"; + return false; + } else + return true; + } + } + + function pass ($pass = "") { + // Sends the PASS command, returns # of msgs in mailbox, + // returns false (undef) on Auth failure + + if(empty($pass)) { + $this->ERROR = _("POP3 pass:") . ' ' . _("No password submitted"); + return false; + } elseif(!isset($this->FP)) { + $this->ERROR = _("POP3 pass:") . ' ' . _("connection not established"); + return false; + } else { + $reply = $this->send_cmd("PASS $pass"); + if(!$this->is_ok($reply)) { + $this->ERROR = _("POP3 pass:") . ' ' . _("authentication failed ") . "[$reply]"; + $this->quit(); + return false; + } else { + // Auth successful. + $count = $this->last("count"); + $this->COUNT = $count; + $this->RFC1939 = $this->noop(); + if(!$this->RFC1939) { + $this->ERROR = _("POP3 pass:") . ' ' . _("NOOP failed. Server not RFC 1939 compliant"); + $this->quit(); + return false; + } else + return $count; + } + } + } + + function apop ($login,$pass) { + // Attempts an APOP login. If this fails, it'll + // try a standard login. YOUR SERVER MUST SUPPORT + // THE USE OF THE APOP COMMAND! + // (apop is optional per rfc1939) + + if(!isset($this->FP)) { + $this->ERROR = _("POP3 apop:") . ' ' . _("No connection to server"); + return false; + } elseif(!$this->ALLOWAPOP) { + $retVal = $this->login($login,$pass); + return $retVal; + } elseif(empty($login)) { + $this->ERROR = _("POP3 apop:") . ' ' . _("No login ID submitted"); + return false; + } elseif(empty($pass)) { + $this->ERROR = _("POP3 apop:") . ' ' . _("No password submitted"); + return false; + } else { + $banner = $this->BANNER; + if( (!$banner) or (empty($banner)) ) { + $this->ERROR = _("POP3 apop:") . ' ' . _("No server banner") . ' - ' . _("abort"); + $retVal = $this->login($login,$pass); + return $retVal; + } else { + $AuthString = $banner; + $AuthString .= $pass; + $APOPString = md5($AuthString); + $cmd = "APOP $login $APOPString"; + $reply = $this->send_cmd($cmd); + if(!$this->is_ok($reply)) { + $this->ERROR = _("POP3 apop:") . ' ' . _("apop authentication failed") . ' - ' . _("abort"); + $retVal = $this->login($login,$pass); + return $retVal; + } else { + // Auth successful. + $count = $this->last("count"); + $this->COUNT = $count; + $this->RFC1939 = $this->noop(); + if(!$this->RFC1939) { + $this->ERROR = _("POP3 apop:") . ' ' . _("NOOP failed. Server not RFC 1939 compliant"); + $this->quit(); + return false; + } else + return $count; + } + } + } + } + + function login ($login = "", $pass = "") { + // Sends both user and pass. Returns # of msgs in mailbox or + // false on failure (or -1, if the error occurs while getting + // the number of messages.) + + if( !isset($this->FP) ) { + $this->ERROR = _("POP3 login:") . ' ' . _("No connection to server"); + return false; + } else { + $fp = $this->FP; + if( !$this->user( $login ) ) { + // Preserve the error generated by user() + return false; + } else { + $count = $this->pass($pass); + if( (!$count) || ($count == -1) ) { + // Preserve the error generated by last() and pass() + return false; + } else + return $count; + } + } + } + + function top ($msgNum, $numLines = "0") { + // Gets the header and first $numLines of the msg body + // returns data in an array with each returned line being + // an array element. If $numLines is empty, returns + // only the header information, and none of the body. + + if(!isset($this->FP)) { + $this->ERROR = _("POP3 top:") . ' ' . _("No connection to server"); + return false; + } + $this->update_timer(); + + $fp = $this->FP; + $buffer = $this->BUFFER; + $cmd = "TOP $msgNum $numLines"; + fwrite($fp, "TOP $msgNum $numLines\r\n"); + $reply = fgets($fp, $buffer); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { + @error_log("POP3 SEND [$cmd] GOT [$reply]",0); + } + if(!$this->is_ok($reply)) + { + $this->ERROR = _("POP3 top:") . ' ' . _("Error ") . "[$reply]"; + return false; + } + + $count = 0; + $MsgArray = array(); + + $line = fgets($fp,$buffer); + while ( !ereg("^\.\r\n",$line)) + { + $MsgArray[$count] = $line; + $count++; + $line = fgets($fp,$buffer); + if(empty($line)) { break; } + } + + return $MsgArray; + } + + function pop_list ($msgNum = "") { + // If called with an argument, returns that msgs' size in octets + // No argument returns an associative array of undeleted + // msg numbers and their sizes in octets + + if(!isset($this->FP)) + { + $this->ERROR = _("POP3 pop_list:") . ' ' . _("No connection to server"); + return false; + } + $fp = $this->FP; + $Total = $this->COUNT; + if( (!$Total) or ($Total == -1) ) + { + return false; + } + if($Total == 0) + { + return array("0","0"); + // return -1; // mailbox empty + } + + $this->update_timer(); + + if(!empty($msgNum)) + { + $cmd = "LIST $msgNum"; + fwrite($fp,"$cmd\r\n"); + $reply = fgets($fp,$this->BUFFER); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { + @error_log("POP3 SEND [$cmd] GOT [$reply]",0); + } + if(!$this->is_ok($reply)) + { + $this->ERROR = _("POP3 pop_list:") . ' ' . _("Error ") . "[$reply]"; + return false; + } + list($junk,$num,$size) = explode(" ",$reply); + return $size; + } + $cmd = "LIST"; + $reply = $this->send_cmd($cmd); + if(!$this->is_ok($reply)) + { + $reply = $this->strip_clf($reply); + $this->ERROR = _("POP3 pop_list:") . ' ' . _("Error ") . "[$reply]"; + return false; + } + $MsgArray = array(); + $MsgArray[0] = $Total; + for($msgC=1;$msgC <= $Total; $msgC++) + { + if($msgC > $Total) { break; } + $line = fgets($fp,$this->BUFFER); + $line = $this->strip_clf($line); + if(ereg("^\.",$line)) + { + $this->ERROR = _("POP3 pop_list:") . ' ' . _("Premature end of list"); + return false; + } + list($thisMsg,$msgSize) = explode(" ",$line); + settype($thisMsg,"integer"); + if($thisMsg != $msgC) + { + $MsgArray[$msgC] = "deleted"; + } + else + { + $MsgArray[$msgC] = $msgSize; + } + } + return $MsgArray; + } + + function get ($msgNum) { + // Retrieve the specified msg number. Returns an array + // where each line of the msg is an array element. + + if(!isset($this->FP)) + { + $this->ERROR = _("POP3 get:") . ' ' . _("No connection to server"); + return false; + } + + $this->update_timer(); + + $fp = $this->FP; + $buffer = $this->BUFFER; + $cmd = "RETR $msgNum"; + $reply = $this->send_cmd($cmd); + + if(!$this->is_ok($reply)) + { + $this->ERROR = _("POP3 get:") . ' ' . _("Error ") . "[$reply]"; + return false; + } + + $count = 0; + $MsgArray = array(); + + $line = fgets($fp,$buffer); + while ( !ereg("^\.\r\n",$line)) + { + $MsgArray[$count] = $line; + $count++; + $line = fgets($fp,$buffer); + if(empty($line)) { break; } + } + return $MsgArray; + } + + function last ( $type = "count" ) { + // Returns the highest msg number in the mailbox. + // returns -1 on error, 0+ on success, if type != count + // results in a popstat() call (2 element array returned) + + $last = -1; + if(!isset($this->FP)) + { + $this->ERROR = _("POP3 last:") . ' ' . _("No connection to server"); + return $last; + } + + $reply = $this->send_cmd("STAT"); + if(!$this->is_ok($reply)) + { + $this->ERROR = _("POP3 last:") . ' ' . _("Error ") . "[$reply]"; + return $last; + } + + $Vars = explode(" ",$reply); + $count = $Vars[1]; + $size = $Vars[2]; + settype($count,"integer"); + settype($size,"integer"); + if($type != "count") + { + return array($count,$size); + } + return $count; + } + + function reset () { + // Resets the status of the remote server. This includes + // resetting the status of ALL msgs to not be deleted. + // This method automatically closes the connection to the server. + + if(!isset($this->FP)) + { + $this->ERROR = _("POP3 reset:") . ' ' . _("No connection to server"); + return false; + } + $reply = $this->send_cmd("RSET"); + if(!$this->is_ok($reply)) + { + // The POP3 RSET command -never- gives a -ERR + // response - if it ever does, something truely + // wild is going on. + + $this->ERROR = _("POP3 reset:") . ' ' . _("Error ") . "[$reply]"; + @error_log("POP3 reset: ERROR [$reply]",0); + } + $this->quit(); + return true; + } + + function send_cmd ( $cmd = "" ) + { + // Sends a user defined command string to the + // POP server and returns the results. Useful for + // non-compliant or custom POP servers. + // Do NOT includ the \r\n as part of your command + // string - it will be appended automatically. + + // The return value is a standard fgets() call, which + // will read up to $this->BUFFER bytes of data, until it + // encounters a new line, or EOF, whichever happens first. + + // This method works best if $cmd responds with only + // one line of data. + + if(!isset($this->FP)) + { + $this->ERROR = _("POP3 send_cmd:") . ' ' . _("No connection to server"); + return false; + } + + if(empty($cmd)) + { + $this->ERROR = _("POP3 send_cmd:") . ' ' . _("Empty command string"); + return ""; + } + + $fp = $this->FP; + $buffer = $this->BUFFER; + $this->update_timer(); + fwrite($fp,"$cmd\r\n"); + $reply = fgets($fp,$buffer); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); } + return $reply; + } + + function quit() { + // Closes the connection to the POP3 server, deleting + // any msgs marked as deleted. + + if(!isset($this->FP)) + { + $this->ERROR = _("POP3 quit:") . ' ' . _("connection does not exist"); + return false; + } + $fp = $this->FP; + $cmd = "QUIT"; + fwrite($fp,"$cmd\r\n"); + $reply = fgets($fp,$this->BUFFER); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); } + fclose($fp); + unset($this->FP); + return true; + } + + function popstat () { + // Returns an array of 2 elements. The number of undeleted + // msgs in the mailbox, and the size of the mbox in octets. + + $PopArray = $this->last("array"); + + if($PopArray == -1) { return false; } + + if( (!$PopArray) or (empty($PopArray)) ) + { + return false; + } + return $PopArray; + } + + function uidl ($msgNum = "") + { + // Returns the UIDL of the msg specified. If called with + // no arguments, returns an associative array where each + // undeleted msg num is a key, and the msg's uidl is the element + // Array element 0 will contain the total number of msgs + + if(!isset($this->FP)) { + $this->ERROR = _("POP3 uidl:") . ' ' . _("No connection to server"); + return false; + } + + $fp = $this->FP; + $buffer = $this->BUFFER; + + if(!empty($msgNum)) { + $cmd = "UIDL $msgNum"; + $reply = $this->send_cmd($cmd); + if(!$this->is_ok($reply)) + { + $this->ERROR = _("POP3 uidl:") . ' ' . _("Error ") . "[$reply]"; + return false; + } + list ($ok,$num,$myUidl) = explode(" ",$reply); + return $myUidl; + } else { + $this->update_timer(); + + $UIDLArray = array(); + $Total = $this->COUNT; + $UIDLArray[0] = $Total; + + if ($Total < 1) + { + return $UIDLArray; + } + $cmd = "UIDL"; + fwrite($fp, "UIDL\r\n"); + $reply = fgets($fp, $buffer); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); } + if(!$this->is_ok($reply)) + { + $this->ERROR = _("POP3 uidl:") . ' ' . _("Error ") . "[$reply]"; + return false; + } + + $line = ""; + $count = 1; + $line = fgets($fp,$buffer); + while ( !ereg("^\.\r\n",$line)) { + if(ereg("^\.\r\n",$line)) { + break; + } + list ($msg,$msgUidl) = explode(" ",$line); + $msgUidl = $this->strip_clf($msgUidl); + if($count == $msg) { + $UIDLArray[$msg] = $msgUidl; + } + else + { + $UIDLArray[$count] = 'deleted'; + } + $count++; + $line = fgets($fp,$buffer); + } + } + return $UIDLArray; + } + + function delete ($msgNum = "") { + // Flags a specified msg as deleted. The msg will not + // be deleted until a quit() method is called. + + if(!isset($this->FP)) + { + $this->ERROR = _("POP3 delete:") . ' ' . _("No connection to server"); + return false; + } + if(empty($msgNum)) + { + $this->ERROR = _("POP3 delete:") . ' ' . _("No msg number submitted"); + return false; + } + $reply = $this->send_cmd("DELE $msgNum"); + if(!$this->is_ok($reply)) + { + $this->ERROR = _("POP3 delete:") . ' ' . _("Command failed ") . "[$reply]"; + return false; + } + return true; + } + + // ********************************************************* + + // The following methods are internal to the class. + + function is_ok ($cmd = "") { + // Return true or false on +OK or -ERR + + if( empty($cmd) ) + return false; + else + return( ereg ("^\+OK", $cmd ) ); + } + + function strip_clf ($text = "") { + // Strips \r\n from server responses + + if(empty($text)) + return $text; + else { + $stripped = str_replace("\r",'',$text); + $stripped = str_replace("\n",'',$stripped); + return $stripped; + } + } + + function parse_banner ( $server_text ) { + $outside = true; + $banner = ""; + $length = strlen($server_text); + for($count =0; $count < $length; $count++) + { + $digit = substr($server_text,$count,1); + if(!empty($digit)) { + if( (!$outside) && ($digit != '<') && ($digit != '>') ) + { + $banner .= $digit; + } + if ($digit == '<') + { + $outside = false; + } + if($digit == '>') + { + $outside = true; + } + } + } + $banner = $this->strip_clf($banner); // Just in case + return "<$banner>"; + } + +} // End class + +?> diff --git a/b2-include/xmlrpc.inc b/b2-include/xmlrpc.inc new file mode 100644 index 0000000000..7e9b4ae2a6 --- /dev/null +++ b/b2-include/xmlrpc.inc @@ -0,0 +1,1149 @@ +<?php // -*-c++-*- +// by Edd Dumbill (C) 1999-2001 +// <edd@usefulinc.com> +// $Id$ + + +# additional fixes for case of missing xml extension file by Michel Valdrighi <m@tidakada.com> + + +// Copyright (c) 1999,2000,2001 Edd Dumbill. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// +// * Neither the name of the "XML-RPC for PHP" nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + + +# b2 fix. some servers have stupid warnings +#error_reporting(0); + +if (!function_exists('logIO')) { + function logIO($m="",$n="") { + return(true); + } +} + + +if (!function_exists('xml_parser_create')) { +// Win 32 fix. From: "Leo West" <lwest@imaginet.fr> +// Fix for missing extension file. From: "Michel Valdrighi" <m@tidakada.com> + if($WINDIR) { + if (@dl("php3_xml.dll")) { + define("CANUSEXMLRPC", 1); + } else { + define("CANUSEXMLRPC", 0); + } + } else { + if (@dl("xml.so")) { + define("CANUSEXMLRPC", 1); + } else { + define("CANUSEXMLRPC", 0); + } + } +} else { + define("CANUSEXMLRPC", 1); +} + +if (CANUSEXMLRPC == 1) { + +$xmlrpcI4="i4"; +$xmlrpcInt="int"; +$xmlrpcBoolean="boolean"; +$xmlrpcDouble="double"; +$xmlrpcString="string"; +$xmlrpcDateTime="dateTime.iso8601"; +$xmlrpcBase64="base64"; +$xmlrpcArray="array"; +$xmlrpcStruct="struct"; + + +$xmlrpcTypes=array($xmlrpcI4 => 1, + $xmlrpcInt => 1, + $xmlrpcBoolean => 1, + $xmlrpcString => 1, + $xmlrpcDouble => 1, + $xmlrpcDateTime => 1, + $xmlrpcBase64 => 1, + $xmlrpcArray => 2, + $xmlrpcStruct => 3); + +$xmlEntities=array( "amp" => "&", + "quot" => '"', + "lt" => "<", + "gt" => ">", + "apos" => "'"); + +$xmlrpcerr["unknown_method"]=1; +$xmlrpcstr["unknown_method"]="Unknown method"; +$xmlrpcerr["invalid_return"]=2; +$xmlrpcstr["invalid_return"]="Invalid return payload: enabling debugging to examine incoming payload"; +$xmlrpcerr["incorrect_params"]=3; +$xmlrpcstr["incorrect_params"]="Incorrect parameters passed to method"; +$xmlrpcerr["introspect_unknown"]=4; +$xmlrpcstr["introspect_unknown"]="Can't introspect: method unknown"; +$xmlrpcerr["http_error"]=5; +$xmlrpcstr["http_error"]="Didn't receive 200 OK from remote server."; +$xmlrpcerr["no_data"]=6; +$xmlrpcstr["no_data"]="No data received from server."; +$xmlrpcerr["no_ssl"]=7; +$xmlrpcstr["no_ssl"]="No SSL support compiled in."; +$xmlrpcerr["curl_fail"]=8; +$xmlrpcstr["curl_fail"]="CURL error"; + +$xmlrpc_defencoding="UTF-8"; + +$xmlrpcName="XML-RPC for PHP"; +$xmlrpcVersion="1.02"; + +// let user errors start at 800 +$xmlrpcerruser=800; +// let XML parse errors start at 100 +$xmlrpcerrxml=100; + +// formulate backslashes for escaping regexp +$xmlrpc_backslash=chr(92).chr(92); + +// used to store state during parsing +// quick explanation of components: +// st - used to build up a string for evaluation +// ac - used to accumulate values +// qt - used to decide if quotes are needed for evaluation +// cm - used to denote struct or array (comma needed) +// isf - used to indicate a fault +// lv - used to indicate "looking for a value": implements +// the logic to allow values with no types to be strings +// params - used to store parameters in method calls +// method - used to store method name + +$_xh=array(); + +function xmlrpc_entity_decode($string) { + $top=split("&", $string); + $op=""; + $i=0; + while($i<sizeof($top)) { + if (ereg("^([#a-zA-Z0-9]+);", $top[$i], $regs)) { + $op.=ereg_replace("^[#a-zA-Z0-9]+;", + xmlrpc_lookup_entity($regs[1]), + $top[$i]); + } else { + if ($i==0) + $op=$top[$i]; + else + $op.="&" . $top[$i]; + } + $i++; + } + return $op; +} + +function xmlrpc_lookup_entity($ent) { + global $xmlEntities; + + if (isset($xmlEntities[strtolower($ent)])) + return $xmlEntities[strtolower($ent)]; + if (ereg("^#([0-9]+)$", $ent, $regs)) + return chr($regs[1]); + return "?"; +} + +function xmlrpc_se($parser, $name, $attrs) { + global $_xh, $xmlrpcDateTime, $xmlrpcString; + + switch($name) { + case "STRUCT": + case "ARRAY": + $_xh[$parser]['st'].="array("; + $_xh[$parser]['cm']++; + // this last line turns quoting off + // this means if we get an empty array we'll + // simply get a bit of whitespace in the eval + $_xh[$parser]['qt']=0; + break; + case "NAME": + $_xh[$parser]['st'].="'"; $_xh[$parser]['ac']=""; + break; + case "FAULT": + $_xh[$parser]['isf']=1; + break; + case "PARAM": + $_xh[$parser]['st']=""; + break; + case "VALUE": + $_xh[$parser]['st'].="new xmlrpcval("; + $_xh[$parser]['vt']=$xmlrpcString; + $_xh[$parser]['ac']=""; + $_xh[$parser]['qt']=0; + $_xh[$parser]['lv']=1; + // look for a value: if this is still 1 by the + // time we reach the first data segment then the type is string + // by implication and we need to add in a quote + break; + + case "I4": + case "INT": + case "STRING": + case "BOOLEAN": + case "DOUBLE": + case "DATETIME.ISO8601": + case "BASE64": + $_xh[$parser]['ac']=""; // reset the accumulator + + if ($name=="DATETIME.ISO8601" || $name=="STRING") { + $_xh[$parser]['qt']=1; + if ($name=="DATETIME.ISO8601") + $_xh[$parser]['vt']=$xmlrpcDateTime; + } else if ($name=="BASE64") { + $_xh[$parser]['qt']=2; + } else { + // No quoting is required here -- but + // at the end of the element we must check + // for data format errors. + $_xh[$parser]['qt']=0; + } + break; + case "MEMBER": + $_xh[$parser]['ac']=""; + break; + default: + break; + } + + if ($name!="VALUE") $_xh[$parser]['lv']=0; +} + +function xmlrpc_ee($parser, $name) { + global $_xh,$xmlrpcTypes,$xmlrpcString; + + switch($name) { + case "STRUCT": + case "ARRAY": + if ($_xh[$parser]['cm'] && substr($_xh[$parser]['st'], -1) ==',') { + $_xh[$parser]['st']=substr($_xh[$parser]['st'],0,-1); + } + $_xh[$parser]['st'].=")"; + $_xh[$parser]['vt']=strtolower($name); + $_xh[$parser]['cm']--; + break; + case "NAME": + $_xh[$parser]['st'].= $_xh[$parser]['ac'] . "' => "; + break; + case "BOOLEAN": + // special case here: we translate boolean 1 or 0 into PHP + // constants true or false + if ($_xh[$parser]['ac']=='1') + $_xh[$parser]['ac']="true"; + else + $_xh[$parser]['ac']="false"; + $_xh[$parser]['vt']=strtolower($name); + // Drop through intentionally. + case "I4": + case "INT": + case "STRING": + case "DOUBLE": + case "DATETIME.ISO8601": + case "BASE64": + if ($_xh[$parser]['qt']==1) { + // we use double quotes rather than single so backslashification works OK + $_xh[$parser]['st'].="\"". $_xh[$parser]['ac'] . "\""; + } else if ($_xh[$parser]['qt']==2) { + $_xh[$parser]['st'].="base64_decode('". $_xh[$parser]['ac'] . "')"; + } else if ($name=="BOOLEAN") { + $_xh[$parser]['st'].=$_xh[$parser]['ac']; + } else { + // we have an I4, INT or a DOUBLE + // we must check that only 0123456789-.<space> are characters here + if (!ereg("^\-?[0123456789 \t\.]+$", $_xh[$parser]['ac'])) { + // TODO: find a better way of throwing an error + // than this! + error_log("XML-RPC: non numeric value received in INT or DOUBLE"); + $_xh[$parser]['st'].="ERROR_NON_NUMERIC_FOUND"; + } else { + // it's ok, add it on + $_xh[$parser]['st'].=$_xh[$parser]['ac']; + } + } + $_xh[$parser]['ac']=""; $_xh[$parser]['qt']=0; + $_xh[$parser]['lv']=3; // indicate we've found a value + break; + case "VALUE": + // deal with a string value + if (strlen($_xh[$parser]['ac'])>0 && + $_xh[$parser]['vt']==$xmlrpcString) { + $_xh[$parser]['st'].="\"". $_xh[$parser]['ac'] . "\""; + } + // This if() detects if no scalar was inside <VALUE></VALUE> + // and pads an empty "". + if($_xh[$parser]['st'][strlen($_xh[$parser]['st'])-1] == '(') { + $_xh[$parser]['st'].= '""'; + } + $_xh[$parser]['st'].=", '" . $_xh[$parser]['vt'] . "')"; + if ($_xh[$parser]['cm']) $_xh[$parser]['st'].=","; + break; + case "MEMBER": + $_xh[$parser]['ac']=""; $_xh[$parser]['qt']=0; + break; + case "DATA": + $_xh[$parser]['ac']=""; $_xh[$parser]['qt']=0; + break; + case "PARAM": + $_xh[$parser]['params'][]=$_xh[$parser]['st']; + break; + case "METHODNAME": + $_xh[$parser]['method']=ereg_replace("^[\n\r\t ]+", "", + $_xh[$parser]['ac']); + break; + case "BOOLEAN": + // special case here: we translate boolean 1 or 0 into PHP + // constants true or false + if ($_xh[$parser]['ac']=='1') + $_xh[$parser]['ac']="true"; + else + $_xh[$parser]['ac']="false"; + $_xh[$parser]['vt']=strtolower($name); + break; + default: + break; + } + // if it's a valid type name, set the type + if (isset($xmlrpcTypes[strtolower($name)])) { + $_xh[$parser]['vt']=strtolower($name); + } + +} + +function xmlrpc_cd($parser, $data) +{ + global $_xh, $xmlrpc_backslash; + + //if (ereg("^[\n\r \t]+$", $data)) return; + // print "adding [${data}]\n"; + + if ($_xh[$parser]['lv']!=3) { + // "lookforvalue==3" means that we've found an entire value + // and should discard any further character data + if ($_xh[$parser]['lv']==1) { + // if we've found text and we're just in a <value> then + // turn quoting on, as this will be a string + $_xh[$parser]['qt']=1; + // and say we've found a value + $_xh[$parser]['lv']=2; + } + // replace characters that eval would + // do special things with + $_xh[$parser]['ac'].=str_replace('$', '\$', + str_replace('"', '\"', str_replace(chr(92), + $xmlrpc_backslash, $data))); + } +} + +function xmlrpc_dh($parser, $data) +{ + global $_xh; + if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") { + if ($_xh[$parser]['lv']==1) { + $_xh[$parser]['qt']=1; + $_xh[$parser]['lv']=2; + } + $_xh[$parser]['ac'].=str_replace('$', '\$', + str_replace('"', '\"', str_replace(chr(92), + $xmlrpc_backslash, $data))); + } +} + +class xmlrpc_client { + var $path; + var $server; + var $port; + var $errno; + var $errstring; + var $debug=0; + var $username=""; + var $password=""; + var $cert=""; + var $certpass=""; + + function xmlrpc_client($path, $server, $port=0) { + $this->port=$port; $this->server=$server; $this->path=$path; + } + + function setDebug($in) { + if ($in) { + $this->debug=1; + } else { + $this->debug=0; + } + } + + function setCredentials($u, $p) { + $this->username=$u; + $this->password=$p; + } + + function setCertificate($cert, $certpass) { + $this->cert = $cert; + $this->certpass = $certpass; + } + + function send($msg, $timeout=0, $method='http') { + // where msg is an xmlrpcmsg + $msg->debug=$this->debug; + + if ($method == 'https') { + return $this->sendPayloadHTTPS($msg, + $this->server, + $this->port, $timeout, + $this->username, $this->password, + $this->cert, + $this->certpass); + } else { + return $this->sendPayloadHTTP10($msg, $this->server, $this->port, + $timeout, $this->username, + $this->password); + } + } + + function sendPayloadHTTP10($msg, $server, $port, $timeout=0, + $username="", $password="") { + if ($port==0) $port=80; + if($timeout>0) + $fp=@fsockopen($server, $port, + $this->errno, $this->errstr, $timeout); +# $fp=@fsockopen($server, $port, +# &$this->errno, &$this->errstr, $timeout); + else + $fp=@fsockopen($server, $port, + $this->errno, $this->errstr); +# $fp=@fsockopen($server, $port, +# &$this->errno, &$this->errstr); + if (!$fp) { + return 0; + } + // Only create the payload if it was not created previously + if(empty($msg->payload)) $msg->createPayload(); + + // thanks to Grant Rauscher <grant7@firstworld.net> + // for this + $credentials=""; + if ($username!="") { + $credentials="Authorization: Basic " . + base64_encode($username . ":" . $password) . "\r\n"; + } + + $op= "POST " . $this->path. " HTTP/1.0\r\nUser-Agent: PHP XMLRPC 1.0\r\n" . + "Host: ". $this->server . "\r\n" . + $credentials . + "Content-Type: text/xml\r\nContent-Length: " . + strlen($msg->payload) . "\r\n\r\n" . + $msg->payload; + + if (!fputs($fp, $op, strlen($op))) { + $this->errstr="Write error"; + return 0; + } + $resp=$msg->parseResponseFile($fp); + fclose($fp); + return $resp; + } + + // contributed by Justin Miller <justin@voxel.net> + // requires curl to be built into PHP + function sendPayloadHTTPS($msg, $server, $port, $timeout=0, + $username="", $password="", $cert="", + $certpass="") { + global $xmlrpcerr, $xmlrpcstr; + if ($port == 0) $port = 443; + + // Only create the payload if it was not created previously + if(empty($msg->payload)) $msg->createPayload(); + + if (!function_exists("curl_init")) { + $r=new xmlrpcresp(0, $xmlrpcerr["no_ssl"], + $xmlrpcstr["no_ssl"]); + return $r; + } + + $curl = curl_init("https://" . $server . ':' . $port . + $this->path); + + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + // results into variable + if ($this->debug) { + curl_setopt($curl, CURLOPT_VERBOSE, 1); + } + curl_setopt($curl, CURLOPT_USERAGENT, 'PHP XMLRPC 1.0'); + // required for XMLRPC + curl_setopt($curl, CURLOPT_POST, 1); + // post the data + curl_setopt($curl, CURLOPT_POSTFIELDS, $msg->payload); + // the data + curl_setopt($curl, CURLOPT_HEADER, 1); + // return the header too + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); + // required for XMLRPC + if ($timeout) curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : + $timeout - 1); + // timeout is borked + if ($username && $password) curl_setopt($curl, CURLOPT_USERPWD, + "$username:$password"); + // set auth stuff + if ($cert) curl_setopt($curl, CURLOPT_SSLCERT, $cert); + // set cert file + if ($certpass) curl_setopt($curl, CURLOPT_SSLCERTPASSWD, + $certpass); + // set cert password + + $result = curl_exec($curl); + + if (!$result) { + $resp=new xmlrpcresp(0, + $xmlrpcerr["curl_fail"], + $xmlrpcstr["curl_fail"]. ": ". + curl_error($curl)); + } else { + $resp = $msg->parseResponse($result); + } + curl_close($curl); + return $resp; + } + +} // end class xmlrpc_client + +class xmlrpcresp { + var $xv; + var $fn; + var $fs; + var $hdrs; + + function xmlrpcresp($val, $fcode=0, $fstr="") { + if ($fcode!=0) { + $this->xv=0; + $this->fn=$fcode; + $this->fs=trim(htmlspecialchars($fstr)); + logIO("O",$this->fs); + } else { + $this->xv=$val; + $this->fn=0; + } + } + + function faultCode() { + if (isset($this->fn)) + return $this->fn; + else + return 0; + } + + function faultString() { return $this->fs; } + function value() { return $this->xv; } + + function serialize() { + $rs="<methodResponse>"; + if ($this->fn) { + $rs.="<fault> + <value> + <struct> + <member> + <name>faultCode</name> + <value><int>" . $this->fn . "</int></value> + </member> + <member> + <name>faultString</name> + <value><string>" . $this->fs . "</string></value> + </member> + </struct> + </value> +</fault>"; + } else { + $rs.="<params><param>" . $this->xv->serialize() . + "</param></params>"; + } + $rs.="</methodResponse>"; + + /* begin Logging + $f=fopen("xmlrpc/xmlrpc.log","a+"); + fwrite($f, date("Ymd H:i:s")."\n\nResponse:\n\n".$rs); + fclose($f); + end Logging */ + logIO("O",$rs); + + return $rs; + } +} + +class xmlrpcmsg { + var $payload; + var $methodname; + var $params=array(); + var $debug=0; + + function xmlrpcmsg($meth, $pars=0) { + $this->methodname=$meth; + if (is_array($pars) && sizeof($pars)>0) { + for($i=0; $i<sizeof($pars); $i++) + $this->addParam($pars[$i]); + } + } + + function xml_header() { + return "<?xml version=\"1.0\"?".">\n<methodCall>\n"; + } + + function xml_footer() { + return "</methodCall>\n"; + } + + function createPayload() { + $this->payload=$this->xml_header(); + $this->payload.="<methodName>" . $this->methodname . "</methodName>\n"; + // if (sizeof($this->params)) { + $this->payload.="<params>\n"; + for($i=0; $i<sizeof($this->params); $i++) { + $p=$this->params[$i]; + $this->payload.="<param>\n" . $p->serialize() . + "</param>\n"; + } + $this->payload.="</params>\n"; + // } + $this->payload.=$this->xml_footer(); + $this->payload=str_replace("\n", "\r\n", $this->payload); + } + + function method($meth="") { + if ($meth!="") { + $this->methodname=$meth; + } + return $this->methodname; + } + + function serialize() { + $this->createPayload(); + logIO("O",$this->payload); + return $this->payload; + } + + function addParam($par) { $this->params[]=$par; } + function getParam($i) { return $this->params[$i]; } + function getNumParams() { return sizeof($this->params); } + + function parseResponseFile($fp) { + $ipd=""; + + while($data=fread($fp, 32768)) { + $ipd.=$data; + } + return $this->parseResponse($ipd); + } + + function parseResponse($data="") { + global $_xh,$xmlrpcerr,$xmlrpcstr; + global $xmlrpc_defencoding; + + + $parser = xml_parser_create($xmlrpc_defencoding); + + $_xh[$parser]=array(); + + $_xh[$parser]['st']=""; + $_xh[$parser]['cm']=0; + $_xh[$parser]['isf']=0; + $_xh[$parser]['ac']=""; + $_xh[$parser]['qt']=""; + $_xh[$parser]['ha']=""; + $_xh[$parser]['ac']=""; + + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + xml_set_element_handler($parser, "xmlrpc_se", "xmlrpc_ee"); + xml_set_character_data_handler($parser, "xmlrpc_cd"); + xml_set_default_handler($parser, "xmlrpc_dh"); + $xmlrpc_value=new xmlrpcval; + + if ($this->debug) + print "<PRE>---GOT---\n" . htmlspecialchars($data) . + "\n---END---\n</PRE>"; + if ($data=="") { + error_log("No response received from server."); + $r=new xmlrpcresp(0, $xmlrpcerr["no_data"], + $xmlrpcstr["no_data"]); + xml_parser_free($parser); + return $r; + } + // see if we got an HTTP 200 OK, else bomb + // but only do this if we're using the HTTP protocol. + if (ereg("^HTTP",$data) && + !ereg("^HTTP/[0-9\.]+ 200 ", $data)) { + $errstr= substr($data, 0, strpos($data, "\n")-1); + error_log("HTTP error, got response: " .$errstr); + $r=new xmlrpcresp(0, $xmlrpcerr["http_error"], + $xmlrpcstr["http_error"]. " (" . $errstr . ")"); + xml_parser_free($parser); + return $r; + } + + // if using HTTP, then gotta get rid of HTTP headers here + // and we store them in the 'ha' bit of our data array + if (ereg("^HTTP", $data)) { + $ar=explode("\r\n", $data); + $newdata=""; + $hdrfnd=0; + for ($i=0; $i<sizeof($ar); $i++) { + if (!$hdrfnd) { + if (strlen($ar[$i])>0) { + $_xh[$parser]['ha'].=$ar[$i]. "\r\n"; + } else { + $hdrfnd=1; + } + } else { + $newdata.=$ar[$i] . "\r\n"; + } + } + $data=$newdata; + } + + if (!xml_parse($parser, $data, sizeof($data))) { + // thanks to Peter Kocks <peter.kocks@baygate.com> + if((xml_get_current_line_number($parser)) == 1) + $errstr = "XML error at line 1, check URL"; + else + $errstr = sprintf("XML error: %s at line %d", + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser)); + error_log($errstr); + $r=new xmlrpcresp(0, $xmlrpcerr["invalid_return"], + $xmlrpcstr["invalid_return"]); + xml_parser_free($parser); + return $r; + } + xml_parser_free($parser); + if ($this->debug) { + print "<PRE>---EVALING---[" . + strlen($_xh[$parser]['st']) . " chars]---\n" . + htmlspecialchars($_xh[$parser]['st']) . ";\n---END---</PRE>"; + } + if (strlen($_xh[$parser]['st'])==0) { + // then something odd has happened + // and it's time to generate a client side error + // indicating something odd went on + $r=new xmlrpcresp(0, $xmlrpcerr["invalid_return"], + $xmlrpcstr["invalid_return"]); + } else { + eval('$v=' . $_xh[$parser]['st'] . '; $allOK=1;'); + if ($_xh[$parser]['isf']) { + $f=$v->structmem("faultCode"); + $fs=$v->structmem("faultString"); + $r=new xmlrpcresp($v, $f->scalarval(), + $fs->scalarval()); + } else { + $r=new xmlrpcresp($v); + } + } + $r->hdrs=split("\r?\n", $_xh[$parser]['ha']); + return $r; + } + +} + +class xmlrpcval { + var $me=array(); + var $mytype=0; + + function xmlrpcval($val=-1, $type="") { + global $xmlrpcTypes; + $this->me=array(); + $this->mytype=0; + if ($val!=-1 || $type!="") { + if ($type=="") $type="string"; + if ($xmlrpcTypes[$type]==1) { + $this->addScalar($val,$type); + } + else if ($xmlrpcTypes[$type]==2) + $this->addArray($val); + else if ($xmlrpcTypes[$type]==3) + $this->addStruct($val); + } + } + + function addScalar($val, $type="string") { + global $xmlrpcTypes, $xmlrpcBoolean; + + if ($this->mytype==1) { + echo "<B>xmlrpcval</B>: scalar can have only one value<BR>"; + return 0; + } + $typeof=$xmlrpcTypes[$type]; + if ($typeof!=1) { + echo "<B>xmlrpcval</B>: not a scalar type (${typeof})<BR>"; + return 0; + } + + if ($type==$xmlrpcBoolean) { + if (strcasecmp($val,"true")==0 || + $val==1 || ($val==true && + strcasecmp($val,"false"))) { + $val=1; + } else { + $val=0; + } + } + + if ($this->mytype==2) { + // we're adding to an array here + $ar=$this->me["array"]; + $ar[]=new xmlrpcval($val, $type); + $this->me["array"]=$ar; + } else { + // a scalar, so set the value and remember we're scalar + $this->me[$type]=$val; + $this->mytype=$typeof; + } + return 1; + } + + function addArray($vals) { + global $xmlrpcTypes; + if ($this->mytype!=0) { + echo "<B>xmlrpcval</B>: already initialized as a [" . + $this->kindOf() . "]<BR>"; + return 0; + } + + $this->mytype=$xmlrpcTypes["array"]; + $this->me["array"]=$vals; + return 1; + } + + function addStruct($vals) { + global $xmlrpcTypes; + if ($this->mytype!=0) { + echo "<B>xmlrpcval</B>: already initialized as a [" . + $this->kindOf() . "]<BR>"; + return 0; + } + $this->mytype=$xmlrpcTypes["struct"]; + $this->me["struct"]=$vals; + return 1; + } + + function dump($ar) { + reset($ar); + while ( list( $key, $val ) = each( $ar ) ) { + echo "$key => $val<br>"; + if ($key == 'array') + while ( list( $key2, $val2 ) = each( $val ) ) { + echo "-- $key2 => $val2<br>"; + } + } + } + + function kindOf() { + switch($this->mytype) { + case 3: + return "struct"; + break; + case 2: + return "array"; + break; + case 1: + return "scalar"; + break; + default: + return "undef"; + } + } + + function serializedata($typ, $val) { + $rs=""; + global $xmlrpcTypes, $xmlrpcBase64, $xmlrpcString, + $xmlrpcBoolean; + switch($xmlrpcTypes[$typ]) { + case 3: + // struct + $rs.="<struct>\n"; + reset($val); + while(list($key2, $val2)=each($val)) { + $rs.="<member><name>${key2}</name>\n"; + $rs.=$this->serializeval($val2); + $rs.="</member>\n"; + } + $rs.="</struct>"; + break; + case 2: + // array + $rs.="<array>\n<data>\n"; + for($i=0; $i<sizeof($val); $i++) { + $rs.=$this->serializeval($val[$i]); + } + $rs.="</data>\n</array>"; + break; + case 1: + switch ($typ) { + case $xmlrpcBase64: + $rs.="<${typ}>" . base64_encode($val) . "</${typ}>"; + break; + case $xmlrpcBoolean: + $rs.="<${typ}>" . ($val ? "1" : "0") . "</${typ}>"; + break; + case $xmlrpcString: + $rs.="<${typ}>" . htmlspecialchars($val). "</${typ}>"; + break; + default: + $rs.="<${typ}>${val}</${typ}>"; + } + break; + default: + break; + } + return $rs; + } + + function serialize() { + return $this->serializeval($this); + } + + function serializeval($o) { + global $xmlrpcTypes; + $rs=""; + $ar=$o->me; + reset($ar); + list($typ, $val) = each($ar); + $rs.="<value>"; + $rs.=$this->serializedata($typ, $val); + $rs.="</value>\n"; + return $rs; + } + + function structmem($m) { + $nv=$this->me["struct"][$m]; + return $nv; + } + + function structreset() { + reset($this->me["struct"]); + } + + function structeach() { + return each($this->me["struct"]); + } + + function getval() { + // UNSTABLE + global $xmlrpcBoolean, $xmlrpcBase64; + reset($this->me); + list($a,$b)=each($this->me); + // contributed by I Sofer, 2001-03-24 + // add support for nested arrays to scalarval + // i've created a new method here, so as to + // preserve back compatibility + + if (is_array($b)) { + foreach ($b as $id => $cont) { + $b[$id] = $cont->scalarval(); + } + } + + // add support for structures directly encoding php objects + if (is_object($b)) { + $t = get_object_vars($b); + foreach ($t as $id => $cont) { + $t[$id] = $cont->scalarval(); + } + foreach ($t as $id => $cont) { + eval('$b->'.$id.' = $cont;'); + } + } + // end contrib + return $b; + } + + function scalarval() { + global $xmlrpcBoolean, $xmlrpcBase64; + reset($this->me); + list($a,$b)=each($this->me); + return $b; + } + + function scalartyp() { + global $xmlrpcI4, $xmlrpcInt; + reset($this->me); + list($a,$b)=each($this->me); + if ($a==$xmlrpcI4) + $a=$xmlrpcInt; + return $a; + } + + function arraymem($m) { + $nv=$this->me["array"][$m]; + return $nv; + } + + function arraysize() { + reset($this->me); + list($a,$b)=each($this->me); + return sizeof($b); + } +} + +// date helpers +function iso8601_encode($timet, $utc=0) { + // return an ISO8601 encoded string + // really, timezones ought to be supported + // but the XML-RPC spec says: + // + // "Don't assume a timezone. It should be specified by the server in its + // documentation what assumptions it makes about timezones." + // + // these routines always assume localtime unless + // $utc is set to 1, in which case UTC is assumed + // and an adjustment for locale is made when encoding + if (!$utc) { + $t=strftime("%Y%m%dT%H:%M:%S", $timet); + } else { + if (function_exists("gmstrftime")) + // gmstrftime doesn't exist in some versions + // of PHP + $t=gmstrftime("%Y%m%dT%H:%M:%S", $timet); + else { + $t=strftime("%Y%m%dT%H:%M:%S", $timet-date("Z")); + } + } + return $t; +} + +function iso8601_decode($idate, $utc=0) { + // return a timet in the localtime, or UTC + $t=0; + if (ereg("([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})", + $idate, $regs)) { + if ($utc) { + $t=gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); + } else { + $t=mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); + } + } + return $t; +} + +/**************************************************************** +* xmlrpc_decode takes a message in PHP xmlrpc object format and * +* tranlates it into native PHP types. * +* * +* author: Dan Libby (dan@libby.com) * +****************************************************************/ +if (!function_exists('xmlrpc_decode')) { + function xmlrpc_decode($xmlrpc_val) { + $kind = $xmlrpc_val->kindOf(); + + if($kind == "scalar") { + return $xmlrpc_val->scalarval(); + } + else if($kind == "array") { + $size = $xmlrpc_val->arraysize(); + $arr = array(); + + for($i = 0; $i < $size; $i++) { + $arr[]=xmlrpc_decode($xmlrpc_val->arraymem($i)); + } + return $arr; + } + else if($kind == "struct") { + $xmlrpc_val->structreset(); + $arr = array(); + + while(list($key,$value)=$xmlrpc_val->structeach()) { + $arr[$key] = xmlrpc_decode($value); + } + return $arr; + } + } +} + +/**************************************************************** +* xmlrpc_encode takes native php types and encodes them into * +* xmlrpc PHP object format. * +* BUG: All sequential arrays are turned into structs. I don't * +* know of a good way to determine if an array is sequential * +* only. * +* * +* feature creep -- could support more types via optional type * +* argument. * +* * +* author: Dan Libby (dan@libby.com) * +****************************************************************/ +if (!function_exists('xmlrpc_encode')) { + function xmlrpc_encode($php_val) { + global $xmlrpcInt; + global $xmlrpcDouble; + global $xmlrpcString; + global $xmlrpcArray; + global $xmlrpcStruct; + global $xmlrpcBoolean; + + $type = gettype($php_val); + $xmlrpc_val = new xmlrpcval; + + switch($type) { + case "array": + case "object": + $arr = array(); + while (list($k,$v) = each($php_val)) { + $arr[$k] = xmlrpc_encode($v); + } + $xmlrpc_val->addStruct($arr); + break; + case "integer": + $xmlrpc_val->addScalar($php_val, $xmlrpcInt); + break; + case "double": + $xmlrpc_val->addScalar($php_val, $xmlrpcDouble); + break; + case "string": + $xmlrpc_val->addScalar($php_val, $xmlrpcString); + break; + // <G_Giunta_2001-02-29> + // Add support for encoding/decoding of booleans, since they are supported in PHP + case "boolean": + $xmlrpc_val->addScalar($php_val, $xmlrpcBoolean); + break; + // </G_Giunta_2001-02-29> + case "unknown type": + default: + // giancarlo pinerolo <ping@alt.it> + // it has to return + // an empty object in case (which is already + // at this point), not a boolean. + break; + } + return $xmlrpc_val; + } +} + + + +} +?> diff --git a/b2-include/xmlrpcs.inc b/b2-include/xmlrpcs.inc new file mode 100644 index 0000000000..18ea02a17f --- /dev/null +++ b/b2-include/xmlrpcs.inc @@ -0,0 +1,309 @@ +<?php +// by Edd Dumbill (C) 1999-2001 +// <edd@usefulinc.com> +// $Id$ + + +# additional fixes for case of missing xml extension file by Michel Valdrighi <m@tidakada.com> + + +// Copyright (c) 1999,2000,2001 Edd Dumbill. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// +// * Neither the name of the "XML-RPC for PHP" nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + +// XML RPC Server class +// requires: xmlrpc.inc + +// listMethods: either a string, or nothing +$_xmlrpcs_listMethods_sig=array(array($xmlrpcArray, $xmlrpcString), + array($xmlrpcArray)); +$_xmlrpcs_listMethods_doc='This method lists all the methods that the XML-RPC server knows how to dispatch'; +function _xmlrpcs_listMethods($server, $m) { + global $xmlrpcerr, $xmlrpcstr, $_xmlrpcs_dmap; + $v=new xmlrpcval(); + $dmap=$server->dmap; + $outAr=array(); + for(reset($dmap); list($key, $val)=each($dmap); ) { + $outAr[]=new xmlrpcval($key, "string"); + } + $dmap=$_xmlrpcs_dmap; + for(reset($dmap); list($key, $val)=each($dmap); ) { + $outAr[]=new xmlrpcval($key, "string"); + } + $v->addArray($outAr); + return new xmlrpcresp($v); +} + +$_xmlrpcs_methodSignature_sig=array(array($xmlrpcArray, $xmlrpcString)); +$_xmlrpcs_methodSignature_doc='Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)'; +function _xmlrpcs_methodSignature($server, $m) { + global $xmlrpcerr, $xmlrpcstr, $_xmlrpcs_dmap; + + $methName=$m->getParam(0); + $methName=$methName->scalarval(); + if (ereg("^system\.", $methName)) { + $dmap=$_xmlrpcs_dmap; $sysCall=1; + } else { + $dmap=$server->dmap; $sysCall=0; + } + // print "<!-- ${methName} -->\n"; + if (isset($dmap[$methName])) { + if ($dmap[$methName]["signature"]) { + $sigs=array(); + $thesigs=$dmap[$methName]["signature"]; + for($i=0; $i<sizeof($thesigs); $i++) { + $cursig=array(); + $inSig=$thesigs[$i]; + for($j=0; $j<sizeof($inSig); $j++) { + $cursig[]=new xmlrpcval($inSig[$j], "string"); + } + $sigs[]=new xmlrpcval($cursig, "array"); + } + $r=new xmlrpcresp(new xmlrpcval($sigs, "array")); + } else { + $r=new xmlrpcresp(new xmlrpcval("undef", "string")); + } + } else { + $r=new xmlrpcresp(0, + $xmlrpcerr["introspect_unknown"], + $xmlrpcstr["introspect_unknown"]); + } + return $r; +} + +$_xmlrpcs_methodHelp_sig=array(array($xmlrpcString, $xmlrpcString)); +$_xmlrpcs_methodHelp_doc='Returns help text if defined for the method passed, otherwise returns an empty string'; +function _xmlrpcs_methodHelp($server, $m) { + global $xmlrpcerr, $xmlrpcstr, $_xmlrpcs_dmap; + + $methName=$m->getParam(0); + $methName=$methName->scalarval(); + if (ereg("^system\.", $methName)) { + $dmap=$_xmlrpcs_dmap; $sysCall=1; + } else { + $dmap=$server->dmap; $sysCall=0; + } + // print "<!-- ${methName} -->\n"; + if (isset($dmap[$methName])) { + if ($dmap[$methName]["docstring"]) { + $r=new xmlrpcresp(new xmlrpcval($dmap[$methName]["docstring"]), + "string"); + } else { + $r=new xmlrpcresp(new xmlrpcval("", "string")); + } + } else { + $r=new xmlrpcresp(0, + $xmlrpcerr["introspect_unknown"], + $xmlrpcstr["introspect_unknown"]); + } + return $r; +} + +$_xmlrpcs_dmap=array( + "system.listMethods" => + array("function" => "_xmlrpcs_listMethods", + "signature" => $_xmlrpcs_listMethods_sig, + "docstring" => $_xmlrpcs_listMethods_doc), + "system.methodHelp" => + array("function" => "_xmlrpcs_methodHelp", + "signature" => $_xmlrpcs_methodHelp_sig, + "docstring" => $_xmlrpcs_methodHelp_doc), + "system.methodSignature" => + array("function" => "_xmlrpcs_methodSignature", + "signature" => $_xmlrpcs_methodSignature_sig, + "docstring" => $_xmlrpcs_methodSignature_doc) + ); + +$_xmlrpc_debuginfo=""; +function xmlrpc_debugmsg($m) { + global $_xmlrpc_debuginfo; + $_xmlrpc_debuginfo=$_xmlrpc_debuginfo . $m . "\n"; +} + +class xmlrpc_server { + var $dmap=array(); + + function xmlrpc_server($dispMap, $serviceNow=1) { + global $HTTP_RAW_POST_DATA; + // dispMap is a despatch array of methods + // mapped to function names and signatures + // if a method + // doesn't appear in the map then an unknown + // method error is generated + $this->dmap=$dispMap; + if ($serviceNow) { + $this->service(); + } + } + + function serializeDebug() { + global $_xmlrpc_debuginfo; + if ($_xmlrpc_debuginfo!="") + return "<!-- DEBUG INFO:\n\n" . + $_xmlrpc_debuginfo . "\n-->\n"; + else + return ""; + } + + function service() { + $r=$this->parseRequest(); + $payload="<?xml version=\"1.0\"?>\n" . + $this->serializeDebug() . + $r->serialize(); + Header("Content-type: text/xml\r\nContent-length: " . + strlen(trim($payload))); + print trim($payload); + } + + function verifySignature($in, $sig) { + for($i=0; $i<sizeof($sig); $i++) { + // check each possible signature in turn + $cursig=$sig[$i]; + if (sizeof($cursig)==$in->getNumParams()+1) { + $itsOK=1; + for($n=0; $n<$in->getNumParams(); $n++) { + $p=$in->getParam($n); + // print "<!-- $p -->\n"; + if ($p->kindOf() == "scalar") { + $pt=$p->scalartyp(); + } else { + $pt=$p->kindOf(); + } + // $n+1 as first type of sig is return type + if ($pt != $cursig[$n+1]) { + $itsOK=0; + $pno=$n+1; $wanted=$cursig[$n+1]; $got=$pt; + break; + } + } + if ($itsOK) + return array(1); + } + } + return array(0, "Wanted ${wanted}, got ${got} at param ${pno})"); + } + + function parseRequest($data="") { + global $_xh,$HTTP_RAW_POST_DATA; + global $xmlrpcerr, $xmlrpcstr, $xmlrpcerrxml, $xmlrpc_defencoding, + $_xmlrpcs_dmap; + + + + if ($data=="") { + $data=$HTTP_RAW_POST_DATA; + } + $parser = xml_parser_create($xmlrpc_defencoding); + + $_xh[$parser]=array(); + $_xh[$parser]['st']=""; + $_xh[$parser]['cm']=0; + $_xh[$parser]['isf']=0; + $_xh[$parser]['params']=array(); + $_xh[$parser]['method']=""; + + // decompose incoming XML into request structure + + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + xml_set_element_handler($parser, "xmlrpc_se", "xmlrpc_ee"); + xml_set_character_data_handler($parser, "xmlrpc_cd"); + xml_set_default_handler($parser, "xmlrpc_dh"); + if (!xml_parse($parser, $data, 1)) { + // return XML error as a faultCode + $r=new xmlrpcresp(0, + $xmlrpcerrxml+xml_get_error_code($parser), + sprintf("XML error: %s at line %d", + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser))); + xml_parser_free($parser); + } else { + xml_parser_free($parser); + $m=new xmlrpcmsg($_xh[$parser]['method']); + // now add parameters in + $plist=""; + for($i=0; $i<sizeof($_xh[$parser]['params']); $i++) { + //print "<!-- " . $_xh[$parser]['params'][$i]. "-->\n"; + $plist.="$i - " . $_xh[$parser]['params'][$i]. " \n"; + eval('$m->addParam(' . $_xh[$parser]['params'][$i]. ");"); + } + // uncomment this to really see what the server's getting! + // xmlrpc_debugmsg($plist); + // now to deal with the method + $methName=$_xh[$parser]['method']; + if (ereg("^system\.", $methName)) { + $dmap=$_xmlrpcs_dmap; $sysCall=1; + } else { + $dmap=$this->dmap; $sysCall=0; + } + if (isset($dmap[$methName]['function'])) { + // dispatch if exists + if (isset($dmap[$methName]['signature'])) { + $sr=$this->verifySignature($m, + $dmap[$methName]['signature'] ); + } + if ( (!isset($dmap[$methName]['signature'])) + || $sr[0]) { + // if no signature or correct signature + if ($sysCall) { + eval('$r=' . $dmap[$methName]['function'] . + '($this, $m);'); + } else { + eval('$r=' . $dmap[$methName]['function'] . + '($m);'); + } + } else { + $r=new xmlrpcresp(0, + $xmlrpcerr["incorrect_params"], + $xmlrpcstr["incorrect_params"].": ". $sr[1]); + } + } else { + // else prepare error response + $r=new xmlrpcresp(0, + $xmlrpcerr["unknown_method"], + $xmlrpcstr["unknown_method"]); + } + } + return $r; + } + + function echoInput() { + global $HTTP_RAW_POST_DATA; + + // a debugging routine: just echos back the input + // packet as a string value + + $r=new xmlrpcresp; + $r->xv=new xmlrpcval( "'Aha said I: '" . $HTTP_RAW_POST_DATA, "string"); + print $r->serialize(); + } +} + +?>