[
  {
    "path": ".buildpath",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<buildpath>\n\t<buildpathentry kind=\"src\" path=\"\"/>\n\t<buildpathentry kind=\"con\" path=\"org.eclipse.php.core.LANGUAGE\"/>\n</buildpath>\n"
  },
  {
    "path": ".htaccess",
    "content": "<IfModule mod_rewrite.c>\n    RewriteEngine On\n    RewriteCond %{REQUEST_FILENAME} !-d\n    RewriteCond %{REQUEST_FILENAME} !-f\n    RewriteRule ^(.*)$ index.php/$1 [QSA,L]\n</IfModule>"
  },
  {
    "path": ".project",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<projectDescription>\n\t<name>qwench_new</name>\n\t<comment></comment>\n\t<projects>\n\t</projects>\n\t<buildSpec>\n\t\t<buildCommand>\n\t\t\t<name>org.eclipse.wst.validation.validationbuilder</name>\n\t\t\t<arguments>\n\t\t\t</arguments>\n\t\t</buildCommand>\n\t\t<buildCommand>\n\t\t\t<name>org.eclipse.dltk.core.scriptbuilder</name>\n\t\t\t<arguments>\n\t\t\t</arguments>\n\t\t</buildCommand>\n\t</buildSpec>\n\t<natures>\n\t\t<nature>org.eclipse.php.core.PHPNature</nature>\n\t</natures>\n</projectDescription>\n"
  },
  {
    "path": ".settings/org.eclipse.php.core.prefs",
    "content": "#Sat Oct 19 18:13:01 WAT 2013\neclipse.preferences.version=1\ninclude_path=0;/qwench_new\n"
  },
  {
    "path": "LICENSE.TXT",
    "content": "Qwench\nCopyright (c) 2009-2010 Inscripts\n\nQwench ('the Software') is a copyrighted work of authorship. Inscripts \nretains ownership of the Software and any copies of it, regardless of the \nform in which the copies may exist.\n\nBy installing and using Qwench on your server, you agree to the following\nterms and conditions. \n\nA Modification, or a Mod, is defined as instructions, to be performed \nmanually or in an automated manner, that alter any part of this Package. \nA Modified Package is defined as this Package or a derivative of it with \none or more Modification applied to it. Distribution is defined as allowing\none or more other people to in any way download or receive a copy of this \nPackage, a Modified Package, or a derivative of this Package.\n\nSuch agreement is either on your own behalf or on behalf\nof any corporate entity which employs you or which you represent\n('Corporate Licensee'). In this Agreement, 'you' includes both the reader\nand any Corporate Licensee and 'Inscripts' means Inscripts (I) Private Limited:\n\n1. Permission is hereby granted to use, copy, modify and/or distribute this \nPackage, provided that: \n\na. All copyright notices within source files and as generated by the Software \nas output are retained, unchanged.\nb. Any Distribution of this Package, whether as a Modified Package or not, \nincludes this license and is released under the terms of this Agreement. This\nclause is not dependant upon any measure of changes made to this Package.\nc. This Package, Modified Packages, and derivative works may not be sold or \nreleased under any paid license. Copying fees for the transport of this Package,\nsupport fees for installation or other services, and hosting fees for hosting \nthe Software may, however, be imposed.\nd. Any Distribution of this Package, whether as a Modified Package or not, \nrequires express written consent from Inscripts.\n\n2.You may make Modifications to this Package or a derivative of it, and \ndistribute your Modifications in a form that is separate from the Package,\nsuch as patches. The following restrictions apply to Modifications: \n\na. A Modification must not alter or remove any copyright notices in the \nSoftware or Package, generated or otherwise.\nb. When a Modification to the Package is released, a non-exclusive \nroyalty-free right is granted to Inscripts to distribute the Modification in \nfuture versions of the Package provided such versions remain available under \nthe terms of this Agreement in addition to any other license(s) of the initial \ndeveloper.\nc. Any Distribution of a Modified Package or derivative requires express \nwritten consent from Inscripts.\n\n3.Permission is hereby also granted to distribute programs which depend on \nthis Package, provided that you do not distribute any Modified Package \nwithout express written consent.\n\nAll Software copyright notices within the scripts must remain unchanged (and visible). \n\nThe Software may not be used for anything that would represent or is associated\nwith an Intellectual Property violation, including, but not limited to, \nengaging in any activity that infringes or misappropriates the intellectual property\nrights of others, including copyrights, trademarks, service marks, trade secrets, \nsoftware piracy, and patents held by individuals, corporations, or other entities. \n\nIf any of the terms of this Agreement are violated, Inscripts reserves the right \nto revoke the Software license at any time. \n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE."
  },
  {
    "path": "README.TXT",
    "content": "Qwench\nCopyright (c) 2009-2010 Inscripts\n\nInstallation Instructions\n-----------------------------------------------\n\n1. Modify config.php as per your site\n2. Run install.php (using your browser)\n3. Done! (Delete install.php)\n4. Register on your new site :)\n\n-----------------------------------------------"
  },
  {
    "path": "TODO.TXT",
    "content": "1\tVisit the installation process, make more precise and show errors, rather than \t\tassume\n\teverything works fine\n\n2\tEdit all forms and add placeholders"
  },
  {
    "path": "VERSION.TXT",
    "content": "1.0"
  },
  {
    "path": "config.default.php",
    "content": "<?php\n\n// Database Details\ndefine('SERVERNAME','localhost');\ndefine('SERVERPORT','3306');\ndefine('DBUSERNAME','root');  // Replace root with your database username. If unsure, leave as is.\ndefine('DBPASSWORD','root');\t// Replace root with your database user password.\ndefine('DBNAME','YOUR_DB'); \t//Create a new database qwench on your server and replace YOUR_DB with it's name\n\nDefine('ANSWERS_PER_PAGE','10');\ndefine('QUESTIONS_PER_PAGE','10');\n\n//if you want to enable production mode vs debug mode (useful for error reporting)\n//Possible values 1 = true or 0 = false\ndefine('DEBUG_MODE','1');\n\n// If you want only logged in users to view the site\ndefine('ALLOW_VISITORS','1');\n\n// Do not change salt after users have registered\ndefine('SALT','yoursecurestringoverhere');\n\n// Set default timezone if you want or comment the line below\ndate_default_timezone_set(\"Asia/Calcutta\");\n\n// No trailing slash\n// Path to the Qwench folder\n// If you have installed Qwench in your\n// root folder then set\n// define('BASE_DIR','');\ndefine('BASE_DIR','/qwench');\n\n// If URL-Rewriting does not work then set\n// define('BASE_PATH',BASE_DIR.'/index.php');\n// If URL-Rewriting works, then leave the line below as is\ndefine('BASE_PATH',BASE_DIR);"
  },
  {
    "path": "controllers/answers.php",
    "content": "<?php\n\nfunction edit() {\n\tauthenticate(1);\n\n\tglobal $path;\n\tglobal $template;\n \t$answerid = sanitize($path[2],\"int\");\n\n\t$basePath = basePath();\n\t$basePathNS = basePathNS();\n\n\t$js = <<<EOD\n\n<script src=\"$basePathNS/js/showdown.js\"></script>\n<script src=\"$basePathNS/js/wmd.js\"></script>\n<link href=\"$basePathNS/css/wmd.css\" type=\"text/css\" rel=\"stylesheet\" />\n\nEOD;\n\n\t$template->set('js',$js);\n\n\t$sql = (\"select * from answers where id = '\".escape($answerid).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\t$template->set('description',$result['description']);\n\t$template->set('answerid',$result['id']);\n}\n\nfunction post() {\n\tauthenticate(1);\n\t$basePath = basePath();\n\n\t$description = sanitize($_POST['description'],\"markdown\");\n\t$questionid = sanitize($_POST['questionid'],\"int\");\n\n\t$sql = (\"select * from questions where id = '\".escape($questionid).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\tif (strlen($description) < 15 || $result['id'] == '' || $result['id'] == 0) {\n\t\theader(\"Location: $basePath/questions/view/$questionid/{$result['slug']}\");\n\t\texit;\n\t}\n\n\t$sql = (\"insert into answers (questionid,description,created,updated,userid,accepted,votes) values ('\".escape($questionid).\"','\".escape($description).\"',NOW(),NOW(),'\".escape($_SESSION['userid']).\"','0','0')\");\n\t$query = mysql_query($sql);\n\n\t$sql = (\"update questions set updated = NOW(), answers=answers+1 where id = '\".escape($result['id']).\"'\");\n\t$query = mysql_query($sql);\n\n\theader(\"Location: $basePath/questions/view/$questionid/{$result['slug']}\");\n}\n\nfunction update() {\n\tauthenticate(1);\n\n\t$answerid = sanitize($_POST['id'],\"int\");\n\t$description = sanitize($_POST['description'],\"markdown\");\n\n\t$sql = (\"select * from answers where id = '\".escape($answerid).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\t$sql = (\"select * from questions where id = '\".escape($result['questionid']).\"'\");\n\t$query = mysql_query($sql);\n\t$qresult = mysql_fetch_array($query);\n\n\tif ($qresult['userid'] != $_SESSION['userid']) {\n\t\t$basePath = basePath();\n\t\theader(\"Location: $basePath/questions/view/{$qresult['id']}/{$qresult['slug']}\");\n\t}\n\t\n\t$sql = (\"update answers set description = '\".escape($description).\"', updated = NOW() where userid = '\".escape($_SESSION['userid']).\"' and id = '\".escape($answerid).\"'\");\n\t$query = mysql_query($sql);\n\n\t$sql = (\"update questions set updated = NOW() where id = '\".escape($result['questionid']).\"'\");\n\t$query = mysql_query($sql);\n\n\t$basePath = basePath();\n\n\theader(\"Location: $basePath/questions/view/{$qresult['id']}/{$qresult['slug']}\");\n}\n\nfunction vote() {\n\tif ($_SESSION['userid'] == '') {\n\t\techo \"0Please login to vote\";\n\t\texit;\n\t}\n\n\t$id = sanitize($_POST['id'],\"int\");\n\t$vote = sanitize($_POST['vote'],\"string\");\n\n\tif ($vote == 'plus') {\n\t\t$vote = '+1';\n\t} else {\n\t\t$vote = '-1';\n\t}\n\n\t$sql = (\"select answers.userid,answers_votes.id qvid,answers_votes.vote qvvote from answers left join answers_votes on (answers.id = answers_votes.answerid and answers_votes.userid =  '\".escape($_SESSION['userid']).\"') where answers.id = '\".escape($id).\"'\");\n\t$query = mysql_query($sql);\n\n\t$answer = mysql_fetch_array($query);\n\n\tif ($answer['userid'] == $_SESSION['userid']) {\n\t\techo \"0\".\"You cannot up/down vote your own answer\";\n\t\texit;\n\t}\n\n\tif ($answer['qvid'] > 0) {\n\t\t\n\t\tif ($answer['qvvote'] == 1 && $vote == '+1') {\n\t\t\t$vote = \"-1\";\n\t\t\tscore('a_upvoted_removed',$id,$answer['userid']);\n\t\t} else if ($answer['qvvote'] == 1 && $vote == '-1') {\n\t\t\t$vote = \"-2\";\n\t\t\tscore('a_upvoted_removed',$id,$answer['userid']);\n\t\t\tscore('a_downvoter',$id);\n\t\t\tscore('a_downvoted',$id,$answer['userid']);\n\t\t} else if ($answer['qvvote'] == -1 && $vote == '-1') {\n\t\t\t$vote = \"+1\";\n\t\t\tscore('a_downvoter_removed',$id);\n\t\t\tscore('a_downvoted_removed',$id,$answer['userid']);\n\t\t} else if ($answer['qvvote'] == -1 && $vote == '+1') {\n\t\t\t$vote = \"+2\";\n\t\t\tscore('a_downvoter_removed',$id);\n\t\t\tscore('a_downvoted_removed',$id,$answer['userid']);\n\t\t\tscore('a_upvoted',$id,$answer['userid']);\n\t\t} else if ($answer['qvvote'] == 0) {\n\t\t\tif ($vote == 1) {\n\t\t\t\tscore('a_upvoted',$id,$answer['userid']);\n\t\t\t} else {\n\t\t\t\tscore('a_downvoter',$id);\n\t\t\t\tscore('a_downvoted',$id,$answer['userid']);\n\t\t\t}\n\t\t}\n\n\t\t$sql = (\"update answers_votes set vote = vote\".escape($vote).\" where id = '\".$answer['qvid'].\"'\");\n\t\t$query = mysql_query($sql);\n\n\t} else {\n\t\t$sql = (\"insert into answers_votes (answerid,userid,vote) values ('\".escape($id).\"','\".escape($_SESSION['userid']).\"','\".escape($vote).\"')\");\n\t\t$query = mysql_query($sql);\n\n\t\tif ($vote == 1) {\n\t\t\tscore('a_upvoted',$id,$answer['userid']);\n\t\t} else {\n\t\t\tscore('a_downvoter',$id);\n\t\t\tscore('a_downvoted',$id,$answer['userid']);\n\t\t}\n\n\t}\n\t\n\t$sql_nest = (\"update answers set votes = votes\".escape($vote).\" where id = '\".escape($id).\"'\");\n\t$query_nest = mysql_query($sql_nest);\n\t\n\techo \"1Thankyou for voting\";\n\texit;\n\n}\n\nfunction accept() {\n\tauthenticate(1);\n\n\t$answerid = sanitize($_GET['id'],\"int\");\n\n\t$sql = (\"select questionid,userid from answers where id = '\".escape($answerid).\"'\");\n\t$query = mysql_query($sql);\n\t$answer = mysql_fetch_array($query);\n\n\t$sql = (\"select questions.*,answers.id answerid, answers.userid answeruserid from questions left join answers on (questions.id = answers.questionid and answers.accepted = 1) where questions.id = '\".escape($answer['questionid']).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\tif ($result['kb'] == 1) {\n\t\theader(\"Location: $basePath/questions/view/{$result['id']}/{$result['slug']}\");\n\t\texit;\n\t}\n\n\tif ($result['answerid'] > 0) {\n\t\tscore('a_accepted_removed',$answerid,$result['answeruserid']);\n\t} else {\n\t\tscore('a_accepter',$answerid);\n\t}\n\n\tif ($result['userid'] == $_SESSION['userid']) {\n\t\t$sql = (\"update answers set accepted = '0' where questionid = '\".escape($result['id']).\"'\");\n\t\t$query = mysql_query($sql);\n\t\t$sql = (\"update answers set accepted = '1' where questionid = '\".escape($result['id']).\"' and id = '\".escape($answerid).\"'\");\n\t\t$query = mysql_query($sql);\n\t\t$sql = (\"update questions set accepted = '1' where id = '\".escape($result['id']).\"' and userid = '\".escape($_SESSION['userid']).\"'\");\n\t\t$query = mysql_query($sql);\n\t\t\n\t\tscore('a_accepted',$answerid,$answer['userid']);\n\n\t}\n\n\t$basePath = basePath();\n\n\theader(\"Location: $basePath/questions/view/{$result['id']}/{$result['slug']}\");\n}"
  },
  {
    "path": "controllers/comments.php",
    "content": "<?php\n\nfunction post() {\n\tif ($_SESSION['userid'] == '') {\n\t\techo \"0\";\n\t\texit;\n\t}\n\n\tglobal $template;\n\tglobal $noheader;\n\t$noheader = true;\n\n\t$id = sanitize($_POST['id'],\"string\");\n\t$type = substr($id,0,1);\n\t$typeid = substr($id,1);\n\tif ($type == 'q') {\n\t\t$type = 0;\n\t} else {\n\t\t$type = 1;\n\t}\n\n\t$comment = sanitize($_POST['comment'],\"comment\");\n\n\tif (strlen($comment) < 10 || strlen($comment) > 600) {\n\t\techo \"0An error has occurred. Please try again later\";\n\t\texit;\n\t}\n\t\n\t$sql = (\"insert into comments (type,comment,votes,created,userid,typeid) values ('\".escape($type).\"','\".escape($comment).\"','0',NOW(),'\".escape($_SESSION['userid']).\"','\".escape($typeid).\"')\");\n\t$query = mysql_query($sql);\n \n\t$template->set('comment',$comment);\n\t\n\t$firstname = $_SESSION['name'];\n\t$pos = strpos($_SESSION['name'],' ');\n\tif ($pos > 0) {\n\t\t$firstname = substr($_SESSION['name'],0,$pos);\n\t}\n\n\t$template->set('username',$firstname);\n\t$template->set('userid',$_SESSION['userid']);\n\n}\n\nfunction vote() {\n\tif ($_SESSION['userid'] == '') {\n\t\techo \"0Please login to vote\";\n\t\texit;\n\t}\n\n\t$id = sanitize($_POST['id'],\"int\");\n\n\t$sql = (\"select userid from comments where id = '\".escape($id).\"'\");\n\t$query = mysql_query($sql);\n\t$comment = mysql_fetch_array($query);\n\n\tif ($comment['userid'] == $_SESSION['userid']) {\n\t\techo \"0You cannot upvote your own comment\";\n\t\texit;\n\t}\n\n\t$sql = (\"select * from comments_votes where commentid = '\".escape($id).\"' and userid = '\".escape($_SESSION['userid']).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\n\tif ($result['id'] > 0) { \n\n\t\t$sql = (\"delete from comments_votes where commentid = '\".escape($id).\"' and userid = '\".escape($_SESSION['userid']).\"'\");\n\t\t$query = mysql_query($sql);\n\t\t$sql_nest = (\"update comments set votes = votes-1 where id = '\".escape($id).\"'\");\n\t\t$query_nest = mysql_query($sql_nest);\n\t\tscore('c_upvoted_removed',$id,$comment['userid']);\n\t\n\t} else {\n\t\t$sql = (\"insert into comments_votes (commentid,userid) values ('\".escape($id).\"','\".escape($_SESSION['userid']).\"')\");\n\t\t$query = mysql_query($sql);\n\t\t$sql_nest = (\"update comments set votes = votes+1 where id = '\".escape($id).\"'\");\n\t\t$query_nest = mysql_query($sql_nest);\n\t\tscore('c_upvoted',$id,$comment['userid']);\n\t}\n\n\techo \"1\";\n\texit;\n\n}\n\nfunction del() {\n\n\t$id = sanitize($_POST['id'],\"int\");\n\n\t$sql = (\"delete from comments where id = '\".escape($id).\"' and userid = '\".escape($_SESSION['userid']).\"'\");\n\t$query = mysql_query($sql);\n\n\techo \"1Comment successfully deleted\";\n\texit;\n\n}"
  },
  {
    "path": "controllers/helpers.php",
    "content": "<?php\n\nfunction getUser($id) {\n\tglobal $helper;\n\n\t$id = sanitize($id,\"int\");\n\t$sql = (\"select * from users where id = '\".escape($id).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\t\n\t$helper->set('user',$result);\n\treturn $helper->render();\n}\n\n "
  },
  {
    "path": "controllers/questions.php",
    "content": "<?php\n\nfunction ask() {\n\tauthenticate(1);\n\n\tglobal $template;\n\t\n\t$basePath = basePath();\n\t$basePathNS = basePathNS();\n\n\t$js = <<<EOD\n\n<script src=\"$basePathNS/js/showdown.js\"></script>\n<script src=\"$basePathNS/js/wmd.js\"></script>\n<link href=\"$basePathNS/css/wmd.css\" type=\"text/css\" rel=\"stylesheet\" />\n\n<script>\n \n\n$(document).ready(function() {\n\t$(\"#tags\").fcbkcomplete({\n\tjson_url: \"$basePath/questions/fetchtags\",\n\tjson_cache: true,\n\tfilter_case: true,\n\tfilter_hide: true,\n\tnewel: true\n\t});\n\n \n\n});\n</script>\n\nEOD;\n\n\t$template->set('js',$js);\n\n\t\n}\n\nfunction edit() {\n\tauthenticate(1);\n\n\tglobal $path;\n\tglobal $template;\n\n\t$basePath = basePath();\n\t$basePathNS = basePathNS();\n\n\t$questionid = sanitize($path[2],\"int\");\n\n\t$js = <<<EOD\n\n<script src=\"$basePathNS/js/showdown.js\"></script>\n<script src=\"$basePathNS/js/wmd.js\"></script>\n<link href=\"$basePathNS/css/wmd.css\" type=\"text/css\" rel=\"stylesheet\" />\n\n<script>\n \n\n$(document).ready(function() {\n\t$(\"#tags\").fcbkcomplete({\n\tjson_url: \"$basePath/questions/fetchtags\",\n\tjson_cache: true,\n\tfilter_case: true,\n\tfilter_hide: true,\n\tnewel: true\n\t});\n\n \n\n});\n</script>\n\nEOD;\n\n\t$template->set('js',$js);\n\n\t$sql = (\"select * from questions where id = '\".escape($questionid).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\t$template->set('title',$result['title']);\n\t$template->set('description',$result['description']);\n\t$template->set('link',$result['link']);\n\t$template->set('kb',$result['kb']);\n\n\t$sql = (\"select tag from tags_questions, tags where questionid = '\".escape($questionid).\"' and tags.id = tags_questions.tagid order by tag\");\n\t$query = mysql_query($sql);\n\n\t$tags = array();\n\n\twhile ($result = mysql_fetch_array($query)) {\n\t\t$tags[] = $result['tag'];\n\t}\n\n\t$template->set('tags',$tags);\n\t$template->set('questionid',$questionid);\n\n\t\n}\n\nfunction post() {\n\tauthenticate(1);\n\t$basePath = basePath();\n\n\t$title = sanitize($_POST['title'],\"string\");\n\t$description = sanitize($_POST['description'],\"markdown\");\n\t$link = sanitize($_POST['link'],\"url\");\n\t$slug = createSlug($title);\n\t\n\t$kb = 0;\n\n\tif (!empty($_POST['answercheck'])) {\n\t\t$kb = sanitize($_POST['answercheck'],\"int\");\n\t}\n\n\t$cache = '';\n\tif (!empty($link)) {\n\t\t$cache = fetchURL($link);\n\t}\n\n\tif (strlen($title) < 15 || strlen($description)<15) {\n\t\theader(\"Location: $basePath/questions/ask\");\n\t\texit;\n\t}\n\n\t$sql = (\"insert into questions (title,description,created,updated,link,userid,slug,linkcache,votes,accepted,answers,kb) values ('\".escape($title).\"','\".escape($description).\"',NOW(),NOW(),'\".escape($link).\"','\".escape($_SESSION['userid']).\"','\".escape($slug).\"','\".escape($cache).\"','0','0','0','\".escape($kb).\"')\");\n\t$query = mysql_query($sql);\n\n\t$questionid = mysql_insert_id();\n\n\tif (!empty($_POST['tags'])) {\n\t\tforeach ($_POST['tags'] as $tag) {\n\t\t\t$tag = createSlug($tag);\n\n\t\t\t$sql = (\"select * from tags where tag = '\".escape($tag).\"'\");\n\t\t\t$query = mysql_query($sql);\n\t\t\t$result = mysql_fetch_array($query);\n\n\t\t\tif ($result['id'] > 0) {\n\t\t\t\t$sql = (\"insert into tags_questions (tagid,questionid) values ('\".escape($result['id']).\"','\".escape($questionid).\"')\");\n\t\t\t\t$query = mysql_query($sql);\n\t\t\t} else {\n\n\t\t\t\t$sql = (\"insert into tags (tag) values ('\".escape($tag).\"')\");\n\t\t\t\t$query = mysql_query($sql);\n\t\t\t\t$tagid = mysql_insert_id();\n\n\t\t\t\t$sql = (\"insert into tags_questions (tagid,questionid) values ('\".escape($tagid).\"','\".escape($questionid).\"')\");\n\t\t\t\t$query = mysql_query($sql);\n\t\t\t}\t\t\t\t\t\n\t\t}\n\t}\n\n\tif (!empty($_POST['answer'])) {\n\t\t$description = sanitize($_POST['answer'],\"markdown\");\n\t\t$sql = (\"insert into answers (questionid,description,created,updated,userid,accepted,votes) values ('\".escape($questionid).\"','\".escape($description).\"',NOW(),NOW(),'\".escape($_SESSION['userid']).\"','1','0')\");\n\t\t$query = mysql_query($sql);\n\t}\n\n\tif ($kb == 1) {\n\t\tscore('kb_posted',$questionid);\t\n\t}\n\t\n\theader(\"Location: $basePath/questions/view/$questionid/$slug\");\n}\n\n\nfunction update() {\n\tauthenticate(1);\n\n\t$questionid = sanitize($_POST['id'],\"int\");\n\t$title = sanitize($_POST['title'],\"string\");\n\t$description = sanitize($_POST['description'],\"markdown\");\n\t$link = sanitize($_POST['link'],\"url\");\n\n\t$slug = createSlug($title);\n\n\t$kb = 0;\n\n\tif (!empty($_POST['answercheck'])) {\n\t\t$kb = sanitize($_POST['answercheck'],\"int\");\n\t}\n\n\t$cache = '';\n\tif (!empty($link)) {\n\t\t$cache = fetchURL($link);\n\t}\n\n\t$sql = (\"select * from questions where id = '\".escape($questionid).\"'\");\n\t$query = mysql_query($sql);\n\n\t$result = mysql_fetch_array($query);\n\n\tif ($result['userid'] != $_SESSION['userid']) {\n\t\t$basePath = basePath();\n\t\theader(\"Location: $basePath/questions/view/{$result['id']}/{$result['slug']}\");\n\t}\n\t\n\t$cacheup = '';\n\n\tif ($result['link'] != $link) {\n\t\t$cacheup = \",linkcache = '\".escape($cache).\"'\";\n\t}\n\n\tif ($result['kb'] == 1 && $kb == 0) {\n\t\tscore('kb_posted_removed',$questionid);\t\n\t} else if ($result['kb'] == 0 && $kb == 1) {\n\t\tscore('kb_posted',$questionid);\t\n\t}\n\n\t$sql = (\"update questions set title = '\".escape($title).\"', kb = '\".escape($kb).\"', description = '\".escape($description).\"' , updated = NOW(), link = '\".escape($link).\"', slug = '\".escape($slug).\"' $cacheup where userid = '\".escape($_SESSION['userid']).\"' and id = '\".escape($questionid).\"'\");\n\t$query = mysql_query($sql);\n\techo mysql_error();\n\t \n\n\t$sql = (\"delete from tags_questions where questionid = '\".escape($questionid).\"'\");\n\t$query = mysql_query($sql);\n\n\t\n\tif (!empty($_POST['tags'])) {\n\t\tforeach ($_POST['tags'] as $tag) {\n\t\t\t$tag = createSlug($tag);\n\n\t\t\t$sql = (\"select * from tags where tag = '\".escape($tag).\"'\");\n\t\t\t$query = mysql_query($sql);\n\t\t\t$result = mysql_fetch_array($query);\n\n\t\t\tif ($result['id'] > 0) {\n\t\t\t\t$sql = (\"insert into tags_questions (tagid,questionid) values ('\".escape($result['id']).\"','\".escape($questionid).\"')\");\n\t\t\t\t$query = mysql_query($sql);\n\t\t\t} else {\n\n\t\t\t\t$sql = (\"insert into tags (tag) values ('\".escape($tag).\"')\");\n\t\t\t\t$query = mysql_query($sql);\n\t\t\t\t$tagid = mysql_insert_id();\n\n\t\t\t\t$sql = (\"insert into tags_questions (tagid,questionid) values ('\".escape($tagid).\"','\".escape($questionid).\"')\");\n\t\t\t\t$query = mysql_query($sql);\n\t\t\t}\t\t\t\t\t\n\t\t}\n\t}\n\n\n\t\n\t$basePath = basePath();\n\theader(\"Location: $basePath/questions/view/$questionid/$slug\");\n}\n\nfunction fetchtags() {\n\tnoRender();\n\t\n\t$tag = createSlug($_GET['tag']);\n\n\theader('Content-type: application/json; charset=utf-8');\n\t$sql = (\"select * from tags where tag LIKE '%\".escape($tag).\"%'\");\n\t$query = mysql_query($sql);\n\t\n\t$resultSet = array();\n\twhile ($result = mysql_fetch_array($query)) {\n\t\t$resultSet[] = array(\"caption\" => $result['tag'], \"value\" => $result['tag']);\n\t}\n\techo json_encode($resultSet);\n\texit();\n}\n\n \nfunction view() {\n\tglobal $path;\n\tglobal $template;\n\n\t$questionid = sanitize($path[2],\"int\");\n\n\t$sql = (\"select * from questions where id = '\".escape($questionid).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\t$template->set('id',$result['id']);\n\t$template->set('userid',$result['userid']);\n\t$template->set('title',$result['title']);\n\t$template->set('created',$result['created']);\n\t$template->set('description',Markdown($result['description']));\n\t$template->set('kb',$result['kb']);\n\n\t$template->set('link',$result['link']);\n\n\t$cache = 0;\n\tif (!empty($result['linkcache'])) {\n\t\t$cache = 1;\n\t}\n\n\t$template->set('cache',$cache);\n\n\t$sql = (\"select tag from tags_questions, tags where questionid = '\".escape($questionid).\"' and tags.id = tags_questions.tagid order by tag\");\n\t$query = mysql_query($sql);\n\n\t$tags = array();\n\twhile ($result = mysql_fetch_array($query)) {\n\t\t$tags[] = $result['tag'];\n\t}\n\n\t$template->set('tags',$tags);\n\n\t\n\t$sql = (\"select * from favorites where questionid = '\".escape($questionid).\"' and userid = '\".escape($_SESSION['userid']).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\t$fave = 0;\n\tif ($result['id'] > 0) { $fave = 1; }\n\t\n\t$template->set('fave',$fave);\n\n\n\t$sql = (\"select sum(vote) count from questions_votes where questionid = '\".escape($questionid).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\t$votes = $result['count'];\n\tif ($votes == '') { $votes = 0; }\n\n\t$template->set('votes',$votes);\n\n\t$sql = (\"select vote from questions_votes where questionid = '\".escape($questionid).\"' and userid = '\".escape($_SESSION['userid']).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\t$nvote = 0;\n\t$pvote = 0;\n\n\tif ($result['vote'] == -1) {\n\t\t$nvote = 1;\n\t}\n\n\tif ($result['vote'] == 1) {\n\t\t$pvote = 1;\n\t}\n\n\t$template->set('nvote',$nvote);\n\t$template->set('pvote',$pvote);\n\n\n\t\n\t$sql = (\"select comments.id,comment,comments.userid,users.name username, comments_votes.id voted, comments.votes from comments left join users on comments.userid = users.id left join comments_votes on (comments_votes.commentid = comments.id and comments_votes.userid = '\".escape($_SESSION['userid']).\"') where type = '0' and typeid = '\".escape($questionid).\"' order by comments.created asc\");\n\t$query = mysql_query($sql);\n\n\t$comments = array();\n\t\n\twhile ($result = mysql_fetch_array($query)) {\n\t\t$pos = strpos($result['username'],' ');\n\t\tif ($pos > 0) {\n\t\t\t$result['username'] = substr($result['username'],0,$pos);\n\t\t}\n\n\t\t$comments[] = array(\"id\" => $result['id'], \"comment\" => $result['comment'], \"userid\" => $result['userid'], \"username\" => $result['username'],  \"voted\" => $result['voted'],  \"votes\" => $result['votes']);\n\t}\n\n\t$template->set('comments',$comments);\n\n\t$sql = (\"select count(id) count from answers where questionid = '\".escape($questionid).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\t$template->set('answerscount',$result['count']);\n\n\t$order = \"votes desc\";\n\t$orderby = \"votes\";\n\t$page = 1;\n\n\tif (!empty($_GET['order'])) { \n\t\tif ($_GET['order'] == \"newest\") {\n\t\t\t$order = \"created desc\"; \n\t\t\t$orderby = \"newest\";\n\t\t} else if ($_GET['order'] == \"oldest\") {\n\t\t\t$order = \"created asc\"; \n\t\t\t$orderby = \"oldest\";\n\t\t}\n\t}\n\n\tif (!empty($_GET['page'])) { \n\t\t$page = $_GET['page']; \n\t}\n\n\t$offset = ($page-1)*ANSWERS_PER_PAGE;\n\n\t$paging = new Pagination();\n\t$paging->set('urlscheme','?order='.$orderby.'&page=%page%');\n\t$paging->set('perpage',ANSWERS_PER_PAGE);\n\t$paging->set('page',$page);\n\t$paging->set('total',$result['count']);\n\t$paging->set('order',$orderby);\n\t\n\t$template->set('pagination',$paging->display());\n\n\t$paging->set('urlscheme','?order=%label%&page=1');\n\t$template->set('orderOptions',$paging->displayOptions());\n\t\n\t$sqlanswer = '';\n\n\tif ($page == 1) {\n\t\t$sqlanswer = \"(select answers.*,users.name username from answers,users where questionid = '\".escape($questionid).\"' and answers.userid = users.id and answers.accepted = '1') UNION \";\n\t}\n\n\t$sql = (\"$sqlanswer (select answers.*,users.name username from answers,users where questionid = '\".escape($questionid).\"' and answers.userid = users.id and answers.accepted = '0' order by $order, created desc LIMIT \".ANSWERS_PER_PAGE.\" OFFSET $offset)\");\n\t$query = mysql_query($sql);\n \n\n\t$answers = array();\n\twhile ($result = mysql_fetch_array($query)) {\n\n\t\t$sql_nest = (\"select sum(vote) count from answers_votes where answerid = '\".escape($result['id']).\"'\");\n\t\t$query_nest = mysql_query($sql_nest);\n\t\t$result_nest = mysql_fetch_array($query_nest);\n\n\t\t$votes = $result_nest['count'];\n\n\t\tif ($votes == '') { $votes = 0; }\n\n\t\t$sql_nest = (\"select vote from answers_votes where answerid = '\".escape($result['id']).\"' and userid = '\".escape($_SESSION['userid']).\"'\");\n\t\t$query_nest = mysql_query($sql_nest);\n\t\t$result_nest = mysql_fetch_array($query_nest);\n\n\t\t$nvote = 0;\n\t\t$pvote = 0;\n\n\t\tif ($result_nest['vote'] == -1) {\n\t\t\t$nvote = 1;\n\t\t}\n\n\t\tif ($result_nest['vote'] == 1) {\n\t\t\t$pvote = 1;\n\t\t}\n\n\n\n\t\t$sql_nest = (\"select comments.id,comment,comments.userid,users.name username, comments_votes.id voted, comments.votes from comments left join users on comments.userid = users.id left join comments_votes on (comments_votes.commentid = comments.id and comments_votes.userid = '\".escape($_SESSION['userid']).\"') where type = '1' and typeid = '\".escape($result['id']).\"' order by comments.created asc\");\n\t\t$query_nest = mysql_query($sql_nest);\n\n\t\t \n\t\t$comments = array();\n\t\t\n\t\twhile ($result_nest = mysql_fetch_array($query_nest)) {\n\t\t\t$pos = strpos($result['username'],' ');\n\t\t\tif ($pos > 0) {\n\t\t\t\t$result['username'] = substr($result['username'],0,$pos);\n\t\t\t}\n\t\t\t$comments[] = array(\"id\" => $result_nest['id'], \"comment\" => $result_nest['comment'], \"userid\" => $result_nest['userid'], \"username\" => $result['username'],  \"voted\" => $result_nest['voted'],  \"votes\" => $result_nest['votes']);\n\t\t}\n\n\t\t$answers[] = array (\"description\" => Markdown($result['description']), \"created\" => $result['created'], \"updated\" => $result['updated'], \"userid\" => $result['userid'], \"username\" => $result['username'], \"pvote\" => $pvote, \"nvote\" => $nvote, \"votes\" => $votes, \"id\" => $result['id'], \"accepted\"=> $result['accepted'], \"comments\" => $comments );\n\t}\n\n\t$template->set('answers',$answers);\n\n\t$basePathNS = basePathNS();\n\t\n\t$js = '';\n\n\tif ($_SESSION['userid'] != '') {\n\t\t$js = <<<EOD\n\n\t\t<script src=\"$basePathNS/js/showdown.js\"></script>\n\t\t<script src=\"$basePathNS/js/wmd.js\"></script>\n\t\t<link href=\"$basePathNS/css/wmd.css\" type=\"text/css\" rel=\"stylesheet\" />\n\nEOD;\n\t\t\n\t}\n\n\t$js .= <<<EOD\n\n\n\n<script>\n\n\tvar basePath = \"{$basePath}\";\n\n\n\tfunction vote(elem,type,voted) {\n\t\t\\$this = $(elem);\n\t\tvar id = \\$this.parent().parent().parent().attr('id');\n\n\t\tvar add = 1;\n\t\tvar minus = -1;\n\t\tvar up = 'up';\n\t\tvar down = 'down';\n\t\tif (voted == 'minus') { add = -1; minus = 1; up = 'down'; down = 'up'; }\n\n\t\t$.post(basePath+\"/\"+type+\"/vote\", { id: id, vote: voted },\n\t\t\tfunction(data) {\n\t\t\t\tvar result = data.substr(0,1);\n\t\t\t\tvar message = data.substr(1);\n\n\t\t\t\tif (result == 1) {\n\n\t\t\t\t\tif (!$(\"#\"+id+\" .questionsview_\"+up+\"\").hasClass(\"voteselected\")) {\n\t\t\t\t\n\t\t\t\t\t\t$(\"#\"+id+\" .questionsview_vote\").html(parseInt($(\"#\"+id+\" .questionsview_vote\").html())+add);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ($(\"#\"+id+\" .questionsview_\"+down+\"\").hasClass(\"voteselected\")) {\n\t\t\t\t\t\t\t$(\"#\"+id+\" .questionsview_vote\").html(parseInt($(\"#\"+id+\" .questionsview_vote\").html())+add);\n\t\t\t\t\t\t\t$(\"#\"+id+\" .questionsview_\"+down+\"\").removeClass(\"voteselected\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$(\"#\"+id+\" .questionsview_vote\").html(parseInt($(\"#\"+id+\" .questionsview_vote\").html())+minus);\n\t\t\t\t\t}\n\n\t\t\t\t\t\\$this.toggleClass(\"voteselected\");\n\t\t\t\t} \n\t\t\t\t\n\t\t\t\tif (message != '') {\n\t\t\t\t\t$.fancyalert(message);\n\t\t\t\t}\n\n\t\t});\n\t}\n \n\t$(document).ready(function() {\n \n\t\t$(\".questionsview_answer .questionsview_up\").click(function() {\n\t\t\tvote(this,'answers','plus');\n\t\t});\n\n\t\t$(\".questionsview_answer .questionsview_down\").click(function() {\n\t\t\tvote(this,'answers','minus');\n\t\t});\n\n\t\t$(\".questionsview_question .questionsview_up\").click(function() {\n\t\t\tvote(this,'questions','plus');\n\t\t});\n\n\t\t$(\".questionsview_question .questionsview_down\").click(function() {\n\t\t\tvote(this,'questions','minus');\n\t\t});\n\n\t\t$(\".questionsview_question .questionsview_fave\").click(function() {\n\t\t\t\\$this = $(this);\n\t\t\tvar id = \\$this.parent().parent().parent().attr('id');\n\t\t\t$.post(basePath+\"/questions/fave\", { id: id },\n\t\t\t\tfunction(data) {\n\t\t\t\t\tvar result = data.substr(0,1);\n\t\t\t\t\tvar message = data.substr(1);\n\n\t\t\t\t\tif (result == 1) {\n\t\t\t\t\t\t\\$this.toggleClass(\"voteselected\");\t\t\t\t\n\t\t\t\t\t}\n\n\t\t\t\t\t$.fancyalert(message);\n\t\t\t\t\t\n\t\t\t});\n\t\t});\n\n\n\t$(\".commentfave\").click(function() {\n\n\t\tvar id = $(this).attr('id');\n\t\t\\$this = $(this);\n\n\t\t$.post(basePath+\"/comments/vote\", { id: id },\n\t\t\tfunction(data) {\n\n\t\t\t\tvar result = data.substr(0,1);\n\t\t\t\tvar message = data.substr(1);\n\n\t\t\t\tif (result == \"1\") {\n\t\t\t\t\tif (\\$this.next('div').html() == '') {\n\t\t\t\t\t\t\\$this.next('div').html('0');\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!\\$this.hasClass(\"voteselected\")) {\n\t\t\t\t\t\t\\$this.next('div').html(parseInt(\\$this.next('div').html())+1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\\$this.next('div').html(parseInt(\\$this.next('div').html())-1);\n\t\t\t\t\t}\n\n\t\t\t\t\t\\$this.toggleClass(\"voteselected\");\n\t\t\t\t}\n\n\t\t\t\tif (message != '') {\n\t\t\t\t\t$.fancyalert(message);\n\t\t\t\t}\n\t\t\t\n\t\t});\n\n\n\t});\n\n\t\t$(\".commentdel\").click(function() {\n\n\t\tvar answer = confirm(\"Delete this comment?\")\n\t\tif (answer){\n\t\t\tvar id = $(this).attr('id');\n\t\t\t\\$this = $(this);\n\t\t\t$.post(basePath+\"/comments/del\", { id: id },\n\t\t\t\tfunction(data) {\n\n\t\t\t\tvar result = data.substr(0,1);\n\t\t\t\tvar message = data.substr(1);\n\n\t\t\t\tif (result == \"1\") {\n\t\t\t\t\t\\$this.parent().fadeOut(2000);\n\t\t\t\t}\n\n\t\t\t\tif (message != '') {\n\t\t\t\t\t$.fancyalert(message);\n\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t});\n\t\t}\n\n\t\t\n\t});\n\n\tvar comments = $(\".comments\");\n\t$.each(comments, function() { \n\t    var elements = ( $('.comment:gt(4)',$(this)).size());\n\n\t\tif (elements > 0) {\t\t\n\t\t\t$('.viewallcomments',$(this)).css('display','block');\n\t\t\t$('.viewallcomments a',$(this)).html('View all comments ('+elements+' more)');\n\t\t} \n\n\t\tallComments = $(\".comment\",$(this)).get();\n\t\tallComments.sort(function(a,b) {\n\t\t\ta = $(\".commentfavevotes\",a).html();    \n\t\t\tb = $(\".commentfavevotes\",b).html();; \n\t\t\t\n\t\t\tif (a == '') a = 0;\n\t\t\tif (b == '') b = 0;\n\n\t\t\tif (a > b) {      \n\t\t\t\treturn -1;   \n\t\t\t} else if (a < b) {  \n\t\t\t\treturn 1;  \n\t\t\t} else {       \n\t\t\t\treturn 0;    \n\t\t\t}\n\t\t});\n\t\t$(allComments.slice(5)).hide(); \n\n \n\n\t}); \n\n});\n\nfunction comment(id) {\n\t$(\"#comment_\"+id).html(\"<textarea class=\\\"commenttextarea\\\" id='commenttext_\"+id+\"'></textarea><input class=\\\"smallbutton\\\" type=\\\"submit\\\" value=\\\"Add Comment\\\" onclick=\\\"addcomment('\"+id+\"')\\\"/>\");\n}\n\nfunction addcomment(id) {\n\n\t\tvar comment = $(\"#commenttext_\"+id).val();\n\n\t\tif (comment.length < 10) {\n\t\t\t$.fancyalert('Your comment must be atleast 10 characters in length');\n\t\t\treturn;\n\t\t}\n\n\t\tif (comment.length > 600) {\n\t\t\t$.fancyalert('Your comment is too long, please reduce it to 600 characters');\n\t\t\treturn;\n\t\t}\n\n\t\t$(\"#commenttext_\"+id).val('');\n\t\t\n\t\t$.post(basePath+\"/comments/post\", { id: id, comment: comment },\n\t\t\tfunction(data) {\n\t\t\t\tif (data == 0) {\n\t\t\t\t\t$(\"#commenttext_\"+id).val(comment);\n\t\t\t\t\t$.fancyalert('Please login to post a comment');\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\t$(\"#comments_\"+id).append(data);\n\t\t\t\t}\n\t\t});\n}\n\n\nfunction viewallcomments(id){\n\t$('#comments_'+id+' .comment').fadeIn(1000);\n\t$('#comment_'+id+' .viewallcomments').css('display','none');\n}\n\n</script>\n\nEOD;\n\n\t$template->set('js',$js);\n}\n\nfunction cache() {\n\tglobal $path;\n\tglobal $template;\n\tglobal $noheader;\n\n\t$noheader = true;\n\t$questionid = sanitize($path[2],\"int\");\n\n\t$sql = (\"select * from questions where id = '\".escape($questionid).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\t$template->set('cachelink',$result['link']);\n\t$template->set('cache',$result['linkcache']);\n}\n\nfunction vote() {\n\tif ($_SESSION['userid'] == '') {\n\t\techo \"0Please login to vote\";\n\t\texit;\n\t}\n\n\t$id = sanitize($_POST['id'],\"int\");\n\t$vote = sanitize($_POST['vote'],\"string\");\n\n\tif ($vote == 'plus') {\n\t\t$vote = '+1';\n\t} else {\n\t\t$vote = '-1';\n\t}\n\n\t$sql = (\"select questions.userid,questions_votes.id qvid,questions_votes.vote qvvote from questions left join questions_votes on (questions.id = questions_votes.questionid and questions_votes.userid =  '\".escape($_SESSION['userid']).\"') where questions.id = '\".escape($id).\"'\");\n\t$query = mysql_query($sql);\n\n\t$question = mysql_fetch_array($query);\n\n\tif ($question['userid'] == $_SESSION['userid']) {\n\t\techo \"0\".\"You cannot up/down vote your own question\";\n\t\texit;\n\t}\n\n\tif ($question['qvid'] > 0) {\n\t\t\n\t\tif ($question['qvvote'] == 1 && $vote == '+1') {\n\t\t\t$vote = \"-1\";\n\t\t\tscore('q_upvoted_removed',$id,$question['userid']);\n\t\t} else if ($question['qvvote'] == 1 && $vote == '-1') {\n\t\t\t$vote = \"-2\";\n\t\t\tscore('q_upvoted_removed',$id,$question['userid']);\n\t\t\tscore('q_downvoter',$id);\n\t\t\tscore('q_downvoted',$id,$question['userid']);\n\t\t} else if ($question['qvvote'] == -1 && $vote == '-1') {\n\t\t\t$vote = \"+1\";\n\t\t\tscore('q_downvoter_removed',$id);\n\t\t\tscore('q_downvoted_removed',$id,$question['userid']);\n\t\t} else if ($question['qvvote'] == -1 && $vote == '+1') {\n\t\t\t$vote = \"+2\";\n\t\t\tscore('q_downvoter_removed',$id);\n\t\t\tscore('q_downvoted_removed',$id,$question['userid']);\n\t\t\tscore('q_upvoted',$id,$question['userid']);\n\t\t} else if ($question['qvvote'] == 0) {\n\t\t\tif ($vote == 1) {\n\t\t\t\tscore('q_upvoted',$id,$question['userid']);\n\t\t\t} else {\n\t\t\t\tscore('q_downvoter',$id);\n\t\t\t\tscore('q_downvoted',$id,$question['userid']);\n\t\t\t}\n\t\t}\n\n\t\t$sql = (\"update questions_votes set vote = vote\".escape($vote).\" where id = '\".$question['qvid'].\"'\");\n\t\t$query = mysql_query($sql);\n\n\t} else {\n\t\t$sql = (\"insert into questions_votes (questionid,userid,vote) values ('\".escape($id).\"','\".escape($_SESSION['userid']).\"','\".escape($vote).\"')\");\n\t\t$query = mysql_query($sql);\n\n\t\tif ($vote == 1) {\n\t\t\tscore('q_upvoted',$id,$question['userid']);\n\t\t} else {\n\t\t\tscore('q_downvoter',$id);\n\t\t\tscore('q_downvoted',$id,$question['userid']);\n\t\t}\n\n\t}\n\t\n\t$sql_nest = (\"update questions set votes = votes\".escape($vote).\" where id = '\".escape($id).\"'\");\n\t$query_nest = mysql_query($sql_nest);\n\t\n\techo \"1Thankyou for voting\";\n\texit;\n\n}\n\nfunction fave() {\n\n\tif ($_SESSION['userid'] == '') {\n\t\techo \"0Please login to add a question to your favorites\";\n\t\texit;\n\t}\n\n\t$id = sanitize($_POST['id'],\"int\");\n\n\t$sql = (\"select * from favorites where questionid = '\".escape($id).\"' and userid = '\".escape($_SESSION['userid']).\"'\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\n\tif ($result['id'] > 0) { \n\t\t$sql = (\"delete from favorites where questionid = '\".escape($id).\"' and userid = '\".escape($_SESSION['userid']).\"'\");\n\t\t$query = mysql_query($sql);\n\t\techo \"1Question removed from your favorites\";\n\n\t} else {\n\t\t$sql = (\"insert into favorites (questionid,userid) values ('\".escape($id).\"','\".escape($_SESSION['userid']).\"')\");\n\t\t$query = mysql_query($sql);\n\t\techo \"1Question added to your favorites\";\n\t}\n\n\t\n\texit;\n\n}\n\nfunction index() {\n\tglobal $path;\n\tglobal $template;\n\t\n\t$conditionspre = '';\n\t$conditionspost = '';\n\t$conditionsselect = '';\n\t$extratitle = '';\n\n\t\n\t$orderby = 'newest';\n\t$order = 'created desc';\n\t$defaultorder = 1;\n\t$nopagination = 0;\n\t$page = 1;\n\t\n\t$searchstringoriginal = '';\n\n\tif (!empty($_GET['search'])) { $searchstringoriginal = sanitize($_GET['search'],\"string\"); }\n\n\tif (!empty($_GET['order'])) { \n\t\tif ($_GET['order'] == \"votes\") {\n\t\t\t$order = \"votes desc\"; \n\t\t\t$orderby = \"votes\";\n\t\t\t$defaultorder = 0;\n\t\t} else if ($_GET['order'] == \"oldest\") {\n\t\t\t$order = \"created asc\"; \n\t\t\t$orderby = \"oldest\";\n\t\t\t$defaultorder = 0;\n\t\t} else if ($_GET['order'] == \"relevance\") {\n\t\t\t$order = \"score desc\"; \n\t\t\t$orderby = \"relevance\";\n\t\t\t$defaultorder = 0;\n\t\t} else if ($_GET['order'] == \"newest\") {\n\t\t\t$defaultorder = 0;\n\t\t}\n\t}\n\n\tif (!empty($_GET['page'])) { \n\t\t$page = sanitize($_GET['page'],\"int\"); \n\t}\n\n\t$type = '';\n\n\n\tif (!empty($_GET['type'])) { \n\t\t\n\t\t$type = \"&type=\".sanitize($_GET['type'],\"string\");\n\t\t\n\t\tif (sanitize($_GET['type'],\"string\") == \"unanswered\") {\n\t\t//\t$conditionspost .= \" questions.id NOT IN (select questions.id from questions,answers where questions.id = answers.questionid and answers.accepted = 1) and \";\n\t\t\t$conditionspost .= \" questions.accepted = 0 and questions.kb = 0 and \";\n\t\t\t$extratitle = \" not yet answered\";\n\n\t\t} else {\n\t\t\t$extratitle = \" active\";\n\t\t\t$order = \" updated desc \";\n\t\t\t$nopagination = 1;\n\t\t}\n\t}\n\n\t$template->set('nopagination',$nopagination);\n\n\t$search = '';\n\t$searchstring = urldecode($searchstringoriginal);\n\t\n\tif (!empty($searchstringoriginal)) {\n\t\t$search = \"&search=\".urlencode($searchstring);\n\t\t$conditionspost .= \" MATCH(title, description) AGAINST ('\".escape($searchstring).\"') and \";\n\t\t$conditionsselect .= \",MATCH(title, description) AGAINST ('\".escape($searchstring).\"') AS score  \";\n\t\t$extratitle = \" showing \".$searchstring;\n\t\tif ($defaultorder == 1) {\n\t\t\t$orderby = 'relevance';\n\t\t\t$order = 'score desc';\n\t\t}\n\t}\n\n\t$template->set('searchstring',$searchstring);\n\n\t$tag = '';\n\n\tif (!empty($_GET['tag'])) {\n\t\t$tag = \"&tag=\".createSlug($_GET['tag']);\n\t\t$conditionspre .= \",tags_questions, tags\";\n\t\t$conditionspost .= \" tags_questions.questionid = questions.id and tags.id = tags_questions.tagid and tags.tag LIKE '\".escape(createSlug($_GET['tag'])).\"' and \";\n\t\t$extratitle = \" tagged \".createSlug($_GET['tag']);\n\t}\n\n\t$offset = ($page-1)*QUESTIONS_PER_PAGE;\n\n\t$sql = (\"select count(questions.id) count from questions $conditionspre WHERE $conditionspost 1\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array(mysql_query($sql));\n \n\t$template->set('questionscount',$result['count']);\n\n\t$paging = new Pagination();\n\t$paging->set('urlscheme','?order='.$orderby.$tag.$type.$search.'&page=%page%');\n\t$paging->set('perpage',QUESTIONS_PER_PAGE);\n\t$paging->set('page',$page);\n\t$paging->set('total',$result['count']);\n\t$paging->set('order',$orderby);\n\t$paging->set('search',$search);\n\t\n\t$template->set('pagination',$paging->display());\n\n\t$paging->set('urlscheme','?order=%label%'.$tag.$type.$search.'&page=1');\n\t$template->set('orderOptions',$paging->displayOptions());\n\t\n\t$template->set('extratitle',$extratitle);\n\n\t$sql = (\"select questions.* $conditionsselect from questions $conditionspre WHERE $conditionspost 1 order by $order, created desc LIMIT \".QUESTIONS_PER_PAGE.\" OFFSET $offset\");\n\t$query = mysql_query($sql);\n \n\t$questions = array();\n\t\n\twhile ($result = mysql_fetch_array($query)) {\n\n\t\t$sql_nest = (\"select tag from tags_questions, tags where questionid = '\".escape($result['id']).\"' and tags.id = tags_questions.tagid order by tag\");\n\t\t$query_nest = mysql_query($sql_nest);\n\n\t\t$tags = array();\n\t\twhile ($result_nest = mysql_fetch_array($query_nest)) {\n\t\t\t$tags[] = $result_nest['tag'];\n\t\t}\n\t\t\t\n\t\t$description = truncate(trim(sanitize(Markdown($result['description']),\"string\")));\n\n\t\tif (!empty($searchstring)) {\n\t\t\t$description = highlight(excerpt((trim(sanitize(Markdown($result['description']),\"string\"))),$searchstring),$searchstring);\n\t\t\t$result['title'] = highlight($result['title'],$searchstring);\n\t\t}\n\n\t\t$questions[] = array (\"title\" => $result['title'], \"created\" => $result['created'], \"updated\" => $result['updated'], \"userid\" => $result['userid'], \"link\" => $result['link'], \"slug\" => $result['slug'], \"answers\" => $result['answers'], \"accepted\" => $result['accepted'], \"kb\" => $result['kb'], \"votes\" => $result['votes'], \"id\" => $result['id'], \"tags\" => $tags, \"description\" => $description);\n\n\t}\n\n\t\t$template->set('questions',$questions);\n\n}\n"
  },
  {
    "path": "controllers/tags.php",
    "content": "<?php\n\nfunction index() {\n\tglobal $template;\n\n\t$sql = (\"select count(id) count from tags\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\t$template->set('count',$result['count']);\n\n\t$sql = (\"select tag, count(tags_questions.questionid) tagcount from tags, tags_questions where tags.id = tags_questions.tagid group by tagid order by tagcount desc\");\n\t$query = mysql_query($sql);\n\n\t$tags = array();\n\t\n\twhile ($result = mysql_fetch_array($query)) {\n\t\t$tags[] = array (\"tag\" => $result['tag'], \"count\" => $result['tagcount']);\n\t}\n\n\t$template->set('tags',$tags);\n\n\t/* Add Pagination Later */\n}"
  },
  {
    "path": "controllers/users.php",
    "content": "<?php\n\nfunction login() {\n\tglobal $template;\n\t$template->set('loginpage','1');\n}\n\nfunction view() {\n\n\tglobal $path;\n\tglobal $template;\n\n\t$userid = sanitize($path[2],\"int\");\n\n\t$sql = (\"select * from users where id = '\".escape($userid).\"'\");\n\t$query = mysql_query($sql);\n\t$user = mysql_fetch_array($query);\n\n\t$basePath = basePath();\n\n\t$template->set('user',$user);\n}\n\nfunction edit() {\n\tauthenticate(1);\n\tglobal $template;\n\t$sql = (\"select * from users where id = '\".escape($_SESSION['userid']).\"'\");\n\t$query = mysql_query($sql);\n\t$user = mysql_fetch_array($query);\n\t$basePath = basePath();\n\t$template->set('user',$user);\n}\n\nfunction update() {\n\tauthenticate(1);\n\tglobal $template;\n\n\t$name = sanitize($_POST['name'],\"string\");\n\t$email = sanitize($_POST['email'],\"email\");\n\t$password = sanitize($_POST['password'],\"string\");\n\t$password = sha1(SALT.$password.$email);\n\n\tif (!empty($_POST['password'])) {\n\t\t$sql = (\"update users set password = '\".escape($password).\"' where id = '\".escape($_SESSION['userid']).\"'\");\n\t\t$query = mysql_query($sql);\n\t}\n\n\t$sql = (\"update users set name = '\".escape($name).\"', email = '\".escape($email).\"' where id = '\".escape($_SESSION['userid']).\"'\");\n\t$query = mysql_query($sql);\n\n\t$slug = createslug($name);\n\n\t$basePath = basePath();\n\theader(\"Location: $basePath/users/view/{$_SESSION['userid']}/$slug\");\n}\n\nfunction validate() {\n\t$email = sanitize($_POST['email'],\"email\");\n\t$password = sanitize($_POST['password'],\"string\");\n\t$password = sha1(SALT.$password.$email);\n\n\t$sql = \"select * from users where email = '\".escape($email).\"' and password = '\".escape($password).\"'\";\n\t$query_result = mysql_query($sql);\n\t$user = mysql_fetch_array($query_result);\n\n\t$basePath = basePath();\n\n\tif ($user['id'] > 0) {\n\t\t$_SESSION['userid'] = $user['id'];\n\t\t$_SESSION['name'] = $user['name'];\n\t\t$_SESSION['email'] = $user['email'];\n\t\t$_SESSION['password'] = $user['password'];\n\t\t$_SESSION['points'] = $user['points'];\n\n\t\tif (!empty($_POST['returnurl'])) {\n\t\t\t$url = sanitize($_POST['returnurl'],\"url\");\n\t\t\theader(\"Location: {$url}\");\n\t\t}  else {\n\n\t\t\theader(\"Location: $basePath\");\n\t\t}\n\t} else {\n\t\theader(\"Location: $basePath/users/login\");\n\t}\n}\n\nfunction register() {\n\n}\n\nfunction create() {\n\t$name = sanitize($_POST['name'],\"string\");\n\t$email = sanitize($_POST['email'],\"email\");\n\t$password = sanitize($_POST['password'],\"string\");\n\t$password = sha1(SALT.$password.$email);\n\n\t$sql = (\"insert into users (name,email,password,points,moderator,created,lastactivity) values ('\".escape($name).\"','\".escape($email).\"','\".escape($password).\"','1','0',NOW(),NOW())\");\n\t$query = mysql_query($sql);\n\n\tvalidate();\n\n}\n\nfunction logout() {\n\tsession_destroy();\n\tsession_start();\n\t$_SESSION['userid'] = '';\n\n}\n\nfunction index() {\n\tglobal $template;\n\n\t$sql = (\"select count(id) count from users\");\n\t$query = mysql_query($sql);\n\t$result = mysql_fetch_array($query);\n\t$template->set('count',$result['count']);\n\n\t$sql = (\"select * from users order by points desc, name asc\");\n\t$query = mysql_query($sql);\n\n\t$users = array();\n\n\twhile ($result = mysql_fetch_array($query)) {\n\t\t$users[] = array (\"id\" => $result['id'], \"name\" => $result['name'], \"points\" => $result['points']);\n\t}\n\n\t$template->set('users',$users);\n\n\t/* Add Pagination Later */\n}"
  },
  {
    "path": "css/main.css",
    "content": "html, body, div, span, applet, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\na, abbr, acronym, address, big, cite, code,\ndel, dfn, em, font, img, ins, kbd, q, s, samp,\nsmall, strike, strong, sub, sup, tt, var,\ndl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td {\n\tmargin: 0;\n\tpadding: 0;\n\tborder: 0;\n\toutline: 0;\n\tfont-weight: inherit;\n\tfont-style: inherit;\n\tfont-size: 100%;\n\tfont-family: inherit;\n\tvertical-align: baseline;\n}\n/* remember to define focus styles! */\n:focus {\n\toutline: 0;\n}\nbody {\n\tline-height: 1;\n\tcolor: black;\n\tbackground: white;\n \n}\nol, ul {\n\tline-height: 130%;\n}\n\n/* tables still need 'cellspacing=\"0\"' in the markup */\ntable {\n\tborder-collapse: separate;\n\tborder-spacing: 0;\n}\ncaption, th, td {\n\ttext-align: left;\n\tfont-weight: normal;\n}\nblockquote:before, blockquote:after,\nq:before, q:after {\n\tcontent: \"\";\n}\nblockquote, q {\n\tquotes: \"\" \"\";\n}\n\n\nbody {\n\tfont-family:Arial,\"Bitstream Vera Sans\",sans-serif;\n\tfont-size:15px;\n\tcolor: #333;\n}\n\np {\n\tcolor: #333333;\n}\n\na {\n\ttext-decoration: none;\n\tborder-bottom: 1px dotted #333333;\n\tcolor: #333333;\n}\n\npre {\n\tfont-size: 11px;\n\tbackground-color: #D3F6FF;\n\tpadding: 5px;\n\tmax-height: 200px;\n\toverflow: auto;\n\tline-height: 130%;\n}\n\n* html pre { \n   height: expression( this.scrollHeight > 199 ? \"200px\" : \"auto\" ); /* sets max-height for IE */\n}\n\n#container {\n\twidth: 960px;\n\tmargin: 0 auto;\n \n}\n\n.textbox {\n\twidth: 654px;\n\tborder: 1px solid #d1dbbd;\n\tcolor: #666666;\n\tfont-size: 15px;\n\tpadding: 3px;\n}\n\n.textarea {\n\twidth: 654px;\n\tborder: 1px solid #d1dbbd;\n\tcolor: #666666;\n\tfont-size: 15px;\n\tpadding: 3px;\n\theight: 300px;\n}\n\nh1 {\n\tcolor: #333333;\n\tfont-size: 20px;\n\tfont-weight: bold;\n\tpadding-left: 5px;\n\tpadding-bottom: 7px;\n}\n\nh2 {\n\tcolor: #333333;\n\tfont-size: 17px;\n\tfont-weight: bold;\n\tpadding-left: 5px;\n\tpadding-top: 7px;\n\tpadding-bottom: 7px;\n}\n\nh3 {\n\tcolor: #333333;\n\tfont-size: 15px;\n\tfont-weight: bold;\n\tpadding-left: 5px;\n\tpadding-top: 7px;\n\tpadding-bottom: 7px;\n}\n\np {\n\tline-height: 130%;\n}\n\n.button {\n\tborder: 1px solid #ccc;\n\tcolor: #666666;\n\tfont-size: 15px;\n\tpadding: 3px;\n}\n\nstrong {\n\tfont-weight: bold;\n}\n\n \n\n/* questions/ask */\n\n \n/*\n* html div#preview { \n   height: expression( this.scrollHeight > 499 ? \"500px\" : \"auto\" ); /* sets max-height for IE \n}\ndiv#preview {\n   max-height: 500px; /* sets max-height value for all standards-compliant browsers \n}\n*/\n\n.questionsview_rating {\n\tfloat: left;\n}\n\n.questionsview_box {\n\tfont-weight: bold;\n\tfont-size: 12px;\n\tmargin-right: 20px;\n\twidth: 38px;\n}\n\n.noborder {\n\tborder: 0px !important;\n\tfloat:left;\n\tmargin-top:10px !important;\n\tpadding: 0px !important;\n}\n\n.nopadding {\n\tpadding-right: 5px !important;\n}\n\n\n\n\n.questionsview_vote {\n\tcolor: #000;\n\tfont-weight: bold;\n\ttext-align: center;\n\tfont-size: 30px;\n}\n\n.questionsview_down {\n\tpadding-top: 3px;\n\tpadding-bottom: 3px;\n\ttext-align: center;\n\tfont-size:25px;\n\tcolor: #555;\n\tcursor: pointer;\n}\n\n.questionsview_up {\n\tpadding-top: 3px;\n\tpadding-bottom: 3px;\n\ttext-align: center;\n\tfont-size:25px;\n\tcolor: #555;\n\tcursor: pointer;\n}\n\n.questionsview_fave {\n\tpadding-top: 3px;\n\tpadding-bottom: 3px;\n\ttext-align: center;\n\tfont-size:25px;\n\tcolor: #555;\n\tcursor: pointer;\n}\n\n.questionsview_question {\n\tpadding-top: 15px;\n\tpadding-bottom: 15px;\n\tmargin-top: 10px;\n\tmargin-bottom: 10px;\n\tborder-top: 1px solid #ccc;\n\tborder-bottom: 1px solid #ccc;\n\twidth: 658px;\n\tpadding-left: 5px;\n\tpadding-right: 5px;\n}\n\n.questionsview_answer {\n\tpadding-top: 15px;\n\tpadding-bottom: 15px;\n\tmargin-top: 10px;\n\tmargin-bottom: 0px;\n\tborder-top: 1px solid #ccc;\n\twidth: 658px;\n\tpadding-left: 5px;\n\tpadding-right: 5px;\n}\n\n.questionsview_form {\n\tpadding-top: 15px;\n\tpadding-bottom: 15px;\n\tmargin-top: 10px;\n\tmargin-bottom: 10px;\n\tborder-top: 1px solid #ccc;\n\twidth: 668px;\n}\n\n.questionsview_answerdescription {\n\tfloat:left;\n\twidth: 600px;\n}\n\n.questionsview_questiondescription {\n\tfloat:left;\n\twidth: 600px;\n}\n\n.voteselected {\n\tcolor: #21a5ca !important;\n\tfont-weight: bold !important;\n}\n\n#navigation {\n\tbackground-color: #16bae2;\n\n\tmargin-bottom: 30px;\n\tcolor: #ffffff;\n\ttext-shadow: 0px 2px 3px #d3d4aa;\n\tfont-size: 12px;\n\tfont-weight: bold;\n\tborder-bottom: 2px solid #21a5ca;\n\n}\n\n#navigation a {\n\tcolor: white;\n\tborder-bottom: 0px;\n\tfont-weight: bold;\n}\n\n.navcenter {\n\twidth: 960px;\n\tmargin: 0 auto;\n\ttext-align:center;\n}\n\n.navcenter input {\n\theight: 20px;\n\twidth: 400px;\n\tmargin: 5px;\n\tfont-size: 14px;\n\tpadding: 2px;\n \n\tcolor: #666;\n\t-moz-border: 3px;\n\tborder: 1px solid #21a5ca;\n\tmargin-left: 0px !important;\n}\n\n#navigation ol {\n\tlist-style: none;\n\tpadding: 0;\n\tmargin: 0 !important;\n}\n\n#navigation li {\n\tfloat: left;\n\tpadding: 10px;\n\tpadding-left:12px;\n\tpadding-right:12px;\n\tborder-right: 1px solid #13a1c9;\n\tborder-left: 1px solid #45c9e9;\n} \n\n#navigation li:hover {\n\tbackground-color: #45c6e6;\n\tcursor:pointer;\n}\n\nbody {\n\tmargin-bottom: 30px;\n}\n\n#leftpanel {\n\twidth: 658px;\n\tfloat: left;\n}\n\n#rightpanel {\n\twidth: 250px;\n\tfloat:right; \n}\n\n.userdetails {\n\tborder: 1px solid #d8dcdc;\n\t-moz-border-radius: 5px;\n\tpadding: 10px;\n\tbackground-color: #eee;\n\tcolor: #666;\n\tfont-size: 12px;\n\tfont-weight: bold;\n\tline-height:1.3em;\n\ttext-align:right;\n\n}\n\n\n.userlogin {\n\tborder: 1px solid #ccc;\n\t-moz-border-radius: 5px;\n\tpadding: 10px;\n\tbackground-color: #fff;\n\tcolor: #666;\n\tfont-size: 12px;\n\tfont-weight: bold;\n\tline-height:1.3em;\n\tmargin-top: 10px;\n \n\n}\n\n.questionsview_userbox {\n\tfloat: right;\n}\n\n.userbox {\n\tpadding: 3px;\n\tpadding-right: 10px;\n\tpadding-left: 10px;\n\tbackground-color: #eee;\n\tfont-size: 10px;\n\tfont-weight: bold;\n\tborder: 1px solid #ccc;\n\t-moz-border-radius-bottomright:6px;\n\t-moz-border-radius-topleft:6px;\n\tcolor: #666;\n}\n\n.userbox a {\n\tborder-bottom: 0px;\n}\n\n.questionsview_details {\n\tpadding: 3px;\n\tpadding-right: 10px;\n\tpadding-left: 10px;\n\tbackground-color: #eee;\n\tfont-size: 10px;\n\tfont-weight: bold;\n\tborder: 1px solid #ccc;\n\t-moz-border-radius-bottomright:6px;\n\t-moz-border-radius-topleft:6px;\n\tcolor: #666;\n\tfloat: right;\n\tmargin-right: 10px;\n}\n\n.questionsview_details a {\n\tborder-bottom: 0px;\n}\n\n.questionsview_options {\n\tpadding: 3px;\n\tpadding-right: 10px;\n\tpadding-left: 10px;\n\tbackground-color: #eee;\n\tfont-size: 10px;\n\tfont-weight: bold;\n\tborder: 1px solid #ccc;\n\t-moz-border-radius-bottomright:6px;\n\t-moz-border-radius-topleft:6px;\n\tcolor: #666;\n\tfloat: right;\n\tmargin-right: 10px;\n}\n\n.questionsview_options a {\n\tborder-bottom: 0px;\n}\n\npre {\n\tmargin-top: 10px;\n\tmargin-bottom: 10px;\n\tfont-size: 13px;\n}\n\n.pagination {\n\tfloat: left;\n\tpadding-top: 7px;\n\tpadding-bottom:7px;\n\tmargin-left: 20px;\n}\n\n.pagination a {\n\ttext-decoration: none;\n\tpadding: 5px;\n\tborder: 1px solid #eee;\n\tmargin-right: 4px;\n}\n\n.selected {\n\ttext-decoration: none;\n\tpadding: 5px;\n\tbackground-color: #eee;\n\tborder: 1px solid #eee;\n\tfont-weight: bold;\n\tmargin-right: 4px;\n\tcursor: pointer;\n}\n\n.bottompagination {\n\tborder-top: 1px solid #ccc;\n\tpadding-top: 10px;\n\twidth: 668px;\n}\n\n.toppagination {\n\tborder-bottom: 1px solid #ccc;\n\tpadding-bottom: 10px;\n\tmargin-bottom: 10px;\n\twidth: 668px;\n}\n\n.questionsgrid_toppagination {\n\tpadding-bottom: 10px;\n\tpadding-top: 10px;\n\n\twidth: 668px;\n\tborder-top: 1px solid #ccc;\n\tborder-bottom: 1px solid #ccc;\n\tmargin-top: 10px;\n\tmargin-bottom: 0px;\n}\n\n.questionsgrid_bottompagination {\n\tpadding-bottom: 10px;\n\tpadding-top: 10px;\n\n\twidth: 668px;\n\tborder-top: 1px solid #ccc;\n\tborder-bottom: 1px solid #ccc;\n}\n\n.questionsview_accepted {\n\tpadding: 3px;\n\tpadding-right: 10px;\n\tpadding-left: 10px;\n\tfont-size: 10px;\n\tfont-weight: bold;\n\t-moz-border-radius-bottomright:6px;\n\t-moz-border-radius-topleft:6px;\n\tfloat: right;\n\tmargin-right: 10px;\n\tborder:1px solid #0d9fca;\n\tbackground-color:#14abd7;\n\tcolor:#fff;\n}\n\n.questionsview_accept {\n\tpadding: 3px;\n\tpadding-right: 10px;\n\tpadding-left: 10px;\n\tfont-size: 10px;\n\tfont-weight: bold;\n\t-moz-border-radius-bottomright:6px;\n\t-moz-border-radius-topleft:6px;\n\tfloat: right;\n\tmargin-right: 10px;\n\tborder:1px solid #6dc900;\n\tbackground-color: #6dc900;\n\tcolor:#fff;\n\tcursor: pointer;\n}\n\n.questionsview_accept a {\n\ttext-decoration: none;\n\tborder-bottom: 0px;\n\tcolor: #fff;\n}\n\n.questionsgrid_title a {\n\tfont-size: 16px;\n\tfont-weight: bold;\n\tborder-bottom: 0px;\n\tcolor: #666;\n\n}\n\n.questionsgrid_description a {\n\tfont-size: 14px;\n\tcolor: #666;\n\tfont-weight: normal;\n}\n\n.tags_list {\n\tline-height: 1.5em;\n\tborder-top:1px solid #ccc;\n\tmargin-top: 10px;\n\tpadding-top: 10px;\n}\n\n.tags_list li {\n\tmargin-top: 5px !important;\n\tmargin-right: 10px !important;\n}\n\n.highlight {\n\tbackground-color: #d3f6ff;\n\tcolor: #333;\n}\n\n.comments {\n\tclear: both;\n\tpadding-top: 20px;\n\n}\n\n.comments a {\n\tfont-size: 12px;\n\tfont-weight: bold;\n\tcolor: #14abd7;\n\ttext-decoration: none;\n\tborder-bottom: 1px dotted #14abd7;\n}\n\n.commentsadd {\n\tborder-top:1px dotted #ccc;\n\tpadding-top: 10px;\n \n\twidth: 580px;\n\tpadding-left: 5px;\n\tpadding-right: 5px;\n}\n\n.commenttextarea {\n\twidth: 570px;\n\tborder: 1px solid #ccc;\n\tcolor: #666666;\n\tfont-size: 12px;\n\tpadding: 3px;\n\theight: 50px;\n}\n\n.smallbutton {\n\tborder: 1px solid #ccc;\n\tcolor: #666666;\n\tfont-size: 11px;\n\tpadding: 2px;\n\tmargin-top: 2px;\n}\n\n.comment {\n\tborder-top:1px dotted #ccc;\n\tpadding-top: 5px;\n\tpadding-bottom: 5px;\n\twidth: 580px;\n\tpadding-left: 5px;\n\tpadding-right: 5px;\n\tfont-size: 12px;\n\tcolor: #666;\n\tline-height: 1.4em;\n}\n\n.comment a {\n\tcolor: #666;\n\tborder-bottom: 1px dotted #666;\n}\n\n.viewallcomments {\n\tdisplay:none;\n}\n\n.comment_text {\n\tfloat:left;\n\twidth:520px;\n\tpadding-right: 10px;\n}\n\n.commentfave {\n\tfloat:left;\n\tfont-size:15px;\n\tfont-weight:bold;\n\tpadding-top:2px;\n\twidth:15px;\n\tcolor:#999;\n\ttext-align:center;\n\tcursor: pointer;\n}\n\n.commentdel {\n\tfloat:left;\n\tfont-size:15px;\n\tfont-weight:bold;\n\tpadding-top:1px;\n\twidth:15px;\n\tcolor:#999;\n\ttext-align:center;\n\tcursor: pointer;\n}\n\n.commentfavevotes {\n\tfloat:left;\n\tfont-size:15px;\n\tfont-weight:bold;\n\tpadding-top:2px;\n\twidth:15px;\n\tcolor:#ccc;\n\ttext-align:left;\n}\n\n#alert {\n\toverflow: hidden;\n\twidth: 100%;\n\ttext-align: center;\n\tposition: fixed;\n\ttop: 0;\n\tleft: 0;\n\tbackground-color: #d3f6ff;\n\theight: 0;\n\tcolor: #333;\n\tfont: 17px/36px arial, sans-serif;\n\tfont-weight: bold;\n\n}\n\nhtml {\n     overflow: -moz-scrollbars-vertical;\n\t overflow-y: scroll;\n}\n\n\n/* markdown */\n\n.markdown {\n\tpadding-top: 5px;\n}\n\n.markdown h1, .markdown  h2, .markdown  h3, .markdown h4 {\n\tpadding-top:7px;\n\tpadding-left:0px;\n}\n\n.markdown hr {\n\tcolor: #ccc;\n\tbackground-color: #ccc;\n\theight: 1px;\n\tborder: 0px;\n\n}\n\n.markdown ol, .markdown li {\n\tmargin-left: 15px;\n}\n\n.markdown blockquotes {\n\tborder-left: 1px solid #ccc;\n}\n\n.markdown em {\n\tfont-style: italic;\n}\n\n.questionsgrid_description {\n\tpadding-top: 5px;\n\tdisplay: block;\n\tline-height: 1.1em;\n}\n\n.markdown {\n\tline-height: 1.2em;\n}\n\n.textalert {\n\tborder: 1px solid #21a5ca !important;\n}\n\n.q {\n\tbackground-color:#14abd7;\n\tborder:1px solid #14abd7;\n\tcolor:#fff;\n\tmargin-left:10px;\n}\n\n.kb {\n\tbackground-color:#d3f6ff;\n\tborder:1px solid #d3f6ff;\n\tcolor:#333;\n\tmargin-left:10px;\n}\n\n.footer {\n\twidth: 940px;\n\ttext-align: right;\n\tmargin-top: 40px;\n\tpadding-right:20px;\n\tpadding-top: 10px;\n\tborder-top: 1px dotted #ccc;\n\tdisplay: block;\n\tfont-family: verdana;\n\tfont-size: 10px;\n\tpadding-bottom:10px;\n\tline-height:15px;\n\tmargin: 0 auto;\n}"
  },
  {
    "path": "css/prettify.css",
    "content": "/* Pretty printing styles. Used with prettify.js. */\n\n.str { color: #080; }\n.kwd { color: #075c70; }\n.com { color: #800; }\n.typ { color: #606; }\n.lit { color: #066; }\n.pun { color: #16bae2; }\n.pln { color: #000; }\n.tag { color: #008; }\n.atn { color: #606; }\n.atv { color: #080; }\n.dec { color: #606; }\npre.prettyprint {  }\n\n@media print {\n  .str { color: #060; }\n  .kwd { color: #006; font-weight: bold; }\n  .com { color: #600; font-style: italic; }\n  .typ { color: #404; font-weight: bold; }\n  .lit { color: #044; }\n  .pun { color: #440; }\n  .pln { color: #000; }\n  .tag { color: #006; font-weight: bold; }\n  .atn { color: #404; }\n  .atv { color: #060; }\n}\n"
  },
  {
    "path": "css/tagscomplete.css",
    "content": " \nul.holder { margin: 0; border: 1px solid #d1dbbd; overflow: hidden; height: auto !important; height: 1%; padding: 4px 5px 0;  color: #333;}\n*:first-child+html ul.holder { padding-bottom: 2px; } * html ul.holder { padding-bottom: 2px; } /* ie7 and below */\nul.holder li { float: left; list-style-type: none; margin: 0 5px 2px 0; white-space:nowrap;}\nul.holder li.bit-box, ul.holder li.bit-input input { font: 10px \"Lucida Grande\", \"Verdana\"; }\nul.holder li.bit-box { -moz-border-radius-topleft: 6px;-moz-border-radius-bottomright: 6px; color:#797953;  -webkit-border-radius: 6px; border-radius: 6px; border: 1px solid #d3d4aa; background: #e7e9d1; padding: 1px 5px 2px; }\nul.holder li.bit-box-focus { border-color: #d3d4aa; background: #CAD8F3; color: #fff; }\nul.holder li.bit-input input { width: auto; overflow:visible; margin: 0; border: 0px; outline: 0; } /* no left/right padding here please */\nul.holder li.bit-input input.smallinput { width: 20px; }\n  \n#add { border: 1px solid #ccc; width: 550px; margin: 50px; padding: 20px 30px 10px; }\nform .holder ol li { list-style-type: none; }\nform .holder  ol { font: 11px \"Lucida Grande\", \"Verdana\"; margin: 0; padding: 0; }\nform .holder ol li.input-text { margin-bottom: 10px; list-style-type: none; padding-bottom: 10px; }\nform .holder  ol li.input-text label { font-weight: bold; cursor: pointer; display: block; font-size: 13px; margin-bottom: 10px; }\nform .holder ol li.input-text input { width: 588px; padding: 3px; font: 11px \"Lucida Grande\", \"Verdana\"; border: 1px solid #fff; }\nform ul.holder { width: 650px; }\nform .holder ul { margin: 0 !important }\nul.holder li.bit-box, #apple-list ul.holder li.bit-box { padding-right: 15px; position: relative; z-index:1000;}\n#apple-list ul.holder li.bit-input { margin: 0; }\n#apple-list ul.holder li.bit-input input.smallinput { width: 5px; }\nul.holder li.bit-hover { background: #BBCEF1; border: 1px solid #6D95E0; }\nul.holder li.bit-box-focus { border-color: #598BEC; background: #ffffff; color: #fff; }\nul.holder li.bit-box a.closebutton { position: absolute; right: 4px; top: 5px; display: block; width: 7px; height: 7px; font-size: 1px; background: url('/qwench/img/close.gif'); }\nul.holder li.bit-box a.closebutton:hover { background-position: 7px; }\nul.holder li.bit-box-focus a.closebutton, ul.holder li.bit-box-focus a.closebutton:hover { background-position: bottom; }\n \n\nul a {\nborder-bottom: 0px;\n}\n.facebook-auto { display: none; position: absolute; width: 512px; background: #fff; border-bottom: 0px; }\n.facebook-auto .default { padding: 5px 7px; border: 1px solid #ccc; border-width: 0 1px 1px;font-family:\"Lucida Grande\",\"Verdana\"; font-size:11px; }\n.facebook-auto ul { display: none; margin: 0; padding: 0; overflow: auto; position:absolute; z-index:9999}\n.facebook-auto ul li { padding: 5px 12px; z-index: 1000; cursor: pointer; margin: 0; list-style-type: none; border: 1px solid #ccc; border-width: 0 1px 1px; font: 11px \"Lucida Grande\", \"Verdana\"; background-color: #fff }\n.facebook-auto ul li em { font-weight: bold; font-style: normal; background: #ccc; }\n.facebook-auto ul li.auto-focus { background: #e7e9d1; color: #333; }\n.facebook-auto ul li.auto-focus em { background: none; }\n.deleted { background-color:#d3d4aa !important; }\n.hidden { display:none;}\n\n#demo ul.holder li.bit-input input { padding: 2px 0 1px; border: 1px solid #ccc; }\n.ie6fix {height:1px;width:1px; position:absolute;top:0px;left:0px;z-index:1;}"
  },
  {
    "path": "css/wmd.css",
    "content": "\n.wmd-panel\n{\n \n}\n\n#wmd-editor\n{\n \n}\n\n#wmd-button-bar \n{\n\twidth: 100%;\n\tpadding-top: 5px;\n\tpadding-bottom: 5px;\n \n}\n\n#wmd-input \n{ \n\twidth: 654px;\n\tborder: 1px solid #d1dbbd;\n\tcolor: #666666;\n\tfont-size: 15px;\n\tpadding: 3px;\n\theight: 300px;\n}\n\n#wmd-preview \n{ \n\toverflow: auto;\n\tbackground-color: #EFFCFF;\n\twidth: 633px;  \n\tpadding: 15px;\n}\n\n#wmd-output \n{ \n\tbackground-color: Pink;\n}\n\n#wmd-button-row \n{\n\tposition: relative; \n\tmargin-left: 5px;\n\tmargin-right: 5px;\n\tmargin-bottom: 5px;\n\tmargin-top: 10px;\n\tpadding: 0px;  \n\theight: 20px;\n}\n\n.wmd-spacer\n{\n\twidth: 1px; \n\theight: 20px; \n\tmargin-left: 14px;\n\t\n\tposition: absolute;\n\tbackground-color: #fff;\n\tdisplay: inline-block; \n\tlist-style: none;\n}\n\n.wmd-button\n{\n\twidth: 20px; \n\theight: 20px; \n\tmargin-left: 5px;\n\tmargin-right: 5px;\n\t\n\tposition: absolute;\n\tbackground-image: url(../img/wmd-buttons.png);\n\tbackground-repeat: no-repeat;\n\tbackground-position: 0px 0px;\n\tdisplay: inline-block; \n\tlist-style: none;\n}\n\n.wmd-button > a\n{\n\twidth: 20px; \n\theight: 20px; \n\tmargin-left: 5px;\n\tmargin-right: 5px;\n\t\n\tposition: absolute;\n\tdisplay: inline-block; \n}\n\n\n/* sprite button slicing style information */\n#wmd-button-bar #wmd-bold-button    {left: 0px;   background-position: 0px 0;}\n#wmd-button-bar #wmd-italic-button  {left: 25px;  background-position: -20px 0;}\n#wmd-button-bar #wmd-spacer1        {left: 50px;}\n#wmd-button-bar #wmd-link-button    {left: 75px;  background-position: -40px 0;}\n#wmd-button-bar #wmd-quote-button   {left: 100px;  background-position: -60px 0;}\n#wmd-button-bar #wmd-code-button    {left: 125px;  background-position: -80px 0;}\n#wmd-button-bar #wmd-image-button   {left: 150px;  background-position: -100px 0;}\n#wmd-button-bar #wmd-spacer2        {left: 175px;}\n#wmd-button-bar #wmd-olist-button   {left: 200px;  background-position: -120px 0;}\n#wmd-button-bar #wmd-ulist-button   {left: 225px; background-position: -140px 0;}\n#wmd-button-bar #wmd-heading-button {left: 250px; background-position: -160px 0;}\n#wmd-button-bar #wmd-hr-button      {left: 275px; background-position: -180px 0;}\n#wmd-button-bar #wmd-spacer3        {left: 300px;}\n#wmd-button-bar #wmd-undo-button    {left: 325px; background-position: -200px 0;}\n#wmd-button-bar #wmd-redo-button    {left: 350px; background-position: -220px 0;}\n#wmd-button-bar #wmd-help-button    {right: 0px; background-position: -240px 0;}\n\n\n.wmd-prompt-background\n{\n\tbackground-color: Black;\n}\n\n.wmd-prompt-dialog\n{\n\tborder: 1px solid #999999;\n\tbackground-color: #F5F5F5;\n}\n\n.wmd-prompt-dialog > div {\n\tfont-size: 0.8em;\n\tfont-family: arial, helvetica, sans-serif;\n}\n\n\n.wmd-prompt-dialog > form > input[type=\"text\"] {\n\tborder: 1px solid #999999;\n\tcolor: black;\n}\n\n.wmd-prompt-dialog > form > input[type=\"button\"]{\n\tborder: 1px solid #888888;\n\tfont-family: trebuchet MS, helvetica, sans-serif;\n\tfont-size: 0.8em;\n\tfont-weight: bold;\n}\n"
  },
  {
    "path": "db/1.txt",
    "content": "-- MySQL dump 10.11\n--\n-- Host: localhost    Database: qwench\n-- ------------------------------------------------------\n-- Server version\t5.0.51b-community-nt\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n/*!40101 SET NAMES utf8 */;\n/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\n/*!40103 SET TIME_ZONE='+00:00' */;\n/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n\n--\n-- Table structure for table `answers`\n--\n\nDROP TABLE IF EXISTS `answers`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `answers` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `questionid` int(10) unsigned NOT NULL,\n  `description` text character set latin1 NOT NULL,\n  `created` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `updated` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `userid` int(10) unsigned NOT NULL,\n  `accepted` int(10) unsigned NOT NULL,\n  `votes` int(11) NOT NULL default '0',\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\n--\n-- Table structure for table `answers_votes`\n--\n\nDROP TABLE IF EXISTS `answers_votes`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `answers_votes` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `answerid` int(10) unsigned NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  `vote` int(11) NOT NULL,\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=72 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\n--\n-- Table structure for table `comments`\n--\n\nDROP TABLE IF EXISTS `comments`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `comments` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `type` int(10) unsigned NOT NULL,\n  `comment` text character set latin1 NOT NULL,\n  `votes` int(10) unsigned NOT NULL default '0',\n  `created` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `userid` int(10) unsigned NOT NULL,\n  `typeid` int(10) unsigned NOT NULL,\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=49 DEFAULT CHARSET=utf8;\nSET character_set_client = @saved_cs_client;\n\n--\n-- Table structure for table `comments_votes`\n--\n\nDROP TABLE IF EXISTS `comments_votes`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `comments_votes` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `commentid` int(10) unsigned NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;\nSET character_set_client = @saved_cs_client;\n\n--\n-- Table structure for table `favorites`\n--\n\nDROP TABLE IF EXISTS `favorites`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `favorites` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `questionid` int(10) unsigned NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\n--\n-- Table structure for table `questions`\n--\n\nDROP TABLE IF EXISTS `questions`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `questions` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `title` text character set latin1 NOT NULL,\n  `description` text character set latin1 NOT NULL,\n  `created` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `updated` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `link` text character set latin1 NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  `slug` text character set latin1 NOT NULL,\n  `linkcache` longtext character set latin1 NOT NULL,\n  `votes` int(11) NOT NULL default '0',\n  PRIMARY KEY  (`id`),\n  FULLTEXT KEY `title` (`title`,`description`)\n) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;\nSET character_set_client = @saved_cs_client;\n\n--\n-- Table structure for table `questions_votes`\n--\n\nDROP TABLE IF EXISTS `questions_votes`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `questions_votes` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `questionid` int(10) unsigned NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  `vote` int(11) NOT NULL,\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=38 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\n--\n-- Table structure for table `tags`\n--\n\nDROP TABLE IF EXISTS `tags`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `tags` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `tag` varchar(255) character set latin1 NOT NULL,\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\n--\n-- Table structure for table `tags_questions`\n--\n\nDROP TABLE IF EXISTS `tags_questions`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `tags_questions` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `tagid` int(10) unsigned NOT NULL,\n  `questionid` int(10) unsigned NOT NULL,\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=93 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\n--\n-- Table structure for table `users`\n--\n\nDROP TABLE IF EXISTS `users`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `users` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `username` varchar(255) character set latin1 NOT NULL,\n  `password` varchar(255) character set latin1 NOT NULL,\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;\n\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\n\n-- Dump completed on 2009-09-11  7:03:59\n"
  },
  {
    "path": "db/2.txt",
    "content": "ALTER TABLE `users` ADD COLUMN `name` VARCHAR(255) NOT NULL AFTER `password`,\n ADD COLUMN `email` VARCHAR(255) NOT NULL AFTER `name`,\n ADD COLUMN `points` INTEGER UNSIGNED NOT NULL AFTER `email`,\n ADD COLUMN `moderator` INTEGER UNSIGNED NOT NULL AFTER `points`;\n ALTER TABLE `users` DROP COLUMN `username`;\n\nALTER TABLE `users` ADD COLUMN `created` DATETIME NOT NULL AFTER `moderator`,\n ADD COLUMN `lastactivity` DATETIME NOT NULL AFTER `created`;\n"
  },
  {
    "path": "db/3.txt",
    "content": "CREATE TABLE `activities` (\n  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,\n  `userid` INTEGER UNSIGNED NOT NULL,\n  `activity` INTEGER UNSIGNED NOT NULL,\n  `points` INTEGER NOT NULL,\n  PRIMARY KEY (`id`)\n)\nENGINE = MyISAM\nCHARACTER SET utf8 COLLATE utf8_general_ci;\n\n\nALTER TABLE `questions` ADD COLUMN `accepted` INTEGER UNSIGNED NOT NULL DEFAULT 0 AFTER `votes`,\n ADD COLUMN `answers` INTEGER UNSIGNED NOT NULL DEFAULT 0 AFTER `accepted`,\n ADD COLUMN `kb` INTEGER UNSIGNED NOT NULL DEFAULT 0 AFTER `answers`;\n\nALTER TABLE `activities` MODIFY COLUMN `activity` VARCHAR(255) NOT NULL DEFAULT '';\n\nALTER TABLE `activities` ADD COLUMN `created` DATETIME NOT NULL AFTER `points`;\nALTER TABLE `activities` ADD COLUMN `activityid` INTEGER UNSIGNED NOT NULL AFTER `created`;\n\nALTER TABLE `users` MODIFY COLUMN `points` INTEGER NOT NULL DEFAULT 0;\n"
  },
  {
    "path": "index.php",
    "content": "<?php\n\n/* Start Session */\n\nsession_name(\"qwench\");\nsession_start();\n\n/* Define */\n\ndefine('ROOT',DIRNAME(__FILE__));\ndefine('DS',DIRECTORY_SEPARATOR);\n\n/* Get Basic Details */\n\n$path = explode(\"/\", substr($_SERVER['PATH_INFO'],1));\n\n$controller = 'questions';\n$action = 'index';\nif (empty($_GET['type'])) { $_GET['type'] = \"active\"; }\n$norender = false;\n$noheader = false;\n\nif (!empty($path[0])) { $controller = $path[0]; if ($_GET['type'] == \"active\") { $_GET['type'] = \"\"; } }\nif (!empty($path[1])) { $action = $path[1]; if ($_GET['type'] == \"active\") { $_GET['type'] = \"\"; } }\n\n/* Include Libraries */\n\ninclude_once ROOT.DS.'config.php';\ninclude_once ROOT.DS.'libraries'.DS.'template.class.php';\ninclude_once ROOT.DS.'libraries'.DS.'helper.class.php';\n\n$template = new Template($controller,$action);\n$helper = new Helper();\n\ninclude_once ROOT.DS.'libraries'.DS.'shared.php';\ninclude_once ROOT.DS.'libraries'.DS.'markdown.php';\ninclude_once ROOT.DS.'libraries'.DS.'timeago.php';\ninclude_once ROOT.DS.'libraries'.DS.'score.php';\ninclude_once ROOT.DS.'libraries'.DS.'pagination.class.php';\ninclude_once ROOT.DS.'controllers'.DS.'helpers.php';\n\n\n/* Check Debug vs Production Mode */\nif (DEBUG_MODE == '1')\n{\n\terror_reporting(E_ALL);\n\tini_set('display_errors','On');\n}\n\n\n\n\n\n/* Basic Bootstrapping */\n\ninclude ROOT.DS.'controllers'.DS.$controller.'.php';\nif (function_exists($action)) {\n\tcall_user_func($action);\n} else {\n\tcall_user_func('index');\n}\nif ($norender == false) {\n\t$template->render($noheader);\n}"
  },
  {
    "path": "install.php",
    "content": "<?php\n\ninclude (dirname(__FILE__)).\"/config.php\";\n\nfunction db() {\n\t$dbh = mysql_connect(SERVERNAME.':'.SERVERPORT,DBUSERNAME,DBPASSWORD);\n\treturn mysql_selectdb(DBNAME,$dbh);\n}\n\n$message = 'Database import completed. ';\n$errorCount = 0;\n\n/*  We cannot assume the use configured the database right.\n    So lets be sure we can connect to the database first.\n*/\n\n    if (db() == false)\n    {\n      $message = 'Error connecting to the database. <br/>  Please edit the config.php file to match you database settings.';\n    }\n    else\n    {\n\n      $body = '';\n      $path = '';\n\n      $rollback = 0;\n      $errors = '';\n\n      $content = <<<EOD\n\n      DROP TABLE IF EXISTS `activities`;\n      SET @saved_cs_client     = @@character_set_client;\n      SET character_set_client = utf8;\n      CREATE TABLE `activities` (\n        `id` int(10) unsigned NOT NULL auto_increment,\n        `userid` int(10) unsigned NOT NULL,\n        `activity` varchar(255) NOT NULL default '',\n        `points` int(11) NOT NULL,\n        `created` datetime NOT NULL,\n        `activityid` int(10) unsigned NOT NULL,\n        PRIMARY KEY  (`id`)\n        ) ENGINE=MyISAM DEFAULT CHARSET=utf8;\nSET character_set_client = @saved_cs_client;\n\nDROP TABLE IF EXISTS `answers`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `answers` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `questionid` int(10) unsigned NOT NULL,\n  `description` text character set latin1 NOT NULL,\n  `created` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `updated` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `userid` int(10) unsigned NOT NULL,\n  `accepted` int(10) unsigned NOT NULL,\n  `votes` int(11) NOT NULL default '0',\n  PRIMARY KEY  (`id`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\nDROP TABLE IF EXISTS `answers_votes`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `answers_votes` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `answerid` int(10) unsigned NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  `vote` int(11) NOT NULL,\n  PRIMARY KEY  (`id`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\nDROP TABLE IF EXISTS `comments`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `comments` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `type` int(10) unsigned NOT NULL,\n  `comment` text character set latin1 NOT NULL,\n  `votes` int(10) unsigned NOT NULL default '0',\n  `created` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `userid` int(10) unsigned NOT NULL,\n  `typeid` int(10) unsigned NOT NULL,\n  PRIMARY KEY  (`id`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8;\nSET character_set_client = @saved_cs_client;\n\nDROP TABLE IF EXISTS `comments_votes`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `comments_votes` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `commentid` int(10) unsigned NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  PRIMARY KEY  (`id`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8;\nSET character_set_client = @saved_cs_client;\n\nDROP TABLE IF EXISTS `favorites`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `favorites` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `questionid` int(10) unsigned NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  PRIMARY KEY  (`id`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\n\nDROP TABLE IF EXISTS `questions`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `questions` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `title` text character set latin1 NOT NULL,\n  `description` text character set latin1 NOT NULL,\n  `created` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `updated` timestamp NOT NULL default '0000-00-00 00:00:00',\n  `link` text character set latin1 NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  `linkcache` longtext character set latin1 NOT NULL,\n  `votes` int(11) NOT NULL default '0',\n  `accepted` int(10) unsigned NOT NULL default '0',\n  `answers` int(10) unsigned NOT NULL default '0',\n  `kb` int(10) unsigned NOT NULL default '0',\n  `slug` text NOT NULL,\n  PRIMARY KEY  (`id`),\n  FULLTEXT KEY `title` (`title`,`description`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8;\nSET character_set_client = @saved_cs_client;\n\n\nDROP TABLE IF EXISTS `questions_votes`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `questions_votes` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `questionid` int(10) unsigned NOT NULL,\n  `userid` int(10) unsigned NOT NULL,\n  `vote` int(11) NOT NULL,\n  PRIMARY KEY  (`id`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\n\nDROP TABLE IF EXISTS `tags`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `tags` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `tag` varchar(255) character set latin1 NOT NULL,\n  PRIMARY KEY  (`id`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\nDROP TABLE IF EXISTS `tags_questions`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `tags_questions` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `tagid` int(10) unsigned NOT NULL,\n  `questionid` int(10) unsigned NOT NULL,\n  PRIMARY KEY  (`id`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\nDROP TABLE IF EXISTS `users`;\nSET @saved_cs_client     = @@character_set_client;\nSET character_set_client = utf8;\nCREATE TABLE `users` (\n  `id` int(10) unsigned NOT NULL auto_increment,\n  `password` varchar(255) character set latin1 NOT NULL,\n  `name` varchar(255) NOT NULL,\n  `email` varchar(255) NOT NULL,\n  `points` int(11) NOT NULL default '0',\n  `moderator` int(10) unsigned NOT NULL,\n  `created` datetime NOT NULL,\n  `lastactivity` datetime NOT NULL,\n  PRIMARY KEY  (`id`)\n  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\nSET character_set_client = @saved_cs_client;\n\nEOD;\n\n$q = preg_split('/;[\\r\\n]+/',$content);\n\nforeach ($q as $query) {\n  if (strlen($query) > 4) {\n    $result = mysql_query($query);\n    if (!$result) {\n      $rollback = 1;\n      $errors .= mysql_error().\"<br/>\\n\";\n    }\n  }\n}\n}\n\n?>\n<html>\n<head>\n  <title>Install</title>\n  <style>\n  body {\n    padding:0;\n    margin:0;\n    font-family: \"Lucida Grande\",Verdana,Arial,\"Bitstream Vera Sans\",sans-serif;\n    font-size: 14px;\n    color: #333333;\n  }\n  a\n  {\n    color: blue;\n    font-style: italic;\n    text-decoration: none;\n  }\n  </style>\n</head>\n<body>\n  <div class=\"setup\"><?php echo $message; ?>\n    <br/>\n    <font style=\"color: red;\">Security Alert!!!</font>\n    <br/>\n    <strong>Delete the install.php file from your server.</strong>\n    <br/>\n    <br/>\n<a href=\"index.php\"> Try out your shiny new server. click here\n</a>\n  </div>\n</body>\n</html>\n\n<?php\nunlink(install.php);\n?>\n"
  },
  {
    "path": "js/fancyalert.js",
    "content": "/*\n\njQuery Fancy Alert\nCopyright (c) 2009 Anant Garg (http://anantgarg.com)\n\nVersion: 1.0\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*/\n\n(function($){   \n  \n\t$.fancyalert = function(message){\n\t\tif ($(\"#alert\").length > 0)\t{ \n\t\t\t$(\"#alert\").html(message);\n\t\t} else {\n\t\t\tvar html = '<div id=\"alert\">'+message+'</div>';\n\t\t\t$('body').append(html);\n\t\t} \n\t\t$alert = $('#alert');\n\t\t\tif($alert.length) {\n\t\t\t\tvar alerttimer = window.setTimeout(function () {\n\t\t\t\t\t$alert.trigger('click');\n\t\t\t\t}, 3000);\n\t\t\t\t$alert.css('border-bottom','2px solid #76e3ff');\n\t\t\t\t$alert.animate({height: $alert.css('line-height') || '50px'}, 200)\n\t\t\t\t.click(function () {\n\t\t\t\t\twindow.clearTimeout(alerttimer);\n\t\t\t\t\t$alert.animate({height: '0'}, 200);\n\t\t\t\t\t$alert.css('border-bottom','0px solid #333333');\n\t\t\t\t});\n\t\t\t}\n\t};   \n  \n})(jQuery);"
  },
  {
    "path": "js/jquery.js",
    "content": "/*\n * jQuery JavaScript Library v1.3.2\n * http://jquery.com/\n *\n * Copyright (c) 2009 John Resig\n * Dual licensed under the MIT and GPL licenses.\n * http://docs.jquery.com/License\n *\n * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)\n * Revision: 6246\n */\n(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\\s)+>)[^>]*$|^#([\\w-]+)$/,f=/^.[^:#\\[\\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E===\"string\"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:\"\",jquery:\"1.3.2\",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H===\"find\"){G.selector=this.selector+(this.selector?\" \":\"\")+E}else{if(H){G.selector=this.selector+\".\"+H+\"(\"+E+\")\"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F===\"string\"){if(H===g){return this[0]&&o[G||\"attr\"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E==\"width\"||E==\"height\")&&parseFloat(F)<0){F=g}return this.attr(E,F,\"curCSS\")},text:function(F){if(typeof F!==\"object\"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E=\"\";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],\"find\",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),\"find\",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement(\"div\");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\\d+=\"(?:\\d+|null)\"/g,\"\").replace(/^\\s*/,\"\")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find(\"*\").andSelf(),F=0;E.find(\"*\").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],\"events\");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),\"filter\",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,\"closest\",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E===\"string\"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),\"not\",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E===\"string\"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is(\".\"+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,\"option\")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,\"select\")){var I=E.selectedIndex,L=[],M=E.options,H=E.type==\"select-one\";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||\"\").replace(/\\r/g,\"\")}return g}if(typeof K===\"number\"){K+=\"\"}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,\"select\")){var N=o.makeArray(K);o(\"option\",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\\d+=\"(?:\\d+|null)\"/g,\"\"):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),\"slice\",Array.prototype.slice.call(arguments).join(\",\"))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,\"table\")&&o.nodeName(O,\"tr\")?(N.getElementsByTagName(\"tbody\")[0]||N.appendChild(N.ownerDocument.createElement(\"tbody\"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:\"script\"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||\"\")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J===\"boolean\"){E=J;J=arguments[1]||{};H=2}if(typeof J!==\"object\"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L===\"object\"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)===\"[object Function]\"},isArray:function(E){return s.call(E)===\"[object Array]\"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!==\"HTML\"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\\S/.test(G)){var F=document.getElementsByTagName(\"head\")[0]||document.documentElement,E=document.createElement(\"script\");E.type=\"text/javascript\";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I===\"number\"&&G==\"curCSS\"&&!b.test(E)?I+\"px\":I},className:{add:function(E,F){o.each((F||\"\").split(/\\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?\" \":\"\")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\\s+/),function(G){return !o.className.has(F,G)}).join(\" \"):\"\"}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F==\"width\"||F==\"height\"){var L,G={position:\"absolute\",visibility:\"hidden\",display:\"block\"},K=F==\"width\"?[\"Left\",\"Right\"]:[\"Top\",\"Bottom\"];function I(){L=F==\"width\"?H.offsetWidth:H.offsetHeight;if(E===\"border\"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,\"padding\"+this,true))||0}if(E===\"margin\"){L+=parseFloat(o.curCSS(H,\"margin\"+this,true))||0}else{L-=parseFloat(o.curCSS(H,\"border\"+this+\"Width\",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F==\"opacity\"&&!o.support.opacity){L=o.attr(E,\"opacity\");return L==\"\"?\"1\":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F=\"float\"}F=F.replace(/([A-Z])/g,\"-$1\").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F==\"opacity\"&&L==\"\"){L=\"1\"}}else{if(I.currentStyle){var J=F.replace(/\\-(\\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\\d+(px)?$/i.test(L)&&/^\\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+\"px\";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement===\"undefined\"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]===\"string\"){var H=/^<(\\w+)\\s*\\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement(\"div\");o.each(F,function(P,S){if(typeof S===\"number\"){S+=\"\"}if(!S){return}if(typeof S===\"string\"){S=S.replace(/(<(\\w+)[^>]*?)\\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+\"></\"+T+\">\"});var O=S.replace(/^\\s+/,\"\").substring(0,10).toLowerCase();var Q=!O.indexOf(\"<opt\")&&[1,\"<select multiple='multiple'>\",\"</select>\"]||!O.indexOf(\"<leg\")&&[1,\"<fieldset>\",\"</fieldset>\"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,\"<table>\",\"</table>\"]||!O.indexOf(\"<tr\")&&[2,\"<table><tbody>\",\"</tbody></table>\"]||(!O.indexOf(\"<td\")||!O.indexOf(\"<th\"))&&[3,\"<table><tbody><tr>\",\"</tr></tbody></table>\"]||!O.indexOf(\"<col\")&&[2,\"<table><tbody></tbody><colgroup>\",\"</colgroup></table>\"]||!o.support.htmlSerialize&&[1,\"div<div>\",\"</div>\"]||[0,\"\",\"\"];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf(\"<table\")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]==\"<table>\"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],\"tbody\")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],\"script\")&&(!G[J].type||G[J].type.toLowerCase()===\"text/javascript\")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName(\"script\"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G==\"selected\"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G==\"type\"&&o.nodeName(J,\"input\")&&J.parentNode){throw\"type property can't be changed\"}J[G]=K}if(o.nodeName(J,\"form\")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G==\"tabIndex\"){var I=J.getAttributeNode(\"tabIndex\");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G==\"style\"){return o.attr(J.style,\"cssText\",K)}if(L){J.setAttribute(G,\"\"+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G==\"opacity\"){if(L){J.zoom=1;J.filter=(J.filter||\"\").replace(/alpha\\([^)]*\\)/,\"\")+(parseInt(K)+\"\"==\"NaN\"?\"\":\"alpha(opacity=\"+K*100+\")\")}return J.filter&&J.filter.indexOf(\"opacity=\")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+\"\":\"\"}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||\"\").replace(/^\\s+|\\s+$/g,\"\")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G===\"string\"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\\/: ]([\\d.]+)/)||[0,\"0\"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,\"parentNode\")},next:function(E){return o.nth(E,2,\"nextSibling\")},prev:function(E){return o.nth(E,2,\"previousSibling\")},nextAll:function(E){return o.dir(E,\"nextSibling\")},prevAll:function(E){return o.dir(E,\"previousSibling\")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,\"iframe\")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G==\"string\"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:\"append\",prependTo:\"prepend\",insertBefore:\"before\",insertAfter:\"after\",replaceAll:\"replaceWith\"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,\"\");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!==\"boolean\"){E=!o.className.has(this,F)}o.className[E?\"add\":\"remove\"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o(\"*\",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h=\"jQuery\"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E=\"\";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||\"fx\")+\"queue\";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G===\"fx\"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(\".\");H[1]=H[1]?\".\"+H[1]:\"\";if(G===g){var F=this.triggerHandler(\"getData\"+H[1]+\"!\",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger(\"setData\"+H[1]+\"!\",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!==\"string\"){F=E;E=\"fx\"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E==\"fx\"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});\n/*\n * Sizzle CSS Selector Engine - v0.9.3\n *  Copyright 2009, The Dojo Foundation\n *  Released under the MIT, BSD, and GPL Licenses.\n *  More information: http://sizzlejs.com/\n */\n(function(){var R=/((?:\\((?:\\([^()]+\\)|[^()]+)+\\)|\\[(?:\\[[^[\\]]*\\]|['\"][^'\"]*['\"]|[^[\\]'\"]+)+\\]|\\\\.|[^ >+~,(\\[\\\\]+)+|[>+~])(\\s*,\\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!==\"string\"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=\"\"}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw\"Syntax error, unrecognized expression: \"+(ah||Y)}if(H.call(ai)===\"[object Array]\"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!==\"\\\\\"){X[1]=(X[1]||\"\").replace(/\\\\/g,\"\");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],\"\");break}}}}if(!Z){Z=T.getElementsByTagName(\"*\")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],\"\");if(!T){return[]}break}}}if(ad==V){if(T==null){throw\"Syntax error, unrecognized expression: \"+ad}else{break}}V=ad}return aa};var I=F.selectors={order:[\"ID\",\"NAME\",\"TAG\"],match:{ID:/#((?:[\\w\\u00c0-\\uFFFF_-]|\\\\.)+)/,CLASS:/\\.((?:[\\w\\u00c0-\\uFFFF_-]|\\\\.)+)/,NAME:/\\[name=['\"]*((?:[\\w\\u00c0-\\uFFFF_-]|\\\\.)+)['\"]*\\]/,ATTR:/\\[\\s*((?:[\\w\\u00c0-\\uFFFF_-]|\\\\.)+)\\s*(?:(\\S?=)\\s*(['\"]*)(.*?)\\3|)\\s*\\]/,TAG:/^((?:[\\w\\u00c0-\\uFFFF\\*_-]|\\\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\\((even|odd|[\\dn+-]*)\\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\))?(?=[^-]|$)/,PSEUDO:/:((?:[\\w\\u00c0-\\uFFFF_-]|\\\\.)+)(?:\\((['\"]*)((?:\\([^\\)]+\\)|[^\\2\\(\\)]*)+)\\2\\))?/},attrMap:{\"class\":\"className\",\"for\":\"htmlFor\"},attrHandle:{href:function(T){return T.getAttribute(\"href\")}},relative:{\"+\":function(aa,T,Z){var X=typeof T===\"string\",ab=X&&!/\\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},\">\":function(Z,U,aa){var X=typeof U===\"string\";if(X&&!/\\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},\"\":function(W,U,Y){var V=L++,T=S;if(!U.match(/\\W/)){var X=U=Y?U:U.toUpperCase();T=P}T(\"parentNode\",U,V,W,X,Y)},\"~\":function(W,U,Y){var V=L++,T=S;if(typeof U===\"string\"&&!U.match(/\\W/)){var X=U=Y?U:U.toUpperCase();T=P}T(\"previousSibling\",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!==\"undefined\"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!==\"undefined\"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute(\"name\")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=\" \"+W[1].replace(/\\\\/g,\"\")+\" \";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(\" \"+Y.className+\" \").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\\\/g,\"\")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]==\"nth\"){var U=/(-?)(\\d*)n((?:\\+|-)?\\d*)/.exec(T[2]==\"even\"&&\"2n\"||T[2]==\"odd\"&&\"2n+1\"||!/\\D/.test(T[2])&&\"0n+\"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\\\/g,\"\");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]===\"~=\"){X[4]=\" \"+X[4]+\" \"}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]===\"not\"){if(X[3].match(R).length>1||/^\\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!==\"hidden\"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\\d/i.test(T.nodeName)},text:function(T){return\"text\"===T.type},radio:function(T){return\"radio\"===T.type},checkbox:function(T){return\"checkbox\"===T.type},file:function(T){return\"file\"===T.type},password:function(T){return\"password\"===T.type},submit:function(T){return\"submit\"===T.type},image:function(T){return\"image\"===T.type},reset:function(T){return\"reset\"===T.type},button:function(T){return\"button\"===T.type||T.nodeName.toUpperCase()===\"BUTTON\"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U===\"contains\"){return(Z.textContent||Z.innerText||\"\").indexOf(V[3])>=0}else{if(U===\"not\"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case\"only\":case\"first\":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z==\"first\"){return true}U=T;case\"last\":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case\"nth\":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute(\"id\")===T},TAG:function(U,T){return(T===\"*\"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(\" \"+(U.className||U.getAttribute(\"class\"))+\" \").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+\"\",X=W[2],U=W[4];return T==null?X===\"!=\":X===\"=\"?Z===U:X===\"*=\"?Z.indexOf(U)>=0:X===\"~=\"?(\" \"+Z+\" \").indexOf(U)>=0:!U?Z&&T!==false:X===\"!=\"?Z!=U:X===\"^=\"?Z.indexOf(U)===0:X===\"$=\"?Z.substr(Z.length-U.length)===U:X===\"|=\"?Z===U||Z.substr(0,U.length+1)===U+\"-\":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\\[]*\\])(?![^\\(]*\\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)===\"[object Array]\"){Array.prototype.push.apply(U,X)}else{if(typeof X.length===\"number\"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if(\"sourceIndex\" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement(\"form\"),V=\"script\"+(new Date).getTime();U.innerHTML=\"<input name='\"+V+\"'/>\";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!==\"undefined\"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!==\"undefined\"&&W.getAttributeNode(\"id\").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!==\"undefined\"&&Y.getAttributeNode(\"id\");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement(\"div\");T.appendChild(document.createComment(\"\"));if(T.getElementsByTagName(\"*\").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]===\"*\"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML=\"<a href='#'></a>\";if(T.firstChild&&typeof T.firstChild.getAttribute!==\"undefined\"&&T.firstChild.getAttribute(\"href\")!==\"#\"){I.attrHandle.href=function(U){return U.getAttribute(\"href\",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement(\"div\");U.innerHTML=\"<p class='TEST'></p>\";if(U.querySelectorAll&&U.querySelectorAll(\".TEST\").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement(\"div\");T.innerHTML=\"<div class='test e'></div><div class='test'></div>\";if(T.getElementsByClassName(\"e\").length===0){return}T.lastChild.className=\"e\";if(T.getElementsByClassName(\"e\").length===1){return}I.order.splice(1,0,\"CLASS\");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!==\"undefined\"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U==\"previousSibling\"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U==\"previousSibling\"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!==\"string\"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!==\"HTML\"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X=\"\",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,\"\")}T=I.relative[T]?T+\"*\":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[\":\"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=\":not(\"+V+\")\"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,\"events\")||o.data(I,\"events\",{}),J=o.data(I,\"handle\")||o.data(I,\"handle\",function(){return typeof o!==\"undefined\"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\\s+/),function(M,N){var O=N.split(\".\");N=O.shift();H.type=O.slice().sort().join(\".\");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent(\"on\"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,\"events\"),F,E;if(G){if(H===g||(typeof H===\"string\"&&H.charAt(0)==\".\")){for(var I in G){this.remove(K,I+(H||\"\"))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\\s+/),function(M,O){var Q=O.split(\".\");O=Q.shift();var N=RegExp(\"(^|\\\\.)\"+Q.slice().sort().join(\".*\\\\.\")+\"(\\\\.|$)\");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,\"handle\"),false)}else{if(K.detachEvent){K.detachEvent(\"on\"+O,o.data(K,\"handle\"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,\"handle\");if(L){L.elem=null}o.removeData(K,\"events\");o.removeData(K,\"handle\")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I===\"object\"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf(\"!\")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,\"handle\");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,\"a\")&&G==\"click\"))&&H[\"on\"+G]&&H[\"on\"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,\"a\")&&G==\"click\")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(\".\");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp(\"(^|\\\\.)\"+L.slice().sort().join(\".*\\\\.\")+\"(\\\\.|$)\");E=(o.data(this,\"events\")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:\"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which\".split(\" \"),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp(\"(^|\\\\.)\"+G[0]+\"(\\\\.|$)\");o.each((o.data(this,\"events\").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:\"mouseenter\",mouseout:\"mouseleave\"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F==\"unload\"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp(\"(^|\\\\.)\"+H.type+\"(\\\\.|$)\"),G=true,F=[];o.each(o.data(this,\"events\").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,\"closest\")-o.data(I.elem,\"closest\")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return[\"live\",F,E.replace(/\\./g,\"`\").replace(/ /g,\"|\")].join(\".\")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler(\"ready\")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener(\"DOMContentLoaded\",function(){document.removeEventListener(\"DOMContentLoaded\",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent(\"onreadystatechange\",function(){if(document.readyState===\"complete\"){document.detachEvent(\"onreadystatechange\",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll(\"left\")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,\"load\",o.ready)}o.each((\"blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error\").split(\",\"),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind(\"unload\",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement(\"script\"),K=document.createElement(\"div\"),J=\"script\"+(new Date).getTime();K.style.display=\"none\";K.innerHTML='   <link/><table></table><a href=\"/a\" style=\"color:red;float:left;opacity:.5;\">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName(\"*\"),E=K.getElementsByTagName(\"a\")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName(\"tbody\").length,objectAll:!!K.getElementsByTagName(\"object\")[0].getElementsByTagName(\"*\").length,htmlSerialize:!!K.getElementsByTagName(\"link\").length,style:/red/.test(E.getAttribute(\"style\")),hrefNormalized:E.getAttribute(\"href\")===\"/a\",opacity:E.style.opacity===\"0.5\",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type=\"text/javascript\";try{G.appendChild(document.createTextNode(\"window.\"+J+\"=1;\"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent(\"onclick\",function(){o.support.noCloneEvent=false;K.detachEvent(\"onclick\",arguments.callee)});K.cloneNode(true).fireEvent(\"onclick\")}o(function(){var L=document.createElement(\"div\");L.style.width=L.style.paddingLeft=\"1px\";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display=\"none\"})})();var w=o.support.cssFloat?\"cssFloat\":\"styleFloat\";o.props={\"for\":\"htmlFor\",\"class\":\"className\",\"float\":w,cssFloat:w,styleFloat:w,readonly:\"readOnly\",maxlength:\"maxLength\",cellspacing:\"cellSpacing\",rowspan:\"rowSpan\",tabindex:\"tabIndex\"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!==\"string\"){return this._load(G)}var I=G.indexOf(\" \");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H=\"GET\";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J===\"object\"){J=o.param(J);H=\"POST\"}}}var F=this;o.ajax({url:G,type:H,dataType:\"html\",data:J,complete:function(M,L){if(L==\"success\"||L==\"notmodified\"){F.html(E?o(\"<div/>\").append(M.responseText.replace(/<script(.|\\s)*?\\/script>/g,\"\")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each(\"ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend\".split(\",\"),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:\"GET\",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,\"script\")},getJSON:function(E,F,G){return o.get(E,F,G,\"json\")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:\"POST\",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:\"GET\",contentType:\"application/x-www-form-urlencoded\",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject(\"Microsoft.XMLHTTP\"):new XMLHttpRequest()},accepts:{xml:\"application/xml, text/xml\",html:\"text/html\",script:\"text/javascript, application/javascript\",json:\"application/json, text/javascript\",text:\"text/plain\",_default:\"*/*\"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!==\"string\"){M.data=o.param(M.data)}if(M.dataType==\"jsonp\"){if(G==\"GET\"){if(!M.url.match(F)){M.url+=(M.url.match(/\\?/)?\"&\":\"?\")+(M.jsonp||\"callback\")+\"=?\"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+\"&\":\"\")+(M.jsonp||\"callback\")+\"=?\"}}M.dataType=\"json\"}if(M.dataType==\"json\"&&(M.data&&M.data.match(F)||M.url.match(F))){W=\"jsonp\"+r++;if(M.data){M.data=(M.data+\"\").replace(F,\"=\"+W+\"$1\")}M.url=M.url.replace(F,\"=\"+W+\"$1\");M.dataType=\"script\";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType==\"script\"&&M.cache==null){M.cache=false}if(M.cache===false&&G==\"GET\"){var E=e();var U=M.url.replace(/(\\?|&)_=.*?(&|$)/,\"$1_=\"+E+\"$2\");M.url=U+((U==M.url)?(M.url.match(/\\?/)?\"&\":\"?\")+\"_=\"+E:\"\")}if(M.data&&G==\"GET\"){M.url+=(M.url.match(/\\?/)?\"&\":\"?\")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger(\"ajaxStart\")}var Q=/^(\\w+:)?\\/\\/([^\\/?#]+)/.exec(M.url);if(M.dataType==\"script\"&&G==\"GET\"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName(\"head\")[0];var T=document.createElement(\"script\");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState==\"loaded\"||this.readyState==\"complete\")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader(\"Content-Type\",M.contentType)}if(M.ifModified){J.setRequestHeader(\"If-Modified-Since\",o.lastModified[M.url]||\"Thu, 01 Jan 1970 00:00:00 GMT\")}J.setRequestHeader(\"X-Requested-With\",\"XMLHttpRequest\");J.setRequestHeader(\"Accept\",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+\", */*\":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger(\"ajaxStop\")}J.abort();return false}if(M.global){o.event.trigger(\"ajaxSend\",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger(\"ajaxStop\")}}}else{if(!K&&J&&(J.readyState==4||X==\"timeout\")){K=true;if(P){clearInterval(P);P=null}R=X==\"timeout\"?\"timeout\":!o.httpSuccess(J)?\"error\":M.ifModified&&o.httpNotModified(J,M.url)?\"notmodified\":\"success\";if(R==\"success\"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R=\"parsererror\"}}if(R==\"success\"){var Y;try{Y=J.getResponseHeader(\"Last-Modified\")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N(\"timeout\")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger(\"ajaxSuccess\",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger(\"ajaxComplete\",[J,M])}if(M.global&&!--o.active){o.event.trigger(\"ajaxStop\")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger(\"ajaxError\",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol==\"file:\"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader(\"Last-Modified\");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader(\"content-type\"),E=H==\"xml\"||!H&&F&&F.indexOf(\"xml\")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName==\"parsererror\"){throw\"parsererror\"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I===\"string\"){if(H==\"script\"){o.globalEval(I)}if(H==\"json\"){I=l[\"eval\"](\"(\"+I+\")\")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+\"=\"+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join(\"&\").replace(/%20/g,\"+\")}});var m={},n,d=[[\"height\",\"marginTop\",\"marginBottom\",\"paddingTop\",\"paddingBottom\"],[\"width\",\"marginLeft\",\"marginRight\",\"paddingLeft\",\"paddingRight\"],[\"opacity\"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t(\"show\",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],\"olddisplay\");this[H].style.display=E||\"\";if(o.css(this[H],\"display\")===\"none\"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o(\"<\"+G+\" />\").appendTo(\"body\");K=I.css(\"display\");if(K===\"none\"){K=\"block\"}I.remove();m[G]=K}o.data(this[H],\"olddisplay\",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],\"olddisplay\")||\"\"}return this}},hide:function(H,I){if(H){return this.animate(t(\"hide\",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],\"olddisplay\");if(!E&&E!==\"none\"){o.data(this[G],\"olddisplay\",o.css(this[G],\"display\"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display=\"none\"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G===\"boolean\";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(\":hidden\");o(this)[H?\"show\":\"hide\"]()}):this.animate(t(\"toggle\",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?\"each\":\"queue\"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(\":hidden\"),J=this;for(M in I){if(I[M]==\"hide\"&&L||I[M]==\"show\"&&!L){return K.complete.call(this)}if((M==\"height\"||M==\"width\")&&this.style){K.display=o.css(this,\"display\");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow=\"hidden\"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S==\"toggle\"?L?\"show\":\"hide\":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||\"px\";if(P!=\"px\"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]==\"-=\"?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,\"\")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t(\"show\",1),slideUp:t(\"hide\",1),slideToggle:t(\"toggle\",1),fadeIn:{opacity:\"show\"},fadeOut:{opacity:\"hide\"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G===\"object\"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration===\"number\"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop==\"height\"||this.prop==\"width\")&&this.elem.style){this.elem.style.display=\"block\"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||\"px\";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop==\"width\"||this.prop==\"height\"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,\"display\")==\"none\"){this.elem.style.display=\"block\"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?\"swing\":\"linear\")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,\"opacity\",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!==\"visible\"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position===\"relative\"||E.position===\"static\"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position===\"fixed\"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement(\"div\"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style=\"position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;\"><div></div></div><table style=\"position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;\" cellpadding=\"0\" cellspacing=\"0\"><tr><td></td></tr></table>';M={position:\"absolute\",top:0,left:0,margin:0,border:0,width:\"1px\",height:\"1px\",visibility:\"hidden\"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow=\"hidden\",H.style.position=\"relative\";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop=\"1px\";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,\"marginTop\",true),10)||0,F+=parseInt(o.curCSS(E,\"marginLeft\",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,\"marginTop\");J.left-=j(this,\"marginLeft\");E.top+=j(G,\"borderTopWidth\");E.left+=j(G,\"borderLeftWidth\");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,\"position\")==\"static\")){E=E.offsetParent}return o(E)}});o.each([\"Left\",\"Top\"],function(F,E){var G=\"scroll\"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?\"pageYOffset\":\"pageXOffset\"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each([\"Height\",\"Width\"],function(I,G){var E=I?\"Left\":\"Top\",H=I?\"Right\":\"Bottom\",F=G.toLowerCase();o.fn[\"inner\"+G]=function(){return this[0]?o.css(this[0],F,false,\"padding\"):null};o.fn[\"outer\"+G]=function(K){return this[0]?o.css(this[0],F,false,K?\"margin\":\"border\"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode==\"CSS1Compat\"&&document.documentElement[\"client\"+G]||document.body[\"client\"+G]:this[0]==document?Math.max(document.documentElement[\"client\"+G],document.body[\"scroll\"+G],document.documentElement[\"scroll\"+G],document.body[\"offset\"+G],document.documentElement[\"offset\"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K===\"string\"?K:K+\"px\")}})})();"
  },
  {
    "path": "js/prettify/lang-css.js",
    "content": "PR.registerLangHandler(PR.createSimpleLexer([[\"pln\",/^[ \\t\\r\\n\\f]+/,null,\" \\t\\r\\n\\u000c\"]],[[\"str\",/^\\\"(?:[^\\n\\r\\f\\\\\\\"]|\\\\(?:\\r\\n?|\\n|\\f)|\\\\[\\s\\S])*\\\"/,null],[\"str\",/^\\'(?:[^\\n\\r\\f\\\\\\']|\\\\(?:\\r\\n?|\\n|\\f)|\\\\[\\s\\S])*\\'/,null],[\"lang-css-str\",/^url\\(([^\\)\\\"\\']*)\\)/i],[\"kwd\",/^(?:url|rgb|\\!important|@import|@page|@media|@charset|inherit)(?=[^\\-\\w]|$)/i,null],[\"lang-css-kw\",/^(-?(?:[_a-z]|(?:\\\\[0-9a-f]+ ?))(?:[_a-z0-9\\-]|\\\\(?:\\\\[0-9a-f]+ ?))*)\\s*:/i],[\"com\",/^\\/\\*[^*]*\\*+(?:[^\\/*][^*]*\\*+)*\\//],[\"com\",\n/^(?:<!--|--\\>)/],[\"lit\",/^(?:\\d+|\\d*\\.\\d+)(?:%|[a-z]+)?/i],[\"lit\",/^#(?:[0-9a-f]{3}){1,2}/i],[\"pln\",/^-?(?:[_a-z]|(?:\\\\[\\da-f]+ ?))(?:[_a-z\\d\\-]|\\\\(?:\\\\[\\da-f]+ ?))*/i],[\"pun\",/^[^\\s\\w\\'\\\"]+/]]),[\"css\"]);PR.registerLangHandler(PR.createSimpleLexer([],[[\"kwd\",/^-?(?:[_a-z]|(?:\\\\[\\da-f]+ ?))(?:[_a-z\\d\\-]|\\\\(?:\\\\[\\da-f]+ ?))*/i]]),[\"css-kw\"]);PR.registerLangHandler(PR.createSimpleLexer([],[[\"str\",/^[^\\)\\\"\\']+/]]),[\"css-str\"]);\n"
  },
  {
    "path": "js/prettify/lang-hs.js",
    "content": "PR.registerLangHandler(PR.createSimpleLexer([[\"pln\",/^[\\t\\n\\x0B\\x0C\\r ]+/,null,\"\\t\\n\\u000b\\u000c\\r \"],[\"str\",/^\\\"(?:[^\\\"\\\\\\n\\x0C\\r]|\\\\[\\s\\S])*(?:\\\"|$)/,null,'\"'],[\"str\",/^\\'(?:[^\\'\\\\\\n\\x0C\\r]|\\\\[^&])\\'?/,null,\"'\"],[\"lit\",/^(?:0o[0-7]+|0x[\\da-f]+|\\d+(?:\\.\\d+)?(?:e[+\\-]?\\d+)?)/i,null,\"0123456789\"]],[[\"com\",/^(?:(?:--+(?:[^\\r\\n\\x0C]*)?)|(?:\\{-(?:[^-]|-+[^-\\}])*-\\}))/],[\"kwd\",/^(?:case|class|data|default|deriving|do|else|if|import|in|infix|infixl|infixr|instance|let|module|newtype|of|then|type|where|_)(?=[^a-zA-Z0-9\\']|$)/,\nnull],[\"pln\",/^(?:[A-Z][\\w\\']*\\.)*[a-zA-Z][\\w\\']*/],[\"pun\",/^[^\\t\\n\\x0B\\x0C\\r a-zA-Z0-9\\'\\\"]+/]]),[\"hs\"]);\n"
  },
  {
    "path": "js/prettify/lang-lisp.js",
    "content": "(function(){var a=null;\nPR.registerLangHandler(PR.createSimpleLexer([[\"opn\",/^\\(/,a,\"(\"],[\"clo\",/^\\)/,a,\")\"],[\"com\",/^;[^\\r\\n]*/,a,\";\"],[\"pln\",/^[\\t\\n\\r \\xA0]+/,a,\"\\t\\n\\r \\u00a0\"],[\"str\",/^\\\"(?:[^\\\"\\\\]|\\\\[\\s\\S])*(?:\\\"|$)/,a,'\"']],[[\"kwd\",/^(?:block|c[ad]+r|catch|cons|defun|do|eq|eql|equal|equalp|eval-when|flet|format|go|if|labels|lambda|let|load-time-value|locally|macrolet|multiple-value-call|nil|progn|progv|quote|require|return-from|setq|symbol-macrolet|t|tagbody|the|throw|unwind)\\b/,a],[\"lit\",/^[+\\-]?(?:0x[0-9a-f]+|\\d+\\/\\d+|(?:\\.\\d+|\\d+(?:\\.\\d*)?)(?:[ed][+\\-]?\\d+)?)/i],[\"lit\",\n/^\\'(?:-*(?:\\w|\\\\[\\x21-\\x7e])(?:[\\w-]*|\\\\[\\x21-\\x7e])[=!?]?)?/],[\"pln\",/^-*(?:[a-z_]|\\\\[\\x21-\\x7e])(?:[\\w-]*|\\\\[\\x21-\\x7e])[=!?]?/i],[\"pun\",/^[^\\w\\t\\n\\r \\xA0()\\\"\\\\\\';]+/]]),[\"cl\",\"el\",\"lisp\",\"scm\"])})()"
  },
  {
    "path": "js/prettify/lang-lua.js",
    "content": "PR.registerLangHandler(PR.createSimpleLexer([[\"pln\",/^[\\t\\n\\r \\xA0]+/,null,\"\\t\\n\\r \\u00a0\"],[\"str\",/^(?:\\\"(?:[^\\\"\\\\]|\\\\[\\s\\S])*(?:\\\"|$)|\\'(?:[^\\'\\\\]|\\\\[\\s\\S])*(?:\\'|$))/,null,\"\\\"'\"]],[[\"com\",/^--(?:\\[(=*)\\[[\\s\\S]*?(?:\\]\\1\\]|$)|[^\\r\\n]*)/],[\"str\",/^\\[(=*)\\[[\\s\\S]*?(?:\\]\\1\\]|$)/],[\"kwd\",/^(?:and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\\b/,null],[\"lit\",/^[+-]?(?:0x[\\da-f]+|(?:(?:\\.\\d+|\\d+(?:\\.\\d*)?)(?:e[+\\-]?\\d+)?))/i],[\"pln\",/^[a-z_]\\w*/i],\n[\"pun\",/^[^\\w\\t\\n\\r \\xA0][^\\w\\t\\n\\r \\xA0\\\"\\-\\+=]*/]]),[\"lua\"]);\n"
  },
  {
    "path": "js/prettify/lang-ml.js",
    "content": "PR.registerLangHandler(PR.createSimpleLexer([[\"pln\",/^[\\t\\n\\r \\xA0]+/,null,\"\\t\\n\\r \\u00a0\"],[\"com\",/^#(?:if[\\t\\n\\r \\xA0]+(?:[a-z_$][\\w\\']*|``[^\\r\\n\\t`]*(?:``|$))|else|endif|light)/i,null,\"#\"],[\"str\",/^(?:\\\"(?:[^\\\"\\\\]|\\\\[\\s\\S])*(?:\\\"|$)|\\'(?:[^\\'\\\\]|\\\\[\\s\\S])*(?:\\'|$))/,null,\"\\\"'\"]],[[\"com\",/^(?:\\/\\/[^\\r\\n]*|\\(\\*[\\s\\S]*?\\*\\))/],[\"kwd\",/^(?:abstract|and|as|assert|begin|class|default|delegate|do|done|downcast|downto|elif|else|end|exception|extern|false|finally|for|fun|function|if|in|inherit|inline|interface|internal|lazy|let|match|member|module|mutable|namespace|new|null|of|open|or|override|private|public|rec|return|static|struct|then|to|true|try|type|upcast|use|val|void|when|while|with|yield|asr|land|lor|lsl|lsr|lxor|mod|sig|atomic|break|checked|component|const|constraint|constructor|continue|eager|event|external|fixed|functor|global|include|method|mixin|object|parallel|process|protected|pure|sealed|trait|virtual|volatile)\\b/],\n[\"lit\",/^[+\\-]?(?:0x[\\da-f]+|(?:(?:\\.\\d+|\\d+(?:\\.\\d*)?)(?:e[+\\-]?\\d+)?))/i],[\"pln\",/^(?:[a-z_]\\w*[!?#]?|``[^\\r\\n\\t`]*(?:``|$))/i],[\"pun\",/^[^\\t\\n\\r \\xA0\\\"\\'\\w]+/]]),[\"fs\",\"ml\"]);\n"
  },
  {
    "path": "js/prettify/lang-proto.js",
    "content": "PR.registerLangHandler(PR.sourceDecorator({keywords:\"bool bytes default double enum extend extensions false fixed32 fixed64 float group import int32 int64 max message option optional package repeated required returns rpc service sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 uint64\",cStyleComments:true}),[\"proto\"]);\n"
  },
  {
    "path": "js/prettify/lang-sql.js",
    "content": "PR.registerLangHandler(PR.createSimpleLexer([[\"pln\",/^[\\t\\n\\r \\xA0]+/,null,\"\\t\\n\\r \\u00a0\"],[\"str\",/^(?:\"(?:[^\\\"\\\\]|\\\\.)*\"|'(?:[^\\'\\\\]|\\\\.)*')/,null,\"\\\"'\"]],[[\"com\",/^(?:--[^\\r\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$))/],[\"kwd\",/^(?:ADD|ALL|ALTER|AND|ANY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PERCENT|PLAN|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNION|UNIQUE|UPDATE|UPDATETEXT|USE|USER|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WRITETEXT)(?=[^\\w-]|$)/i,\nnull],[\"lit\",/^[+-]?(?:0x[\\da-f]+|(?:(?:\\.\\d+|\\d+(?:\\.\\d*)?)(?:e[+\\-]?\\d+)?))/i],[\"pln\",/^[a-z_][\\w-]*/i],[\"pun\",/^[^\\w\\t\\n\\r \\xA0]+/]]),[\"sql\"]);\n"
  },
  {
    "path": "js/prettify/lang-vb.js",
    "content": "PR.registerLangHandler(PR.createSimpleLexer([[\"pln\",/^[\\t\\n\\r \\xA0\\u2028\\u2029]+/,null,\"\\t\\n\\r \\u00a0\\u2028\\u2029\"],[\"str\",/^(?:[\\\"\\u201C\\u201D](?:[^\\\"\\u201C\\u201D]|[\\\"\\u201C\\u201D]{2})(?:[\\\"\\u201C\\u201D]c|$)|[\\\"\\u201C\\u201D](?:[^\\\"\\u201C\\u201D]|[\\\"\\u201C\\u201D]{2})*(?:[\\\"\\u201C\\u201D]|$))/i,null,'\"\\u201c\\u201d'],[\"com\",/^[\\'\\u2018\\u2019][^\\r\\n\\u2028\\u2029]*/,null,\"'\\u2018\\u2019\"]],[[\"kwd\",/^(?:AddHandler|AddressOf|Alias|And|AndAlso|Ansi|As|Assembly|Auto|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|CDbl|CDec|Char|CInt|Class|CLng|CObj|Const|CShort|CSng|CStr|CType|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else|ElseIf|End|EndIf|Enum|Erase|Error|Event|Exit|Finally|For|Friend|Function|Get|GetType|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|Let|Lib|Like|Long|Loop|Me|Mod|Module|MustInherit|MustOverride|MyBase|MyClass|Namespace|New|Next|Not|NotInheritable|NotOverridable|Object|On|Option|Optional|Or|OrElse|Overloads|Overridable|Overrides|ParamArray|Preserve|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|Return|Select|Set|Shadows|Shared|Short|Single|Static|Step|Stop|String|Structure|Sub|SyncLock|Then|Throw|To|Try|TypeOf|Unicode|Until|Variant|Wend|When|While|With|WithEvents|WriteOnly|Xor|EndIf|GoSub|Let|Variant|Wend)\\b/i,\nnull],[\"com\",/^REM[^\\r\\n\\u2028\\u2029]*/i],[\"lit\",/^(?:True\\b|False\\b|Nothing\\b|\\d+(?:E[+\\-]?\\d+[FRD]?|[FRDSIL])?|(?:&H[0-9A-F]+|&O[0-7]+)[SIL]?|\\d*\\.\\d+(?:E[+\\-]?\\d+)?[FRD]?|#\\s+(?:\\d+[\\-\\/]\\d+[\\-\\/]\\d+(?:\\s+\\d+:\\d+(?::\\d+)?(\\s*(?:AM|PM))?)?|\\d+:\\d+(?::\\d+)?(\\s*(?:AM|PM))?)\\s+#)/i],[\"pln\",/^(?:(?:[a-z]|_\\w)\\w*|\\[(?:[a-z]|_\\w)\\w*\\])/i],[\"pun\",/^[^\\w\\t\\n\\r \\\"\\'\\[\\]\\xA0\\u2018\\u2019\\u201C\\u201D\\u2028\\u2029]+/],[\"pun\",/^(?:\\[|\\])/]]),[\"vb\",\"vbs\"]);\n"
  },
  {
    "path": "js/prettify/lang-wiki.js",
    "content": "PR.registerLangHandler(PR.createSimpleLexer([[\"pln\",/^[\\t \\xA0a-gi-z0-9]+/,null,\"\\t \\u00a0abcdefgijklmnopqrstuvwxyz0123456789\"],[\"pun\",/^[=*~\\^\\[\\]]+/,null,\"=*~^[]\"]],[[\"lang-wiki.meta\",/(?:^^|\\r\\n?|\\n)(#[a-z]+)\\b/],[\"lit\",/^(?:[A-Z][a-z][a-z0-9]+[A-Z][a-z][a-zA-Z0-9]+)\\b/],[\"lang-\",/^\\{\\{\\{([\\s\\S]+?)\\}\\}\\}/],[\"lang-\",/^`([^\\r\\n`]+)`/],[\"str\",/^https?:\\/\\/[^\\/?#\\s]*(?:\\/[^?#\\s]*)?(?:\\?[^#\\s]*)?(?:#\\S*)?/i],[\"pln\",/^(?:\\r\\n|[\\s\\S])[^#=*~^A-Zh\\{`\\[\\r\\n]*/]]),[\"wiki\"]);\nPR.registerLangHandler(PR.createSimpleLexer([[\"kwd\",/^#[a-z]+/i,null,\"#\"]],[]),[\"wiki.meta\"]);\n"
  },
  {
    "path": "js/prettify/prettify.js",
    "content": "(function(){\nvar o=true,r=null,z=false;window.PR_SHOULD_USE_CONTINUATION=o;window.PR_TAB_WIDTH=8;window.PR_normalizedHtml=window.PR=window.prettyPrintOne=window.prettyPrint=void 0;window._pr_isIE6=function(){var N=navigator&&navigator.userAgent&&/\\bMSIE 6\\./.test(navigator.userAgent);window._pr_isIE6=function(){return N};return N};\nvar aa=\"!\",ba=\"!=\",ca=\"!==\",F=\"#\",da=\"%\",ea=\"%=\",G=\"&\",fa=\"&&\",ja=\"&&=\",ka=\"&=\",H=\"(\",la=\"*\",ma=\"*=\",na=\"+=\",oa=\",\",pa=\"-=\",qa=\"->\",ra=\"/\",sa=\"/=\",ta=\":\",ua=\"::\",va=\";\",I=\"<\",wa=\"<<\",xa=\"<<=\",ya=\"<=\",za=\"=\",Aa=\"==\",Ba=\"===\",J=\">\",Ca=\">=\",Da=\">>\",Ea=\">>=\",Fa=\">>>\",Ga=\">>>=\",Ha=\"?\",Ia=\"@\",L=\"[\",M=\"^\",Ta=\"^=\",Ua=\"^^\",Va=\"^^=\",Wa=\"{\",O=\"|\",Xa=\"|=\",Ya=\"||\",Za=\"||=\",$a=\"~\",ab=\"break\",bb=\"case\",cb=\"continue\",db=\"delete\",eb=\"do\",fb=\"else\",gb=\"finally\",hb=\"instanceof\",ib=\"return\",jb=\"throw\",kb=\"try\",lb=\"typeof\",\nmb=\"(?:^^|[+-]\",nb=\"\\\\$1\",ob=\")\\\\s*\",pb=\"&amp;\",qb=\"&lt;\",rb=\"&gt;\",sb=\"&quot;\",tb=\"&#\",ub=\"x\",vb=\"'\",wb='\"',xb=\" \",yb=\"XMP\",zb=\"</\",Ab='=\"',P=\"\",Q=\"\\\\\",Bb=\"b\",Cb=\"t\",Db=\"n\",Eb=\"v\",Fb=\"f\",Gb=\"r\",Hb=\"u\",Ib=\"0\",Jb=\"1\",Kb=\"2\",Lb=\"3\",Mb=\"4\",Nb=\"5\",Ob=\"6\",Pb=\"7\",Qb=\"\\\\x0\",Rb=\"\\\\x\",Sb=\"-\",Tb=\"]\",Ub=\"\\\\\\\\u[0-9A-Fa-f]{4}|\\\\\\\\x[0-9A-Fa-f]{2}|\\\\\\\\[0-3][0-7]{0,2}|\\\\\\\\[0-7]{1,2}|\\\\\\\\[\\\\s\\\\S]|-|[^-\\\\\\\\]\",R=\"g\",Vb=\"\\\\B\",Wb=\"\\\\b\",Xb=\"\\\\D\",Yb=\"\\\\d\",Zb=\"\\\\S\",$b=\"\\\\s\",ac=\"\\\\W\",bc=\"\\\\w\",cc=\"(?:\\\\[(?:[^\\\\x5C\\\\x5D]|\\\\\\\\[\\\\s\\\\S])*\\\\]|\\\\\\\\u[A-Fa-f0-9]{4}|\\\\\\\\x[A-Fa-f0-9]{2}|\\\\\\\\[0-9]+|\\\\\\\\[^ux0-9]|\\\\(\\\\?[:!=]|[\\\\(\\\\)\\\\^]|[^\\\\x5B\\\\x5C\\\\(\\\\)\\\\^]+)\",\ndc=\"(?:\",ec=\")\",fc=\"gi\",gc=\"PRE\",hc='<!DOCTYPE foo PUBLIC \"foo bar\">\\n<foo />',ic=\"\\t\",jc=\"\\n\",kc=\"[^<]+|<!--[\\\\s\\\\S]*?--\\>|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>|</?[a-zA-Z][^>]*>|<\",lc=\"nocode\",mc=' $1=\"$2$3$4\"',S=\"pln\",nc=\"string\",T=\"lang-\",oc=\"src\",U=\"str\",pc=\"'\\\"\",qc=\"'\\\"`\",rc=\"\\\"'\",V=\"com\",sc=\"lang-regex\",tc=\"(/(?=[^/*])(?:[^/\\\\x5B\\\\x5C]|\\\\x5C[\\\\s\\\\S]|\\\\x5B(?:[^\\\\x5C\\\\x5D]|\\\\x5C[\\\\s\\\\S])*(?:\\\\x5D|$))+/)\",uc=\"kwd\",vc=\"^(?:\",wc=\")\\\\b\",xc=\" \\r\\n\\t\\u00a0\",yc=\"lit\",zc=\"typ\",Ac=\"0123456789\",Y=\"pun\",Bc=\"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try alignof align_union asm axiom bool concept concept_map const_cast constexpr decltype dynamic_cast explicit export friend inline late_check mutable namespace nullptr reinterpret_cast static_assert static_cast template typeid typename typeof using virtual wchar_t where break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try boolean byte extends final finally implements import instanceof null native package strictfp super synchronized throws transient as base by checked decimal delegate descending event fixed foreach from group implicit in interface internal into is lock object out override orderby params partial readonly ref sbyte sealed stackalloc string select uint ulong unchecked unsafe ushort var break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try debugger eval export function get null set undefined var with Infinity NaN caller delete die do dump elsif eval exit foreach for goto if import last local my next no our print package redo require sub undef unless until use wantarray while BEGIN END break continue do else for if return while and as assert class def del elif except exec finally from global import in is lambda nonlocal not or pass print raise try with yield False True None break continue do else for if return while alias and begin case class def defined elsif end ensure false in module next nil not or redo rescue retry self super then true undef unless until when yield BEGIN END break continue do else for if return while case done elif esac eval fi function in local set then until \",\nCc=\"</span>\",Dc='<span class=\"',Ec='\">',Fc=\"$1&nbsp;\",Gc=\"&nbsp;<br />\",Hc=\"<br />\",Ic=\"console\",Jc=\"cannot override language handler %s\",Kc=\"default-markup\",Lc=\"default-code\",Mc=\"dec\",Z=\"lang-js\",$=\"lang-css\",Nc=\"lang-in.tag\",Oc=\"htm\",Pc=\"html\",Qc=\"mxml\",Rc=\"xhtml\",Sc=\"xml\",Tc=\"xsl\",Uc=\" \\t\\r\\n\",Vc=\"atv\",Wc=\"tag\",Xc=\"atn\",Yc=\"lang-uq.val\",Zc=\"in.tag\",$c=\"uq.val\",ad=\"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try alignof align_union asm axiom bool concept concept_map const_cast constexpr decltype dynamic_cast explicit export friend inline late_check mutable namespace nullptr reinterpret_cast static_assert static_cast template typeid typename typeof using virtual wchar_t where \",\nbd=\"c\",cd=\"cc\",dd=\"cpp\",ed=\"cxx\",fd=\"cyc\",gd=\"m\",hd=\"null true false\",id=\"json\",jd=\"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try boolean byte extends final finally implements import instanceof null native package strictfp super synchronized throws transient as base by checked decimal delegate descending event fixed foreach from group implicit in interface internal into is lock object out override orderby params partial readonly ref sbyte sealed stackalloc string select uint ulong unchecked unsafe ushort var \",\nkd=\"cs\",ld=\"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try boolean byte extends final finally implements import instanceof null native package strictfp super synchronized throws transient \",md=\"java\",nd=\"break continue do else for if return while case done elif esac eval fi function in local set then until \",\nod=\"bsh\",pd=\"csh\",qd=\"sh\",rd=\"break continue do else for if return while and as assert class def del elif except exec finally from global import in is lambda nonlocal not or pass print raise try with yield False True None \",sd=\"cv\",td=\"py\",ud=\"caller delete die do dump elsif eval exit foreach for goto if import last local my next no our print package redo require sub undef unless until use wantarray while BEGIN END \",vd=\"perl\",wd=\"pl\",xd=\"pm\",yd=\"break continue do else for if return while alias and begin case class def defined elsif end ensure false in module next nil not or redo rescue retry self super then true undef unless until when yield BEGIN END \",\nzd=\"rb\",Ad=\"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try debugger eval export function get null set undefined var with Infinity NaN \",Bd=\"js\",Cd=\"regex\",Dd=\"pre\",Ed=\"code\",Fd=\"xmp\",Gd=\"prettyprint\",Hd=\"class\",Id=\"br\",Jd=\"\\r\";\n(function(){var N=function(){for(var a=[aa,ba,ca,F,da,ea,G,fa,ja,ka,H,la,ma,na,oa,pa,qa,ra,sa,ta,ua,va,I,wa,xa,ya,za,Aa,Ba,J,Ca,Da,Ea,Fa,Ga,Ha,Ia,L,M,Ta,Ua,Va,Wa,O,Xa,Ya,Za,$a,ab,bb,cb,db,eb,fb,gb,hb,ib,jb,kb,lb],b=mb,c=0;c<a.length;++c)b+=O+a[c].replace(/([^=<>:&a-z])/g,nb);b+=ob;return b}(),Ja=/&/g,Ka=/</g,La=/>/g,Kd=/\\\"/g;function Ld(a){return a.replace(Ja,pb).replace(Ka,qb).replace(La,rb).replace(Kd,sb)}function ga(a){return a.replace(Ja,pb).replace(Ka,qb).replace(La,rb)}var Md=/&lt;/g,Nd=/&gt;/g,\nOd=/&apos;/g,Pd=/&quot;/g,Qd=/&amp;/g,Rd=/&nbsp;/g;function Sd(a){var b=a.indexOf(G);if(b<0)return a;for(--b;(b=a.indexOf(tb,b+1))>=0;){var c=a.indexOf(va,b);if(c>=0){var d=a.substring(b+3,c),g=10;if(d&&d.charAt(0)===ub){d=d.substring(1);g=16}var i=parseInt(d,g);isNaN(i)||(a=a.substring(0,b)+String.fromCharCode(i)+a.substring(c+1))}}return a.replace(Md,I).replace(Nd,J).replace(Od,vb).replace(Pd,wb).replace(Qd,G).replace(Rd,xb)}function Ma(a){return yb===a.tagName}function W(a,b){switch(a.nodeType){case 1:var c=\na.tagName.toLowerCase();b.push(I,c);for(var d=0;d<a.attributes.length;++d){var g=a.attributes[d];if(g.specified){b.push(xb);W(g,b)}}b.push(J);for(var i=a.firstChild;i;i=i.nextSibling)W(i,b);if(a.firstChild||!/^(?:br|link|img)$/.test(c))b.push(zb,c,J);break;case 2:b.push(a.name.toLowerCase(),Ab,Ld(a.value),wb);break;case 3:case 4:b.push(ga(a.nodeValue));break}}function Na(a){for(var b=0,c=z,d=z,g=0,i=a.length;g<i;++g){var m=a[g];if(m.ignoreCase)d=o;else if(/[a-z]/i.test(m.source.replace(/\\\\u[0-9a-f]{4}|\\\\x[0-9a-f]{2}|\\\\[^ux]/gi,\nP))){c=o;d=z;break}}function l(j){if(j.charAt(0)!==Q)return j.charCodeAt(0);switch(j.charAt(1)){case Bb:return 8;case Cb:return 9;case Db:return 10;case Eb:return 11;case Fb:return 12;case Gb:return 13;case Hb:case ub:return parseInt(j.substring(2),16)||j.charCodeAt(1);case Ib:case Jb:case Kb:case Lb:case Mb:case Nb:case Ob:case Pb:return parseInt(j.substring(1),8);default:return j.charCodeAt(1)}}function n(j){if(j<32)return(j<16?Qb:Rb)+j.toString(16);var f=String.fromCharCode(j);if(f===Q||f===Sb||\nf===L||f===Tb)f=Q+f;return f}function q(j){for(var f=j.substring(1,j.length-1).match(new RegExp(Ub,R)),s=[],k=[],h=f[0]===M,e=h?1:0,p=f.length;e<p;++e){var t=f[e];switch(t){case Vb:case Wb:case Xb:case Yb:case Zb:case $b:case ac:case bc:s.push(t);continue}var u=l(t),x;if(e+2<p&&Sb===f[e+1]){x=l(f[e+2]);e+=2}else x=u;k.push([u,x]);if(!(x<65||u>122)){x<65||u>90||k.push([Math.max(65,u)|32,Math.min(x,90)|32]);x<97||u>122||k.push([Math.max(97,u)&-33,Math.min(x,122)&-33])}}k.sort(function(Oa,Pa){return Oa[0]-\nPa[0]||Pa[1]-Oa[1]});var B=[],E=[NaN,NaN];for(e=0;e<k.length;++e){var A=k[e];if(A[0]<=E[1]+1)E[1]=Math.max(E[1],A[1]);else B.push(E=A)}var D=[L];h&&D.push(M);D.push.apply(D,s);for(e=0;e<B.length;++e){A=B[e];D.push(n(A[0]));if(A[1]>A[0]){A[1]+1>A[0]&&D.push(Sb);D.push(n(A[1]))}}D.push(Tb);return D.join(P)}function v(j){var f=j.source.match(new RegExp(cc,R)),s=f.length,k=[],h,e=0;for(h=0;e<s;++e){var p=f[e];if(p===H)++h;else if(Q===p.charAt(0)){var t=+p.substring(1);if(t&&t<=h)k[t]=-1}}for(e=1;e<k.length;++e)if(-1===\nk[e])k[e]=++b;for(h=e=0;e<s;++e){p=f[e];if(p===H){++h;if(k[h]===undefined)f[e]=dc}else if(Q===p.charAt(0))if((t=+p.substring(1))&&t<=h)f[e]=Q+k[h]}for(h=e=0;e<s;++e)if(M===f[e]&&M!==f[e+1])f[e]=P;if(j.ignoreCase&&c)for(e=0;e<s;++e){p=f[e];var u=p.charAt(0);if(p.length>=2&&u===L)f[e]=q(p);else if(u!==Q)f[e]=p.replace(/[a-zA-Z]/g,function(x){var B=x.charCodeAt(0);return L+String.fromCharCode(B&-33,B|32)+Tb})}return f.join(P)}var w=[];g=0;for(i=a.length;g<i;++g){m=a[g];if(m.global||m.multiline)throw new Error(P+\nm);w.push(dc+v(m)+ec)}return new RegExp(w.join(O),d?fc:R)}var ha=r;function Td(a){if(r===ha){var b=document.createElement(gc);b.appendChild(document.createTextNode(hc));ha=!/</.test(b.innerHTML)}if(ha){var c=a.innerHTML;if(Ma(a))c=ga(c);return c}for(var d=[],g=a.firstChild;g;g=g.nextSibling)W(g,d);return d.join(P)}function Ud(a){var b=0;return function(c){for(var d=r,g=0,i=0,m=c.length;i<m;++i){var l=c.charAt(i);switch(l){case ic:d||(d=[]);d.push(c.substring(g,i));var n=a-b%a;for(b+=n;n>=0;n-=\"                \".length)d.push(\"                \".substring(0,\nn));g=i+1;break;case jc:b=0;break;default:++b}}if(!d)return c;d.push(c.substring(g));return d.join(P)}}var Vd=new RegExp(kc,R),Wd=/^<\\!--/,Xd=/^<\\[CDATA\\[/,Yd=/^<br\\b/i,Qa=/^<(\\/?)([a-zA-Z]+)/;function Zd(a){var b=a.match(Vd),c=[],d=0,g=[];if(b)for(var i=0,m=b.length;i<m;++i){var l=b[i];if(l.length>1&&l.charAt(0)===I){if(!Wd.test(l))if(Xd.test(l)){c.push(l.substring(9,l.length-3));d+=l.length-12}else if(Yd.test(l)){c.push(jc);++d}else if(l.indexOf(lc)>=0&&$d(l)){var n=l.match(Qa)[2],q=1,v;v=i+1;a:for(;v<\nm;++v){var w=b[v].match(Qa);if(w&&w[2]===n)if(w[1]===ra){if(--q===0)break a}else++q}if(v<m){g.push(d,b.slice(i,v+1).join(P));i=v}else g.push(d,l)}else g.push(d,l)}else{var j=Sd(l);c.push(j);d+=j.length}}return{source:c.join(P),tags:g}}function $d(a){return!!a.replace(/\\s(\\w+)\\s*=\\s*(?:\\\"([^\\\"]*)\\\"|'([^\\']*)'|(\\S+))/g,mc).match(/[cC][lL][aA][sS][sS]=\\\"[^\\\"]*\\bnocode\\b/)}function ia(a,b,c,d){if(b){var g={source:b,b:a};c(g);d.push.apply(d,g.c)}}function K(a,b){var c={},d;(function(){for(var m=a.concat(b),\nl=[],n={},q=0,v=m.length;q<v;++q){var w=m[q],j=w[3];if(j)for(var f=j.length;--f>=0;)c[j.charAt(f)]=w;var s=w[1],k=P+s;if(!n.hasOwnProperty(k)){l.push(s);n[k]=r}}l.push(/[\\0-\\uffff]/);d=Na(l)})();var g=b.length,i=function(m){for(var l=m.source,n=m.b,q=[n,S],v=0,w=l.match(d)||[],j={},f=0,s=w.length;f<s;++f){var k=w[f],h=j[k],e,p;if(typeof h===nc)p=z;else{var t=c[k.charAt(0)];if(t){e=k.match(t[1]);h=t[0]}else{for(var u=0;u<g;++u){t=b[u];if(e=k.match(t[1])){h=t[0];break}}e||(h=S)}if((p=h.length>=5&&T===\nh.substring(0,5))&&!(e&&e[1])){p=z;h=oc}p||(j[k]=h)}var x=v;v+=k.length;if(p){var B=e[1],E=k.indexOf(B),A=E+B.length,D=h.substring(5);ia(n+x,k.substring(0,E),i,q);ia(n+x+E,B,Ra(D,B),q);ia(n+x+A,k.substring(A),i,q)}else q.push(n+x,h)}m.c=q};return i}function C(a){var b=[],c=[];if(a.tripleQuotedStrings)b.push([U,/^(?:\\'\\'\\'(?:[^\\'\\\\]|\\\\[\\s\\S]|\\'{1,2}(?=[^\\']))*(?:\\'\\'\\'|$)|\\\"\\\"\\\"(?:[^\\\"\\\\]|\\\\[\\s\\S]|\\\"{1,2}(?=[^\\\"]))*(?:\\\"\\\"\\\"|$)|\\'(?:[^\\\\\\']|\\\\[\\s\\S])*(?:\\'|$)|\\\"(?:[^\\\\\\\"]|\\\\[\\s\\S])*(?:\\\"|$))/,r,pc]);\nelse a.multiLineStrings?b.push([U,/^(?:\\'(?:[^\\\\\\']|\\\\[\\s\\S])*(?:\\'|$)|\\\"(?:[^\\\\\\\"]|\\\\[\\s\\S])*(?:\\\"|$)|\\`(?:[^\\\\\\`]|\\\\[\\s\\S])*(?:\\`|$))/,r,qc]):b.push([U,/^(?:\\'(?:[^\\\\\\'\\r\\n]|\\\\.)*(?:\\'|$)|\\\"(?:[^\\\\\\\"\\r\\n]|\\\\.)*(?:\\\"|$))/,r,rc]);if(a.hashComments)a.cStyleComments?b.push([V,/^#(?:[^\\r\\n\\/]|\\/(?!\\*)|\\/\\*[^\\r\\n]*?\\*\\/)*/,r,F]):b.push([V,/^#[^\\r\\n]*/,r,F]);if(a.cStyleComments){c.push([V,/^\\/\\/[^\\r\\n]*/,r]);c.push([V,/^\\/\\*[\\s\\S]*?(?:\\*\\/|$)/,r])}a.regexLiterals&&c.push([sc,new RegExp(M+N+tc)]);var d=\na.keywords.replace(/^\\s+|\\s+$/g,P);d.length&&c.push([uc,new RegExp(vc+d.replace(/\\s+/g,O)+wc),r]);b.push([S,/^\\s+/,r,xc]);c.push([yc,/^@[a-z_$][a-z_$@0-9]*/i,r,Ia],[zc,/^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/,r],[S,/^[a-z_$][a-z_$@0-9]*/i,r],[yc,/^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*/i,r,Ac],[Y,/^.[^\\s\\w\\.$@\\'\\\"\\`\\/\\#]*/,r]);return K(b,c)}var ae=C({keywords:Bc,hashComments:o,cStyleComments:o,multiLineStrings:o,regexLiterals:o});function be(a){var b=a.source,c=a.f,d=a.c,\ng=[],i=0,m=r,l=r,n=0,q=0,v=Ud(window.PR_TAB_WIDTH),w=/([\\r\\n ]) /g,j=/(^| ) /gm,f=/\\r\\n?|\\n/g,s=/[ \\r\\n]$/,k=o;function h(p){if(p>i){if(m&&m!==l){g.push(Cc);m=r}if(!m&&l){m=l;g.push(Dc,m,Ec)}var t=ga(v(b.substring(i,p))).replace(k?j:w,Fc);k=s.test(t);var u=window._pr_isIE6()?Gc:Hc;g.push(t.replace(f,u));i=p}}for(;1;){var e;if(e=n<c.length?q<d.length?c[n]<=d[q]:o:z){h(c[n]);if(m){g.push(Cc);m=r}g.push(c[n+1]);n+=2}else if(q<d.length){h(d[q]);l=d[q+1];q+=2}else break}h(b.length);m&&g.push(Cc);a.a=g.join(P)}\nvar X={};function y(a,b){for(var c=b.length;--c>=0;){var d=b[c];if(X.hasOwnProperty(d))Ic in window&&console.i(Jc,d);else X[d]=a}}function Ra(a,b){a&&X.hasOwnProperty(a)||(a=/^\\s*</.test(b)?Kc:Lc);return X[a]}y(ae,[Lc]);y(K([],[[S,/^[^<?]+/],[Mc,/^<!\\w[^>]*(?:>|$)/],[V,/^<\\!--[\\s\\S]*?(?:-\\->|$)/],[T,/^<\\?([\\s\\S]+?)(?:\\?>|$)/],[T,/^<%([\\s\\S]+?)(?:%>|$)/],[Y,/^(?:<[%?]|[%?]>)/],[T,/^<xmp\\b[^>]*>([\\s\\S]+?)<\\/xmp\\b[^>]*>/i],[Z,/^<script\\b[^>]*>([\\s\\S]+?)<\\/script\\b[^>]*>/i],[$,/^<style\\b[^>]*>([\\s\\S]+?)<\\/style\\b[^>]*>/i],\n[Nc,/^(<\\/?[a-z][^<>]*>)/i]]),[Kc,Oc,Pc,Qc,Rc,Sc,Tc]);y(K([[S,/^[\\s]+/,r,Uc],[Vc,/^(?:\\\"[^\\\"]*\\\"?|\\'[^\\']*\\'?)/,r,rc]],[[Wc,/^^<\\/?[a-z](?:[\\w:-]*\\w)?|\\/?>$/],[Xc,/^(?!style\\b|on)[a-z](?:[\\w:-]*\\w)?/],[Yc,/^=\\s*([^>\\'\\\"\\s]*(?:[^>\\'\\\"\\s\\/]|\\/(?=\\s)))/],[Y,/^[=<>\\/]+/],[Z,/^on\\w+\\s*=\\s*\\\"([^\\\"]+)\\\"/i],[Z,/^on\\w+\\s*=\\s*\\'([^\\']+)\\'/i],[Z,/^on\\w+\\s*=\\s*([^\\\"\\'>\\s]+)/i],[$,/^sty\\w+\\s*=\\s*\\\"([^\\\"]+)\\\"/i],[$,/^sty\\w+\\s*=\\s*\\'([^\\']+)\\'/i],[$,/^sty\\w+\\s*=\\s*([^\\\"\\'>\\s]+)/i]]),[Zc]);y(K([],[[Vc,/^[\\s\\S]+/]]),\n[$c]);y(C({keywords:ad,hashComments:o,cStyleComments:o}),[bd,cd,dd,ed,fd,gd]);y(C({keywords:hd}),[id]);y(C({keywords:jd,hashComments:o,cStyleComments:o}),[kd]);y(C({keywords:ld,cStyleComments:o}),[md]);y(C({keywords:nd,hashComments:o,multiLineStrings:o}),[od,pd,qd]);y(C({keywords:rd,hashComments:o,multiLineStrings:o,tripleQuotedStrings:o}),[sd,td]);y(C({keywords:ud,hashComments:o,multiLineStrings:o,regexLiterals:o}),[vd,wd,xd]);y(C({keywords:yd,hashComments:o,multiLineStrings:o,regexLiterals:o}),\n[zd]);y(C({keywords:Ad,cStyleComments:o,regexLiterals:o}),[Bd]);y(K([],[[U,/^[\\s\\S]+/]]),[Cd]);function Sa(a){var b=a.e,c=a.d;a.a=b;try{var d=Zd(b),g=d.source;a.source=g;a.b=0;a.f=d.tags;Ra(c,g)(a);be(a)}catch(i){if(Ic in window){console.log(i);console.h()}}}function ce(a,b){var c={e:a,d:b};Sa(c);return c.a}function de(a){for(var b=window._pr_isIE6(),c=[document.getElementsByTagName(Dd),document.getElementsByTagName(Ed),document.getElementsByTagName(Fd)],d=[],g=0;g<c.length;++g)for(var i=0,m=c[g].length;i<\nm;++i)d.push(c[g][i]);c=r;var l=Date;l.now||(l={now:function(){return(new Date).getTime()}});var n=0,q;function v(){for(var j=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;n<d.length&&l.now()<j;n++){var f=d[n];if(f.className&&f.className.indexOf(Gd)>=0){var s=f.className.match(/\\blang-(\\w+)\\b/);if(s)s=s[1];for(var k=z,h=f.parentNode;h;h=h.parentNode)if((h.tagName===Dd||h.tagName===Ed||h.tagName===Fd)&&h.className&&h.className.indexOf(Gd)>=0){k=o;break}if(!k){var e=Td(f);e=e.replace(/(?:\\r\\n?|\\n)$/,\nP);q={e:e,d:s,g:f};Sa(q);w()}}}if(n<d.length)setTimeout(v,250);else a&&a()}function w(){var j=q.a;if(j){var f=q.g;if(Ma(f)){for(var s=document.createElement(gc),k=0;k<f.attributes.length;++k){var h=f.attributes[k];if(h.specified){var e=h.name.toLowerCase();if(e===Hd)s.className=h.value;else s.setAttribute(h.name,h.value)}}s.innerHTML=j;f.parentNode.replaceChild(s,f);f=s}else f.innerHTML=j;if(b&&f.tagName===gc)for(var p=f.getElementsByTagName(Id),t=p.length;--t>=0;){var u=p[t];u.parentNode.replaceChild(document.createTextNode(Jd),\nu)}}}v()}window.PR_normalizedHtml=W;window.prettyPrintOne=ce;window.prettyPrint=de;window.PR={combinePrefixPatterns:Na,createSimpleLexer:K,registerLangHandler:y,sourceDecorator:C,PR_ATTRIB_NAME:Xc,PR_ATTRIB_VALUE:Vc,PR_COMMENT:V,PR_DECLARATION:Mc,PR_KEYWORD:uc,PR_LITERAL:yc,PR_NOCODE:lc,PR_PLAIN:S,PR_PUNCTUATION:Y,PR_SOURCE:oc,PR_STRING:U,PR_TAG:Wc,PR_TYPE:zc}})();\n})()\n"
  },
  {
    "path": "js/showdown.js",
    "content": "//\n// showdown.js -- A javascript port of Markdown.\n//\n// Copyright (c) 2007 John Fraser.\n//\n// Original Markdown Copyright (c) 2004-2005 John Gruber\n//   <http://daringfireball.net/projects/markdown/>\n//\n// The full source distribution is at:\n//\n//\t\t\t\tA A L\n//\t\t\t\tT C A\n//\t\t\t\tT K B\n//\n//   <http://www.attacklab.net/>\n//\n\n//\n// Wherever possible, Showdown is a straight, line-by-line port\n// of the Perl version of Markdown.\n//\n// This is not a normal parser design; it's basically just a\n// series of string substitutions.  It's hard to read and\n// maintain this way,  but keeping Showdown close to the original\n// design makes it easier to port new features.\n//\n// More importantly, Showdown behaves like markdown.pl in most\n// edge cases.  So web applications can do client-side preview\n// in Javascript, and then build identical HTML on the server.\n//\n// This port needs the new RegExp functionality of ECMA 262,\n// 3rd Edition (i.e. Javascript 1.5).  Most modern web browsers\n// should do fine.  Even with the new regular expression features,\n// We do a lot of work to emulate Perl's regex functionality.\n// The tricky changes in this file mostly have the \"attacklab:\"\n// label.  Major or self-explanatory changes don't.\n//\n// Smart diff tools like Araxis Merge will be able to match up\n// this file with markdown.pl in a useful way.  A little tweaking\n// helps: in a copy of markdown.pl, replace \"#\" with \"//\" and\n// replace \"$text\" with \"text\".  Be sure to ignore whitespace\n// and line endings.\n//\n\n\n//\n// Showdown usage:\n//\n//   var text = \"Markdown *rocks*.\";\n//\n//   var converter = new Attacklab.showdown.converter();\n//   var html = converter.makeHtml(text);\n//\n//   alert(html);\n//\n// Note: move the sample code to the bottom of this\n// file before uncommenting it.\n//\n\n\n//\n// Attacklab namespace\n//\nvar Attacklab = Attacklab || {}\n\n//\n// Showdown namespace\n//\nAttacklab.showdown = Attacklab.showdown || {}\n\n//\n// converter\n//\n// Wraps all \"globals\" so that the only thing\n// exposed is makeHtml().\n//\nAttacklab.showdown.converter = function() {\n\n//\n// Globals:\n//\n\n// Global hashes, used by various utility routines\nvar g_urls;\nvar g_titles;\nvar g_html_blocks;\n\n// Used to track when we're inside an ordered or unordered list\n// (see _ProcessListItems() for details):\nvar g_list_level = 0;\n\n\nthis.makeHtml = function(text) {\n//\n// Main function. The order in which other subs are called here is\n// essential. Link and image substitutions need to happen before\n// _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>\n// and <img> tags get encoded.\n//\n\n\t// Clear the global hashes. If we don't clear these, you get conflicts\n\t// from other articles when generating a page which contains more than\n\t// one article (e.g. an index page that shows the N most recent\n\t// articles):\n\tg_urls = new Array();\n\tg_titles = new Array();\n\tg_html_blocks = new Array();\n\n\t// attacklab: Replace ~ with ~T\n\t// This lets us use tilde as an escape char to avoid md5 hashes\n\t// The choice of character is arbitray; anything that isn't\n    // magic in Markdown will work.\n\ttext = text.replace(/~/g,\"~T\");\n\n\t// attacklab: Replace $ with ~D\n\t// RegExp interprets $ as a special character\n\t// when it's in a replacement string\n\ttext = text.replace(/\\$/g,\"~D\");\n\n\t// Standardize line endings\n\ttext = text.replace(/\\r\\n/g,\"\\n\"); // DOS to Unix\n\ttext = text.replace(/\\r/g,\"\\n\"); // Mac to Unix\n\n\t// Make sure text begins and ends with a couple of newlines:\n\ttext = \"\\n\\n\" + text + \"\\n\\n\";\n\n\t// Convert all tabs to spaces.\n\ttext = _Detab(text);\n\n\t// Strip any lines consisting only of spaces and tabs.\n\t// This makes subsequent regexen easier to write, because we can\n\t// match consecutive blank lines with /\\n+/ instead of something\n\t// contorted like /[ \\t]*\\n+/ .\n\ttext = text.replace(/^[ \\t]+$/mg,\"\");\n\n\t// Turn block-level HTML blocks into hash entries\n\ttext = _HashHTMLBlocks(text);\n\n\t// Strip link definitions, store in hashes.\n\ttext = _StripLinkDefinitions(text);\n\n\ttext = _RunBlockGamut(text);\n\n\ttext = _UnescapeSpecialChars(text);\n\n\t// attacklab: Restore dollar signs\n\ttext = text.replace(/~D/g,\"$$\");\n\n\t// attacklab: Restore tildes\n\ttext = text.replace(/~T/g,\"~\");\n\n\treturn text;\n}\n\nvar _StripLinkDefinitions = function(text) {\n//\n// Strips link definitions from text, stores the URLs and titles in\n// hash references.\n//\n\n\t// Link defs are in the form: ^[id]: url \"optional title\"\n\n\t/*\n\t\tvar text = text.replace(/\n\t\t\t\t^[ ]{0,3}\\[(.+)\\]:  // id = $1  attacklab: g_tab_width - 1\n\t\t\t\t  [ \\t]*\n\t\t\t\t  \\n?\t\t\t\t// maybe *one* newline\n\t\t\t\t  [ \\t]*\n\t\t\t\t<?(\\S+?)>?\t\t\t// url = $2\n\t\t\t\t  [ \\t]*\n\t\t\t\t  \\n?\t\t\t\t// maybe one newline\n\t\t\t\t  [ \\t]*\n\t\t\t\t(?:\n\t\t\t\t  (\\n*)\t\t\t\t// any lines skipped = $3 attacklab: lookbehind removed\n\t\t\t\t  [\"(]\n\t\t\t\t  (.+?)\t\t\t\t// title = $4\n\t\t\t\t  [\")]\n\t\t\t\t  [ \\t]*\n\t\t\t\t)?\t\t\t\t\t// title is optional\n\t\t\t\t(?:\\n+|$)\n\t\t\t  /gm,\n\t\t\t  function(){...});\n\t*/\n\tvar text = text.replace(/^[ ]{0,3}\\[(.+)\\]:[ \\t]*\\n?[ \\t]*<?(\\S+?)>?[ \\t]*\\n?[ \\t]*(?:(\\n*)[\"(](.+?)[\")][ \\t]*)?(?:\\n+)/gm,\n\t\tfunction (wholeMatch,m1,m2,m3,m4) {\n\t\t\tm1 = m1.toLowerCase();\n\t\t\tg_urls[m1] = _EncodeAmpsAndAngles(m2);  // Link IDs are case-insensitive\n\t\t\tif (m3) {\n\t\t\t\t// Oops, found blank lines, so it's not a title.\n\t\t\t\t// Put back the parenthetical statement we stole.\n\t\t\t\treturn m3+m4;\n\t\t\t} else if (m4) {\n\t\t\t\tg_titles[m1] = m4.replace(/\"/g,\"&quot;\");\n\t\t\t}\n\t\t\t\n\t\t\t// Completely remove the definition from the text\n\t\t\treturn \"\";\n\t\t}\n\t);\n\n\treturn text;\n}\n\nvar _HashHTMLBlocks = function(text) {\n\t// attacklab: Double up blank lines to reduce lookaround\n\ttext = text.replace(/\\n/g,\"\\n\\n\");\n\n\t// Hashify HTML blocks:\n\t// We only want to do this for block-level HTML tags, such as headers,\n\t// lists, and tables. That's because we still want to wrap <p>s around\n\t// \"paragraphs\" that are wrapped in non-block-level tags, such as anchors,\n\t// phrase emphasis, and spans. The list of tags we're looking for is\n\t// hard-coded:\n\tvar block_tags_a = \"p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del\"\n\tvar block_tags_b = \"p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math\"\n\n\t// First, look for nested blocks, e.g.:\n\t//   <div>\n\t//     <div>\n\t//     tags for inner block must be indented.\n\t//     </div>\n\t//   </div>\n\t//\n\t// The outermost tags must start at the left margin for this to match, and\n\t// the inner nested divs must be indented.\n\t// We need to do this before the next, more liberal match, because the next\n\t// match will start at the first `<div>` and stop at the first `</div>`.\n\n\t// attacklab: This regex can be expensive when it fails.\n\t/*\n\t\tvar text = text.replace(/\n\t\t(\t\t\t\t\t\t// save in $1\n\t\t\t^\t\t\t\t\t// start of line  (with /m)\n\t\t\t<($block_tags_a)\t// start tag = $2\n\t\t\t\\b\t\t\t\t\t// word break\n\t\t\t\t\t\t\t\t// attacklab: hack around khtml/pcre bug...\n\t\t\t[^\\r]*?\\n\t\t\t// any number of lines, minimally matching\n\t\t\t</\\2>\t\t\t\t// the matching end tag\n\t\t\t[ \\t]*\t\t\t\t// trailing spaces/tabs\n\t\t\t(?=\\n+)\t\t\t\t// followed by a newline\n\t\t)\t\t\t\t\t\t// attacklab: there are sentinel newlines at end of document\n\t\t/gm,function(){...}};\n\t*/\n\ttext = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\\b[^\\r]*?\\n<\\/\\2>[ \\t]*(?=\\n+))/gm,hashElement);\n\n\t//\n\t// Now match more liberally, simply from `\\n<tag>` to `</tag>\\n`\n\t//\n\n\t/*\n\t\tvar text = text.replace(/\n\t\t(\t\t\t\t\t\t// save in $1\n\t\t\t^\t\t\t\t\t// start of line  (with /m)\n\t\t\t<($block_tags_b)\t// start tag = $2\n\t\t\t\\b\t\t\t\t\t// word break\n\t\t\t\t\t\t\t\t// attacklab: hack around khtml/pcre bug...\n\t\t\t[^\\r]*?\t\t\t\t// any number of lines, minimally matching\n\t\t\t.*</\\2>\t\t\t\t// the matching end tag\n\t\t\t[ \\t]*\t\t\t\t// trailing spaces/tabs\n\t\t\t(?=\\n+)\t\t\t\t// followed by a newline\n\t\t)\t\t\t\t\t\t// attacklab: there are sentinel newlines at end of document\n\t\t/gm,function(){...}};\n\t*/\n\ttext = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\\b[^\\r]*?.*<\\/\\2>[ \\t]*(?=\\n+)\\n)/gm,hashElement);\n\n\t// Special case just for <hr />. It was easier to make a special case than\n\t// to make the other regex more complicated.  \n\n\t/*\n\t\ttext = text.replace(/\n\t\t(\t\t\t\t\t\t// save in $1\n\t\t\t\\n\\n\t\t\t\t// Starting after a blank line\n\t\t\t[ ]{0,3}\n\t\t\t(<(hr)\t\t\t\t// start tag = $2\n\t\t\t\\b\t\t\t\t\t// word break\n\t\t\t([^<>])*?\t\t\t// \n\t\t\t\\/?>)\t\t\t\t// the matching end tag\n\t\t\t[ \\t]*\n\t\t\t(?=\\n{2,})\t\t\t// followed by a blank line\n\t\t)\n\t\t/g,hashElement);\n\t*/\n\ttext = text.replace(/(\\n[ ]{0,3}(<(hr)\\b([^<>])*?\\/?>)[ \\t]*(?=\\n{2,}))/g,hashElement);\n\n\t// Special case for standalone HTML comments:\n\n\t/*\n\t\ttext = text.replace(/\n\t\t(\t\t\t\t\t\t// save in $1\n\t\t\t\\n\\n\t\t\t\t// Starting after a blank line\n\t\t\t[ ]{0,3}\t\t\t// attacklab: g_tab_width - 1\n\t\t\t<!\n\t\t\t(--[^\\r]*?--\\s*)+\n\t\t\t>\n\t\t\t[ \\t]*\n\t\t\t(?=\\n{2,})\t\t\t// followed by a blank line\n\t\t)\n\t\t/g,hashElement);\n\t*/\n\ttext = text.replace(/(\\n\\n[ ]{0,3}<!(--[^\\r]*?--\\s*)+>[ \\t]*(?=\\n{2,}))/g,hashElement);\n\n\t// PHP and ASP-style processor instructions (<?...?> and <%...%>)\n\n\t/*\n\t\ttext = text.replace(/\n\t\t(?:\n\t\t\t\\n\\n\t\t\t\t// Starting after a blank line\n\t\t)\n\t\t(\t\t\t\t\t\t// save in $1\n\t\t\t[ ]{0,3}\t\t\t// attacklab: g_tab_width - 1\n\t\t\t(?:\n\t\t\t\t<([?%])\t\t\t// $2\n\t\t\t\t[^\\r]*?\n\t\t\t\t\\2>\n\t\t\t)\n\t\t\t[ \\t]*\n\t\t\t(?=\\n{2,})\t\t\t// followed by a blank line\n\t\t)\n\t\t/g,hashElement);\n\t*/\n\ttext = text.replace(/(?:\\n\\n)([ ]{0,3}(?:<([?%])[^\\r]*?\\2>)[ \\t]*(?=\\n{2,}))/g,hashElement);\n\n\t// attacklab: Undo double lines (see comment at top of this function)\n\ttext = text.replace(/\\n\\n/g,\"\\n\");\n\treturn text;\n}\n\nvar hashElement = function(wholeMatch,m1) {\n\tvar blockText = m1;\n\n\t// Undo double lines\n\tblockText = blockText.replace(/\\n\\n/g,\"\\n\");\n\tblockText = blockText.replace(/^\\n/,\"\");\n\t\n\t// strip trailing blank lines\n\tblockText = blockText.replace(/\\n+$/g,\"\");\n\t\n\t// Replace the element text with a marker (\"~KxK\" where x is its key)\n\tblockText = \"\\n\\n~K\" + (g_html_blocks.push(blockText)-1) + \"K\\n\\n\";\n\t\n\treturn blockText;\n};\n\nvar _RunBlockGamut = function(text) {\n//\n// These are all the transformations that form block-level\n// tags like paragraphs, headers, and list items.\n//\n\ttext = _DoHeaders(text);\n\n\t// Do Horizontal Rules:\n\tvar key = hashBlock(\"<hr />\");\n\ttext = text.replace(/^[ ]{0,2}([ ]?\\*[ ]?){3,}[ \\t]*$/gm,key);\n\ttext = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \\t]*$/gm,key);\n\ttext = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \\t]*$/gm,key);\n\n\ttext = _DoLists(text);\n\ttext = _DoCodeBlocks(text);\n\ttext = _DoBlockQuotes(text);\n\n\t// We already ran _HashHTMLBlocks() before, in Markdown(), but that\n\t// was to escape raw HTML in the original Markdown source. This time,\n\t// we're escaping the markup we've just created, so that we don't wrap\n\t// <p> tags around block-level tags.\n\ttext = _HashHTMLBlocks(text);\n\ttext = _FormParagraphs(text);\n\n\treturn text;\n}\n\n\nvar _RunSpanGamut = function(text) {\n//\n// These are all the transformations that occur *within* block-level\n// tags like paragraphs, headers, and list items.\n//\n\n\ttext = _DoCodeSpans(text);\n\ttext = _EscapeSpecialCharsWithinTagAttributes(text);\n\ttext = _EncodeBackslashEscapes(text);\n\n\t// Process anchor and image tags. Images must come first,\n\t// because ![foo][f] looks like an anchor.\n\ttext = _DoImages(text);\n\ttext = _DoAnchors(text);\n\n\t// Make links out of things like `<http://example.com/>`\n\t// Must come after _DoAnchors(), because you can use < and >\n\t// delimiters in inline links like [this](<url>).\n\ttext = _DoAutoLinks(text);\n\ttext = _EncodeAmpsAndAngles(text);\n\ttext = _DoItalicsAndBold(text);\n\n\t// Do hard breaks:\n\ttext = text.replace(/  +\\n/g,\" <br />\\n\");\n\n\treturn text;\n}\n\nvar _EscapeSpecialCharsWithinTagAttributes = function(text) {\n//\n// Within tags -- meaning between < and > -- encode [\\ ` * _] so they\n// don't conflict with their use in Markdown for code, italics and strong.\n//\n\n\t// Build a regex to find HTML tags and comments.  See Friedl's \n\t// \"Mastering Regular Expressions\", 2nd Ed., pp. 200-201.\n\tvar regex = /(<[a-z\\/!$](\"[^\"]*\"|'[^']*'|[^'\">])*>|<!(--.*?--\\s*)+>)/gi;\n\n\ttext = text.replace(regex, function(wholeMatch) {\n\t\tvar tag = wholeMatch.replace(/(.)<\\/?code>(?=.)/g,\"$1`\");\n\t\ttag = escapeCharacters(tag,\"\\\\`*_\");\n\t\treturn tag;\n\t});\n\n\treturn text;\n}\n\nvar _DoAnchors = function(text) {\n//\n// Turn Markdown link shortcuts into XHTML <a> tags.\n//\n\t//\n\t// First, handle reference-style links: [link text] [id]\n\t//\n\n\t/*\n\t\ttext = text.replace(/\n\t\t(\t\t\t\t\t\t\t// wrap whole match in $1\n\t\t\t\\[\n\t\t\t(\n\t\t\t\t(?:\n\t\t\t\t\t\\[[^\\]]*\\]\t\t// allow brackets nested one level\n\t\t\t\t\t|\n\t\t\t\t\t[^\\[]\t\t\t// or anything else\n\t\t\t\t)*\n\t\t\t)\n\t\t\t\\]\n\n\t\t\t[ ]?\t\t\t\t\t// one optional space\n\t\t\t(?:\\n[ ]*)?\t\t\t\t// one optional newline followed by spaces\n\n\t\t\t\\[\n\t\t\t(.*?)\t\t\t\t\t// id = $3\n\t\t\t\\]\n\t\t)()()()()\t\t\t\t\t// pad remaining backreferences\n\t\t/g,_DoAnchors_callback);\n\t*/\n\ttext = text.replace(/(\\[((?:\\[[^\\]]*\\]|[^\\[\\]])*)\\][ ]?(?:\\n[ ]*)?\\[(.*?)\\])()()()()/g,writeAnchorTag);\n\n\t//\n\t// Next, inline-style links: [link text](url \"optional title\")\n\t//\n\n\t/*\n\t\ttext = text.replace(/\n\t\t\t(\t\t\t\t\t\t// wrap whole match in $1\n\t\t\t\t\\[\n\t\t\t\t(\n\t\t\t\t\t(?:\n\t\t\t\t\t\t\\[[^\\]]*\\]\t// allow brackets nested one level\n\t\t\t\t\t|\n\t\t\t\t\t[^\\[\\]]\t\t\t// or anything else\n\t\t\t\t)\n\t\t\t)\n\t\t\t\\]\n\t\t\t\\(\t\t\t\t\t\t// literal paren\n\t\t\t[ \\t]*\n\t\t\t()\t\t\t\t\t\t// no id, so leave $3 empty\n\t\t\t<?(.*?)>?\t\t\t\t// href = $4\n\t\t\t[ \\t]*\n\t\t\t(\t\t\t\t\t\t// $5\n\t\t\t\t(['\"])\t\t\t\t// quote char = $6\n\t\t\t\t(.*?)\t\t\t\t// Title = $7\n\t\t\t\t\\6\t\t\t\t\t// matching quote\n\t\t\t\t[ \\t]*\t\t\t\t// ignore any spaces/tabs between closing quote and )\n\t\t\t)?\t\t\t\t\t\t// title is optional\n\t\t\t\\)\n\t\t)\n\t\t/g,writeAnchorTag);\n\t*/\n\ttext = text.replace(/(\\[((?:\\[[^\\]]*\\]|[^\\[\\]])*)\\]\\([ \\t]*()<?(.*?)>?[ \\t]*((['\"])(.*?)\\6[ \\t]*)?\\))/g,writeAnchorTag);\n\n\t//\n\t// Last, handle reference-style shortcuts: [link text]\n\t// These must come last in case you've also got [link test][1]\n\t// or [link test](/foo)\n\t//\n\n\t/*\n\t\ttext = text.replace(/\n\t\t(\t\t \t\t\t\t\t// wrap whole match in $1\n\t\t\t\\[\n\t\t\t([^\\[\\]]+)\t\t\t\t// link text = $2; can't contain '[' or ']'\n\t\t\t\\]\n\t\t)()()()()()\t\t\t\t\t// pad rest of backreferences\n\t\t/g, writeAnchorTag);\n\t*/\n\ttext = text.replace(/(\\[([^\\[\\]]+)\\])()()()()()/g, writeAnchorTag);\n\n\treturn text;\n}\n\nvar writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {\n\tif (m7 == undefined) m7 = \"\";\n\tvar whole_match = m1;\n\tvar link_text   = m2;\n\tvar link_id\t = m3.toLowerCase();\n\tvar url\t\t= m4;\n\tvar title\t= m7;\n\t\n\tif (url == \"\") {\n\t\tif (link_id == \"\") {\n\t\t\t// lower-case and turn embedded newlines into spaces\n\t\t\tlink_id = link_text.toLowerCase().replace(/ ?\\n/g,\" \");\n\t\t}\n\t\turl = \"#\"+link_id;\n\t\t\n\t\tif (g_urls[link_id] != undefined) {\n\t\t\turl = g_urls[link_id];\n\t\t\tif (g_titles[link_id] != undefined) {\n\t\t\t\ttitle = g_titles[link_id];\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (whole_match.search(/\\(\\s*\\)$/m)>-1) {\n\t\t\t\t// Special case for explicit empty url\n\t\t\t\turl = \"\";\n\t\t\t} else {\n\t\t\t\treturn whole_match;\n\t\t\t}\n\t\t}\n\t}\t\n\t\n\turl = escapeCharacters(url,\"*_\");\n\tvar result = \"<a href=\\\"\" + url + \"\\\"\";\n\t\n\tif (title != \"\") {\n\t\ttitle = title.replace(/\"/g,\"&quot;\");\n\t\ttitle = escapeCharacters(title,\"*_\");\n\t\tresult +=  \" title=\\\"\" + title + \"\\\"\";\n\t}\n\t\n\tresult += \">\" + link_text + \"</a>\";\n\t\n\treturn result;\n}\n\n\nvar _DoImages = function(text) {\n//\n// Turn Markdown image shortcuts into <img> tags.\n//\n\n\t//\n\t// First, handle reference-style labeled images: ![alt text][id]\n\t//\n\n\t/*\n\t\ttext = text.replace(/\n\t\t(\t\t\t\t\t\t// wrap whole match in $1\n\t\t\t!\\[\n\t\t\t(.*?)\t\t\t\t// alt text = $2\n\t\t\t\\]\n\n\t\t\t[ ]?\t\t\t\t// one optional space\n\t\t\t(?:\\n[ ]*)?\t\t\t// one optional newline followed by spaces\n\n\t\t\t\\[\n\t\t\t(.*?)\t\t\t\t// id = $3\n\t\t\t\\]\n\t\t)()()()()\t\t\t\t// pad rest of backreferences\n\t\t/g,writeImageTag);\n\t*/\n\ttext = text.replace(/(!\\[(.*?)\\][ ]?(?:\\n[ ]*)?\\[(.*?)\\])()()()()/g,writeImageTag);\n\n\t//\n\t// Next, handle inline images:  ![alt text](url \"optional title\")\n\t// Don't forget: encode * and _\n\n\t/*\n\t\ttext = text.replace(/\n\t\t(\t\t\t\t\t\t// wrap whole match in $1\n\t\t\t!\\[\n\t\t\t(.*?)\t\t\t\t// alt text = $2\n\t\t\t\\]\n\t\t\t\\s?\t\t\t\t\t// One optional whitespace character\n\t\t\t\\(\t\t\t\t\t// literal paren\n\t\t\t[ \\t]*\n\t\t\t()\t\t\t\t\t// no id, so leave $3 empty\n\t\t\t<?(\\S+?)>?\t\t\t// src url = $4\n\t\t\t[ \\t]*\n\t\t\t(\t\t\t\t\t// $5\n\t\t\t\t(['\"])\t\t\t// quote char = $6\n\t\t\t\t(.*?)\t\t\t// title = $7\n\t\t\t\t\\6\t\t\t\t// matching quote\n\t\t\t\t[ \\t]*\n\t\t\t)?\t\t\t\t\t// title is optional\n\t\t\\)\n\t\t)\n\t\t/g,writeImageTag);\n\t*/\n\ttext = text.replace(/(!\\[(.*?)\\]\\s?\\([ \\t]*()<?(\\S+?)>?[ \\t]*((['\"])(.*?)\\6[ \\t]*)?\\))/g,writeImageTag);\n\n\treturn text;\n}\n\nvar writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {\n\tvar whole_match = m1;\n\tvar alt_text   = m2;\n\tvar link_id\t = m3.toLowerCase();\n\tvar url\t\t= m4;\n\tvar title\t= m7;\n\n\tif (!title) title = \"\";\n\t\n\tif (url == \"\") {\n\t\tif (link_id == \"\") {\n\t\t\t// lower-case and turn embedded newlines into spaces\n\t\t\tlink_id = alt_text.toLowerCase().replace(/ ?\\n/g,\" \");\n\t\t}\n\t\turl = \"#\"+link_id;\n\t\t\n\t\tif (g_urls[link_id] != undefined) {\n\t\t\turl = g_urls[link_id];\n\t\t\tif (g_titles[link_id] != undefined) {\n\t\t\t\ttitle = g_titles[link_id];\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn whole_match;\n\t\t}\n\t}\t\n\t\n\talt_text = alt_text.replace(/\"/g,\"&quot;\");\n\turl = escapeCharacters(url,\"*_\");\n\tvar result = \"<img src=\\\"\" + url + \"\\\" alt=\\\"\" + alt_text + \"\\\"\";\n\n\t// attacklab: Markdown.pl adds empty title attributes to images.\n\t// Replicate this bug.\n\n\t//if (title != \"\") {\n\t\ttitle = title.replace(/\"/g,\"&quot;\");\n\t\ttitle = escapeCharacters(title,\"*_\");\n\t\tresult +=  \" title=\\\"\" + title + \"\\\"\";\n\t//}\n\t\n\tresult += \" />\";\n\t\n\treturn result;\n}\n\n\nvar _DoHeaders = function(text) {\n\n\t// Setext-style headers:\n\t//\tHeader 1\n\t//\t========\n\t//  \n\t//\tHeader 2\n\t//\t--------\n\t//\n\ttext = text.replace(/^(.+)[ \\t]*\\n=+[ \\t]*\\n+/gm,\n\t\tfunction(wholeMatch,m1){return hashBlock(\"<h1>\" + _RunSpanGamut(m1) + \"</h1>\");});\n\n\ttext = text.replace(/^(.+)[ \\t]*\\n-+[ \\t]*\\n+/gm,\n\t\tfunction(matchFound,m1){return hashBlock(\"<h2>\" + _RunSpanGamut(m1) + \"</h2>\");});\n\n\t// atx-style headers:\n\t//  # Header 1\n\t//  ## Header 2\n\t//  ## Header 2 with closing hashes ##\n\t//  ...\n\t//  ###### Header 6\n\t//\n\n\t/*\n\t\ttext = text.replace(/\n\t\t\t^(\\#{1,6})\t\t\t\t// $1 = string of #'s\n\t\t\t[ \\t]*\n\t\t\t(.+?)\t\t\t\t\t// $2 = Header text\n\t\t\t[ \\t]*\n\t\t\t\\#*\t\t\t\t\t\t// optional closing #'s (not counted)\n\t\t\t\\n+\n\t\t/gm, function() {...});\n\t*/\n\n\ttext = text.replace(/^(\\#{1,6})[ \\t]*(.+?)[ \\t]*\\#*\\n+/gm,\n\t\tfunction(wholeMatch,m1,m2) {\n\t\t\tvar h_level = m1.length;\n\t\t\treturn hashBlock(\"<h\" + h_level + \">\" + _RunSpanGamut(m2) + \"</h\" + h_level + \">\");\n\t\t});\n\n\treturn text;\n}\n\n// This declaration keeps Dojo compressor from outputting garbage:\nvar _ProcessListItems;\n\nvar _DoLists = function(text) {\n//\n// Form HTML ordered (numbered) and unordered (bulleted) lists.\n//\n\n\t// attacklab: add sentinel to hack around khtml/safari bug:\n\t// http://bugs.webkit.org/show_bug.cgi?id=11231\n\ttext += \"~0\";\n\n\t// Re-usable pattern to match any entirel ul or ol list:\n\n\t/*\n\t\tvar whole_list = /\n\t\t(\t\t\t\t\t\t\t\t\t// $1 = whole list\n\t\t\t(\t\t\t\t\t\t\t\t// $2\n\t\t\t\t[ ]{0,3}\t\t\t\t\t// attacklab: g_tab_width - 1\n\t\t\t\t([*+-]|\\d+[.])\t\t\t\t// $3 = first list item marker\n\t\t\t\t[ \\t]+\n\t\t\t)\n\t\t\t[^\\r]+?\n\t\t\t(\t\t\t\t\t\t\t\t// $4\n\t\t\t\t~0\t\t\t\t\t\t\t// sentinel for workaround; should be $\n\t\t\t|\n\t\t\t\t\\n{2,}\n\t\t\t\t(?=\\S)\n\t\t\t\t(?!\t\t\t\t\t\t\t// Negative lookahead for another list item marker\n\t\t\t\t\t[ \\t]*\n\t\t\t\t\t(?:[*+-]|\\d+[.])[ \\t]+\n\t\t\t\t)\n\t\t\t)\n\t\t)/g\n\t*/\n\tvar whole_list = /^(([ ]{0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(~0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/gm;\n\n\tif (g_list_level) {\n\t\ttext = text.replace(whole_list,function(wholeMatch,m1,m2) {\n\t\t\tvar list = m1;\n\t\t\tvar list_type = (m2.search(/[*+-]/g)>-1) ? \"ul\" : \"ol\";\n\n\t\t\t// Turn double returns into triple returns, so that we can make a\n\t\t\t// paragraph for the last item in a list, if necessary:\n\t\t\tlist = list.replace(/\\n{2,}/g,\"\\n\\n\\n\");;\n\t\t\tvar result = _ProcessListItems(list);\n\t\n\t\t\t// Trim any trailing whitespace, to put the closing `</$list_type>`\n\t\t\t// up on the preceding line, to get it past the current stupid\n\t\t\t// HTML block parser. This is a hack to work around the terrible\n\t\t\t// hack that is the HTML block parser.\n\t\t\tresult = result.replace(/\\s+$/,\"\");\n\t\t\tresult = \"<\"+list_type+\">\" + result + \"</\"+list_type+\">\\n\";\n\t\t\treturn result;\n\t\t});\n\t} else {\n\t\twhole_list = /(\\n\\n|^\\n?)(([ ]{0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(~0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/g;\n\t\ttext = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {\n\t\t\tvar runup = m1;\n\t\t\tvar list = m2;\n\n\t\t\tvar list_type = (m3.search(/[*+-]/g)>-1) ? \"ul\" : \"ol\";\n\t\t\t// Turn double returns into triple returns, so that we can make a\n\t\t\t// paragraph for the last item in a list, if necessary:\n\t\t\tvar list = list.replace(/\\n{2,}/g,\"\\n\\n\\n\");;\n\t\t\tvar result = _ProcessListItems(list);\n\t\t\tresult = runup + \"<\"+list_type+\">\\n\" + result + \"</\"+list_type+\">\\n\";\t\n\t\t\treturn result;\n\t\t});\n\t}\n\n\t// attacklab: strip sentinel\n\ttext = text.replace(/~0/,\"\");\n\n\treturn text;\n}\n\n_ProcessListItems = function(list_str) {\n//\n//  Process the contents of a single ordered or unordered list, splitting it\n//  into individual list items.\n//\n\t// The $g_list_level global keeps track of when we're inside a list.\n\t// Each time we enter a list, we increment it; when we leave a list,\n\t// we decrement. If it's zero, we're not in a list anymore.\n\t//\n\t// We do this because when we're not inside a list, we want to treat\n\t// something like this:\n\t//\n\t//    I recommend upgrading to version\n\t//    8. Oops, now this line is treated\n\t//    as a sub-list.\n\t//\n\t// As a single paragraph, despite the fact that the second line starts\n\t// with a digit-period-space sequence.\n\t//\n\t// Whereas when we're inside a list (or sub-list), that line will be\n\t// treated as the start of a sub-list. What a kludge, huh? This is\n\t// an aspect of Markdown's syntax that's hard to parse perfectly\n\t// without resorting to mind-reading. Perhaps the solution is to\n\t// change the syntax rules such that sub-lists must start with a\n\t// starting cardinal number; e.g. \"1.\" or \"a.\".\n\n\tg_list_level++;\n\n\t// trim trailing blank lines:\n\tlist_str = list_str.replace(/\\n{2,}$/,\"\\n\");\n\n\t// attacklab: add sentinel to emulate \\z\n\tlist_str += \"~0\";\n\n\t/*\n\t\tlist_str = list_str.replace(/\n\t\t\t(\\n)?\t\t\t\t\t\t\t// leading line = $1\n\t\t\t(^[ \\t]*)\t\t\t\t\t\t// leading whitespace = $2\n\t\t\t([*+-]|\\d+[.]) [ \\t]+\t\t\t// list marker = $3\n\t\t\t([^\\r]+?\t\t\t\t\t\t// list item text   = $4\n\t\t\t(\\n{1,2}))\n\t\t\t(?= \\n* (~0 | \\2 ([*+-]|\\d+[.]) [ \\t]+))\n\t\t/gm, function(){...});\n\t*/\n\tlist_str = list_str.replace(/(\\n)?(^[ \\t]*)([*+-]|\\d+[.])[ \\t]+([^\\r]+?(\\n{1,2}))(?=\\n*(~0|\\2([*+-]|\\d+[.])[ \\t]+))/gm,\n\t\tfunction(wholeMatch,m1,m2,m3,m4){\n\t\t\tvar item = m4;\n\t\t\tvar leading_line = m1;\n\t\t\tvar leading_space = m2;\n\n\t\t\tif (leading_line || (item.search(/\\n{2,}/)>-1)) {\n\t\t\t\titem = _RunBlockGamut(_Outdent(item));\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Recursion for sub-lists:\n\t\t\t\titem = _DoLists(_Outdent(item));\n\t\t\t\titem = item.replace(/\\n$/,\"\"); // chomp(item)\n\t\t\t\titem = _RunSpanGamut(item);\n\t\t\t}\n\n\t\t\treturn  \"<li>\" + item + \"</li>\\n\";\n\t\t}\n\t);\n\n\t// attacklab: strip sentinel\n\tlist_str = list_str.replace(/~0/g,\"\");\n\n\tg_list_level--;\n\treturn list_str;\n}\n\n\nvar _DoCodeBlocks = function(text) {\n//\n//  Process Markdown `<pre><code>` blocks.\n//  \n\n\t/*\n\t\ttext = text.replace(text,\n\t\t\t/(?:\\n\\n|^)\n\t\t\t(\t\t\t\t\t\t\t\t// $1 = the code block -- one or more lines, starting with a space/tab\n\t\t\t\t(?:\n\t\t\t\t\t(?:[ ]{4}|\\t)\t\t\t// Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width\n\t\t\t\t\t.*\\n+\n\t\t\t\t)+\n\t\t\t)\n\t\t\t(\\n*[ ]{0,3}[^ \\t\\n]|(?=~0))\t// attacklab: g_tab_width\n\t\t/g,function(){...});\n\t*/\n\n\t// attacklab: sentinel workarounds for lack of \\A and \\Z, safari\\khtml bug\n\ttext += \"~0\";\n\t\n\ttext = text.replace(/(?:\\n\\n|^)((?:(?:[ ]{4}|\\t).*\\n+)+)(\\n*[ ]{0,3}[^ \\t\\n]|(?=~0))/g,\n\t\tfunction(wholeMatch,m1,m2) {\n\t\t\tvar codeblock = m1;\n\t\t\tvar nextChar = m2;\n\t\t\n\t\t\tcodeblock = _EncodeCode( _Outdent(codeblock));\n\t\t\tcodeblock = _Detab(codeblock);\n\t\t\tcodeblock = codeblock.replace(/^\\n+/g,\"\"); // trim leading newlines\n\t\t\tcodeblock = codeblock.replace(/\\n+$/g,\"\"); // trim trailing whitespace\n\n\t\t\tcodeblock = \"<pre><code>\" + codeblock + \"\\n</code></pre>\";\n\n\t\t\treturn hashBlock(codeblock) + nextChar;\n\t\t}\n\t);\n\n\t// attacklab: strip sentinel\n\ttext = text.replace(/~0/,\"\");\n\n\treturn text;\n}\n\nvar hashBlock = function(text) {\n\ttext = text.replace(/(^\\n+|\\n+$)/g,\"\");\n\treturn \"\\n\\n~K\" + (g_html_blocks.push(text)-1) + \"K\\n\\n\";\n}\n\n\nvar _DoCodeSpans = function(text) {\n//\n//   *  Backtick quotes are used for <code></code> spans.\n// \n//   *  You can use multiple backticks as the delimiters if you want to\n//\t include literal backticks in the code span. So, this input:\n//\t \n//\t\t Just type ``foo `bar` baz`` at the prompt.\n//\t \n//\t   Will translate to:\n//\t \n//\t\t <p>Just type <code>foo `bar` baz</code> at the prompt.</p>\n//\t \n//\tThere's no arbitrary limit to the number of backticks you\n//\tcan use as delimters. If you need three consecutive backticks\n//\tin your code, use four for delimiters, etc.\n//\n//  *  You can use spaces to get literal backticks at the edges:\n//\t \n//\t\t ... type `` `bar` `` ...\n//\t \n//\t   Turns to:\n//\t \n//\t\t ... type <code>`bar`</code> ...\n//\n\n\t/*\n\t\ttext = text.replace(/\n\t\t\t(^|[^\\\\])\t\t\t\t\t// Character before opening ` can't be a backslash\n\t\t\t(`+)\t\t\t\t\t\t// $2 = Opening run of `\n\t\t\t(\t\t\t\t\t\t\t// $3 = The code block\n\t\t\t\t[^\\r]*?\n\t\t\t\t[^`]\t\t\t\t\t// attacklab: work around lack of lookbehind\n\t\t\t)\n\t\t\t\\2\t\t\t\t\t\t\t// Matching closer\n\t\t\t(?!`)\n\t\t/gm, function(){...});\n\t*/\n\n\ttext = text.replace(/(^|[^\\\\])(`+)([^\\r]*?[^`])\\2(?!`)/gm,\n\t\tfunction(wholeMatch,m1,m2,m3,m4) {\n\t\t\tvar c = m3;\n\t\t\tc = c.replace(/^([ \\t]*)/g,\"\");\t// leading whitespace\n\t\t\tc = c.replace(/[ \\t]*$/g,\"\");\t// trailing whitespace\n\t\t\tc = _EncodeCode(c);\n\t\t\treturn m1+\"<code>\"+c+\"</code>\";\n\t\t});\n\n\treturn text;\n}\n\n\nvar _EncodeCode = function(text) {\n//\n// Encode/escape certain characters inside Markdown code runs.\n// The point is that in code, these characters are literals,\n// and lose their special Markdown meanings.\n//\n\t// Encode all ampersands; HTML entities are not\n\t// entities within a Markdown code span.\n\ttext = text.replace(/&/g,\"&amp;\");\n\n\t// Do the angle bracket song and dance:\n\ttext = text.replace(/</g,\"&lt;\");\n\ttext = text.replace(/>/g,\"&gt;\");\n\n\t// Now, escape characters that are magic in Markdown:\n\ttext = escapeCharacters(text,\"\\*_{}[]\\\\\",false);\n\n// jj the line above breaks this:\n//---\n\n//* Item\n\n//   1. Subitem\n\n//            special char: *\n//---\n\n\treturn text;\n}\n\n\nvar _DoItalicsAndBold = function(text) {\n\n\t// <strong> must go first:\n\ttext = text.replace(/(\\*\\*|__)(?=\\S)([^\\r]*?\\S[\\*_]*)\\1/g,\n\t\t\"<strong>$2</strong>\");\n\n\ttext = text.replace(/(\\*|_)(?=\\S)([^\\r]*?\\S)\\1/g,\n\t\t\"<em>$2</em>\");\n\n\treturn text;\n}\n\n\nvar _DoBlockQuotes = function(text) {\n\n\t/*\n\t\ttext = text.replace(/\n\t\t(\t\t\t\t\t\t\t\t// Wrap whole match in $1\n\t\t\t(\n\t\t\t\t^[ \\t]*>[ \\t]?\t\t\t// '>' at the start of a line\n\t\t\t\t.+\\n\t\t\t\t\t// rest of the first line\n\t\t\t\t(.+\\n)*\t\t\t\t\t// subsequent consecutive lines\n\t\t\t\t\\n*\t\t\t\t\t\t// blanks\n\t\t\t)+\n\t\t)\n\t\t/gm, function(){...});\n\t*/\n\n\ttext = text.replace(/((^[ \\t]*>[ \\t]?.+\\n(.+\\n)*\\n*)+)/gm,\n\t\tfunction(wholeMatch,m1) {\n\t\t\tvar bq = m1;\n\n\t\t\t// attacklab: hack around Konqueror 3.5.4 bug:\n\t\t\t// \"----------bug\".replace(/^-/g,\"\") == \"bug\"\n\n\t\t\tbq = bq.replace(/^[ \\t]*>[ \\t]?/gm,\"~0\");\t// trim one level of quoting\n\n\t\t\t// attacklab: clean up hack\n\t\t\tbq = bq.replace(/~0/g,\"\");\n\n\t\t\tbq = bq.replace(/^[ \\t]+$/gm,\"\");\t\t// trim whitespace-only lines\n\t\t\tbq = _RunBlockGamut(bq);\t\t\t\t// recurse\n\t\t\t\n\t\t\tbq = bq.replace(/(^|\\n)/g,\"$1  \");\n\t\t\t// These leading spaces screw with <pre> content, so we need to fix that:\n\t\t\tbq = bq.replace(\n\t\t\t\t\t/(\\s*<pre>[^\\r]+?<\\/pre>)/gm,\n\t\t\t\tfunction(wholeMatch,m1) {\n\t\t\t\t\tvar pre = m1;\n\t\t\t\t\t// attacklab: hack around Konqueror 3.5.4 bug:\n\t\t\t\t\tpre = pre.replace(/^  /mg,\"~0\");\n\t\t\t\t\tpre = pre.replace(/~0/g,\"\");\n\t\t\t\t\treturn pre;\n\t\t\t\t});\n\t\t\t\n\t\t\treturn hashBlock(\"<blockquote>\\n\" + bq + \"\\n</blockquote>\");\n\t\t});\n\treturn text;\n}\n\n\nvar _FormParagraphs = function(text) {\n//\n//  Params:\n//    $text - string to process with html <p> tags\n//\n\n\t// Strip leading and trailing lines:\n\ttext = text.replace(/^\\n+/g,\"\");\n\ttext = text.replace(/\\n+$/g,\"\");\n\n\tvar grafs = text.split(/\\n{2,}/g);\n\tvar grafsOut = new Array();\n\n\t//\n\t// Wrap <p> tags.\n\t//\n\tvar end = grafs.length;\n\tfor (var i=0; i<end; i++) {\n\t\tvar str = grafs[i];\n\n\t\t// if this is an HTML marker, copy it\n\t\tif (str.search(/~K(\\d+)K/g) >= 0) {\n\t\t\tgrafsOut.push(str);\n\t\t}\n\t\telse if (str.search(/\\S/) >= 0) {\n\t\t\tstr = _RunSpanGamut(str);\n\t\t\tstr = str.replace(/^([ \\t]*)/g,\"<p>\");\n\t\t\tstr += \"</p>\"\n\t\t\tgrafsOut.push(str);\n\t\t}\n\n\t}\n\n\t//\n\t// Unhashify HTML blocks\n\t//\n\tend = grafsOut.length;\n\tfor (var i=0; i<end; i++) {\n\t\t// if this is a marker for an html block...\n\t\twhile (grafsOut[i].search(/~K(\\d+)K/) >= 0) {\n\t\t\tvar blockText = g_html_blocks[RegExp.$1];\n\t\t\tblockText = blockText.replace(/\\$/g,\"$$$$\"); // Escape any dollar signs\n\t\t\tgrafsOut[i] = grafsOut[i].replace(/~K\\d+K/,blockText);\n\t\t}\n\t}\n\n\treturn grafsOut.join(\"\\n\\n\");\n}\n\n\nvar _EncodeAmpsAndAngles = function(text) {\n// Smart processing for ampersands and angle brackets that need to be encoded.\n\t\n\t// Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:\n\t//   http://bumppo.net/projects/amputator/\n\ttext = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)/g,\"&amp;\");\n\t\n\t// Encode naked <'s\n\ttext = text.replace(/<(?![a-z\\/?\\$!])/gi,\"&lt;\");\n\t\n\treturn text;\n}\n\n\nvar _EncodeBackslashEscapes = function(text) {\n//\n//   Parameter:  String.\n//   Returns:\tThe string, with after processing the following backslash\n//\t\t\t   escape sequences.\n//\n\n\t// attacklab: The polite way to do this is with the new\n\t// escapeCharacters() function:\n\t//\n\t// \ttext = escapeCharacters(text,\"\\\\\",true);\n\t// \ttext = escapeCharacters(text,\"`*_{}[]()>#+-.!\",true);\n\t//\n\t// ...but we're sidestepping its use of the (slow) RegExp constructor\n\t// as an optimization for Firefox.  This function gets called a LOT.\n\n\ttext = text.replace(/\\\\(\\\\)/g,escapeCharacters_callback);\n\ttext = text.replace(/\\\\([`*_{}\\[\\]()>#+-.!])/g,escapeCharacters_callback);\n\treturn text;\n}\n\n\nvar _DoAutoLinks = function(text) {\n\n\ttext = text.replace(/<((https?|ftp|dict):[^'\">\\s]+)>/gi,\"<a href=\\\"$1\\\">$1</a>\");\n\n\t// Email addresses: <address@domain.foo>\n\n\t/*\n\t\ttext = text.replace(/\n\t\t\t<\n\t\t\t(?:mailto:)?\n\t\t\t(\n\t\t\t\t[-.\\w]+\n\t\t\t\t\\@\n\t\t\t\t[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+\n\t\t\t)\n\t\t\t>\n\t\t/gi, _DoAutoLinks_callback());\n\t*/\n\ttext = text.replace(/<(?:mailto:)?([-.\\w]+\\@[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+)>/gi,\n\t\tfunction(wholeMatch,m1) {\n\t\t\treturn _EncodeEmailAddress( _UnescapeSpecialChars(m1) );\n\t\t}\n\t);\n\n\treturn text;\n}\n\n\nvar _EncodeEmailAddress = function(addr) {\n//\n//  Input: an email address, e.g. \"foo@example.com\"\n//\n//  Output: the email address as a mailto link, with each character\n//\tof the address encoded as either a decimal or hex entity, in\n//\tthe hopes of foiling most address harvesting spam bots. E.g.:\n//\n//\t<a href=\"&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;\n//\t   x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;\">&#102;&#111;&#111;\n//\t   &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>\n//\n//  Based on a filter by Matthew Wickline, posted to the BBEdit-Talk\n//  mailing list: <http://tinyurl.com/yu7ue>\n//\n\n\t// attacklab: why can't javascript speak hex?\n\tfunction char2hex(ch) {\n\t\tvar hexDigits = '0123456789ABCDEF';\n\t\tvar dec = ch.charCodeAt(0);\n\t\treturn(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));\n\t}\n\n\tvar encode = [\n\t\tfunction(ch){return \"&#\"+ch.charCodeAt(0)+\";\";},\n\t\tfunction(ch){return \"&#x\"+char2hex(ch)+\";\";},\n\t\tfunction(ch){return ch;}\n\t];\n\n\taddr = \"mailto:\" + addr;\n\n\taddr = addr.replace(/./g, function(ch) {\n\t\tif (ch == \"@\") {\n\t\t   \t// this *must* be encoded. I insist.\n\t\t\tch = encode[Math.floor(Math.random()*2)](ch);\n\t\t} else if (ch !=\":\") {\n\t\t\t// leave ':' alone (to spot mailto: later)\n\t\t\tvar r = Math.random();\n\t\t\t// roughly 10% raw, 45% hex, 45% dec\n\t\t\tch =  (\n\t\t\t\t\tr > .9  ?\tencode[2](ch)   :\n\t\t\t\t\tr > .45 ?\tencode[1](ch)   :\n\t\t\t\t\t\t\t\tencode[0](ch)\n\t\t\t\t);\n\t\t}\n\t\treturn ch;\n\t});\n\n\taddr = \"<a href=\\\"\" + addr + \"\\\">\" + addr + \"</a>\";\n\taddr = addr.replace(/\">.+:/g,\"\\\">\"); // strip the mailto: from the visible part\n\n\treturn addr;\n}\n\n\nvar _UnescapeSpecialChars = function(text) {\n//\n// Swap back in all the special characters we've hidden.\n//\n\ttext = text.replace(/~E(\\d+)E/g,\n\t\tfunction(wholeMatch,m1) {\n\t\t\tvar charCodeToReplace = parseInt(m1);\n\t\t\treturn String.fromCharCode(charCodeToReplace);\n\t\t}\n\t);\n\treturn text;\n}\n\n\nvar _Outdent = function(text) {\n//\n// Remove one level of line-leading tabs or spaces\n//\n\n\t// attacklab: hack around Konqueror 3.5.4 bug:\n\t// \"----------bug\".replace(/^-/g,\"\") == \"bug\"\n\n\ttext = text.replace(/^(\\t|[ ]{1,4})/gm,\"~0\"); // attacklab: g_tab_width\n\n\t// attacklab: clean up hack\n\ttext = text.replace(/~0/g,\"\")\n\n\treturn text;\n}\n\nvar _Detab = function(text) {\n// attacklab: Detab's completely rewritten for speed.\n// In perl we could fix it by anchoring the regexp with \\G.\n// In javascript we're less fortunate.\n\n\t// expand first n-1 tabs\n\ttext = text.replace(/\\t(?=\\t)/g,\"    \"); // attacklab: g_tab_width\n\n\t// replace the nth with two sentinels\n\ttext = text.replace(/\\t/g,\"~A~B\");\n\n\t// use the sentinel to anchor our regex so it doesn't explode\n\ttext = text.replace(/~B(.+?)~A/g,\n\t\tfunction(wholeMatch,m1,m2) {\n\t\t\tvar leadingText = m1;\n\t\t\tvar numSpaces = 4 - leadingText.length % 4;  // attacklab: g_tab_width\n\n\t\t\t// there *must* be a better way to do this:\n\t\t\tfor (var i=0; i<numSpaces; i++) leadingText+=\" \";\n\n\t\t\treturn leadingText;\n\t\t}\n\t);\n\n\t// clean up sentinels\n\ttext = text.replace(/~A/g,\"    \");  // attacklab: g_tab_width\n\ttext = text.replace(/~B/g,\"\");\n\n\treturn text;\n}\n\n\n//\n//  attacklab: Utility functions\n//\n\n\nvar escapeCharacters = function(text, charsToEscape, afterBackslash) {\n\t// First we have to escape the escape characters so that\n\t// we can build a character class out of them\n\tvar regexString = \"([\" + charsToEscape.replace(/([\\[\\]\\\\])/g,\"\\\\$1\") + \"])\";\n\n\tif (afterBackslash) {\n\t\tregexString = \"\\\\\\\\\" + regexString;\n\t}\n\n\tvar regex = new RegExp(regexString,\"g\");\n\ttext = text.replace(regex,escapeCharacters_callback);\n\n\treturn text;\n}\n\n\nvar escapeCharacters_callback = function(wholeMatch,m1) {\n\tvar charCodeToEscape = m1.charCodeAt(0);\n\treturn \"~E\"+charCodeToEscape+\"E\";\n}\n\n} // end of Attacklab.showdown.converter\n\n\n// Version 0.9 used the Showdown namespace instead of Attacklab.showdown\n// The old namespace is deprecated, but we'll support it for now:\nvar Showdown = Attacklab.showdown;\n\n// If anyone's interested, tell the world that this file's been loaded\nif (Attacklab.fileLoaded) {\n\tAttacklab.fileLoaded(\"showdown.js\");\n}"
  },
  {
    "path": "js/tagscomplete.js",
    "content": "/*\n FCBKcomplete 2.6\n - Jquery version required: 1.2.x, 1.3.x\n \n Changelog:\n \n - 2.00\tnew version of fcbkcomplete\n \n - 2.01 fixed bugs & added features\n \t\tfixed filter bug for preadded items\n \t\tfocus on the input after selecting tag\n \t\tthe element removed pressing backspace when the element is selected\n \t\tinput tag in the control has a border in IE7\n \t\tadded iterate over each match and apply the plugin separately\n \t\tset focus on the input after selecting tag\n \n - 2.02 fixed fist element selected bug\n \t\tfixed defaultfilter error bug\n \n - 2.5 \tremoved selected=\"selected\" attribute due ie bug\n \t\telement search algorithm changed\n \t\tbetter performance fix added\n \t\tfixed many small bugs\n \t\tonselect event added\n \t\tonremove event added\n \t\t\n - 2.6 \tie6/7 support fix added\n \t\tadded new public method addItem due request\n \t\tadded new options \"firstselected\" that you can set true/false to select first element on dropdown list\n \t\tautoexpand input element added\n \t\tremoveItem bug fixed\n \t\tand many more bug fixed\n \t\t\n */\n\n/* Coded by: emposha <admin@emposha.com> */\n/* Copyright: Emposha.com <http://www.emposha.com/> - Distributed under MIT - Keep this message! */\n/*\n * json_url         - url to fetch json object\n * cache       \t\t- use cache\n * height           - maximum number of element shown before scroll will apear\n * newel            - show typed text like a element\n * firstselected\t- automaticly select first element from dropdown\n * filter_case      - case sensitive filter\n * filter_selected  - filter selected items from list\n * complete_text    - text for complete page\n * maxshownitems\t- maximum numbers that will be shown at dropdown list (less better performance)\n * onselect\t\t\t- fire event on item select\n * onremove\t\t\t- fire event on item remove\n */\n \njQuery(\n    function ($) \n    {\n\t    $.fn.fcbkcomplete = function (opt) \n\t    {\n    \t\treturn this.each(function()\n\t\t\t{\n\t\t        function init()\n\t\t        {\n\t\t           createFCBK();       \n\t               preSet();\n\t               addInput(0); \n\t\t        }\n\t        \t\n\t\t        function createFCBK()\n\t\t        {\t    \n\t\t           element.hide();\n\t\t           element.attr(\"multiple\",\"multiple\");\n\t\t           if (element.attr(\"name\").indexOf(\"[]\") == -1)\n\t\t           {\n\t\t           \t   element.attr(\"name\",element.attr(\"name\")+\"[]\");\n\t\t           }\n\t        \t   \n\t\t           holder = $(document.createElement(\"ul\"));\n\t               holder.attr(\"class\", \"holder\");\n\t               element.after(holder);\n\t               \n\t               complete = $(document.createElement(\"div\"));\n\t               complete.addClass(\"facebook-auto\");\n\t            //   complete.append('<div class=\"default\">'+ options.complete_text +\"</div>\");\n\t               \n\t\t\t\t   if (browser_msie)\n\t               {\n\t                    complete.append('<iframe class=\"ie6fix\" scrolling=\"no\" frameborder=\"0\"></iframe>');\n\t                    browser_msie_frame = complete.children('.ie6fix');\n\t\t\t\t\t\t//$(\"input:checkbox\").parent().css(\"z-index\",\"-1\");\n\t               }\n\t\t\t\t   \n\t               feed = $(document.createElement(\"ul\"));\n\t               feed.attr(\"id\", elemid + \"_feed\");\n\t               \n\t               complete.prepend(feed);\n\t               holder.after(complete);\n\t\t\t\t   feed.css(\"width\",complete.width());\n\t\t        }\n\t        \t\n\t\t        function preSet()\n\t\t        {\t\t\t\t\t\t\t\t\t\t\n\t\t            element.children(\"option\").each( \n\t\t                function(i,option) \n\t\t                {\t\t\t\t\t\t\t\t\t                    \n\t\t\t\t\t\t\toption = $(option);\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t                    if (option.hasClass(\"selected\"))\n\t\t                    {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t                        addItem (option.text(), option.val(), true);\n\t\t\t\t\t\t\t\toption.attr(\"selected\",\"selected\");\n\t\t                    } \n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toption.removeAttr(\"selected\");\t\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcache.push({\n\t\t\t\t\t\t\t\tcaption: option.text(),\n\t\t\t\t\t\t\t\tvalue: option.val()\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tsearch_string += \"\" + (cache.length - 1) + \":\" + option.text() + \";\";                \n\t\t                }\n\t\t            );\n\t\t        }\n\t\t\t\t\n\t\t\t\t//public method to add new item\n\t\t\t\tthis.addItem = function(title, value)\n\t\t\t\t{\n\t\t\t\t\taddItem(title, value);\n\t\t\t\t}\n\t        \t\n\t\t        function addItem (title, value, preadded)\n\t\t        {\n\t                var li = document.createElement(\"li\");\n\t                var txt = document.createTextNode(title);\n\t                var aclose = document.createElement(\"a\");       \n\t                \n\t                $(li).attr({\"class\": \"bit-box\",\"rel\": value});\n\t                $(li).prepend(txt);        \n\t                $(aclose).attr({\"class\": \"closebutton\",\"href\": \"#\"});\n\t                \n\t                li.appendChild(aclose);\n\t                holder.append(li);\n\t                \n\t                $(aclose).click(\n\t                    function(){\n\t                        $(this).parent(\"li\").fadeOut(\"fast\", \n\t                            function(){\n\t\t\t\t\t\t\t\t\tremoveItem($(this));\t                                \n\t                            }\n\t                        );\n\t                        return false;\n\t                    }\n\t                );\n\t                \n\t                if (!preadded) \n\t                {\t\t\t\t\t\t\n\t                    $(\"#\"+elemid + \"_annoninput\").remove();\n\t\t\t\t\t\tvar _item;\n\t                    addInput(1);                        \n\t                    if (element.children(\"option[value=\" + value + \"]\").length)\n\t                    {   \n\t\t\t\t\t\t\t_item = element.children(\"option[value=\" + value + \"]\");            \n\t                        _item.get(0).setAttribute(\"selected\", \"selected\");\n\t\t\t\t\t\t\tif (!_item.hasClass(\"selected\")) \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t_item.addClass(\"selected\");\n\t\t\t\t\t\t\t}\n\t                    }\n\t                    else\n\t                    {\n\t                        var _item = $(document.createElement(\"option\"));\n\t                        _item.attr(\"value\", value).get(0).setAttribute(\"selected\", \"selected\");\n\t\t\t\t\t\t\t_item.attr(\"value\", value).addClass(\"selected\");\n\t                        _item.text(title);              \n\t                        element.append(_item);\n\t                    }\n\t\t\t\t\t\tif (options.onselect.length)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfunCall(options.onselect,_item)\n\t\t\t\t\t\t}\t\n\t                }\t\t\t\t\t     \n\t                holder.children(\"li.bit-box.deleted\").removeClass(\"deleted\");\n\t                feed.hide();\n\t\t\t\t\tbrowser_msie?browser_msie_frame.hide():'';\n\t            }\n\t        \t\n\t\t\t\tfunction removeItem(item)\n\t\t\t\t{\t\t\t\t\t\n\t\t\t\t\tif (options.onremove.length)\n\t\t\t\t\t{\n\t\t\t\t\t    var _item = element.children(\"option[value=\" + item.attr(\"rel\") + \"]\");\n\t\t\t\t\t\tfunCall(options.onremove,_item)\n\t\t\t\t\t}\n\t\t\t\t\telement.children(\"option[value=\" + item.attr(\"rel\") + \"]\").removeAttr(\"selected\");\n\t\t\t\t\telement.children(\"option[value=\" + item.attr(\"rel\") + \"]\").removeClass(\"selected\");\n                    item.remove();\t\t\t\t\t\n\t\t\t\t\tdeleting = 0;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t        function addInput(focusme)\n\t\t        {\n\t\t            var li = $(document.createElement(\"li\"));\n\t                var input = $(document.createElement(\"input\"));\n\t                \n\t                li.attr({\"class\": \"bit-input\",\"id\": elemid + \"_annoninput\"});        \n\t                input.attr({\"type\": \"text\",\"class\": \"maininput\",\"size\": \"1\"});        \n\t                holder.append(li.append(input));\n\t                \n\t                input.focus(\n\t                    function()\n\t                    {\n\t                        complete.fadeIn(\"fast\");\n\t                    }\n\t                );\n\t                \n\t                input.blur(\n\t                    function()\n\t                    {\n\t                        complete.fadeOut(\"fast\");\n\t                    }\n\t                );\n\t                \n\t                holder.click(\n\t                    function()\n\t                    {\n\t                        input.focus();\n\t\t\t\t            if (feed.length && input.val().length) \n\t\t\t\t            {\n\t\t\t\t\t            feed.show();\n\t\t\t\t            }\n\t\t\t\t            else \n\t\t\t\t            {\t\t\t\t\n\t\t\t\t\t            feed.hide();\n\t\t\t\t\t\t\t\tbrowser_msie?browser_msie_frame.hide():'';\n\t\t\t\t\t            complete.children(\".default\").show();\n\t\t\t\t            }\n\t                    }\n\t                );\n\t                \n\t\t\t\t\tinput.keypress(\n\t                    function(event)\n\t                    {\t\t\t\t\t\t\t\n\t                        if (event.keyCode == 13)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t    return false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//auto expand input\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tinput.attr(\"size\",input.val().length + 1);\t\t\t\t\t\t\t\n\t                    }\n\t                );\n\t\t\t\t\t\n\t\t\t\t\tinput.keydown(\n\t                    function(event)\n\t                    {\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//prevent to enter some bad chars when input is empty\n\t\t\t\t\t\t\tif(event.keyCode == 191)\n\t\t\t\t\t\t\t{\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\t                       \t\t\t\t\t\n\t                    }\n\t                );\n\t\t\t\t\t\n\t                input.keyup(\n\t                    function(event)\n\t                    {\n\t\t\t\t\t\t\tvar etext = xssPrevent(input.val());\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (event.keyCode == 8 && etext.length == 0)\n\t\t\t\t\t\t\t{\t\t\t\n\t\t\t\t\t\t\t\tfeed.hide();\n\t\t\t\t\t\t\t\tbrowser_msie?browser_msie_frame.hide():'';\t\t\t\t\n\t\t\t\t\t\t\t\tif (holder.children(\"li.bit-box.deleted\").length == 0) \n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tholder.children(\"li.bit-box:last\").addClass(\"deleted\");\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (deleting)\n\t\t\t\t\t\t\t\t    {\n\t\t\t\t\t\t\t\t        return;\n\t\t\t\t\t\t\t\t    }\n\t\t\t\t\t\t\t\t\tdeleting = 1;\n\t\t\t\t\t\t\t\t\tholder.children(\"li.bit-box.deleted\").fadeOut(\"fast\", function()\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tremoveItem($(this));\n\t\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t                        if (event.keyCode != 40 && event.keyCode != 38 && etext.length != 0) \n\t                        {\n\t                            counter = 0;\t\t\t\t\t\t\t\t\t                            \n\t\t\t\t\t\t\t\t\n\t                            if (options.json_url) \n\t                            {\n\t                                if (options.cache && json_cache) \n\t                                {\n\t                                    addMembers(etext);\n\t                                    bindEvents();\n\t                                }\n\t                                else \n\t                                {\n\t                                    $.getJSON(options.json_url + \"?tag=\" + etext, null, \n\t                                        function(data)\n\t                                        {\n\t                                            addMembers(etext, data);\n\t                                            json_cache = true;\n\t                                            bindEvents();\n\t                                        }\n\t                                    );\n\t                                }\n\t                            }\n\t                            else \n\t                            {\n\t\t\t\t\t\t\t\t\taddMembers(etext);\n\t                                bindEvents();\n\t                            }\n\t                            complete.children(\".default\").hide();\n\t\t\t\t\t\t\t\tfeed.show();\n\t                        }\n\t                    }\n\t                );\n\t\t\t\t\tif (focusme)\n\t\t\t\t\t{\n\t\t\t\t\t\tsetTimeout(function(){\n\t\t\t\t\t\t\tinput.focus();\n\t\t\t\t\t\t\tcomplete.children(\".default\").show();\n\t\t\t\t\t\t},1);\n\t\t\t\t\t}\t\t\t\t\t\t    \n\t\t        }\n\t        \t\n\t\t\t\tfunction addMembers(etext, data)\n\t\t\t\t{\n\t\t\t\t\tfeed.html('');\n\t\t\t\t\t\n\t\t\t\t\tif (!options.cache) \n\t\t\t\t\t{\n\t\t\t\t\t\tcache = new Array();\n\t\t\t\t\t\tsearch_string = \"\";\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\taddTextItem(etext);\n\t\t\t\t\t\n\t\t\t\t\tif (data != null && data.length)\n\t\t\t\t\t{\n\t\t\t\t\t\t$.each(data, \n\t                    \tfunction(i, val)\n\t                    \t{\n\t\t\t\t\t\t\t\tcache.push (\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcaption: val.caption,\n\t\t\t\t\t\t\t\t\t\tvalue: val.value\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tsearch_string += \"\" + (cache.length - 1) + \":\" + val.caption + \";\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tvar maximum = options.maxshownitems<cache.length?options.maxshownitems:cache.length;\n\t\t\t\t\tvar filter = \"i\";\n\t\t\t\t\tif (options.filter_case)\n\t\t\t\t\t{\n\t\t\t\t\t\tfilter = \"\"; \n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tvar myregexp, match;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmyregexp = eval('/(?:^|;)\\\\s*(\\\\d+)\\\\s*:[^;]*?' + etext + '[^;]*/g' + filter);\n\t\t\t\t\t\tmatch = myregexp.exec(search_string);\n\t\t\t\t\t} catch(ex){};\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tvar content = '';\n\t\t\t\t\twhile (match != null && maximum > 0) \n\t\t\t\t\t{\n\t\t\t\t\t\tvar id = match[1];\t\t\t\t\t\t\n\t\t\t\t\t\tvar object = cache[id];\t\n\t\t\t\t\t\tif (options.filter_selected && element.children(\"option[value=\" + object.value + \"]\").hasClass(\"selected\")) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//nothing here...\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontent += '<li rel=\"' + object.value + '\">' + itemIllumination(object.caption, etext) + '</li>';\n\t\t\t\t\t\t\tcounter++;\n\t\t\t\t\t\t\tmaximum--;\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t\tmatch = myregexp.exec(search_string);\n\t\t\t\t\t}\n\t\t\t\t\tfeed.append(content);\n\t\t\t\t\t\n\t\t\t\t\tif (options.firstselected)\n\t\t\t\t\t{\n\t\t\t\t\t    focuson = feed.children(\"li:visible:first\");\n\t\t\t\t\t    focuson.addClass(\"auto-focus\");\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (counter > options.height) \n\t                {\n\t                    feed.css({\"height\": (options.height * 24) + \"px\",\"overflow\": \"auto\"});\n\t\t\t\t\t\tif (browser_msie)\n\t                    {\n\t                        browser_msie_frame.css({\"height\": (options.height * 24) + \"px\", \"width\": feed.width() + \"px\"}).show();\n\t                    }\n\t                }\n\t                else \n\t                {\n\t                    feed.css(\"height\", \"auto\");\n\t\t\t\t\t\tif (browser_msie)\n\t                    {\n\t                        browser_msie_frame.css({\"height\": feed.height() + \"px\", \"width\": feed.width() + \"px\"}).show();\n\t                    }\n\t                }\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfunction itemIllumination(text, etext)\n\t\t\t\t{\n\t\t\t\t\tif (options.filter_case) \n                    {     \n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\teval(\"var text = text.replace(/(.*)(\" + etext + \")(.*)/gi,'$1<em>$2</em>$3');\");\n\t\t\t\t\t\t} catch(ex){};\n                    }\n                    else \n                    {    \n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\teval(\"var text = text.replace(/(.*)(\" + etext.toLowerCase() + \")(.*)/gi,'$1<em>$2</em>$3');\");\n\t\t\t\t\t\t}catch(ex){};\n                    }\t\t\t\t\t\n\t\t\t\t\treturn text;\n\t\t\t\t}\n\t        \t\n\t\t        function bindFeedEvent() \n\t\t        {\t\t\n\t\t\t        feed.children(\"li\").mouseover(\n\t\t\t            function()\n\t\t\t            {\n\t\t\t\t            feed.children(\"li\").removeClass(\"auto-focus\");\n\t                        $(this).addClass(\"auto-focus\");\n\t                        focuson = $(this);\n\t                    }\n\t                );\n\t        \t\t\n\t\t\t        feed.children(\"li\").mouseout(\n\t\t\t            function()\n\t\t\t            {\n\t                        $(this).removeClass(\"auto-focus\");\n\t                        focuson = null;\n\t                    }\n\t                );\n\t\t        }\n\t        \t\n\t\t        function removeFeedEvent() \n\t\t        {       \t\n\t\t\t        feed.children(\"li\").unbind(\"mouseover\");\t\n\t\t\t        feed.children(\"li\").unbind(\"mouseout\");\n\t\t\t        feed.mousemove(\n\t\t\t            function () \n\t\t\t            {\n\t\t\t\t            bindFeedEvent();\n\t\t\t\t            feed.unbind(\"mousemove\");\n\t\t\t            }\n\t\t\t        );\t\n\t\t        }\n\t        \t\n\t\t        function bindEvents()\n\t\t        {\n\t\t            var maininput = $(\"#\"+elemid + \"_annoninput\").children(\".maininput\");\t                 \t\n\t       \t        bindFeedEvent();      \t\n\t                feed.children(\"li\").unbind(\"mousedown\");        \n\t                feed.children(\"li\").mousedown( \n\t                    function()\n\t                    {\n\t                        var option = $(this);\n\t                        addItem(option.text(),option.attr(\"rel\"));\n\t                        feed.hide();\n\t\t\t\t\t\t\tbrowser_msie?browser_msie_frame.hide():'';\n\t                        complete.hide();\n\t                    }\n\t                );\n\t                \n\t                maininput.unbind(\"keydown\");\n\t                maininput.keydown(\n\t                    function(event)\n\t                    {\t\t\n\t\t\t\t\t\t\tif(event.keyCode == 191)\n\t\t\t\t\t\t\t{\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (event.keyCode != 8) \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tholder.children(\"li.bit-box.deleted\").removeClass(\"deleted\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t                        if (event.keyCode == 13 && checkFocusOn()) \n\t                        {\n\t                            var option = focuson;\n\t                            addItem(option.text(), option.attr(\"rel\"));\n\t                            complete.hide();\n\t                            event.preventDefault();\n\t\t\t\t\t\t\t\tfocuson = null;\n\t\t\t\t\t\t\t\treturn false;\n\t                        }\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (event.keyCode == 13 && !checkFocusOn()) \n\t                        {\n\t\t\t\t\t\t\t\tif (options.newel) \n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvar value = xssPrevent($(this).val());\n\t\t\t\t\t\t\t\t\taddItem(value, value);\n\t\t\t\t\t\t\t\t\tcomplete.hide();\n\t\t\t\t\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\t\t\t\t\tfocuson = null;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn false;\t\t\t\t\t\t\t\n\t                        }\n\t                        \n\t                        if (event.keyCode == 40) \n\t                        {               \n\t\t\t\t\t            removeFeedEvent();\n\t                            if (focuson == null || focuson.length == 0) \n\t                            {\n\t                                focuson = feed.children(\"li:visible:first\");\n\t\t\t\t\t\t            feed.get(0).scrollTop = 0;\n\t                            }\n\t                            else \n\t                            {\n\t                                focuson.removeClass(\"auto-focus\");\n\t                                focuson = focuson.nextAll(\"li:visible:first\");\n\t\t\t\t\t\t            var prev = parseInt(focuson.prevAll(\"li:visible\").length,10);\n\t\t\t\t\t\t            var next = parseInt(focuson.nextAll(\"li:visible\").length,10);\n\t\t\t\t\t\t            if ((prev > Math.round(options.height /2) || next <= Math.round(options.height /2)) && typeof(focuson.get(0)) != \"undefined\") \n\t\t\t\t\t\t            {\n\t\t\t\t\t\t\t            feed.get(0).scrollTop = parseInt(focuson.get(0).scrollHeight,10) * (prev - Math.round(options.height /2));\n\t\t\t\t\t\t            }\n\t                            }\n\t\t\t\t\t            feed.children(\"li\").removeClass(\"auto-focus\");\n\t                            focuson.addClass(\"auto-focus\");\n\t                        }\n\t                        if (event.keyCode == 38) \n\t                        {\n\t\t\t\t\t            removeFeedEvent();\n\t                            if (focuson == null || focuson.length == 0) \n\t                            {\n\t                                focuson = feed.children(\"li:visible:last\");\n\t\t\t\t\t\t            feed.get(0).scrollTop = parseInt(focuson.get(0).scrollHeight,10) * (parseInt(feed.children(\"li:visible\").length,10) - Math.round(options.height /2));\n\t                            }\n\t                            else \n\t                            {\n\t                                focuson.removeClass(\"auto-focus\");\n\t                                focuson = focuson.prevAll(\"li:visible:first\");\n\t\t\t\t\t\t            var prev = parseInt(focuson.prevAll(\"li:visible\").length,10);\n\t\t\t\t\t\t            var next = parseInt(focuson.nextAll(\"li:visible\").length,10);\n\t\t\t\t\t\t            if ((next > Math.round(options.height /2) || prev <= Math.round(options.height /2)) && typeof(focuson.get(0)) != \"undefined\") \n\t\t\t\t\t\t            {\n\t\t\t\t\t\t\t            feed.get(0).scrollTop = parseInt(focuson.get(0).scrollHeight,10) * (prev - Math.round(options.height /2));\n\t\t\t\t\t\t            }\n\t                            }\n\t\t\t\t\t            feed.children(\"li\").removeClass(\"auto-focus\");\n\t                            focuson.addClass(\"auto-focus\");\n\t                        }\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t                    }\n\t                );\n\t\t        }\n\t        \t\n\t\t        function addTextItem(value)\n\t\t        {\t\t\t\t\t\n\t                if (options.newel) \n\t                {\n\t                    feed.children(\"li[fckb=1]\").remove();\n\t                    if (value.length == 0)\n\t                    {\n\t                    \treturn;\n\t                    }\n\t                    var li = $(document.createElement(\"li\"));\n\t                    li.attr({\"rel\": value,\"fckb\": \"1\"}).html(value);\n\t                    feed.prepend(li);\n\t\t\t\t        counter++;\n\t                } else \n\t\t\t\t\t{\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t            }\n\t        \t\n\t\t\t\tfunction funCall(func,item)\n\t\t\t\t{\t\n\t\t\t\t\tvar _object = \"\";\t\t\t\n\t\t\t\t\tfor(i=0;i < item.get(0).attributes.length;i++)\n\t\t\t\t\t{\t\n\t\t\t\t\t\tif (item.get(0).attributes[i].nodeValue != null) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t_object += \"\\\"_\" + item.get(0).attributes[i].nodeName + \"\\\": \\\"\" + item.get(0).attributes[i].nodeValue + \"\\\",\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t_object = \"{\"+ _object + \" notinuse: 0}\";\n\t\t\t\t\ttry {\n\t\t\t\t\t\teval(func + \"(\" + _object + \")\");\n\t\t\t\t\t}catch(ex){};\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfunction checkFocusOn()\n\t\t        {\n\t\t            if (focuson == null)\n\t\t            {\n\t\t                return false;\n\t\t            }\n\t\t            if (focuson.length == 0)\n\t\t            {\n\t\t                return false;\n\t\t            }\n\t\t            return true;\n\t\t        }\n\t\t\t\t\n\t\t\t\tfunction xssPrevent(string)\n                {\t\t\t\t\t\n                    string = string.replace(/[\\\"\\'][\\s]*javascript:(.*)[\\\"\\']/g, \"\\\"\\\"\");\n                    string = string.replace(/script(.*)/g, \"script\");    \n                    string = string.replace(/eval\\((.*)\\)/g, \"eval\");\n                    string = string.replace('/([\\x00-\\x08,\\x0b-\\x0c,\\x0e-\\x19])/', '');\n                    return string;\n                }\n\t\t\t\t\n\t\t        var options = $.extend({\n\t\t\t\t        json_url: null,\n\t\t\t\t        cache: false,\n\t\t\t\t        height: \"10\",\n\t\t\t\t        newel: true,\n\t\t\t\t\t\tfirstselected: false,\n\t\t\t\t        filter_case: false,\n\t\t\t\t        filter_hide: false,\n\t\t\t\t        complete_text: \"Type a tag\",\n\t\t\t\t\t\tmaxshownitems:  5,\n\t\t\t\t\t\tonselect: \"\",\n\t\t\t\t\t\tonremove: \"\"\n\t\t\t        }, opt);\n\t        \t\n\t\t        //system variables\n\t\t        var holder     \t\t= null;\n\t\t        var feed       \t\t= null;\n\t\t        var complete   \t\t= null;\n\t\t        var counter    \t\t= 0;\n\t\t        var cache      \t\t= new Array();\n\t\t\t\tvar json_cache\t\t= false;\n\t\t\t\tvar search_string\t= \"\";\n\t\t        var focuson    \t\t= null;\n\t        \tvar deleting\t\t= 0;\n\t\t\t\tvar browser_msie\t= \"\\v\"==\"v\";\n\t\t\t\tvar browser_msie_frame;\n\t\t\t\t\n\t\t        var element = $(this);\n\t\t        var elemid = element.attr(\"id\");\n\t\t        init();\n\n\t\t        return this;\n\t\t\t});\n\t    };\n    }\n);"
  },
  {
    "path": "js/wmd.js",
    "content": "var Attacklab = Attacklab || {};\n\nAttacklab.wmdBase = function(){\n\n\t// A few handy aliases for readability.\n\tvar wmd  = top.Attacklab;\n\tvar doc  = top.document;\n\tvar re   = top.RegExp;\n\tvar nav  = top.navigator;\n\t\n\t// Some namespaces.\n\twmd.Util = {};\n\twmd.Position = {};\n\twmd.Command = {};\n\twmd.Global = {};\n\t\n\tvar util = wmd.Util;\n\tvar position = wmd.Position;\n\tvar command = wmd.Command;\n\tvar global = wmd.Global;\n\t\n\t\n\t// Used to work around some browser bugs where we can't use feature testing.\n\tglobal.isIE \t\t= /msie/.test(nav.userAgent.toLowerCase());\n\tglobal.isIE_5or6 \t= /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase());\n\tglobal.isIE_7plus \t= global.isIE && !global.isIE_5or6;\n\tglobal.isOpera \t\t= /opera/.test(nav.userAgent.toLowerCase());\n\tglobal.isKonqueror \t= /konqueror/.test(nav.userAgent.toLowerCase());\n\t\n\t\n\t// -------------------------------------------------------------------\n\t//  YOUR CHANGES GO HERE\n\t//\n\t// I've tried to localize the things you are likely to change to \n\t// this area.\n\t// -------------------------------------------------------------------\n\t\n\t// The text that appears on the upper part of the dialog box when\n\t// entering links.\n\tvar imageDialogText = \"<p style='margin-top: 0px'><b>Enter the image URL.</b></p><p>You can also add a title, which will be displayed as a tool tip.</p><p>Example:<br />http://www.inscripts.com/images/cloud.jpg   \\\"Optional title\\\"</p>\";\n\tvar linkDialogText = \"<p style='margin-top: 0px'><b>Enter the web address.</b></p><p>You can also add a title, which will be displayed as a tool tip.</p><p>Example:<br />http://www.inscripts.com/   \\\"Optional title\\\"</p>\";\n\t\n\t// The default text that appears in the dialog input box when entering\n\t// links.\n\tvar imageDefaultText = \"http://\";\n\tvar linkDefaultText = \"http://\";\n\t\n\t// The location of your button images relative to the base directory.\n\tvar imageDirectory = \"img/\";\n\t\n\t// Some intervals in ms.  These can be adjusted to reduce the control's load.\n\tvar previewPollInterval = 500;\n\tvar pastePollInterval = 100;\n\t\n\t// The link and title for the help button\n\tvar helpLink = \"http://en.wikipedia.org/wiki/Markdown\";\n\tvar helpHoverTitle = \"Help\";\n\tvar helpTarget = \"_blank\";\n\t\n\t// -------------------------------------------------------------------\n\t//  END OF YOUR CHANGES\n\t// -------------------------------------------------------------------\n\t\n\t// A collection of the important regions on the page.\n\t// Cached so we don't have to keep traversing the DOM.\n\twmd.PanelCollection = function(){\n\t\tthis.buttonBar = doc.getElementById(\"wmd-button-bar\");\n\t\tthis.preview = doc.getElementById(\"wmd-preview\");\n\t\tthis.output = doc.getElementById(\"wmd-output\");\n\t\tthis.input = doc.getElementById(\"wmd-input\");\n\t};\n\t\n\t// This PanelCollection object can't be filled until after the page\n\t// has loaded.\n\twmd.panels = undefined;\n\t\n\t// Internet explorer has problems with CSS sprite buttons that use HTML\n\t// lists.  When you click on the background image \"button\", IE will \n\t// select the non-existent link text and discard the selection in the\n\t// textarea.  The solution to this is to cache the textarea selection\n\t// on the button's mousedown event and set a flag.  In the part of the\n\t// code where we need to grab the selection, we check for the flag\n\t// and, if it's set, use the cached area instead of querying the\n\t// textarea.\n\t//\n\t// This ONLY affects Internet Explorer (tested on versions 6, 7\n\t// and 8) and ONLY on button clicks.  Keyboard shortcuts work\n\t// normally since the focus never leaves the textarea.\n\twmd.ieCachedRange = null;\t\t// cached textarea selection\n\twmd.ieRetardedClick = false;\t// flag\n\t\n\t// Returns true if the DOM element is visible, false if it's hidden.\n\t// Checks if display is anything other than none.\n\tutil.isVisible = function (elem) {\n\t\n\t    if (window.getComputedStyle) {\n\t        // Most browsers\n\t\t\treturn window.getComputedStyle(elem, null).getPropertyValue(\"display\") !== \"none\";\n\t\t}\n\t\telse if (elem.currentStyle) {\n\t\t    // IE\n\t\t\treturn elem.currentStyle[\"display\"] !== \"none\";\n\t\t}\n\t};\n\t\n\t\n\t// Adds a listener callback to a DOM element which is fired on a specified\n\t// event.\n\tutil.addEvent = function(elem, event, listener){\n\t\tif (elem.attachEvent) {\n\t\t\t// IE only.  The \"on\" is mandatory.\n\t\t\telem.attachEvent(\"on\" + event, listener);\n\t\t}\n\t\telse {\n\t\t\t// Other browsers.\n\t\t\telem.addEventListener(event, listener, false);\n\t\t}\n\t};\n\n\t\n\t// Removes a listener callback from a DOM element which is fired on a specified\n\t// event.\n\tutil.removeEvent = function(elem, event, listener){\n\t\tif (elem.detachEvent) {\n\t\t\t// IE only.  The \"on\" is mandatory.\n\t\t\telem.detachEvent(\"on\" + event, listener);\n\t\t}\n\t\telse {\n\t\t\t// Other browsers.\n\t\t\telem.removeEventListener(event, listener, false);\n\t\t}\n\t};\n\n\t// Converts \\r\\n and \\r to \\n.\n\tutil.fixEolChars = function(text){\n\t\ttext = text.replace(/\\r\\n/g, \"\\n\");\n\t\ttext = text.replace(/\\r/g, \"\\n\");\n\t\treturn text;\n\t};\n\n\t// Extends a regular expression.  Returns a new RegExp\n\t// using pre + regex + post as the expression.\n\t// Used in a few functions where we have a base\n\t// expression and we want to pre- or append some\n\t// conditions to it (e.g. adding \"$\" to the end).\n\t// The flags are unchanged.\n\t//\n\t// regex is a RegExp, pre and post are strings.\n\tutil.extendRegExp = function(regex, pre, post){\n\t\t\n\t\tif (pre === null || pre === undefined)\n\t\t{\n\t\t\tpre = \"\";\n\t\t}\n\t\tif(post === null || post === undefined)\n\t\t{\n\t\t\tpost = \"\";\n\t\t}\n\t\t\n\t\tvar pattern = regex.toString();\n\t\tvar flags = \"\";\n\t\t\n\t\t// Replace the flags with empty space and store them.\n\t\t// Technically, this can match incorrect flags like \"gmm\".\n\t\tvar result = pattern.match(/\\/([gim]*)$/);\n\t\tif (result === null) {\n\t\t\tflags = result[0];\n\t\t}\n\t\telse {\n\t\t\tflags = \"\";\n\t\t}\n\t\t\n\t\t// Remove the flags and slash delimiters from the regular expression.\n\t\tpattern = pattern.replace(/(^\\/|\\/[gim]*$)/g, \"\");\n\t\tpattern = pre + pattern + post;\n\t\t\n\t\treturn new RegExp(pattern, flags);\n\t}\n\n\t\n\t// Sets the image for a button passed to the WMD editor.\n\t// Returns a new element with the image attached.\n\t// Adds several style properties to the image.\n\tutil.createImage = function(img){\n\t\t\n\t\tvar imgPath = imageDirectory + img;\n\t\t\n\t\tvar elem = doc.createElement(\"img\");\n\t\telem.className = \"wmd-button\";\n\t\telem.src = imgPath;\n\n\t\treturn elem;\n\t};\n\t\n\n\t// This simulates a modal dialog box and asks for the URL when you\n\t// click the hyperlink or image buttons.\n\t//\n\t// text: The html for the input box.\n\t// defaultInputText: The default value that appears in the input box.\n\t// makeLinkMarkdown: The function which is executed when the prompt is dismissed, either via OK or Cancel\n\tutil.prompt = function(text, defaultInputText, makeLinkMarkdown){\n\t\n\t\t// These variables need to be declared at this level since they are used\n\t\t// in multiple functions.\n\t\tvar dialog;\t\t\t// The dialog box.\n\t\tvar background;\t\t// The background beind the dialog box.\n\t\tvar input;\t\t\t// The text box where you enter the hyperlink.\n\t\t\n\n\t\tif (defaultInputText === undefined) {\n\t\t\tdefaultInputText = \"\";\n\t\t}\n\t\t\n\t\t// Used as a keydown event handler. Esc dismisses the prompt.\n\t\t// Key code 27 is ESC.\n\t\tvar checkEscape = function(key){\n\t\t\tvar code = (key.charCode || key.keyCode);\n\t\t\tif (code === 27) {\n\t\t\t\tclose(true);\n\t\t\t}\n\t\t};\n\t\t\n\t\t// Dismisses the hyperlink input box.\n\t\t// isCancel is true if we don't care about the input text.\n\t\t// isCancel is false if we are going to keep the text.\n\t\tvar close = function(isCancel){\n\t\t\tutil.removeEvent(doc.body, \"keydown\", checkEscape);\n\t\t\tvar text = input.value;\n\n\t\t\tif (isCancel){\n\t\t\t\ttext = null;\n\t\t\t}\n\t\t\telse{\n\t\t\t\t// Fixes common pasting errors.\n\t\t\t\ttext = text.replace('http://http://', 'http://');\n\t\t\t\ttext = text.replace('http://https://', 'https://');\n\t\t\t\ttext = text.replace('http://ftp://', 'ftp://');\n\t\t\t\t\n\t\t\t\tif (text.indexOf('http://') === -1 && text.indexOf('ftp://') === -1 && text.indexOf('https://') === -1) {\n\t\t\t\t\ttext = 'http://' + text;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tdialog.parentNode.removeChild(dialog);\n\t\t\tbackground.parentNode.removeChild(background);\n\t\t\tmakeLinkMarkdown(text);\n\t\t\treturn false;\n\t\t};\n\t\t\n\t\t// Creates the background behind the hyperlink text entry box.\n\t\t// Most of this has been moved to CSS but the div creation and\n\t\t// browser-specific hacks remain here.\n\t\tvar createBackground = function(){\n\t\t\n\t\t\tbackground = doc.createElement(\"div\");\n\t\t\tbackground.className = \"wmd-prompt-background\";\n\t\t\tstyle = background.style;\n\t\t\tstyle.position = \"absolute\";\n\t\t\tstyle.top = \"0\";\n\t\t\t\n\t\t\tstyle.zIndex = \"1000\";\n\t\t\t\n\t\t\t// Some versions of Konqueror don't support transparent colors\n\t\t\t// so we make the whole window transparent.\n\t\t\t//\n\t\t\t// Is this necessary on modern konqueror browsers?\n\t\t\tif (global.isKonqueror){\n\t\t\t\tstyle.backgroundColor = \"transparent\";\n\t\t\t}\n\t\t\telse if (global.isIE){\n\t\t\t\tstyle.filter = \"alpha(opacity=50)\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstyle.opacity = \"0.5\";\n\t\t\t}\n\t\t\t\n\t\t\tvar pageSize = position.getPageSize();\n\t\t\tstyle.height = pageSize[1] + \"px\";\n\t\t\t\n\t\t\tif(global.isIE){\n\t\t\t\tstyle.left = doc.documentElement.scrollLeft;\n\t\t\t\tstyle.width = doc.documentElement.clientWidth;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstyle.left = \"0\";\n\t\t\t\tstyle.width = \"100%\";\n\t\t\t}\n\t\t\t\n\t\t\tdoc.body.appendChild(background);\n\t\t};\n\t\t\n\t\t// Create the text input box form/window.\n\t\tvar createDialog = function(){\n\t\t\n\t\t\t// The main dialog box.\n\t\t\tdialog = doc.createElement(\"div\");\n\t\t\tdialog.className = \"wmd-prompt-dialog\";\n\t\t\tdialog.style.padding = \"10px;\";\n\t\t\tdialog.style.position = \"fixed\";\n\t\t\tdialog.style.width = \"400px\";\n\t\t\tdialog.style.zIndex = \"1001\";\n\t\t\t\n\t\t\t// The dialog text.\n\t\t\tvar question = doc.createElement(\"div\");\n\t\t\tquestion.innerHTML = text;\n\t\t\tquestion.style.padding = \"5px\";\n\t\t\tdialog.appendChild(question);\n\t\t\t\n\t\t\t// The web form container for the text box and buttons.\n\t\t\tvar form = doc.createElement(\"form\");\n\t\t\tform.onsubmit = function(){ return close(false); };\n\t\t\tstyle = form.style;\n\t\t\tstyle.padding = \"0\";\n\t\t\tstyle.margin = \"0\";\n\t\t\tstyle.cssFloat = \"left\";\n\t\t\tstyle.width = \"100%\";\n\t\t\tstyle.textAlign = \"center\";\n\t\t\tstyle.position = \"relative\";\n\t\t\tdialog.appendChild(form);\n\t\t\t\n\t\t\t// The input text box\n\t\t\tinput = doc.createElement(\"input\");\n\t\t\tinput.type = \"text\";\n\t\t\tinput.value = defaultInputText;\n\t\t\tstyle = input.style;\n\t\t\tstyle.display = \"block\";\n\t\t\tstyle.width = \"80%\";\n\t\t\tstyle.marginLeft = style.marginRight = \"auto\";\n\t\t\tform.appendChild(input);\n\t\t\t\n\t\t\t// The ok button\n\t\t\tvar okButton = doc.createElement(\"input\");\n\t\t\tokButton.type = \"button\";\n\t\t\tokButton.onclick = function(){ return close(false); };\n\t\t\tokButton.value = \"OK\";\n\t\t\tstyle = okButton.style;\n\t\t\tstyle.margin = \"10px\";\n\t\t\tstyle.display = \"inline\";\n\t\t\tstyle.width = \"7em\";\n\n\t\t\t\n\t\t\t// The cancel button\n\t\t\tvar cancelButton = doc.createElement(\"input\");\n\t\t\tcancelButton.type = \"button\";\n\t\t\tcancelButton.onclick = function(){ return close(true); };\n\t\t\tcancelButton.value = \"Cancel\";\n\t\t\tstyle = cancelButton.style;\n\t\t\tstyle.margin = \"10px\";\n\t\t\tstyle.display = \"inline\";\n\t\t\tstyle.width = \"7em\";\n\n\t\t\t// The order of these buttons is different on macs.\n\t\t\tif (/mac/.test(nav.platform.toLowerCase())) {\n\t\t\t\tform.appendChild(cancelButton);\n\t\t\t\tform.appendChild(okButton);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tform.appendChild(okButton);\n\t\t\t\tform.appendChild(cancelButton);\n\t\t\t}\n\n\t\t\tutil.addEvent(doc.body, \"keydown\", checkEscape);\n\t\t\tdialog.style.top = \"50%\";\n\t\t\tdialog.style.left = \"50%\";\n\t\t\tdialog.style.display = \"block\";\n\t\t\tif(global.isIE_5or6){\n\t\t\t\tdialog.style.position = \"absolute\";\n\t\t\t\tdialog.style.top = doc.documentElement.scrollTop + 200 + \"px\";\n\t\t\t\tdialog.style.left = \"50%\";\n\t\t\t}\n\t\t\tdoc.body.appendChild(dialog);\n\t\t\t\n\t\t\t// This has to be done AFTER adding the dialog to the form if you\n\t\t\t// want it to be centered.\n\t\t\tdialog.style.marginTop = -(position.getHeight(dialog) / 2) + \"px\";\n\t\t\tdialog.style.marginLeft = -(position.getWidth(dialog) / 2) + \"px\";\n\t\t\t\n\t\t};\n\t\t\n\t\tcreateBackground();\n\t\t\n\t\t// Why is this in a zero-length timeout?\n\t\t// Is it working around a browser bug?\n\t\ttop.setTimeout(function(){\n\t\t\n\t\t\tcreateDialog();\n\n\t\t\tvar defTextLen = defaultInputText.length;\n\t\t\tif (input.selectionStart !== undefined) {\n\t\t\t\tinput.selectionStart = 0;\n\t\t\t\tinput.selectionEnd = defTextLen;\n\t\t\t}\n\t\t\telse if (input.createTextRange) {\n\t\t\t\tvar range = input.createTextRange();\n\t\t\t\trange.collapse(false);\n\t\t\t\trange.moveStart(\"character\", -defTextLen);\n\t\t\t\trange.moveEnd(\"character\", defTextLen);\n\t\t\t\trange.select();\n\t\t\t}\n\t\t\t\n\t\t\tinput.focus();\n\t\t}, 0);\n\t};\n\t\n\t\n\t// UNFINISHED\n\t// The assignment in the while loop makes jslint cranky.\n\t// I'll change it to a better loop later.\n\tposition.getTop = function(elem, isInner){\n\t\tvar result = elem.offsetTop;\n\t\tif (!isInner) {\n\t\t\twhile (elem = elem.offsetParent) {\n\t\t\t\tresult += elem.offsetTop;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t};\n\t\n\tposition.getHeight = function (elem) {\n\t\treturn elem.offsetHeight || elem.scrollHeight;\n\t};\n\n\tposition.getWidth = function (elem) {\n\t\treturn elem.offsetWidth || elem.scrollWidth;\n\t};\n\n\tposition.getPageSize = function(){\n\t\t\n\t\tvar scrollWidth, scrollHeight;\n\t\tvar innerWidth, innerHeight;\n\t\t\n\t\t// It's not very clear which blocks work with which browsers.\n\t\tif(self.innerHeight && self.scrollMaxY){\n\t\t\tscrollWidth = doc.body.scrollWidth;\n\t\t\tscrollHeight = self.innerHeight + self.scrollMaxY;\n\t\t}\n\t\telse if(doc.body.scrollHeight > doc.body.offsetHeight){\n\t\t\tscrollWidth = doc.body.scrollWidth;\n\t\t\tscrollHeight = doc.body.scrollHeight;\n\t\t}\n\t\telse{\n\t\t\tscrollWidth = doc.body.offsetWidth;\n\t\t\tscrollHeight = doc.body.offsetHeight;\n\t\t}\n\t\t\n\t\tif(self.innerHeight){\n\t\t\t// Non-IE browser\n\t\t\tinnerWidth = self.innerWidth;\n\t\t\tinnerHeight = self.innerHeight;\n\t\t}\n\t\telse if(doc.documentElement && doc.documentElement.clientHeight){\n\t\t\t// Some versions of IE (IE 6 w/ a DOCTYPE declaration)\n\t\t\tinnerWidth = doc.documentElement.clientWidth;\n\t\t\tinnerHeight = doc.documentElement.clientHeight;\n\t\t}\n\t\telse if(doc.body){\n\t\t\t// Other versions of IE\n\t\t\tinnerWidth = doc.body.clientWidth;\n\t\t\tinnerHeight = doc.body.clientHeight;\n\t\t}\n\t\t\n        var maxWidth = Math.max(scrollWidth, innerWidth);\n        var maxHeight = Math.max(scrollHeight, innerHeight);\n        return [maxWidth, maxHeight, innerWidth, innerHeight];\n\t};\n\t\n\t// Watches the input textarea, polling at an interval and runs\n\t// a callback function if anything has changed.\n\twmd.inputPoller = function(callback, interval){\n\t\n\t\tvar pollerObj = this;\n\t\tvar inputArea = wmd.panels.input;\n\t\t\n\t\t// Stored start, end and text.  Used to see if there are changes to the input.\n\t\tvar lastStart;\n\t\tvar lastEnd;\n\t\tvar markdown;\n\t\t\n\t\tvar killHandle; // Used to cancel monitoring on destruction.\n\t\t// Checks to see if anything has changed in the textarea.\n\t\t// If so, it runs the callback.\n\t\tthis.tick = function(){\n\t\t\n\t\t\tif (!util.isVisible(inputArea)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// Update the selection start and end, text.\n\t\t\tif (inputArea.selectionStart || inputArea.selectionStart === 0) {\n\t\t\t\tvar start = inputArea.selectionStart;\n\t\t\t\tvar end = inputArea.selectionEnd;\n\t\t\t\tif (start != lastStart || end != lastEnd) {\n\t\t\t\t\tlastStart = start;\n\t\t\t\t\tlastEnd = end;\n\t\t\t\t\t\n\t\t\t\t\tif (markdown != inputArea.value) {\n\t\t\t\t\t\tmarkdown = inputArea.value;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t\t\n\t\t\n\t\tvar doTickCallback = function(){\n\t\t\n\t\t\tif (!util.isVisible(inputArea)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// If anything has changed, call the function.\n\t\t\tif (pollerObj.tick()) {\n\t\t\t\tcallback();\n\t\t\t}\n\t\t};\n\t\t\n\t\t// Set how often we poll the textarea for changes.\n\t\tvar assignInterval = function(){\n\t\t\t// previewPollInterval is set at the top of the namespace.\n\t\t\tkillHandle = top.setInterval(doTickCallback, interval);\n\t\t};\n\t\t\n\t\tthis.destroy = function(){\n\t\t\ttop.clearInterval(killHandle);\n\t\t};\n\t\t\n\t\tassignInterval();\n\t};\n\t\n\t// Handles pushing and popping TextareaStates for undo/redo commands.\n\t// I should rename the stack variables to list.\n\twmd.undoManager = function(callback){\n\t\n\t\tvar undoObj = this;\n\t\tvar undoStack = []; // A stack of undo states\n\t\tvar stackPtr = 0; // The index of the current state\n\t\tvar mode = \"none\";\n\t\tvar lastState; // The last state\n\t\tvar poller;\n\t\tvar timer; // The setTimeout handle for cancelling the timer\n\t\tvar inputStateObj;\n\t\t\n\t\t// Set the mode for later logic steps.\n\t\tvar setMode = function(newMode, noSave){\n\t\t\n\t\t\tif (mode != newMode) {\n\t\t\t\tmode = newMode;\n\t\t\t\tif (!noSave) {\n\t\t\t\t\tsaveState();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (!global.isIE || mode != \"moving\") {\n\t\t\t\ttimer = top.setTimeout(refreshState, 1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tinputStateObj = null;\n\t\t\t}\n\t\t};\n\t\t\n\t\tvar refreshState = function(){\n\t\t\tinputStateObj = new wmd.TextareaState();\n\t\t\tpoller.tick();\n\t\t\ttimer = undefined;\n\t\t};\n\t\t\n\t\tthis.setCommandMode = function(){\n\t\t\tmode = \"command\";\n\t\t\tsaveState();\n\t\t\ttimer = top.setTimeout(refreshState, 0);\n\t\t};\n\t\t\n\t\tthis.canUndo = function(){\n\t\t\treturn stackPtr > 1;\n\t\t};\n\t\t\n\t\tthis.canRedo = function(){\n\t\t\tif (undoStack[stackPtr + 1]) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t\t\n\t\t// Removes the last state and restores it.\n\t\tthis.undo = function(){\n\t\t\n\t\t\tif (undoObj.canUndo()) {\n\t\t\t\tif (lastState) {\n\t\t\t\t\t// What about setting state -1 to null or checking for undefined?\n\t\t\t\t\tlastState.restore();\n\t\t\t\t\tlastState = null;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tundoStack[stackPtr] = new wmd.TextareaState();\n\t\t\t\t\tundoStack[--stackPtr].restore();\n\t\t\t\t\t\n\t\t\t\t\tif (callback) {\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tmode = \"none\";\n\t\t\twmd.panels.input.focus();\n\t\t\trefreshState();\n\t\t};\n\t\t\n\t\t// Redo an action.\n\t\tthis.redo = function(){\n\t\t\n\t\t\tif (undoObj.canRedo()) {\n\t\t\t\n\t\t\t\tundoStack[++stackPtr].restore();\n\t\t\t\t\n\t\t\t\tif (callback) {\n\t\t\t\t\tcallback();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tmode = \"none\";\n\t\t\twmd.panels.input.focus();\n\t\t\trefreshState();\n\t\t};\n\t\t\n\t\t// Push the input area state to the stack.\n\t\tvar saveState = function(){\n\t\t\n\t\t\tvar currState = inputStateObj || new wmd.TextareaState();\n\t\t\t\n\t\t\tif (!currState) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (mode == \"moving\") {\n\t\t\t\tif (!lastState) {\n\t\t\t\t\tlastState = currState;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (lastState) {\n\t\t\t\tif (undoStack[stackPtr - 1].text != lastState.text) {\n\t\t\t\t\tundoStack[stackPtr++] = lastState;\n\t\t\t\t}\n\t\t\t\tlastState = null;\n\t\t\t}\n\t\t\tundoStack[stackPtr++] = currState;\n\t\t\tundoStack[stackPtr + 1] = null;\n\t\t\tif (callback) {\n\t\t\t\tcallback();\n\t\t\t}\n\t\t};\n\t\t\n\t\tvar handleCtrlYZ = function(event){\n\t\t\n\t\t\tvar handled = false;\n\t\t\t\n\t\t\tif (event.ctrlKey || event.metaKey) {\n\t\t\t\n\t\t\t\t// IE and Opera do not support charCode.\n\t\t\t\tvar keyCode = event.charCode || event.keyCode;\n\t\t\t\tvar keyCodeChar = String.fromCharCode(keyCode);\n\t\t\t\t\n\t\t\t\tswitch (keyCodeChar) {\n\t\t\t\t\n\t\t\t\t\tcase \"y\":\n\t\t\t\t\t\tundoObj.redo();\n\t\t\t\t\t\thandled = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\n\t\t\t\t\tcase \"z\":\n\t\t\t\t\t\tif (!event.shiftKey) {\n\t\t\t\t\t\t\tundoObj.undo();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tundoObj.redo();\n\t\t\t\t\t\t}\n\t\t\t\t\t\thandled = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (handled) {\n\t\t\t\tif (event.preventDefault) {\n\t\t\t\t\tevent.preventDefault();\n\t\t\t\t}\n\t\t\t\tif (top.event) {\n\t\t\t\t\ttop.event.returnValue = false;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t};\n\t\t\n\t\t// Set the mode depending on what is going on in the input area.\n\t\tvar handleModeChange = function(event){\n\t\t\n\t\t\tif (!event.ctrlKey && !event.metaKey) {\n\t\t\t\n\t\t\t\tvar keyCode = event.keyCode;\n\t\t\t\t\n\t\t\t\tif ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {\n\t\t\t\t\t// 33 - 40: page up/dn and arrow keys\n\t\t\t\t\t// 63232 - 63235: page up/dn and arrow keys on safari\n\t\t\t\t\tsetMode(\"moving\");\n\t\t\t\t}\n\t\t\t\telse if (keyCode == 8 || keyCode == 46 || keyCode == 127) {\n\t\t\t\t\t// 8: backspace\n\t\t\t\t\t// 46: delete\n\t\t\t\t\t// 127: delete\n\t\t\t\t\tsetMode(\"deleting\");\n\t\t\t\t}\n\t\t\t\telse if (keyCode == 13) {\n\t\t\t\t\t// 13: Enter\n\t\t\t\t\tsetMode(\"newlines\");\n\t\t\t\t}\n\t\t\t\telse if (keyCode == 27) {\n\t\t\t\t\t// 27: escape\n\t\t\t\t\tsetMode(\"escape\");\n\t\t\t\t}\n\t\t\t\telse if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {\n\t\t\t\t\t// 16-20 are shift, etc. \n\t\t\t\t\t// 91: left window key\n\t\t\t\t\t// I think this might be a little messed up since there are\n\t\t\t\t\t// a lot of nonprinting keys above 20.\n\t\t\t\t\tsetMode(\"typing\");\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t\tvar setEventHandlers = function(){\n\t\t\n\t\t\tutil.addEvent(wmd.panels.input, \"keypress\", function(event){\n\t\t\t\t// keyCode 89: y\n\t\t\t\t// keyCode 90: z\n\t\t\t\tif ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {\n\t\t\t\t\tevent.preventDefault();\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t\tvar handlePaste = function(){\n\t\t\t\tif (global.isIE || (inputStateObj && inputStateObj.text != wmd.panels.input.value)) {\n\t\t\t\t\tif (timer == undefined) {\n\t\t\t\t\t\tmode = \"paste\";\n\t\t\t\t\t\tsaveState();\n\t\t\t\t\t\trefreshState();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t\t// pastePollInterval is specified at the beginning of this namespace.\n\t\t\tpoller = new wmd.inputPoller(handlePaste, pastePollInterval);\n\t\t\t\n\t\t\tutil.addEvent(wmd.panels.input, \"keydown\", handleCtrlYZ);\n\t\t\tutil.addEvent(wmd.panels.input, \"keydown\", handleModeChange);\n\t\t\t\n\t\t\tutil.addEvent(wmd.panels.input, \"mousedown\", function(){\n\t\t\t\tsetMode(\"moving\");\n\t\t\t});\n\t\t\twmd.panels.input.onpaste = handlePaste;\n\t\t\twmd.panels.input.ondrop = handlePaste;\n\t\t};\n\t\t\n\t\tvar init = function(){\n\t\t\tsetEventHandlers();\n\t\t\trefreshState();\n\t\t\tsaveState();\n\t\t};\n\t\t\n\t\tthis.destroy = function(){\n\t\t\tif (poller) {\n\t\t\t\tpoller.destroy();\n\t\t\t}\n\t\t};\n\t\t\n\t\tinit();\n\t};\n\t\n\t// I think my understanding of how the buttons and callbacks are stored in the array is incomplete.\n\twmd.editor = function(previewRefreshCallback){\n\t\n\t\tif (!previewRefreshCallback) {\n\t\t\tpreviewRefreshCallback = function(){};\n\t\t}\n\t\t\n\t\tvar inputBox = wmd.panels.input;\n\t\t\n\t\tvar offsetHeight = 0;\n\t\t\n\t\tvar editObj = this;\n\t\t\n\t\tvar mainDiv;\n\t\tvar mainSpan;\n\t\t\n\t\tvar div; // This name is pretty ambiguous.  I should rename this.\n\t\t\n\t\t// Used to cancel recurring events from setInterval.\n\t\tvar creationHandle;\n\t\t\n\t\tvar undoMgr; // The undo manager\n\t\t\n\t\t// Perform the button's action.\n\t\tvar doClick = function(button){\n\t\t\n\t\t\tinputBox.focus();\n\t\t\t\n\t\t\tif (button.textOp) {\n\t\t\t\t\n\t\t\t\tif (undoMgr) {\n\t\t\t\t\tundoMgr.setCommandMode();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvar state = new wmd.TextareaState();\n\t\t\t\t\n\t\t\t\tif (!state) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvar chunks = state.getChunks();\n\t\t\t\t\n\t\t\t\t// Some commands launch a \"modal\" prompt dialog.  Javascript\n\t\t\t\t// can't really make a modal dialog box and the WMD code\n\t\t\t\t// will continue to execute while the dialog is displayed.\n\t\t\t\t// This prevents the dialog pattern I'm used to and means\n\t\t\t\t// I can't do something like this:\n\t\t\t\t//\n\t\t\t\t// var link = CreateLinkDialog();\n\t\t\t\t// makeMarkdownLink(link);\n\t\t\t\t// \n\t\t\t\t// Instead of this straightforward method of handling a\n\t\t\t\t// dialog I have to pass any code which would execute\n\t\t\t\t// after the dialog is dismissed (e.g. link creation)\n\t\t\t\t// in a function parameter.\n\t\t\t\t//\n\t\t\t\t// Yes this is awkward and I think it sucks, but there's\n\t\t\t\t// no real workaround.  Only the image and link code\n\t\t\t\t// create dialogs and require the function pointers.\n\t\t\t\tvar fixupInputArea = function(){\n\t\t\t\t\n\t\t\t\t\tinputBox.focus();\n\t\t\t\t\t\n\t\t\t\t\tif (chunks) {\n\t\t\t\t\t\tstate.setChunks(chunks);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tstate.restore();\n\t\t\t\t\tpreviewRefreshCallback();\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tvar useDefaultText = true;\n\t\t\t\tvar noCleanup = button.textOp(chunks, fixupInputArea, useDefaultText);\n\t\t\t\t\n\t\t\t\tif(!noCleanup) {\n\t\t\t\t\tfixupInputArea();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif (button.execute) {\n\t\t\t\tbutton.execute(editObj);\n\t\t\t}\n\t\t};\n\t\t\t\n\t\tvar setUndoRedoButtonStates = function(){\n\t\t\tif(undoMgr){\n\t\t\t\tsetupButton(document.getElementById(\"wmd-undo-button\"), undoMgr.canUndo());\n\t\t\t\tsetupButton(document.getElementById(\"wmd-redo-button\"), undoMgr.canRedo());\n\t\t\t}\n\t\t};\n\t\t\n\t\tvar setupButton = function(button, isEnabled) {\n\t\t\n\t\t\tvar normalYShift = \"0px\";\n\t\t\tvar disabledYShift = \"-20px\";\n\t\t\tvar highlightYShift = \"-40px\";\n\t\t\t\n\t\t\tif(isEnabled) {\n\t\t\t\tbutton.style.backgroundPosition = button.XShift + \" \" + normalYShift;\n\t\t\t\tbutton.onmouseover = function(){\n\t\t\t\t\tthis.style.backgroundPosition = this.XShift + \" \" + highlightYShift;\n\t\t\t\t};\n\t\t\t\t\t\t\t\n\t\t\t\tbutton.onmouseout = function(){\n\t\t\t\t\tthis.style.backgroundPosition = this.XShift + \" \" + normalYShift;\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t// IE tries to select the background image \"button\" text (it's\n\t\t\t\t// implemented in a list item) so we have to cache the selection\n\t\t\t\t// on mousedown.\n\t\t\t\tif(global.isIE) {\n\t\t\t\t\tbutton.onmousedown =  function() { \n\t\t\t\t\t\twmd.ieRetardedClick = true;\n\t\t\t\t\t\twmd.ieCachedRange = document.selection.createRange(); \n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!button.isHelp)\n\t\t\t\t{\n\t\t\t\t\tbutton.onclick = function() {\n\t\t\t\t\t\tif (this.onmouseout) {\n\t\t\t\t\t\t\tthis.onmouseout();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdoClick(this);\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbutton.style.backgroundPosition = button.XShift + \" \" + disabledYShift;\n\t\t\t\tbutton.onmouseover = button.onmouseout = button.onclick = function(){};\n\t\t\t}\n\t\t}\n\t\n\t\tvar makeSpritedButtonRow = function(){\n\t\t \t\n\t\t\tvar buttonBar = document.getElementById(\"wmd-button-bar\");\n \t\n\t\t\tvar normalYShift = \"0px\";\n\t\t\tvar disabledYShift = \"-20px\";\n\t\t\tvar highlightYShift = \"-40px\";\n\t\t\t\n\t\t\tvar buttonRow = document.createElement(\"ul\");\n\t\t\tbuttonRow.id = \"wmd-button-row\";\n\t\t\tbuttonRow = buttonBar.appendChild(buttonRow);\n\n\t\t\t\n\t\t\tvar boldButton = document.createElement(\"li\");\n\t\t\tboldButton.className = \"wmd-button\";\n\t\t\tboldButton.id = \"wmd-bold-button\";\n\t\t\tboldButton.title = \"Strong <strong> Ctrl+B\";\n\t\t\tboldButton.XShift = \"0px\";\n\t\t\tboldButton.textOp = command.doBold;\n\t\t\tsetupButton(boldButton, true);\n\t\t\tbuttonRow.appendChild(boldButton);\n\t\t\t\n\t\t\tvar italicButton = document.createElement(\"li\");\n\t\t\titalicButton.className = \"wmd-button\";\n\t\t\titalicButton.id = \"wmd-italic-button\";\n\t\t\titalicButton.title = \"Emphasis <em> Ctrl+I\";\n\t\t\titalicButton.XShift = \"-20px\";\n\t\t\titalicButton.textOp = command.doItalic;\n\t\t\tsetupButton(italicButton, true);\n\t\t\tbuttonRow.appendChild(italicButton);\n\n\t\t\tvar spacer1 = document.createElement(\"li\");\n\t\t\tspacer1.className = \"wmd-spacer\";\n\t\t\tspacer1.id = \"wmd-spacer1\";\n\t\t\tbuttonRow.appendChild(spacer1); \n\n\t\t\tvar linkButton = document.createElement(\"li\");\n\t\t\tlinkButton.className = \"wmd-button\";\n\t\t\tlinkButton.id = \"wmd-link-button\";\n\t\t\tlinkButton.title = \"Hyperlink <a> Ctrl+L\";\n\t\t\tlinkButton.XShift = \"-40px\";\n\t\t\tlinkButton.textOp = function(chunk, postProcessing, useDefaultText){\n\t\t\t\treturn command.doLinkOrImage(chunk, postProcessing, false);\n\t\t\t};\n\t\t\tsetupButton(linkButton, true);\n\t\t\tbuttonRow.appendChild(linkButton);\n\n\t\t\tvar quoteButton = document.createElement(\"li\");\n\t\t\tquoteButton.className = \"wmd-button\";\n\t\t\tquoteButton.id = \"wmd-quote-button\";\n\t\t\tquoteButton.title = \"Blockquote <blockquote> Ctrl+Q\";\n\t\t\tquoteButton.XShift = \"-60px\";\n\t\t\tquoteButton.textOp = command.doBlockquote;\n\t\t\tsetupButton(quoteButton, true);\n\t\t\tbuttonRow.appendChild(quoteButton);\n\t\t\t\n\t\t\tvar codeButton = document.createElement(\"li\");\n\t\t\tcodeButton.className = \"wmd-button\";\n\t\t\tcodeButton.id = \"wmd-code-button\";\n\t\t\tcodeButton.title = \"Code Sample <pre><code> Ctrl+K\";\n\t\t\tcodeButton.XShift = \"-80px\";\n\t\t\tcodeButton.textOp = command.doCode;\n\t\t\tsetupButton(codeButton, true);\n\t\t\tbuttonRow.appendChild(codeButton);\n\n\t\t\tvar imageButton = document.createElement(\"li\");\n\t\t\timageButton.className = \"wmd-button\";\n\t\t\timageButton.id = \"wmd-image-button\";\n\t\t\timageButton.title = \"Image <img> Ctrl+G\";\n\t\t\timageButton.XShift = \"-100px\";\n\t\t\timageButton.textOp = function(chunk, postProcessing, useDefaultText){\n\t\t\t\treturn command.doLinkOrImage(chunk, postProcessing, true);\n\t\t\t};\n\t\t\tsetupButton(imageButton, true);\n\t\t\tbuttonRow.appendChild(imageButton);\n\n\t\t\tvar spacer2 = document.createElement(\"li\");\n\t\t\tspacer2.className = \"wmd-spacer\";\n\t\t\tspacer2.id = \"wmd-spacer2\";\n\t\t\tbuttonRow.appendChild(spacer2); \n\n\t\t\tvar olistButton = document.createElement(\"li\");\n\t\t\tolistButton.className = \"wmd-button\";\n\t\t\tolistButton.id = \"wmd-olist-button\";\n\t\t\tolistButton.title = \"Numbered List <ol> Ctrl+O\";\n\t\t\tolistButton.XShift = \"-120px\";\n\t\t\tolistButton.textOp = function(chunk, postProcessing, useDefaultText){\n\t\t\t\tcommand.doList(chunk, postProcessing, true, useDefaultText);\n\t\t\t};\n\t\t\tsetupButton(olistButton, true);\n\t\t\tbuttonRow.appendChild(olistButton);\n\t\t\t\n\t\t\tvar ulistButton = document.createElement(\"li\");\n\t\t\tulistButton.className = \"wmd-button\";\n\t\t\tulistButton.id = \"wmd-ulist-button\";\n\t\t\tulistButton.title = \"Bulleted List <ul> Ctrl+U\";\n\t\t\tulistButton.XShift = \"-140px\";\n\t\t\tulistButton.textOp = function(chunk, postProcessing, useDefaultText){\n\t\t\t\tcommand.doList(chunk, postProcessing, false, useDefaultText);\n\t\t\t};\n\t\t\tsetupButton(ulistButton, true);\n\t\t\tbuttonRow.appendChild(ulistButton);\n\t\t\t\n\t\t\tvar headingButton = document.createElement(\"li\");\n\t\t\theadingButton.className = \"wmd-button\";\n\t\t\theadingButton.id = \"wmd-heading-button\";\n\t\t\theadingButton.title = \"Heading <h1>/<h2> Ctrl+H\";\n\t\t\theadingButton.XShift = \"-160px\";\n\t\t\theadingButton.textOp = command.doHeading;\n\t\t\tsetupButton(headingButton, true);\n\t\t\tbuttonRow.appendChild(headingButton); \n\t\t\t\n\t\t\tvar hrButton = document.createElement(\"li\");\n\t\t\thrButton.className = \"wmd-button\";\n\t\t\thrButton.id = \"wmd-hr-button\";\n\t\t\thrButton.title = \"Horizontal Rule <hr> Ctrl+R\";\n\t\t\thrButton.XShift = \"-180px\";\n\t\t\thrButton.textOp = command.doHorizontalRule;\n\t\t\tsetupButton(hrButton, true);\n\t\t\tbuttonRow.appendChild(hrButton); \n\t\t\t\n\t\t\tvar spacer3 = document.createElement(\"li\");\n\t\t\tspacer3.className = \"wmd-spacer\";\n\t\t\tspacer3.id = \"wmd-spacer3\";\n\t\t\tbuttonRow.appendChild(spacer3); \n\t\t\t\n\t\t\tvar undoButton = document.createElement(\"li\");\n\t\t\tundoButton.className = \"wmd-button\";\n\t\t\tundoButton.id = \"wmd-undo-button\";\n\t\t\tundoButton.title = \"Undo - Ctrl+Z\";\n\t\t\tundoButton.XShift = \"-200px\";\n\t\t\tundoButton.execute = function(manager){\n\t\t\t\tmanager.undo();\n\t\t\t};\n\t\t\tsetupButton(undoButton, true);\n\t\t\tbuttonRow.appendChild(undoButton); \n\t\t\t\n\t\t\tvar redoButton = document.createElement(\"li\");\n\t\t\tredoButton.className = \"wmd-button\";\n\t\t\tredoButton.id = \"wmd-redo-button\";\n\t\t\tredoButton.title = \"Redo - Ctrl+Y\";\n\t\t\tif (/win/.test(nav.platform.toLowerCase())) {\n\t\t\t\tredoButton.title = \"Redo - Ctrl+Y\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// mac and other non-Windows platforms\n\t\t\t\tredoButton.title = \"Redo - Ctrl+Shift+Z\";\n\t\t\t}\n\t\t\tredoButton.XShift = \"-220px\";\n\t\t\tredoButton.execute = function(manager){\n\t\t\t\tmanager.redo();\n\t\t\t};\n\t\t\tsetupButton(redoButton, true);\n\t\t\tbuttonRow.appendChild(redoButton); \n\t\t\t\n\t\t\tvar helpButton = document.createElement(\"li\");\n\t\t\thelpButton.className = \"wmd-button\";\n\t\t\thelpButton.id = \"wmd-help-button\";\n\t\t\thelpButton.XShift = \"-240px\";\n\t\t\thelpButton.isHelp = true;\n\t\t\t\n\t\t\tvar helpAnchor = document.createElement(\"a\");\n\t\t\thelpAnchor.href = helpLink;\n\t\t\thelpAnchor.target = helpTarget\n\t\t\thelpAnchor.title = helpHoverTitle;\n\t\t\thelpButton.appendChild(helpAnchor);\n\t\t\t\n\t\t\tsetupButton(helpButton, true);\n\t\t\tbuttonRow.appendChild(helpButton);\n\t\t\t\n\t\t\tsetUndoRedoButtonStates();\n\t\t}\n\t\t\n\t\tvar setupEditor = function(){\n\t\t\n\t\t\tif (/\\?noundo/.test(doc.location.href)) {\n\t\t\t\twmd.nativeUndo = true;\n\t\t\t}\n\t\t\t\n\t\t\tif (!wmd.nativeUndo) {\n\t\t\t\tundoMgr = new wmd.undoManager(function(){\n\t\t\t\t\tpreviewRefreshCallback();\n\t\t\t\t\tsetUndoRedoButtonStates();\n\t\t\t\t});\n\t\t\t}\n\t\t\t\n\t\t\tmakeSpritedButtonRow();\n\t\t\t\n\t\t\t\n\t\t\tvar keyEvent = \"keydown\";\n\t\t\tif (global.isOpera) {\n\t\t\t\tkeyEvent = \"keypress\";\n\t\t\t}\n\t\t\t\n\t\t\tutil.addEvent(inputBox, keyEvent, function(key){\n\t\t\t\t\n\t\t\t\t// Check to see if we have a button key and, if so execute the callback.\n\t\t\t\tif (key.ctrlKey || key.metaKey) {\n\t\t\t\n\t\t\t\t\tvar keyCode = key.charCode || key.keyCode;\n\t\t\t\t\tvar keyCodeStr = String.fromCharCode(keyCode).toLowerCase();\n\t\t\t\t\t\n\t\t\t\t\tswitch(keyCodeStr) {\n\t\t\t\t\t\tcase \"b\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-bold-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"i\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-italic-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"l\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-link-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"q\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-quote-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"k\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-code-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"g\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-image-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"o\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-olist-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"u\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-ulist-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"h\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-heading-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"r\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-hr-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"y\":\n\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-redo-button\"));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"z\":\n\t\t\t\t\t\t\tif(key.shiftKey) {\n\t\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-redo-button\"));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tdoClick(document.getElementById(\"wmd-undo-button\"));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t\n\n\t\t\t\t\tif (key.preventDefault) {\n\t\t\t\t\t\tkey.preventDefault();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (top.event) {\n\t\t\t\t\t\ttop.event.returnValue = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t\t// Auto-continue lists, code blocks and block quotes when\n\t\t\t// the enter key is pressed.\n\t\t\tutil.addEvent(inputBox, \"keyup\", function(key){\n\t\t\t\tif (!key.shiftKey && !key.ctrlKey && !key.metaKey) {\n\t\t\t\t\tvar keyCode = key.charCode || key.keyCode;\n\t\t\t\t\t// Key code 13 is Enter\n\t\t\t\t\tif (keyCode === 13) {\n\t\t\t\t\t\tfakeButton = {};\n\t\t\t\t\t\tfakeButton.textOp = command.doAutoindent;\n\t\t\t\t\t\tdoClick(fakeButton);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t\t// Disable ESC clearing the input textarea on IE\n\t\t\tif (global.isIE) {\n\t\t\t\tutil.addEvent(inputBox, \"keydown\", function(key){\n\t\t\t\t\tvar code = key.keyCode;\n\t\t\t\t\t// Key code 27 is ESC\n\t\t\t\t\tif (code === 27) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\t\n\t\t\tif (inputBox.form) {\n\t\t\t\tvar submitCallback = inputBox.form.onsubmit;\n\t\t\t\tinputBox.form.onsubmit = function(){\n\t\t\t\t\tconvertToHtml();\n\t\t\t\t\tif (submitCallback) {\n\t\t\t\t\t\treturn submitCallback.apply(this, arguments);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t\t\n\t\t// Convert the contents of the input textarea to HTML in the output/preview panels.\n\t\tvar convertToHtml = function(){\n\t\t\n\t\t\tif (wmd.showdown) {\n\t\t\t\tvar markdownConverter = new wmd.showdown.converter();\n\t\t\t}\n\t\t\tvar text = inputBox.value;\n\t\t\t\n\t\t\tvar callback = function(){\n\t\t\t\tinputBox.value = text;\n\t\t\t};\n\t\t\t\n\t\t\tif (!/markdown/.test(wmd.wmd_env.output.toLowerCase())) {\n\t\t\t\tif (markdownConverter) {\n\t\t\t\t\tinputBox.value = markdownConverter.makeHtml(text);\n\t\t\t\t\ttop.setTimeout(callback, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\t\n\t\t\n\t\tthis.undo = function(){\n\t\t\tif (undoMgr) {\n\t\t\t\tundoMgr.undo();\n\t\t\t}\n\t\t};\n\t\t\n\t\tthis.redo = function(){\n\t\t\tif (undoMgr) {\n\t\t\t\tundoMgr.redo();\n\t\t\t}\n\t\t};\n\t\t\n\t\t// This is pretty useless.  The setupEditor function contents\n\t\t// should just be copied here.\n\t\tvar init = function(){\n\t\t\tsetupEditor();\n\t\t};\n\t\t\n\t\tthis.destroy = function(){\n\t\t\tif (undoMgr) {\n\t\t\t\tundoMgr.destroy();\n\t\t\t}\n\t\t\tif (div.parentNode) {\n\t\t\t\tdiv.parentNode.removeChild(div);\n\t\t\t}\n\t\t\tif (inputBox) {\n\t\t\t\tinputBox.style.marginTop = \"\";\n\t\t\t}\n\t\t\ttop.clearInterval(creationHandle);\n\t\t};\n\t\t\n\t\tinit();\n\t};\n\t\n\t// The input textarea state/contents.\n\t// This is used to implement undo/redo by the undo manager.\n\twmd.TextareaState = function(){\n\t\n\t\t// Aliases\n\t\tvar stateObj = this;\n\t\tvar inputArea = wmd.panels.input;\n\t\t\n\t\tthis.init = function() {\n\t\t\n\t\t\tif (!util.isVisible(inputArea)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\t\n\t\t\tthis.setInputAreaSelectionStartEnd();\n\t\t\tthis.scrollTop = inputArea.scrollTop;\n\t\t\tif (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {\n\t\t\t\tthis.text = inputArea.value;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t// Sets the selected text in the input box after we've performed an\n\t\t// operation.\n\t\tthis.setInputAreaSelection = function(){\n\t\t\n\t\t\tif (!util.isVisible(inputArea)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tif (inputArea.selectionStart !== undefined && !global.isOpera) {\n\t\t\t\n\t\t\t\tinputArea.focus();\n\t\t\t\tinputArea.selectionStart = stateObj.start;\n\t\t\t\tinputArea.selectionEnd = stateObj.end;\n\t\t\t\tinputArea.scrollTop = stateObj.scrollTop;\n\t\t\t}\n\t\t\telse if (doc.selection) {\n\t\t\t\t\n\t\t\t\tif (doc.activeElement && doc.activeElement !== inputArea) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\tinputArea.focus();\n\t\t\t\tvar range = inputArea.createTextRange();\n\t\t\t\trange.moveStart(\"character\", -inputArea.value.length);\n\t\t\t\trange.moveEnd(\"character\", -inputArea.value.length);\n\t\t\t\trange.moveEnd(\"character\", stateObj.end);\n\t\t\t\trange.moveStart(\"character\", stateObj.start);\n\t\t\t\trange.select();\n\t\t\t}\n\t\t};\n\t\t\n\t\tthis.setInputAreaSelectionStartEnd = function(){\n\t\t\n\t\t\tif (inputArea.selectionStart || inputArea.selectionStart === 0) {\n\t\t\t\n\t\t\t\tstateObj.start = inputArea.selectionStart;\n\t\t\t\tstateObj.end = inputArea.selectionEnd;\n\t\t\t}\n\t\t\telse if (doc.selection) {\n\t\t\t\t\n\t\t\t\tstateObj.text = util.fixEolChars(inputArea.value);\n\t\t\t\t\n\t\t\t\t// IE loses the selection in the textarea when buttons are\n\t\t\t\t// clicked.  On IE we cache the selection and set a flag\n\t\t\t\t// which we check for here.\n\t\t\t\tvar range;\n\t\t\t\tif(wmd.ieRetardedClick && wmd.ieCachedRange) {\n\t\t\t\t\trange = wmd.ieCachedRange;\n\t\t\t\t\twmd.ieRetardedClick = false;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\trange = doc.selection.createRange();\n\t\t\t\t}\n\n\t\t\t\tvar fixedRange = util.fixEolChars(range.text);\n\t\t\t\tvar marker = \"\\x07\";\n\t\t\t\tvar markedRange = marker + fixedRange + marker;\n\t\t\t\trange.text = markedRange;\n\t\t\t\tvar inputText = util.fixEolChars(inputArea.value);\n\t\t\t\t\t\n\t\t\t\trange.moveStart(\"character\", -markedRange.length);\n\t\t\t\trange.text = fixedRange;\n\n\t\t\t\tstateObj.start = inputText.indexOf(marker);\n\t\t\t\tstateObj.end = inputText.lastIndexOf(marker) - marker.length;\n\t\t\t\t\t\n\t\t\t\tvar len = stateObj.text.length - util.fixEolChars(inputArea.value).length;\n\t\t\t\t\t\n\t\t\t\tif (len) {\n\t\t\t\t\trange.moveStart(\"character\", -fixedRange.length);\n\t\t\t\t\twhile (len--) {\n\t\t\t\t\t\tfixedRange += \"\\n\";\n\t\t\t\t\t\tstateObj.end += 1;\n\t\t\t\t\t}\n\t\t\t\t\trange.text = fixedRange;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\tthis.setInputAreaSelection();\n\t\t\t}\n\t\t};\n\t\t\n\t\t// Restore this state into the input area.\n\t\tthis.restore = function(){\n\t\t\n\t\t\tif (stateObj.text != undefined && stateObj.text != inputArea.value) {\n\t\t\t\tinputArea.value = stateObj.text;\n\t\t\t}\n\t\t\tthis.setInputAreaSelection();\n\t\t\tinputArea.scrollTop = stateObj.scrollTop;\n\t\t};\n\t\t\n\t\t// Gets a collection of HTML chunks from the inptut textarea.\n\t\tthis.getChunks = function(){\n\t\t\n\t\t\tvar chunk = new wmd.Chunks();\n\t\t\t\n\t\t\tchunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));\n\t\t\tchunk.startTag = \"\";\n\t\t\tchunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));\n\t\t\tchunk.endTag = \"\";\n\t\t\tchunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));\n\t\t\tchunk.scrollTop = stateObj.scrollTop;\n\t\t\t\n\t\t\treturn chunk;\n\t\t};\n\t\t\n\t\t// Sets the TextareaState properties given a chunk of markdown.\n\t\tthis.setChunks = function(chunk){\n\t\t\n\t\t\tchunk.before = chunk.before + chunk.startTag;\n\t\t\tchunk.after = chunk.endTag + chunk.after;\n\t\t\t\n\t\t\tif (global.isOpera) {\n\t\t\t\tchunk.before = chunk.before.replace(/\\n/g, \"\\r\\n\");\n\t\t\t\tchunk.selection = chunk.selection.replace(/\\n/g, \"\\r\\n\");\n\t\t\t\tchunk.after = chunk.after.replace(/\\n/g, \"\\r\\n\");\n\t\t\t}\n\t\t\t\n\t\t\tthis.start = chunk.before.length;\n\t\t\tthis.end = chunk.before.length + chunk.selection.length;\n\t\t\tthis.text = chunk.before + chunk.selection + chunk.after;\n\t\t\tthis.scrollTop = chunk.scrollTop;\n\t\t};\n\n\t\tthis.init();\n\t};\n\t\n\t// before: contains all the text in the input box BEFORE the selection.\n\t// after: contains all the text in the input box AFTER the selection.\n\twmd.Chunks = function(){\n\t};\n\t\n\t// startRegex: a regular expression to find the start tag\n\t// endRegex: a regular expresssion to find the end tag\n\twmd.Chunks.prototype.findTags = function(startRegex, endRegex){\n\t\n\t\tvar chunkObj = this;\n\t\tvar regex;\n\t\t\n\t\tif (startRegex) {\n\t\t\t\n\t\t\tregex = util.extendRegExp(startRegex, \"\", \"$\");\n\t\t\t\n\t\t\tthis.before = this.before.replace(regex, \n\t\t\t\tfunction(match){\n\t\t\t\t\tchunkObj.startTag = chunkObj.startTag + match;\n\t\t\t\t\treturn \"\";\n\t\t\t\t});\n\t\t\t\n\t\t\tregex = util.extendRegExp(startRegex, \"^\", \"\");\n\t\t\t\n\t\t\tthis.selection = this.selection.replace(regex, \n\t\t\t\tfunction(match){\n\t\t\t\t\tchunkObj.startTag = chunkObj.startTag + match;\n\t\t\t\t\treturn \"\";\n\t\t\t\t});\n\t\t}\n\t\t\n\t\tif (endRegex) {\n\t\t\t\n\t\t\tregex = util.extendRegExp(endRegex, \"\", \"$\");\n\t\t\t\n\t\t\tthis.selection = this.selection.replace(regex,\n\t\t\t\tfunction(match){\n\t\t\t\t\tchunkObj.endTag = match + chunkObj.endTag;\n\t\t\t\t\treturn \"\";\n\t\t\t\t});\n\n\t\t\tregex = util.extendRegExp(endRegex, \"^\", \"\");\n\t\t\t\n\t\t\tthis.after = this.after.replace(regex,\n\t\t\t\tfunction(match){\n\t\t\t\t\tchunkObj.endTag = match + chunkObj.endTag;\n\t\t\t\t\treturn \"\";\n\t\t\t\t});\n\t\t}\n\t};\n\t\n\t// If remove is false, the whitespace is transferred\n\t// to the before/after regions.\n\t//\n\t// If remove is true, the whitespace disappears.\n\twmd.Chunks.prototype.trimWhitespace = function(remove){\n\t\n\t\tthis.selection = this.selection.replace(/^(\\s*)/, \"\");\n\t\t\n\t\tif (!remove) {\n\t\t\tthis.before += re.$1;\n\t\t}\n\t\t\n\t\tthis.selection = this.selection.replace(/(\\s*)$/, \"\");\n\t\t\n\t\tif (!remove) {\n\t\t\tthis.after = re.$1 + this.after;\n\t\t}\n\t};\n\t\n\t\n\twmd.Chunks.prototype.addBlankLines = function(nLinesBefore, nLinesAfter, findExtraNewlines){\n\t\n\t\tif (nLinesBefore === undefined) {\n\t\t\tnLinesBefore = 1;\n\t\t}\n\t\t\n\t\tif (nLinesAfter === undefined) {\n\t\t\tnLinesAfter = 1;\n\t\t}\n\t\t\n\t\tnLinesBefore++;\n\t\tnLinesAfter++;\n\t\t\n\t\tvar regexText;\n\t\tvar replacementText;\n\t\t\n\t\tthis.selection = this.selection.replace(/(^\\n*)/, \"\");\n\t\tthis.startTag = this.startTag + re.$1;\n\t\tthis.selection = this.selection.replace(/(\\n*$)/, \"\");\n\t\tthis.endTag = this.endTag + re.$1;\n\t\tthis.startTag = this.startTag.replace(/(^\\n*)/, \"\");\n\t\tthis.before = this.before + re.$1;\n\t\tthis.endTag = this.endTag.replace(/(\\n*$)/, \"\");\n\t\tthis.after = this.after + re.$1;\n\t\t\n\t\tif (this.before) {\n\t\t\n\t\t\tregexText = replacementText = \"\";\n\t\t\t\n\t\t\twhile (nLinesBefore--) {\n\t\t\t\tregexText += \"\\\\n?\";\n\t\t\t\treplacementText += \"\\n\";\n\t\t\t}\n\t\t\t\n\t\t\tif (findExtraNewlines) {\n\t\t\t\tregexText = \"\\\\n*\";\n\t\t\t}\n\t\t\tthis.before = this.before.replace(new re(regexText + \"$\", \"\"), replacementText);\n\t\t}\n\t\t\n\t\tif (this.after) {\n\t\t\n\t\t\tregexText = replacementText = \"\";\n\t\t\t\n\t\t\twhile (nLinesAfter--) {\n\t\t\t\tregexText += \"\\\\n?\";\n\t\t\t\treplacementText += \"\\n\";\n\t\t\t}\n\t\t\tif (findExtraNewlines) {\n\t\t\t\tregexText = \"\\\\n*\";\n\t\t\t}\n\t\t\t\n\t\t\tthis.after = this.after.replace(new re(regexText, \"\"), replacementText);\n\t\t}\n\t};\n\t\n\t// The markdown symbols - 4 spaces = code, > = blockquote, etc.\n\tcommand.prefixes = \"(?:\\\\s{4,}|\\\\s*>|\\\\s*-\\\\s+|\\\\s*\\\\d+\\\\.|=|\\\\+|-|_|\\\\*|#|\\\\s*\\\\[[^\\n]]+\\\\]:)\";\n\t\n\t// Remove markdown symbols from the chunk selection.\n\tcommand.unwrap = function(chunk){\n\t\tvar txt = new re(\"([^\\\\n])\\\\n(?!(\\\\n|\" + command.prefixes + \"))\", \"g\");\n\t\tchunk.selection = chunk.selection.replace(txt, \"$1 $2\");\n\t};\n\t\n\tcommand.wrap = function(chunk, len){\n\t\tcommand.unwrap(chunk);\n\t\tvar regex = new re(\"(.{1,\" + len + \"})( +|$\\\\n?)\", \"gm\");\n\t\t\n\t\tchunk.selection = chunk.selection.replace(regex, function(line, marked){\n\t\t\tif (new re(\"^\" + command.prefixes, \"\").test(line)) {\n\t\t\t\treturn line;\n\t\t\t}\n\t\t\treturn marked + \"\\n\";\n\t\t});\n\t\t\n\t\tchunk.selection = chunk.selection.replace(/\\s+$/, \"\");\n\t};\n\t\n\tcommand.doBold = function(chunk, postProcessing, useDefaultText){\n\t\treturn command.doBorI(chunk, 2, \"strong text\");\n\t};\n\t\n\tcommand.doItalic = function(chunk, postProcessing, useDefaultText){\n\t\treturn command.doBorI(chunk, 1, \"emphasized text\");\n\t};\n\t\n\t// chunk: The selected region that will be enclosed with */**\n\t// nStars: 1 for italics, 2 for bold\n\t// insertText: If you just click the button without highlighting text, this gets inserted\n\tcommand.doBorI = function(chunk, nStars, insertText){\n\t\n\t\t// Get rid of whitespace and fixup newlines.\n\t\tchunk.trimWhitespace();\n\t\tchunk.selection = chunk.selection.replace(/\\n{2,}/g, \"\\n\");\n\t\t\n\t\t// Look for stars before and after.  Is the chunk already marked up?\n\t\tchunk.before.search(/(\\**$)/);\n\t\tvar starsBefore = re.$1;\n\t\t\n\t\tchunk.after.search(/(^\\**)/);\n\t\tvar starsAfter = re.$1;\n\t\t\n\t\tvar prevStars = Math.min(starsBefore.length, starsAfter.length);\n\t\t\n\t\t// Remove stars if we have to since the button acts as a toggle.\n\t\tif ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {\n\t\t\tchunk.before = chunk.before.replace(re(\"[*]{\" + nStars + \"}$\", \"\"), \"\");\n\t\t\tchunk.after = chunk.after.replace(re(\"^[*]{\" + nStars + \"}\", \"\"), \"\");\n\t\t}\n\t\telse if (!chunk.selection && starsAfter) {\n\t\t\t// It's not really clear why this code is necessary.  It just moves\n\t\t\t// some arbitrary stuff around.\n\t\t\tchunk.after = chunk.after.replace(/^([*_]*)/, \"\");\n\t\t\tchunk.before = chunk.before.replace(/(\\s?)$/, \"\");\n\t\t\tvar whitespace = re.$1;\n\t\t\tchunk.before = chunk.before + starsAfter + whitespace;\n\t\t}\n\t\telse {\n\t\t\n\t\t\t// In most cases, if you don't have any selected text and click the button\n\t\t\t// you'll get a selected, marked up region with the default text inserted.\n\t\t\tif (!chunk.selection && !starsAfter) {\n\t\t\t\tchunk.selection = insertText;\n\t\t\t}\n\t\t\t\n\t\t\t// Add the true markup.\n\t\t\tvar markup = nStars <= 1 ? \"*\" : \"**\"; // shouldn't the test be = ?\n\t\t\tchunk.before = chunk.before + markup;\n\t\t\tchunk.after = markup + chunk.after;\n\t\t}\n\t\t\n\t\treturn;\n\t};\n\t\n\tcommand.stripLinkDefs = function(text, defsToAdd){\n\t\n\t\ttext = text.replace(/^[ ]{0,3}\\[(\\d+)\\]:[ \\t]*\\n?[ \\t]*<?(\\S+?)>?[ \\t]*\\n?[ \\t]*(?:(\\n*)[\"(](.+?)[\")][ \\t]*)?(?:\\n+|$)/gm, \n\t\t\tfunction(totalMatch, id, link, newlines, title){\t\n\t\t\t\tdefsToAdd[id] = totalMatch.replace(/\\s*$/, \"\");\n\t\t\t\tif (newlines) {\n\t\t\t\t\t// Strip the title and return that separately.\n\t\t\t\t\tdefsToAdd[id] = totalMatch.replace(/[\"(](.+?)[\")]$/, \"\");\n\t\t\t\t\treturn newlines + title;\n\t\t\t\t}\n\t\t\t\treturn \"\";\n\t\t\t});\n\t\t\n\t\treturn text;\n\t};\n\t\n\tcommand.addLinkDef = function(chunk, linkDef){\n\t\n\t\tvar refNumber = 0; // The current reference number\n\t\tvar defsToAdd = {}; //\n\t\t// Start with a clean slate by removing all previous link definitions.\n\t\tchunk.before = command.stripLinkDefs(chunk.before, defsToAdd);\n\t\tchunk.selection = command.stripLinkDefs(chunk.selection, defsToAdd);\n\t\tchunk.after = command.stripLinkDefs(chunk.after, defsToAdd);\n\t\t\n\t\tvar defs = \"\";\n\t\tvar regex = /(\\[(?:\\[[^\\]]*\\]|[^\\[\\]])*\\][ ]?(?:\\n[ ]*)?\\[)(\\d+)(\\])/g;\n\t\t\n\t\tvar addDefNumber = function(def){\n\t\t\trefNumber++;\n\t\t\tdef = def.replace(/^[ ]{0,3}\\[(\\d+)\\]:/, \"  [\" + refNumber + \"]:\");\n\t\t\tdefs += \"\\n\" + def;\n\t\t};\n\t\t\n\t\tvar getLink = function(wholeMatch, link, id, end){\n\t\t\n\t\t\tif (defsToAdd[id]) {\n\t\t\t\taddDefNumber(defsToAdd[id]);\n\t\t\t\treturn link + refNumber + end;\n\t\t\t\t\n\t\t\t}\n\t\t\treturn wholeMatch;\n\t\t};\n\t\t\n\t\tchunk.before = chunk.before.replace(regex, getLink);\n\t\t\n\t\tif (linkDef) {\n\t\t\taddDefNumber(linkDef);\n\t\t}\n\t\telse {\n\t\t\tchunk.selection = chunk.selection.replace(regex, getLink);\n\t\t}\n\t\t\n\t\tvar refOut = refNumber;\n\t\t\n\t\tchunk.after = chunk.after.replace(regex, getLink);\n\t\t\n\t\tif (chunk.after) {\n\t\t\tchunk.after = chunk.after.replace(/\\n*$/, \"\");\n\t\t}\n\t\tif (!chunk.after) {\n\t\t\tchunk.selection = chunk.selection.replace(/\\n*$/, \"\");\n\t\t}\n\t\t\n\t\tchunk.after += \"\\n\\n\" + defs;\n\t\t\n\t\treturn refOut;\n\t};\n\t\n\tcommand.doLinkOrImage = function(chunk, postProcessing, isImage){\n\t\n\t\tchunk.trimWhitespace();\n\t\tchunk.findTags(/\\s*!?\\[/, /\\][ ]?(?:\\n[ ]*)?(\\[.*?\\])?/);\n\t\t\n\t\tif (chunk.endTag.length > 1) {\n\t\t\n\t\t\tchunk.startTag = chunk.startTag.replace(/!?\\[/, \"\");\n\t\t\tchunk.endTag = \"\";\n\t\t\tcommand.addLinkDef(chunk, null);\n\t\t\t\n\t\t}\n\t\telse {\n\t\t\n\t\t\tif (/\\n\\n/.test(chunk.selection)) {\n\t\t\t\tcommand.addLinkDef(chunk, null);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// The function to be executed when you enter a link and press OK or Cancel.\n\t\t\t// Marks up the link and adds the ref.\n\t\t\tvar makeLinkMarkdown = function(link){\n\t\t\t\n\t\t\t\tif (link !== null) {\n\t\t\t\t\n\t\t\t\t\tchunk.startTag = chunk.endTag = \"\";\n\t\t\t\t\tvar linkDef = \" [999]: \" + link;\n\t\t\t\t\t\n\t\t\t\t\tvar num = command.addLinkDef(chunk, linkDef);\n\t\t\t\t\tchunk.startTag = isImage ? \"![\" : \"[\";\n\t\t\t\t\tchunk.endTag = \"][\" + num + \"]\";\n\t\t\t\t\t\n\t\t\t\t\tif (!chunk.selection) {\n\t\t\t\t\t\tif (isImage) {\n\t\t\t\t\t\t\tchunk.selection = \"alt text\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tchunk.selection = \"link text\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpostProcessing();\n\t\t\t};\n\t\t\t\n\t\t\tif (isImage) {\n\t\t\t\tutil.prompt(imageDialogText, imageDefaultText, makeLinkMarkdown);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tutil.prompt(linkDialogText, linkDefaultText, makeLinkMarkdown);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t};\n\t\n\tutil.makeAPI = function(){\n\t\twmd.wmd = {};\n\t\twmd.wmd.editor = wmd.editor;\n\t\twmd.wmd.previewManager = wmd.previewManager;\n\t};\n\t\n\tutil.startEditor = function(){\n\t\n\t\tif (wmd.wmd_env.autostart === false) {\n\t\t\tutil.makeAPI();\n\t\t\treturn;\n\t\t}\n\n\t\tvar edit;\t\t// The editor (buttons + input + outputs) - the main object.\n\t\tvar previewMgr;\t// The preview manager.\n\t\t\n\t\t// Fired after the page has fully loaded.\n\t\tvar loadListener = function(){\n\t\t\n\t\t\twmd.panels = new wmd.PanelCollection();\n\t\t\t\n\t\t\tpreviewMgr = new wmd.previewManager();\n\t\t\tvar previewRefreshCallback = previewMgr.refresh;\n\t\t\t\t\t\t\n\t\t\tedit = new wmd.editor(previewRefreshCallback);\n\t\t\t\n\t\t\tpreviewMgr.refresh(true);\n\t\t\t\n\t\t};\n\t\t\n\t\tutil.addEvent(top, \"load\", loadListener);\n\t};\n\t\n\twmd.previewManager = function(){\n\t\t\n\t\tvar managerObj = this;\n\t\tvar converter;\n\t\tvar poller;\n\t\tvar timeout;\n\t\tvar elapsedTime;\n\t\tvar oldInputText;\n\t\tvar htmlOut;\n\t\tvar maxDelay = 3000;\n\t\tvar startType = \"delayed\"; // The other legal value is \"manual\"\n\t\t\n\t\t// Adds event listeners to elements and creates the input poller.\n\t\tvar setupEvents = function(inputElem, listener){\n\t\t\n\t\t\tutil.addEvent(inputElem, \"input\", listener);\n\t\t\tinputElem.onpaste = listener;\n\t\t\tinputElem.ondrop = listener;\n\t\t\t\n\t\t\tutil.addEvent(inputElem, \"keypress\", listener);\n\t\t\tutil.addEvent(inputElem, \"keydown\", listener);\n\t\t\t// previewPollInterval is set at the top of this file.\n\t\t\tpoller = new wmd.inputPoller(listener, previewPollInterval);\n\t\t};\n\t\t\n\t\tvar getDocScrollTop = function(){\n\t\t\n\t\t\tvar result = 0;\n\t\t\t\n\t\t\tif (top.innerHeight) {\n\t\t\t\tresult = top.pageYOffset;\n\t\t\t}\n\t\t\telse \n\t\t\t\tif (doc.documentElement && doc.documentElement.scrollTop) {\n\t\t\t\t\tresult = doc.documentElement.scrollTop;\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t\tif (doc.body) {\n\t\t\t\t\t\tresult = doc.body.scrollTop;\n\t\t\t\t\t}\n\t\t\t\n\t\t\treturn result;\n\t\t};\n\t\t\n\t\tvar makePreviewHtml = function(){\n\t\t\n\t\t\t// If there are no registered preview and output panels\n\t\t\t// there is nothing to do.\n\t\t\tif (!wmd.panels.preview && !wmd.panels.output) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tvar text = wmd.panels.input.value;\n\t\t\tif (text && text == oldInputText) {\n\t\t\t\treturn; // Input text hasn't changed.\n\t\t\t}\n\t\t\telse {\n\t\t\t\toldInputText = text;\n\t\t\t}\n\t\t\t\n\t\t\tvar prevTime = new Date().getTime();\n\t\t\t\n\t\t\tif (!converter && wmd.showdown) {\n\t\t\t\tconverter = new wmd.showdown.converter();\n\t\t\t}\n\t\t\t\n\t\t\tif (converter) {\n\t\t\t\ttext = converter.makeHtml(text);\n\t\t\t}\n\t\t\t\n\t\t\t// Calculate the processing time of the HTML creation.\n\t\t\t// It's used as the delay time in the event listener.\n\t\t\tvar currTime = new Date().getTime();\n\t\t\telapsedTime = currTime - prevTime;\n\t\t\t\n\t\t\tpushPreviewHtml(text);\n\t\t\thtmlOut = text;\n\t\t};\n\t\t\n\t\t// setTimeout is already used.  Used as an event listener.\n\t\tvar applyTimeout = function(){\n\t\t\n\t\t\tif (timeout) {\n\t\t\t\ttop.clearTimeout(timeout);\n\t\t\t\ttimeout = undefined;\n\t\t\t}\n\t\t\t\n\t\t\tif (startType !== \"manual\") {\n\t\t\t\n\t\t\t\tvar delay = 0;\n\t\t\t\t\n\t\t\t\tif (startType === \"delayed\") {\n\t\t\t\t\tdelay = elapsedTime;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (delay > maxDelay) {\n\t\t\t\t\tdelay = maxDelay;\n\t\t\t\t}\n\t\t\t\ttimeout = top.setTimeout(makePreviewHtml, delay);\n\t\t\t}\n\t\t};\n\t\t\n\t\tvar getScaleFactor = function(panel){\n\t\t\tif (panel.scrollHeight <= panel.clientHeight) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\treturn panel.scrollTop / (panel.scrollHeight - panel.clientHeight);\n\t\t};\n\t\t\n\t\tvar setPanelScrollTops = function(){\n\t\t\n\t\t\tif (wmd.panels.preview) {\n\t\t\t\twmd.panels.preview.scrollTop = (wmd.panels.preview.scrollHeight - wmd.panels.preview.clientHeight) * getScaleFactor(wmd.panels.preview);\n\t\t\t\t;\n\t\t\t}\n\t\t\t\n\t\t\tif (wmd.panels.output) {\n\t\t\t\twmd.panels.output.scrollTop = (wmd.panels.output.scrollHeight - wmd.panels.output.clientHeight) * getScaleFactor(wmd.panels.output);\n\t\t\t\t;\n\t\t\t}\n\t\t};\n\t\t\n\t\tthis.refresh = function(requiresRefresh){\n\t\t\n\t\t\tif (requiresRefresh) {\n\t\t\t\toldInputText = \"\";\n\t\t\t\tmakePreviewHtml();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tapplyTimeout();\n\t\t\t}\n\t\t};\n\t\t\n\t\tthis.processingTime = function(){\n\t\t\treturn elapsedTime;\n\t\t};\n\t\t\n\t\t// The output HTML\n\t\tthis.output = function(){\n\t\t\treturn htmlOut;\n\t\t};\n\t\t\n\t\t// The mode can be \"manual\" or \"delayed\"\n\t\tthis.setUpdateMode = function(mode){\n\t\t\tstartType = mode;\n\t\t\tmanagerObj.refresh();\n\t\t};\n\t\t\n\t\tvar isFirstTimeFilled = true;\n\t\t\n\t\tvar pushPreviewHtml = function(text){\n\t\t\n\t\t\tvar emptyTop = position.getTop(wmd.panels.input) - getDocScrollTop();\n\t\t\t\n\t\t\t// Send the encoded HTML to the output textarea/div.\n\t\t\tif (wmd.panels.output) {\n\t\t\t\t// The value property is only defined if the output is a textarea.\n\t\t\t\tif (wmd.panels.output.value !== undefined) {\n\t\t\t\t\twmd.panels.output.value = text;\n\t\t\t\t\twmd.panels.output.readOnly = true;\n\t\t\t\t}\n\t\t\t\t// Otherwise we are just replacing the text in a div.\n\t\t\t\t// Send the HTML wrapped in <pre><code>\n\t\t\t\telse {\n\t\t\t\t\tvar newText = text.replace(/&/g, \"&amp;\");\n\t\t\t\t\tnewText = newText.replace(/</g, \"&lt;\");\n\t\t\t\t\twmd.panels.output.innerHTML = \"<pre><code>\" + newText + \"</code></pre>\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (wmd.panels.preview) {\n\t\t\t\twmd.panels.preview.innerHTML = text;\n\t\t\t}\n\t\t\t\n\t\t\tsetPanelScrollTops();\n\t\t\t\n\t\t\tif (isFirstTimeFilled) {\n\t\t\t\tisFirstTimeFilled = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tvar fullTop = position.getTop(wmd.panels.input) - getDocScrollTop();\n\t\t\t\n\t\t\tif (global.isIE) {\n\t\t\t\ttop.setTimeout(function(){\n\t\t\t\t\ttop.scrollBy(0, fullTop - emptyTop);\n\t\t\t\t}, 0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttop.scrollBy(0, fullTop - emptyTop);\n\t\t\t}\n\t\t};\n\t\t\n\t\tvar init = function(){\n\t\t\n\t\t\tsetupEvents(wmd.panels.input, applyTimeout);\n\t\t\tmakePreviewHtml();\n\t\t\t\n\t\t\tif (wmd.panels.preview) {\n\t\t\t\twmd.panels.preview.scrollTop = 0;\n\t\t\t}\n\t\t\tif (wmd.panels.output) {\n\t\t\t\twmd.panels.output.scrollTop = 0;\n\t\t\t}\n\t\t};\n\t\t\n\t\tthis.destroy = function(){\n\t\t\tif (poller) {\n\t\t\t\tpoller.destroy();\n\t\t\t}\n\t\t};\n\t\t\n\t\tinit();\n\t};\n\n\t// Moves the cursor to the next line and continues lists, quotes and code.\n\tcommand.doAutoindent = function(chunk, postProcessing, useDefaultText){\n\t\t\n\t\tchunk.before = chunk.before.replace(/(\\n|^)[ ]{0,3}([*+-]|\\d+[.])[ \\t]*\\n$/, \"\\n\\n\");\n\t\tchunk.before = chunk.before.replace(/(\\n|^)[ ]{0,3}>[ \\t]*\\n$/, \"\\n\\n\");\n\t\tchunk.before = chunk.before.replace(/(\\n|^)[ \\t]+\\n$/, \"\\n\\n\");\n\t\t\n\t\tuseDefaultText = false;\n\t\t\n\t\tif(/(\\n|^)[ ]{0,3}([*+-])[ \\t]+.*\\n$/.test(chunk.before)){\n\t\t\tif(command.doList){\n\t\t\t\tcommand.doList(chunk, postProcessing, false, true);\n\t\t\t}\n\t\t}\n\t\tif(/(\\n|^)[ ]{0,3}(\\d+[.])[ \\t]+.*\\n$/.test(chunk.before)){\n\t\t\tif(command.doList){\n\t\t\t\tcommand.doList(chunk, postProcessing, true, true);\n\t\t\t}\n\t\t}\n\t\tif(/(\\n|^)[ ]{0,3}>[ \\t]+.*\\n$/.test(chunk.before)){\n\t\t\tif(command.doBlockquote){\n\t\t\t\tcommand.doBlockquote(chunk, postProcessing, useDefaultText);\n\t\t\t}\n\t\t}\n\t\tif(/(\\n|^)(\\t|[ ]{4,}).*\\n$/.test(chunk.before)){\n\t\t\tif(command.doCode){\n\t\t\t\tcommand.doCode(chunk, postProcessing, useDefaultText);\n\t\t\t}\n\t\t}\n\t};\n\t\n\tcommand.doBlockquote = function(chunk, postProcessing, useDefaultText){\n\t\t\n\t\tchunk.selection = chunk.selection.replace(/^(\\n*)([^\\r]+?)(\\n*)$/,\n\t\t\tfunction(totalMatch, newlinesBefore, text, newlinesAfter){\n\t\t\t\tchunk.before += newlinesBefore;\n\t\t\t\tchunk.after = newlinesAfter + chunk.after;\n\t\t\t\treturn text;\n\t\t\t});\n\t\t\t\n\t\tchunk.before = chunk.before.replace(/(>[ \\t]*)$/,\n\t\t\tfunction(totalMatch, blankLine){\n\t\t\t\tchunk.selection = blankLine + chunk.selection;\n\t\t\t\treturn \"\";\n\t\t\t});\n\t\t\n\t\tvar defaultText = useDefaultText ? \"Blockquote\" : \"\";\n\t\tchunk.selection = chunk.selection.replace(/^(\\s|>)+$/ ,\"\");\n\t\tchunk.selection = chunk.selection || defaultText;\n\t\t\n\t\tif(chunk.before){\n\t\t\tchunk.before = chunk.before.replace(/\\n?$/,\"\\n\");\n\t\t}\n\t\tif(chunk.after){\n\t\t\tchunk.after = chunk.after.replace(/^\\n?/,\"\\n\");\n\t\t}\n\t\t\n\t\tchunk.before = chunk.before.replace(/(((\\n|^)(\\n[ \\t]*)*>(.+\\n)*.*)+(\\n[ \\t]*)*$)/,\n\t\t\tfunction(totalMatch){\n\t\t\t\tchunk.startTag = totalMatch;\n\t\t\t\treturn \"\";\n\t\t\t});\n\t\t\t\n\t\tchunk.after = chunk.after.replace(/^(((\\n|^)(\\n[ \\t]*)*>(.+\\n)*.*)+(\\n[ \\t]*)*)/,\n\t\t\tfunction(totalMatch){\n\t\t\t\tchunk.endTag = totalMatch;\n\t\t\t\treturn \"\";\n\t\t\t});\n\t\t\n\t\tvar replaceBlanksInTags = function(useBracket){\n\t\t\t\n\t\t\tvar replacement = useBracket ? \"> \" : \"\";\n\t\t\t\n\t\t\tif(chunk.startTag){\n\t\t\t\tchunk.startTag = chunk.startTag.replace(/\\n((>|\\s)*)\\n$/,\n\t\t\t\t\tfunction(totalMatch, markdown){\n\t\t\t\t\t\treturn \"\\n\" + markdown.replace(/^[ ]{0,3}>?[ \\t]*$/gm, replacement) + \"\\n\";\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tif(chunk.endTag){\n\t\t\t\tchunk.endTag = chunk.endTag.replace(/^\\n((>|\\s)*)\\n/,\n\t\t\t\t\tfunction(totalMatch, markdown){\n\t\t\t\t\t\treturn \"\\n\" + markdown.replace(/^[ ]{0,3}>?[ \\t]*$/gm, replacement) + \"\\n\";\n\t\t\t\t\t});\n\t\t\t}\n\t\t};\n\t\t\n\t\tif(/^(?![ ]{0,3}>)/m.test(chunk.selection)){\n\t\t\tcommand.wrap(chunk, wmd.wmd_env.lineLength - 2);\n\t\t\tchunk.selection = chunk.selection.replace(/^/gm, \"> \");\n\t\t\treplaceBlanksInTags(true);\n\t\t\tchunk.addBlankLines();\n\t\t}\n\t\telse{\n\t\t\tchunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, \"\");\n\t\t\tcommand.unwrap(chunk);\n\t\t\treplaceBlanksInTags(false);\n\t\t\t\n\t\t\tif(!/^(\\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag){\n\t\t\t\tchunk.startTag = chunk.startTag.replace(/\\n{0,2}$/, \"\\n\\n\");\n\t\t\t}\n\t\t\t\n\t\t\tif(!/(\\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag){\n\t\t\t\tchunk.endTag=chunk.endTag.replace(/^\\n{0,2}/, \"\\n\\n\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(!/\\n/.test(chunk.selection)){\n\t\t\tchunk.selection = chunk.selection.replace(/^(> *)/,\n\t\t\tfunction(wholeMatch, blanks){\n\t\t\t\tchunk.startTag += blanks;\n\t\t\t\treturn \"\";\n\t\t\t});\n\t\t}\n\t};\n\n\tcommand.doCode = function(chunk, postProcessing, useDefaultText){\n\t\t\n\t\tvar hasTextBefore = /\\S[ ]*$/.test(chunk.before);\n\t\tvar hasTextAfter = /^[ ]*\\S/.test(chunk.after);\n\t\t\n\t\t// Use 'four space' markdown if the selection is on its own\n\t\t// line or is multiline.\n\t\tif((!hasTextAfter && !hasTextBefore) || /\\n/.test(chunk.selection)){\n\t\t\t\n\t\t\tchunk.before = chunk.before.replace(/[ ]{4}$/,\n\t\t\t\tfunction(totalMatch){\n\t\t\t\t\tchunk.selection = totalMatch + chunk.selection;\n\t\t\t\t\treturn \"\";\n\t\t\t\t});\n\t\t\t\t\n\t\t\tvar nLinesBefore = 1;\n\t\t\tvar nLinesAfter = 1;\n\t\t\t\n\t\t\t\n\t\t\tif(/\\n(\\t|[ ]{4,}).*\\n$/.test(chunk.before) || chunk.after === \"\"){\n\t\t\t\tnLinesBefore = 0; \n\t\t\t}\n\t\t\tif(/^\\n(\\t|[ ]{4,})/.test(chunk.after)){\n\t\t\t\tnLinesAfter = 0; // This needs to happen on line 1\n\t\t\t}\n\t\t\t\n\t\t\tchunk.addBlankLines(nLinesBefore, nLinesAfter);\n\t\t\t\n\t\t\tif(!chunk.selection){\n\t\t\t\tchunk.startTag = \"    \";\n\t\t\t\tchunk.selection = useDefaultText ? \"enter code here\" : \"\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif(/^[ ]{0,3}\\S/m.test(chunk.selection)){\n\t\t\t\t\tchunk.selection = chunk.selection.replace(/^/gm, \"    \");\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tchunk.selection = chunk.selection.replace(/^[ ]{4}/gm, \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\t// Use backticks (`) to delimit the code block.\n\t\t\t\n\t\t\tchunk.trimWhitespace();\n\t\t\tchunk.findTags(/`/, /`/);\n\t\t\t\n\t\t\tif(!chunk.startTag && !chunk.endTag){\n\t\t\t\tchunk.startTag = chunk.endTag=\"`\";\n\t\t\t\tif(!chunk.selection){\n\t\t\t\t\tchunk.selection = useDefaultText ? \"enter code here\" : \"\";\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(chunk.endTag && !chunk.startTag){\n\t\t\t\tchunk.before += chunk.endTag;\n\t\t\t\tchunk.endTag = \"\";\n\t\t\t}\n\t\t\telse{\n\t\t\t\tchunk.startTag = chunk.endTag=\"\";\n\t\t\t}\n\t\t}\n\t};\n\t\n\tcommand.doList = function(chunk, postProcessing, isNumberedList, useDefaultText){\n\t\t\t\t\n\t\t// These are identical except at the very beginning and end.\n\t\t// Should probably use the regex extension function to make this clearer.\n\t\tvar previousItemsRegex = /(\\n|^)(([ ]{0,3}([*+-]|\\d+[.])[ \\t]+.*)(\\n.+|\\n{2,}([*+-].*|\\d+[.])[ \\t]+.*|\\n{2,}[ \\t]+\\S.*)*)\\n*$/;\n\t\tvar nextItemsRegex = /^\\n*(([ ]{0,3}([*+-]|\\d+[.])[ \\t]+.*)(\\n.+|\\n{2,}([*+-].*|\\d+[.])[ \\t]+.*|\\n{2,}[ \\t]+\\S.*)*)\\n*/;\n\t\t\n\t\t// The default bullet is a dash but others are possible.\n\t\t// This has nothing to do with the particular HTML bullet,\n\t\t// it's just a markdown bullet.\n\t\tvar bullet = \"-\";\n\t\t\n\t\t// The number in a numbered list.\n\t\tvar num = 1;\n\t\t\n\t\t// Get the item prefix - e.g. \" 1. \" for a numbered list, \" - \" for a bulleted list.\n\t\tvar getItemPrefix = function(){\n\t\t\tvar prefix;\n\t\t\tif(isNumberedList){\n\t\t\t\tprefix = \" \" + num + \". \";\n\t\t\t\tnum++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tprefix = \" \" + bullet + \" \";\n\t\t\t}\n\t\t\treturn prefix;\n\t\t};\n\t\t\n\t\t// Fixes the prefixes of the other list items.\n\t\tvar getPrefixedItem = function(itemText){\n\t\t\n\t\t\t// The numbering flag is unset when called by autoindent.\n\t\t\tif(isNumberedList === undefined){\n\t\t\t\tisNumberedList = /^\\s*\\d/.test(itemText);\n\t\t\t}\n\t\t\t\n\t\t\t// Renumber/bullet the list element.\n\t\t\titemText = itemText.replace(/^[ ]{0,3}([*+-]|\\d+[.])\\s/gm,\n\t\t\t\tfunction( _ ){\n\t\t\t\t\treturn getItemPrefix();\n\t\t\t\t});\n\t\t\t\t\n\t\t\treturn itemText;\n\t\t};\n\t\t\n\t\tchunk.findTags(/(\\n|^)*[ ]{0,3}([*+-]|\\d+[.])\\s+/, null);\n\t\t\n\t\tif(chunk.before && !/\\n$/.test(chunk.before) && !/^\\n/.test(chunk.startTag)){\n\t\t\tchunk.before += chunk.startTag;\n\t\t\tchunk.startTag = \"\";\n\t\t}\n\t\t\n\t\tif(chunk.startTag){\n\t\t\t\n\t\t\tvar hasDigits = /\\d+[.]/.test(chunk.startTag);\n\t\t\tchunk.startTag = \"\";\n\t\t\tchunk.selection = chunk.selection.replace(/\\n[ ]{4}/g, \"\\n\");\n\t\t\tcommand.unwrap(chunk);\n\t\t\tchunk.addBlankLines();\n\t\t\t\n\t\t\tif(hasDigits){\n\t\t\t\t// Have to renumber the bullet points if this is a numbered list.\n\t\t\t\tchunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);\n\t\t\t}\n\t\t\tif(isNumberedList == hasDigits){\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\tvar nLinesBefore = 1;\n\t\t\n\t\tchunk.before = chunk.before.replace(previousItemsRegex,\n\t\t\tfunction(itemText){\n\t\t\t\tif(/^\\s*([*+-])/.test(itemText)){\n\t\t\t\t\tbullet = re.$1;\n\t\t\t\t}\n\t\t\t\tnLinesBefore = /[^\\n]\\n\\n[^\\n]/.test(itemText) ? 1 : 0;\n\t\t\t\treturn getPrefixedItem(itemText);\n\t\t\t});\n\t\t\t\n\t\tif(!chunk.selection){\n\t\t\tchunk.selection = useDefaultText ? \"List item\" : \" \";\n\t\t}\n\t\t\n\t\tvar prefix = getItemPrefix();\n\t\t\n\t\tvar nLinesAfter = 1;\n\t\t\n\t\tchunk.after = chunk.after.replace(nextItemsRegex,\n\t\t\tfunction(itemText){\n\t\t\t\tnLinesAfter = /[^\\n]\\n\\n[^\\n]/.test(itemText) ? 1 : 0;\n\t\t\t\treturn getPrefixedItem(itemText);\n\t\t\t});\n\t\t\t\n\t\tchunk.trimWhitespace(true);\n\t\tchunk.addBlankLines(nLinesBefore, nLinesAfter, true);\n\t\tchunk.startTag = prefix;\n\t\tvar spaces = prefix.replace(/./g, \" \");\n\t\tcommand.wrap(chunk, wmd.wmd_env.lineLength - spaces.length);\n\t\tchunk.selection = chunk.selection.replace(/\\n/g, \"\\n\" + spaces);\n\t\t\n\t};\n\t\n\tcommand.doHeading = function(chunk, postProcessing, useDefaultText){\n\t\t\n\t\t// Remove leading/trailing whitespace and reduce internal spaces to single spaces.\n\t\tchunk.selection = chunk.selection.replace(/\\s+/g, \" \");\n\t\tchunk.selection = chunk.selection.replace(/(^\\s+|\\s+$)/g, \"\");\n\t\t\n\t\t// If we clicked the button with no selected text, we just\n\t\t// make a level 2 hash header around some default text.\n\t\tif(!chunk.selection){\n\t\t\tchunk.startTag = \"## \";\n\t\t\tchunk.selection = \"Heading\";\n\t\t\tchunk.endTag = \" ##\";\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tvar headerLevel = 0;\t\t// The existing header level of the selected text.\n\t\t\n\t\t// Remove any existing hash heading markdown and save the header level.\n\t\tchunk.findTags(/#+[ ]*/, /[ ]*#+/);\n\t\tif(/#+/.test(chunk.startTag)){\n\t\t\theaderLevel = re.lastMatch.length;\n\t\t}\n\t\tchunk.startTag = chunk.endTag = \"\";\n\t\t\n\t\t// Try to get the current header level by looking for - and = in the line\n\t\t// below the selection.\n\t\tchunk.findTags(null, /\\s?(-+|=+)/);\n\t\tif(/=+/.test(chunk.endTag)){\n\t\t\theaderLevel = 1;\n\t\t}\n\t\tif(/-+/.test(chunk.endTag)){\n\t\t\theaderLevel = 2;\n\t\t}\n\t\t\n\t\t// Skip to the next line so we can create the header markdown.\n\t\tchunk.startTag = chunk.endTag = \"\";\n\t\tchunk.addBlankLines(1, 1);\n\n\t\t// We make a level 2 header if there is no current header.\n\t\t// If there is a header level, we substract one from the header level.\n\t\t// If it's already a level 1 header, it's removed.\n\t\tvar headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;\n\t\t\n\t\tif(headerLevelToCreate > 0){\n\t\t\t\n\t\t\t// The button only creates level 1 and 2 underline headers.\n\t\t\t// Why not have it iterate over hash header levels?  Wouldn't that be easier and cleaner?\n\t\t\tvar headerChar = headerLevelToCreate >= 2 ? \"-\" : \"=\";\n\t\t\tvar len = chunk.selection.length;\n\t\t\tif(len > wmd.wmd_env.lineLength){\n\t\t\t\tlen = wmd.wmd_env.lineLength;\n\t\t\t}\n\t\t\tchunk.endTag = \"\\n\";\n\t\t\twhile(len--){\n\t\t\t\tchunk.endTag += headerChar;\n\t\t\t}\n\t\t}\n\t};\t\n\t\n\tcommand.doHorizontalRule = function(chunk, postProcessing, useDefaultText){\n\t\tchunk.startTag = \"----------\\n\";\n\t\tchunk.selection = \"\";\n\t\tchunk.addBlankLines(2, 1, true);\n\t}\n};\n\n\nAttacklab.wmd_env = {};\nAttacklab.account_options = {};\nAttacklab.wmd_defaults = {version:1, output:\"markdown\", lineLength:40, delayLoad:false};\n\nif(!Attacklab.wmd)\n{\n\tAttacklab.wmd = function()\n\t{\n\t\tAttacklab.loadEnv = function()\n\t\t{\n\t\t\tvar mergeEnv = function(env)\n\t\t\t{\n\t\t\t\tif(!env)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\n\t\t\t\tfor(var key in env)\n\t\t\t\t{\n\t\t\t\t\tAttacklab.wmd_env[key] = env[key];\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t\tmergeEnv(Attacklab.wmd_defaults);\n\t\t\tmergeEnv(Attacklab.account_options);\n\t\t\tmergeEnv(top[\"wmd_options\"]);\n\t\t\tAttacklab.full = true;\n\t\t\t\n\t\t\tvar defaultButtons = \"bold italic link blockquote code image ol ul heading hr\";\n\t\t\tAttacklab.wmd_env.buttons = Attacklab.wmd_env.buttons || defaultButtons;\n\t\t};\n\t\tAttacklab.loadEnv();\n\n\t};\n\t\n\tAttacklab.wmd();\n\tAttacklab.wmdBase();\n\tAttacklab.Util.startEditor();\n};\n\n"
  },
  {
    "path": "libraries/helper.class.php",
    "content": "<?php\nclass Helper {\n\t\n\tprotected $variables = array();\n\tprotected $_action;\n\t\n\t/** Set Variables **/\n\n\n\n\tfunction set($name,$value) {\n\t\t$this->variables[$name] = $value;\n\t}\n\n\t/** Display Template **/\n\t\n    function render() {\n\n\t\t$backtrace = debug_backtrace();\n\t\t$function = strtolower($backtrace[1]['function']);\n\t\t\n\t\textract($this->variables);\n\n\t\t$contents = '';\n\t\t\n\t\tif (file_exists(ROOT . DS . 'views' . DS . 'helpers' . DS . $function . '.php')) {\n\t\t\t$filename = (ROOT . DS . 'views' . DS . 'helpers' . DS . $function . '.php');\t\n\t\t\t\n\t\t\tif (is_file($filename)) {\n\t\t\t\tob_start();\n\t\t\t\tinclude $filename;\n\t\t\t\t$contents = ob_get_contents();\n\t\t\t\tob_end_clean();\n\t\t\t}\n\t\t}\n\n\t\t$this->variables = array();\n\t\t\n\t\treturn $contents;\n\n    }\n\n\t\n\n}\n\nfunction getContent($filename) {\n\n    return false;\n}\n"
  },
  {
    "path": "libraries/markdown.php",
    "content": "<?php\n#\n# Markdown  -  A text-to-HTML conversion tool for web writers\n#\n# PHP Markdown\n# Copyright (c) 2004-2008 Michel Fortin  \n# <http://www.michelf.com/projects/php-markdown/>\n#\n# Original Markdown\n# Copyright (c) 2004-2006 John Gruber  \n# <http://daringfireball.net/projects/markdown/>\n#\n\n\ndefine( 'MARKDOWN_VERSION',  \"1.0.1m\" ); # Sat 21 Jun 2008\n\n\n#\n# Global default settings:\n#\n\n# Change to \">\" for HTML output\n@define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX',  \" />\");\n\n# Define the width of a tab for code blocks.\n@define( 'MARKDOWN_TAB_WIDTH',     4 );\n\n\n#\n# WordPress settings:\n#\n\n# Change to false to remove Markdown from posts and/or comments.\n@define( 'MARKDOWN_WP_POSTS',      true );\n@define( 'MARKDOWN_WP_COMMENTS',   true );\n\n\n\n### Standard Function Interface ###\n\n@define( 'MARKDOWN_PARSER_CLASS',  'Markdown_Parser' );\n\nfunction Markdown($text) {\n#\n# Initialize the parser and return the result of its transform method.\n#\n\t# Setup static parser variable.\n\tstatic $parser;\n\tif (!isset($parser)) {\n\t\t$parser_class = MARKDOWN_PARSER_CLASS;\n\t\t$parser = new $parser_class;\n\t}\n\n\t# Transform text using parser.\n\treturn $parser->transform($text);\n}\n\n\n### WordPress Plugin Interface ###\n\n/*\nPlugin Name: Markdown\nPlugin URI: http://www.michelf.com/projects/php-markdown/\nDescription: <a href=\"http://daringfireball.net/projects/markdown/syntax\">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href=\"http://daringfireball.net/\">John Gruber</a>. <a href=\"http://www.michelf.com/projects/php-markdown/\">More...</a>\nVersion: 1.0.1m\nAuthor: Michel Fortin\nAuthor URI: http://www.michelf.com/\n*/\n\nif (isset($wp_version)) {\n\t# More details about how it works here:\n\t# <http://www.michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>\n\t\n\t# Post content and excerpts\n\t# - Remove WordPress paragraph generator.\n\t# - Run Markdown on excerpt, then remove all tags.\n\t# - Add paragraph tag around the excerpt, but remove it for the excerpt rss.\n\tif (MARKDOWN_WP_POSTS) {\n\t\tremove_filter('the_content',     'wpautop');\n        remove_filter('the_content_rss', 'wpautop');\n\t\tremove_filter('the_excerpt',     'wpautop');\n\t\tadd_filter('the_content',     'Markdown', 6);\n        add_filter('the_content_rss', 'Markdown', 6);\n\t\tadd_filter('get_the_excerpt', 'Markdown', 6);\n\t\tadd_filter('get_the_excerpt', 'trim', 7);\n\t\tadd_filter('the_excerpt',     'mdwp_add_p');\n\t\tadd_filter('the_excerpt_rss', 'mdwp_strip_p');\n\t\t\n\t\tremove_filter('content_save_pre',  'balanceTags', 50);\n\t\tremove_filter('excerpt_save_pre',  'balanceTags', 50);\n\t\tadd_filter('the_content',  \t  'balanceTags', 50);\n\t\tadd_filter('get_the_excerpt', 'balanceTags', 9);\n\t}\n\t\n\t# Comments\n\t# - Remove WordPress paragraph generator.\n\t# - Remove WordPress auto-link generator.\n\t# - Scramble important tags before passing them to the kses filter.\n\t# - Run Markdown on excerpt then remove paragraph tags.\n\tif (MARKDOWN_WP_COMMENTS) {\n\t\tremove_filter('comment_text', 'wpautop', 30);\n\t\tremove_filter('comment_text', 'make_clickable');\n\t\tadd_filter('pre_comment_content', 'Markdown', 6);\n\t\tadd_filter('pre_comment_content', 'mdwp_hide_tags', 8);\n\t\tadd_filter('pre_comment_content', 'mdwp_show_tags', 12);\n\t\tadd_filter('get_comment_text',    'Markdown', 6);\n\t\tadd_filter('get_comment_excerpt', 'Markdown', 6);\n\t\tadd_filter('get_comment_excerpt', 'mdwp_strip_p', 7);\n\t\n\t\tglobal $mdwp_hidden_tags, $mdwp_placeholders;\n\t\t$mdwp_hidden_tags = explode(' ',\n\t\t\t'<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');\n\t\t$mdwp_placeholders = explode(' ', str_rot13(\n\t\t\t'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.\n\t\t\t'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));\n\t}\n\t\n\tfunction mdwp_add_p($text) {\n\t\tif (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {\n\t\t\t$text = '<p>'.$text.'</p>';\n\t\t\t$text = preg_replace('{\\n{2,}}', \"</p>\\n\\n<p>\", $text);\n\t\t}\n\t\treturn $text;\n\t}\n\t\n\tfunction mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }\n\n\tfunction mdwp_hide_tags($text) {\n\t\tglobal $mdwp_hidden_tags, $mdwp_placeholders;\n\t\treturn str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);\n\t}\n\tfunction mdwp_show_tags($text) {\n\t\tglobal $mdwp_hidden_tags, $mdwp_placeholders;\n\t\treturn str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);\n\t}\n}\n\n\n### bBlog Plugin Info ###\n\nfunction identify_modifier_markdown() {\n\treturn array(\n\t\t'name'\t\t\t=> 'markdown',\n\t\t'type'\t\t\t=> 'modifier',\n\t\t'nicename'\t\t=> 'Markdown',\n\t\t'description'\t=> 'A text-to-HTML conversion tool for web writers',\n\t\t'authors'\t\t=> 'Michel Fortin and John Gruber',\n\t\t'licence'\t\t=> 'BSD-like',\n\t\t'version'\t\t=> MARKDOWN_VERSION,\n\t\t'help'\t\t\t=> '<a href=\"http://daringfireball.net/projects/markdown/syntax\">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href=\"http://daringfireball.net/\">John Gruber</a>. <a href=\"http://www.michelf.com/projects/php-markdown/\">More...</a>'\n\t);\n}\n\n\n### Smarty Modifier Interface ###\n\nfunction smarty_modifier_markdown($text) {\n\treturn Markdown($text);\n}\n\n\n### Textile Compatibility Mode ###\n\n# Rename this file to \"classTextile.php\" and it can replace Textile everywhere.\n\nif (strcasecmp(substr(__FILE__, -16), \"classTextile.php\") == 0) {\n\t# Try to include PHP SmartyPants. Should be in the same directory.\n\t@include_once 'smartypants.php';\n\t# Fake Textile class. It calls Markdown instead.\n\tclass Textile {\n\t\tfunction TextileThis($text, $lite='', $encode='') {\n\t\t\tif ($lite == '' && $encode == '')    $text = Markdown($text);\n\t\t\tif (function_exists('SmartyPants'))  $text = SmartyPants($text);\n\t\t\treturn $text;\n\t\t}\n\t\t# Fake restricted version: restrictions are not supported for now.\n\t\tfunction TextileRestricted($text, $lite='', $noimage='') {\n\t\t\treturn $this->TextileThis($text, $lite);\n\t\t}\n\t\t# Workaround to ensure compatibility with TextPattern 4.0.3.\n\t\tfunction blockLite($text) { return $text; }\n\t}\n}\n\n\n\n#\n# Markdown Parser Class\n#\n\nclass Markdown_Parser {\n\n\t# Regex to match balanced [brackets].\n\t# Needed to insert a maximum bracked depth while converting to PHP.\n\tvar $nested_brackets_depth = 6;\n\tvar $nested_brackets_re;\n\t\n\tvar $nested_url_parenthesis_depth = 4;\n\tvar $nested_url_parenthesis_re;\n\n\t# Table of hash values for escaped characters:\n\tvar $escape_chars = '\\`*_{}[]()>#+-.!';\n\tvar $escape_chars_re;\n\n\t# Change to \">\" for HTML output.\n\tvar $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;\n\tvar $tab_width = MARKDOWN_TAB_WIDTH;\n\t\n\t# Change to `true` to disallow markup or entities.\n\tvar $no_markup = false;\n\tvar $no_entities = false;\n\t\n\t# Predefined urls and titles for reference links and images.\n\tvar $predef_urls = array();\n\tvar $predef_titles = array();\n\n\n\tfunction Markdown_Parser() {\n\t#\n\t# Constructor function. Initialize appropriate member variables.\n\t#\n\t\t$this->_initDetab();\n\t\t$this->prepareItalicsAndBold();\n\t\n\t\t$this->nested_brackets_re = \n\t\t\tstr_repeat('(?>[^\\[\\]]+|\\[', $this->nested_brackets_depth).\n\t\t\tstr_repeat('\\])*', $this->nested_brackets_depth);\n\t\n\t\t$this->nested_url_parenthesis_re = \n\t\t\tstr_repeat('(?>[^()\\s]+|\\(', $this->nested_url_parenthesis_depth).\n\t\t\tstr_repeat('(?>\\)))*', $this->nested_url_parenthesis_depth);\n\t\t\n\t\t$this->escape_chars_re = '['.preg_quote($this->escape_chars).']';\n\t\t\n\t\t# Sort document, block, and span gamut in ascendent priority order.\n\t\tasort($this->document_gamut);\n\t\tasort($this->block_gamut);\n\t\tasort($this->span_gamut);\n\t}\n\n\n\t# Internal hashes used during transformation.\n\tvar $urls = array();\n\tvar $titles = array();\n\tvar $html_hashes = array();\n\t\n\t# Status flag to avoid invalid nesting.\n\tvar $in_anchor = false;\n\t\n\t\n\tfunction setup() {\n\t#\n\t# Called before the transformation process starts to setup parser \n\t# states.\n\t#\n\t\t# Clear global hashes.\n\t\t$this->urls = $this->predef_urls;\n\t\t$this->titles = $this->predef_titles;\n\t\t$this->html_hashes = array();\n\t\t\n\t\t$in_anchor = false;\n\t}\n\t\n\tfunction teardown() {\n\t#\n\t# Called after the transformation process to clear any variable \n\t# which may be taking up memory unnecessarly.\n\t#\n\t\t$this->urls = array();\n\t\t$this->titles = array();\n\t\t$this->html_hashes = array();\n\t}\n\n\n\tfunction transform($text) {\n\t#\n\t# Main function. Performs some preprocessing on the input text\n\t# and pass it through the document gamut.\n\t#\n\t\t$this->setup();\n\t\n\t\t# Remove UTF-8 BOM and marker character in input, if present.\n\t\t$text = preg_replace('{^\\xEF\\xBB\\xBF|\\x1A}', '', $text);\n\n\t\t# Standardize line endings:\n\t\t#   DOS to Unix and Mac to Unix\n\t\t$text = preg_replace('{\\r\\n?}', \"\\n\", $text);\n\n\t\t# Make sure $text ends with a couple of newlines:\n\t\t$text .= \"\\n\\n\";\n\n\t\t# Convert all tabs to spaces.\n\t\t$text = $this->detab($text);\n\n\t\t# Turn block-level HTML blocks into hash entries\n\t\t$text = $this->hashHTMLBlocks($text);\n\n\t\t# Strip any lines consisting only of spaces and tabs.\n\t\t# This makes subsequent regexen easier to write, because we can\n\t\t# match consecutive blank lines with /\\n+/ instead of something\n\t\t# contorted like /[ ]*\\n+/ .\n\t\t$text = preg_replace('/^[ ]+$/m', '', $text);\n\n\t\t# Run document gamut methods.\n\t\tforeach ($this->document_gamut as $method => $priority) {\n\t\t\t$text = $this->$method($text);\n\t\t}\n\t\t\n\t\t$this->teardown();\n\n\t\treturn $text . \"\\n\";\n\t}\n\t\n\tvar $document_gamut = array(\n\t\t# Strip link definitions, store in hashes.\n\t\t\"stripLinkDefinitions\" => 20,\n\t\t\n\t\t\"runBasicBlockGamut\"   => 30,\n\t\t);\n\n\n\tfunction stripLinkDefinitions($text) {\n\t#\n\t# Strips link definitions from text, stores the URLs and titles in\n\t# hash references.\n\t#\n\t\t$less_than_tab = $this->tab_width - 1;\n\n\t\t# Link defs are in the form: ^[id]: url \"optional title\"\n\t\t$text = preg_replace_callback('{\n\t\t\t\t\t\t\t^[ ]{0,'.$less_than_tab.'}\\[(.+)\\][ ]?:\t# id = $1\n\t\t\t\t\t\t\t  [ ]*\n\t\t\t\t\t\t\t  \\n?\t\t\t\t# maybe *one* newline\n\t\t\t\t\t\t\t  [ ]*\n\t\t\t\t\t\t\t<?(\\S+?)>?\t\t\t# url = $2\n\t\t\t\t\t\t\t  [ ]*\n\t\t\t\t\t\t\t  \\n?\t\t\t\t# maybe one newline\n\t\t\t\t\t\t\t  [ ]*\n\t\t\t\t\t\t\t(?:\n\t\t\t\t\t\t\t\t(?<=\\s)\t\t\t# lookbehind for whitespace\n\t\t\t\t\t\t\t\t[\"(]\n\t\t\t\t\t\t\t\t(.*?)\t\t\t# title = $3\n\t\t\t\t\t\t\t\t[\")]\n\t\t\t\t\t\t\t\t[ ]*\n\t\t\t\t\t\t\t)?\t# title is optional\n\t\t\t\t\t\t\t(?:\\n+|\\Z)\n\t\t\t}xm',\n\t\t\tarray(&$this, '_stripLinkDefinitions_callback'),\n\t\t\t$text);\n\t\treturn $text;\n\t}\n\tfunction _stripLinkDefinitions_callback($matches) {\n\t\t$link_id = strtolower($matches[1]);\n\t\t$this->urls[$link_id] = $matches[2];\n\t\t$this->titles[$link_id] =& $matches[3];\n\t\treturn ''; # String that will replace the block\n\t}\n\n\n\tfunction hashHTMLBlocks($text) {\n\t\tif ($this->no_markup)  return $text;\n\n\t\t$less_than_tab = $this->tab_width - 1;\n\n\t\t# Hashify HTML blocks:\n\t\t# We only want to do this for block-level HTML tags, such as headers,\n\t\t# lists, and tables. That's because we still want to wrap <p>s around\n\t\t# \"paragraphs\" that are wrapped in non-block-level tags, such as anchors,\n\t\t# phrase emphasis, and spans. The list of tags we're looking for is\n\t\t# hard-coded:\n\t\t#\n\t\t# *  List \"a\" is made of tags which can be both inline or block-level.\n\t\t#    These will be treated block-level when the start tag is alone on \n\t\t#    its line, otherwise they're not matched here and will be taken as \n\t\t#    inline later.\n\t\t# *  List \"b\" is made of tags which are always block-level;\n\t\t#\n\t\t$block_tags_a_re = 'ins|del';\n\t\t$block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.\n\t\t\t\t\t\t   'script|noscript|form|fieldset|iframe|math';\n\n\t\t# Regular expression for the content of a block tag.\n\t\t$nested_tags_level = 4;\n\t\t$attr = '\n\t\t\t(?>\t\t\t\t# optional tag attributes\n\t\t\t  \\s\t\t\t# starts with whitespace\n\t\t\t  (?>\n\t\t\t\t[^>\"/]+\t\t# text outside quotes\n\t\t\t  |\n\t\t\t\t/+(?!>)\t\t# slash not followed by \">\"\n\t\t\t  |\n\t\t\t\t\"[^\"]*\"\t\t# text inside double quotes (tolerate \">\")\n\t\t\t  |\n\t\t\t\t\\'[^\\']*\\'\t# text inside single quotes (tolerate \">\")\n\t\t\t  )*\n\t\t\t)?\t\n\t\t\t';\n\t\t$content =\n\t\t\tstr_repeat('\n\t\t\t\t(?>\n\t\t\t\t  [^<]+\t\t\t# content without tag\n\t\t\t\t|\n\t\t\t\t  <\\2\t\t\t# nested opening tag\n\t\t\t\t\t'.$attr.'\t# attributes\n\t\t\t\t\t(?>\n\t\t\t\t\t  />\n\t\t\t\t\t|\n\t\t\t\t\t  >', $nested_tags_level).\t# end of opening tag\n\t\t\t\t\t  '.*?'.\t\t\t\t\t# last level nested tag content\n\t\t\tstr_repeat('\n\t\t\t\t\t  </\\2\\s*>\t# closing nested tag\n\t\t\t\t\t)\n\t\t\t\t  |\t\t\t\t\n\t\t\t\t\t<(?!/\\2\\s*>\t# other tags with a different name\n\t\t\t\t  )\n\t\t\t\t)*',\n\t\t\t\t$nested_tags_level);\n\t\t$content2 = str_replace('\\2', '\\3', $content);\n\n\t\t# First, look for nested blocks, e.g.:\n\t\t# \t<div>\n\t\t# \t\t<div>\n\t\t# \t\ttags for inner block must be indented.\n\t\t# \t\t</div>\n\t\t# \t</div>\n\t\t#\n\t\t# The outermost tags must start at the left margin for this to match, and\n\t\t# the inner nested divs must be indented.\n\t\t# We need to do this before the next, more liberal match, because the next\n\t\t# match will start at the first `<div>` and stop at the first `</div>`.\n\t\t$text = preg_replace_callback('{(?>\n\t\t\t(?>\n\t\t\t\t(?<=\\n\\n)\t\t# Starting after a blank line\n\t\t\t\t|\t\t\t\t# or\n\t\t\t\t\\A\\n?\t\t\t# the beginning of the doc\n\t\t\t)\n\t\t\t(\t\t\t\t\t\t# save in $1\n\n\t\t\t  # Match from `\\n<tag>` to `</tag>\\n`, handling nested tags \n\t\t\t  # in between.\n\t\t\t\t\t\n\t\t\t\t\t\t[ ]{0,'.$less_than_tab.'}\n\t\t\t\t\t\t<('.$block_tags_b_re.')# start tag = $2\n\t\t\t\t\t\t'.$attr.'>\t\t\t# attributes followed by > and \\n\n\t\t\t\t\t\t'.$content.'\t\t# content, support nesting\n\t\t\t\t\t\t</\\2>\t\t\t\t# the matching end tag\n\t\t\t\t\t\t[ ]*\t\t\t\t# trailing spaces/tabs\n\t\t\t\t\t\t(?=\\n+|\\Z)\t# followed by a newline or end of document\n\n\t\t\t| # Special version for tags of group a.\n\n\t\t\t\t\t\t[ ]{0,'.$less_than_tab.'}\n\t\t\t\t\t\t<('.$block_tags_a_re.')# start tag = $3\n\t\t\t\t\t\t'.$attr.'>[ ]*\\n\t# attributes followed by >\n\t\t\t\t\t\t'.$content2.'\t\t# content, support nesting\n\t\t\t\t\t\t</\\3>\t\t\t\t# the matching end tag\n\t\t\t\t\t\t[ ]*\t\t\t\t# trailing spaces/tabs\n\t\t\t\t\t\t(?=\\n+|\\Z)\t# followed by a newline or end of document\n\t\t\t\t\t\n\t\t\t| # Special case just for <hr />. It was easier to make a special \n\t\t\t  # case than to make the other regex more complicated.\n\t\t\t\n\t\t\t\t\t\t[ ]{0,'.$less_than_tab.'}\n\t\t\t\t\t\t<(hr)\t\t\t\t# start tag = $2\n\t\t\t\t\t\t'.$attr.'\t\t\t# attributes\n\t\t\t\t\t\t/?>\t\t\t\t\t# the matching end tag\n\t\t\t\t\t\t[ ]*\n\t\t\t\t\t\t(?=\\n{2,}|\\Z)\t\t# followed by a blank line or end of document\n\t\t\t\n\t\t\t| # Special case for standalone HTML comments:\n\t\t\t\n\t\t\t\t\t[ ]{0,'.$less_than_tab.'}\n\t\t\t\t\t(?s:\n\t\t\t\t\t\t<!-- .*? -->\n\t\t\t\t\t)\n\t\t\t\t\t[ ]*\n\t\t\t\t\t(?=\\n{2,}|\\Z)\t\t# followed by a blank line or end of document\n\t\t\t\n\t\t\t| # PHP and ASP-style processor instructions (<? and <%)\n\t\t\t\n\t\t\t\t\t[ ]{0,'.$less_than_tab.'}\n\t\t\t\t\t(?s:\n\t\t\t\t\t\t<([?%])\t\t\t# $2\n\t\t\t\t\t\t.*?\n\t\t\t\t\t\t\\2>\n\t\t\t\t\t)\n\t\t\t\t\t[ ]*\n\t\t\t\t\t(?=\\n{2,}|\\Z)\t\t# followed by a blank line or end of document\n\t\t\t\t\t\n\t\t\t)\n\t\t\t)}Sxmi',\n\t\t\tarray(&$this, '_hashHTMLBlocks_callback'),\n\t\t\t$text);\n\n\t\treturn $text;\n\t}\n\tfunction _hashHTMLBlocks_callback($matches) {\n\t\t$text = $matches[1];\n\t\t$key  = $this->hashBlock($text);\n\t\treturn \"\\n\\n$key\\n\\n\";\n\t}\n\t\n\t\n\tfunction hashPart($text, $boundary = 'X') {\n\t#\n\t# Called whenever a tag must be hashed when a function insert an atomic \n\t# element in the text stream. Passing $text to through this function gives\n\t# a unique text-token which will be reverted back when calling unhash.\n\t#\n\t# The $boundary argument specify what character should be used to surround\n\t# the token. By convension, \"B\" is used for block elements that needs not\n\t# to be wrapped into paragraph tags at the end, \":\" is used for elements\n\t# that are word separators and \"X\" is used in the general case.\n\t#\n\t\t# Swap back any tag hash found in $text so we do not have to `unhash`\n\t\t# multiple times at the end.\n\t\t$text = $this->unhash($text);\n\t\t\n\t\t# Then hash the block.\n\t\tstatic $i = 0;\n\t\t$key = \"$boundary\\x1A\" . ++$i . $boundary;\n\t\t$this->html_hashes[$key] = $text;\n\t\treturn $key; # String that will replace the tag.\n\t}\n\n\n\tfunction hashBlock($text) {\n\t#\n\t# Shortcut function for hashPart with block-level boundaries.\n\t#\n\t\treturn $this->hashPart($text, 'B');\n\t}\n\n\n\tvar $block_gamut = array(\n\t#\n\t# These are all the transformations that form block-level\n\t# tags like paragraphs, headers, and list items.\n\t#\n\t\t\"doHeaders\"         => 10,\n\t\t\"doHorizontalRules\" => 20,\n\t\t\n\t\t\"doLists\"           => 40,\n\t\t\"doCodeBlocks\"      => 50,\n\t\t\"doBlockQuotes\"     => 60,\n\t\t);\n\n\tfunction runBlockGamut($text) {\n\t#\n\t# Run block gamut tranformations.\n\t#\n\t\t# We need to escape raw HTML in Markdown source before doing anything \n\t\t# else. This need to be done for each block, and not only at the \n\t\t# begining in the Markdown function since hashed blocks can be part of\n\t\t# list items and could have been indented. Indented blocks would have \n\t\t# been seen as a code block in a previous pass of hashHTMLBlocks.\n\t\t$text = $this->hashHTMLBlocks($text);\n\t\t\n\t\treturn $this->runBasicBlockGamut($text);\n\t}\n\t\n\tfunction runBasicBlockGamut($text) {\n\t#\n\t# Run block gamut tranformations, without hashing HTML blocks. This is \n\t# useful when HTML blocks are known to be already hashed, like in the first\n\t# whole-document pass.\n\t#\n\t\tforeach ($this->block_gamut as $method => $priority) {\n\t\t\t$text = $this->$method($text);\n\t\t}\n\t\t\n\t\t# Finally form paragraph and restore hashed blocks.\n\t\t$text = $this->formParagraphs($text);\n\n\t\treturn $text;\n\t}\n\t\n\t\n\tfunction doHorizontalRules($text) {\n\t\t# Do Horizontal Rules:\n\t\treturn preg_replace(\n\t\t\t'{\n\t\t\t\t^[ ]{0,3}\t# Leading space\n\t\t\t\t([-*_])\t\t# $1: First marker\n\t\t\t\t(?>\t\t\t# Repeated marker group\n\t\t\t\t\t[ ]{0,2}\t# Zero, one, or two spaces.\n\t\t\t\t\t\\1\t\t\t# Marker character\n\t\t\t\t){2,}\t\t# Group repeated at least twice\n\t\t\t\t[ ]*\t\t# Tailing spaces\n\t\t\t\t$\t\t\t# End of line.\n\t\t\t}mx',\n\t\t\t\"\\n\".$this->hashBlock(\"<hr$this->empty_element_suffix\").\"\\n\", \n\t\t\t$text);\n\t}\n\n\n\tvar $span_gamut = array(\n\t#\n\t# These are all the transformations that occur *within* block-level\n\t# tags like paragraphs, headers, and list items.\n\t#\n\t\t# Process character escapes, code spans, and inline HTML\n\t\t# in one shot.\n\t\t\"parseSpan\"           => -30,\n\n\t\t# Process anchor and image tags. Images must come first,\n\t\t# because ![foo][f] looks like an anchor.\n\t\t\"doImages\"            =>  10,\n\t\t\"doAnchors\"           =>  20,\n\t\t\n\t\t# Make links out of things like `<http://example.com/>`\n\t\t# Must come after doAnchors, because you can use < and >\n\t\t# delimiters in inline links like [this](<url>).\n\t\t\"doAutoLinks\"         =>  30,\n\t\t\"encodeAmpsAndAngles\" =>  40,\n\n\t\t\"doItalicsAndBold\"    =>  50,\n\t\t\"doHardBreaks\"        =>  60,\n\t\t);\n\n\tfunction runSpanGamut($text) {\n\t#\n\t# Run span gamut tranformations.\n\t#\n\t\tforeach ($this->span_gamut as $method => $priority) {\n\t\t\t$text = $this->$method($text);\n\t\t}\n\n\t\treturn $text;\n\t}\n\t\n\t\n\tfunction doHardBreaks($text) {\n\t\t# Do hard breaks:\n\t\treturn preg_replace_callback('/ {2,}\\n/', \n\t\t\tarray(&$this, '_doHardBreaks_callback'), $text);\n\t}\n\tfunction _doHardBreaks_callback($matches) {\n\t\treturn $this->hashPart(\"<br$this->empty_element_suffix\\n\");\n\t}\n\n\n\tfunction doAnchors($text) {\n\t#\n\t# Turn Markdown link shortcuts into XHTML <a> tags.\n\t#\n\t\tif ($this->in_anchor) return $text;\n\t\t$this->in_anchor = true;\n\t\t\n\t\t#\n\t\t# First, handle reference-style links: [link text] [id]\n\t\t#\n\t\t$text = preg_replace_callback('{\n\t\t\t(\t\t\t\t\t# wrap whole match in $1\n\t\t\t  \\[\n\t\t\t\t('.$this->nested_brackets_re.')\t# link text = $2\n\t\t\t  \\]\n\n\t\t\t  [ ]?\t\t\t\t# one optional space\n\t\t\t  (?:\\n[ ]*)?\t\t# one optional newline followed by spaces\n\n\t\t\t  \\[\n\t\t\t\t(.*?)\t\t# id = $3\n\t\t\t  \\]\n\t\t\t)\n\t\t\t}xs',\n\t\t\tarray(&$this, '_doAnchors_reference_callback'), $text);\n\n\t\t#\n\t\t# Next, inline-style links: [link text](url \"optional title\")\n\t\t#\n\t\t$text = preg_replace_callback('{\n\t\t\t(\t\t\t\t# wrap whole match in $1\n\t\t\t  \\[\n\t\t\t\t('.$this->nested_brackets_re.')\t# link text = $2\n\t\t\t  \\]\n\t\t\t  \\(\t\t\t# literal paren\n\t\t\t\t[ ]*\n\t\t\t\t(?:\n\t\t\t\t\t<(\\S*)>\t# href = $3\n\t\t\t\t|\n\t\t\t\t\t('.$this->nested_url_parenthesis_re.')\t# href = $4\n\t\t\t\t)\n\t\t\t\t[ ]*\n\t\t\t\t(\t\t\t# $5\n\t\t\t\t  ([\\'\"])\t# quote char = $6\n\t\t\t\t  (.*?)\t\t# Title = $7\n\t\t\t\t  \\6\t\t# matching quote\n\t\t\t\t  [ ]*\t# ignore any spaces/tabs between closing quote and )\n\t\t\t\t)?\t\t\t# title is optional\n\t\t\t  \\)\n\t\t\t)\n\t\t\t}xs',\n\t\t\tarray(&$this, '_DoAnchors_inline_callback'), $text);\n\n\t\t#\n\t\t# Last, handle reference-style shortcuts: [link text]\n\t\t# These must come last in case you've also got [link test][1]\n\t\t# or [link test](/foo)\n\t\t#\n//\t\t$text = preg_replace_callback('{\n//\t\t\t(\t\t\t\t\t# wrap whole match in $1\n//\t\t\t  \\[\n//\t\t\t\t([^\\[\\]]+)\t\t# link text = $2; can\\'t contain [ or ]\n//\t\t\t  \\]\n//\t\t\t)\n//\t\t\t}xs',\n//\t\t\tarray(&$this, '_doAnchors_reference_callback'), $text);\n\n\t\t$this->in_anchor = false;\n\t\treturn $text;\n\t}\n\tfunction _doAnchors_reference_callback($matches) {\n\t\t$whole_match =  $matches[1];\n\t\t$link_text   =  $matches[2];\n\t\t$link_id     =& $matches[3];\n\n\t\tif ($link_id == \"\") {\n\t\t\t# for shortcut links like [this][] or [this].\n\t\t\t$link_id = $link_text;\n\t\t}\n\t\t\n\t\t# lower-case and turn embedded newlines into spaces\n\t\t$link_id = strtolower($link_id);\n\t\t$link_id = preg_replace('{[ ]?\\n}', ' ', $link_id);\n\n\t\tif (isset($this->urls[$link_id])) {\n\t\t\t$url = $this->urls[$link_id];\n\t\t\t$url = $this->encodeAttribute($url);\n\t\t\t\n\t\t\t$result = \"<a href=\\\"$url\\\"\";\n\t\t\tif ( isset( $this->titles[$link_id] ) ) {\n\t\t\t\t$title = $this->titles[$link_id];\n\t\t\t\t$title = $this->encodeAttribute($title);\n\t\t\t\t$result .=  \" title=\\\"$title\\\"\";\n\t\t\t}\n\t\t\n\t\t\t$link_text = $this->runSpanGamut($link_text);\n\t\t\t$result .= \">$link_text</a>\";\n\t\t\t$result = $this->hashPart($result);\n\t\t}\n\t\telse {\n\t\t\t$result = $whole_match;\n\t\t}\n\t\treturn $result;\n\t}\n\tfunction _doAnchors_inline_callback($matches) {\n\t\t$whole_match\t=  $matches[1];\n\t\t$link_text\t\t=  $this->runSpanGamut($matches[2]);\n\t\t$url\t\t\t=  $matches[3] == '' ? $matches[4] : $matches[3];\n\t\t$title\t\t\t=& $matches[7];\n\n\t\t$url = $this->encodeAttribute($url);\n\n\t\t$result = \"<a href=\\\"$url\\\"\";\n\t\tif (isset($title)) {\n\t\t\t$title = $this->encodeAttribute($title);\n\t\t\t$result .=  \" title=\\\"$title\\\"\";\n\t\t}\n\t\t\n\t\t$link_text = $this->runSpanGamut($link_text);\n\t\t$result .= \">$link_text</a>\";\n\n\t\treturn $this->hashPart($result);\n\t}\n\n\n\tfunction doImages($text) {\n\t#\n\t# Turn Markdown image shortcuts into <img> tags.\n\t#\n\t\t#\n\t\t# First, handle reference-style labeled images: ![alt text][id]\n\t\t#\n\t\t$text = preg_replace_callback('{\n\t\t\t(\t\t\t\t# wrap whole match in $1\n\t\t\t  !\\[\n\t\t\t\t('.$this->nested_brackets_re.')\t\t# alt text = $2\n\t\t\t  \\]\n\n\t\t\t  [ ]?\t\t\t\t# one optional space\n\t\t\t  (?:\\n[ ]*)?\t\t# one optional newline followed by spaces\n\n\t\t\t  \\[\n\t\t\t\t(.*?)\t\t# id = $3\n\t\t\t  \\]\n\n\t\t\t)\n\t\t\t}xs', \n\t\t\tarray(&$this, '_doImages_reference_callback'), $text);\n\n\t\t#\n\t\t# Next, handle inline images:  ![alt text](url \"optional title\")\n\t\t# Don't forget: encode * and _\n\t\t#\n\t\t$text = preg_replace_callback('{\n\t\t\t(\t\t\t\t# wrap whole match in $1\n\t\t\t  !\\[\n\t\t\t\t('.$this->nested_brackets_re.')\t\t# alt text = $2\n\t\t\t  \\]\n\t\t\t  \\s?\t\t\t# One optional whitespace character\n\t\t\t  \\(\t\t\t# literal paren\n\t\t\t\t[ ]*\n\t\t\t\t(?:\n\t\t\t\t\t<(\\S*)>\t# src url = $3\n\t\t\t\t|\n\t\t\t\t\t('.$this->nested_url_parenthesis_re.')\t# src url = $4\n\t\t\t\t)\n\t\t\t\t[ ]*\n\t\t\t\t(\t\t\t# $5\n\t\t\t\t  ([\\'\"])\t# quote char = $6\n\t\t\t\t  (.*?)\t\t# title = $7\n\t\t\t\t  \\6\t\t# matching quote\n\t\t\t\t  [ ]*\n\t\t\t\t)?\t\t\t# title is optional\n\t\t\t  \\)\n\t\t\t)\n\t\t\t}xs',\n\t\t\tarray(&$this, '_doImages_inline_callback'), $text);\n\n\t\treturn $text;\n\t}\n\tfunction _doImages_reference_callback($matches) {\n\t\t$whole_match = $matches[1];\n\t\t$alt_text    = $matches[2];\n\t\t$link_id     = strtolower($matches[3]);\n\n\t\tif ($link_id == \"\") {\n\t\t\t$link_id = strtolower($alt_text); # for shortcut links like ![this][].\n\t\t}\n\n\t\t$alt_text = $this->encodeAttribute($alt_text);\n\t\tif (isset($this->urls[$link_id])) {\n\t\t\t$url = $this->encodeAttribute($this->urls[$link_id]);\n\t\t\t$result = \"<img src=\\\"$url\\\" alt=\\\"$alt_text\\\"\";\n\t\t\tif (isset($this->titles[$link_id])) {\n\t\t\t\t$title = $this->titles[$link_id];\n\t\t\t\t$title = $this->encodeAttribute($title);\n\t\t\t\t$result .=  \" title=\\\"$title\\\"\";\n\t\t\t}\n\t\t\t$result .= $this->empty_element_suffix;\n\t\t\t$result = $this->hashPart($result);\n\t\t}\n\t\telse {\n\t\t\t# If there's no such link ID, leave intact:\n\t\t\t$result = $whole_match;\n\t\t}\n\n\t\treturn $result;\n\t}\n\tfunction _doImages_inline_callback($matches) {\n\t\t$whole_match\t= $matches[1];\n\t\t$alt_text\t\t= $matches[2];\n\t\t$url\t\t\t= $matches[3] == '' ? $matches[4] : $matches[3];\n\t\t$title\t\t\t=& $matches[7];\n\n\t\t$alt_text = $this->encodeAttribute($alt_text);\n\t\t$url = $this->encodeAttribute($url);\n\t\t$result = \"<img src=\\\"$url\\\" alt=\\\"$alt_text\\\"\";\n\t\tif (isset($title)) {\n\t\t\t$title = $this->encodeAttribute($title);\n\t\t\t$result .=  \" title=\\\"$title\\\"\"; # $title already quoted\n\t\t}\n\t\t$result .= $this->empty_element_suffix;\n\n\t\treturn $this->hashPart($result);\n\t}\n\n\n\tfunction doHeaders($text) {\n\t\t# Setext-style headers:\n\t\t#\t  Header 1\n\t\t#\t  ========\n\t\t#  \n\t\t#\t  Header 2\n\t\t#\t  --------\n\t\t#\n\t\t$text = preg_replace_callback('{ ^(.+?)[ ]*\\n(=+|-+)[ ]*\\n+ }mx',\n\t\t\tarray(&$this, '_doHeaders_callback_setext'), $text);\n\n\t\t# atx-style headers:\n\t\t#\t# Header 1\n\t\t#\t## Header 2\n\t\t#\t## Header 2 with closing hashes ##\n\t\t#\t...\n\t\t#\t###### Header 6\n\t\t#\n\t\t$text = preg_replace_callback('{\n\t\t\t\t^(\\#{1,6})\t# $1 = string of #\\'s\n\t\t\t\t[ ]*\n\t\t\t\t(.+?)\t\t# $2 = Header text\n\t\t\t\t[ ]*\n\t\t\t\t\\#*\t\t\t# optional closing #\\'s (not counted)\n\t\t\t\t\\n+\n\t\t\t}xm',\n\t\t\tarray(&$this, '_doHeaders_callback_atx'), $text);\n\n\t\treturn $text;\n\t}\n\tfunction _doHeaders_callback_setext($matches) {\n\t\t# Terrible hack to check we haven't found an empty list item.\n\t\tif ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))\n\t\t\treturn $matches[0];\n\t\t\n\t\t$level = $matches[2]{0} == '=' ? 1 : 2;\n\t\t$block = \"<h$level>\".$this->runSpanGamut($matches[1]).\"</h$level>\";\n\t\treturn \"\\n\" . $this->hashBlock($block) . \"\\n\\n\";\n\t}\n\tfunction _doHeaders_callback_atx($matches) {\n\t\t$level = strlen($matches[1]);\n\t\t$block = \"<h$level>\".$this->runSpanGamut($matches[2]).\"</h$level>\";\n\t\treturn \"\\n\" . $this->hashBlock($block) . \"\\n\\n\";\n\t}\n\n\n\tfunction doLists($text) {\n\t#\n\t# Form HTML ordered (numbered) and unordered (bulleted) lists.\n\t#\n\t\t$less_than_tab = $this->tab_width - 1;\n\n\t\t# Re-usable patterns to match list item bullets and number markers:\n\t\t$marker_ul_re  = '[*+-]';\n\t\t$marker_ol_re  = '\\d+[.]';\n\t\t$marker_any_re = \"(?:$marker_ul_re|$marker_ol_re)\";\n\n\t\t$markers_relist = array($marker_ul_re, $marker_ol_re);\n\n\t\tforeach ($markers_relist as $marker_re) {\n\t\t\t# Re-usable pattern to match any entirel ul or ol list:\n\t\t\t$whole_list_re = '\n\t\t\t\t(\t\t\t\t\t\t\t\t# $1 = whole list\n\t\t\t\t  (\t\t\t\t\t\t\t\t# $2\n\t\t\t\t\t[ ]{0,'.$less_than_tab.'}\n\t\t\t\t\t('.$marker_re.')\t\t\t# $3 = first list item marker\n\t\t\t\t\t[ ]+\n\t\t\t\t  )\n\t\t\t\t  (?s:.+?)\n\t\t\t\t  (\t\t\t\t\t\t\t\t# $4\n\t\t\t\t\t  \\z\n\t\t\t\t\t|\n\t\t\t\t\t  \\n{2,}\n\t\t\t\t\t  (?=\\S)\n\t\t\t\t\t  (?!\t\t\t\t\t\t# Negative lookahead for another list item marker\n\t\t\t\t\t\t[ ]*\n\t\t\t\t\t\t'.$marker_re.'[ ]+\n\t\t\t\t\t  )\n\t\t\t\t  )\n\t\t\t\t)\n\t\t\t'; // mx\n\t\t\t\n\t\t\t# We use a different prefix before nested lists than top-level lists.\n\t\t\t# See extended comment in _ProcessListItems().\n\t\t\n\t\t\tif ($this->list_level) {\n\t\t\t\t$text = preg_replace_callback('{\n\t\t\t\t\t\t^\n\t\t\t\t\t\t'.$whole_list_re.'\n\t\t\t\t\t}mx',\n\t\t\t\t\tarray(&$this, '_doLists_callback'), $text);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$text = preg_replace_callback('{\n\t\t\t\t\t\t(?:(?<=\\n)\\n|\\A\\n?) # Must eat the newline\n\t\t\t\t\t\t'.$whole_list_re.'\n\t\t\t\t\t}mx',\n\t\t\t\t\tarray(&$this, '_doLists_callback'), $text);\n\t\t\t}\n\t\t}\n\n\t\treturn $text;\n\t}\n\tfunction _doLists_callback($matches) {\n\t\t# Re-usable patterns to match list item bullets and number markers:\n\t\t$marker_ul_re  = '[*+-]';\n\t\t$marker_ol_re  = '\\d+[.]';\n\t\t$marker_any_re = \"(?:$marker_ul_re|$marker_ol_re)\";\n\t\t\n\t\t$list = $matches[1];\n\t\t$list_type = preg_match(\"/$marker_ul_re/\", $matches[3]) ? \"ul\" : \"ol\";\n\t\t\n\t\t$marker_any_re = ( $list_type == \"ul\" ? $marker_ul_re : $marker_ol_re );\n\t\t\n\t\t$list .= \"\\n\";\n\t\t$result = $this->processListItems($list, $marker_any_re);\n\t\t\n\t\t$result = $this->hashBlock(\"<$list_type>\\n\" . $result . \"</$list_type>\");\n\t\treturn \"\\n\". $result .\"\\n\\n\";\n\t}\n\n\tvar $list_level = 0;\n\n\tfunction processListItems($list_str, $marker_any_re) {\n\t#\n\t#\tProcess the contents of a single ordered or unordered list, splitting it\n\t#\tinto individual list items.\n\t#\n\t\t# The $this->list_level global keeps track of when we're inside a list.\n\t\t# Each time we enter a list, we increment it; when we leave a list,\n\t\t# we decrement. If it's zero, we're not in a list anymore.\n\t\t#\n\t\t# We do this because when we're not inside a list, we want to treat\n\t\t# something like this:\n\t\t#\n\t\t#\t\tI recommend upgrading to version\n\t\t#\t\t8. Oops, now this line is treated\n\t\t#\t\tas a sub-list.\n\t\t#\n\t\t# As a single paragraph, despite the fact that the second line starts\n\t\t# with a digit-period-space sequence.\n\t\t#\n\t\t# Whereas when we're inside a list (or sub-list), that line will be\n\t\t# treated as the start of a sub-list. What a kludge, huh? This is\n\t\t# an aspect of Markdown's syntax that's hard to parse perfectly\n\t\t# without resorting to mind-reading. Perhaps the solution is to\n\t\t# change the syntax rules such that sub-lists must start with a\n\t\t# starting cardinal number; e.g. \"1.\" or \"a.\".\n\t\t\n\t\t$this->list_level++;\n\n\t\t# trim trailing blank lines:\n\t\t$list_str = preg_replace(\"/\\n{2,}\\\\z/\", \"\\n\", $list_str);\n\n\t\t$list_str = preg_replace_callback('{\n\t\t\t(\\n)?\t\t\t\t\t\t\t# leading line = $1\n\t\t\t(^[ ]*)\t\t\t\t\t\t\t# leading whitespace = $2\n\t\t\t('.$marker_any_re.'\t\t\t\t# list marker and space = $3\n\t\t\t\t(?:[ ]+|(?=\\n))\t# space only required if item is not empty\n\t\t\t)\n\t\t\t((?s:.*?))\t\t\t\t\t\t# list item text   = $4\n\t\t\t(?:(\\n+(?=\\n))|\\n)\t\t\t\t# tailing blank line = $5\n\t\t\t(?= \\n* (\\z | \\2 ('.$marker_any_re.') (?:[ ]+|(?=\\n))))\n\t\t\t}xm',\n\t\t\tarray(&$this, '_processListItems_callback'), $list_str);\n\n\t\t$this->list_level--;\n\t\treturn $list_str;\n\t}\n\tfunction _processListItems_callback($matches) {\n\t\t$item = $matches[4];\n\t\t$leading_line =& $matches[1];\n\t\t$leading_space =& $matches[2];\n\t\t$marker_space = $matches[3];\n\t\t$tailing_blank_line =& $matches[5];\n\n\t\tif ($leading_line || $tailing_blank_line || \n\t\t\tpreg_match('/\\n{2,}/', $item))\n\t\t{\n\t\t\t# Replace marker with the appropriate whitespace indentation\n\t\t\t$item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;\n\t\t\t$item = $this->runBlockGamut($this->outdent($item).\"\\n\");\n\t\t}\n\t\telse {\n\t\t\t# Recursion for sub-lists:\n\t\t\t$item = $this->doLists($this->outdent($item));\n\t\t\t$item = preg_replace('/\\n+$/', '', $item);\n\t\t\t$item = $this->runSpanGamut($item);\n\t\t}\n\n\t\treturn \"<li>\" . $item . \"</li>\\n\";\n\t}\n\n\n\tfunction doCodeBlocks($text) {\n\t#\n\t#\tProcess Markdown `<pre><code>` blocks.\n\t#\n\t\t$text = preg_replace_callback('{\n\t\t\t\t(?:\\n\\n|\\A\\n?)\n\t\t\t\t(\t            # $1 = the code block -- one or more lines, starting with a space/tab\n\t\t\t\t  (?>\n\t\t\t\t\t[ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces\n\t\t\t\t\t.*\\n+\n\t\t\t\t  )+\n\t\t\t\t)\n\t\t\t\t((?=^[ ]{0,'.$this->tab_width.'}\\S)|\\Z)\t# Lookahead for non-space at line-start, or end of doc\n\t\t\t}xm',\n\t\t\tarray(&$this, '_doCodeBlocks_callback'), $text);\n\n\t\treturn $text;\n\t}\n\tfunction _doCodeBlocks_callback($matches) {\n\t\t$codeblock = $matches[1];\n\n\t\t$codeblock = $this->outdent($codeblock);\n\t\t$codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);\n\n\t\t# trim leading newlines and trailing newlines\n\t\t$codeblock = preg_replace('/\\A\\n+|\\n+\\z/', '', $codeblock);\n\n\t\t$codeblock = \"<pre class=\\\"prettyprint\\\"><code>$codeblock\\n</code></pre>\";\n\t\treturn \"\\n\\n\".$this->hashBlock($codeblock).\"\\n\\n\";\n\t}\n\n\n\tfunction makeCodeSpan($code) {\n\t#\n\t# Create a code span markup for $code. Called from handleSpanToken.\n\t#\n\t\t$code = htmlspecialchars(trim($code), ENT_NOQUOTES);\n\t\treturn $this->hashPart(\"<code>$code</code>\");\n\t}\n\n\n\tvar $em_relist = array(\n\t\t''  => '(?:(?<!\\*)\\*(?!\\*)|(?<!_)_(?!_))(?=\\S)(?![.,:;]\\s)',\n\t\t'*' => '(?<=\\S)(?<!\\*)\\*(?!\\*)',\n\t\t'_' => '(?<=\\S)(?<!_)_(?!_)',\n\t\t);\n\tvar $strong_relist = array(\n\t\t''   => '(?:(?<!\\*)\\*\\*(?!\\*)|(?<!_)__(?!_))(?=\\S)(?![.,:;]\\s)',\n\t\t'**' => '(?<=\\S)(?<!\\*)\\*\\*(?!\\*)',\n\t\t'__' => '(?<=\\S)(?<!_)__(?!_)',\n\t\t);\n\tvar $em_strong_relist = array(\n\t\t''    => '(?:(?<!\\*)\\*\\*\\*(?!\\*)|(?<!_)___(?!_))(?=\\S)(?![.,:;]\\s)',\n\t\t'***' => '(?<=\\S)(?<!\\*)\\*\\*\\*(?!\\*)',\n\t\t'___' => '(?<=\\S)(?<!_)___(?!_)',\n\t\t);\n\tvar $em_strong_prepared_relist;\n\t\n\tfunction prepareItalicsAndBold() {\n\t#\n\t# Prepare regular expressions for seraching emphasis tokens in any\n\t# context.\n\t#\n\t\tforeach ($this->em_relist as $em => $em_re) {\n\t\t\tforeach ($this->strong_relist as $strong => $strong_re) {\n\t\t\t\t# Construct list of allowed token expressions.\n\t\t\t\t$token_relist = array();\n\t\t\t\tif (isset($this->em_strong_relist[\"$em$strong\"])) {\n\t\t\t\t\t$token_relist[] = $this->em_strong_relist[\"$em$strong\"];\n\t\t\t\t}\n\t\t\t\t$token_relist[] = $em_re;\n\t\t\t\t$token_relist[] = $strong_re;\n\t\t\t\t\n\t\t\t\t# Construct master expression from list.\n\t\t\t\t$token_re = '{('. implode('|', $token_relist) .')}';\n\t\t\t\t$this->em_strong_prepared_relist[\"$em$strong\"] = $token_re;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfunction doItalicsAndBold($text) {\n\t\t$token_stack = array('');\n\t\t$text_stack = array('');\n\t\t$em = '';\n\t\t$strong = '';\n\t\t$tree_char_em = false;\n\t\t\n\t\twhile (1) {\n\t\t\t#\n\t\t\t# Get prepared regular expression for seraching emphasis tokens\n\t\t\t# in current context.\n\t\t\t#\n\t\t\t$token_re = $this->em_strong_prepared_relist[\"$em$strong\"];\n\t\t\t\n\t\t\t#\n\t\t\t# Each loop iteration seach for the next emphasis token. \n\t\t\t# Each token is then passed to handleSpanToken.\n\t\t\t#\n\t\t\t$parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);\n\t\t\t$text_stack[0] .= $parts[0];\n\t\t\t$token =& $parts[1];\n\t\t\t$text =& $parts[2];\n\t\t\t\n\t\t\tif (empty($token)) {\n\t\t\t\t# Reached end of text span: empty stack without emitting.\n\t\t\t\t# any more emphasis.\n\t\t\t\twhile ($token_stack[0]) {\n\t\t\t\t\t$text_stack[1] .= array_shift($token_stack);\n\t\t\t\t\t$text_stack[0] .= array_shift($text_stack);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\t$token_len = strlen($token);\n\t\t\tif ($tree_char_em) {\n\t\t\t\t# Reached closing marker while inside a three-char emphasis.\n\t\t\t\tif ($token_len == 3) {\n\t\t\t\t\t# Three-char closing marker, close em and strong.\n\t\t\t\t\tarray_shift($token_stack);\n\t\t\t\t\t$span = array_shift($text_stack);\n\t\t\t\t\t$span = $this->runSpanGamut($span);\n\t\t\t\t\t$span = \"<strong><em>$span</em></strong>\";\n\t\t\t\t\t$text_stack[0] .= $this->hashPart($span);\n\t\t\t\t\t$em = '';\n\t\t\t\t\t$strong = '';\n\t\t\t\t} else {\n\t\t\t\t\t# Other closing marker: close one em or strong and\n\t\t\t\t\t# change current token state to match the other\n\t\t\t\t\t$token_stack[0] = str_repeat($token{0}, 3-$token_len);\n\t\t\t\t\t$tag = $token_len == 2 ? \"strong\" : \"em\";\n\t\t\t\t\t$span = $text_stack[0];\n\t\t\t\t\t$span = $this->runSpanGamut($span);\n\t\t\t\t\t$span = \"<$tag>$span</$tag>\";\n\t\t\t\t\t$text_stack[0] = $this->hashPart($span);\n\t\t\t\t\t$$tag = ''; # $$tag stands for $em or $strong\n\t\t\t\t}\n\t\t\t\t$tree_char_em = false;\n\t\t\t} else if ($token_len == 3) {\n\t\t\t\tif ($em) {\n\t\t\t\t\t# Reached closing marker for both em and strong.\n\t\t\t\t\t# Closing strong marker:\n\t\t\t\t\tfor ($i = 0; $i < 2; ++$i) {\n\t\t\t\t\t\t$shifted_token = array_shift($token_stack);\n\t\t\t\t\t\t$tag = strlen($shifted_token) == 2 ? \"strong\" : \"em\";\n\t\t\t\t\t\t$span = array_shift($text_stack);\n\t\t\t\t\t\t$span = $this->runSpanGamut($span);\n\t\t\t\t\t\t$span = \"<$tag>$span</$tag>\";\n\t\t\t\t\t\t$text_stack[0] .= $this->hashPart($span);\n\t\t\t\t\t\t$$tag = ''; # $$tag stands for $em or $strong\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t# Reached opening three-char emphasis marker. Push on token \n\t\t\t\t\t# stack; will be handled by the special condition above.\n\t\t\t\t\t$em = $token{0};\n\t\t\t\t\t$strong = \"$em$em\";\n\t\t\t\t\tarray_unshift($token_stack, $token);\n\t\t\t\t\tarray_unshift($text_stack, '');\n\t\t\t\t\t$tree_char_em = true;\n\t\t\t\t}\n\t\t\t} else if ($token_len == 2) {\n\t\t\t\tif ($strong) {\n\t\t\t\t\t# Unwind any dangling emphasis marker:\n\t\t\t\t\tif (strlen($token_stack[0]) == 1) {\n\t\t\t\t\t\t$text_stack[1] .= array_shift($token_stack);\n\t\t\t\t\t\t$text_stack[0] .= array_shift($text_stack);\n\t\t\t\t\t}\n\t\t\t\t\t# Closing strong marker:\n\t\t\t\t\tarray_shift($token_stack);\n\t\t\t\t\t$span = array_shift($text_stack);\n\t\t\t\t\t$span = $this->runSpanGamut($span);\n\t\t\t\t\t$span = \"<strong>$span</strong>\";\n\t\t\t\t\t$text_stack[0] .= $this->hashPart($span);\n\t\t\t\t\t$strong = '';\n\t\t\t\t} else {\n\t\t\t\t\tarray_unshift($token_stack, $token);\n\t\t\t\t\tarray_unshift($text_stack, '');\n\t\t\t\t\t$strong = $token;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t# Here $token_len == 1\n\t\t\t\tif ($em) {\n\t\t\t\t\tif (strlen($token_stack[0]) == 1) {\n\t\t\t\t\t\t# Closing emphasis marker:\n\t\t\t\t\t\tarray_shift($token_stack);\n\t\t\t\t\t\t$span = array_shift($text_stack);\n\t\t\t\t\t\t$span = $this->runSpanGamut($span);\n\t\t\t\t\t\t$span = \"<em>$span</em>\";\n\t\t\t\t\t\t$text_stack[0] .= $this->hashPart($span);\n\t\t\t\t\t\t$em = '';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$text_stack[0] .= $token;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tarray_unshift($token_stack, $token);\n\t\t\t\t\tarray_unshift($text_stack, '');\n\t\t\t\t\t$em = $token;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $text_stack[0];\n\t}\n\n\n\tfunction doBlockQuotes($text) {\n\t\t$text = preg_replace_callback('/\n\t\t\t  (\t\t\t\t\t\t\t\t# Wrap whole match in $1\n\t\t\t\t(?>\n\t\t\t\t  ^[ ]*>[ ]?\t\t\t# \">\" at the start of a line\n\t\t\t\t\t.+\\n\t\t\t\t\t# rest of the first line\n\t\t\t\t  (.+\\n)*\t\t\t\t\t# subsequent consecutive lines\n\t\t\t\t  \\n*\t\t\t\t\t\t# blanks\n\t\t\t\t)+\n\t\t\t  )\n\t\t\t/xm',\n\t\t\tarray(&$this, '_doBlockQuotes_callback'), $text);\n\n\t\treturn $text;\n\t}\n\tfunction _doBlockQuotes_callback($matches) {\n\t\t$bq = $matches[1];\n\t\t# trim one level of quoting - trim whitespace-only lines\n\t\t$bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);\n\t\t$bq = $this->runBlockGamut($bq);\t\t# recurse\n\n\t\t$bq = preg_replace('/^/m', \"  \", $bq);\n\t\t# These leading spaces cause problem with <pre> content, \n\t\t# so we need to fix that:\n\t\t$bq = preg_replace_callback('{(\\s*<pre>.+?</pre>)}sx', \n\t\t\tarray(&$this, '_DoBlockQuotes_callback2'), $bq);\n\n\t\treturn \"\\n\". $this->hashBlock(\"<blockquote>\\n$bq\\n</blockquote>\").\"\\n\\n\";\n\t}\n\tfunction _doBlockQuotes_callback2($matches) {\n\t\t$pre = $matches[1];\n\t\t$pre = preg_replace('/^  /m', '', $pre);\n\t\treturn $pre;\n\t}\n\n\n\tfunction formParagraphs($text) {\n\t#\n\t#\tParams:\n\t#\t\t$text - string to process with html <p> tags\n\t#\n\t\t# Strip leading and trailing lines:\n\t\t$text = preg_replace('/\\A\\n+|\\n+\\z/', '', $text);\n\n\t\t$grafs = preg_split('/\\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);\n\n\t\t#\n\t\t# Wrap <p> tags and unhashify HTML blocks\n\t\t#\n\t\tforeach ($grafs as $key => $value) {\n\t\t\tif (!preg_match('/^B\\x1A[0-9]+B$/', $value)) {\n\t\t\t\t# Is a paragraph.\n\t\t\t\t$value = $this->runSpanGamut($value);\n\t\t\t\t$value = preg_replace('/^([ ]*)/', \"<p>\", $value);\n\t\t\t\t$value .= \"</p>\";\n\t\t\t\t$grafs[$key] = $this->unhash($value);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t# Is a block.\n\t\t\t\t# Modify elements of @grafs in-place...\n\t\t\t\t$graf = $value;\n\t\t\t\t$block = $this->html_hashes[$graf];\n\t\t\t\t$graf = $block;\n//\t\t\t\tif (preg_match('{\n//\t\t\t\t\t\\A\n//\t\t\t\t\t(\t\t\t\t\t\t\t# $1 = <div> tag\n//\t\t\t\t\t  <div  \\s+\n//\t\t\t\t\t  [^>]*\n//\t\t\t\t\t  \\b\n//\t\t\t\t\t  markdown\\s*=\\s*  ([\\'\"])\t#\t$2 = attr quote char\n//\t\t\t\t\t  1\n//\t\t\t\t\t  \\2\n//\t\t\t\t\t  [^>]*\n//\t\t\t\t\t  >\n//\t\t\t\t\t)\n//\t\t\t\t\t(\t\t\t\t\t\t\t# $3 = contents\n//\t\t\t\t\t.*\n//\t\t\t\t\t)\n//\t\t\t\t\t(</div>)\t\t\t\t\t# $4 = closing tag\n//\t\t\t\t\t\\z\n//\t\t\t\t\t}xs', $block, $matches))\n//\t\t\t\t{\n//\t\t\t\t\tlist(, $div_open, , $div_content, $div_close) = $matches;\n//\n//\t\t\t\t\t# We can't call Markdown(), because that resets the hash;\n//\t\t\t\t\t# that initialization code should be pulled into its own sub, though.\n//\t\t\t\t\t$div_content = $this->hashHTMLBlocks($div_content);\n//\t\t\t\t\t\n//\t\t\t\t\t# Run document gamut methods on the content.\n//\t\t\t\t\tforeach ($this->document_gamut as $method => $priority) {\n//\t\t\t\t\t\t$div_content = $this->$method($div_content);\n//\t\t\t\t\t}\n//\n//\t\t\t\t\t$div_open = preg_replace(\n//\t\t\t\t\t\t'{\\smarkdown\\s*=\\s*([\\'\"]).+?\\1}', '', $div_open);\n//\n//\t\t\t\t\t$graf = $div_open . \"\\n\" . $div_content . \"\\n\" . $div_close;\n//\t\t\t\t}\n\t\t\t\t$grafs[$key] = $graf;\n\t\t\t}\n\t\t}\n\n\t\treturn implode(\"\\n\\n\", $grafs);\n\t}\n\n\n\tfunction encodeAttribute($text) {\n\t#\n\t# Encode text for a double-quoted HTML attribute. This function\n\t# is *not* suitable for attributes enclosed in single quotes.\n\t#\n\t\t$text = $this->encodeAmpsAndAngles($text);\n\t\t$text = str_replace('\"', '&quot;', $text);\n\t\treturn $text;\n\t}\n\t\n\t\n\tfunction encodeAmpsAndAngles($text) {\n\t#\n\t# Smart processing for ampersands and angle brackets that need to \n\t# be encoded. Valid character entities are left alone unless the\n\t# no-entities mode is set.\n\t#\n\t\tif ($this->no_entities) {\n\t\t\t$text = str_replace('&', '&amp;', $text);\n\t\t} else {\n\t\t\t# Ampersand-encoding based entirely on Nat Irons's Amputator\n\t\t\t# MT plugin: <http://bumppo.net/projects/amputator/>\n\t\t\t$text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)/', \n\t\t\t\t\t\t\t\t'&amp;', $text);;\n\t\t}\n\t\t# Encode remaining <'s\n\t\t$text = str_replace('<', '&lt;', $text);\n\n\t\treturn $text;\n\t}\n\n\n\tfunction doAutoLinks($text) {\n\t\t$text = preg_replace_callback('{<((https?|ftp|dict):[^\\'\">\\s]+)>}i', \n\t\t\tarray(&$this, '_doAutoLinks_url_callback'), $text);\n\n\t\t# Email addresses: <address@domain.foo>\n\t\t$text = preg_replace_callback('{\n\t\t\t<\n\t\t\t(?:mailto:)?\n\t\t\t(\n\t\t\t\t[-.\\w\\x80-\\xFF]+\n\t\t\t\t\\@\n\t\t\t\t[-a-z0-9\\x80-\\xFF]+(\\.[-a-z0-9\\x80-\\xFF]+)*\\.[a-z]+\n\t\t\t)\n\t\t\t>\n\t\t\t}xi',\n\t\t\tarray(&$this, '_doAutoLinks_email_callback'), $text);\n\n\t\treturn $text;\n\t}\n\tfunction _doAutoLinks_url_callback($matches) {\n\t\t$url = $this->encodeAttribute($matches[1]);\n\t\t$link = \"<a target=\\\"_blank\\\" href=\\\"$url\\\">$url</a>\";\n\t\treturn $this->hashPart($link);\n\t}\n\tfunction _doAutoLinks_email_callback($matches) {\n\t\t$address = $matches[1];\n\t\t$link = $this->encodeEmailAddress($address);\n\t\treturn $this->hashPart($link);\n\t}\n\n\n\tfunction encodeEmailAddress($addr) {\n\t#\n\t#\tInput: an email address, e.g. \"foo@example.com\"\n\t#\n\t#\tOutput: the email address as a mailto link, with each character\n\t#\t\tof the address encoded as either a decimal or hex entity, in\n\t#\t\tthe hopes of foiling most address harvesting spam bots. E.g.:\n\t#\n\t#\t  <p><a href=\"&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;\n\t#        &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;\n\t#        &#x6d;\">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;\n\t#        &#101;&#46;&#x63;&#111;&#x6d;</a></p>\n\t#\n\t#\tBased by a filter by Matthew Wickline, posted to BBEdit-Talk.\n\t#   With some optimizations by Milian Wolff.\n\t#\n\t\t$addr = \"mailto:\" . $addr;\n\t\t$chars = preg_split('/(?<!^)(?!$)/', $addr);\n\t\t$seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.\n\t\t\n\t\tforeach ($chars as $key => $char) {\n\t\t\t$ord = ord($char);\n\t\t\t# Ignore non-ascii chars.\n\t\t\tif ($ord < 128) {\n\t\t\t\t$r = ($seed * (1 + $key)) % 100; # Pseudo-random function.\n\t\t\t\t# roughly 10% raw, 45% hex, 45% dec\n\t\t\t\t# '@' *must* be encoded. I insist.\n\t\t\t\tif ($r > 90 && $char != '@') /* do nothing */;\n\t\t\t\telse if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';\n\t\t\t\telse              $chars[$key] = '&#'.$ord.';';\n\t\t\t}\n\t\t}\n\t\t\n\t\t$addr = implode('', $chars);\n\t\t$text = implode('', array_slice($chars, 7)); # text without `mailto:`\n\t\t$addr = \"<a target=\\\"_blank\\\" href=\\\"$addr\\\">$text</a>\";\n\n\t\treturn $addr;\n\t}\n\n\n\tfunction parseSpan($str) {\n\t#\n\t# Take the string $str and parse it into tokens, hashing embeded HTML,\n\t# escaped characters and handling code spans.\n\t#\n\t\t$output = '';\n\t\t\n\t\t$span_re = '{\n\t\t\t\t(\n\t\t\t\t\t\\\\\\\\'.$this->escape_chars_re.'\n\t\t\t\t|\n\t\t\t\t\t(?<![`\\\\\\\\])\n\t\t\t\t\t`+\t\t\t\t\t\t# code span marker\n\t\t\t'.( $this->no_markup ? '' : '\n\t\t\t\t|\n\t\t\t\t\t<!--    .*?     -->\t\t# comment\n\t\t\t\t|\n\t\t\t\t\t<\\?.*?\\?> | <%.*?%>\t\t# processing instruction\n\t\t\t\t|\n\t\t\t\t\t<[/!$]?[-a-zA-Z0-9:]+\t# regular tags\n\t\t\t\t\t(?>\n\t\t\t\t\t\t\\s\n\t\t\t\t\t\t(?>[^\"\\'>]+|\"[^\"]*\"|\\'[^\\']*\\')*\n\t\t\t\t\t)?\n\t\t\t\t\t>\n\t\t\t').'\n\t\t\t\t)\n\t\t\t\t}xs';\n\n\t\twhile (1) {\n\t\t\t#\n\t\t\t# Each loop iteration seach for either the next tag, the next \n\t\t\t# openning code span marker, or the next escaped character. \n\t\t\t# Each token is then passed to handleSpanToken.\n\t\t\t#\n\t\t\t$parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);\n\t\t\t\n\t\t\t# Create token from text preceding tag.\n\t\t\tif ($parts[0] != \"\") {\n\t\t\t\t$output .= $parts[0];\n\t\t\t}\n\t\t\t\n\t\t\t# Check if we reach the end.\n\t\t\tif (isset($parts[1])) {\n\t\t\t\t$output .= $this->handleSpanToken($parts[1], $parts[2]);\n\t\t\t\t$str = $parts[2];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn $output;\n\t}\n\t\n\t\n\tfunction handleSpanToken($token, &$str) {\n\t#\n\t# Handle $token provided by parseSpan by determining its nature and \n\t# returning the corresponding value that should replace it.\n\t#\n\t\tswitch ($token{0}) {\n\t\t\tcase \"\\\\\":\n\t\t\t\treturn $this->hashPart(\"&#\". ord($token{1}). \";\");\n\t\t\tcase \"`\":\n\t\t\t\t# Search for end marker in remaining text.\n\t\t\t\tif (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', \n\t\t\t\t\t$str, $matches))\n\t\t\t\t{\n\t\t\t\t\t$str = $matches[2];\n\t\t\t\t\t$codespan = $this->makeCodeSpan($matches[1]);\n\t\t\t\t\treturn $this->hashPart($codespan);\n\t\t\t\t}\n\t\t\t\treturn $token; // return as text since no ending marker found.\n\t\t\tdefault:\n\t\t\t\treturn $this->hashPart($token);\n\t\t}\n\t}\n\n\n\tfunction outdent($text) {\n\t#\n\t# Remove one level of line-leading tabs or spaces\n\t#\n\t\treturn preg_replace('/^(\\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);\n\t}\n\n\n\t# String length function for detab. `_initDetab` will create a function to \n\t# hanlde UTF-8 if the default function does not exist.\n\tvar $utf8_strlen = 'mb_strlen';\n\t\n\tfunction detab($text) {\n\t#\n\t# Replace tabs with the appropriate amount of space.\n\t#\n\t\t# For each line we separate the line in blocks delemited by\n\t\t# tab characters. Then we reconstruct every line by adding the \n\t\t# appropriate number of space between each blocks.\n\t\t\n\t\t$text = preg_replace_callback('/^.*\\t.*$/m',\n\t\t\tarray(&$this, '_detab_callback'), $text);\n\n\t\treturn $text;\n\t}\n\tfunction _detab_callback($matches) {\n\t\t$line = $matches[0];\n\t\t$strlen = $this->utf8_strlen; # strlen function for UTF-8.\n\t\t\n\t\t# Split in blocks.\n\t\t$blocks = explode(\"\\t\", $line);\n\t\t# Add each blocks to the line.\n\t\t$line = $blocks[0];\n\t\tunset($blocks[0]); # Do not add first block twice.\n\t\tforeach ($blocks as $block) {\n\t\t\t# Calculate amount of space, insert spaces, insert block.\n\t\t\t$amount = $this->tab_width - \n\t\t\t\t$strlen($line, 'UTF-8') % $this->tab_width;\n\t\t\t$line .= str_repeat(\" \", $amount) . $block;\n\t\t}\n\t\treturn $line;\n\t}\n\tfunction _initDetab() {\n\t#\n\t# Check for the availability of the function in the `utf8_strlen` property\n\t# (initially `mb_strlen`). If the function is not available, create a \n\t# function that will loosely count the number of UTF-8 characters with a\n\t# regular expression.\n\t#\n\t\tif (function_exists($this->utf8_strlen)) return;\n\t\t$this->utf8_strlen = create_function('$text', 'return preg_match_all(\n\t\t\t\"/[\\\\\\\\x00-\\\\\\\\xBF]|[\\\\\\\\xC0-\\\\\\\\xFF][\\\\\\\\x80-\\\\\\\\xBF]*/\", \n\t\t\t$text, $m);');\n\t}\n\n\n\tfunction unhash($text) {\n\t#\n\t# Swap back in all the tags hashed by _HashHTMLBlocks.\n\t#\n\t\treturn preg_replace_callback('/(.)\\x1A[0-9]+\\1/', \n\t\t\tarray(&$this, '_unhash_callback'), $text);\n\t}\n\tfunction _unhash_callback($matches) {\n\t\treturn $this->html_hashes[$matches[0]];\n\t}\n\n}\n\n/*\n\nPHP Markdown\n============\n\nDescription\n-----------\n\nThis is a PHP translation of the original Markdown formatter written in\nPerl by John Gruber.\n\nMarkdown is a text-to-HTML filter; it translates an easy-to-read /\neasy-to-write structured text format into HTML. Markdown's text format\nis most similar to that of plain text email, and supports features such\nas headers, *emphasis*, code blocks, blockquotes, and links.\n\nMarkdown's syntax is designed not as a generic markup language, but\nspecifically to serve as a front-end to (X)HTML. You can use span-level\nHTML tags anywhere in a Markdown document, and you can use block level\nHTML tags (like <div> and <table> as well).\n\nFor more information about Markdown's syntax, see:\n\n<http://daringfireball.net/projects/markdown/>\n\n\nBugs\n----\n\nTo file bug reports please send email to:\n\n<michel.fortin@michelf.com>\n\nPlease include with your report: (1) the example input; (2) the output you\nexpected; (3) the output Markdown actually produced.\n\n\nVersion History\n--------------- \n\nSee the readme file for detailed release notes for this version.\n\n\nCopyright and License\n---------------------\n\nPHP Markdown\nCopyright (c) 2004-2008 Michel Fortin  \n<http://www.michelf.com/>  \nAll rights reserved.\n\nBased on Markdown\nCopyright (c) 2003-2006 John Gruber   \n<http://daringfireball.net/>   \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n*\tRedistributions of source code must retain the above copyright notice,\n\tthis list of conditions and the following disclaimer.\n\n*\tRedistributions in binary form must reproduce the above copyright\n\tnotice, this list of conditions and the following disclaimer in the\n\tdocumentation and/or other materials provided with the distribution.\n\n*\tNeither the name \"Markdown\" nor the names of its contributors may\n\tbe used to endorse or promote products derived from this software\n\twithout specific prior written permission.\n\nThis software is provided by the copyright holders and contributors \"as\nis\" and any express or implied warranties, including, but not limited\nto, the implied warranties of merchantability and fitness for a\nparticular purpose are disclaimed. In no event shall the copyright owner\nor contributors be liable for any direct, indirect, incidental, special,\nexemplary, or consequential damages (including, but not limited to,\nprocurement of substitute goods or services; loss of use, data, or\nprofits; or business interruption) however caused and on any theory of\nliability, whether in contract, strict liability, or tort (including\nnegligence or otherwise) arising in any way out of the use of this\nsoftware, even if advised of the possibility of such damage.\n\n*/\n?>"
  },
  {
    "path": "libraries/pagination.class.php",
    "content": "<?php\n\n/* http://code.google.com/p/spaceshipcollaborative/wiki/PHPagination */\n\nclass Pagination{\n    var $output = '';    \n    var $options = array(\n        'urlscheme' => '',\n        'perpage' => '',\n        'page' => '',\n        'total' => '',\n        'numlinks' => '5',\n        'nexttext' => '>',\n        'prevtext' => '<',\n        'focusedclass' => 'selected',\n        'delimiter' => '',\n\t\t'lasttext' => '>>',\n\t\t'firsttext' => '<<',\n\t\t'order' => 'votes',\n\t\t'search' => ''\n    );\n   \n   function set($who,$what){\n       $this->output = '';\n       $this->options[$who] = $what;\n   }\n   \n   function checkValues(){\n       $errors = array();\n       if($this->options['perpage']=='') $errors[] = 'Invalid perpage value';\n       if($this->options['page']=='') $errors[] = 'Invalid page value';\n       if($this->options['total']=='') $errors[] = 'Invalid total value';\n       if($this->options['numlinks']=='') $errors[] = 'Invalid numlinks value';\n   }\n   function display($return = true){\n       $this->checkValues();\n       if($this->output=='') $this->generateOutput();\n       if(!$return) echo $this->output;\n       else return $this->output;\n   }\n   function generateOutput(){\n       $elements = array();\n       $num_pages = ceil($this->options['total']/$this->options['perpage']);\n       $front_links = ceil($this->options['numlinks']/2);\n       $end_links = floor($this->options['numlinks']/2);\n       if($this->options['page'] > $num_pages){ $this->set('page',1); }\n       \n       $start_page = max(1,($this->options['page']-$front_links+1));\n       $end_page = min($this->options['numlinks'] + $start_page-1,$num_pages);\n\n       if($this->options['page'] > 1){\n\t\t   if ($num_pages > 10) {\n\t\t\t   $elements[] = $this->generate_link(1,$this->options['firsttext']);\n\t\t   }\n\t\t\n\t\t$elements[] = $this->generate_link($this->options['page']-1,$this->options['prevtext']);\n\t\t   \n       }\n       \n       for($i=$start_page;$i<=$end_page;$i++){\n           $elements[] = $this->generate_link($i);\n       }\n       \n       if($this->options['page'] < $num_pages){\n           $elements[] = $this->generate_link($this->options['page']+1,$this->options['nexttext']);\n   \t\t   if ($num_pages > 10) {\n\t\t\t   $elements[] = $this->generate_link($num_pages,$this->options['lasttext']);\n\t\t   }\n       }\n      \n       $this->output = implode($this->options['delimiter'],$elements);\n   }\n   function generate_link($page,$label=''){\n       $url = str_replace('%page%',$page,$this->options['urlscheme']);\n       if($label=='') $label=$page;\n       $html = \"<a \".(($this->options['focusedclass']!='' && $page == $this->options['page'])?\"class=\\\"{$this->options['focusedclass']}\\\" \":\"\").\"href=\\\"{$url}\\\">{$label}</a>\";\n       return $html;\n   }\n\n    function displayOptions(){\n\t\tif ($this->options['search']!='') {\n\t\t\t$elements[] = $this->generate_seclink('relevance');\n\t\t}\n\t\t $elements[] = $this->generate_seclink('votes');\n\t\t $elements[] = $this->generate_seclink('newest');\n\t\t $elements[] = $this->generate_seclink('oldest');\n\t\t return implode($this->options['delimiter'],$elements);\n\n\t}\n\n\n     function generate_seclink($label){\n       $url = str_replace('%label%',$label,$this->options['urlscheme']);\n       $html = \"<a \".(($this->options['focusedclass']!='' && $label == $this->options['order'])?\"class=\\\"{$this->options['focusedclass']}\\\" \":\"\").\"href=\\\"{$url}\\\">{$label}</a>\";\n       return $html;\n   }\n}"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrCollections.php",
    "content": "<?php\n\n/**\n * Defines common attribute collections that modules reference\n */\n\nclass HTMLPurifier_AttrCollections\n{\n\n    /**\n     * Associative array of attribute collections, indexed by name\n     */\n    public $info = array();\n\n    /**\n     * Performs all expansions on internal data for use by other inclusions\n     * It also collects all attribute collection extensions from\n     * modules\n     * @param $attr_types HTMLPurifier_AttrTypes instance\n     * @param $modules Hash array of HTMLPurifier_HTMLModule members\n     */\n    public function __construct($attr_types, $modules) {\n        // load extensions from the modules\n        foreach ($modules as $module) {\n            foreach ($module->attr_collections as $coll_i => $coll) {\n                if (!isset($this->info[$coll_i])) {\n                    $this->info[$coll_i] = array();\n                }\n                foreach ($coll as $attr_i => $attr) {\n                    if ($attr_i === 0 && isset($this->info[$coll_i][$attr_i])) {\n                        // merge in includes\n                        $this->info[$coll_i][$attr_i] = array_merge(\n                            $this->info[$coll_i][$attr_i], $attr);\n                        continue;\n                    }\n                    $this->info[$coll_i][$attr_i] = $attr;\n                }\n            }\n        }\n        // perform internal expansions and inclusions\n        foreach ($this->info as $name => $attr) {\n            // merge attribute collections that include others\n            $this->performInclusions($this->info[$name]);\n            // replace string identifiers with actual attribute objects\n            $this->expandIdentifiers($this->info[$name], $attr_types);\n        }\n    }\n\n    /**\n     * Takes a reference to an attribute associative array and performs\n     * all inclusions specified by the zero index.\n     * @param &$attr Reference to attribute array\n     */\n    public function performInclusions(&$attr) {\n        if (!isset($attr[0])) return;\n        $merge = $attr[0];\n        $seen  = array(); // recursion guard\n        // loop through all the inclusions\n        for ($i = 0; isset($merge[$i]); $i++) {\n            if (isset($seen[$merge[$i]])) continue;\n            $seen[$merge[$i]] = true;\n            // foreach attribute of the inclusion, copy it over\n            if (!isset($this->info[$merge[$i]])) continue;\n            foreach ($this->info[$merge[$i]] as $key => $value) {\n                if (isset($attr[$key])) continue; // also catches more inclusions\n                $attr[$key] = $value;\n            }\n            if (isset($this->info[$merge[$i]][0])) {\n                // recursion\n                $merge = array_merge($merge, $this->info[$merge[$i]][0]);\n            }\n        }\n        unset($attr[0]);\n    }\n\n    /**\n     * Expands all string identifiers in an attribute array by replacing\n     * them with the appropriate values inside HTMLPurifier_AttrTypes\n     * @param &$attr Reference to attribute array\n     * @param $attr_types HTMLPurifier_AttrTypes instance\n     */\n    public function expandIdentifiers(&$attr, $attr_types) {\n\n        // because foreach will process new elements we add, make sure we\n        // skip duplicates\n        $processed = array();\n\n        foreach ($attr as $def_i => $def) {\n            // skip inclusions\n            if ($def_i === 0) continue;\n\n            if (isset($processed[$def_i])) continue;\n\n            // determine whether or not attribute is required\n            if ($required = (strpos($def_i, '*') !== false)) {\n                // rename the definition\n                unset($attr[$def_i]);\n                $def_i = trim($def_i, '*');\n                $attr[$def_i] = $def;\n            }\n\n            $processed[$def_i] = true;\n\n            // if we've already got a literal object, move on\n            if (is_object($def)) {\n                // preserve previous required\n                $attr[$def_i]->required = ($required || $attr[$def_i]->required);\n                continue;\n            }\n\n            if ($def === false) {\n                unset($attr[$def_i]);\n                continue;\n            }\n\n            if ($t = $attr_types->get($def)) {\n                $attr[$def_i] = $t;\n                $attr[$def_i]->required = $required;\n            } else {\n                unset($attr[$def_i]);\n            }\n        }\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/AlphaValue.php",
    "content": "<?php\n\nclass HTMLPurifier_AttrDef_CSS_AlphaValue extends HTMLPurifier_AttrDef_CSS_Number\n{\n\n    public function __construct() {\n        parent::__construct(false); // opacity is non-negative, but we will clamp it\n    }\n\n    public function validate($number, $config, $context) {\n        $result = parent::validate($number, $config, $context);\n        if ($result === false) return $result;\n        $float = (float) $result;\n        if ($float < 0.0) $result = '0';\n        if ($float > 1.0) $result = '1';\n        return $result;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Background.php",
    "content": "<?php\n\n/**\n * Validates shorthand CSS property background.\n * @warning Does not support url tokens that have internal spaces.\n */\nclass HTMLPurifier_AttrDef_CSS_Background extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Local copy of component validators.\n     * @note See HTMLPurifier_AttrDef_Font::$info for a similar impl.\n     */\n    protected $info;\n\n    public function __construct($config) {\n        $def = $config->getCSSDefinition();\n        $this->info['background-color'] = $def->info['background-color'];\n        $this->info['background-image'] = $def->info['background-image'];\n        $this->info['background-repeat'] = $def->info['background-repeat'];\n        $this->info['background-attachment'] = $def->info['background-attachment'];\n        $this->info['background-position'] = $def->info['background-position'];\n    }\n\n    public function validate($string, $config, $context) {\n\n        // regular pre-processing\n        $string = $this->parseCDATA($string);\n        if ($string === '') return false;\n\n        // munge rgb() decl if necessary\n        $string = $this->mungeRgb($string);\n\n        // assumes URI doesn't have spaces in it\n        $bits = explode(' ', strtolower($string)); // bits to process\n\n        $caught = array();\n        $caught['color']    = false;\n        $caught['image']    = false;\n        $caught['repeat']   = false;\n        $caught['attachment'] = false;\n        $caught['position'] = false;\n\n        $i = 0; // number of catches\n        $none = false;\n\n        foreach ($bits as $bit) {\n            if ($bit === '') continue;\n            foreach ($caught as $key => $status) {\n                if ($key != 'position') {\n                    if ($status !== false) continue;\n                    $r = $this->info['background-' . $key]->validate($bit, $config, $context);\n                } else {\n                    $r = $bit;\n                }\n                if ($r === false) continue;\n                if ($key == 'position') {\n                    if ($caught[$key] === false) $caught[$key] = '';\n                    $caught[$key] .= $r . ' ';\n                } else {\n                    $caught[$key] = $r;\n                }\n                $i++;\n                break;\n            }\n        }\n\n        if (!$i) return false;\n        if ($caught['position'] !== false) {\n            $caught['position'] = $this->info['background-position']->\n                validate($caught['position'], $config, $context);\n        }\n\n        $ret = array();\n        foreach ($caught as $value) {\n            if ($value === false) continue;\n            $ret[] = $value;\n        }\n\n        if (empty($ret)) return false;\n        return implode(' ', $ret);\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php",
    "content": "<?php\n\n/* W3C says:\n    [ // adjective and number must be in correct order, even if\n      // you could switch them without introducing ambiguity.\n      // some browsers support that syntax\n        [\n            <percentage> | <length> | left | center | right\n        ]\n        [\n            <percentage> | <length> | top | center | bottom\n        ]?\n    ] |\n    [ // this signifies that the vertical and horizontal adjectives\n      // can be arbitrarily ordered, however, there can only be two,\n      // one of each, or none at all\n        [\n            left | center | right\n        ] ||\n        [\n            top | center | bottom\n        ]\n    ]\n    top, left = 0%\n    center, (none) = 50%\n    bottom, right = 100%\n*/\n\n/* QuirksMode says:\n    keyword + length/percentage must be ordered correctly, as per W3C\n\n    Internet Explorer and Opera, however, support arbitrary ordering. We\n    should fix it up.\n\n    Minor issue though, not strictly necessary.\n*/\n\n// control freaks may appreciate the ability to convert these to\n// percentages or something, but it's not necessary\n\n/**\n * Validates the value of background-position.\n */\nclass HTMLPurifier_AttrDef_CSS_BackgroundPosition extends HTMLPurifier_AttrDef\n{\n\n    protected $length;\n    protected $percentage;\n\n    public function __construct() {\n        $this->length     = new HTMLPurifier_AttrDef_CSS_Length();\n        $this->percentage = new HTMLPurifier_AttrDef_CSS_Percentage();\n    }\n\n    public function validate($string, $config, $context) {\n        $string = $this->parseCDATA($string);\n        $bits = explode(' ', $string);\n\n        $keywords = array();\n        $keywords['h'] = false; // left, right\n        $keywords['v'] = false; // top, bottom\n        $keywords['c'] = false; // center\n        $measures = array();\n\n        $i = 0;\n\n        $lookup = array(\n            'top' => 'v',\n            'bottom' => 'v',\n            'left' => 'h',\n            'right' => 'h',\n            'center' => 'c'\n        );\n\n        foreach ($bits as $bit) {\n            if ($bit === '') continue;\n\n            // test for keyword\n            $lbit = ctype_lower($bit) ? $bit : strtolower($bit);\n            if (isset($lookup[$lbit])) {\n                $status = $lookup[$lbit];\n                $keywords[$status] = $lbit;\n                $i++;\n            }\n\n            // test for length\n            $r = $this->length->validate($bit, $config, $context);\n            if ($r !== false) {\n                $measures[] = $r;\n                $i++;\n            }\n\n            // test for percentage\n            $r = $this->percentage->validate($bit, $config, $context);\n            if ($r !== false) {\n                $measures[] = $r;\n                $i++;\n            }\n\n        }\n\n        if (!$i) return false; // no valid values were caught\n\n\n        $ret = array();\n\n        // first keyword\n        if     ($keywords['h'])     $ret[] = $keywords['h'];\n        elseif (count($measures))   $ret[] = array_shift($measures);\n        elseif ($keywords['c']) {\n            $ret[] = $keywords['c'];\n            $keywords['c'] = false; // prevent re-use: center = center center\n        }\n\n        if     ($keywords['v'])     $ret[] = $keywords['v'];\n        elseif (count($measures))   $ret[] = array_shift($measures);\n        elseif ($keywords['c'])     $ret[] = $keywords['c'];\n\n        if (empty($ret)) return false;\n        return implode(' ', $ret);\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Border.php",
    "content": "<?php\n\n/**\n * Validates the border property as defined by CSS.\n */\nclass HTMLPurifier_AttrDef_CSS_Border extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Local copy of properties this property is shorthand for.\n     */\n    protected $info = array();\n\n    public function __construct($config) {\n        $def = $config->getCSSDefinition();\n        $this->info['border-width'] = $def->info['border-width'];\n        $this->info['border-style'] = $def->info['border-style'];\n        $this->info['border-top-color'] = $def->info['border-top-color'];\n    }\n\n    public function validate($string, $config, $context) {\n        $string = $this->parseCDATA($string);\n        $string = $this->mungeRgb($string);\n        $bits = explode(' ', $string);\n        $done = array(); // segments we've finished\n        $ret = ''; // return value\n        foreach ($bits as $bit) {\n            foreach ($this->info as $propname => $validator) {\n                if (isset($done[$propname])) continue;\n                $r = $validator->validate($bit, $config, $context);\n                if ($r !== false) {\n                    $ret .= $r . ' ';\n                    $done[$propname] = true;\n                    break;\n                }\n            }\n        }\n        return rtrim($ret);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Color.php",
    "content": "<?php\n\n/**\n * Validates Color as defined by CSS.\n */\nclass HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef\n{\n\n    public function validate($color, $config, $context) {\n\n        static $colors = null;\n        if ($colors === null) $colors = $config->get('Core.ColorKeywords');\n\n        $color = trim($color);\n        if ($color === '') return false;\n\n        $lower = strtolower($color);\n        if (isset($colors[$lower])) return $colors[$lower];\n\n        if (strpos($color, 'rgb(') !== false) {\n            // rgb literal handling\n            $length = strlen($color);\n            if (strpos($color, ')') !== $length - 1) return false;\n            $triad = substr($color, 4, $length - 4 - 1);\n            $parts = explode(',', $triad);\n            if (count($parts) !== 3) return false;\n            $type = false; // to ensure that they're all the same type\n            $new_parts = array();\n            foreach ($parts as $part) {\n                $part = trim($part);\n                if ($part === '') return false;\n                $length = strlen($part);\n                if ($part[$length - 1] === '%') {\n                    // handle percents\n                    if (!$type) {\n                        $type = 'percentage';\n                    } elseif ($type !== 'percentage') {\n                        return false;\n                    }\n                    $num = (float) substr($part, 0, $length - 1);\n                    if ($num < 0) $num = 0;\n                    if ($num > 100) $num = 100;\n                    $new_parts[] = \"$num%\";\n                } else {\n                    // handle integers\n                    if (!$type) {\n                        $type = 'integer';\n                    } elseif ($type !== 'integer') {\n                        return false;\n                    }\n                    $num = (int) $part;\n                    if ($num < 0) $num = 0;\n                    if ($num > 255) $num = 255;\n                    $new_parts[] = (string) $num;\n                }\n            }\n            $new_triad = implode(',', $new_parts);\n            $color = \"rgb($new_triad)\";\n        } else {\n            // hexadecimal handling\n            if ($color[0] === '#') {\n                $hex = substr($color, 1);\n            } else {\n                $hex = $color;\n                $color = '#' . $color;\n            }\n            $length = strlen($hex);\n            if ($length !== 3 && $length !== 6) return false;\n            if (!ctype_xdigit($hex)) return false;\n        }\n\n        return $color;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Composite.php",
    "content": "<?php\n\n/**\n * Allows multiple validators to attempt to validate attribute.\n *\n * Composite is just what it sounds like: a composite of many validators.\n * This means that multiple HTMLPurifier_AttrDef objects will have a whack\n * at the string.  If one of them passes, that's what is returned.  This is\n * especially useful for CSS values, which often are a choice between\n * an enumerated set of predefined values or a flexible data type.\n */\nclass HTMLPurifier_AttrDef_CSS_Composite extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * List of HTMLPurifier_AttrDef objects that may process strings\n     * @todo Make protected\n     */\n    public $defs;\n\n    /**\n     * @param $defs List of HTMLPurifier_AttrDef objects\n     */\n    public function __construct($defs) {\n        $this->defs = $defs;\n    }\n\n    public function validate($string, $config, $context) {\n        foreach ($this->defs as $i => $def) {\n            $result = $this->defs[$i]->validate($string, $config, $context);\n            if ($result !== false) return $result;\n        }\n        return false;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php",
    "content": "<?php\n\n/**\n * Decorator which enables CSS properties to be disabled for specific elements.\n */\nclass HTMLPurifier_AttrDef_CSS_DenyElementDecorator extends HTMLPurifier_AttrDef\n{\n    public $def, $element;\n\n    /**\n     * @param $def Definition to wrap\n     * @param $element Element to deny\n     */\n    public function __construct($def, $element) {\n        $this->def = $def;\n        $this->element = $element;\n    }\n    /**\n     * Checks if CurrentToken is set and equal to $this->element\n     */\n    public function validate($string, $config, $context) {\n        $token = $context->get('CurrentToken', true);\n        if ($token && $token->name == $this->element) return false;\n        return $this->def->validate($string, $config, $context);\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Filter.php",
    "content": "<?php\n\n/**\n * Microsoft's proprietary filter: CSS property\n * @note Currently supports the alpha filter. In the future, this will\n *       probably need an extensible framework\n */\nclass HTMLPurifier_AttrDef_CSS_Filter extends HTMLPurifier_AttrDef\n{\n\n    protected $intValidator;\n\n    public function __construct() {\n        $this->intValidator = new HTMLPurifier_AttrDef_Integer();\n    }\n\n    public function validate($value, $config, $context) {\n        $value = $this->parseCDATA($value);\n        if ($value === 'none') return $value;\n        // if we looped this we could support multiple filters\n        $function_length = strcspn($value, '(');\n        $function = trim(substr($value, 0, $function_length));\n        if ($function !== 'alpha' &&\n            $function !== 'Alpha' &&\n            $function !== 'progid:DXImageTransform.Microsoft.Alpha'\n            ) return false;\n        $cursor = $function_length + 1;\n        $parameters_length = strcspn($value, ')', $cursor);\n        $parameters = substr($value, $cursor, $parameters_length);\n        $params = explode(',', $parameters);\n        $ret_params = array();\n        $lookup = array();\n        foreach ($params as $param) {\n            list($key, $value) = explode('=', $param);\n            $key   = trim($key);\n            $value = trim($value);\n            if (isset($lookup[$key])) continue;\n            if ($key !== 'opacity') continue;\n            $value = $this->intValidator->validate($value, $config, $context);\n            if ($value === false) continue;\n            $int = (int) $value;\n            if ($int > 100) $value = '100';\n            if ($int < 0) $value = '0';\n            $ret_params[] = \"$key=$value\";\n            $lookup[$key] = true;\n        }\n        $ret_parameters = implode(',', $ret_params);\n        $ret_function = \"$function($ret_parameters)\";\n        return $ret_function;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Font.php",
    "content": "<?php\n\n/**\n * Validates shorthand CSS property font.\n */\nclass HTMLPurifier_AttrDef_CSS_Font extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Local copy of component validators.\n     *\n     * @note If we moved specific CSS property definitions to their own\n     *       classes instead of having them be assembled at run time by\n     *       CSSDefinition, this wouldn't be necessary.  We'd instantiate\n     *       our own copies.\n     */\n    protected $info = array();\n\n    public function __construct($config) {\n        $def = $config->getCSSDefinition();\n        $this->info['font-style']   = $def->info['font-style'];\n        $this->info['font-variant'] = $def->info['font-variant'];\n        $this->info['font-weight']  = $def->info['font-weight'];\n        $this->info['font-size']    = $def->info['font-size'];\n        $this->info['line-height']  = $def->info['line-height'];\n        $this->info['font-family']  = $def->info['font-family'];\n    }\n\n    public function validate($string, $config, $context) {\n\n        static $system_fonts = array(\n            'caption' => true,\n            'icon' => true,\n            'menu' => true,\n            'message-box' => true,\n            'small-caption' => true,\n            'status-bar' => true\n        );\n\n        // regular pre-processing\n        $string = $this->parseCDATA($string);\n        if ($string === '') return false;\n\n        // check if it's one of the keywords\n        $lowercase_string = strtolower($string);\n        if (isset($system_fonts[$lowercase_string])) {\n            return $lowercase_string;\n        }\n\n        $bits = explode(' ', $string); // bits to process\n        $stage = 0; // this indicates what we're looking for\n        $caught = array(); // which stage 0 properties have we caught?\n        $stage_1 = array('font-style', 'font-variant', 'font-weight');\n        $final = ''; // output\n\n        for ($i = 0, $size = count($bits); $i < $size; $i++) {\n            if ($bits[$i] === '') continue;\n            switch ($stage) {\n\n                // attempting to catch font-style, font-variant or font-weight\n                case 0:\n                    foreach ($stage_1 as $validator_name) {\n                        if (isset($caught[$validator_name])) continue;\n                        $r = $this->info[$validator_name]->validate(\n                                                $bits[$i], $config, $context);\n                        if ($r !== false) {\n                            $final .= $r . ' ';\n                            $caught[$validator_name] = true;\n                            break;\n                        }\n                    }\n                    // all three caught, continue on\n                    if (count($caught) >= 3) $stage = 1;\n                    if ($r !== false) break;\n\n                // attempting to catch font-size and perhaps line-height\n                case 1:\n                    $found_slash = false;\n                    if (strpos($bits[$i], '/') !== false) {\n                        list($font_size, $line_height) =\n                                                    explode('/', $bits[$i]);\n                        if ($line_height === '') {\n                            // ooh, there's a space after the slash!\n                            $line_height = false;\n                            $found_slash = true;\n                        }\n                    } else {\n                        $font_size = $bits[$i];\n                        $line_height = false;\n                    }\n                    $r = $this->info['font-size']->validate(\n                                              $font_size, $config, $context);\n                    if ($r !== false) {\n                        $final .= $r;\n                        // attempt to catch line-height\n                        if ($line_height === false) {\n                            // we need to scroll forward\n                            for ($j = $i + 1; $j < $size; $j++) {\n                                if ($bits[$j] === '') continue;\n                                if ($bits[$j] === '/') {\n                                    if ($found_slash) {\n                                        return false;\n                                    } else {\n                                        $found_slash = true;\n                                        continue;\n                                    }\n                                }\n                                $line_height = $bits[$j];\n                                break;\n                            }\n                        } else {\n                            // slash already found\n                            $found_slash = true;\n                            $j = $i;\n                        }\n                        if ($found_slash) {\n                            $i = $j;\n                            $r = $this->info['line-height']->validate(\n                                              $line_height, $config, $context);\n                            if ($r !== false) {\n                                $final .= '/' . $r;\n                            }\n                        }\n                        $final .= ' ';\n                        $stage = 2;\n                        break;\n                    }\n                    return false;\n\n                // attempting to catch font-family\n                case 2:\n                    $font_family =\n                        implode(' ', array_slice($bits, $i, $size - $i));\n                    $r = $this->info['font-family']->validate(\n                                              $font_family, $config, $context);\n                    if ($r !== false) {\n                        $final .= $r . ' ';\n                        // processing completed successfully\n                        return rtrim($final);\n                    }\n                    return false;\n            }\n        }\n        return false;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/FontFamily.php",
    "content": "<?php\n\n/**\n * Validates a font family list according to CSS spec\n * @todo whitelisting allowed fonts would be nice\n */\nclass HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef\n{\n\n    public function validate($string, $config, $context) {\n        static $generic_names = array(\n            'serif' => true,\n            'sans-serif' => true,\n            'monospace' => true,\n            'fantasy' => true,\n            'cursive' => true\n        );\n\n        // assume that no font names contain commas in them\n        $fonts = explode(',', $string);\n        $final = '';\n        foreach($fonts as $font) {\n            $font = trim($font);\n            if ($font === '') continue;\n            // match a generic name\n            if (isset($generic_names[$font])) {\n                $final .= $font . ', ';\n                continue;\n            }\n            // match a quoted name\n            if ($font[0] === '\"' || $font[0] === \"'\") {\n                $length = strlen($font);\n                if ($length <= 2) continue;\n                $quote = $font[0];\n                if ($font[$length - 1] !== $quote) continue;\n                $font = substr($font, 1, $length - 2);\n\n                $new_font = '';\n                for ($i = 0, $c = strlen($font); $i < $c; $i++) {\n                    if ($font[$i] === '\\\\') {\n                        $i++;\n                        if ($i >= $c) {\n                            $new_font .= '\\\\';\n                            break;\n                        }\n                        if (ctype_xdigit($font[$i])) {\n                            $code = $font[$i];\n                            for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) {\n                                if (!ctype_xdigit($font[$i])) break;\n                                $code .= $font[$i];\n                            }\n                            // We have to be extremely careful when adding\n                            // new characters, to make sure we're not breaking\n                            // the encoding.\n                            $char = HTMLPurifier_Encoder::unichr(hexdec($code));\n                            if (HTMLPurifier_Encoder::cleanUTF8($char) === '') continue;\n                            $new_font .= $char;\n                            if ($i < $c && trim($font[$i]) !== '') $i--;\n                            continue;\n                        }\n                        if ($font[$i] === \"\\n\") continue;\n                    }\n                    $new_font .= $font[$i];\n                }\n\n                $font = $new_font;\n            }\n            // $font is a pure representation of the font name\n\n            if (ctype_alnum($font) && $font !== '') {\n                // very simple font, allow it in unharmed\n                $final .= $font . ', ';\n                continue;\n            }\n\n            // complicated font, requires quoting\n\n            // armor single quotes and new lines\n            $font = str_replace(\"\\\\\", \"\\\\\\\\\", $font);\n            $font = str_replace(\"'\", \"\\\\'\", $font);\n            $final .= \"'$font', \";\n        }\n        $final = rtrim($final, ', ');\n        if ($final === '') return false;\n        return $final;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php",
    "content": "<?php\n\n/**\n * Decorator which enables !important to be used in CSS values.\n */\nclass HTMLPurifier_AttrDef_CSS_ImportantDecorator extends HTMLPurifier_AttrDef\n{\n    public $def, $allow;\n\n    /**\n     * @param $def Definition to wrap\n     * @param $allow Whether or not to allow !important\n     */\n    public function __construct($def, $allow = false) {\n        $this->def = $def;\n        $this->allow = $allow;\n    }\n    /**\n     * Intercepts and removes !important if necessary\n     */\n    public function validate($string, $config, $context) {\n        // test for ! and important tokens\n        $string = trim($string);\n        $is_important = false;\n        // :TODO: optimization: test directly for !important and ! important\n        if (strlen($string) >= 9 && substr($string, -9) === 'important') {\n            $temp = rtrim(substr($string, 0, -9));\n            // use a temp, because we might want to restore important\n            if (strlen($temp) >= 1 && substr($temp, -1) === '!') {\n                $string = rtrim(substr($temp, 0, -1));\n                $is_important = true;\n            }\n        }\n        $string = $this->def->validate($string, $config, $context);\n        if ($this->allow && $is_important) $string .= ' !important';\n        return $string;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Length.php",
    "content": "<?php\n\n/**\n * Represents a Length as defined by CSS.\n */\nclass HTMLPurifier_AttrDef_CSS_Length extends HTMLPurifier_AttrDef\n{\n\n    protected $min, $max;\n\n    /**\n     * @param HTMLPurifier_Length $max Minimum length, or null for no bound. String is also acceptable.\n     * @param HTMLPurifier_Length $max Maximum length, or null for no bound. String is also acceptable.\n     */\n    public function __construct($min = null, $max = null) {\n        $this->min = $min !== null ? HTMLPurifier_Length::make($min) : null;\n        $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null;\n    }\n\n    public function validate($string, $config, $context) {\n        $string = $this->parseCDATA($string);\n\n        // Optimizations\n        if ($string === '') return false;\n        if ($string === '0') return '0';\n        if (strlen($string) === 1) return false;\n\n        $length = HTMLPurifier_Length::make($string);\n        if (!$length->isValid()) return false;\n\n        if ($this->min) {\n            $c = $length->compareTo($this->min);\n            if ($c === false) return false;\n            if ($c < 0) return false;\n        }\n        if ($this->max) {\n            $c = $length->compareTo($this->max);\n            if ($c === false) return false;\n            if ($c > 0) return false;\n        }\n\n        return $length->toString();\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/ListStyle.php",
    "content": "<?php\n\n/**\n * Validates shorthand CSS property list-style.\n * @warning Does not support url tokens that have internal spaces.\n */\nclass HTMLPurifier_AttrDef_CSS_ListStyle extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Local copy of component validators.\n     * @note See HTMLPurifier_AttrDef_CSS_Font::$info for a similar impl.\n     */\n    protected $info;\n\n    public function __construct($config) {\n        $def = $config->getCSSDefinition();\n        $this->info['list-style-type']     = $def->info['list-style-type'];\n        $this->info['list-style-position'] = $def->info['list-style-position'];\n        $this->info['list-style-image'] = $def->info['list-style-image'];\n    }\n\n    public function validate($string, $config, $context) {\n\n        // regular pre-processing\n        $string = $this->parseCDATA($string);\n        if ($string === '') return false;\n\n        // assumes URI doesn't have spaces in it\n        $bits = explode(' ', strtolower($string)); // bits to process\n\n        $caught = array();\n        $caught['type']     = false;\n        $caught['position'] = false;\n        $caught['image']    = false;\n\n        $i = 0; // number of catches\n        $none = false;\n\n        foreach ($bits as $bit) {\n            if ($i >= 3) return; // optimization bit\n            if ($bit === '') continue;\n            foreach ($caught as $key => $status) {\n                if ($status !== false) continue;\n                $r = $this->info['list-style-' . $key]->validate($bit, $config, $context);\n                if ($r === false) continue;\n                if ($r === 'none') {\n                    if ($none) continue;\n                    else $none = true;\n                    if ($key == 'image') continue;\n                }\n                $caught[$key] = $r;\n                $i++;\n                break;\n            }\n        }\n\n        if (!$i) return false;\n\n        $ret = array();\n\n        // construct type\n        if ($caught['type']) $ret[] = $caught['type'];\n\n        // construct image\n        if ($caught['image']) $ret[] = $caught['image'];\n\n        // construct position\n        if ($caught['position']) $ret[] = $caught['position'];\n\n        if (empty($ret)) return false;\n        return implode(' ', $ret);\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Multiple.php",
    "content": "<?php\n\n/**\n * Framework class for strings that involve multiple values.\n *\n * Certain CSS properties such as border-width and margin allow multiple\n * lengths to be specified.  This class can take a vanilla border-width\n * definition and multiply it, usually into a max of four.\n *\n * @note Even though the CSS specification isn't clear about it, inherit\n *       can only be used alone: it will never manifest as part of a multi\n *       shorthand declaration.  Thus, this class does not allow inherit.\n */\nclass HTMLPurifier_AttrDef_CSS_Multiple extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Instance of component definition to defer validation to.\n     * @todo Make protected\n     */\n    public $single;\n\n    /**\n     * Max number of values allowed.\n     * @todo Make protected\n     */\n    public $max;\n\n    /**\n     * @param $single HTMLPurifier_AttrDef to multiply\n     * @param $max Max number of values allowed (usually four)\n     */\n    public function __construct($single, $max = 4) {\n        $this->single = $single;\n        $this->max = $max;\n    }\n\n    public function validate($string, $config, $context) {\n        $string = $this->parseCDATA($string);\n        if ($string === '') return false;\n        $parts = explode(' ', $string); // parseCDATA replaced \\r, \\t and \\n\n        $length = count($parts);\n        $final = '';\n        for ($i = 0, $num = 0; $i < $length && $num < $this->max; $i++) {\n            if (ctype_space($parts[$i])) continue;\n            $result = $this->single->validate($parts[$i], $config, $context);\n            if ($result !== false) {\n                $final .= $result . ' ';\n                $num++;\n            }\n        }\n        if ($final === '') return false;\n        return rtrim($final);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Number.php",
    "content": "<?php\n\n/**\n * Validates a number as defined by the CSS spec.\n */\nclass HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Bool indicating whether or not only positive values allowed.\n     */\n    protected $non_negative = false;\n\n    /**\n     * @param $non_negative Bool indicating whether negatives are forbidden\n     */\n    public function __construct($non_negative = false) {\n        $this->non_negative = $non_negative;\n    }\n\n    /**\n     * @warning Some contexts do not pass $config, $context. These\n     *          variables should not be used without checking HTMLPurifier_Length\n     */\n    public function validate($number, $config, $context) {\n\n        $number = $this->parseCDATA($number);\n\n        if ($number === '') return false;\n        if ($number === '0') return '0';\n\n        $sign = '';\n        switch ($number[0]) {\n            case '-':\n                if ($this->non_negative) return false;\n                $sign = '-';\n            case '+':\n                $number = substr($number, 1);\n        }\n\n        if (ctype_digit($number)) {\n            $number = ltrim($number, '0');\n            return $number ? $sign . $number : '0';\n        }\n\n        // Period is the only non-numeric character allowed\n        if (strpos($number, '.') === false) return false;\n\n        list($left, $right) = explode('.', $number, 2);\n\n        if ($left === '' && $right === '') return false;\n        if ($left !== '' && !ctype_digit($left)) return false;\n\n        $left  = ltrim($left,  '0');\n        $right = rtrim($right, '0');\n\n        if ($right === '') {\n            return $left ? $sign . $left : '0';\n        } elseif (!ctype_digit($right)) {\n            return false;\n        }\n\n        return $sign . $left . '.' . $right;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/Percentage.php",
    "content": "<?php\n\n/**\n * Validates a Percentage as defined by the CSS spec.\n */\nclass HTMLPurifier_AttrDef_CSS_Percentage extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Instance of HTMLPurifier_AttrDef_CSS_Number to defer number validation\n     */\n    protected $number_def;\n\n    /**\n     * @param Bool indicating whether to forbid negative values\n     */\n    public function __construct($non_negative = false) {\n        $this->number_def = new HTMLPurifier_AttrDef_CSS_Number($non_negative);\n    }\n\n    public function validate($string, $config, $context) {\n\n        $string = $this->parseCDATA($string);\n\n        if ($string === '') return false;\n        $length = strlen($string);\n        if ($length === 1) return false;\n        if ($string[$length - 1] !== '%') return false;\n\n        $number = substr($string, 0, $length - 1);\n        $number = $this->number_def->validate($number, $config, $context);\n\n        if ($number === false) return false;\n        return \"$number%\";\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/TextDecoration.php",
    "content": "<?php\n\n/**\n * Validates the value for the CSS property text-decoration\n * @note This class could be generalized into a version that acts sort of\n *       like Enum except you can compound the allowed values.\n */\nclass HTMLPurifier_AttrDef_CSS_TextDecoration extends HTMLPurifier_AttrDef\n{\n\n    public function validate($string, $config, $context) {\n\n        static $allowed_values = array(\n            'line-through' => true,\n            'overline' => true,\n            'underline' => true,\n        );\n\n        $string = strtolower($this->parseCDATA($string));\n\n        if ($string === 'none') return $string;\n\n        $parts = explode(' ', $string);\n        $final = '';\n        foreach ($parts as $part) {\n            if (isset($allowed_values[$part])) {\n                $final .= $part . ' ';\n            }\n        }\n        $final = rtrim($final);\n        if ($final === '') return false;\n        return $final;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS/URI.php",
    "content": "<?php\n\n/**\n * Validates a URI in CSS syntax, which uses url('http://example.com')\n * @note While theoretically speaking a URI in a CSS document could\n *       be non-embedded, as of CSS2 there is no such usage so we're\n *       generalizing it. This may need to be changed in the future.\n * @warning Since HTMLPurifier_AttrDef_CSS blindly uses semicolons as\n *          the separator, you cannot put a literal semicolon in\n *          in the URI. Try percent encoding it, in that case.\n */\nclass HTMLPurifier_AttrDef_CSS_URI extends HTMLPurifier_AttrDef_URI\n{\n\n    public function __construct() {\n        parent::__construct(true); // always embedded\n    }\n\n    public function validate($uri_string, $config, $context) {\n        // parse the URI out of the string and then pass it onto\n        // the parent object\n\n        $uri_string = $this->parseCDATA($uri_string);\n        if (strpos($uri_string, 'url(') !== 0) return false;\n        $uri_string = substr($uri_string, 4);\n        $new_length = strlen($uri_string) - 1;\n        if ($uri_string[$new_length] != ')') return false;\n        $uri = trim(substr($uri_string, 0, $new_length));\n\n        if (!empty($uri) && ($uri[0] == \"'\" || $uri[0] == '\"')) {\n            $quote = $uri[0];\n            $new_length = strlen($uri) - 1;\n            if ($uri[$new_length] !== $quote) return false;\n            $uri = substr($uri, 1, $new_length - 1);\n        }\n\n        $keys   = array(  '(',   ')',   ',',   ' ',   '\"',   \"'\");\n        $values = array('\\\\(', '\\\\)', '\\\\,', '\\\\ ', '\\\\\"', \"\\\\'\");\n        $uri = str_replace($values, $keys, $uri);\n\n        $result = parent::validate($uri, $config, $context);\n\n        if ($result === false) return false;\n\n        // escape necessary characters according to CSS spec\n        // except for the comma, none of these should appear in the\n        // URI at all\n        $result = str_replace($keys, $values, $result);\n\n        return \"url($result)\";\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/CSS.php",
    "content": "<?php\n\n/**\n * Validates the HTML attribute style, otherwise known as CSS.\n * @note We don't implement the whole CSS specification, so it might be\n *       difficult to reuse this component in the context of validating\n *       actual stylesheet declarations.\n * @note If we were really serious about validating the CSS, we would\n *       tokenize the styles and then parse the tokens. Obviously, we\n *       are not doing that. Doing that could seriously harm performance,\n *       but would make these components a lot more viable for a CSS\n *       filtering solution.\n */\nclass HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef\n{\n\n    public function validate($css, $config, $context) {\n\n        $css = $this->parseCDATA($css);\n\n        $definition = $config->getCSSDefinition();\n\n        // we're going to break the spec and explode by semicolons.\n        // This is because semicolon rarely appears in escaped form\n        // Doing this is generally flaky but fast\n        // IT MIGHT APPEAR IN URIs, see HTMLPurifier_AttrDef_CSSURI\n        // for details\n\n        $declarations = explode(';', $css);\n        $propvalues = array();\n\n        /**\n         * Name of the current CSS property being validated.\n         */\n        $property = false;\n        $context->register('CurrentCSSProperty', $property);\n\n        foreach ($declarations as $declaration) {\n            if (!$declaration) continue;\n            if (!strpos($declaration, ':')) continue;\n            list($property, $value) = explode(':', $declaration, 2);\n            $property = trim($property);\n            $value    = trim($value);\n            $ok = false;\n            do {\n                if (isset($definition->info[$property])) {\n                    $ok = true;\n                    break;\n                }\n                if (ctype_lower($property)) break;\n                $property = strtolower($property);\n                if (isset($definition->info[$property])) {\n                    $ok = true;\n                    break;\n                }\n            } while(0);\n            if (!$ok) continue;\n            // inefficient call, since the validator will do this again\n            if (strtolower(trim($value)) !== 'inherit') {\n                // inherit works for everything (but only on the base property)\n                $result = $definition->info[$property]->validate(\n                    $value, $config, $context );\n            } else {\n                $result = 'inherit';\n            }\n            if ($result === false) continue;\n            $propvalues[$property] = $result;\n        }\n\n        $context->destroy('CurrentCSSProperty');\n\n        // procedure does not write the new CSS simultaneously, so it's\n        // slightly inefficient, but it's the only way of getting rid of\n        // duplicates. Perhaps config to optimize it, but not now.\n\n        $new_declarations = '';\n        foreach ($propvalues as $prop => $value) {\n            $new_declarations .= \"$prop:$value;\";\n        }\n\n        return $new_declarations ? $new_declarations : false;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/Enum.php",
    "content": "<?php\n\n// Enum = Enumerated\n/**\n * Validates a keyword against a list of valid values.\n * @warning The case-insensitive compare of this function uses PHP's\n *          built-in strtolower and ctype_lower functions, which may\n *          cause problems with international comparisons\n */\nclass HTMLPurifier_AttrDef_Enum extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Lookup table of valid values.\n     * @todo Make protected\n     */\n    public $valid_values   = array();\n\n    /**\n     * Bool indicating whether or not enumeration is case sensitive.\n     * @note In general this is always case insensitive.\n     */\n    protected $case_sensitive = false; // values according to W3C spec\n\n    /**\n     * @param $valid_values List of valid values\n     * @param $case_sensitive Bool indicating whether or not case sensitive\n     */\n    public function __construct(\n        $valid_values = array(), $case_sensitive = false\n    ) {\n        $this->valid_values = array_flip($valid_values);\n        $this->case_sensitive = $case_sensitive;\n    }\n\n    public function validate($string, $config, $context) {\n        $string = trim($string);\n        if (!$this->case_sensitive) {\n            // we may want to do full case-insensitive libraries\n            $string = ctype_lower($string) ? $string : strtolower($string);\n        }\n        $result = isset($this->valid_values[$string]);\n\n        return $result ? $string : false;\n    }\n\n    /**\n     * @param $string In form of comma-delimited list of case-insensitive\n     *      valid values. Example: \"foo,bar,baz\". Prepend \"s:\" to make\n     *      case sensitive\n     */\n    public function make($string) {\n        if (strlen($string) > 2 && $string[0] == 's' && $string[1] == ':') {\n            $string = substr($string, 2);\n            $sensitive = true;\n        } else {\n            $sensitive = false;\n        }\n        $values = explode(',', $string);\n        return new HTMLPurifier_AttrDef_Enum($values, $sensitive);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/Bool.php",
    "content": "<?php\n\n/**\n * Validates a boolean attribute\n */\nclass HTMLPurifier_AttrDef_HTML_Bool extends HTMLPurifier_AttrDef\n{\n\n    protected $name;\n    public $minimized = true;\n\n    public function __construct($name = false) {$this->name = $name;}\n\n    public function validate($string, $config, $context) {\n        if (empty($string)) return false;\n        return $this->name;\n    }\n\n    /**\n     * @param $string Name of attribute\n     */\n    public function make($string) {\n        return new HTMLPurifier_AttrDef_HTML_Bool($string);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/Class.php",
    "content": "<?php\n\n/**\n * Implements special behavior for class attribute (normally NMTOKENS)\n */\nclass HTMLPurifier_AttrDef_HTML_Class extends HTMLPurifier_AttrDef_HTML_Nmtokens\n{\n    protected function split($string, $config, $context) {\n        // really, this twiddle should be lazy loaded\n        $name = $config->getDefinition('HTML')->doctype->name;\n        if ($name == \"XHTML 1.1\" || $name == \"XHTML 2.0\") {\n            return parent::split($string, $config, $context);\n        } else {\n            return preg_split('/\\s+/', $string);\n        }\n    }\n    protected function filter($tokens, $config, $context) {\n        $allowed = $config->get('Attr.AllowedClasses');\n        $forbidden = $config->get('Attr.ForbiddenClasses');\n        $ret = array();\n        foreach ($tokens as $token) {\n            if (\n                ($allowed === null || isset($allowed[$token])) &&\n                !isset($forbidden[$token]) &&\n                // We need this O(n) check because of PHP's array\n                // implementation that casts -0 to 0.\n                !in_array($token, $ret, true)\n            ) {\n                $ret[] = $token;\n            }\n        }\n        return $ret;\n    }\n}\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/Color.php",
    "content": "<?php\n\n/**\n * Validates a color according to the HTML spec.\n */\nclass HTMLPurifier_AttrDef_HTML_Color extends HTMLPurifier_AttrDef\n{\n\n    public function validate($string, $config, $context) {\n\n        static $colors = null;\n        if ($colors === null) $colors = $config->get('Core.ColorKeywords');\n\n        $string = trim($string);\n\n        if (empty($string)) return false;\n        if (isset($colors[$string])) return $colors[$string];\n        if ($string[0] === '#') $hex = substr($string, 1);\n        else $hex = $string;\n\n        $length = strlen($hex);\n        if ($length !== 3 && $length !== 6) return false;\n        if (!ctype_xdigit($hex)) return false;\n        if ($length === 3) $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];\n\n        return \"#$hex\";\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/FrameTarget.php",
    "content": "<?php\n\n/**\n * Special-case enum attribute definition that lazy loads allowed frame targets\n */\nclass HTMLPurifier_AttrDef_HTML_FrameTarget extends HTMLPurifier_AttrDef_Enum\n{\n\n    public $valid_values = false; // uninitialized value\n    protected $case_sensitive = false;\n\n    public function __construct() {}\n\n    public function validate($string, $config, $context) {\n        if ($this->valid_values === false) $this->valid_values = $config->get('Attr.AllowedFrameTargets');\n        return parent::validate($string, $config, $context);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/ID.php",
    "content": "<?php\n\n/**\n * Validates the HTML attribute ID.\n * @warning Even though this is the id processor, it\n *          will ignore the directive Attr:IDBlacklist, since it will only\n *          go according to the ID accumulator. Since the accumulator is\n *          automatically generated, it will have already absorbed the\n *          blacklist. If you're hacking around, make sure you use load()!\n */\n\nclass HTMLPurifier_AttrDef_HTML_ID extends HTMLPurifier_AttrDef\n{\n\n    // ref functionality disabled, since we also have to verify\n    // whether or not the ID it refers to exists\n\n    public function validate($id, $config, $context) {\n\n        if (!$config->get('Attr.EnableID')) return false;\n\n        $id = trim($id); // trim it first\n\n        if ($id === '') return false;\n\n        $prefix = $config->get('Attr.IDPrefix');\n        if ($prefix !== '') {\n            $prefix .= $config->get('Attr.IDPrefixLocal');\n            // prevent re-appending the prefix\n            if (strpos($id, $prefix) !== 0) $id = $prefix . $id;\n        } elseif ($config->get('Attr.IDPrefixLocal') !== '') {\n            trigger_error('%Attr.IDPrefixLocal cannot be used unless '.\n                '%Attr.IDPrefix is set', E_USER_WARNING);\n        }\n\n        //if (!$this->ref) {\n            $id_accumulator =& $context->get('IDAccumulator');\n            if (isset($id_accumulator->ids[$id])) return false;\n        //}\n\n        // we purposely avoid using regex, hopefully this is faster\n\n        if (ctype_alpha($id)) {\n            $result = true;\n        } else {\n            if (!ctype_alpha(@$id[0])) return false;\n            $trim = trim( // primitive style of regexps, I suppose\n                $id,\n                'A..Za..z0..9:-._'\n              );\n            $result = ($trim === '');\n        }\n\n        $regexp = $config->get('Attr.IDBlacklistRegexp');\n        if ($regexp && preg_match($regexp, $id)) {\n            return false;\n        }\n\n        if (/*!$this->ref && */$result) $id_accumulator->add($id);\n\n        // if no change was made to the ID, return the result\n        // else, return the new id if stripping whitespace made it\n        //     valid, or return false.\n        return $result ? $id : false;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/Length.php",
    "content": "<?php\n\n/**\n * Validates the HTML type length (not to be confused with CSS's length).\n *\n * This accepts integer pixels or percentages as lengths for certain\n * HTML attributes.\n */\n\nclass HTMLPurifier_AttrDef_HTML_Length extends HTMLPurifier_AttrDef_HTML_Pixels\n{\n\n    public function validate($string, $config, $context) {\n\n        $string = trim($string);\n        if ($string === '') return false;\n\n        $parent_result = parent::validate($string, $config, $context);\n        if ($parent_result !== false) return $parent_result;\n\n        $length = strlen($string);\n        $last_char = $string[$length - 1];\n\n        if ($last_char !== '%') return false;\n\n        $points = substr($string, 0, $length - 1);\n\n        if (!is_numeric($points)) return false;\n\n        $points = (int) $points;\n\n        if ($points < 0) return '0%';\n        if ($points > 100) return '100%';\n\n        return ((string) $points) . '%';\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/LinkTypes.php",
    "content": "<?php\n\n/**\n * Validates a rel/rev link attribute against a directive of allowed values\n * @note We cannot use Enum because link types allow multiple\n *       values.\n * @note Assumes link types are ASCII text\n */\nclass HTMLPurifier_AttrDef_HTML_LinkTypes extends HTMLPurifier_AttrDef\n{\n\n    /** Name config attribute to pull. */\n    protected $name;\n\n    public function __construct($name) {\n        $configLookup = array(\n            'rel' => 'AllowedRel',\n            'rev' => 'AllowedRev'\n        );\n        if (!isset($configLookup[$name])) {\n            trigger_error('Unrecognized attribute name for link '.\n                'relationship.', E_USER_ERROR);\n            return;\n        }\n        $this->name = $configLookup[$name];\n    }\n\n    public function validate($string, $config, $context) {\n\n        $allowed = $config->get('Attr.' . $this->name);\n        if (empty($allowed)) return false;\n\n        $string = $this->parseCDATA($string);\n        $parts = explode(' ', $string);\n\n        // lookup to prevent duplicates\n        $ret_lookup = array();\n        foreach ($parts as $part) {\n            $part = strtolower(trim($part));\n            if (!isset($allowed[$part])) continue;\n            $ret_lookup[$part] = true;\n        }\n\n        if (empty($ret_lookup)) return false;\n        $string = implode(' ', array_keys($ret_lookup));\n\n        return $string;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/MultiLength.php",
    "content": "<?php\n\n/**\n * Validates a MultiLength as defined by the HTML spec.\n *\n * A multilength is either a integer (pixel count), a percentage, or\n * a relative number.\n */\nclass HTMLPurifier_AttrDef_HTML_MultiLength extends HTMLPurifier_AttrDef_HTML_Length\n{\n\n    public function validate($string, $config, $context) {\n\n        $string = trim($string);\n        if ($string === '') return false;\n\n        $parent_result = parent::validate($string, $config, $context);\n        if ($parent_result !== false) return $parent_result;\n\n        $length = strlen($string);\n        $last_char = $string[$length - 1];\n\n        if ($last_char !== '*') return false;\n\n        $int = substr($string, 0, $length - 1);\n\n        if ($int == '') return '*';\n        if (!is_numeric($int)) return false;\n\n        $int = (int) $int;\n\n        if ($int < 0) return false;\n        if ($int == 0) return '0';\n        if ($int == 1) return '*';\n        return ((string) $int) . '*';\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/Nmtokens.php",
    "content": "<?php\n\n/**\n * Validates contents based on NMTOKENS attribute type.\n */\nclass HTMLPurifier_AttrDef_HTML_Nmtokens extends HTMLPurifier_AttrDef\n{\n\n    public function validate($string, $config, $context) {\n\n        $string = trim($string);\n\n        // early abort: '' and '0' (strings that convert to false) are invalid\n        if (!$string) return false;\n\n        $tokens = $this->split($string, $config, $context);\n        $tokens = $this->filter($tokens, $config, $context);\n        if (empty($tokens)) return false;\n        return implode(' ', $tokens);\n\n    }\n\n    /**\n     * Splits a space separated list of tokens into its constituent parts.\n     */\n    protected function split($string, $config, $context) {\n        // OPTIMIZABLE!\n        // do the preg_match, capture all subpatterns for reformulation\n\n        // we don't support U+00A1 and up codepoints or\n        // escaping because I don't know how to do that with regexps\n        // and plus it would complicate optimization efforts (you never\n        // see that anyway).\n        $pattern = '/(?:(?<=\\s)|\\A)'. // look behind for space or string start\n                   '((?:--|-?[A-Za-z_])[A-Za-z_\\-0-9]*)'.\n                   '(?:(?=\\s)|\\z)/'; // look ahead for space or string end\n        preg_match_all($pattern, $string, $matches);\n        return $matches[1];\n    }\n\n    /**\n     * Template method for removing certain tokens based on arbitrary criteria.\n     * @note If we wanted to be really functional, we'd do an array_filter\n     *       with a callback. But... we're not.\n     */\n    protected function filter($tokens, $config, $context) {\n        return $tokens;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/HTML/Pixels.php",
    "content": "<?php\n\n/**\n * Validates an integer representation of pixels according to the HTML spec.\n */\nclass HTMLPurifier_AttrDef_HTML_Pixels extends HTMLPurifier_AttrDef\n{\n\n    protected $max;\n\n    public function __construct($max = null) {\n        $this->max = $max;\n    }\n\n    public function validate($string, $config, $context) {\n\n        $string = trim($string);\n        if ($string === '0') return $string;\n        if ($string === '')  return false;\n        $length = strlen($string);\n        if (substr($string, $length - 2) == 'px') {\n            $string = substr($string, 0, $length - 2);\n        }\n        if (!is_numeric($string)) return false;\n        $int = (int) $string;\n\n        if ($int < 0) return '0';\n\n        // upper-bound value, extremely high values can\n        // crash operating systems, see <http://ha.ckers.org/imagecrash.html>\n        // WARNING, above link WILL crash you if you're using Windows\n\n        if ($this->max !== null && $int > $this->max) return (string) $this->max;\n\n        return (string) $int;\n\n    }\n\n    public function make($string) {\n        if ($string === '') $max = null;\n        else $max = (int) $string;\n        $class = get_class($this);\n        return new $class($max);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/Integer.php",
    "content": "<?php\n\n/**\n * Validates an integer.\n * @note While this class was modeled off the CSS definition, no currently\n *       allowed CSS uses this type.  The properties that do are: widows,\n *       orphans, z-index, counter-increment, counter-reset.  Some of the\n *       HTML attributes, however, find use for a non-negative version of this.\n */\nclass HTMLPurifier_AttrDef_Integer extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Bool indicating whether or not negative values are allowed\n     */\n    protected $negative = true;\n\n    /**\n     * Bool indicating whether or not zero is allowed\n     */\n    protected $zero = true;\n\n    /**\n     * Bool indicating whether or not positive values are allowed\n     */\n    protected $positive = true;\n\n    /**\n     * @param $negative Bool indicating whether or not negative values are allowed\n     * @param $zero Bool indicating whether or not zero is allowed\n     * @param $positive Bool indicating whether or not positive values are allowed\n     */\n    public function __construct(\n        $negative = true, $zero = true, $positive = true\n    ) {\n        $this->negative = $negative;\n        $this->zero     = $zero;\n        $this->positive = $positive;\n    }\n\n    public function validate($integer, $config, $context) {\n\n        $integer = $this->parseCDATA($integer);\n        if ($integer === '') return false;\n\n        // we could possibly simply typecast it to integer, but there are\n        // certain fringe cases that must not return an integer.\n\n        // clip leading sign\n        if ( $this->negative && $integer[0] === '-' ) {\n            $digits = substr($integer, 1);\n            if ($digits === '0') $integer = '0'; // rm minus sign for zero\n        } elseif( $this->positive && $integer[0] === '+' ) {\n            $digits = $integer = substr($integer, 1); // rm unnecessary plus\n        } else {\n            $digits = $integer;\n        }\n\n        // test if it's numeric\n        if (!ctype_digit($digits)) return false;\n\n        // perform scope tests\n        if (!$this->zero     && $integer == 0) return false;\n        if (!$this->positive && $integer > 0) return false;\n        if (!$this->negative && $integer < 0) return false;\n\n        return $integer;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/Lang.php",
    "content": "<?php\n\n/**\n * Validates the HTML attribute lang, effectively a language code.\n * @note Built according to RFC 3066, which obsoleted RFC 1766\n */\nclass HTMLPurifier_AttrDef_Lang extends HTMLPurifier_AttrDef\n{\n\n    public function validate($string, $config, $context) {\n\n        $string = trim($string);\n        if (!$string) return false;\n\n        $subtags = explode('-', $string);\n        $num_subtags = count($subtags);\n\n        if ($num_subtags == 0) return false; // sanity check\n\n        // process primary subtag : $subtags[0]\n        $length = strlen($subtags[0]);\n        switch ($length) {\n            case 0:\n                return false;\n            case 1:\n                if (! ($subtags[0] == 'x' || $subtags[0] == 'i') ) {\n                    return false;\n                }\n                break;\n            case 2:\n            case 3:\n                if (! ctype_alpha($subtags[0]) ) {\n                    return false;\n                } elseif (! ctype_lower($subtags[0]) ) {\n                    $subtags[0] = strtolower($subtags[0]);\n                }\n                break;\n            default:\n                return false;\n        }\n\n        $new_string = $subtags[0];\n        if ($num_subtags == 1) return $new_string;\n\n        // process second subtag : $subtags[1]\n        $length = strlen($subtags[1]);\n        if ($length == 0 || ($length == 1 && $subtags[1] != 'x') || $length > 8 || !ctype_alnum($subtags[1])) {\n            return $new_string;\n        }\n        if (!ctype_lower($subtags[1])) $subtags[1] = strtolower($subtags[1]);\n\n        $new_string .= '-' . $subtags[1];\n        if ($num_subtags == 2) return $new_string;\n\n        // process all other subtags, index 2 and up\n        for ($i = 2; $i < $num_subtags; $i++) {\n            $length = strlen($subtags[$i]);\n            if ($length == 0 || $length > 8 || !ctype_alnum($subtags[$i])) {\n                return $new_string;\n            }\n            if (!ctype_lower($subtags[$i])) {\n                $subtags[$i] = strtolower($subtags[$i]);\n            }\n            $new_string .= '-' . $subtags[$i];\n        }\n\n        return $new_string;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/Switch.php",
    "content": "<?php\n\n/**\n * Decorator that, depending on a token, switches between two definitions.\n */\nclass HTMLPurifier_AttrDef_Switch\n{\n\n    protected $tag;\n    protected $withTag, $withoutTag;\n\n    /**\n     * @param string $tag Tag name to switch upon\n     * @param HTMLPurifier_AttrDef $with_tag Call if token matches tag\n     * @param HTMLPurifier_AttrDef $without_tag Call if token doesn't match, or there is no token\n     */\n    public function __construct($tag, $with_tag, $without_tag) {\n        $this->tag = $tag;\n        $this->withTag = $with_tag;\n        $this->withoutTag = $without_tag;\n    }\n\n    public function validate($string, $config, $context) {\n        $token = $context->get('CurrentToken', true);\n        if (!$token || $token->name !== $this->tag) {\n            return $this->withoutTag->validate($string, $config, $context);\n        } else {\n            return $this->withTag->validate($string, $config, $context);\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/Text.php",
    "content": "<?php\n\n/**\n * Validates arbitrary text according to the HTML spec.\n */\nclass HTMLPurifier_AttrDef_Text extends HTMLPurifier_AttrDef\n{\n\n    public function validate($string, $config, $context) {\n        return $this->parseCDATA($string);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php",
    "content": "<?php\n\n/**\n * Primitive email validation class based on the regexp found at\n * http://www.regular-expressions.info/email.html\n */\nclass HTMLPurifier_AttrDef_URI_Email_SimpleCheck extends HTMLPurifier_AttrDef_URI_Email\n{\n\n    public function validate($string, $config, $context) {\n        // no support for named mailboxes i.e. \"Bob <bob@example.com>\"\n        // that needs more percent encoding to be done\n        if ($string == '') return false;\n        $string = trim($string);\n        $result = preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i', $string);\n        return $result ? $string : false;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/URI/Email.php",
    "content": "<?php\n\nabstract class HTMLPurifier_AttrDef_URI_Email extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Unpacks a mailbox into its display-name and address\n     */\n    function unpack($string) {\n        // needs to be implemented\n    }\n\n}\n\n// sub-implementations\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/URI/Host.php",
    "content": "<?php\n\n/**\n * Validates a host according to the IPv4, IPv6 and DNS (future) specifications.\n */\nclass HTMLPurifier_AttrDef_URI_Host extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * Instance of HTMLPurifier_AttrDef_URI_IPv4 sub-validator\n     */\n    protected $ipv4;\n\n    /**\n     * Instance of HTMLPurifier_AttrDef_URI_IPv6 sub-validator\n     */\n    protected $ipv6;\n\n    public function __construct() {\n        $this->ipv4 = new HTMLPurifier_AttrDef_URI_IPv4();\n        $this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6();\n    }\n\n    public function validate($string, $config, $context) {\n        $length = strlen($string);\n        if ($string === '') return '';\n        if ($length > 1 && $string[0] === '[' && $string[$length-1] === ']') {\n            //IPv6\n            $ip = substr($string, 1, $length - 2);\n            $valid = $this->ipv6->validate($ip, $config, $context);\n            if ($valid === false) return false;\n            return '['. $valid . ']';\n        }\n\n        // need to do checks on unusual encodings too\n        $ipv4 = $this->ipv4->validate($string, $config, $context);\n        if ($ipv4 !== false) return $ipv4;\n\n        // A regular domain name.\n\n        // This breaks I18N domain names, but we don't have proper IRI support,\n        // so force users to insert Punycode. If there's complaining we'll\n        // try to fix things into an international friendly form.\n\n        // The productions describing this are:\n        $a   = '[a-z]';     // alpha\n        $an  = '[a-z0-9]';  // alphanum\n        $and = '[a-z0-9-]'; // alphanum | \"-\"\n        // domainlabel = alphanum | alphanum *( alphanum | \"-\" ) alphanum\n        $domainlabel   = \"$an($and*$an)?\";\n        // toplabel    = alpha | alpha *( alphanum | \"-\" ) alphanum\n        $toplabel      = \"$a($and*$an)?\";\n        // hostname    = *( domainlabel \".\" ) toplabel [ \".\" ]\n        $match = preg_match(\"/^($domainlabel\\.)*$toplabel\\.?$/i\", $string);\n        if (!$match) return false;\n\n        return $string;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/URI/IPv4.php",
    "content": "<?php\n\n/**\n * Validates an IPv4 address\n * @author Feyd @ forums.devnetwork.net (public domain)\n */\nclass HTMLPurifier_AttrDef_URI_IPv4 extends HTMLPurifier_AttrDef\n{\n\n    /**\n     * IPv4 regex, protected so that IPv6 can reuse it\n     */\n    protected $ip4;\n\n    public function validate($aIP, $config, $context) {\n\n        if (!$this->ip4) $this->_loadRegex();\n\n        if (preg_match('#^' . $this->ip4 . '$#s', $aIP))\n        {\n                return $aIP;\n        }\n\n        return false;\n\n    }\n\n    /**\n     * Lazy load function to prevent regex from being stuffed in\n     * cache.\n     */\n    protected function _loadRegex() {\n        $oct = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'; // 0-255\n        $this->ip4 = \"(?:{$oct}\\\\.{$oct}\\\\.{$oct}\\\\.{$oct})\";\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/URI/IPv6.php",
    "content": "<?php\n\n/**\n * Validates an IPv6 address.\n * @author Feyd @ forums.devnetwork.net (public domain)\n * @note This function requires brackets to have been removed from address\n *       in URI.\n */\nclass HTMLPurifier_AttrDef_URI_IPv6 extends HTMLPurifier_AttrDef_URI_IPv4\n{\n\n    public function validate($aIP, $config, $context) {\n\n        if (!$this->ip4) $this->_loadRegex();\n\n        $original = $aIP;\n\n        $hex = '[0-9a-fA-F]';\n        $blk = '(?:' . $hex . '{1,4})';\n        $pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))';   // /0 - /128\n\n        //      prefix check\n        if (strpos($aIP, '/') !== false)\n        {\n                if (preg_match('#' . $pre . '$#s', $aIP, $find))\n                {\n                        $aIP = substr($aIP, 0, 0-strlen($find[0]));\n                        unset($find);\n                }\n                else\n                {\n                        return false;\n                }\n        }\n\n        //      IPv4-compatiblity check\n        if (preg_match('#(?<=:'.')' . $this->ip4 . '$#s', $aIP, $find))\n        {\n                $aIP = substr($aIP, 0, 0-strlen($find[0]));\n                $ip = explode('.', $find[0]);\n                $ip = array_map('dechex', $ip);\n                $aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3];\n                unset($find, $ip);\n        }\n\n        //      compression check\n        $aIP = explode('::', $aIP);\n        $c = count($aIP);\n        if ($c > 2)\n        {\n                return false;\n        }\n        elseif ($c == 2)\n        {\n                list($first, $second) = $aIP;\n                $first = explode(':', $first);\n                $second = explode(':', $second);\n\n                if (count($first) + count($second) > 8)\n                {\n                        return false;\n                }\n\n                while(count($first) < 8)\n                {\n                        array_push($first, '0');\n                }\n\n                array_splice($first, 8 - count($second), 8, $second);\n                $aIP = $first;\n                unset($first,$second);\n        }\n        else\n        {\n                $aIP = explode(':', $aIP[0]);\n        }\n        $c = count($aIP);\n\n        if ($c != 8)\n        {\n                return false;\n        }\n\n        //      All the pieces should be 16-bit hex strings. Are they?\n        foreach ($aIP as $piece)\n        {\n                if (!preg_match('#^[0-9a-fA-F]{4}$#s', sprintf('%04s', $piece)))\n                {\n                        return false;\n                }\n        }\n\n        return $original;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef/URI.php",
    "content": "<?php\n\n/**\n * Validates a URI as defined by RFC 3986.\n * @note Scheme-specific mechanics deferred to HTMLPurifier_URIScheme\n */\nclass HTMLPurifier_AttrDef_URI extends HTMLPurifier_AttrDef\n{\n\n    protected $parser;\n    protected $embedsResource;\n\n    /**\n     * @param $embeds_resource_resource Does the URI here result in an extra HTTP request?\n     */\n    public function __construct($embeds_resource = false) {\n        $this->parser = new HTMLPurifier_URIParser();\n        $this->embedsResource = (bool) $embeds_resource;\n    }\n\n    public function make($string) {\n        $embeds = (bool) $string;\n        return new HTMLPurifier_AttrDef_URI($embeds);\n    }\n\n    public function validate($uri, $config, $context) {\n\n        if ($config->get('URI.Disable')) return false;\n\n        $uri = $this->parseCDATA($uri);\n\n        // parse the URI\n        $uri = $this->parser->parse($uri);\n        if ($uri === false) return false;\n\n        // add embedded flag to context for validators\n        $context->register('EmbeddedURI', $this->embedsResource);\n\n        $ok = false;\n        do {\n\n            // generic validation\n            $result = $uri->validate($config, $context);\n            if (!$result) break;\n\n            // chained filtering\n            $uri_def = $config->getDefinition('URI');\n            $result = $uri_def->filter($uri, $config, $context);\n            if (!$result) break;\n\n            // scheme-specific validation\n            $scheme_obj = $uri->getSchemeObj($config, $context);\n            if (!$scheme_obj) break;\n            if ($this->embedsResource && !$scheme_obj->browsable) break;\n            $result = $scheme_obj->validate($uri, $config, $context);\n            if (!$result) break;\n\n            // Post chained filtering\n            $result = $uri_def->postFilter($uri, $config, $context);\n            if (!$result) break;\n\n            // survived gauntlet\n            $ok = true;\n\n        } while (false);\n\n        $context->destroy('EmbeddedURI');\n        if (!$ok) return false;\n\n        // back to string\n        return $uri->toString();\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrDef.php",
    "content": "<?php\n\n/**\n * Base class for all validating attribute definitions.\n *\n * This family of classes forms the core for not only HTML attribute validation,\n * but also any sort of string that needs to be validated or cleaned (which\n * means CSS properties and composite definitions are defined here too).\n * Besides defining (through code) what precisely makes the string valid,\n * subclasses are also responsible for cleaning the code if possible.\n */\n\nabstract class HTMLPurifier_AttrDef\n{\n\n    /**\n     * Tells us whether or not an HTML attribute is minimized. Has no\n     * meaning in other contexts.\n     */\n    public $minimized = false;\n\n    /**\n     * Tells us whether or not an HTML attribute is required. Has no\n     * meaning in other contexts\n     */\n    public $required = false;\n\n    /**\n     * Validates and cleans passed string according to a definition.\n     *\n     * @param $string String to be validated and cleaned.\n     * @param $config Mandatory HTMLPurifier_Config object.\n     * @param $context Mandatory HTMLPurifier_AttrContext object.\n     */\n    abstract public function validate($string, $config, $context);\n\n    /**\n     * Convenience method that parses a string as if it were CDATA.\n     *\n     * This method process a string in the manner specified at\n     * <http://www.w3.org/TR/html4/types.html#h-6.2> by removing\n     * leading and trailing whitespace, ignoring line feeds, and replacing\n     * carriage returns and tabs with spaces.  While most useful for HTML\n     * attributes specified as CDATA, it can also be applied to most CSS\n     * values.\n     *\n     * @note This method is not entirely standards compliant, as trim() removes\n     *       more types of whitespace than specified in the spec. In practice,\n     *       this is rarely a problem, as those extra characters usually have\n     *       already been removed by HTMLPurifier_Encoder.\n     *\n     * @warning This processing is inconsistent with XML's whitespace handling\n     *          as specified by section 3.3.3 and referenced XHTML 1.0 section\n     *          4.7.  However, note that we are NOT necessarily\n     *          parsing XML, thus, this behavior may still be correct. We\n     *          assume that newlines have been normalized.\n     */\n    public function parseCDATA($string) {\n        $string = trim($string);\n        $string = str_replace(array(\"\\n\", \"\\t\", \"\\r\"), ' ', $string);\n        return $string;\n    }\n\n    /**\n     * Factory method for creating this class from a string.\n     * @param $string String construction info\n     * @return Created AttrDef object corresponding to $string\n     */\n    public function make($string) {\n        // default implementation, return a flyweight of this object.\n        // If $string has an effect on the returned object (i.e. you\n        // need to overload this method), it is best\n        // to clone or instantiate new copies. (Instantiation is safer.)\n        return $this;\n    }\n\n    /**\n     * Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work\n     * properly. THIS IS A HACK!\n     */\n    protected function mungeRgb($string) {\n        return preg_replace('/rgb\\((\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\)/', 'rgb(\\1,\\2,\\3)', $string);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/Background.php",
    "content": "<?php\n\n/**\n * Pre-transform that changes proprietary background attribute to CSS.\n */\nclass HTMLPurifier_AttrTransform_Background extends HTMLPurifier_AttrTransform {\n\n    public function transform($attr, $config, $context) {\n\n        if (!isset($attr['background'])) return $attr;\n\n        $background = $this->confiscateAttr($attr, 'background');\n        // some validation should happen here\n\n        $this->prependCSS($attr, \"background-image:url($background);\");\n\n        return $attr;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/BdoDir.php",
    "content": "<?php\n\n// this MUST be placed in post, as it assumes that any value in dir is valid\n\n/**\n * Post-trasnform that ensures that bdo tags have the dir attribute set.\n */\nclass HTMLPurifier_AttrTransform_BdoDir extends HTMLPurifier_AttrTransform\n{\n\n    public function transform($attr, $config, $context) {\n        if (isset($attr['dir'])) return $attr;\n        $attr['dir'] = $config->get('Attr.DefaultTextDir');\n        return $attr;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/BgColor.php",
    "content": "<?php\n\n/**\n * Pre-transform that changes deprecated bgcolor attribute to CSS.\n */\nclass HTMLPurifier_AttrTransform_BgColor extends HTMLPurifier_AttrTransform {\n\n    public function transform($attr, $config, $context) {\n\n        if (!isset($attr['bgcolor'])) return $attr;\n\n        $bgcolor = $this->confiscateAttr($attr, 'bgcolor');\n        // some validation should happen here\n\n        $this->prependCSS($attr, \"background-color:$bgcolor;\");\n\n        return $attr;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/BoolToCSS.php",
    "content": "<?php\n\n/**\n * Pre-transform that changes converts a boolean attribute to fixed CSS\n */\nclass HTMLPurifier_AttrTransform_BoolToCSS extends HTMLPurifier_AttrTransform {\n\n    /**\n     * Name of boolean attribute that is trigger\n     */\n    protected $attr;\n\n    /**\n     * CSS declarations to add to style, needs trailing semicolon\n     */\n    protected $css;\n\n    /**\n     * @param $attr string attribute name to convert from\n     * @param $css string CSS declarations to add to style (needs semicolon)\n     */\n    public function __construct($attr, $css) {\n        $this->attr = $attr;\n        $this->css  = $css;\n    }\n\n    public function transform($attr, $config, $context) {\n        if (!isset($attr[$this->attr])) return $attr;\n        unset($attr[$this->attr]);\n        $this->prependCSS($attr, $this->css);\n        return $attr;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/Border.php",
    "content": "<?php\n\n/**\n * Pre-transform that changes deprecated border attribute to CSS.\n */\nclass HTMLPurifier_AttrTransform_Border extends HTMLPurifier_AttrTransform {\n\n    public function transform($attr, $config, $context) {\n        if (!isset($attr['border'])) return $attr;\n        $border_width = $this->confiscateAttr($attr, 'border');\n        // some validation should happen here\n        $this->prependCSS($attr, \"border:{$border_width}px solid;\");\n        return $attr;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/EnumToCSS.php",
    "content": "<?php\n\n/**\n * Generic pre-transform that converts an attribute with a fixed number of\n * values (enumerated) to CSS.\n */\nclass HTMLPurifier_AttrTransform_EnumToCSS extends HTMLPurifier_AttrTransform {\n\n    /**\n     * Name of attribute to transform from\n     */\n    protected $attr;\n\n    /**\n     * Lookup array of attribute values to CSS\n     */\n    protected $enumToCSS = array();\n\n    /**\n     * Case sensitivity of the matching\n     * @warning Currently can only be guaranteed to work with ASCII\n     *          values.\n     */\n    protected $caseSensitive = false;\n\n    /**\n     * @param $attr String attribute name to transform from\n     * @param $enumToCSS Lookup array of attribute values to CSS\n     * @param $case_sensitive Boolean case sensitivity indicator, default false\n     */\n    public function __construct($attr, $enum_to_css, $case_sensitive = false) {\n        $this->attr = $attr;\n        $this->enumToCSS = $enum_to_css;\n        $this->caseSensitive = (bool) $case_sensitive;\n    }\n\n    public function transform($attr, $config, $context) {\n\n        if (!isset($attr[$this->attr])) return $attr;\n\n        $value = trim($attr[$this->attr]);\n        unset($attr[$this->attr]);\n\n        if (!$this->caseSensitive) $value = strtolower($value);\n\n        if (!isset($this->enumToCSS[$value])) {\n            return $attr;\n        }\n\n        $this->prependCSS($attr, $this->enumToCSS[$value]);\n\n        return $attr;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/ImgRequired.php",
    "content": "<?php\n\n// must be called POST validation\n\n/**\n * Transform that supplies default values for the src and alt attributes\n * in img tags, as well as prevents the img tag from being removed\n * because of a missing alt tag. This needs to be registered as both\n * a pre and post attribute transform.\n */\nclass HTMLPurifier_AttrTransform_ImgRequired extends HTMLPurifier_AttrTransform\n{\n\n    public function transform($attr, $config, $context) {\n\n        $src = true;\n        if (!isset($attr['src'])) {\n            if ($config->get('Core.RemoveInvalidImg')) return $attr;\n            $attr['src'] = $config->get('Attr.DefaultInvalidImage');\n            $src = false;\n        }\n\n        if (!isset($attr['alt'])) {\n            if ($src) {\n                $alt = $config->get('Attr.DefaultImageAlt');\n                if ($alt === null) {\n                    $attr['alt'] = basename($attr['src']);\n                } else {\n                    $attr['alt'] = $alt;\n                }\n            } else {\n                $attr['alt'] = $config->get('Attr.DefaultInvalidImageAlt');\n            }\n        }\n\n        return $attr;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/ImgSpace.php",
    "content": "<?php\n\n/**\n * Pre-transform that changes deprecated hspace and vspace attributes to CSS\n */\nclass HTMLPurifier_AttrTransform_ImgSpace extends HTMLPurifier_AttrTransform {\n\n    protected $attr;\n    protected $css = array(\n        'hspace' => array('left', 'right'),\n        'vspace' => array('top', 'bottom')\n    );\n\n    public function __construct($attr) {\n        $this->attr = $attr;\n        if (!isset($this->css[$attr])) {\n            trigger_error(htmlspecialchars($attr) . ' is not valid space attribute');\n        }\n    }\n\n    public function transform($attr, $config, $context) {\n\n        if (!isset($attr[$this->attr])) return $attr;\n\n        $width = $this->confiscateAttr($attr, $this->attr);\n        // some validation could happen here\n\n        if (!isset($this->css[$this->attr])) return $attr;\n\n        $style = '';\n        foreach ($this->css[$this->attr] as $suffix) {\n            $property = \"margin-$suffix\";\n            $style .= \"$property:{$width}px;\";\n        }\n\n        $this->prependCSS($attr, $style);\n\n        return $attr;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/Input.php",
    "content": "<?php\n\n/**\n * Performs miscellaneous cross attribute validation and filtering for\n * input elements. This is meant to be a post-transform.\n */\nclass HTMLPurifier_AttrTransform_Input extends HTMLPurifier_AttrTransform {\n\n    protected $pixels;\n\n    public function __construct() {\n        $this->pixels = new HTMLPurifier_AttrDef_HTML_Pixels();\n    }\n\n    public function transform($attr, $config, $context) {\n        if (!isset($attr['type'])) $t = 'text';\n        else $t = strtolower($attr['type']);\n        if (isset($attr['checked']) && $t !== 'radio' && $t !== 'checkbox') {\n            unset($attr['checked']);\n        }\n        if (isset($attr['maxlength']) && $t !== 'text' && $t !== 'password') {\n            unset($attr['maxlength']);\n        }\n        if (isset($attr['size']) && $t !== 'text' && $t !== 'password') {\n            $result = $this->pixels->validate($attr['size'], $config, $context);\n            if ($result === false) unset($attr['size']);\n            else $attr['size'] = $result;\n        }\n        if (isset($attr['src']) && $t !== 'image') {\n            unset($attr['src']);\n        }\n        if (!isset($attr['value']) && ($t === 'radio' || $t === 'checkbox')) {\n            $attr['value'] = '';\n        }\n        return $attr;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/Lang.php",
    "content": "<?php\n\n/**\n * Post-transform that copies lang's value to xml:lang (and vice-versa)\n * @note Theoretically speaking, this could be a pre-transform, but putting\n *       post is more efficient.\n */\nclass HTMLPurifier_AttrTransform_Lang extends HTMLPurifier_AttrTransform\n{\n\n    public function transform($attr, $config, $context) {\n\n        $lang     = isset($attr['lang']) ? $attr['lang'] : false;\n        $xml_lang = isset($attr['xml:lang']) ? $attr['xml:lang'] : false;\n\n        if ($lang !== false && $xml_lang === false) {\n            $attr['xml:lang'] = $lang;\n        } elseif ($xml_lang !== false) {\n            $attr['lang'] = $xml_lang;\n        }\n\n        return $attr;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/Length.php",
    "content": "<?php\n\n/**\n * Class for handling width/height length attribute transformations to CSS\n */\nclass HTMLPurifier_AttrTransform_Length extends HTMLPurifier_AttrTransform\n{\n\n    protected $name;\n    protected $cssName;\n\n    public function __construct($name, $css_name = null) {\n        $this->name = $name;\n        $this->cssName = $css_name ? $css_name : $name;\n    }\n\n    public function transform($attr, $config, $context) {\n        if (!isset($attr[$this->name])) return $attr;\n        $length = $this->confiscateAttr($attr, $this->name);\n        if(ctype_digit($length)) $length .= 'px';\n        $this->prependCSS($attr, $this->cssName . \":$length;\");\n        return $attr;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/Name.php",
    "content": "<?php\n\n/**\n * Pre-transform that changes deprecated name attribute to ID if necessary\n */\nclass HTMLPurifier_AttrTransform_Name extends HTMLPurifier_AttrTransform\n{\n\n    public function transform($attr, $config, $context) {\n        // Abort early if we're using relaxed definition of name\n        if ($config->get('HTML.Attr.Name.UseCDATA')) return $attr;\n        if (!isset($attr['name'])) return $attr;\n        $id = $this->confiscateAttr($attr, 'name');\n        if ( isset($attr['id']))   return $attr;\n        $attr['id'] = $id;\n        return $attr;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/NameSync.php",
    "content": "<?php\n\n/**\n * Post-transform that performs validation to the name attribute; if\n * it is present with an equivalent id attribute, it is passed through;\n * otherwise validation is performed.\n */\nclass HTMLPurifier_AttrTransform_NameSync extends HTMLPurifier_AttrTransform\n{\n\n    public function __construct() {\n        $this->idDef = new HTMLPurifier_AttrDef_HTML_ID();\n    }\n\n    public function transform($attr, $config, $context) {\n        if (!isset($attr['name'])) return $attr;\n        $name = $attr['name'];\n        if (isset($attr['id']) && $attr['id'] === $name) return $attr;\n        $result = $this->idDef->validate($name, $config, $context);\n        if ($result === false) unset($attr['name']);\n        else $attr['name'] = $result;\n        return $attr;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/SafeEmbed.php",
    "content": "<?php\n\nclass HTMLPurifier_AttrTransform_SafeEmbed extends HTMLPurifier_AttrTransform\n{\n    public $name = \"SafeEmbed\";\n\n    public function transform($attr, $config, $context) {\n        $attr['allowscriptaccess'] = 'never';\n        $attr['allownetworking'] = 'internal';\n        $attr['type'] = 'application/x-shockwave-flash';\n        return $attr;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/SafeObject.php",
    "content": "<?php\n\n/**\n * Writes default type for all objects. Currently only supports flash.\n */\nclass HTMLPurifier_AttrTransform_SafeObject extends HTMLPurifier_AttrTransform\n{\n    public $name = \"SafeObject\";\n\n    function transform($attr, $config, $context) {\n        if (!isset($attr['type'])) $attr['type'] = 'application/x-shockwave-flash';\n        return $attr;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/SafeParam.php",
    "content": "<?php\n\n/**\n * Validates name/value pairs in param tags to be used in safe objects. This\n * will only allow name values it recognizes, and pre-fill certain attributes\n * with required values.\n *\n * @note\n *      This class only supports Flash. In the future, Quicktime support\n *      may be added.\n *\n * @warning\n *      This class expects an injector to add the necessary parameters tags.\n */\nclass HTMLPurifier_AttrTransform_SafeParam extends HTMLPurifier_AttrTransform\n{\n    public $name = \"SafeParam\";\n    private $uri;\n\n    public function __construct() {\n        $this->uri = new HTMLPurifier_AttrDef_URI(true); // embedded\n    }\n\n    public function transform($attr, $config, $context) {\n        // If we add support for other objects, we'll need to alter the\n        // transforms.\n        switch ($attr['name']) {\n            // application/x-shockwave-flash\n            // Keep this synchronized with Injector/SafeObject.php\n            case 'allowScriptAccess':\n                $attr['value'] = 'never';\n                break;\n            case 'allowNetworking':\n                $attr['value'] = 'internal';\n                break;\n            case 'wmode':\n                $attr['value'] = 'window';\n                break;\n            case 'movie':\n                $attr['value'] = $this->uri->validate($attr['value'], $config, $context);\n                break;\n            // add other cases to support other param name/value pairs\n            default:\n                $attr['name'] = $attr['value'] = null;\n        }\n        return $attr;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/ScriptRequired.php",
    "content": "<?php\n\n/**\n * Implements required attribute stipulation for <script>\n */\nclass HTMLPurifier_AttrTransform_ScriptRequired extends HTMLPurifier_AttrTransform\n{\n    public function transform($attr, $config, $context) {\n        if (!isset($attr['type'])) {\n            $attr['type'] = 'text/javascript';\n        }\n        return $attr;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform/Textarea.php",
    "content": "<?php\n\n/**\n * Sets height/width defaults for <textarea>\n */\nclass HTMLPurifier_AttrTransform_Textarea extends HTMLPurifier_AttrTransform\n{\n\n    public function transform($attr, $config, $context) {\n        // Calculated from Firefox\n        if (!isset($attr['cols'])) $attr['cols'] = '22';\n        if (!isset($attr['rows'])) $attr['rows'] = '3';\n        return $attr;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTransform.php",
    "content": "<?php\n\n/**\n * Processes an entire attribute array for corrections needing multiple values.\n *\n * Occasionally, a certain attribute will need to be removed and popped onto\n * another value.  Instead of creating a complex return syntax for\n * HTMLPurifier_AttrDef, we just pass the whole attribute array to a\n * specialized object and have that do the special work.  That is the\n * family of HTMLPurifier_AttrTransform.\n *\n * An attribute transformation can be assigned to run before or after\n * HTMLPurifier_AttrDef validation.  See HTMLPurifier_HTMLDefinition for\n * more details.\n */\n\nabstract class HTMLPurifier_AttrTransform\n{\n\n    /**\n     * Abstract: makes changes to the attributes dependent on multiple values.\n     *\n     * @param $attr Assoc array of attributes, usually from\n     *              HTMLPurifier_Token_Tag::$attr\n     * @param $config Mandatory HTMLPurifier_Config object.\n     * @param $context Mandatory HTMLPurifier_Context object\n     * @returns Processed attribute array.\n     */\n    abstract public function transform($attr, $config, $context);\n\n    /**\n     * Prepends CSS properties to the style attribute, creating the\n     * attribute if it doesn't exist.\n     * @param $attr Attribute array to process (passed by reference)\n     * @param $css CSS to prepend\n     */\n    public function prependCSS(&$attr, $css) {\n        $attr['style'] = isset($attr['style']) ? $attr['style'] : '';\n        $attr['style'] = $css . $attr['style'];\n    }\n\n    /**\n     * Retrieves and removes an attribute\n     * @param $attr Attribute array to process (passed by reference)\n     * @param $key Key of attribute to confiscate\n     */\n    public function confiscateAttr(&$attr, $key) {\n        if (!isset($attr[$key])) return null;\n        $value = $attr[$key];\n        unset($attr[$key]);\n        return $value;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrTypes.php",
    "content": "<?php\n\n/**\n * Provides lookup array of attribute types to HTMLPurifier_AttrDef objects\n */\nclass HTMLPurifier_AttrTypes\n{\n    /**\n     * Lookup array of attribute string identifiers to concrete implementations\n     */\n    protected $info = array();\n\n    /**\n     * Constructs the info array, supplying default implementations for attribute\n     * types.\n     */\n    public function __construct() {\n        // pseudo-types, must be instantiated via shorthand\n        $this->info['Enum']    = new HTMLPurifier_AttrDef_Enum();\n        $this->info['Bool']    = new HTMLPurifier_AttrDef_HTML_Bool();\n\n        $this->info['CDATA']    = new HTMLPurifier_AttrDef_Text();\n        $this->info['ID']       = new HTMLPurifier_AttrDef_HTML_ID();\n        $this->info['Length']   = new HTMLPurifier_AttrDef_HTML_Length();\n        $this->info['MultiLength'] = new HTMLPurifier_AttrDef_HTML_MultiLength();\n        $this->info['NMTOKENS'] = new HTMLPurifier_AttrDef_HTML_Nmtokens();\n        $this->info['Pixels']   = new HTMLPurifier_AttrDef_HTML_Pixels();\n        $this->info['Text']     = new HTMLPurifier_AttrDef_Text();\n        $this->info['URI']      = new HTMLPurifier_AttrDef_URI();\n        $this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang();\n        $this->info['Color']    = new HTMLPurifier_AttrDef_HTML_Color();\n\n        // unimplemented aliases\n        $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text();\n        $this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text();\n        $this->info['Charsets'] = new HTMLPurifier_AttrDef_Text();\n        $this->info['Character'] = new HTMLPurifier_AttrDef_Text();\n\n        // \"proprietary\" types\n        $this->info['Class'] = new HTMLPurifier_AttrDef_HTML_Class();\n\n        // number is really a positive integer (one or more digits)\n        // FIXME: ^^ not always, see start and value of list items\n        $this->info['Number']   = new HTMLPurifier_AttrDef_Integer(false, false, true);\n    }\n\n    /**\n     * Retrieves a type\n     * @param $type String type name\n     * @return Object AttrDef for type\n     */\n    public function get($type) {\n\n        // determine if there is any extra info tacked on\n        if (strpos($type, '#') !== false) list($type, $string) = explode('#', $type, 2);\n        else $string = '';\n\n        if (!isset($this->info[$type])) {\n            trigger_error('Cannot retrieve undefined attribute type ' . $type, E_USER_ERROR);\n            return;\n        }\n\n        return $this->info[$type]->make($string);\n\n    }\n\n    /**\n     * Sets a new implementation for a type\n     * @param $type String type name\n     * @param $impl Object AttrDef for type\n     */\n    public function set($type, $impl) {\n        $this->info[$type] = $impl;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/AttrValidator.php",
    "content": "<?php\n\n/**\n * Validates the attributes of a token. Doesn't manage required attributes\n * very well. The only reason we factored this out was because RemoveForeignElements\n * also needed it besides ValidateAttributes.\n */\nclass HTMLPurifier_AttrValidator\n{\n\n    /**\n     * Validates the attributes of a token, returning a modified token\n     * that has valid tokens\n     * @param $token Reference to token to validate. We require a reference\n     *     because the operation this class performs on the token are\n     *     not atomic, so the context CurrentToken to be updated\n     *     throughout\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     */\n    public function validateToken(&$token, &$config, $context) {\n\n        $definition = $config->getHTMLDefinition();\n        $e =& $context->get('ErrorCollector', true);\n\n        // initialize IDAccumulator if necessary\n        $ok =& $context->get('IDAccumulator', true);\n        if (!$ok) {\n            $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);\n            $context->register('IDAccumulator', $id_accumulator);\n        }\n\n        // initialize CurrentToken if necessary\n        $current_token =& $context->get('CurrentToken', true);\n        if (!$current_token) $context->register('CurrentToken', $token);\n\n        if (\n            !$token instanceof HTMLPurifier_Token_Start &&\n            !$token instanceof HTMLPurifier_Token_Empty\n        ) return $token;\n\n        // create alias to global definition array, see also $defs\n        // DEFINITION CALL\n        $d_defs = $definition->info_global_attr;\n\n        // don't update token until the very end, to ensure an atomic update\n        $attr = $token->attr;\n\n        // do global transformations (pre)\n        // nothing currently utilizes this\n        foreach ($definition->info_attr_transform_pre as $transform) {\n            $attr = $transform->transform($o = $attr, $config, $context);\n            if ($e) {\n                if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);\n            }\n        }\n\n        // do local transformations only applicable to this element (pre)\n        // ex. <p align=\"right\"> to <p style=\"text-align:right;\">\n        foreach ($definition->info[$token->name]->attr_transform_pre as $transform) {\n            $attr = $transform->transform($o = $attr, $config, $context);\n            if ($e) {\n                if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);\n            }\n        }\n\n        // create alias to this element's attribute definition array, see\n        // also $d_defs (global attribute definition array)\n        // DEFINITION CALL\n        $defs = $definition->info[$token->name]->attr;\n\n        $attr_key = false;\n        $context->register('CurrentAttr', $attr_key);\n\n        // iterate through all the attribute keypairs\n        // Watch out for name collisions: $key has previously been used\n        foreach ($attr as $attr_key => $value) {\n\n            // call the definition\n            if ( isset($defs[$attr_key]) ) {\n                // there is a local definition defined\n                if ($defs[$attr_key] === false) {\n                    // We've explicitly been told not to allow this element.\n                    // This is usually when there's a global definition\n                    // that must be overridden.\n                    // Theoretically speaking, we could have a\n                    // AttrDef_DenyAll, but this is faster!\n                    $result = false;\n                } else {\n                    // validate according to the element's definition\n                    $result = $defs[$attr_key]->validate(\n                                    $value, $config, $context\n                               );\n                }\n            } elseif ( isset($d_defs[$attr_key]) ) {\n                // there is a global definition defined, validate according\n                // to the global definition\n                $result = $d_defs[$attr_key]->validate(\n                                $value, $config, $context\n                           );\n            } else {\n                // system never heard of the attribute? DELETE!\n                $result = false;\n            }\n\n            // put the results into effect\n            if ($result === false || $result === null) {\n                // this is a generic error message that should replaced\n                // with more specific ones when possible\n                if ($e) $e->send(E_ERROR, 'AttrValidator: Attribute removed');\n\n                // remove the attribute\n                unset($attr[$attr_key]);\n            } elseif (is_string($result)) {\n                // generally, if a substitution is happening, there\n                // was some sort of implicit correction going on. We'll\n                // delegate it to the attribute classes to say exactly what.\n\n                // simple substitution\n                $attr[$attr_key] = $result;\n            } else {\n                // nothing happens\n            }\n\n            // we'd also want slightly more complicated substitution\n            // involving an array as the return value,\n            // although we're not sure how colliding attributes would\n            // resolve (certain ones would be completely overriden,\n            // others would prepend themselves).\n        }\n\n        $context->destroy('CurrentAttr');\n\n        // post transforms\n\n        // global (error reporting untested)\n        foreach ($definition->info_attr_transform_post as $transform) {\n            $attr = $transform->transform($o = $attr, $config, $context);\n            if ($e) {\n                if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);\n            }\n        }\n\n        // local (error reporting untested)\n        foreach ($definition->info[$token->name]->attr_transform_post as $transform) {\n            $attr = $transform->transform($o = $attr, $config, $context);\n            if ($e) {\n                if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);\n            }\n        }\n\n        $token->attr = $attr;\n\n        // destroy CurrentToken if we made it ourselves\n        if (!$current_token) $context->destroy('CurrentToken');\n\n    }\n\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Bootstrap.php",
    "content": "<?php\n\n// constants are slow, so we use as few as possible\nif (!defined('HTMLPURIFIER_PREFIX')) {\n    define('HTMLPURIFIER_PREFIX', realpath(dirname(__FILE__) . '/..'));\n}\n\n// accomodations for versions earlier than 5.0.2\n// borrowed from PHP_Compat, LGPL licensed, by Aidan Lister <aidan@php.net>\nif (!defined('PHP_EOL')) {\n    switch (strtoupper(substr(PHP_OS, 0, 3))) {\n        case 'WIN':\n            define('PHP_EOL', \"\\r\\n\");\n            break;\n        case 'DAR':\n            define('PHP_EOL', \"\\r\");\n            break;\n        default:\n            define('PHP_EOL', \"\\n\");\n    }\n}\n\n/**\n * Bootstrap class that contains meta-functionality for HTML Purifier such as\n * the autoload function.\n *\n * @note\n *      This class may be used without any other files from HTML Purifier.\n */\nclass HTMLPurifier_Bootstrap\n{\n\n    /**\n     * Autoload function for HTML Purifier\n     * @param $class Class to load\n     */\n    public static function autoload($class) {\n        $file = HTMLPurifier_Bootstrap::getPath($class);\n        if (!$file) return false;\n        require HTMLPURIFIER_PREFIX . '/' . $file;\n        return true;\n    }\n\n    /**\n     * Returns the path for a specific class.\n     */\n    public static function getPath($class) {\n        if (strncmp('HTMLPurifier', $class, 12) !== 0) return false;\n        // Custom implementations\n        if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) {\n            $code = str_replace('_', '-', substr($class, 22));\n            $file = 'HTMLPurifier/Language/classes/' . $code . '.php';\n        } else {\n            $file = str_replace('_', '/', $class) . '.php';\n        }\n        if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) return false;\n        return $file;\n    }\n\n    /**\n     * \"Pre-registers\" our autoloader on the SPL stack.\n     */\n    public static function registerAutoload() {\n        $autoload = array('HTMLPurifier_Bootstrap', 'autoload');\n        if ( ($funcs = spl_autoload_functions()) === false ) {\n            spl_autoload_register($autoload);\n        } elseif (function_exists('spl_autoload_unregister')) {\n            $compat = version_compare(PHP_VERSION, '5.1.2', '<=') &&\n                      version_compare(PHP_VERSION, '5.1.0', '>=');\n            foreach ($funcs as $func) {\n                if (is_array($func)) {\n                    // :TRICKY: There are some compatibility issues and some\n                    // places where we need to error out\n                    $reflector = new ReflectionMethod($func[0], $func[1]);\n                    if (!$reflector->isStatic()) {\n                        throw new Exception('\n                            HTML Purifier autoloader registrar is not compatible\n                            with non-static object methods due to PHP Bug #44144;\n                            Please do not use HTMLPurifier.autoload.php (or any\n                            file that includes this file); instead, place the code:\n                            spl_autoload_register(array(\\'HTMLPurifier_Bootstrap\\', \\'autoload\\'))\n                            after your own autoloaders.\n                        ');\n                    }\n                    // Suprisingly, spl_autoload_register supports the\n                    // Class::staticMethod callback format, although call_user_func doesn't\n                    if ($compat) $func = implode('::', $func);\n                }\n                spl_autoload_unregister($func);\n            }\n            spl_autoload_register($autoload);\n            foreach ($funcs as $func) spl_autoload_register($func);\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/CSSDefinition.php",
    "content": "<?php\n\n/**\n * Defines allowed CSS attributes and what their values are.\n * @see HTMLPurifier_HTMLDefinition\n */\nclass HTMLPurifier_CSSDefinition extends HTMLPurifier_Definition\n{\n\n    public $type = 'CSS';\n\n    /**\n     * Assoc array of attribute name to definition object.\n     */\n    public $info = array();\n\n    /**\n     * Constructs the info array.  The meat of this class.\n     */\n    protected function doSetup($config) {\n\n        $this->info['text-align'] = new HTMLPurifier_AttrDef_Enum(\n            array('left', 'right', 'center', 'justify'), false);\n\n        $border_style =\n        $this->info['border-bottom-style'] =\n        $this->info['border-right-style'] =\n        $this->info['border-left-style'] =\n        $this->info['border-top-style'] =  new HTMLPurifier_AttrDef_Enum(\n            array('none', 'hidden', 'dotted', 'dashed', 'solid', 'double',\n            'groove', 'ridge', 'inset', 'outset'), false);\n\n        $this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style);\n\n        $this->info['clear'] = new HTMLPurifier_AttrDef_Enum(\n            array('none', 'left', 'right', 'both'), false);\n        $this->info['float'] = new HTMLPurifier_AttrDef_Enum(\n            array('none', 'left', 'right'), false);\n        $this->info['font-style'] = new HTMLPurifier_AttrDef_Enum(\n            array('normal', 'italic', 'oblique'), false);\n        $this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum(\n            array('normal', 'small-caps'), false);\n\n        $uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite(\n            array(\n                new HTMLPurifier_AttrDef_Enum(array('none')),\n                new HTMLPurifier_AttrDef_CSS_URI()\n            )\n        );\n\n        $this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum(\n            array('inside', 'outside'), false);\n        $this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum(\n            array('disc', 'circle', 'square', 'decimal', 'lower-roman',\n            'upper-roman', 'lower-alpha', 'upper-alpha', 'none'), false);\n        $this->info['list-style-image'] = $uri_or_none;\n\n        $this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config);\n\n        $this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum(\n            array('capitalize', 'uppercase', 'lowercase', 'none'), false);\n        $this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color();\n\n        $this->info['background-image'] = $uri_or_none;\n        $this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum(\n            array('repeat', 'repeat-x', 'repeat-y', 'no-repeat')\n        );\n        $this->info['background-attachment'] = new HTMLPurifier_AttrDef_Enum(\n            array('scroll', 'fixed')\n        );\n        $this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition();\n\n        $border_color =\n        $this->info['border-top-color'] =\n        $this->info['border-bottom-color'] =\n        $this->info['border-left-color'] =\n        $this->info['border-right-color'] =\n        $this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_Enum(array('transparent')),\n            new HTMLPurifier_AttrDef_CSS_Color()\n        ));\n\n        $this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config);\n\n        $this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color);\n\n        $border_width =\n        $this->info['border-top-width'] =\n        $this->info['border-bottom-width'] =\n        $this->info['border-left-width'] =\n        $this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')),\n            new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative\n        ));\n\n        $this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width);\n\n        $this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_Enum(array('normal')),\n            new HTMLPurifier_AttrDef_CSS_Length()\n        ));\n\n        $this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_Enum(array('normal')),\n            new HTMLPurifier_AttrDef_CSS_Length()\n        ));\n\n        $this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_Enum(array('xx-small', 'x-small',\n                'small', 'medium', 'large', 'x-large', 'xx-large',\n                'larger', 'smaller')),\n            new HTMLPurifier_AttrDef_CSS_Percentage(),\n            new HTMLPurifier_AttrDef_CSS_Length()\n        ));\n\n        $this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_Enum(array('normal')),\n            new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives\n            new HTMLPurifier_AttrDef_CSS_Length('0'),\n            new HTMLPurifier_AttrDef_CSS_Percentage(true)\n        ));\n\n        $margin =\n        $this->info['margin-top'] =\n        $this->info['margin-bottom'] =\n        $this->info['margin-left'] =\n        $this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_CSS_Length(),\n            new HTMLPurifier_AttrDef_CSS_Percentage(),\n            new HTMLPurifier_AttrDef_Enum(array('auto'))\n        ));\n\n        $this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin);\n\n        // non-negative\n        $padding =\n        $this->info['padding-top'] =\n        $this->info['padding-bottom'] =\n        $this->info['padding-left'] =\n        $this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_CSS_Length('0'),\n            new HTMLPurifier_AttrDef_CSS_Percentage(true)\n        ));\n\n        $this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding);\n\n        $this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_CSS_Length(),\n            new HTMLPurifier_AttrDef_CSS_Percentage()\n        ));\n\n        $trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_CSS_Length('0'),\n            new HTMLPurifier_AttrDef_CSS_Percentage(true),\n            new HTMLPurifier_AttrDef_Enum(array('auto'))\n        ));\n        $max = $config->get('CSS.MaxImgLength');\n\n        $this->info['width'] =\n        $this->info['height'] =\n            $max === null ?\n            $trusted_wh :\n            new HTMLPurifier_AttrDef_Switch('img',\n                // For img tags:\n                new HTMLPurifier_AttrDef_CSS_Composite(array(\n                    new HTMLPurifier_AttrDef_CSS_Length('0', $max),\n                    new HTMLPurifier_AttrDef_Enum(array('auto'))\n                )),\n                // For everyone else:\n                $trusted_wh\n            );\n\n        $this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration();\n\n        $this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily();\n\n        // this could use specialized code\n        $this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum(\n            array('normal', 'bold', 'bolder', 'lighter', '100', '200', '300',\n            '400', '500', '600', '700', '800', '900'), false);\n\n        // MUST be called after other font properties, as it references\n        // a CSSDefinition object\n        $this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config);\n\n        // same here\n        $this->info['border'] =\n        $this->info['border-bottom'] =\n        $this->info['border-top'] =\n        $this->info['border-left'] =\n        $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config);\n\n        $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum(array(\n            'collapse', 'separate'));\n\n        $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum(array(\n            'top', 'bottom'));\n\n        $this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum(array(\n            'auto', 'fixed'));\n\n        $this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite(array(\n            new HTMLPurifier_AttrDef_Enum(array('baseline', 'sub', 'super',\n                'top', 'text-top', 'middle', 'bottom', 'text-bottom')),\n            new HTMLPurifier_AttrDef_CSS_Length(),\n            new HTMLPurifier_AttrDef_CSS_Percentage()\n        ));\n\n        $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2);\n\n        // partial support\n        $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum(array('nowrap'));\n\n        if ($config->get('CSS.Proprietary')) {\n            $this->doSetupProprietary($config);\n        }\n\n        if ($config->get('CSS.AllowTricky')) {\n            $this->doSetupTricky($config);\n        }\n\n        $allow_important = $config->get('CSS.AllowImportant');\n        // wrap all attr-defs with decorator that handles !important\n        foreach ($this->info as $k => $v) {\n            $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important);\n        }\n\n        $this->setupConfigStuff($config);\n    }\n\n    protected function doSetupProprietary($config) {\n        // Internet Explorer only scrollbar colors\n        $this->info['scrollbar-arrow-color']        = new HTMLPurifier_AttrDef_CSS_Color();\n        $this->info['scrollbar-base-color']         = new HTMLPurifier_AttrDef_CSS_Color();\n        $this->info['scrollbar-darkshadow-color']   = new HTMLPurifier_AttrDef_CSS_Color();\n        $this->info['scrollbar-face-color']         = new HTMLPurifier_AttrDef_CSS_Color();\n        $this->info['scrollbar-highlight-color']    = new HTMLPurifier_AttrDef_CSS_Color();\n        $this->info['scrollbar-shadow-color']       = new HTMLPurifier_AttrDef_CSS_Color();\n\n        // technically not proprietary, but CSS3, and no one supports it\n        $this->info['opacity']          = new HTMLPurifier_AttrDef_CSS_AlphaValue();\n        $this->info['-moz-opacity']     = new HTMLPurifier_AttrDef_CSS_AlphaValue();\n        $this->info['-khtml-opacity']   = new HTMLPurifier_AttrDef_CSS_AlphaValue();\n\n        // only opacity, for now\n        $this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter();\n\n    }\n\n    protected function doSetupTricky($config) {\n        $this->info['display'] = new HTMLPurifier_AttrDef_Enum(array(\n            'inline', 'block', 'list-item', 'run-in', 'compact',\n            'marker', 'table', 'inline-table', 'table-row-group',\n            'table-header-group', 'table-footer-group', 'table-row',\n            'table-column-group', 'table-column', 'table-cell', 'table-caption', 'none'\n        ));\n        $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum(array(\n            'visible', 'hidden', 'collapse'\n        ));\n        $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll'));\n    }\n\n\n    /**\n     * Performs extra config-based processing. Based off of\n     * HTMLPurifier_HTMLDefinition.\n     * @todo Refactor duplicate elements into common class (probably using\n     *       composition, not inheritance).\n     */\n    protected function setupConfigStuff($config) {\n\n        // setup allowed elements\n        $support = \"(for information on implementing this, see the \".\n                   \"support forums) \";\n        $allowed_attributes = $config->get('CSS.AllowedProperties');\n        if ($allowed_attributes !== null) {\n            foreach ($this->info as $name => $d) {\n                if(!isset($allowed_attributes[$name])) unset($this->info[$name]);\n                unset($allowed_attributes[$name]);\n            }\n            // emit errors\n            foreach ($allowed_attributes as $name => $d) {\n                // :TODO: Is this htmlspecialchars() call really necessary?\n                $name = htmlspecialchars($name);\n                trigger_error(\"Style attribute '$name' is not supported $support\", E_USER_WARNING);\n            }\n        }\n\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ChildDef/Chameleon.php",
    "content": "<?php\n\n/**\n * Definition that uses different definitions depending on context.\n *\n * The del and ins tags are notable because they allow different types of\n * elements depending on whether or not they're in a block or inline context.\n * Chameleon allows this behavior to happen by using two different\n * definitions depending on context.  While this somewhat generalized,\n * it is specifically intended for those two tags.\n */\nclass HTMLPurifier_ChildDef_Chameleon extends HTMLPurifier_ChildDef\n{\n\n    /**\n     * Instance of the definition object to use when inline. Usually stricter.\n     */\n    public $inline;\n\n    /**\n     * Instance of the definition object to use when block.\n     */\n    public $block;\n\n    public $type = 'chameleon';\n\n    /**\n     * @param $inline List of elements to allow when inline.\n     * @param $block List of elements to allow when block.\n     */\n    public function __construct($inline, $block) {\n        $this->inline = new HTMLPurifier_ChildDef_Optional($inline);\n        $this->block  = new HTMLPurifier_ChildDef_Optional($block);\n        $this->elements = $this->block->elements;\n    }\n\n    public function validateChildren($tokens_of_children, $config, $context) {\n        if ($context->get('IsInline') === false) {\n            return $this->block->validateChildren(\n                $tokens_of_children, $config, $context);\n        } else {\n            return $this->inline->validateChildren(\n                $tokens_of_children, $config, $context);\n        }\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ChildDef/Custom.php",
    "content": "<?php\n\n/**\n * Custom validation class, accepts DTD child definitions\n *\n * @warning Currently this class is an all or nothing proposition, that is,\n *          it will only give a bool return value.\n */\nclass HTMLPurifier_ChildDef_Custom extends HTMLPurifier_ChildDef\n{\n    public $type = 'custom';\n    public $allow_empty = false;\n    /**\n     * Allowed child pattern as defined by the DTD\n     */\n    public $dtd_regex;\n    /**\n     * PCRE regex derived from $dtd_regex\n     * @private\n     */\n    private $_pcre_regex;\n    /**\n     * @param $dtd_regex Allowed child pattern from the DTD\n     */\n    public function __construct($dtd_regex) {\n        $this->dtd_regex = $dtd_regex;\n        $this->_compileRegex();\n    }\n    /**\n     * Compiles the PCRE regex from a DTD regex ($dtd_regex to $_pcre_regex)\n     */\n    protected function _compileRegex() {\n        $raw = str_replace(' ', '', $this->dtd_regex);\n        if ($raw{0} != '(') {\n            $raw = \"($raw)\";\n        }\n        $el = '[#a-zA-Z0-9_.-]+';\n        $reg = $raw;\n\n        // COMPLICATED! AND MIGHT BE BUGGY! I HAVE NO CLUE WHAT I'M\n        // DOING! Seriously: if there's problems, please report them.\n\n        // collect all elements into the $elements array\n        preg_match_all(\"/$el/\", $reg, $matches);\n        foreach ($matches[0] as $match) {\n            $this->elements[$match] = true;\n        }\n\n        // setup all elements as parentheticals with leading commas\n        $reg = preg_replace(\"/$el/\", '(,\\\\0)', $reg);\n\n        // remove commas when they were not solicited\n        $reg = preg_replace(\"/([^,(|]\\(+),/\", '\\\\1', $reg);\n\n        // remove all non-paranthetical commas: they are handled by first regex\n        $reg = preg_replace(\"/,\\(/\", '(', $reg);\n\n        $this->_pcre_regex = $reg;\n    }\n    public function validateChildren($tokens_of_children, $config, $context) {\n        $list_of_children = '';\n        $nesting = 0; // depth into the nest\n        foreach ($tokens_of_children as $token) {\n            if (!empty($token->is_whitespace)) continue;\n\n            $is_child = ($nesting == 0); // direct\n\n            if ($token instanceof HTMLPurifier_Token_Start) {\n                $nesting++;\n            } elseif ($token instanceof HTMLPurifier_Token_End) {\n                $nesting--;\n            }\n\n            if ($is_child) {\n                $list_of_children .= $token->name . ',';\n            }\n        }\n        // add leading comma to deal with stray comma declarations\n        $list_of_children = ',' . rtrim($list_of_children, ',');\n        $okay =\n            preg_match(\n                '/^,?'.$this->_pcre_regex.'$/',\n                $list_of_children\n            );\n\n        return (bool) $okay;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ChildDef/Empty.php",
    "content": "<?php\n\n/**\n * Definition that disallows all elements.\n * @warning validateChildren() in this class is actually never called, because\n *          empty elements are corrected in HTMLPurifier_Strategy_MakeWellFormed\n *          before child definitions are parsed in earnest by\n *          HTMLPurifier_Strategy_FixNesting.\n */\nclass HTMLPurifier_ChildDef_Empty extends HTMLPurifier_ChildDef\n{\n    public $allow_empty = true;\n    public $type = 'empty';\n    public function __construct() {}\n    public function validateChildren($tokens_of_children, $config, $context) {\n        return array();\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ChildDef/Optional.php",
    "content": "<?php\n\n/**\n * Definition that allows a set of elements, and allows no children.\n * @note This is a hack to reuse code from HTMLPurifier_ChildDef_Required,\n *       really, one shouldn't inherit from the other.  Only altered behavior\n *       is to overload a returned false with an array.  Thus, it will never\n *       return false.\n */\nclass HTMLPurifier_ChildDef_Optional extends HTMLPurifier_ChildDef_Required\n{\n    public $allow_empty = true;\n    public $type = 'optional';\n    public function validateChildren($tokens_of_children, $config, $context) {\n        $result = parent::validateChildren($tokens_of_children, $config, $context);\n        // we assume that $tokens_of_children is not modified\n        if ($result === false) {\n            if (empty($tokens_of_children)) return true;\n            elseif ($this->whitespace) return $tokens_of_children;\n            else return array();\n        }\n        return $result;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ChildDef/Required.php",
    "content": "<?php\n\n/**\n * Definition that allows a set of elements, but disallows empty children.\n */\nclass HTMLPurifier_ChildDef_Required extends HTMLPurifier_ChildDef\n{\n    /**\n     * Lookup table of allowed elements.\n     * @public\n     */\n    public $elements = array();\n    /**\n     * Whether or not the last passed node was all whitespace.\n     */\n    protected $whitespace = false;\n    /**\n     * @param $elements List of allowed element names (lowercase).\n     */\n    public function __construct($elements) {\n        if (is_string($elements)) {\n            $elements = str_replace(' ', '', $elements);\n            $elements = explode('|', $elements);\n        }\n        $keys = array_keys($elements);\n        if ($keys == array_keys($keys)) {\n            $elements = array_flip($elements);\n            foreach ($elements as $i => $x) {\n                $elements[$i] = true;\n                if (empty($i)) unset($elements[$i]); // remove blank\n            }\n        }\n        $this->elements = $elements;\n    }\n    public $allow_empty = false;\n    public $type = 'required';\n    public function validateChildren($tokens_of_children, $config, $context) {\n        // Flag for subclasses\n        $this->whitespace = false;\n\n        // if there are no tokens, delete parent node\n        if (empty($tokens_of_children)) return false;\n\n        // the new set of children\n        $result = array();\n\n        // current depth into the nest\n        $nesting = 0;\n\n        // whether or not we're deleting a node\n        $is_deleting = false;\n\n        // whether or not parsed character data is allowed\n        // this controls whether or not we silently drop a tag\n        // or generate escaped HTML from it\n        $pcdata_allowed = isset($this->elements['#PCDATA']);\n\n        // a little sanity check to make sure it's not ALL whitespace\n        $all_whitespace = true;\n\n        // some configuration\n        $escape_invalid_children = $config->get('Core.EscapeInvalidChildren');\n\n        // generator\n        $gen = new HTMLPurifier_Generator($config, $context);\n\n        foreach ($tokens_of_children as $token) {\n            if (!empty($token->is_whitespace)) {\n                $result[] = $token;\n                continue;\n            }\n            $all_whitespace = false; // phew, we're not talking about whitespace\n\n            $is_child = ($nesting == 0);\n\n            if ($token instanceof HTMLPurifier_Token_Start) {\n                $nesting++;\n            } elseif ($token instanceof HTMLPurifier_Token_End) {\n                $nesting--;\n            }\n\n            if ($is_child) {\n                $is_deleting = false;\n                if (!isset($this->elements[$token->name])) {\n                    $is_deleting = true;\n                    if ($pcdata_allowed && $token instanceof HTMLPurifier_Token_Text) {\n                        $result[] = $token;\n                    } elseif ($pcdata_allowed && $escape_invalid_children) {\n                        $result[] = new HTMLPurifier_Token_Text(\n                            $gen->generateFromToken($token)\n                        );\n                    }\n                    continue;\n                }\n            }\n            if (!$is_deleting || ($pcdata_allowed && $token instanceof HTMLPurifier_Token_Text)) {\n                $result[] = $token;\n            } elseif ($pcdata_allowed && $escape_invalid_children) {\n                $result[] =\n                    new HTMLPurifier_Token_Text(\n                        $gen->generateFromToken($token)\n                    );\n            } else {\n                // drop silently\n            }\n        }\n        if (empty($result)) return false;\n        if ($all_whitespace) {\n            $this->whitespace = true;\n            return false;\n        }\n        if ($tokens_of_children == $result) return true;\n        return $result;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ChildDef/StrictBlockquote.php",
    "content": "<?php\n\n/**\n * Takes the contents of blockquote when in strict and reformats for validation.\n */\nclass HTMLPurifier_ChildDef_StrictBlockquote extends HTMLPurifier_ChildDef_Required\n{\n    protected $real_elements;\n    protected $fake_elements;\n    public $allow_empty = true;\n    public $type = 'strictblockquote';\n    protected $init = false;\n\n    /**\n     * @note We don't want MakeWellFormed to auto-close inline elements since\n     *       they might be allowed.\n     */\n    public function getAllowedElements($config) {\n        $this->init($config);\n        return $this->fake_elements;\n    }\n\n    public function validateChildren($tokens_of_children, $config, $context) {\n\n        $this->init($config);\n\n        // trick the parent class into thinking it allows more\n        $this->elements = $this->fake_elements;\n        $result = parent::validateChildren($tokens_of_children, $config, $context);\n        $this->elements = $this->real_elements;\n\n        if ($result === false) return array();\n        if ($result === true) $result = $tokens_of_children;\n\n        $def = $config->getHTMLDefinition();\n        $block_wrap_start = new HTMLPurifier_Token_Start($def->info_block_wrapper);\n        $block_wrap_end   = new HTMLPurifier_Token_End(  $def->info_block_wrapper);\n        $is_inline = false;\n        $depth = 0;\n        $ret = array();\n\n        // assuming that there are no comment tokens\n        foreach ($result as $i => $token) {\n            $token = $result[$i];\n            // ifs are nested for readability\n            if (!$is_inline) {\n                if (!$depth) {\n                     if (\n                        ($token instanceof HTMLPurifier_Token_Text && !$token->is_whitespace) ||\n                        (!$token instanceof HTMLPurifier_Token_Text && !isset($this->elements[$token->name]))\n                     ) {\n                        $is_inline = true;\n                        $ret[] = $block_wrap_start;\n                     }\n                }\n            } else {\n                if (!$depth) {\n                    // starting tokens have been inline text / empty\n                    if ($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) {\n                        if (isset($this->elements[$token->name])) {\n                            // ended\n                            $ret[] = $block_wrap_end;\n                            $is_inline = false;\n                        }\n                    }\n                }\n            }\n            $ret[] = $token;\n            if ($token instanceof HTMLPurifier_Token_Start) $depth++;\n            if ($token instanceof HTMLPurifier_Token_End)   $depth--;\n        }\n        if ($is_inline) $ret[] = $block_wrap_end;\n        return $ret;\n    }\n\n    private function init($config) {\n        if (!$this->init) {\n            $def = $config->getHTMLDefinition();\n            // allow all inline elements\n            $this->real_elements = $this->elements;\n            $this->fake_elements = $def->info_content_sets['Flow'];\n            $this->fake_elements['#PCDATA'] = true;\n            $this->init = true;\n        }\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ChildDef/Table.php",
    "content": "<?php\n\n/**\n * Definition for tables\n */\nclass HTMLPurifier_ChildDef_Table extends HTMLPurifier_ChildDef\n{\n    public $allow_empty = false;\n    public $type = 'table';\n    public $elements = array('tr' => true, 'tbody' => true, 'thead' => true,\n        'tfoot' => true, 'caption' => true, 'colgroup' => true, 'col' => true);\n    public function __construct() {}\n    public function validateChildren($tokens_of_children, $config, $context) {\n        if (empty($tokens_of_children)) return false;\n\n        // this ensures that the loop gets run one last time before closing\n        // up. It's a little bit of a hack, but it works! Just make sure you\n        // get rid of the token later.\n        $tokens_of_children[] = false;\n\n        // only one of these elements is allowed in a table\n        $caption = false;\n        $thead   = false;\n        $tfoot   = false;\n\n        // as many of these as you want\n        $cols    = array();\n        $content = array();\n\n        $nesting = 0; // current depth so we can determine nodes\n        $is_collecting = false; // are we globbing together tokens to package\n                                // into one of the collectors?\n        $collection = array(); // collected nodes\n        $tag_index = 0; // the first node might be whitespace,\n                            // so this tells us where the start tag is\n\n        foreach ($tokens_of_children as $token) {\n            $is_child = ($nesting == 0);\n\n            if ($token === false) {\n                // terminating sequence started\n            } elseif ($token instanceof HTMLPurifier_Token_Start) {\n                $nesting++;\n            } elseif ($token instanceof HTMLPurifier_Token_End) {\n                $nesting--;\n            }\n\n            // handle node collection\n            if ($is_collecting) {\n                if ($is_child) {\n                    // okay, let's stash the tokens away\n                    // first token tells us the type of the collection\n                    switch ($collection[$tag_index]->name) {\n                        case 'tr':\n                        case 'tbody':\n                            $content[] = $collection;\n                            break;\n                        case 'caption':\n                            if ($caption !== false) break;\n                            $caption = $collection;\n                            break;\n                        case 'thead':\n                        case 'tfoot':\n                            // access the appropriate variable, $thead or $tfoot\n                            $var = $collection[$tag_index]->name;\n                            if ($$var === false) {\n                                $$var = $collection;\n                            } else {\n                                // transmutate the first and less entries into\n                                // tbody tags, and then put into content\n                                $collection[$tag_index]->name = 'tbody';\n                                $collection[count($collection)-1]->name = 'tbody';\n                                $content[] = $collection;\n                            }\n                            break;\n                         case 'colgroup':\n                            $cols[] = $collection;\n                            break;\n                    }\n                    $collection = array();\n                    $is_collecting = false;\n                    $tag_index = 0;\n                } else {\n                    // add the node to the collection\n                    $collection[] = $token;\n                }\n            }\n\n            // terminate\n            if ($token === false) break;\n\n            if ($is_child) {\n                // determine what we're dealing with\n                if ($token->name == 'col') {\n                    // the only empty tag in the possie, we can handle it\n                    // immediately\n                    $cols[] = array_merge($collection, array($token));\n                    $collection = array();\n                    $tag_index = 0;\n                    continue;\n                }\n                switch($token->name) {\n                    case 'caption':\n                    case 'colgroup':\n                    case 'thead':\n                    case 'tfoot':\n                    case 'tbody':\n                    case 'tr':\n                        $is_collecting = true;\n                        $collection[] = $token;\n                        continue;\n                    default:\n                        if (!empty($token->is_whitespace)) {\n                            $collection[] = $token;\n                            $tag_index++;\n                        }\n                        continue;\n                }\n            }\n        }\n\n        if (empty($content)) return false;\n\n        $ret = array();\n        if ($caption !== false) $ret = array_merge($ret, $caption);\n        if ($cols !== false)    foreach ($cols as $token_array) $ret = array_merge($ret, $token_array);\n        if ($thead !== false)   $ret = array_merge($ret, $thead);\n        if ($tfoot !== false)   $ret = array_merge($ret, $tfoot);\n        foreach ($content as $token_array) $ret = array_merge($ret, $token_array);\n        if (!empty($collection) && $is_collecting == false){\n            // grab the trailing space\n            $ret = array_merge($ret, $collection);\n        }\n\n        array_pop($tokens_of_children); // remove phantom token\n\n        return ($ret === $tokens_of_children) ? true : $ret;\n\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ChildDef.php",
    "content": "<?php\n\n/**\n * Defines allowed child nodes and validates tokens against it.\n */\nabstract class HTMLPurifier_ChildDef\n{\n    /**\n     * Type of child definition, usually right-most part of class name lowercase.\n     * Used occasionally in terms of context.\n     */\n    public $type;\n\n    /**\n     * Bool that indicates whether or not an empty array of children is okay\n     *\n     * This is necessary for redundant checking when changes affecting\n     * a child node may cause a parent node to now be disallowed.\n     */\n    public $allow_empty;\n\n    /**\n     * Lookup array of all elements that this definition could possibly allow\n     */\n    public $elements = array();\n\n    /**\n     * Get lookup of tag names that should not close this element automatically.\n     * All other elements will do so.\n     */\n    public function getAllowedElements($config) {\n        return $this->elements;\n    }\n\n    /**\n     * Validates nodes according to definition and returns modification.\n     *\n     * @param $tokens_of_children Array of HTMLPurifier_Token\n     * @param $config HTMLPurifier_Config object\n     * @param $context HTMLPurifier_Context object\n     * @return bool true to leave nodes as is\n     * @return bool false to remove parent node\n     * @return array of replacement child tokens\n     */\n    abstract public function validateChildren($tokens_of_children, $config, $context);\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Config.php",
    "content": "<?php\n\n/**\n * Configuration object that triggers customizable behavior.\n *\n * @warning This class is strongly defined: that means that the class\n *          will fail if an undefined directive is retrieved or set.\n *\n * @note Many classes that could (although many times don't) use the\n *       configuration object make it a mandatory parameter.  This is\n *       because a configuration object should always be forwarded,\n *       otherwise, you run the risk of missing a parameter and then\n *       being stumped when a configuration directive doesn't work.\n *\n * @todo Reconsider some of the public member variables\n */\nclass HTMLPurifier_Config\n{\n\n    /**\n     * HTML Purifier's version\n     */\n    public $version = '4.0.0';\n\n    /**\n     * Bool indicator whether or not to automatically finalize\n     * the object if a read operation is done\n     */\n    public $autoFinalize = true;\n\n    // protected member variables\n\n    /**\n     * Namespace indexed array of serials for specific namespaces (see\n     * getSerial() for more info).\n     */\n    protected $serials = array();\n\n    /**\n     * Serial for entire configuration object\n     */\n    protected $serial;\n\n    /**\n     * Parser for variables\n     */\n    protected $parser;\n\n    /**\n     * Reference HTMLPurifier_ConfigSchema for value checking\n     * @note This is public for introspective purposes. Please don't\n     *       abuse!\n     */\n    public $def;\n\n    /**\n     * Indexed array of definitions\n     */\n    protected $definitions;\n\n    /**\n     * Bool indicator whether or not config is finalized\n     */\n    protected $finalized = false;\n\n    /**\n     * Property list containing configuration directives.\n     */\n    protected $plist;\n\n    /**\n     * Whether or not a set is taking place due to an\n     * alias lookup.\n     */\n    private $aliasMode;\n\n    /**\n     * Set to false if you do not want line and file numbers in errors\n     * (useful when unit testing)\n     */\n    public $chatty = true;\n\n    /**\n     * Current lock; only gets to this namespace are allowed.\n     */\n    private $lock;\n\n    /**\n     * @param $definition HTMLPurifier_ConfigSchema that defines what directives\n     *                    are allowed.\n     */\n    public function __construct($definition, $parent = null) {\n        $parent = $parent ? $parent : $definition->defaultPlist;\n        $this->plist = new HTMLPurifier_PropertyList($parent);\n        $this->def = $definition; // keep a copy around for checking\n        $this->parser = new HTMLPurifier_VarParser_Flexible();\n    }\n\n    /**\n     * Convenience constructor that creates a config object based on a mixed var\n     * @param mixed $config Variable that defines the state of the config\n     *                      object. Can be: a HTMLPurifier_Config() object,\n     *                      an array of directives based on loadArray(),\n     *                      or a string filename of an ini file.\n     * @param HTMLPurifier_ConfigSchema Schema object\n     * @return Configured HTMLPurifier_Config object\n     */\n    public static function create($config, $schema = null) {\n        if ($config instanceof HTMLPurifier_Config) {\n            // pass-through\n            return $config;\n        }\n        if (!$schema) {\n            $ret = HTMLPurifier_Config::createDefault();\n        } else {\n            $ret = new HTMLPurifier_Config($schema);\n        }\n        if (is_string($config)) $ret->loadIni($config);\n        elseif (is_array($config)) $ret->loadArray($config);\n        return $ret;\n    }\n\n    /**\n     * Creates a new config object that inherits from a previous one.\n     * @param HTMLPurifier_Config $config Configuration object to inherit\n     *        from.\n     * @return HTMLPurifier_Config object with $config as its parent.\n     */\n    public static function inherit(HTMLPurifier_Config $config) {\n        return new HTMLPurifier_Config($config->def, $config->plist);\n    }\n\n    /**\n     * Convenience constructor that creates a default configuration object.\n     * @return Default HTMLPurifier_Config object.\n     */\n    public static function createDefault() {\n        $definition = HTMLPurifier_ConfigSchema::instance();\n        $config = new HTMLPurifier_Config($definition);\n        return $config;\n    }\n\n    /**\n     * Retreives a value from the configuration.\n     * @param $key String key\n     */\n    public function get($key, $a = null) {\n        if ($a !== null) {\n            $this->triggerError(\"Using deprecated API: use \\$config->get('$key.$a') instead\", E_USER_WARNING);\n            $key = \"$key.$a\";\n        }\n        if (!$this->finalized) $this->autoFinalize();\n        if (!isset($this->def->info[$key])) {\n            // can't add % due to SimpleTest bug\n            $this->triggerError('Cannot retrieve value of undefined directive ' . htmlspecialchars($key),\n                E_USER_WARNING);\n            return;\n        }\n        if (isset($this->def->info[$key]->isAlias)) {\n            $d = $this->def->info[$key];\n            $this->triggerError('Cannot get value from aliased directive, use real name ' . $d->key,\n                E_USER_ERROR);\n            return;\n        }\n        if ($this->lock) {\n            list($ns) = explode('.', $key);\n            if ($ns !== $this->lock) {\n                $this->triggerError('Cannot get value of namespace ' . $ns . ' when lock for ' . $this->lock . ' is active, this probably indicates a Definition setup method is accessing directives that are not within its namespace', E_USER_ERROR);\n                return;\n            }\n        }\n        return $this->plist->get($key);\n    }\n\n    /**\n     * Retreives an array of directives to values from a given namespace\n     * @param $namespace String namespace\n     */\n    public function getBatch($namespace) {\n        if (!$this->finalized) $this->autoFinalize();\n        $full = $this->getAll();\n        if (!isset($full[$namespace])) {\n            $this->triggerError('Cannot retrieve undefined namespace ' . htmlspecialchars($namespace),\n                E_USER_WARNING);\n            return;\n        }\n        return $full[$namespace];\n    }\n\n    /**\n     * Returns a md5 signature of a segment of the configuration object\n     * that uniquely identifies that particular configuration\n     * @note Revision is handled specially and is removed from the batch\n     *       before processing!\n     * @param $namespace Namespace to get serial for\n     */\n    public function getBatchSerial($namespace) {\n        if (empty($this->serials[$namespace])) {\n            $batch = $this->getBatch($namespace);\n            unset($batch['DefinitionRev']);\n            $this->serials[$namespace] = md5(serialize($batch));\n        }\n        return $this->serials[$namespace];\n    }\n\n    /**\n     * Returns a md5 signature for the entire configuration object\n     * that uniquely identifies that particular configuration\n     */\n    public function getSerial() {\n        if (empty($this->serial)) {\n            $this->serial = md5(serialize($this->getAll()));\n        }\n        return $this->serial;\n    }\n\n    /**\n     * Retrieves all directives, organized by namespace\n     * @warning This is a pretty inefficient function, avoid if you can\n     */\n    public function getAll() {\n        if (!$this->finalized) $this->autoFinalize();\n        $ret = array();\n        foreach ($this->plist->squash() as $name => $value) {\n            list($ns, $key) = explode('.', $name, 2);\n            $ret[$ns][$key] = $value;\n        }\n        return $ret;\n    }\n\n    /**\n     * Sets a value to configuration.\n     * @param $key String key\n     * @param $value Mixed value\n     */\n    public function set($key, $value, $a = null) {\n        if (strpos($key, '.') === false) {\n            $namespace = $key;\n            $directive = $value;\n            $value = $a;\n            $key = \"$key.$directive\";\n            $this->triggerError(\"Using deprecated API: use \\$config->set('$key', ...) instead\", E_USER_NOTICE);\n        } else {\n            list($namespace) = explode('.', $key);\n        }\n        if ($this->isFinalized('Cannot set directive after finalization')) return;\n        if (!isset($this->def->info[$key])) {\n            $this->triggerError('Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',\n                E_USER_WARNING);\n            return;\n        }\n        $def = $this->def->info[$key];\n\n        if (isset($def->isAlias)) {\n            if ($this->aliasMode) {\n                $this->triggerError('Double-aliases not allowed, please fix '.\n                    'ConfigSchema bug with' . $key, E_USER_ERROR);\n                return;\n            }\n            $this->aliasMode = true;\n            $this->set($def->key, $value);\n            $this->aliasMode = false;\n            $this->triggerError(\"$key is an alias, preferred directive name is {$def->key}\", E_USER_NOTICE);\n            return;\n        }\n\n        // Raw type might be negative when using the fully optimized form\n        // of stdclass, which indicates allow_null == true\n        $rtype = is_int($def) ? $def : $def->type;\n        if ($rtype < 0) {\n            $type = -$rtype;\n            $allow_null = true;\n        } else {\n            $type = $rtype;\n            $allow_null = isset($def->allow_null);\n        }\n\n        try {\n            $value = $this->parser->parse($value, $type, $allow_null);\n        } catch (HTMLPurifier_VarParserException $e) {\n            $this->triggerError('Value for ' . $key . ' is of invalid type, should be ' . HTMLPurifier_VarParser::getTypeName($type), E_USER_WARNING);\n            return;\n        }\n        if (is_string($value) && is_object($def)) {\n            // resolve value alias if defined\n            if (isset($def->aliases[$value])) {\n                $value = $def->aliases[$value];\n            }\n            // check to see if the value is allowed\n            if (isset($def->allowed) && !isset($def->allowed[$value])) {\n                $this->triggerError('Value not supported, valid values are: ' .\n                    $this->_listify($def->allowed), E_USER_WARNING);\n                return;\n            }\n        }\n        $this->plist->set($key, $value);\n\n        // reset definitions if the directives they depend on changed\n        // this is a very costly process, so it's discouraged\n        // with finalization\n        if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') {\n            $this->definitions[$namespace] = null;\n        }\n\n        $this->serials[$namespace] = false;\n    }\n\n    /**\n     * Convenience function for error reporting\n     */\n    private function _listify($lookup) {\n        $list = array();\n        foreach ($lookup as $name => $b) $list[] = $name;\n        return implode(', ', $list);\n    }\n\n    /**\n     * Retrieves object reference to the HTML definition.\n     * @param $raw Return a copy that has not been setup yet. Must be\n     *             called before it's been setup, otherwise won't work.\n     */\n    public function getHTMLDefinition($raw = false) {\n        return $this->getDefinition('HTML', $raw);\n    }\n\n    /**\n     * Retrieves object reference to the CSS definition\n     * @param $raw Return a copy that has not been setup yet. Must be\n     *             called before it's been setup, otherwise won't work.\n     */\n    public function getCSSDefinition($raw = false) {\n        return $this->getDefinition('CSS', $raw);\n    }\n\n    /**\n     * Retrieves a definition\n     * @param $type Type of definition: HTML, CSS, etc\n     * @param $raw  Whether or not definition should be returned raw\n     */\n    public function getDefinition($type, $raw = false) {\n        if (!$this->finalized) $this->autoFinalize();\n        // temporarily suspend locks, so we can handle recursive definition calls\n        $lock = $this->lock;\n        $this->lock = null;\n        $factory = HTMLPurifier_DefinitionCacheFactory::instance();\n        $cache = $factory->create($type, $this);\n        $this->lock = $lock;\n        if (!$raw) {\n            // see if we can quickly supply a definition\n            if (!empty($this->definitions[$type])) {\n                if (!$this->definitions[$type]->setup) {\n                    $this->definitions[$type]->setup($this);\n                    $cache->set($this->definitions[$type], $this);\n                }\n                return $this->definitions[$type];\n            }\n            // memory check missed, try cache\n            $this->definitions[$type] = $cache->get($this);\n            if ($this->definitions[$type]) {\n                // definition in cache, return it\n                return $this->definitions[$type];\n            }\n        } elseif (\n            !empty($this->definitions[$type]) &&\n            !$this->definitions[$type]->setup\n        ) {\n            // raw requested, raw in memory, quick return\n            return $this->definitions[$type];\n        }\n        // quick checks failed, let's create the object\n        if ($type == 'HTML') {\n            $this->definitions[$type] = new HTMLPurifier_HTMLDefinition();\n        } elseif ($type == 'CSS') {\n            $this->definitions[$type] = new HTMLPurifier_CSSDefinition();\n        } elseif ($type == 'URI') {\n            $this->definitions[$type] = new HTMLPurifier_URIDefinition();\n        } else {\n            throw new HTMLPurifier_Exception(\"Definition of $type type not supported\");\n        }\n        // quick abort if raw\n        if ($raw) {\n            if (is_null($this->get($type . '.DefinitionID'))) {\n                // fatally error out if definition ID not set\n                throw new HTMLPurifier_Exception(\"Cannot retrieve raw version without specifying %$type.DefinitionID\");\n            }\n            return $this->definitions[$type];\n        }\n        // set it up\n        $this->lock = $type;\n        $this->definitions[$type]->setup($this);\n        $this->lock = null;\n        // save in cache\n        $cache->set($this->definitions[$type], $this);\n        return $this->definitions[$type];\n    }\n\n    /**\n     * Loads configuration values from an array with the following structure:\n     * Namespace.Directive => Value\n     * @param $config_array Configuration associative array\n     */\n    public function loadArray($config_array) {\n        if ($this->isFinalized('Cannot load directives after finalization')) return;\n        foreach ($config_array as $key => $value) {\n            $key = str_replace('_', '.', $key);\n            if (strpos($key, '.') !== false) {\n                $this->set($key, $value);\n            } else {\n                $namespace = $key;\n                $namespace_values = $value;\n                foreach ($namespace_values as $directive => $value) {\n                    $this->set($namespace .'.'. $directive, $value);\n                }\n            }\n        }\n    }\n\n    /**\n     * Returns a list of array(namespace, directive) for all directives\n     * that are allowed in a web-form context as per an allowed\n     * namespaces/directives list.\n     * @param $allowed List of allowed namespaces/directives\n     */\n    public static function getAllowedDirectivesForForm($allowed, $schema = null) {\n        if (!$schema) {\n            $schema = HTMLPurifier_ConfigSchema::instance();\n        }\n        if ($allowed !== true) {\n             if (is_string($allowed)) $allowed = array($allowed);\n             $allowed_ns = array();\n             $allowed_directives = array();\n             $blacklisted_directives = array();\n             foreach ($allowed as $ns_or_directive) {\n                 if (strpos($ns_or_directive, '.') !== false) {\n                     // directive\n                     if ($ns_or_directive[0] == '-') {\n                         $blacklisted_directives[substr($ns_or_directive, 1)] = true;\n                     } else {\n                         $allowed_directives[$ns_or_directive] = true;\n                     }\n                 } else {\n                     // namespace\n                     $allowed_ns[$ns_or_directive] = true;\n                 }\n             }\n        }\n        $ret = array();\n        foreach ($schema->info as $key => $def) {\n            list($ns, $directive) = explode('.', $key, 2);\n            if ($allowed !== true) {\n                if (isset($blacklisted_directives[\"$ns.$directive\"])) continue;\n                if (!isset($allowed_directives[\"$ns.$directive\"]) && !isset($allowed_ns[$ns])) continue;\n            }\n            if (isset($def->isAlias)) continue;\n            if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') continue;\n            $ret[] = array($ns, $directive);\n        }\n        return $ret;\n    }\n\n    /**\n     * Loads configuration values from $_GET/$_POST that were posted\n     * via ConfigForm\n     * @param $array $_GET or $_POST array to import\n     * @param $index Index/name that the config variables are in\n     * @param $allowed List of allowed namespaces/directives\n     * @param $mq_fix Boolean whether or not to enable magic quotes fix\n     * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy\n     */\n    public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {\n        $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);\n        $config = HTMLPurifier_Config::create($ret, $schema);\n        return $config;\n    }\n\n    /**\n     * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.\n     * @note Same parameters as loadArrayFromForm\n     */\n    public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) {\n         $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);\n         $this->loadArray($ret);\n    }\n\n    /**\n     * Prepares an array from a form into something usable for the more\n     * strict parts of HTMLPurifier_Config\n     */\n    public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {\n        if ($index !== false) $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();\n        $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();\n\n        $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);\n        $ret = array();\n        foreach ($allowed as $key) {\n            list($ns, $directive) = $key;\n            $skey = \"$ns.$directive\";\n            if (!empty($array[\"Null_$skey\"])) {\n                $ret[$ns][$directive] = null;\n                continue;\n            }\n            if (!isset($array[$skey])) continue;\n            $value = $mq ? stripslashes($array[$skey]) : $array[$skey];\n            $ret[$ns][$directive] = $value;\n        }\n        return $ret;\n    }\n\n    /**\n     * Loads configuration values from an ini file\n     * @param $filename Name of ini file\n     */\n    public function loadIni($filename) {\n        if ($this->isFinalized('Cannot load directives after finalization')) return;\n        $array = parse_ini_file($filename, true);\n        $this->loadArray($array);\n    }\n\n    /**\n     * Checks whether or not the configuration object is finalized.\n     * @param $error String error message, or false for no error\n     */\n    public function isFinalized($error = false) {\n        if ($this->finalized && $error) {\n            $this->triggerError($error, E_USER_ERROR);\n        }\n        return $this->finalized;\n    }\n\n    /**\n     * Finalizes configuration only if auto finalize is on and not\n     * already finalized\n     */\n    public function autoFinalize() {\n        if ($this->autoFinalize) {\n            $this->finalize();\n        } else {\n            $this->plist->squash(true);\n        }\n    }\n\n    /**\n     * Finalizes a configuration object, prohibiting further change\n     */\n    public function finalize() {\n        $this->finalized = true;\n        unset($this->parser);\n    }\n\n    /**\n     * Produces a nicely formatted error message by supplying the\n     * stack frame information from two levels up and OUTSIDE of\n     * HTMLPurifier_Config.\n     */\n    protected function triggerError($msg, $no) {\n        // determine previous stack frame\n        $backtrace = debug_backtrace();\n        if ($this->chatty && isset($backtrace[1])) {\n            $frame = $backtrace[1];\n            $extra = \" on line {$frame['line']} in file {$frame['file']}\";\n        } else {\n            $extra = '';\n        }\n        trigger_error($msg . $extra, $no);\n    }\n\n    /**\n     * Returns a serialized form of the configuration object that can\n     * be reconstituted.\n     */\n    public function serialize() {\n        $this->getDefinition('HTML');\n        $this->getDefinition('CSS');\n        $this->getDefinition('URI');\n        return serialize($this);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php",
    "content": "<?php\n\n/**\n * Converts HTMLPurifier_ConfigSchema_Interchange to our runtime\n * representation used to perform checks on user configuration.\n */\nclass HTMLPurifier_ConfigSchema_Builder_ConfigSchema\n{\n\n    public function build($interchange) {\n        $schema = new HTMLPurifier_ConfigSchema();\n        foreach ($interchange->directives as $d) {\n            $schema->add(\n                $d->id->key,\n                $d->default,\n                $d->type,\n                $d->typeAllowsNull\n            );\n            if ($d->allowed !== null) {\n                $schema->addAllowedValues(\n                    $d->id->key,\n                    $d->allowed\n                );\n            }\n            foreach ($d->aliases as $alias) {\n                $schema->addAlias(\n                    $alias->key,\n                    $d->id->key\n                );\n            }\n            if ($d->valueAliases !== null) {\n                $schema->addValueAliases(\n                    $d->id->key,\n                    $d->valueAliases\n                );\n            }\n        }\n        $schema->postProcess();\n        return $schema;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/Builder/Xml.php",
    "content": "<?php\n\n/**\n * Converts HTMLPurifier_ConfigSchema_Interchange to an XML format,\n * which can be further processed to generate documentation.\n */\nclass HTMLPurifier_ConfigSchema_Builder_Xml extends XMLWriter\n{\n\n    protected $interchange;\n    private $namespace;\n\n    protected function writeHTMLDiv($html) {\n        $this->startElement('div');\n\n        $purifier = HTMLPurifier::getInstance();\n        $html = $purifier->purify($html);\n        $this->writeAttribute('xmlns', 'http://www.w3.org/1999/xhtml');\n        $this->writeRaw($html);\n\n        $this->endElement(); // div\n    }\n\n    protected function export($var) {\n        if ($var === array()) return 'array()';\n        return var_export($var, true);\n    }\n\n    public function build($interchange) {\n        // global access, only use as last resort\n        $this->interchange = $interchange;\n\n        $this->setIndent(true);\n        $this->startDocument('1.0', 'UTF-8');\n        $this->startElement('configdoc');\n        $this->writeElement('title', $interchange->name);\n\n        foreach ($interchange->directives as $directive) {\n            $this->buildDirective($directive);\n        }\n\n        if ($this->namespace) $this->endElement(); // namespace\n\n        $this->endElement(); // configdoc\n        $this->flush();\n    }\n\n    public function buildDirective($directive) {\n\n        // Kludge, although I suppose having a notion of a \"root namespace\"\n        // certainly makes things look nicer when documentation is built.\n        // Depends on things being sorted.\n        if (!$this->namespace || $this->namespace !== $directive->id->getRootNamespace()) {\n            if ($this->namespace) $this->endElement(); // namespace\n            $this->namespace = $directive->id->getRootNamespace();\n            $this->startElement('namespace');\n            $this->writeAttribute('id', $this->namespace);\n            $this->writeElement('name', $this->namespace);\n        }\n\n        $this->startElement('directive');\n        $this->writeAttribute('id', $directive->id->toString());\n\n        $this->writeElement('name', $directive->id->getDirective());\n\n        $this->startElement('aliases');\n            foreach ($directive->aliases as $alias) $this->writeElement('alias', $alias->toString());\n        $this->endElement(); // aliases\n\n        $this->startElement('constraints');\n            if ($directive->version) $this->writeElement('version', $directive->version);\n            $this->startElement('type');\n                if ($directive->typeAllowsNull) $this->writeAttribute('allow-null', 'yes');\n                $this->text($directive->type);\n            $this->endElement(); // type\n            if ($directive->allowed) {\n                $this->startElement('allowed');\n                    foreach ($directive->allowed as $value => $x) $this->writeElement('value', $value);\n                $this->endElement(); // allowed\n            }\n            $this->writeElement('default', $this->export($directive->default));\n            $this->writeAttribute('xml:space', 'preserve');\n            if ($directive->external) {\n                $this->startElement('external');\n                    foreach ($directive->external as $project) $this->writeElement('project', $project);\n                $this->endElement();\n            }\n        $this->endElement(); // constraints\n\n        if ($directive->deprecatedVersion) {\n            $this->startElement('deprecated');\n                $this->writeElement('version', $directive->deprecatedVersion);\n                $this->writeElement('use', $directive->deprecatedUse->toString());\n            $this->endElement(); // deprecated\n        }\n\n        $this->startElement('description');\n            $this->writeHTMLDiv($directive->description);\n        $this->endElement(); // description\n\n        $this->endElement(); // directive\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/Exception.php",
    "content": "<?php\n\n/**\n * Exceptions related to configuration schema\n */\nclass HTMLPurifier_ConfigSchema_Exception extends HTMLPurifier_Exception\n{\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/Interchange/Directive.php",
    "content": "<?php\n\n/**\n * Interchange component class describing configuration directives.\n */\nclass HTMLPurifier_ConfigSchema_Interchange_Directive\n{\n\n    /**\n     * ID of directive, instance of HTMLPurifier_ConfigSchema_Interchange_Id.\n     */\n    public $id;\n\n    /**\n     * String type, e.g. 'integer' or 'istring'.\n     */\n    public $type;\n\n    /**\n     * Default value, e.g. 3 or 'DefaultVal'.\n     */\n    public $default;\n\n    /**\n     * HTML description.\n     */\n    public $description;\n\n    /**\n     * Boolean whether or not null is allowed as a value.\n     */\n    public $typeAllowsNull = false;\n\n    /**\n     * Lookup table of allowed scalar values, e.g. array('allowed' => true).\n     * Null if all values are allowed.\n     */\n    public $allowed;\n\n    /**\n     * List of aliases for the directive,\n     * e.g. array(new HTMLPurifier_ConfigSchema_Interchange_Id('Ns', 'Dir'))).\n     */\n    public $aliases = array();\n\n    /**\n     * Hash of value aliases, e.g. array('alt' => 'real'). Null if value\n     * aliasing is disabled (necessary for non-scalar types).\n     */\n    public $valueAliases;\n\n    /**\n     * Version of HTML Purifier the directive was introduced, e.g. '1.3.1'.\n     * Null if the directive has always existed.\n     */\n    public $version;\n\n    /**\n     * ID of directive that supercedes this old directive, is an instance\n     * of HTMLPurifier_ConfigSchema_Interchange_Id. Null if not deprecated.\n     */\n    public $deprecatedUse;\n\n    /**\n     * Version of HTML Purifier this directive was deprecated. Null if not\n     * deprecated.\n     */\n    public $deprecatedVersion;\n\n    /**\n     * List of external projects this directive depends on, e.g. array('CSSTidy').\n     */\n    public $external = array();\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/Interchange/Id.php",
    "content": "<?php\n\n/**\n * Represents a directive ID in the interchange format.\n */\nclass HTMLPurifier_ConfigSchema_Interchange_Id\n{\n\n    public $key;\n\n    public function __construct($key) {\n        $this->key = $key;\n    }\n\n    /**\n     * @warning This is NOT magic, to ensure that people don't abuse SPL and\n     *          cause problems for PHP 5.0 support.\n     */\n    public function toString() {\n        return $this->key;\n    }\n\n    public function getRootNamespace() {\n        return substr($this->key, 0, strpos($this->key, \".\"));\n    }\n\n    public function getDirective() {\n        return substr($this->key, strpos($this->key, \".\") + 1);\n    }\n\n    public static function make($id) {\n        return new HTMLPurifier_ConfigSchema_Interchange_Id($id);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/Interchange.php",
    "content": "<?php\n\n/**\n * Generic schema interchange format that can be converted to a runtime\n * representation (HTMLPurifier_ConfigSchema) or HTML documentation. Members\n * are completely validated.\n */\nclass HTMLPurifier_ConfigSchema_Interchange\n{\n\n    /**\n     * Name of the application this schema is describing.\n     */\n    public $name;\n\n    /**\n     * Array of Directive ID => array(directive info)\n     */\n    public $directives = array();\n\n    /**\n     * Adds a directive array to $directives\n     */\n    public function addDirective($directive) {\n        if (isset($this->directives[$i = $directive->id->toString()])) {\n            throw new HTMLPurifier_ConfigSchema_Exception(\"Cannot redefine directive '$i'\");\n        }\n        $this->directives[$i] = $directive;\n    }\n\n    /**\n     * Convenience function to perform standard validation. Throws exception\n     * on failed validation.\n     */\n    public function validate() {\n        $validator = new HTMLPurifier_ConfigSchema_Validator();\n        return $validator->validate($this);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/InterchangeBuilder.php",
    "content": "<?php\n\nclass HTMLPurifier_ConfigSchema_InterchangeBuilder\n{\n\n    /**\n     * Used for processing DEFAULT, nothing else.\n     */\n    protected $varParser;\n\n    public function __construct($varParser = null) {\n        $this->varParser = $varParser ? $varParser : new HTMLPurifier_VarParser_Native();\n    }\n\n    public static function buildFromDirectory($dir = null) {\n        $builder     = new HTMLPurifier_ConfigSchema_InterchangeBuilder();\n        $interchange = new HTMLPurifier_ConfigSchema_Interchange();\n        return $builder->buildDir($interchange, $dir);\n    }\n\n    public function buildDir($interchange, $dir = null) {\n        if (!$dir) $dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema';\n        if (file_exists($dir . '/info.ini')) {\n            $info = parse_ini_file($dir . '/info.ini');\n            $interchange->name = $info['name'];\n        }\n\n        $files = array();\n        $dh = opendir($dir);\n        while (false !== ($file = readdir($dh))) {\n            if (!$file || $file[0] == '.' || strrchr($file, '.') !== '.txt') {\n                continue;\n            }\n            $files[] = $file;\n        }\n        closedir($dh);\n\n        sort($files);\n        foreach ($files as $file) {\n            $this->buildFile($interchange, $dir . '/' . $file);\n        }\n\n        return $interchange;\n    }\n\n    public function buildFile($interchange, $file) {\n        $parser = new HTMLPurifier_StringHashParser();\n        $this->build(\n            $interchange,\n            new HTMLPurifier_StringHash( $parser->parseFile($file) )\n        );\n    }\n\n    /**\n     * Builds an interchange object based on a hash.\n     * @param $interchange HTMLPurifier_ConfigSchema_Interchange object to build\n     * @param $hash HTMLPurifier_ConfigSchema_StringHash source data\n     */\n    public function build($interchange, $hash) {\n        if (!$hash instanceof HTMLPurifier_StringHash) {\n            $hash = new HTMLPurifier_StringHash($hash);\n        }\n        if (!isset($hash['ID'])) {\n            throw new HTMLPurifier_ConfigSchema_Exception('Hash does not have any ID');\n        }\n        if (strpos($hash['ID'], '.') === false) {\n            if (count($hash) == 2 && isset($hash['DESCRIPTION'])) {\n                $hash->offsetGet('DESCRIPTION'); // prevent complaining\n            } else {\n                throw new HTMLPurifier_ConfigSchema_Exception('All directives must have a namespace');\n            }\n        } else {\n            $this->buildDirective($interchange, $hash);\n        }\n        $this->_findUnused($hash);\n    }\n\n    public function buildDirective($interchange, $hash) {\n        $directive = new HTMLPurifier_ConfigSchema_Interchange_Directive();\n\n        // These are required elements:\n        $directive->id = $this->id($hash->offsetGet('ID'));\n        $id = $directive->id->toString(); // convenience\n\n        if (isset($hash['TYPE'])) {\n            $type = explode('/', $hash->offsetGet('TYPE'));\n            if (isset($type[1])) $directive->typeAllowsNull = true;\n            $directive->type = $type[0];\n        } else {\n            throw new HTMLPurifier_ConfigSchema_Exception(\"TYPE in directive hash '$id' not defined\");\n        }\n\n        if (isset($hash['DEFAULT'])) {\n            try {\n                $directive->default = $this->varParser->parse($hash->offsetGet('DEFAULT'), $directive->type, $directive->typeAllowsNull);\n            } catch (HTMLPurifier_VarParserException $e) {\n                throw new HTMLPurifier_ConfigSchema_Exception($e->getMessage() . \" in DEFAULT in directive hash '$id'\");\n            }\n        }\n\n        if (isset($hash['DESCRIPTION'])) {\n            $directive->description = $hash->offsetGet('DESCRIPTION');\n        }\n\n        if (isset($hash['ALLOWED'])) {\n            $directive->allowed = $this->lookup($this->evalArray($hash->offsetGet('ALLOWED')));\n        }\n\n        if (isset($hash['VALUE-ALIASES'])) {\n            $directive->valueAliases = $this->evalArray($hash->offsetGet('VALUE-ALIASES'));\n        }\n\n        if (isset($hash['ALIASES'])) {\n            $raw_aliases = trim($hash->offsetGet('ALIASES'));\n            $aliases = preg_split('/\\s*,\\s*/', $raw_aliases);\n            foreach ($aliases as $alias) {\n                $directive->aliases[] = $this->id($alias);\n            }\n        }\n\n        if (isset($hash['VERSION'])) {\n            $directive->version = $hash->offsetGet('VERSION');\n        }\n\n        if (isset($hash['DEPRECATED-USE'])) {\n            $directive->deprecatedUse = $this->id($hash->offsetGet('DEPRECATED-USE'));\n        }\n\n        if (isset($hash['DEPRECATED-VERSION'])) {\n            $directive->deprecatedVersion = $hash->offsetGet('DEPRECATED-VERSION');\n        }\n\n        if (isset($hash['EXTERNAL'])) {\n            $directive->external = preg_split('/\\s*,\\s*/', trim($hash->offsetGet('EXTERNAL')));\n        }\n\n        $interchange->addDirective($directive);\n    }\n\n    /**\n     * Evaluates an array PHP code string without array() wrapper\n     */\n    protected function evalArray($contents) {\n        return eval('return array('. $contents .');');\n    }\n\n    /**\n     * Converts an array list into a lookup array.\n     */\n    protected function lookup($array) {\n        $ret = array();\n        foreach ($array as $val) $ret[$val] = true;\n        return $ret;\n    }\n\n    /**\n     * Convenience function that creates an HTMLPurifier_ConfigSchema_Interchange_Id\n     * object based on a string Id.\n     */\n    protected function id($id) {\n        return HTMLPurifier_ConfigSchema_Interchange_Id::make($id);\n    }\n\n    /**\n     * Triggers errors for any unused keys passed in the hash; such keys\n     * may indicate typos, missing values, etc.\n     * @param $hash Instance of ConfigSchema_StringHash to check.\n     */\n    protected function _findUnused($hash) {\n        $accessed = $hash->getAccessed();\n        foreach ($hash as $k => $v) {\n            if (!isset($accessed[$k])) {\n                trigger_error(\"String hash key '$k' not used by builder\", E_USER_NOTICE);\n            }\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/Validator.php",
    "content": "<?php\n\n/**\n * Performs validations on HTMLPurifier_ConfigSchema_Interchange\n *\n * @note If you see '// handled by InterchangeBuilder', that means a\n *       design decision in that class would prevent this validation from\n *       ever being necessary. We have them anyway, however, for\n *       redundancy.\n */\nclass HTMLPurifier_ConfigSchema_Validator\n{\n\n    /**\n     * Easy to access global objects.\n     */\n    protected $interchange, $aliases;\n\n    /**\n     * Context-stack to provide easy to read error messages.\n     */\n    protected $context = array();\n\n    /**\n     * HTMLPurifier_VarParser to test default's type.\n     */\n    protected $parser;\n\n    public function __construct() {\n        $this->parser = new HTMLPurifier_VarParser();\n    }\n\n    /**\n     * Validates a fully-formed interchange object. Throws an\n     * HTMLPurifier_ConfigSchema_Exception if there's a problem.\n     */\n    public function validate($interchange) {\n        $this->interchange = $interchange;\n        $this->aliases = array();\n        // PHP is a bit lax with integer <=> string conversions in\n        // arrays, so we don't use the identical !== comparison\n        foreach ($interchange->directives as $i => $directive) {\n            $id = $directive->id->toString();\n            if ($i != $id) $this->error(false, \"Integrity violation: key '$i' does not match internal id '$id'\");\n            $this->validateDirective($directive);\n        }\n        return true;\n    }\n\n    /**\n     * Validates a HTMLPurifier_ConfigSchema_Interchange_Id object.\n     */\n    public function validateId($id) {\n        $id_string = $id->toString();\n        $this->context[] = \"id '$id_string'\";\n        if (!$id instanceof HTMLPurifier_ConfigSchema_Interchange_Id) {\n            // handled by InterchangeBuilder\n            $this->error(false, 'is not an instance of HTMLPurifier_ConfigSchema_Interchange_Id');\n        }\n        // keys are now unconstrained (we might want to narrow down to A-Za-z0-9.)\n        // we probably should check that it has at least one namespace\n        $this->with($id, 'key')\n            ->assertNotEmpty()\n            ->assertIsString(); // implicit assertIsString handled by InterchangeBuilder\n        array_pop($this->context);\n    }\n\n    /**\n     * Validates a HTMLPurifier_ConfigSchema_Interchange_Directive object.\n     */\n    public function validateDirective($d) {\n        $id = $d->id->toString();\n        $this->context[] = \"directive '$id'\";\n        $this->validateId($d->id);\n\n        $this->with($d, 'description')\n            ->assertNotEmpty();\n\n        // BEGIN - handled by InterchangeBuilder\n        $this->with($d, 'type')\n            ->assertNotEmpty();\n        $this->with($d, 'typeAllowsNull')\n            ->assertIsBool();\n        try {\n            // This also tests validity of $d->type\n            $this->parser->parse($d->default, $d->type, $d->typeAllowsNull);\n        } catch (HTMLPurifier_VarParserException $e) {\n            $this->error('default', 'had error: ' . $e->getMessage());\n        }\n        // END - handled by InterchangeBuilder\n\n        if (!is_null($d->allowed) || !empty($d->valueAliases)) {\n            // allowed and valueAliases require that we be dealing with\n            // strings, so check for that early.\n            $d_int = HTMLPurifier_VarParser::$types[$d->type];\n            if (!isset(HTMLPurifier_VarParser::$stringTypes[$d_int])) {\n                $this->error('type', 'must be a string type when used with allowed or value aliases');\n            }\n        }\n\n        $this->validateDirectiveAllowed($d);\n        $this->validateDirectiveValueAliases($d);\n        $this->validateDirectiveAliases($d);\n\n        array_pop($this->context);\n    }\n\n    /**\n     * Extra validation if $allowed member variable of\n     * HTMLPurifier_ConfigSchema_Interchange_Directive is defined.\n     */\n    public function validateDirectiveAllowed($d) {\n        if (is_null($d->allowed)) return;\n        $this->with($d, 'allowed')\n            ->assertNotEmpty()\n            ->assertIsLookup(); // handled by InterchangeBuilder\n        if (is_string($d->default) && !isset($d->allowed[$d->default])) {\n            $this->error('default', 'must be an allowed value');\n        }\n        $this->context[] = 'allowed';\n        foreach ($d->allowed as $val => $x) {\n            if (!is_string($val)) $this->error(\"value $val\", 'must be a string');\n        }\n        array_pop($this->context);\n    }\n\n    /**\n     * Extra validation if $valueAliases member variable of\n     * HTMLPurifier_ConfigSchema_Interchange_Directive is defined.\n     */\n    public function validateDirectiveValueAliases($d) {\n        if (is_null($d->valueAliases)) return;\n        $this->with($d, 'valueAliases')\n            ->assertIsArray(); // handled by InterchangeBuilder\n        $this->context[] = 'valueAliases';\n        foreach ($d->valueAliases as $alias => $real) {\n            if (!is_string($alias)) $this->error(\"alias $alias\", 'must be a string');\n            if (!is_string($real))  $this->error(\"alias target $real from alias '$alias'\",  'must be a string');\n            if ($alias === $real) {\n                $this->error(\"alias '$alias'\", \"must not be an alias to itself\");\n            }\n        }\n        if (!is_null($d->allowed)) {\n            foreach ($d->valueAliases as $alias => $real) {\n                if (isset($d->allowed[$alias])) {\n                    $this->error(\"alias '$alias'\", 'must not be an allowed value');\n                } elseif (!isset($d->allowed[$real])) {\n                    $this->error(\"alias '$alias'\", 'must be an alias to an allowed value');\n                }\n            }\n        }\n        array_pop($this->context);\n    }\n\n    /**\n     * Extra validation if $aliases member variable of\n     * HTMLPurifier_ConfigSchema_Interchange_Directive is defined.\n     */\n    public function validateDirectiveAliases($d) {\n        $this->with($d, 'aliases')\n            ->assertIsArray(); // handled by InterchangeBuilder\n        $this->context[] = 'aliases';\n        foreach ($d->aliases as $alias) {\n            $this->validateId($alias);\n            $s = $alias->toString();\n            if (isset($this->interchange->directives[$s])) {\n                $this->error(\"alias '$s'\", 'collides with another directive');\n            }\n            if (isset($this->aliases[$s])) {\n                $other_directive = $this->aliases[$s];\n                $this->error(\"alias '$s'\", \"collides with alias for directive '$other_directive'\");\n            }\n            $this->aliases[$s] = $d->id->toString();\n        }\n        array_pop($this->context);\n    }\n\n    // protected helper functions\n\n    /**\n     * Convenience function for generating HTMLPurifier_ConfigSchema_ValidatorAtom\n     * for validating simple member variables of objects.\n     */\n    protected function with($obj, $member) {\n        return new HTMLPurifier_ConfigSchema_ValidatorAtom($this->getFormattedContext(), $obj, $member);\n    }\n\n    /**\n     * Emits an error, providing helpful context.\n     */\n    protected function error($target, $msg) {\n        if ($target !== false) $prefix = ucfirst($target) . ' in ' .  $this->getFormattedContext();\n        else $prefix = ucfirst($this->getFormattedContext());\n        throw new HTMLPurifier_ConfigSchema_Exception(trim($prefix . ' ' . $msg));\n    }\n\n    /**\n     * Returns a formatted context string.\n     */\n    protected function getFormattedContext() {\n        return implode(' in ', array_reverse($this->context));\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/ValidatorAtom.php",
    "content": "<?php\n\n/**\n * Fluent interface for validating the contents of member variables.\n * This should be immutable. See HTMLPurifier_ConfigSchema_Validator for\n * use-cases. We name this an 'atom' because it's ONLY for validations that\n * are independent and usually scalar.\n */\nclass HTMLPurifier_ConfigSchema_ValidatorAtom\n{\n\n    protected $context, $obj, $member, $contents;\n\n    public function __construct($context, $obj, $member) {\n        $this->context     = $context;\n        $this->obj         = $obj;\n        $this->member      = $member;\n        $this->contents    =& $obj->$member;\n    }\n\n    public function assertIsString() {\n        if (!is_string($this->contents)) $this->error('must be a string');\n        return $this;\n    }\n\n    public function assertIsBool() {\n        if (!is_bool($this->contents)) $this->error('must be a boolean');\n        return $this;\n    }\n\n    public function assertIsArray() {\n        if (!is_array($this->contents)) $this->error('must be an array');\n        return $this;\n    }\n\n    public function assertNotNull() {\n        if ($this->contents === null) $this->error('must not be null');\n        return $this;\n    }\n\n    public function assertAlnum() {\n        $this->assertIsString();\n        if (!ctype_alnum($this->contents)) $this->error('must be alphanumeric');\n        return $this;\n    }\n\n    public function assertNotEmpty() {\n        if (empty($this->contents)) $this->error('must not be empty');\n        return $this;\n    }\n\n    public function assertIsLookup() {\n        $this->assertIsArray();\n        foreach ($this->contents as $v) {\n            if ($v !== true) $this->error('must be a lookup array');\n        }\n        return $this;\n    }\n\n    protected function error($msg) {\n        throw new HTMLPurifier_ConfigSchema_Exception(ucfirst($this->member) . ' in ' . $this->context . ' ' . $msg);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt",
    "content": "Attr.AllowedClasses\nTYPE: lookup/null\nVERSION: 4.0.0\nDEFAULT: null\n--DESCRIPTION--\nList of allowed class values in the class attribute. By default, this is null,\nwhich means all classes are allowed.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt",
    "content": "Attr.AllowedFrameTargets\nTYPE: lookup\nDEFAULT: array()\n--DESCRIPTION--\nLookup table of all allowed link frame targets.  Some commonly used link\ntargets include _blank, _self, _parent and _top. Values should be\nlowercase, as validation will be done in a case-sensitive manner despite\nW3C's recommendation. XHTML 1.0 Strict does not permit the target attribute\nso this directive will have no effect in that doctype. XHTML 1.1 does not\nenable the Target module by default, you will have to manually enable it\n(see the module documentation for more details.)\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt",
    "content": "Attr.AllowedRel\nTYPE: lookup\nVERSION: 1.6.0\nDEFAULT: array()\n--DESCRIPTION--\nList of allowed forward document relationships in the rel attribute. Common\nvalues may be nofollow or print. By default, this is empty, meaning that no\ndocument relationships are allowed.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt",
    "content": "Attr.AllowedRev\nTYPE: lookup\nVERSION: 1.6.0\nDEFAULT: array()\n--DESCRIPTION--\nList of allowed reverse document relationships in the rev attribute. This\nattribute is a bit of an edge-case; if you don't know what it is for, stay\naway.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt",
    "content": "Attr.ClassUseCDATA\nTYPE: bool/null\nDEFAULT: null\nVERSION: 4.0.0\n--DESCRIPTION--\nIf null, class will auto-detect the doctype and, if matching XHTML 1.1 or\nXHTML 2.0, will use the restrictive NMTOKENS specification of class. Otherwise,\nit will use a relaxed CDATA definition.  If true, the relaxed CDATA definition\nis forced; if false, the NMTOKENS definition is forced.  To get behavior\nof HTML Purifier prior to 4.0.0, set this directive to false.\n\nSome rational behind the auto-detection:\nin previous versions of HTML Purifier, it was assumed that the form of\nclass was NMTOKENS, as specified by the XHTML Modularization (representing\nXHTML 1.1 and XHTML 2.0).  The DTDs for HTML 4.01 and XHTML 1.0, however\nspecify class as CDATA.  HTML 5 effectively defines it as CDATA, but\nwith the additional constraint that each name should be unique (this is not\nexplicitly outlined in previous specifications).\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt",
    "content": "Attr.DefaultImageAlt\nTYPE: string/null\nDEFAULT: null\nVERSION: 3.2.0\n--DESCRIPTION--\nThis is the content of the alt tag of an image if the user had not\npreviously specified an alt attribute.  This applies to all images without\na valid alt attribute, as opposed to %Attr.DefaultInvalidImageAlt, which\nonly applies to invalid images, and overrides in the case of an invalid image.\nDefault behavior with null is to use the basename of the src tag for the alt.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt",
    "content": "Attr.DefaultInvalidImage\nTYPE: string\nDEFAULT: ''\n--DESCRIPTION--\nThis is the default image an img tag will be pointed to if it does not have\na valid src attribute.  In future versions, we may allow the image tag to\nbe removed completely, but due to design issues, this is not possible right\nnow.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt",
    "content": "Attr.DefaultInvalidImageAlt\nTYPE: string\nDEFAULT: 'Invalid image'\n--DESCRIPTION--\nThis is the content of the alt tag of an invalid image if the user had not\npreviously specified an alt attribute.  It has no effect when the image is\nvalid but there was no alt attribute present.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt",
    "content": "Attr.DefaultTextDir\nTYPE: string\nDEFAULT: 'ltr'\n--DESCRIPTION--\nDefines the default text direction (ltr or rtl) of the document being\nparsed.  This generally is the same as the value of the dir attribute in\nHTML, or ltr if that is not specified.\n--ALLOWED--\n'ltr', 'rtl'\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt",
    "content": "Attr.EnableID\nTYPE: bool\nDEFAULT: false\nVERSION: 1.2.0\n--DESCRIPTION--\nAllows the ID attribute in HTML.  This is disabled by default due to the\nfact that without proper configuration user input can easily break the\nvalidation of a webpage by specifying an ID that is already on the\nsurrounding HTML.  If you don't mind throwing caution to the wind, enable\nthis directive, but I strongly recommend you also consider blacklisting IDs\nyou use (%Attr.IDBlacklist) or prefixing all user supplied IDs\n(%Attr.IDPrefix).  When set to true HTML Purifier reverts to the behavior of\npre-1.2.0 versions.\n--ALIASES--\nHTML.EnableAttrID\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt",
    "content": "Attr.ForbiddenClasses\nTYPE: lookup\nVERSION: 4.0.0\nDEFAULT: array()\n--DESCRIPTION--\nList of forbidden class values in the class attribute. By default, this is\nempty, which means that no classes are forbidden. See also %Attr.AllowedClasses.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt",
    "content": "Attr.IDBlacklist\nTYPE: list\nDEFAULT: array()\nDESCRIPTION: Array of IDs not allowed in the document.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt",
    "content": "Attr.IDBlacklistRegexp\nTYPE: string/null\nVERSION: 1.6.0\nDEFAULT: NULL\n--DESCRIPTION--\nPCRE regular expression to be matched against all IDs. If the expression is\nmatches, the ID is rejected. Use this with care: may cause significant\ndegradation. ID matching is done after all other validation.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt",
    "content": "Attr.IDPrefix\nTYPE: string\nVERSION: 1.2.0\nDEFAULT: ''\n--DESCRIPTION--\nString to prefix to IDs.  If you have no idea what IDs your pages may use,\nyou may opt to simply add a prefix to all user-submitted ID attributes so\nthat they are still usable, but will not conflict with core page IDs.\nExample: setting the directive to 'user_' will result in a user submitted\n'foo' to become 'user_foo'  Be sure to set %HTML.EnableAttrID to true\nbefore using this.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt",
    "content": "Attr.IDPrefixLocal\nTYPE: string\nVERSION: 1.2.0\nDEFAULT: ''\n--DESCRIPTION--\nTemporary prefix for IDs used in conjunction with %Attr.IDPrefix.  If you\nneed to allow multiple sets of user content on web page, you may need to\nhave a seperate prefix that changes with each iteration.  This way,\nseperately submitted user content displayed on the same page doesn't\nclobber each other. Ideal values are unique identifiers for the content it\nrepresents (i.e. the id of the row in the database). Be sure to add a\nseperator (like an underscore) at the end.  Warning: this directive will\nnot work unless %Attr.IDPrefix is set to a non-empty value!\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt",
    "content": "AutoFormat.AutoParagraph\nTYPE: bool\nVERSION: 2.0.1\nDEFAULT: false\n--DESCRIPTION--\n\n<p>\n  This directive turns on auto-paragraphing, where double newlines are\n  converted in to paragraphs whenever possible. Auto-paragraphing:\n</p>\n<ul>\n  <li>Always applies to inline elements or text in the root node,</li>\n  <li>Applies to inline elements or text with double newlines in nodes\n      that allow paragraph tags,</li>\n  <li>Applies to double newlines in paragraph tags</li>\n</ul>\n<p>\n  <code>p</code> tags must be allowed for this directive to take effect.\n  We do not use <code>br</code> tags for paragraphing, as that is\n  semantically incorrect.\n</p>\n<p>\n  To prevent auto-paragraphing as a content-producer, refrain from using\n  double-newlines except to specify a new paragraph or in contexts where\n  it has special meaning (whitespace usually has no meaning except in\n  tags like <code>pre</code>, so this should not be difficult.) To prevent\n  the paragraphing of inline text adjacent to block elements, wrap them\n  in <code>div</code> tags (the behavior is slightly different outside of\n  the root node.)\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt",
    "content": "AutoFormat.Custom\nTYPE: list\nVERSION: 2.0.1\nDEFAULT: array()\n--DESCRIPTION--\n\n<p>\n  This directive can be used to add custom auto-format injectors.\n  Specify an array of injector names (class name minus the prefix)\n  or concrete implementations. Injector class must exist.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt",
    "content": "AutoFormat.DisplayLinkURI\nTYPE: bool\nVERSION: 3.2.0\nDEFAULT: false\n--DESCRIPTION--\n<p>\n  This directive turns on the in-text display of URIs in &lt;a&gt; tags, and disables\n  those links. For example, <a href=\"http://example.com\">example</a> becomes\n  example (<a>http://example.com</a>).\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt",
    "content": "AutoFormat.Linkify\nTYPE: bool\nVERSION: 2.0.1\nDEFAULT: false\n--DESCRIPTION--\n\n<p>\n  This directive turns on linkification, auto-linking http, ftp and\n  https URLs. <code>a</code> tags with the <code>href</code> attribute\n  must be allowed.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt",
    "content": "AutoFormat.PurifierLinkify.DocURL\nTYPE: string\nVERSION: 2.0.1\nDEFAULT: '#%s'\nALIASES: AutoFormatParam.PurifierLinkifyDocURL\n--DESCRIPTION--\n<p>\n  Location of configuration documentation to link to, let %s substitute\n  into the configuration's namespace and directive names sans the percent\n  sign.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt",
    "content": "AutoFormat.PurifierLinkify\nTYPE: bool\nVERSION: 2.0.1\nDEFAULT: false\n--DESCRIPTION--\n\n<p>\n  Internal auto-formatter that converts configuration directives in\n  syntax <a>%Namespace.Directive</a> to links. <code>a</code> tags\n  with the <code>href</code> attribute must be allowed.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt",
    "content": "AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions\nTYPE: lookup\nVERSION: 4.0.0\nDEFAULT: array('td' => true, 'th' => true)\n--DESCRIPTION--\n<p>\n  When %AutoFormat.RemoveEmpty and %AutoFormat.RemoveEmpty.RemoveNbsp\n  are enabled, this directive defines what HTML elements should not be\n  removede if they have only a non-breaking space in them.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt",
    "content": "AutoFormat.RemoveEmpty.RemoveNbsp\nTYPE: bool\nVERSION: 4.0.0\nDEFAULT: false\n--DESCRIPTION--\n<p>\n  When enabled, HTML Purifier will treat any elements that contain only\n  non-breaking spaces as well as regular whitespace as empty, and remove\n  them when %AutoForamt.RemoveEmpty is enabled.\n</p>\n<p>\n  See %AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions for a list of elements\n  that don't have this behavior applied to them.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt",
    "content": "AutoFormat.RemoveEmpty\nTYPE: bool\nVERSION: 3.2.0\nDEFAULT: false\n--DESCRIPTION--\n<p>\n  When enabled, HTML Purifier will attempt to remove empty elements that\n  contribute no semantic information to the document. The following types\n  of nodes will be removed:\n</p>\n<ul><li>\n    Tags with no attributes and no content, and that are not empty\n    elements (remove <code>&lt;a&gt;&lt;/a&gt;</code> but not\n    <code>&lt;br /&gt;</code>), and\n  </li>\n  <li>\n    Tags with no content, except for:<ul>\n      <li>The <code>colgroup</code> element, or</li>\n      <li>\n        Elements with the <code>id</code> or <code>name</code> attribute,\n        when those attributes are permitted on those elements.\n      </li>\n    </ul></li>\n</ul>\n<p>\n  Please be very careful when using this functionality; while it may not\n  seem that empty elements contain useful information, they can alter the\n  layout of a document given appropriate styling. This directive is most\n  useful when you are processing machine-generated HTML, please avoid using\n  it on regular user HTML.\n</p>\n<p>\n  Elements that contain only whitespace will be treated as empty. Non-breaking\n  spaces, however, do not count as whitespace. See\n  %AutoFormat.RemoveEmpty.RemoveNbsp for alternate behavior.\n</p>\n<p>\n  This algorithm is not perfect; you may still notice some empty tags,\n  particularly if a node had elements, but those elements were later removed\n  because they were not permitted in that context, or tags that, after\n  being auto-closed by another tag, where empty. This is for safety reasons\n  to prevent clever code from breaking validation. The general rule of thumb:\n  if a tag looked empty on the way in, it will get removed; if HTML Purifier\n  made it empty, it will stay.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt",
    "content": "CSS.AllowImportant\nTYPE: bool\nDEFAULT: false\nVERSION: 3.1.0\n--DESCRIPTION--\nThis parameter determines whether or not !important cascade modifiers should\nbe allowed in user CSS. If false, !important will stripped.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt",
    "content": "CSS.AllowTricky\nTYPE: bool\nDEFAULT: false\nVERSION: 3.1.0\n--DESCRIPTION--\nThis parameter determines whether or not to allow \"tricky\" CSS properties and\nvalues. Tricky CSS properties/values can drastically modify page layout or\nbe used for deceptive practices but do not directly constitute a security risk.\nFor example, <code>display:none;</code> is considered a tricky property that\nwill only be allowed if this directive is set to true.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt",
    "content": "CSS.AllowedProperties\nTYPE: lookup/null\nVERSION: 3.1.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    If HTML Purifier's style attributes set is unsatisfactory for your needs,\n    you can overload it with your own list of tags to allow.  Note that this\n    method is subtractive: it does its job by taking away from HTML Purifier\n    usual feature set, so you cannot add an attribute that HTML Purifier never\n    supported in the first place.\n</p>\n<p>\n    <strong>Warning:</strong> If another directive conflicts with the\n    elements here, <em>that</em> directive will win and override.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt",
    "content": "CSS.DefinitionRev\nTYPE: int\nVERSION: 2.0.0\nDEFAULT: 1\n--DESCRIPTION--\n\n<p>\n    Revision identifier for your custom definition. See\n    %HTML.DefinitionRev for details.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt",
    "content": "CSS.MaxImgLength\nTYPE: string/null\nDEFAULT: '1200px'\nVERSION: 3.1.1\n--DESCRIPTION--\n<p>\n This parameter sets the maximum allowed length on <code>img</code> tags,\n effectively the <code>width</code> and <code>height</code> properties.\n Only absolute units of measurement (in, pt, pc, mm, cm) and pixels (px) are allowed. This is\n in place to prevent imagecrash attacks, disable with null at your own risk.\n This directive is similar to %HTML.MaxImgLength, and both should be\n concurrently edited, although there are\n subtle differences in the input format (the CSS max is a number with\n a unit).\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt",
    "content": "CSS.Proprietary\nTYPE: bool\nVERSION: 3.0.0\nDEFAULT: false\n--DESCRIPTION--\n\n<p>\n    Whether or not to allow safe, proprietary CSS values.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt",
    "content": "Cache.DefinitionImpl\nTYPE: string/null\nVERSION: 2.0.0\nDEFAULT: 'Serializer'\n--DESCRIPTION--\n\nThis directive defines which method to use when caching definitions,\nthe complex data-type that makes HTML Purifier tick. Set to null\nto disable caching (not recommended, as you will see a definite\nperformance degradation).\n\n--ALIASES--\nCore.DefinitionCache\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt",
    "content": "Cache.SerializerPath\nTYPE: string/null\nVERSION: 2.0.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    Absolute path with no trailing slash to store serialized definitions in.\n    Default is within the\n    HTML Purifier library inside DefinitionCache/Serializer. This\n    path must be writable by the webserver.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt",
    "content": "Core.AggressivelyFixLt\nTYPE: bool\nVERSION: 2.1.0\nDEFAULT: true\n--DESCRIPTION--\n<p>\n    This directive enables aggressive pre-filter fixes HTML Purifier can\n    perform in order to ensure that open angled-brackets do not get killed\n    during parsing stage. Enabling this will result in two preg_replace_callback\n    calls and at least two preg_replace calls for every HTML document parsed;\n    if your users make very well-formed HTML, you can set this directive false.\n    This has no effect when DirectLex is used.\n</p>\n<p>\n    <strong>Notice:</strong> This directive's default turned from false to true\n    in HTML Purifier 3.2.0.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt",
    "content": "Core.CollectErrors\nTYPE: bool\nVERSION: 2.0.0\nDEFAULT: false\n--DESCRIPTION--\n\nWhether or not to collect errors found while filtering the document. This\nis a useful way to give feedback to your users. <strong>Warning:</strong>\nCurrently this feature is very patchy and experimental, with lots of\npossible error messages not yet implemented. It will not cause any\nproblems, but it may not help your users either.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt",
    "content": "Core.ColorKeywords\nTYPE: hash\nVERSION: 2.0.0\n--DEFAULT--\narray (\n  'maroon' => '#800000',\n  'red' => '#FF0000',\n  'orange' => '#FFA500',\n  'yellow' => '#FFFF00',\n  'olive' => '#808000',\n  'purple' => '#800080',\n  'fuchsia' => '#FF00FF',\n  'white' => '#FFFFFF',\n  'lime' => '#00FF00',\n  'green' => '#008000',\n  'navy' => '#000080',\n  'blue' => '#0000FF',\n  'aqua' => '#00FFFF',\n  'teal' => '#008080',\n  'black' => '#000000',\n  'silver' => '#C0C0C0',\n  'gray' => '#808080',\n)\n--DESCRIPTION--\n\nLookup array of color names to six digit hexadecimal number corresponding\nto color, with preceding hash mark. Used when parsing colors.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt",
    "content": "Core.ConvertDocumentToFragment\nTYPE: bool\nDEFAULT: true\n--DESCRIPTION--\n\nThis parameter determines whether or not the filter should convert\ninput that is a full document with html and body tags to a fragment\nof just the contents of a body tag. This parameter is simply something\nHTML Purifier can do during an edge-case: for most inputs, this\nprocessing is not necessary.\n\n--ALIASES--\nCore.AcceptFullDocuments\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt",
    "content": "Core.DirectLexLineNumberSyncInterval\nTYPE: int\nVERSION: 2.0.0\nDEFAULT: 0\n--DESCRIPTION--\n\n<p>\n  Specifies the number of tokens the DirectLex line number tracking\n  implementations should process before attempting to resyncronize the\n  current line count by manually counting all previous new-lines. When\n  at 0, this functionality is disabled. Lower values will decrease\n  performance, and this is only strictly necessary if the counting\n  algorithm is buggy (in which case you should report it as a bug).\n  This has no effect when %Core.MaintainLineNumbers is disabled or DirectLex is\n  not being used.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt",
    "content": "Core.Encoding\nTYPE: istring\nDEFAULT: 'utf-8'\n--DESCRIPTION--\nIf for some reason you are unable to convert all webpages to UTF-8, you can\nuse this directive as a stop-gap compatibility change to let HTML Purifier\ndeal with non UTF-8 input.  This technique has notable deficiencies:\nabsolutely no characters outside of the selected character encoding will be\npreserved, not even the ones that have been ampersand escaped (this is due\nto a UTF-8 specific <em>feature</em> that automatically resolves all\nentities), making it pretty useless for anything except the most I18N-blind\napplications, although %Core.EscapeNonASCIICharacters offers fixes this\ntrouble with another tradeoff. This directive only accepts ISO-8859-1 if\niconv is not enabled.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt",
    "content": "Core.EscapeInvalidChildren\nTYPE: bool\nDEFAULT: false\n--DESCRIPTION--\nWhen true, a child is found that is not allowed in the context of the\nparent element will be transformed into text as if it were ASCII. When\nfalse, that element and all internal tags will be dropped, though text will\nbe preserved.  There is no option for dropping the element but preserving\nchild nodes.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt",
    "content": "Core.EscapeInvalidTags\nTYPE: bool\nDEFAULT: false\n--DESCRIPTION--\nWhen true, invalid tags will be written back to the document as plain text.\nOtherwise, they are silently dropped.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt",
    "content": "Core.EscapeNonASCIICharacters\nTYPE: bool\nVERSION: 1.4.0\nDEFAULT: false\n--DESCRIPTION--\nThis directive overcomes a deficiency in %Core.Encoding by blindly\nconverting all non-ASCII characters into decimal numeric entities before\nconverting it to its native encoding. This means that even characters that\ncan be expressed in the non-UTF-8 encoding will be entity-ized, which can\nbe a real downer for encodings like Big5. It also assumes that the ASCII\nrepetoire is available, although this is the case for almost all encodings.\nAnyway, use UTF-8!\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt",
    "content": "Core.HiddenElements\nTYPE: lookup\n--DEFAULT--\narray (\n  'script' => true,\n  'style' => true,\n)\n--DESCRIPTION--\n\n<p>\n  This directive is a lookup array of elements which should have their\n  contents removed when they are not allowed by the HTML definition.\n  For example, the contents of a <code>script</code> tag are not\n  normally shown in a document, so if script tags are to be removed,\n  their contents should be removed to. This is opposed to a <code>b</code>\n  tag, which defines some presentational changes but does not hide its\n  contents.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.Language.txt",
    "content": "Core.Language\nTYPE: string\nVERSION: 2.0.0\nDEFAULT: 'en'\n--DESCRIPTION--\n\nISO 639 language code for localizable things in HTML Purifier to use,\nwhich is mainly error reporting. There is currently only an English (en)\ntranslation, so this directive is currently useless.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt",
    "content": "Core.LexerImpl\nTYPE: mixed/null\nVERSION: 2.0.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n  This parameter determines what lexer implementation can be used. The\n  valid values are:\n</p>\n<dl>\n  <dt><em>null</em></dt>\n  <dd>\n    Recommended, the lexer implementation will be auto-detected based on\n    your PHP-version and configuration.\n  </dd>\n  <dt><em>string</em> lexer identifier</dt>\n  <dd>\n    This is a slim way of manually overridding the implementation.\n    Currently recognized values are: DOMLex (the default PHP5\nimplementation)\n    and DirectLex (the default PHP4 implementation). Only use this if\n    you know what you are doing: usually, the auto-detection will\n    manage things for cases you aren't even aware of.\n  </dd>\n  <dt><em>object</em> lexer instance</dt>\n  <dd>\n    Super-advanced: you can specify your own, custom, implementation that\n    implements the interface defined by <code>HTMLPurifier_Lexer</code>.\n    I may remove this option simply because I don't expect anyone\n    to use it.\n  </dd>\n</dl>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt",
    "content": "Core.MaintainLineNumbers\nTYPE: bool/null\nVERSION: 2.0.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n  If true, HTML Purifier will add line number information to all tokens.\n  This is useful when error reporting is turned on, but can result in\n  significant performance degradation and should not be used when\n  unnecessary. This directive must be used with the DirectLex lexer,\n  as the DOMLex lexer does not (yet) support this functionality.\n  If the value is null, an appropriate value will be selected based\n  on other configuration.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt",
    "content": "Core.RemoveInvalidImg\nTYPE: bool\nDEFAULT: true\nVERSION: 1.3.0\n--DESCRIPTION--\n\n<p>\n  This directive enables pre-emptive URI checking in <code>img</code>\n  tags, as the attribute validation strategy is not authorized to\n  remove elements from the document. Revert to pre-1.3.0 behavior by setting to false.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt",
    "content": "Core.RemoveScriptContents\nTYPE: bool/null\nDEFAULT: NULL\nVERSION: 2.0.0\nDEPRECATED-VERSION: 2.1.0\nDEPRECATED-USE: Core.HiddenElements\n--DESCRIPTION--\n<p>\n  This directive enables HTML Purifier to remove not only script tags\n  but all of their contents.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt",
    "content": "Filter.Custom\nTYPE: list\nVERSION: 3.1.0\nDEFAULT: array()\n--DESCRIPTION--\n<p>\n  This directive can be used to add custom filters; it is nearly the\n  equivalent of the now deprecated <code>HTMLPurifier-&gt;addFilter()</code>\n  method. Specify an array of concrete implementations.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt",
    "content": "Filter.ExtractStyleBlocks.Escaping\nTYPE: bool\nVERSION: 3.0.0\nDEFAULT: true\nALIASES: Filter.ExtractStyleBlocksEscaping, FilterParam.ExtractStyleBlocksEscaping\n--DESCRIPTION--\n\n<p>\n  Whether or not to escape the dangerous characters &lt;, &gt; and &amp;\n  as \\3C, \\3E and \\26, respectively. This is can be safely set to false\n  if the contents of StyleBlocks will be placed in an external stylesheet,\n  where there is no risk of it being interpreted as HTML.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt",
    "content": "Filter.ExtractStyleBlocks.Scope\nTYPE: string/null\nVERSION: 3.0.0\nDEFAULT: NULL\nALIASES: Filter.ExtractStyleBlocksScope, FilterParam.ExtractStyleBlocksScope\n--DESCRIPTION--\n\n<p>\n  If you would like users to be able to define external stylesheets, but\n  only allow them to specify CSS declarations for a specific node and\n  prevent them from fiddling with other elements, use this directive.\n  It accepts any valid CSS selector, and will prepend this to any\n  CSS declaration extracted from the document. For example, if this\n  directive is set to <code>#user-content</code> and a user uses the\n  selector <code>a:hover</code>, the final selector will be\n  <code>#user-content a:hover</code>.\n</p>\n<p>\n  The comma shorthand may be used; consider the above example, with\n  <code>#user-content, #user-content2</code>, the final selector will\n  be <code>#user-content a:hover, #user-content2 a:hover</code>.\n</p>\n<p>\n  <strong>Warning:</strong> It is possible for users to bypass this measure\n  using a naughty + selector. This is a bug in CSS Tidy 1.3, not HTML\n  Purifier, and I am working to get it fixed. Until then, HTML Purifier\n  performs a basic check to prevent this.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt",
    "content": "Filter.ExtractStyleBlocks.TidyImpl\nTYPE: mixed/null\nVERSION: 3.1.0\nDEFAULT: NULL\nALIASES: FilterParam.ExtractStyleBlocksTidyImpl\n--DESCRIPTION--\n<p>\n  If left NULL, HTML Purifier will attempt to instantiate a <code>csstidy</code>\n  class to use for internal cleaning. This will usually be good enough.\n</p>\n<p>\n  However, for trusted user input, you can set this to <code>false</code> to\n  disable cleaning. In addition, you can supply your own concrete implementation\n  of Tidy's interface to use, although I don't know why you'd want to do that.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt",
    "content": "Filter.ExtractStyleBlocks\nTYPE: bool\nVERSION: 3.1.0\nDEFAULT: false\nEXTERNAL: CSSTidy\n--DESCRIPTION--\n<p>\n  This directive turns on the style block extraction filter, which removes\n  <code>style</code> blocks from input HTML, cleans them up with CSSTidy,\n  and places them in the <code>StyleBlocks</code> context variable, for further\n  use by you, usually to be placed in an external stylesheet, or a\n  <code>style</code> block in the <code>head</code> of your document.\n</p>\n<p>\n  Sample usage:\n</p>\n<pre><![CDATA[\n<?php\n    header('Content-type: text/html; charset=utf-8');\n    echo '<?xml version=\"1.0\" encoding=\"UTF-8\"?>';\n?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n<head>\n  <title>Filter.ExtractStyleBlocks</title>\n<?php\n    require_once '/path/to/library/HTMLPurifier.auto.php';\n    require_once '/path/to/csstidy.class.php';\n\n    $dirty = '<style>body {color:#F00;}</style> Some text';\n\n    $config = HTMLPurifier_Config::createDefault();\n    $config->set('Filter', 'ExtractStyleBlocks', true);\n    $purifier = new HTMLPurifier($config);\n\n    $html = $purifier->purify($dirty);\n\n    // This implementation writes the stylesheets to the styles/ directory.\n    // You can also echo the styles inside the document, but it's a bit\n    // more difficult to make sure they get interpreted properly by\n    // browsers; try the usual CSS armoring techniques.\n    $styles = $purifier->context->get('StyleBlocks');\n    $dir = 'styles/';\n    if (!is_dir($dir)) mkdir($dir);\n    $hash = sha1($_GET['html']);\n    foreach ($styles as $i => $style) {\n        file_put_contents($name = $dir . $hash . \"_$i\");\n        echo '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.$name.'\" />';\n    }\n?>\n</head>\n<body>\n  <div>\n    <?php echo $html; ?>\n  </div>\n</b]]><![CDATA[ody>\n</html>\n]]></pre>\n<p>\n  <strong>Warning:</strong> It is possible for a user to mount an\n  imagecrash attack using this CSS. Counter-measures are difficult;\n  it is not simply enough to limit the range of CSS lengths (using\n  relative lengths with many nesting levels allows for large values\n  to be attained without actually specifying them in the stylesheet),\n  and the flexible nature of selectors makes it difficult to selectively\n  disable lengths on image tags (HTML Purifier, however, does disable\n  CSS width and height in inline styling). There are probably two effective\n  counter measures: an explicit width and height set to auto in all\n  images in your document (unlikely) or the disabling of width and\n  height (somewhat reasonable). Whether or not these measures should be\n  used is left to the reader.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt",
    "content": "Filter.YouTube\nTYPE: bool\nVERSION: 3.1.0\nDEFAULT: false\n--DESCRIPTION--\n<p>\n  This directive enables YouTube video embedding in HTML Purifier. Check\n  <a href=\"http://htmlpurifier.org/docs/enduser-youtube.html\">this document\n  on embedding videos</a> for more information on what this filter does.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt",
    "content": "HTML.Allowed\nTYPE: itext/null\nVERSION: 2.0.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    This is a convenience directive that rolls the functionality of\n    %HTML.AllowedElements and %HTML.AllowedAttributes into one directive.\n    Specify elements and attributes that are allowed using:\n    <code>element1[attr1|attr2],element2...</code>. You can also use\n    newlines instead of commas to separate elements.\n</p>\n<p>\n    <strong>Warning</strong>:\n    All of the constraints on the component directives are still enforced.\n    The syntax is a <em>subset</em> of TinyMCE's <code>valid_elements</code>\n    whitelist: directly copy-pasting it here will probably result in\n    broken whitelists. If %HTML.AllowedElements or %HTML.AllowedAttributes\n    are set, this directive has no effect.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt",
    "content": "HTML.AllowedAttributes\nTYPE: lookup/null\nVERSION: 1.3.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    If HTML Purifier's attribute set is unsatisfactory, overload it!\n    The syntax is \"tag.attr\" or \"*.attr\" for the global attributes\n    (style, id, class, dir, lang, xml:lang).\n</p>\n<p>\n    <strong>Warning:</strong> If another directive conflicts with the\n    elements here, <em>that</em> directive will win and override. For\n    example, %HTML.EnableAttrID will take precedence over *.id in this\n    directive.  You must set that directive to true before you can use\n    IDs at all.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt",
    "content": "HTML.AllowedElements\nTYPE: lookup/null\nVERSION: 1.3.0\nDEFAULT: NULL\n--DESCRIPTION--\n<p>\n    If HTML Purifier's tag set is unsatisfactory for your needs, you\n    can overload it with your own list of tags to allow.  Note that this\n    method is subtractive: it does its job by taking away from HTML Purifier\n    usual feature set, so you cannot add a tag that HTML Purifier never\n    supported in the first place (like embed, form or head).  If you\n    change this, you probably also want to change %HTML.AllowedAttributes.\n</p>\n<p>\n    <strong>Warning:</strong> If another directive conflicts with the\n    elements here, <em>that</em> directive will win and override.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt",
    "content": "HTML.AllowedModules\nTYPE: lookup/null\nVERSION: 2.0.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    A doctype comes with a set of usual modules to use. Without having\n    to mucking about with the doctypes, you can quickly activate or\n    disable these modules by specifying which modules you wish to allow\n    with this directive. This is most useful for unit testing specific\n    modules, although end users may find it useful for their own ends.\n</p>\n<p>\n    If you specify a module that does not exist, the manager will silently\n    fail to use it, so be careful! User-defined modules are not affected\n    by this directive. Modules defined in %HTML.CoreModules are not\n    affected by this directive.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt",
    "content": "HTML.Attr.Name.UseCDATA\nTYPE: bool\nDEFAULT: false\nVERSION: 4.0.0\n--DESCRIPTION--\nThe W3C specification DTD defines the name attribute to be CDATA, not ID, due\nto limitations of DTD.  In certain documents, this relaxed behavior is desired,\nwhether it is to specify duplicate names, or to specify names that would be\nillegal IDs (for example, names that begin with a digit.) Set this configuration\ndirective to true to use the relaxed parsing rules.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt",
    "content": "HTML.BlockWrapper\nTYPE: string\nVERSION: 1.3.0\nDEFAULT: 'p'\n--DESCRIPTION--\n\n<p>\n    String name of element to wrap inline elements that are inside a block\n    context.  This only occurs in the children of blockquote in strict mode.\n</p>\n<p>\n    Example: by default value,\n    <code>&lt;blockquote&gt;Foo&lt;/blockquote&gt;</code> would become\n    <code>&lt;blockquote&gt;&lt;p&gt;Foo&lt;/p&gt;&lt;/blockquote&gt;</code>.\n    The <code>&lt;p&gt;</code> tags can be replaced with whatever you desire,\n    as long as it is a block level element.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt",
    "content": "HTML.CoreModules\nTYPE: lookup\nVERSION: 2.0.0\n--DEFAULT--\narray (\n  'Structure' => true,\n  'Text' => true,\n  'Hypertext' => true,\n  'List' => true,\n  'NonXMLCommonAttributes' => true,\n  'XMLCommonAttributes' => true,\n  'CommonAttributes' => true,\n)\n--DESCRIPTION--\n\n<p>\n    Certain modularized doctypes (XHTML, namely), have certain modules\n    that must be included for the doctype to be an conforming document\n    type: put those modules here. By default, XHTML's core modules\n    are used. You can set this to a blank array to disable core module\n    protection, but this is not recommended.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt",
    "content": "HTML.CustomDoctype\nTYPE: string/null\nVERSION: 2.0.1\nDEFAULT: NULL\n--DESCRIPTION--\n\nA custom doctype for power-users who defined there own document\ntype. This directive only applies when %HTML.Doctype is blank.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt",
    "content": "HTML.DefinitionID\nTYPE: string/null\nDEFAULT: NULL\nVERSION: 2.0.0\n--DESCRIPTION--\n\n<p>\n    Unique identifier for a custom-built HTML definition. If you edit\n    the raw version of the HTMLDefinition, introducing changes that the\n    configuration object does not reflect, you must specify this variable.\n    If you change your custom edits, you should change this directive, or\n    clear your cache. Example:\n</p>\n<pre>\n$config = HTMLPurifier_Config::createDefault();\n$config->set('HTML', 'DefinitionID', '1');\n$def = $config->getHTMLDefinition();\n$def->addAttribute('a', 'tabindex', 'Number');\n</pre>\n<p>\n    In the above example, the configuration is still at the defaults, but\n    using the advanced API, an extra attribute has been added. The\n    configuration object normally has no way of knowing that this change\n    has taken place, so it needs an extra directive: %HTML.DefinitionID.\n    If someone else attempts to use the default configuration, these two\n    pieces of code will not clobber each other in the cache, since one has\n    an extra directive attached to it.\n</p>\n<p>\n    You <em>must</em> specify a value to this directive to use the\n    advanced API features.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt",
    "content": "HTML.DefinitionRev\nTYPE: int\nVERSION: 2.0.0\nDEFAULT: 1\n--DESCRIPTION--\n\n<p>\n    Revision identifier for your custom definition specified in\n    %HTML.DefinitionID.  This serves the same purpose: uniquely identifying\n    your custom definition, but this one does so in a chronological\n    context: revision 3 is more up-to-date then revision 2.  Thus, when\n    this gets incremented, the cache handling is smart enough to clean\n    up any older revisions of your definition as well as flush the\n    cache.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt",
    "content": "HTML.Doctype\nTYPE: string/null\nDEFAULT: NULL\n--DESCRIPTION--\nDoctype to use during filtering. Technically speaking this is not actually\na doctype (as it does not identify a corresponding DTD), but we are using\nthis name for sake of simplicity. When non-blank, this will override any\nolder directives like %HTML.XHTML or %HTML.Strict.\n--ALLOWED--\n'HTML 4.01 Transitional', 'HTML 4.01 Strict', 'XHTML 1.0 Transitional', 'XHTML 1.0 Strict', 'XHTML 1.1'\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt",
    "content": "HTML.ForbiddenAttributes\nTYPE: lookup\nVERSION: 3.1.0\nDEFAULT: array()\n--DESCRIPTION--\n<p>\n    While this directive is similar to %HTML.AllowedAttributes, for\n    forwards-compatibility with XML, this attribute has a different syntax. Instead of\n    <code>tag.attr</code>, use <code>tag@attr</code>. To disallow <code>href</code>\n    attributes in <code>a</code> tags, set this directive to\n    <code>a@href</code>. You can also disallow an attribute globally with\n    <code>attr</code> or <code>*@attr</code> (either syntax is fine; the latter\n    is provided for consistency with %HTML.AllowedAttributes).\n</p>\n<p>\n    <strong>Warning:</strong> This directive complements %HTML.ForbiddenElements,\n    accordingly, check\n    out that directive for a discussion of why you\n    should think twice before using this directive.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt",
    "content": "HTML.ForbiddenElements\nTYPE: lookup\nVERSION: 3.1.0\nDEFAULT: array()\n--DESCRIPTION--\n<p>\n    This was, perhaps, the most requested feature ever in HTML\n    Purifier. Please don't abuse it! This is the logical inverse of\n    %HTML.AllowedElements, and it will override that directive, or any\n    other directive.\n</p>\n<p>\n    If possible, %HTML.Allowed is recommended over this directive, because it\n    can sometimes be difficult to tell whether or not you've forbidden all of\n    the behavior you would like to disallow. If you forbid <code>img</code>\n    with the expectation of preventing images on your site, you'll be in for\n    a nasty surprise when people start using the <code>background-image</code>\n    CSS property.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt",
    "content": "HTML.MaxImgLength\nTYPE: int/null\nDEFAULT: 1200\nVERSION: 3.1.1\n--DESCRIPTION--\n<p>\n This directive controls the maximum number of pixels in the width and\n height attributes in <code>img</code> tags. This is\n in place to prevent imagecrash attacks, disable with null at your own risk.\n This directive is similar to %CSS.MaxImgLength, and both should be\n concurrently edited, although there are\n subtle differences in the input format (the HTML max is an integer).\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt",
    "content": "HTML.Parent\nTYPE: string\nVERSION: 1.3.0\nDEFAULT: 'div'\n--DESCRIPTION--\n\n<p>\n    String name of element that HTML fragment passed to library will be\n    inserted in.  An interesting variation would be using span as the\n    parent element, meaning that only inline tags would be allowed.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt",
    "content": "HTML.Proprietary\nTYPE: bool\nVERSION: 3.1.0\nDEFAULT: false\n--DESCRIPTION--\n<p>\n    Whether or not to allow proprietary elements and attributes in your\n    documents, as per <code>HTMLPurifier_HTMLModule_Proprietary</code>.\n    <strong>Warning:</strong> This can cause your documents to stop\n    validating!\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt",
    "content": "HTML.SafeEmbed\nTYPE: bool\nVERSION: 3.1.1\nDEFAULT: false\n--DESCRIPTION--\n<p>\n    Whether or not to permit embed tags in documents, with a number of extra\n    security features added to prevent script execution. This is similar to\n    what websites like MySpace do to embed tags. Embed is a proprietary\n    element and will cause your website to stop validating. You probably want\n    to enable this with %HTML.SafeObject.\n    <strong>Highly experimental.</strong>\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt",
    "content": "HTML.SafeObject\nTYPE: bool\nVERSION: 3.1.1\nDEFAULT: false\n--DESCRIPTION--\n<p>\n    Whether or not to permit object tags in documents, with a number of extra\n    security features added to prevent script execution. This is similar to\n    what websites like MySpace do to object tags. You may also want to\n    enable %HTML.SafeEmbed for maximum interoperability with Internet Explorer,\n    although embed tags will cause your website to stop validating.\n    <strong>Highly experimental.</strong>\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt",
    "content": "HTML.Strict\nTYPE: bool\nVERSION: 1.3.0\nDEFAULT: false\nDEPRECATED-VERSION: 1.7.0\nDEPRECATED-USE: HTML.Doctype\n--DESCRIPTION--\nDetermines whether or not to use Transitional (loose) or Strict rulesets.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt",
    "content": "HTML.TidyAdd\nTYPE: lookup\nVERSION: 2.0.0\nDEFAULT: array()\n--DESCRIPTION--\n\nFixes to add to the default set of Tidy fixes as per your level.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt",
    "content": "HTML.TidyLevel\nTYPE: string\nVERSION: 2.0.0\nDEFAULT: 'medium'\n--DESCRIPTION--\n\n<p>General level of cleanliness the Tidy module should enforce.\nThere are four allowed values:</p>\n<dl>\n    <dt>none</dt>\n    <dd>No extra tidying should be done</dd>\n    <dt>light</dt>\n    <dd>Only fix elements that would be discarded otherwise due to\n    lack of support in doctype</dd>\n    <dt>medium</dt>\n    <dd>Enforce best practices</dd>\n    <dt>heavy</dt>\n    <dd>Transform all deprecated elements and attributes to standards\n    compliant equivalents</dd>\n</dl>\n\n--ALLOWED--\n'none', 'light', 'medium', 'heavy'\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt",
    "content": "HTML.TidyRemove\nTYPE: lookup\nVERSION: 2.0.0\nDEFAULT: array()\n--DESCRIPTION--\n\nFixes to remove from the default set of Tidy fixes as per your level.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt",
    "content": "HTML.Trusted\nTYPE: bool\nVERSION: 2.0.0\nDEFAULT: false\n--DESCRIPTION--\nIndicates whether or not the user input is trusted or not. If the input is\ntrusted, a more expansive set of allowed tags and attributes will be used.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt",
    "content": "HTML.XHTML\nTYPE: bool\nDEFAULT: true\nVERSION: 1.1.0\nDEPRECATED-VERSION: 1.7.0\nDEPRECATED-USE: HTML.Doctype\n--DESCRIPTION--\nDetermines whether or not output is XHTML 1.0 or HTML 4.01 flavor.\n--ALIASES--\nCore.XHTML\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt",
    "content": "Output.CommentScriptContents\nTYPE: bool\nVERSION: 2.0.0\nDEFAULT: true\n--DESCRIPTION--\nDetermines whether or not HTML Purifier should attempt to fix up the\ncontents of script tags for legacy browsers with comments.\n--ALIASES--\nCore.CommentScriptContents\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt",
    "content": "Output.Newline\nTYPE: string/null\nVERSION: 2.0.1\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    Newline string to format final output with. If left null, HTML Purifier\n    will auto-detect the default newline type of the system and use that;\n    you can manually override it here. Remember, \\r\\n is Windows, \\r\n    is Mac, and \\n is Unix.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt",
    "content": "Output.SortAttr\nTYPE: bool\nVERSION: 3.2.0\nDEFAULT: false\n--DESCRIPTION--\n<p>\n  If true, HTML Purifier will sort attributes by name before writing them back\n  to the document, converting a tag like: <code>&lt;el b=\"\" a=\"\" c=\"\" /&gt;</code>\n  to <code>&lt;el a=\"\" b=\"\" c=\"\" /&gt;</code>. This is a workaround for\n  a bug in FCKeditor which causes it to swap attributes order, adding noise\n  to text diffs. If you're not seeing this bug, chances are, you don't need\n  this directive.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt",
    "content": "Output.TidyFormat\nTYPE: bool\nVERSION: 1.1.1\nDEFAULT: false\n--DESCRIPTION--\n<p>\n    Determines whether or not to run Tidy on the final output for pretty\n    formatting reasons, such as indentation and wrap.\n</p>\n<p>\n    This can greatly improve readability for editors who are hand-editing\n    the HTML, but is by no means necessary as HTML Purifier has already\n    fixed all major errors the HTML may have had. Tidy is a non-default\n    extension, and this directive will silently fail if Tidy is not\n    available.\n</p>\n<p>\n    If you are looking to make the overall look of your page's source\n    better, I recommend running Tidy on the entire page rather than just\n    user-content (after all, the indentation relative to the containing\n    blocks will be incorrect).\n</p>\n--ALIASES--\nCore.TidyFormat\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt",
    "content": "Test.ForceNoIconv\nTYPE: bool\nDEFAULT: false\n--DESCRIPTION--\nWhen set to true, HTMLPurifier_Encoder will act as if iconv does not exist\nand use only pure PHP implementations.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt",
    "content": "URI.AllowedSchemes\nTYPE: lookup\n--DEFAULT--\narray (\n  'http' => true,\n  'https' => true,\n  'mailto' => true,\n  'ftp' => true,\n  'nntp' => true,\n  'news' => true,\n)\n--DESCRIPTION--\nWhitelist that defines the schemes that a URI is allowed to have.  This\nprevents XSS attacks from using pseudo-schemes like javascript or mocha.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.Base.txt",
    "content": "URI.Base\nTYPE: string/null\nVERSION: 2.1.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    The base URI is the URI of the document this purified HTML will be\n    inserted into.  This information is important if HTML Purifier needs\n    to calculate absolute URIs from relative URIs, such as when %URI.MakeAbsolute\n    is on.  You may use a non-absolute URI for this value, but behavior\n    may vary (%URI.MakeAbsolute deals nicely with both absolute and\n    relative paths, but forwards-compatibility is not guaranteed).\n    <strong>Warning:</strong> If set, the scheme on this URI\n    overrides the one specified by %URI.DefaultScheme.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt",
    "content": "URI.DefaultScheme\nTYPE: string\nDEFAULT: 'http'\n--DESCRIPTION--\n\n<p>\n    Defines through what scheme the output will be served, in order to\n    select the proper object validator when no scheme information is present.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt",
    "content": "URI.DefinitionID\nTYPE: string/null\nVERSION: 2.1.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    Unique identifier for a custom-built URI definition. If you  want\n    to add custom URIFilters, you must specify this value.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt",
    "content": "URI.DefinitionRev\nTYPE: int\nVERSION: 2.1.0\nDEFAULT: 1\n--DESCRIPTION--\n\n<p>\n    Revision identifier for your custom definition. See\n    %HTML.DefinitionRev for details.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt",
    "content": "URI.Disable\nTYPE: bool\nVERSION: 1.3.0\nDEFAULT: false\n--DESCRIPTION--\n\n<p>\n    Disables all URIs in all forms. Not sure why you'd want to do that\n    (after all, the Internet's founded on the notion of a hyperlink).\n</p>\n\n--ALIASES--\nAttr.DisableURI\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt",
    "content": "URI.DisableExternal\nTYPE: bool\nVERSION: 1.2.0\nDEFAULT: false\n--DESCRIPTION--\nDisables links to external websites.  This is a highly effective anti-spam\nand anti-pagerank-leech measure, but comes at a hefty price: nolinks or\nimages outside of your domain will be allowed.  Non-linkified URIs will\nstill be preserved.  If you want to be able to link to subdomains or use\nabsolute URIs, specify %URI.Host for your website.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt",
    "content": "URI.DisableExternalResources\nTYPE: bool\nVERSION: 1.3.0\nDEFAULT: false\n--DESCRIPTION--\nDisables the embedding of external resources, preventing users from\nembedding things like images from other hosts. This prevents access\ntracking (good for email viewers), bandwidth leeching, cross-site request\nforging, goatse.cx posting, and other nasties, but also results in a loss\nof end-user functionality (they can't directly post a pic they posted from\nFlickr anymore). Use it if you don't have a robust user-content moderation\nteam.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt",
    "content": "URI.DisableResources\nTYPE: bool\nVERSION: 1.3.0\nDEFAULT: false\n--DESCRIPTION--\n\n<p>\n    Disables embedding resources, essentially meaning no pictures. You can\n    still link to them though. See %URI.DisableExternalResources for why\n    this might be a good idea.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.Host.txt",
    "content": "URI.Host\nTYPE: string/null\nVERSION: 1.2.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    Defines the domain name of the server, so we can determine whether or\n    an absolute URI is from your website or not.  Not strictly necessary,\n    as users should be using relative URIs to reference resources on your\n    website.  It will, however, let you use absolute URIs to link to\n    subdomains of the domain you post here: i.e. example.com will allow\n    sub.example.com.  However, higher up domains will still be excluded:\n    if you set %URI.Host to sub.example.com, example.com will be blocked.\n    <strong>Note:</strong> This directive overrides %URI.Base because\n    a given page may be on a sub-domain, but you wish HTML Purifier to be\n    more relaxed and allow some of the parent domains too.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt",
    "content": "URI.HostBlacklist\nTYPE: list\nVERSION: 1.3.0\nDEFAULT: array()\n--DESCRIPTION--\nList of strings that are forbidden in the host of any URI. Use it to kill\ndomain names of spam, etc. Note that it will catch anything in the domain,\nso <tt>moo.com</tt> will catch <tt>moo.com.example.com</tt>.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt",
    "content": "URI.MakeAbsolute\nTYPE: bool\nVERSION: 2.1.0\nDEFAULT: false\n--DESCRIPTION--\n\n<p>\n    Converts all URIs into absolute forms. This is useful when the HTML\n    being filtered assumes a specific base path, but will actually be\n    viewed in a different context (and setting an alternate base URI is\n    not possible). %URI.Base must be set for this directive to work.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt",
    "content": "URI.Munge\nTYPE: string/null\nVERSION: 1.3.0\nDEFAULT: NULL\n--DESCRIPTION--\n\n<p>\n    Munges all browsable (usually http, https and ftp)\n    absolute URIs into another URI, usually a URI redirection service.\n    This directive accepts a URI, formatted with a <code>%s</code> where\n    the url-encoded original URI should be inserted (sample:\n    <code>http://www.google.com/url?q=%s</code>).\n</p>\n<p>\n    Uses for this directive:\n</p>\n<ul>\n    <li>\n        Prevent PageRank leaks, while being fairly transparent\n        to users (you may also want to add some client side JavaScript to\n        override the text in the statusbar). <strong>Notice</strong>:\n        Many security experts believe that this form of protection does not deter spam-bots.\n    </li>\n    <li>\n        Redirect users to a splash page telling them they are leaving your\n        website. While this is poor usability practice, it is often mandated\n        in corporate environments.\n    </li>\n</ul>\n<p>\n    Prior to HTML Purifier 3.1.1, this directive also enabled the munging\n    of browsable external resources, which could break things if your redirection\n    script was a splash page or used <code>meta</code> tags. To revert to\n    previous behavior, please use %URI.MungeResources.\n</p>\n<p>\n    You may want to also use %URI.MungeSecretKey along with this directive\n    in order to enforce what URIs your redirector script allows. Open\n    redirector scripts can be a security risk and negatively affect the\n    reputation of your domain name.\n</p>\n<p>\n    Starting with HTML Purifier 3.1.1, there is also these substitutions:\n</p>\n<table>\n    <thead>\n        <tr>\n            <th>Key</th>\n            <th>Description</th>\n            <th>Example <code>&lt;a href=\"\"&gt;</code></th>\n        </tr>\n    </thead>\n    <tbody>\n        <tr>\n            <td>%r</td>\n            <td>1 - The URI embeds a resource<br />(blank) - The URI is merely a link</td>\n            <td></td>\n        </tr>\n        <tr>\n            <td>%n</td>\n            <td>The name of the tag this URI came from</td>\n            <td>a</td>\n        </tr>\n        <tr>\n            <td>%m</td>\n            <td>The name of the attribute this URI came from</td>\n            <td>href</td>\n        </tr>\n        <tr>\n            <td>%p</td>\n            <td>The name of the CSS property this URI came from, or blank if irrelevant</td>\n            <td></td>\n        </tr>\n    </tbody>\n</table>\n<p>\n    Admittedly, these letters are somewhat arbitrary; the only stipulation\n    was that they couldn't be a through f. r is for resource (I would have preferred\n    e, but you take what you can get), n is for name, m\n    was picked because it came after n (and I couldn't use a), p is for\n    property.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt",
    "content": "URI.MungeResources\nTYPE: bool\nVERSION: 3.1.1\nDEFAULT: false\n--DESCRIPTION--\n<p>\n    If true, any URI munging directives like %URI.Munge\n    will also apply to embedded resources, such as <code>&lt;img src=\"\"&gt;</code>.\n    Be careful enabling this directive if you have a redirector script\n    that does not use the <code>Location</code> HTTP header; all of your images\n    and other embedded resources will break.\n</p>\n<p>\n    <strong>Warning:</strong> It is strongly advised you use this in conjunction\n    %URI.MungeSecretKey to mitigate the security risk of an open redirector.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt",
    "content": "URI.MungeSecretKey\nTYPE: string/null\nVERSION: 3.1.1\nDEFAULT: NULL\n--DESCRIPTION--\n<p>\n    This directive enables secure checksum generation along with %URI.Munge.\n    It should be set to a secure key that is not shared with anyone else.\n    The checksum can be placed in the URI using %t. Use of this checksum\n    affords an additional level of protection by allowing a redirector\n    to check if a URI has passed through HTML Purifier with this line:\n</p>\n\n<pre>$checksum === sha1($secret_key . ':' . $url)</pre>\n\n<p>\n    If the output is TRUE, the redirector script should accept the URI.\n</p>\n\n<p>\n    Please note that it would still be possible for an attacker to procure\n    secure hashes en-mass by abusing your website's Preview feature or the\n    like, but this service affords an additional level of protection\n    that should be combined with website blacklisting.\n</p>\n\n<p>\n    Remember this has no effect if %URI.Munge is not on.\n</p>\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt",
    "content": "URI.OverrideAllowedSchemes\nTYPE: bool\nDEFAULT: true\n--DESCRIPTION--\nIf this is set to true (which it is by default), you can override\n%URI.AllowedSchemes by simply registering a HTMLPurifier_URIScheme to the\nregistry.  If false, you will also have to update that directive in order\nto add more schemes.\n--# vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema/schema/info.ini",
    "content": "name = \"HTML Purifier\"\n\n; vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ConfigSchema.php",
    "content": "<?php\n\n/**\n * Configuration definition, defines directives and their defaults.\n */\nclass HTMLPurifier_ConfigSchema {\n\n    /**\n     * Defaults of the directives and namespaces.\n     * @note This shares the exact same structure as HTMLPurifier_Config::$conf\n     */\n    public $defaults = array();\n\n    /**\n     * The default property list. Do not edit this property list.\n     */\n    public $defaultPlist;\n\n    /**\n     * Definition of the directives. The structure of this is:\n     *\n     *  array(\n     *      'Namespace' => array(\n     *          'Directive' => new stdclass(),\n     *      )\n     *  )\n     *\n     * The stdclass may have the following properties:\n     *\n     *  - If isAlias isn't set:\n     *      - type: Integer type of directive, see HTMLPurifier_VarParser for definitions\n     *      - allow_null: If set, this directive allows null values\n     *      - aliases: If set, an associative array of value aliases to real values\n     *      - allowed: If set, a lookup array of allowed (string) values\n     *  - If isAlias is set:\n     *      - namespace: Namespace this directive aliases to\n     *      - name: Directive name this directive aliases to\n     *\n     * In certain degenerate cases, stdclass will actually be an integer. In\n     * that case, the value is equivalent to an stdclass with the type\n     * property set to the integer. If the integer is negative, type is\n     * equal to the absolute value of integer, and allow_null is true.\n     *\n     * This class is friendly with HTMLPurifier_Config. If you need introspection\n     * about the schema, you're better of using the ConfigSchema_Interchange,\n     * which uses more memory but has much richer information.\n     */\n    public $info = array();\n\n    /**\n     * Application-wide singleton\n     */\n    static protected $singleton;\n\n    public function __construct() {\n        $this->defaultPlist = new HTMLPurifier_PropertyList();\n    }\n\n    /**\n     * Unserializes the default ConfigSchema.\n     */\n    public static function makeFromSerial() {\n        return unserialize(file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema.ser'));\n    }\n\n    /**\n     * Retrieves an instance of the application-wide configuration definition.\n     */\n    public static function instance($prototype = null) {\n        if ($prototype !== null) {\n            HTMLPurifier_ConfigSchema::$singleton = $prototype;\n        } elseif (HTMLPurifier_ConfigSchema::$singleton === null || $prototype === true) {\n            HTMLPurifier_ConfigSchema::$singleton = HTMLPurifier_ConfigSchema::makeFromSerial();\n        }\n        return HTMLPurifier_ConfigSchema::$singleton;\n    }\n\n    /**\n     * Defines a directive for configuration\n     * @warning Will fail of directive's namespace is defined.\n     * @warning This method's signature is slightly different from the legacy\n     *          define() static method! Beware!\n     * @param $namespace Namespace the directive is in\n     * @param $name Key of directive\n     * @param $default Default value of directive\n     * @param $type Allowed type of the directive. See\n     *      HTMLPurifier_DirectiveDef::$type for allowed values\n     * @param $allow_null Whether or not to allow null values\n     */\n    public function add($key, $default, $type, $allow_null) {\n        $obj = new stdclass();\n        $obj->type = is_int($type) ? $type : HTMLPurifier_VarParser::$types[$type];\n        if ($allow_null) $obj->allow_null = true;\n        $this->info[$key] = $obj;\n        $this->defaults[$key] = $default;\n        $this->defaultPlist->set($key, $default);\n    }\n\n    /**\n     * Defines a directive value alias.\n     *\n     * Directive value aliases are convenient for developers because it lets\n     * them set a directive to several values and get the same result.\n     * @param $namespace Directive's namespace\n     * @param $name Name of Directive\n     * @param $aliases Hash of aliased values to the real alias\n     */\n    public function addValueAliases($key, $aliases) {\n        if (!isset($this->info[$key]->aliases)) {\n            $this->info[$key]->aliases = array();\n        }\n        foreach ($aliases as $alias => $real) {\n            $this->info[$key]->aliases[$alias] = $real;\n        }\n    }\n\n    /**\n     * Defines a set of allowed values for a directive.\n     * @warning This is slightly different from the corresponding static\n     *          method definition.\n     * @param $namespace Namespace of directive\n     * @param $name Name of directive\n     * @param $allowed Lookup array of allowed values\n     */\n    public function addAllowedValues($key, $allowed) {\n        $this->info[$key]->allowed = $allowed;\n    }\n\n    /**\n     * Defines a directive alias for backwards compatibility\n     * @param $namespace\n     * @param $name Directive that will be aliased\n     * @param $new_namespace\n     * @param $new_name Directive that the alias will be to\n     */\n    public function addAlias($key, $new_key) {\n        $obj = new stdclass;\n        $obj->key = $new_key;\n        $obj->isAlias = true;\n        $this->info[$key] = $obj;\n    }\n\n    /**\n     * Replaces any stdclass that only has the type property with type integer.\n     */\n    public function postProcess() {\n        foreach ($this->info as $key => $v) {\n            if (count((array) $v) == 1) {\n                $this->info[$key] = $v->type;\n            } elseif (count((array) $v) == 2 && isset($v->allow_null)) {\n                $this->info[$key] = -$v->type;\n            }\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ContentSets.php",
    "content": "<?php\n\n/**\n * @todo Unit test\n */\nclass HTMLPurifier_ContentSets\n{\n\n    /**\n     * List of content set strings (pipe seperators) indexed by name.\n     */\n    public $info = array();\n\n    /**\n     * List of content set lookups (element => true) indexed by name.\n     * @note This is in HTMLPurifier_HTMLDefinition->info_content_sets\n     */\n    public $lookup = array();\n\n    /**\n     * Synchronized list of defined content sets (keys of info)\n     */\n    protected $keys = array();\n    /**\n     * Synchronized list of defined content values (values of info)\n     */\n    protected $values = array();\n\n    /**\n     * Merges in module's content sets, expands identifiers in the content\n     * sets and populates the keys, values and lookup member variables.\n     * @param $modules List of HTMLPurifier_HTMLModule\n     */\n    public function __construct($modules) {\n        if (!is_array($modules)) $modules = array($modules);\n        // populate content_sets based on module hints\n        // sorry, no way of overloading\n        foreach ($modules as $module_i => $module) {\n            foreach ($module->content_sets as $key => $value) {\n                $temp = $this->convertToLookup($value);\n                if (isset($this->lookup[$key])) {\n                    // add it into the existing content set\n                    $this->lookup[$key] = array_merge($this->lookup[$key], $temp);\n                } else {\n                    $this->lookup[$key] = $temp;\n                }\n            }\n        }\n        $old_lookup = false;\n        while ($old_lookup !== $this->lookup) {\n            $old_lookup = $this->lookup;\n            foreach ($this->lookup as $i => $set) {\n                $add = array();\n                foreach ($set as $element => $x) {\n                    if (isset($this->lookup[$element])) {\n                        $add += $this->lookup[$element];\n                        unset($this->lookup[$i][$element]);\n                    }\n                }\n                $this->lookup[$i] += $add;\n            }\n        }\n\n        foreach ($this->lookup as $key => $lookup) {\n            $this->info[$key] = implode(' | ', array_keys($lookup));\n        }\n        $this->keys   = array_keys($this->info);\n        $this->values = array_values($this->info);\n    }\n\n    /**\n     * Accepts a definition; generates and assigns a ChildDef for it\n     * @param $def HTMLPurifier_ElementDef reference\n     * @param $module Module that defined the ElementDef\n     */\n    public function generateChildDef(&$def, $module) {\n        if (!empty($def->child)) return; // already done!\n        $content_model = $def->content_model;\n        if (is_string($content_model)) {\n            // Assume that $this->keys is alphanumeric\n            $def->content_model = preg_replace_callback(\n                '/\\b(' . implode('|', $this->keys) . ')\\b/',\n                array($this, 'generateChildDefCallback'),\n                $content_model\n            );\n            //$def->content_model = str_replace(\n            //    $this->keys, $this->values, $content_model);\n        }\n        $def->child = $this->getChildDef($def, $module);\n    }\n\n    public function generateChildDefCallback($matches) {\n        return $this->info[$matches[0]];\n    }\n\n    /**\n     * Instantiates a ChildDef based on content_model and content_model_type\n     * member variables in HTMLPurifier_ElementDef\n     * @note This will also defer to modules for custom HTMLPurifier_ChildDef\n     *       subclasses that need content set expansion\n     * @param $def HTMLPurifier_ElementDef to have ChildDef extracted\n     * @return HTMLPurifier_ChildDef corresponding to ElementDef\n     */\n    public function getChildDef($def, $module) {\n        $value = $def->content_model;\n        if (is_object($value)) {\n            trigger_error(\n                'Literal object child definitions should be stored in '.\n                'ElementDef->child not ElementDef->content_model',\n                E_USER_NOTICE\n            );\n            return $value;\n        }\n        switch ($def->content_model_type) {\n            case 'required':\n                return new HTMLPurifier_ChildDef_Required($value);\n            case 'optional':\n                return new HTMLPurifier_ChildDef_Optional($value);\n            case 'empty':\n                return new HTMLPurifier_ChildDef_Empty();\n            case 'custom':\n                return new HTMLPurifier_ChildDef_Custom($value);\n        }\n        // defer to its module\n        $return = false;\n        if ($module->defines_child_def) { // save a func call\n            $return = $module->getChildDef($def);\n        }\n        if ($return !== false) return $return;\n        // error-out\n        trigger_error(\n            'Could not determine which ChildDef class to instantiate',\n            E_USER_ERROR\n        );\n        return false;\n    }\n\n    /**\n     * Converts a string list of elements separated by pipes into\n     * a lookup array.\n     * @param $string List of elements\n     * @return Lookup array of elements\n     */\n    protected function convertToLookup($string) {\n        $array = explode('|', str_replace(' ', '', $string));\n        $ret = array();\n        foreach ($array as $i => $k) {\n            $ret[$k] = true;\n        }\n        return $ret;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Context.php",
    "content": "<?php\n\n/**\n * Registry object that contains information about the current context.\n * @warning Is a bit buggy when variables are set to null: it thinks\n *          they don't exist! So use false instead, please.\n * @note Since the variables Context deals with may not be objects,\n *       references are very important here! Do not remove!\n */\nclass HTMLPurifier_Context\n{\n\n    /**\n     * Private array that stores the references.\n     */\n    private $_storage = array();\n\n    /**\n     * Registers a variable into the context.\n     * @param $name String name\n     * @param $ref Reference to variable to be registered\n     */\n    public function register($name, &$ref) {\n        if (isset($this->_storage[$name])) {\n            trigger_error(\"Name $name produces collision, cannot re-register\",\n                          E_USER_ERROR);\n            return;\n        }\n        $this->_storage[$name] =& $ref;\n    }\n\n    /**\n     * Retrieves a variable reference from the context.\n     * @param $name String name\n     * @param $ignore_error Boolean whether or not to ignore error\n     */\n    public function &get($name, $ignore_error = false) {\n        if (!isset($this->_storage[$name])) {\n            if (!$ignore_error) {\n                trigger_error(\"Attempted to retrieve non-existent variable $name\",\n                              E_USER_ERROR);\n            }\n            $var = null; // so we can return by reference\n            return $var;\n        }\n        return $this->_storage[$name];\n    }\n\n    /**\n     * Destorys a variable in the context.\n     * @param $name String name\n     */\n    public function destroy($name) {\n        if (!isset($this->_storage[$name])) {\n            trigger_error(\"Attempted to destroy non-existent variable $name\",\n                          E_USER_ERROR);\n            return;\n        }\n        unset($this->_storage[$name]);\n    }\n\n    /**\n     * Checks whether or not the variable exists.\n     * @param $name String name\n     */\n    public function exists($name) {\n        return isset($this->_storage[$name]);\n    }\n\n    /**\n     * Loads a series of variables from an associative array\n     * @param $context_array Assoc array of variables to load\n     */\n    public function loadArray($context_array) {\n        foreach ($context_array as $key => $discard) {\n            $this->register($key, $context_array[$key]);\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Definition.php",
    "content": "<?php\n\n/**\n * Super-class for definition datatype objects, implements serialization\n * functions for the class.\n */\nabstract class HTMLPurifier_Definition\n{\n\n    /**\n     * Has setup() been called yet?\n     */\n    public $setup = false;\n\n    /**\n     * What type of definition is it?\n     */\n    public $type;\n\n    /**\n     * Sets up the definition object into the final form, something\n     * not done by the constructor\n     * @param $config HTMLPurifier_Config instance\n     */\n    abstract protected function doSetup($config);\n\n    /**\n     * Setup function that aborts if already setup\n     * @param $config HTMLPurifier_Config instance\n     */\n    public function setup($config) {\n        if ($this->setup) return;\n        $this->setup = true;\n        $this->doSetup($config);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php",
    "content": "<?php\n\n/**\n * Definition cache decorator class that cleans up the cache\n * whenever there is a cache miss.\n */\nclass HTMLPurifier_DefinitionCache_Decorator_Cleanup extends\n      HTMLPurifier_DefinitionCache_Decorator\n{\n\n    public $name = 'Cleanup';\n\n    public function copy() {\n        return new HTMLPurifier_DefinitionCache_Decorator_Cleanup();\n    }\n\n    public function add($def, $config) {\n        $status = parent::add($def, $config);\n        if (!$status) parent::cleanup($config);\n        return $status;\n    }\n\n    public function set($def, $config) {\n        $status = parent::set($def, $config);\n        if (!$status) parent::cleanup($config);\n        return $status;\n    }\n\n    public function replace($def, $config) {\n        $status = parent::replace($def, $config);\n        if (!$status) parent::cleanup($config);\n        return $status;\n    }\n\n    public function get($config) {\n        $ret = parent::get($config);\n        if (!$ret) parent::cleanup($config);\n        return $ret;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DefinitionCache/Decorator/Memory.php",
    "content": "<?php\n\n/**\n * Definition cache decorator class that saves all cache retrievals\n * to PHP's memory; good for unit tests or circumstances where\n * there are lots of configuration objects floating around.\n */\nclass HTMLPurifier_DefinitionCache_Decorator_Memory extends\n      HTMLPurifier_DefinitionCache_Decorator\n{\n\n    protected $definitions;\n    public $name = 'Memory';\n\n    public function copy() {\n        return new HTMLPurifier_DefinitionCache_Decorator_Memory();\n    }\n\n    public function add($def, $config) {\n        $status = parent::add($def, $config);\n        if ($status) $this->definitions[$this->generateKey($config)] = $def;\n        return $status;\n    }\n\n    public function set($def, $config) {\n        $status = parent::set($def, $config);\n        if ($status) $this->definitions[$this->generateKey($config)] = $def;\n        return $status;\n    }\n\n    public function replace($def, $config) {\n        $status = parent::replace($def, $config);\n        if ($status) $this->definitions[$this->generateKey($config)] = $def;\n        return $status;\n    }\n\n    public function get($config) {\n        $key = $this->generateKey($config);\n        if (isset($this->definitions[$key])) return $this->definitions[$key];\n        $this->definitions[$key] = parent::get($config);\n        return $this->definitions[$key];\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DefinitionCache/Decorator/Template.php.in",
    "content": "<?php\n\nrequire_once 'HTMLPurifier/DefinitionCache/Decorator.php';\n\n/**\n * Definition cache decorator template.\n */\nclass HTMLPurifier_DefinitionCache_Decorator_Template extends\n      HTMLPurifier_DefinitionCache_Decorator\n{\n\n    var $name = 'Template'; // replace this\n\n    function copy() {\n        // replace class name with yours\n        return new HTMLPurifier_DefinitionCache_Decorator_Template();\n    }\n\n    // remove methods you don't need\n\n    function add($def, $config) {\n        return parent::add($def, $config);\n    }\n\n    function set($def, $config) {\n        return parent::set($def, $config);\n    }\n\n    function replace($def, $config) {\n        return parent::replace($def, $config);\n    }\n\n    function get($config) {\n        return parent::get($config);\n    }\n\n    function flush() {\n        return parent::flush();\n    }\n\n    function cleanup($config) {\n        return parent::cleanup($config);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DefinitionCache/Decorator.php",
    "content": "<?php\n\nclass HTMLPurifier_DefinitionCache_Decorator extends HTMLPurifier_DefinitionCache\n{\n\n    /**\n     * Cache object we are decorating\n     */\n    public $cache;\n\n    public function __construct() {}\n\n    /**\n     * Lazy decorator function\n     * @param $cache Reference to cache object to decorate\n     */\n    public function decorate(&$cache) {\n        $decorator = $this->copy();\n        // reference is necessary for mocks in PHP 4\n        $decorator->cache =& $cache;\n        $decorator->type  = $cache->type;\n        return $decorator;\n    }\n\n    /**\n     * Cross-compatible clone substitute\n     */\n    public function copy() {\n        return new HTMLPurifier_DefinitionCache_Decorator();\n    }\n\n    public function add($def, $config) {\n        return $this->cache->add($def, $config);\n    }\n\n    public function set($def, $config) {\n        return $this->cache->set($def, $config);\n    }\n\n    public function replace($def, $config) {\n        return $this->cache->replace($def, $config);\n    }\n\n    public function get($config) {\n        return $this->cache->get($config);\n    }\n\n    public function remove($config) {\n        return $this->cache->remove($config);\n    }\n\n    public function flush($config) {\n        return $this->cache->flush($config);\n    }\n\n    public function cleanup($config) {\n        return $this->cache->cleanup($config);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DefinitionCache/Null.php",
    "content": "<?php\n\n/**\n * Null cache object to use when no caching is on.\n */\nclass HTMLPurifier_DefinitionCache_Null extends HTMLPurifier_DefinitionCache\n{\n\n    public function add($def, $config) {\n        return false;\n    }\n\n    public function set($def, $config) {\n        return false;\n    }\n\n    public function replace($def, $config) {\n        return false;\n    }\n\n    public function remove($config) {\n        return false;\n    }\n\n    public function get($config) {\n        return false;\n    }\n\n    public function flush($config) {\n        return false;\n    }\n\n    public function cleanup($config) {\n        return false;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DefinitionCache/Serializer/README",
    "content": "This is a dummy file to prevent Git from ignoring this empty directory.\n\n    vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DefinitionCache/Serializer.php",
    "content": "<?php\n\nclass HTMLPurifier_DefinitionCache_Serializer extends\n      HTMLPurifier_DefinitionCache\n{\n\n    public function add($def, $config) {\n        if (!$this->checkDefType($def)) return;\n        $file = $this->generateFilePath($config);\n        if (file_exists($file)) return false;\n        if (!$this->_prepareDir($config)) return false;\n        return $this->_write($file, serialize($def));\n    }\n\n    public function set($def, $config) {\n        if (!$this->checkDefType($def)) return;\n        $file = $this->generateFilePath($config);\n        if (!$this->_prepareDir($config)) return false;\n        return $this->_write($file, serialize($def));\n    }\n\n    public function replace($def, $config) {\n        if (!$this->checkDefType($def)) return;\n        $file = $this->generateFilePath($config);\n        if (!file_exists($file)) return false;\n        if (!$this->_prepareDir($config)) return false;\n        return $this->_write($file, serialize($def));\n    }\n\n    public function get($config) {\n        $file = $this->generateFilePath($config);\n        if (!file_exists($file)) return false;\n        return unserialize(file_get_contents($file));\n    }\n\n    public function remove($config) {\n        $file = $this->generateFilePath($config);\n        if (!file_exists($file)) return false;\n        return unlink($file);\n    }\n\n    public function flush($config) {\n        if (!$this->_prepareDir($config)) return false;\n        $dir = $this->generateDirectoryPath($config);\n        $dh  = opendir($dir);\n        while (false !== ($filename = readdir($dh))) {\n            if (empty($filename)) continue;\n            if ($filename[0] === '.') continue;\n            unlink($dir . '/' . $filename);\n        }\n    }\n\n    public function cleanup($config) {\n        if (!$this->_prepareDir($config)) return false;\n        $dir = $this->generateDirectoryPath($config);\n        $dh  = opendir($dir);\n        while (false !== ($filename = readdir($dh))) {\n            if (empty($filename)) continue;\n            if ($filename[0] === '.') continue;\n            $key = substr($filename, 0, strlen($filename) - 4);\n            if ($this->isOld($key, $config)) unlink($dir . '/' . $filename);\n        }\n    }\n\n    /**\n     * Generates the file path to the serial file corresponding to\n     * the configuration and definition name\n     * @todo Make protected\n     */\n    public function generateFilePath($config) {\n        $key = $this->generateKey($config);\n        return $this->generateDirectoryPath($config) . '/' . $key . '.ser';\n    }\n\n    /**\n     * Generates the path to the directory contain this cache's serial files\n     * @note No trailing slash\n     * @todo Make protected\n     */\n    public function generateDirectoryPath($config) {\n        $base = $this->generateBaseDirectoryPath($config);\n        return $base . '/' . $this->type;\n    }\n\n    /**\n     * Generates path to base directory that contains all definition type\n     * serials\n     * @todo Make protected\n     */\n    public function generateBaseDirectoryPath($config) {\n        $base = $config->get('Cache.SerializerPath');\n        $base = is_null($base) ? HTMLPURIFIER_PREFIX . '/HTMLPurifier/DefinitionCache/Serializer' : $base;\n        return $base;\n    }\n\n    /**\n     * Convenience wrapper function for file_put_contents\n     * @param $file File name to write to\n     * @param $data Data to write into file\n     * @return Number of bytes written if success, or false if failure.\n     */\n    private function _write($file, $data) {\n        return file_put_contents($file, $data);\n    }\n\n    /**\n     * Prepares the directory that this type stores the serials in\n     * @return True if successful\n     */\n    private function _prepareDir($config) {\n        $directory = $this->generateDirectoryPath($config);\n        if (!is_dir($directory)) {\n            $base = $this->generateBaseDirectoryPath($config);\n            if (!is_dir($base)) {\n                trigger_error('Base directory '.$base.' does not exist,\n                    please create or change using %Cache.SerializerPath',\n                    E_USER_WARNING);\n                return false;\n            } elseif (!$this->_testPermissions($base)) {\n                return false;\n            }\n            $old = umask(0022); // disable group and world writes\n            mkdir($directory);\n            umask($old);\n        } elseif (!$this->_testPermissions($directory)) {\n            return false;\n        }\n        return true;\n    }\n\n    /**\n     * Tests permissions on a directory and throws out friendly\n     * error messages and attempts to chmod it itself if possible\n     */\n    private function _testPermissions($dir) {\n        // early abort, if it is writable, everything is hunky-dory\n        if (is_writable($dir)) return true;\n        if (!is_dir($dir)) {\n            // generally, you'll want to handle this beforehand\n            // so a more specific error message can be given\n            trigger_error('Directory '.$dir.' does not exist',\n                E_USER_WARNING);\n            return false;\n        }\n        if (function_exists('posix_getuid')) {\n            // POSIX system, we can give more specific advice\n            if (fileowner($dir) === posix_getuid()) {\n                // we can chmod it ourselves\n                chmod($dir, 0755);\n                return true;\n            } elseif (filegroup($dir) === posix_getgid()) {\n                $chmod = '775';\n            } else {\n                // PHP's probably running as nobody, so we'll\n                // need to give global permissions\n                $chmod = '777';\n            }\n            trigger_error('Directory '.$dir.' not writable, '.\n                'please chmod to ' . $chmod,\n                E_USER_WARNING);\n        } else {\n            // generic error message\n            trigger_error('Directory '.$dir.' not writable, '.\n                'please alter file permissions',\n                E_USER_WARNING);\n        }\n        return false;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DefinitionCache.php",
    "content": "<?php\n\n/**\n * Abstract class representing Definition cache managers that implements\n * useful common methods and is a factory.\n * @todo Create a separate maintenance file advanced users can use to\n *       cache their custom HTMLDefinition, which can be loaded\n *       via a configuration directive\n * @todo Implement memcached\n */\nabstract class HTMLPurifier_DefinitionCache\n{\n\n    public $type;\n\n    /**\n     * @param $name Type of definition objects this instance of the\n     *      cache will handle.\n     */\n    public function __construct($type) {\n        $this->type = $type;\n    }\n\n    /**\n     * Generates a unique identifier for a particular configuration\n     * @param Instance of HTMLPurifier_Config\n     */\n    public function generateKey($config) {\n        return $config->version . ',' . // possibly replace with function calls\n               $config->getBatchSerial($this->type) . ',' .\n               $config->get($this->type . '.DefinitionRev');\n    }\n\n    /**\n     * Tests whether or not a key is old with respect to the configuration's\n     * version and revision number.\n     * @param $key Key to test\n     * @param $config Instance of HTMLPurifier_Config to test against\n     */\n    public function isOld($key, $config) {\n        if (substr_count($key, ',') < 2) return true;\n        list($version, $hash, $revision) = explode(',', $key, 3);\n        $compare = version_compare($version, $config->version);\n        // version mismatch, is always old\n        if ($compare != 0) return true;\n        // versions match, ids match, check revision number\n        if (\n            $hash == $config->getBatchSerial($this->type) &&\n            $revision < $config->get($this->type . '.DefinitionRev')\n        ) return true;\n        return false;\n    }\n\n    /**\n     * Checks if a definition's type jives with the cache's type\n     * @note Throws an error on failure\n     * @param $def Definition object to check\n     * @return Boolean true if good, false if not\n     */\n    public function checkDefType($def) {\n        if ($def->type !== $this->type) {\n            trigger_error(\"Cannot use definition of type {$def->type} in cache for {$this->type}\");\n            return false;\n        }\n        return true;\n    }\n\n    /**\n     * Adds a definition object to the cache\n     */\n    abstract public function add($def, $config);\n\n    /**\n     * Unconditionally saves a definition object to the cache\n     */\n    abstract public function set($def, $config);\n\n    /**\n     * Replace an object in the cache\n     */\n    abstract public function replace($def, $config);\n\n    /**\n     * Retrieves a definition object from the cache\n     */\n    abstract public function get($config);\n\n    /**\n     * Removes a definition object to the cache\n     */\n    abstract public function remove($config);\n\n    /**\n     * Clears all objects from cache\n     */\n    abstract public function flush($config);\n\n    /**\n     * Clears all expired (older version or revision) objects from cache\n     * @note Be carefuly implementing this method as flush. Flush must\n     *       not interfere with other Definition types, and cleanup()\n     *       should not be repeatedly called by userland code.\n     */\n    abstract public function cleanup($config);\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DefinitionCacheFactory.php",
    "content": "<?php\n\n/**\n * Responsible for creating definition caches.\n */\nclass HTMLPurifier_DefinitionCacheFactory\n{\n\n    protected $caches = array('Serializer' => array());\n    protected $implementations = array();\n    protected $decorators = array();\n\n    /**\n     * Initialize default decorators\n     */\n    public function setup() {\n        $this->addDecorator('Cleanup');\n    }\n\n    /**\n     * Retrieves an instance of global definition cache factory.\n     */\n    public static function instance($prototype = null) {\n        static $instance;\n        if ($prototype !== null) {\n            $instance = $prototype;\n        } elseif ($instance === null || $prototype === true) {\n            $instance = new HTMLPurifier_DefinitionCacheFactory();\n            $instance->setup();\n        }\n        return $instance;\n    }\n\n    /**\n     * Registers a new definition cache object\n     * @param $short Short name of cache object, for reference\n     * @param $long Full class name of cache object, for construction\n     */\n    public function register($short, $long) {\n        $this->implementations[$short] = $long;\n    }\n\n    /**\n     * Factory method that creates a cache object based on configuration\n     * @param $name Name of definitions handled by cache\n     * @param $config Instance of HTMLPurifier_Config\n     */\n    public function create($type, $config) {\n        $method = $config->get('Cache.DefinitionImpl');\n        if ($method === null) {\n            return new HTMLPurifier_DefinitionCache_Null($type);\n        }\n        if (!empty($this->caches[$method][$type])) {\n            return $this->caches[$method][$type];\n        }\n        if (\n          isset($this->implementations[$method]) &&\n          class_exists($class = $this->implementations[$method], false)\n        ) {\n            $cache = new $class($type);\n        } else {\n            if ($method != 'Serializer') {\n                trigger_error(\"Unrecognized DefinitionCache $method, using Serializer instead\", E_USER_WARNING);\n            }\n            $cache = new HTMLPurifier_DefinitionCache_Serializer($type);\n        }\n        foreach ($this->decorators as $decorator) {\n            $new_cache = $decorator->decorate($cache);\n            // prevent infinite recursion in PHP 4\n            unset($cache);\n            $cache = $new_cache;\n        }\n        $this->caches[$method][$type] = $cache;\n        return $this->caches[$method][$type];\n    }\n\n    /**\n     * Registers a decorator to add to all new cache objects\n     * @param\n     */\n    public function addDecorator($decorator) {\n        if (is_string($decorator)) {\n            $class = \"HTMLPurifier_DefinitionCache_Decorator_$decorator\";\n            $decorator = new $class;\n        }\n        $this->decorators[$decorator->name] = $decorator;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Doctype.php",
    "content": "<?php\n\n/**\n * Represents a document type, contains information on which modules\n * need to be loaded.\n * @note This class is inspected by Printer_HTMLDefinition->renderDoctype.\n *       If structure changes, please update that function.\n */\nclass HTMLPurifier_Doctype\n{\n    /**\n     * Full name of doctype\n     */\n    public $name;\n\n    /**\n     * List of standard modules (string identifiers or literal objects)\n     * that this doctype uses\n     */\n    public $modules = array();\n\n    /**\n     * List of modules to use for tidying up code\n     */\n    public $tidyModules = array();\n\n    /**\n     * Is the language derived from XML (i.e. XHTML)?\n     */\n    public $xml = true;\n\n    /**\n     * List of aliases for this doctype\n     */\n    public $aliases = array();\n\n    /**\n     * Public DTD identifier\n     */\n    public $dtdPublic;\n\n    /**\n     * System DTD identifier\n     */\n    public $dtdSystem;\n\n    public function __construct($name = null, $xml = true, $modules = array(),\n        $tidyModules = array(), $aliases = array(), $dtd_public = null, $dtd_system = null\n    ) {\n        $this->name         = $name;\n        $this->xml          = $xml;\n        $this->modules      = $modules;\n        $this->tidyModules  = $tidyModules;\n        $this->aliases      = $aliases;\n        $this->dtdPublic    = $dtd_public;\n        $this->dtdSystem    = $dtd_system;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/DoctypeRegistry.php",
    "content": "<?php\n\nclass HTMLPurifier_DoctypeRegistry\n{\n\n    /**\n     * Hash of doctype names to doctype objects\n     */\n    protected $doctypes;\n\n    /**\n     * Lookup table of aliases to real doctype names\n     */\n    protected $aliases;\n\n    /**\n     * Registers a doctype to the registry\n     * @note Accepts a fully-formed doctype object, or the\n     *       parameters for constructing a doctype object\n     * @param $doctype Name of doctype or literal doctype object\n     * @param $modules Modules doctype will load\n     * @param $modules_for_modes Modules doctype will load for certain modes\n     * @param $aliases Alias names for doctype\n     * @return Editable registered doctype\n     */\n    public function register($doctype, $xml = true, $modules = array(),\n        $tidy_modules = array(), $aliases = array(), $dtd_public = null, $dtd_system = null\n    ) {\n        if (!is_array($modules)) $modules = array($modules);\n        if (!is_array($tidy_modules)) $tidy_modules = array($tidy_modules);\n        if (!is_array($aliases)) $aliases = array($aliases);\n        if (!is_object($doctype)) {\n            $doctype = new HTMLPurifier_Doctype(\n                $doctype, $xml, $modules, $tidy_modules, $aliases, $dtd_public, $dtd_system\n            );\n        }\n        $this->doctypes[$doctype->name] = $doctype;\n        $name = $doctype->name;\n        // hookup aliases\n        foreach ($doctype->aliases as $alias) {\n            if (isset($this->doctypes[$alias])) continue;\n            $this->aliases[$alias] = $name;\n        }\n        // remove old aliases\n        if (isset($this->aliases[$name])) unset($this->aliases[$name]);\n        return $doctype;\n    }\n\n    /**\n     * Retrieves reference to a doctype of a certain name\n     * @note This function resolves aliases\n     * @note When possible, use the more fully-featured make()\n     * @param $doctype Name of doctype\n     * @return Editable doctype object\n     */\n    public function get($doctype) {\n        if (isset($this->aliases[$doctype])) $doctype = $this->aliases[$doctype];\n        if (!isset($this->doctypes[$doctype])) {\n            trigger_error('Doctype ' . htmlspecialchars($doctype) . ' does not exist', E_USER_ERROR);\n            $anon = new HTMLPurifier_Doctype($doctype);\n            return $anon;\n        }\n        return $this->doctypes[$doctype];\n    }\n\n    /**\n     * Creates a doctype based on a configuration object,\n     * will perform initialization on the doctype\n     * @note Use this function to get a copy of doctype that config\n     *       can hold on to (this is necessary in order to tell\n     *       Generator whether or not the current document is XML\n     *       based or not).\n     */\n    public function make($config) {\n        return clone $this->get($this->getDoctypeFromConfig($config));\n    }\n\n    /**\n     * Retrieves the doctype from the configuration object\n     */\n    public function getDoctypeFromConfig($config) {\n        // recommended test\n        $doctype = $config->get('HTML.Doctype');\n        if (!empty($doctype)) return $doctype;\n        $doctype = $config->get('HTML.CustomDoctype');\n        if (!empty($doctype)) return $doctype;\n        // backwards-compatibility\n        if ($config->get('HTML.XHTML')) {\n            $doctype = 'XHTML 1.0';\n        } else {\n            $doctype = 'HTML 4.01';\n        }\n        if ($config->get('HTML.Strict')) {\n            $doctype .= ' Strict';\n        } else {\n            $doctype .= ' Transitional';\n        }\n        return $doctype;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ElementDef.php",
    "content": "<?php\n\n/**\n * Structure that stores an HTML element definition. Used by\n * HTMLPurifier_HTMLDefinition and HTMLPurifier_HTMLModule.\n * @note This class is inspected by HTMLPurifier_Printer_HTMLDefinition.\n *       Please update that class too.\n * @warning If you add new properties to this class, you MUST update\n *          the mergeIn() method.\n */\nclass HTMLPurifier_ElementDef\n{\n\n    /**\n     * Does the definition work by itself, or is it created solely\n     * for the purpose of merging into another definition?\n     */\n    public $standalone = true;\n\n    /**\n     * Associative array of attribute name to HTMLPurifier_AttrDef\n     * @note Before being processed by HTMLPurifier_AttrCollections\n     *       when modules are finalized during\n     *       HTMLPurifier_HTMLDefinition->setup(), this array may also\n     *       contain an array at index 0 that indicates which attribute\n     *       collections to load into the full array. It may also\n     *       contain string indentifiers in lieu of HTMLPurifier_AttrDef,\n     *       see HTMLPurifier_AttrTypes on how they are expanded during\n     *       HTMLPurifier_HTMLDefinition->setup() processing.\n     */\n    public $attr = array();\n\n    /**\n     * Indexed list of tag's HTMLPurifier_AttrTransform to be done before validation\n     */\n    public $attr_transform_pre = array();\n\n    /**\n     * Indexed list of tag's HTMLPurifier_AttrTransform to be done after validation\n     */\n    public $attr_transform_post = array();\n\n    /**\n     * HTMLPurifier_ChildDef of this tag.\n     */\n    public $child;\n\n    /**\n     * Abstract string representation of internal ChildDef rules. See\n     * HTMLPurifier_ContentSets for how this is parsed and then transformed\n     * into an HTMLPurifier_ChildDef.\n     * @warning This is a temporary variable that is not available after\n     *      being processed by HTMLDefinition\n     */\n    public $content_model;\n\n    /**\n     * Value of $child->type, used to determine which ChildDef to use,\n     * used in combination with $content_model.\n     * @warning This must be lowercase\n     * @warning This is a temporary variable that is not available after\n     *      being processed by HTMLDefinition\n     */\n    public $content_model_type;\n\n\n\n    /**\n     * Does the element have a content model (#PCDATA | Inline)*? This\n     * is important for chameleon ins and del processing in\n     * HTMLPurifier_ChildDef_Chameleon. Dynamically set: modules don't\n     * have to worry about this one.\n     */\n    public $descendants_are_inline = false;\n\n    /**\n     * List of the names of required attributes this element has. Dynamically\n     * populated by HTMLPurifier_HTMLDefinition::getElement\n     */\n    public $required_attr = array();\n\n    /**\n     * Lookup table of tags excluded from all descendants of this tag.\n     * @note SGML permits exclusions for all descendants, but this is\n     *       not possible with DTDs or XML Schemas. W3C has elected to\n     *       use complicated compositions of content_models to simulate\n     *       exclusion for children, but we go the simpler, SGML-style\n     *       route of flat-out exclusions, which correctly apply to\n     *       all descendants and not just children. Note that the XHTML\n     *       Modularization Abstract Modules are blithely unaware of such\n     *       distinctions.\n     */\n    public $excludes = array();\n\n    /**\n     * This tag is explicitly auto-closed by the following tags.\n     */\n    public $autoclose = array();\n\n    /**\n     * Whether or not this is a formatting element affected by the\n     * \"Active Formatting Elements\" algorithm.\n     */\n    public $formatting;\n\n    /**\n     * Low-level factory constructor for creating new standalone element defs\n     */\n    public static function create($content_model, $content_model_type, $attr) {\n        $def = new HTMLPurifier_ElementDef();\n        $def->content_model = $content_model;\n        $def->content_model_type = $content_model_type;\n        $def->attr = $attr;\n        return $def;\n    }\n\n    /**\n     * Merges the values of another element definition into this one.\n     * Values from the new element def take precedence if a value is\n     * not mergeable.\n     */\n    public function mergeIn($def) {\n\n        // later keys takes precedence\n        foreach($def->attr as $k => $v) {\n            if ($k === 0) {\n                // merge in the includes\n                // sorry, no way to override an include\n                foreach ($v as $v2) {\n                    $this->attr[0][] = $v2;\n                }\n                continue;\n            }\n            if ($v === false) {\n                if (isset($this->attr[$k])) unset($this->attr[$k]);\n                continue;\n            }\n            $this->attr[$k] = $v;\n        }\n        $this->_mergeAssocArray($this->attr_transform_pre, $def->attr_transform_pre);\n        $this->_mergeAssocArray($this->attr_transform_post, $def->attr_transform_post);\n        $this->_mergeAssocArray($this->excludes, $def->excludes);\n\n        if(!empty($def->content_model)) {\n            $this->content_model =\n                str_replace(\"#SUPER\", $this->content_model, $def->content_model);\n            $this->child = false;\n        }\n        if(!empty($def->content_model_type)) {\n            $this->content_model_type = $def->content_model_type;\n            $this->child = false;\n        }\n        if(!is_null($def->child)) $this->child = $def->child;\n        if(!is_null($def->formatting)) $this->formatting = $def->formatting;\n        if($def->descendants_are_inline) $this->descendants_are_inline = $def->descendants_are_inline;\n\n    }\n\n    /**\n     * Merges one array into another, removes values which equal false\n     * @param $a1 Array by reference that is merged into\n     * @param $a2 Array that merges into $a1\n     */\n    private function _mergeAssocArray(&$a1, $a2) {\n        foreach ($a2 as $k => $v) {\n            if ($v === false) {\n                if (isset($a1[$k])) unset($a1[$k]);\n                continue;\n            }\n            $a1[$k] = $v;\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Encoder.php",
    "content": "<?php\n\n/**\n * A UTF-8 specific character encoder that handles cleaning and transforming.\n * @note All functions in this class should be static.\n */\nclass HTMLPurifier_Encoder\n{\n\n    /**\n     * Constructor throws fatal error if you attempt to instantiate class\n     */\n    private function __construct() {\n        trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR);\n    }\n\n    /**\n     * Error-handler that mutes errors, alternative to shut-up operator.\n     */\n    public static function muteErrorHandler() {}\n\n    /**\n     * Cleans a UTF-8 string for well-formedness and SGML validity\n     *\n     * It will parse according to UTF-8 and return a valid UTF8 string, with\n     * non-SGML codepoints excluded.\n     *\n     * @note Just for reference, the non-SGML code points are 0 to 31 and\n     *       127 to 159, inclusive.  However, we allow code points 9, 10\n     *       and 13, which are the tab, line feed and carriage return\n     *       respectively. 128 and above the code points map to multibyte\n     *       UTF-8 representations.\n     *\n     * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and\n     *       hsivonen@iki.fi at <http://iki.fi/hsivonen/php-utf8/> under the\n     *       LGPL license.  Notes on what changed are inside, but in general,\n     *       the original code transformed UTF-8 text into an array of integer\n     *       Unicode codepoints. Understandably, transforming that back to\n     *       a string would be somewhat expensive, so the function was modded to\n     *       directly operate on the string.  However, this discourages code\n     *       reuse, and the logic enumerated here would be useful for any\n     *       function that needs to be able to understand UTF-8 characters.\n     *       As of right now, only smart lossless character encoding converters\n     *       would need that, and I'm probably not going to implement them.\n     *       Once again, PHP 6 should solve all our problems.\n     */\n    public static function cleanUTF8($str, $force_php = false) {\n\n        // UTF-8 validity is checked since PHP 4.3.5\n        // This is an optimization: if the string is already valid UTF-8, no\n        // need to do PHP stuff. 99% of the time, this will be the case.\n        // The regexp matches the XML char production, as well as well as excluding\n        // non-SGML codepoints U+007F to U+009F\n        if (preg_match('/^[\\x{9}\\x{A}\\x{D}\\x{20}-\\x{7E}\\x{A0}-\\x{D7FF}\\x{E000}-\\x{FFFD}\\x{10000}-\\x{10FFFF}]*$/Du', $str)) {\n            return $str;\n        }\n\n        $mState = 0; // cached expected number of octets after the current octet\n                     // until the beginning of the next UTF8 character sequence\n        $mUcs4  = 0; // cached Unicode character\n        $mBytes = 1; // cached expected number of octets in the current sequence\n\n        // original code involved an $out that was an array of Unicode\n        // codepoints.  Instead of having to convert back into UTF-8, we've\n        // decided to directly append valid UTF-8 characters onto a string\n        // $out once they're done.  $char accumulates raw bytes, while $mUcs4\n        // turns into the Unicode code point, so there's some redundancy.\n\n        $out = '';\n        $char = '';\n\n        $len = strlen($str);\n        for($i = 0; $i < $len; $i++) {\n            $in = ord($str{$i});\n            $char .= $str[$i]; // append byte to char\n            if (0 == $mState) {\n                // When mState is zero we expect either a US-ASCII character\n                // or a multi-octet sequence.\n                if (0 == (0x80 & ($in))) {\n                    // US-ASCII, pass straight through.\n                    if (($in <= 31 || $in == 127) &&\n                        !($in == 9 || $in == 13 || $in == 10) // save \\r\\t\\n\n                    ) {\n                        // control characters, remove\n                    } else {\n                        $out .= $char;\n                    }\n                    // reset\n                    $char = '';\n                    $mBytes = 1;\n                } elseif (0xC0 == (0xE0 & ($in))) {\n                    // First octet of 2 octet sequence\n                    $mUcs4 = ($in);\n                    $mUcs4 = ($mUcs4 & 0x1F) << 6;\n                    $mState = 1;\n                    $mBytes = 2;\n                } elseif (0xE0 == (0xF0 & ($in))) {\n                    // First octet of 3 octet sequence\n                    $mUcs4 = ($in);\n                    $mUcs4 = ($mUcs4 & 0x0F) << 12;\n                    $mState = 2;\n                    $mBytes = 3;\n                } elseif (0xF0 == (0xF8 & ($in))) {\n                    // First octet of 4 octet sequence\n                    $mUcs4 = ($in);\n                    $mUcs4 = ($mUcs4 & 0x07) << 18;\n                    $mState = 3;\n                    $mBytes = 4;\n                } elseif (0xF8 == (0xFC & ($in))) {\n                    // First octet of 5 octet sequence.\n                    //\n                    // This is illegal because the encoded codepoint must be\n                    // either:\n                    // (a) not the shortest form or\n                    // (b) outside the Unicode range of 0-0x10FFFF.\n                    // Rather than trying to resynchronize, we will carry on\n                    // until the end of the sequence and let the later error\n                    // handling code catch it.\n                    $mUcs4 = ($in);\n                    $mUcs4 = ($mUcs4 & 0x03) << 24;\n                    $mState = 4;\n                    $mBytes = 5;\n                } elseif (0xFC == (0xFE & ($in))) {\n                    // First octet of 6 octet sequence, see comments for 5\n                    // octet sequence.\n                    $mUcs4 = ($in);\n                    $mUcs4 = ($mUcs4 & 1) << 30;\n                    $mState = 5;\n                    $mBytes = 6;\n                } else {\n                    // Current octet is neither in the US-ASCII range nor a\n                    // legal first octet of a multi-octet sequence.\n                    $mState = 0;\n                    $mUcs4  = 0;\n                    $mBytes = 1;\n                    $char = '';\n                }\n            } else {\n                // When mState is non-zero, we expect a continuation of the\n                // multi-octet sequence\n                if (0x80 == (0xC0 & ($in))) {\n                    // Legal continuation.\n                    $shift = ($mState - 1) * 6;\n                    $tmp = $in;\n                    $tmp = ($tmp & 0x0000003F) << $shift;\n                    $mUcs4 |= $tmp;\n\n                    if (0 == --$mState) {\n                        // End of the multi-octet sequence. mUcs4 now contains\n                        // the final Unicode codepoint to be output\n\n                        // Check for illegal sequences and codepoints.\n\n                        // From Unicode 3.1, non-shortest form is illegal\n                        if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||\n                            ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||\n                            ((4 == $mBytes) && ($mUcs4 < 0x10000)) ||\n                            (4 < $mBytes) ||\n                            // From Unicode 3.2, surrogate characters = illegal\n                            (($mUcs4 & 0xFFFFF800) == 0xD800) ||\n                            // Codepoints outside the Unicode range are illegal\n                            ($mUcs4 > 0x10FFFF)\n                        ) {\n\n                        } elseif (0xFEFF != $mUcs4 && // omit BOM\n                            // check for valid Char unicode codepoints\n                            (\n                                0x9 == $mUcs4 ||\n                                0xA == $mUcs4 ||\n                                0xD == $mUcs4 ||\n                                (0x20 <= $mUcs4 && 0x7E >= $mUcs4) ||\n                                // 7F-9F is not strictly prohibited by XML,\n                                // but it is non-SGML, and thus we don't allow it\n                                (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) ||\n                                (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4)\n                            )\n                        ) {\n                            $out .= $char;\n                        }\n                        // initialize UTF8 cache (reset)\n                        $mState = 0;\n                        $mUcs4  = 0;\n                        $mBytes = 1;\n                        $char = '';\n                    }\n                } else {\n                    // ((0xC0 & (*in) != 0x80) && (mState != 0))\n                    // Incomplete multi-octet sequence.\n                    // used to result in complete fail, but we'll reset\n                    $mState = 0;\n                    $mUcs4  = 0;\n                    $mBytes = 1;\n                    $char ='';\n                }\n            }\n        }\n        return $out;\n    }\n\n    /**\n     * Translates a Unicode codepoint into its corresponding UTF-8 character.\n     * @note Based on Feyd's function at\n     *       <http://forums.devnetwork.net/viewtopic.php?p=191404#191404>,\n     *       which is in public domain.\n     * @note While we're going to do code point parsing anyway, a good\n     *       optimization would be to refuse to translate code points that\n     *       are non-SGML characters.  However, this could lead to duplication.\n     * @note This is very similar to the unichr function in\n     *       maintenance/generate-entity-file.php (although this is superior,\n     *       due to its sanity checks).\n     */\n\n    // +----------+----------+----------+----------+\n    // | 33222222 | 22221111 | 111111   |          |\n    // | 10987654 | 32109876 | 54321098 | 76543210 | bit\n    // +----------+----------+----------+----------+\n    // |          |          |          | 0xxxxxxx | 1 byte 0x00000000..0x0000007F\n    // |          |          | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF\n    // |          | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF\n    // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF\n    // +----------+----------+----------+----------+\n    // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF)\n    // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes\n    // +----------+----------+----------+----------+\n\n    public static function unichr($code) {\n        if($code > 1114111 or $code < 0 or\n          ($code >= 55296 and $code <= 57343) ) {\n            // bits are set outside the \"valid\" range as defined\n            // by UNICODE 4.1.0\n            return '';\n        }\n\n        $x = $y = $z = $w = 0;\n        if ($code < 128) {\n            // regular ASCII character\n            $x = $code;\n        } else {\n            // set up bits for UTF-8\n            $x = ($code & 63) | 128;\n            if ($code < 2048) {\n                $y = (($code & 2047) >> 6) | 192;\n            } else {\n                $y = (($code & 4032) >> 6) | 128;\n                if($code < 65536) {\n                    $z = (($code >> 12) & 15) | 224;\n                } else {\n                    $z = (($code >> 12) & 63) | 128;\n                    $w = (($code >> 18) & 7)  | 240;\n                }\n            }\n        }\n        // set up the actual character\n        $ret = '';\n        if($w) $ret .= chr($w);\n        if($z) $ret .= chr($z);\n        if($y) $ret .= chr($y);\n        $ret .= chr($x);\n\n        return $ret;\n    }\n\n    /**\n     * Converts a string to UTF-8 based on configuration.\n     */\n    public static function convertToUTF8($str, $config, $context) {\n        $encoding = $config->get('Core.Encoding');\n        if ($encoding === 'utf-8') return $str;\n        static $iconv = null;\n        if ($iconv === null) $iconv = function_exists('iconv');\n        set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));\n        if ($iconv && !$config->get('Test.ForceNoIconv')) {\n            $str = iconv($encoding, 'utf-8//IGNORE', $str);\n            if ($str === false) {\n                // $encoding is not a valid encoding\n                restore_error_handler();\n                trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR);\n                return '';\n            }\n            // If the string is bjorked by Shift_JIS or a similar encoding\n            // that doesn't support all of ASCII, convert the naughty\n            // characters to their true byte-wise ASCII/UTF-8 equivalents.\n            $str = strtr($str, HTMLPurifier_Encoder::testEncodingSupportsASCII($encoding));\n            restore_error_handler();\n            return $str;\n        } elseif ($encoding === 'iso-8859-1') {\n            $str = utf8_encode($str);\n            restore_error_handler();\n            return $str;\n        }\n        trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);\n    }\n\n    /**\n     * Converts a string from UTF-8 based on configuration.\n     * @note Currently, this is a lossy conversion, with unexpressable\n     *       characters being omitted.\n     */\n    public static function convertFromUTF8($str, $config, $context) {\n        $encoding = $config->get('Core.Encoding');\n        if ($encoding === 'utf-8') return $str;\n        static $iconv = null;\n        if ($iconv === null) $iconv = function_exists('iconv');\n        if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {\n            $str = HTMLPurifier_Encoder::convertToASCIIDumbLossless($str);\n        }\n        set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));\n        if ($iconv && !$config->get('Test.ForceNoIconv')) {\n            // Undo our previous fix in convertToUTF8, otherwise iconv will barf\n            $ascii_fix = HTMLPurifier_Encoder::testEncodingSupportsASCII($encoding);\n            if (!$escape && !empty($ascii_fix)) {\n                $clear_fix = array();\n                foreach ($ascii_fix as $utf8 => $native) $clear_fix[$utf8] = '';\n                $str = strtr($str, $clear_fix);\n            }\n            $str = strtr($str, array_flip($ascii_fix));\n            // Normal stuff\n            $str = iconv('utf-8', $encoding . '//IGNORE', $str);\n            restore_error_handler();\n            return $str;\n        } elseif ($encoding === 'iso-8859-1') {\n            $str = utf8_decode($str);\n            restore_error_handler();\n            return $str;\n        }\n        trigger_error('Encoding not supported', E_USER_ERROR);\n    }\n\n    /**\n     * Lossless (character-wise) conversion of HTML to ASCII\n     * @param $str UTF-8 string to be converted to ASCII\n     * @returns ASCII encoded string with non-ASCII character entity-ized\n     * @warning Adapted from MediaWiki, claiming fair use: this is a common\n     *       algorithm. If you disagree with this license fudgery,\n     *       implement it yourself.\n     * @note Uses decimal numeric entities since they are best supported.\n     * @note This is a DUMB function: it has no concept of keeping\n     *       character entities that the projected character encoding\n     *       can allow. We could possibly implement a smart version\n     *       but that would require it to also know which Unicode\n     *       codepoints the charset supported (not an easy task).\n     * @note Sort of with cleanUTF8() but it assumes that $str is\n     *       well-formed UTF-8\n     */\n    public static function convertToASCIIDumbLossless($str) {\n        $bytesleft = 0;\n        $result = '';\n        $working = 0;\n        $len = strlen($str);\n        for( $i = 0; $i < $len; $i++ ) {\n            $bytevalue = ord( $str[$i] );\n            if( $bytevalue <= 0x7F ) { //0xxx xxxx\n                $result .= chr( $bytevalue );\n                $bytesleft = 0;\n            } elseif( $bytevalue <= 0xBF ) { //10xx xxxx\n                $working = $working << 6;\n                $working += ($bytevalue & 0x3F);\n                $bytesleft--;\n                if( $bytesleft <= 0 ) {\n                    $result .= \"&#\" . $working . \";\";\n                }\n            } elseif( $bytevalue <= 0xDF ) { //110x xxxx\n                $working = $bytevalue & 0x1F;\n                $bytesleft = 1;\n            } elseif( $bytevalue <= 0xEF ) { //1110 xxxx\n                $working = $bytevalue & 0x0F;\n                $bytesleft = 2;\n            } else { //1111 0xxx\n                $working = $bytevalue & 0x07;\n                $bytesleft = 3;\n            }\n        }\n        return $result;\n    }\n\n    /**\n     * This expensive function tests whether or not a given character\n     * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will\n     * fail this test, and require special processing. Variable width\n     * encodings shouldn't ever fail.\n     *\n     * @param string $encoding Encoding name to test, as per iconv format\n     * @param bool $bypass Whether or not to bypass the precompiled arrays.\n     * @return Array of UTF-8 characters to their corresponding ASCII,\n     *      which can be used to \"undo\" any overzealous iconv action.\n     */\n    public static function testEncodingSupportsASCII($encoding, $bypass = false) {\n        static $encodings = array();\n        if (!$bypass) {\n            if (isset($encodings[$encoding])) return $encodings[$encoding];\n            $lenc = strtolower($encoding);\n            switch ($lenc) {\n                case 'shift_jis':\n                    return array(\"\\xC2\\xA5\" => '\\\\', \"\\xE2\\x80\\xBE\" => '~');\n                case 'johab':\n                    return array(\"\\xE2\\x82\\xA9\" => '\\\\');\n            }\n            if (strpos($lenc, 'iso-8859-') === 0) return array();\n        }\n        $ret = array();\n        set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));\n        if (iconv('UTF-8', $encoding, 'a') === false) return false;\n        for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars\n            $c = chr($i); // UTF-8 char\n            $r = iconv('UTF-8', \"$encoding//IGNORE\", $c); // initial conversion\n            if (\n                $r === '' ||\n                // This line is needed for iconv implementations that do not\n                // omit characters that do not exist in the target character set\n                ($r === $c && iconv($encoding, 'UTF-8//IGNORE', $r) !== $c)\n            ) {\n                // Reverse engineer: what's the UTF-8 equiv of this byte\n                // sequence? This assumes that there's no variable width\n                // encoding that doesn't support ASCII.\n                $ret[iconv($encoding, 'UTF-8//IGNORE', $c)] = $c;\n            }\n        }\n        restore_error_handler();\n        $encodings[$encoding] = $ret;\n        return $ret;\n    }\n\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/EntityLookup/entities.ser",
    "content": "a:246:{s:4:\"nbsp\";s:2:\" \";s:5:\"iexcl\";s:2:\"¡\";s:4:\"cent\";s:2:\"¢\";s:5:\"pound\";s:2:\"£\";s:6:\"curren\";s:2:\"¤\";s:3:\"yen\";s:2:\"¥\";s:6:\"brvbar\";s:2:\"¦\";s:4:\"sect\";s:2:\"§\";s:3:\"uml\";s:2:\"¨\";s:4:\"copy\";s:2:\"©\";s:4:\"ordf\";s:2:\"ª\";s:5:\"laquo\";s:2:\"«\";s:3:\"not\";s:2:\"¬\";s:3:\"shy\";s:2:\"­\";s:3:\"reg\";s:2:\"®\";s:4:\"macr\";s:2:\"¯\";s:3:\"deg\";s:2:\"°\";s:6:\"plusmn\";s:2:\"±\";s:5:\"acute\";s:2:\"´\";s:5:\"micro\";s:2:\"µ\";s:4:\"para\";s:2:\"¶\";s:6:\"middot\";s:2:\"·\";s:5:\"cedil\";s:2:\"¸\";s:4:\"ordm\";s:2:\"º\";s:5:\"raquo\";s:2:\"»\";s:6:\"iquest\";s:2:\"¿\";s:6:\"Agrave\";s:2:\"À\";s:6:\"Aacute\";s:2:\"Á\";s:5:\"Acirc\";s:2:\"Â\";s:6:\"Atilde\";s:2:\"Ã\";s:4:\"Auml\";s:2:\"Ä\";s:5:\"Aring\";s:2:\"Å\";s:5:\"AElig\";s:2:\"Æ\";s:6:\"Ccedil\";s:2:\"Ç\";s:6:\"Egrave\";s:2:\"È\";s:6:\"Eacute\";s:2:\"É\";s:5:\"Ecirc\";s:2:\"Ê\";s:4:\"Euml\";s:2:\"Ë\";s:6:\"Igrave\";s:2:\"Ì\";s:6:\"Iacute\";s:2:\"Í\";s:5:\"Icirc\";s:2:\"Î\";s:4:\"Iuml\";s:2:\"Ï\";s:3:\"ETH\";s:2:\"Ð\";s:6:\"Ntilde\";s:2:\"Ñ\";s:6:\"Ograve\";s:2:\"Ò\";s:6:\"Oacute\";s:2:\"Ó\";s:5:\"Ocirc\";s:2:\"Ô\";s:6:\"Otilde\";s:2:\"Õ\";s:4:\"Ouml\";s:2:\"Ö\";s:5:\"times\";s:2:\"×\";s:6:\"Oslash\";s:2:\"Ø\";s:6:\"Ugrave\";s:2:\"Ù\";s:6:\"Uacute\";s:2:\"Ú\";s:5:\"Ucirc\";s:2:\"Û\";s:4:\"Uuml\";s:2:\"Ü\";s:6:\"Yacute\";s:2:\"Ý\";s:5:\"THORN\";s:2:\"Þ\";s:5:\"szlig\";s:2:\"ß\";s:6:\"agrave\";s:2:\"à\";s:6:\"aacute\";s:2:\"á\";s:5:\"acirc\";s:2:\"â\";s:6:\"atilde\";s:2:\"ã\";s:4:\"auml\";s:2:\"ä\";s:5:\"aring\";s:2:\"å\";s:5:\"aelig\";s:2:\"æ\";s:6:\"ccedil\";s:2:\"ç\";s:6:\"egrave\";s:2:\"è\";s:6:\"eacute\";s:2:\"é\";s:5:\"ecirc\";s:2:\"ê\";s:4:\"euml\";s:2:\"ë\";s:6:\"igrave\";s:2:\"ì\";s:6:\"iacute\";s:2:\"í\";s:5:\"icirc\";s:2:\"î\";s:4:\"iuml\";s:2:\"ï\";s:3:\"eth\";s:2:\"ð\";s:6:\"ntilde\";s:2:\"ñ\";s:6:\"ograve\";s:2:\"ò\";s:6:\"oacute\";s:2:\"ó\";s:5:\"ocirc\";s:2:\"ô\";s:6:\"otilde\";s:2:\"õ\";s:4:\"ouml\";s:2:\"ö\";s:6:\"divide\";s:2:\"÷\";s:6:\"oslash\";s:2:\"ø\";s:6:\"ugrave\";s:2:\"ù\";s:6:\"uacute\";s:2:\"ú\";s:5:\"ucirc\";s:2:\"û\";s:4:\"uuml\";s:2:\"ü\";s:6:\"yacute\";s:2:\"ý\";s:5:\"thorn\";s:2:\"þ\";s:4:\"yuml\";s:2:\"ÿ\";s:4:\"quot\";s:1:\"\"\";s:3:\"amp\";s:1:\"&\";s:2:\"lt\";s:1:\"<\";s:2:\"gt\";s:1:\">\";s:4:\"apos\";s:1:\"'\";s:5:\"OElig\";s:2:\"Œ\";s:5:\"oelig\";s:2:\"œ\";s:6:\"Scaron\";s:2:\"Š\";s:6:\"scaron\";s:2:\"š\";s:4:\"Yuml\";s:2:\"Ÿ\";s:4:\"circ\";s:2:\"ˆ\";s:5:\"tilde\";s:2:\"˜\";s:4:\"ensp\";s:3:\" \";s:4:\"emsp\";s:3:\" \";s:6:\"thinsp\";s:3:\" \";s:4:\"zwnj\";s:3:\"‌\";s:3:\"zwj\";s:3:\"‍\";s:3:\"lrm\";s:3:\"‎\";s:3:\"rlm\";s:3:\"‏\";s:5:\"ndash\";s:3:\"–\";s:5:\"mdash\";s:3:\"—\";s:5:\"lsquo\";s:3:\"‘\";s:5:\"rsquo\";s:3:\"’\";s:5:\"sbquo\";s:3:\"‚\";s:5:\"ldquo\";s:3:\"“\";s:5:\"rdquo\";s:3:\"”\";s:5:\"bdquo\";s:3:\"„\";s:6:\"dagger\";s:3:\"†\";s:6:\"Dagger\";s:3:\"‡\";s:6:\"permil\";s:3:\"‰\";s:6:\"lsaquo\";s:3:\"‹\";s:6:\"rsaquo\";s:3:\"›\";s:4:\"euro\";s:3:\"€\";s:4:\"fnof\";s:2:\"ƒ\";s:5:\"Alpha\";s:2:\"Α\";s:4:\"Beta\";s:2:\"Β\";s:5:\"Gamma\";s:2:\"Γ\";s:5:\"Delta\";s:2:\"Δ\";s:7:\"Epsilon\";s:2:\"Ε\";s:4:\"Zeta\";s:2:\"Ζ\";s:3:\"Eta\";s:2:\"Η\";s:5:\"Theta\";s:2:\"Θ\";s:4:\"Iota\";s:2:\"Ι\";s:5:\"Kappa\";s:2:\"Κ\";s:6:\"Lambda\";s:2:\"Λ\";s:2:\"Mu\";s:2:\"Μ\";s:2:\"Nu\";s:2:\"Ν\";s:2:\"Xi\";s:2:\"Ξ\";s:7:\"Omicron\";s:2:\"Ο\";s:2:\"Pi\";s:2:\"Π\";s:3:\"Rho\";s:2:\"Ρ\";s:5:\"Sigma\";s:2:\"Σ\";s:3:\"Tau\";s:2:\"Τ\";s:7:\"Upsilon\";s:2:\"Υ\";s:3:\"Phi\";s:2:\"Φ\";s:3:\"Chi\";s:2:\"Χ\";s:3:\"Psi\";s:2:\"Ψ\";s:5:\"Omega\";s:2:\"Ω\";s:5:\"alpha\";s:2:\"α\";s:4:\"beta\";s:2:\"β\";s:5:\"gamma\";s:2:\"γ\";s:5:\"delta\";s:2:\"δ\";s:7:\"epsilon\";s:2:\"ε\";s:4:\"zeta\";s:2:\"ζ\";s:3:\"eta\";s:2:\"η\";s:5:\"theta\";s:2:\"θ\";s:4:\"iota\";s:2:\"ι\";s:5:\"kappa\";s:2:\"κ\";s:6:\"lambda\";s:2:\"λ\";s:2:\"mu\";s:2:\"μ\";s:2:\"nu\";s:2:\"ν\";s:2:\"xi\";s:2:\"ξ\";s:7:\"omicron\";s:2:\"ο\";s:2:\"pi\";s:2:\"π\";s:3:\"rho\";s:2:\"ρ\";s:6:\"sigmaf\";s:2:\"ς\";s:5:\"sigma\";s:2:\"σ\";s:3:\"tau\";s:2:\"τ\";s:7:\"upsilon\";s:2:\"υ\";s:3:\"phi\";s:2:\"φ\";s:3:\"chi\";s:2:\"χ\";s:3:\"psi\";s:2:\"ψ\";s:5:\"omega\";s:2:\"ω\";s:8:\"thetasym\";s:2:\"ϑ\";s:5:\"upsih\";s:2:\"ϒ\";s:3:\"piv\";s:2:\"ϖ\";s:4:\"bull\";s:3:\"•\";s:6:\"hellip\";s:3:\"…\";s:5:\"prime\";s:3:\"′\";s:5:\"Prime\";s:3:\"″\";s:5:\"oline\";s:3:\"‾\";s:5:\"frasl\";s:3:\"⁄\";s:6:\"weierp\";s:3:\"℘\";s:5:\"image\";s:3:\"ℑ\";s:4:\"real\";s:3:\"ℜ\";s:5:\"trade\";s:3:\"™\";s:7:\"alefsym\";s:3:\"ℵ\";s:4:\"larr\";s:3:\"←\";s:4:\"uarr\";s:3:\"↑\";s:4:\"rarr\";s:3:\"→\";s:4:\"darr\";s:3:\"↓\";s:4:\"harr\";s:3:\"↔\";s:5:\"crarr\";s:3:\"↵\";s:4:\"lArr\";s:3:\"⇐\";s:4:\"uArr\";s:3:\"⇑\";s:4:\"rArr\";s:3:\"⇒\";s:4:\"dArr\";s:3:\"⇓\";s:4:\"hArr\";s:3:\"⇔\";s:6:\"forall\";s:3:\"∀\";s:4:\"part\";s:3:\"∂\";s:5:\"exist\";s:3:\"∃\";s:5:\"empty\";s:3:\"∅\";s:5:\"nabla\";s:3:\"∇\";s:4:\"isin\";s:3:\"∈\";s:5:\"notin\";s:3:\"∉\";s:2:\"ni\";s:3:\"∋\";s:4:\"prod\";s:3:\"∏\";s:3:\"sum\";s:3:\"∑\";s:5:\"minus\";s:3:\"−\";s:6:\"lowast\";s:3:\"∗\";s:5:\"radic\";s:3:\"√\";s:4:\"prop\";s:3:\"∝\";s:5:\"infin\";s:3:\"∞\";s:3:\"ang\";s:3:\"∠\";s:3:\"and\";s:3:\"∧\";s:2:\"or\";s:3:\"∨\";s:3:\"cap\";s:3:\"∩\";s:3:\"cup\";s:3:\"∪\";s:3:\"int\";s:3:\"∫\";s:3:\"sim\";s:3:\"∼\";s:4:\"cong\";s:3:\"≅\";s:5:\"asymp\";s:3:\"≈\";s:2:\"ne\";s:3:\"≠\";s:5:\"equiv\";s:3:\"≡\";s:2:\"le\";s:3:\"≤\";s:2:\"ge\";s:3:\"≥\";s:3:\"sub\";s:3:\"⊂\";s:3:\"sup\";s:3:\"⊃\";s:4:\"nsub\";s:3:\"⊄\";s:4:\"sube\";s:3:\"⊆\";s:4:\"supe\";s:3:\"⊇\";s:5:\"oplus\";s:3:\"⊕\";s:6:\"otimes\";s:3:\"⊗\";s:4:\"perp\";s:3:\"⊥\";s:4:\"sdot\";s:3:\"⋅\";s:5:\"lceil\";s:3:\"⌈\";s:5:\"rceil\";s:3:\"⌉\";s:6:\"lfloor\";s:3:\"⌊\";s:6:\"rfloor\";s:3:\"⌋\";s:4:\"lang\";s:3:\"〈\";s:4:\"rang\";s:3:\"〉\";s:3:\"loz\";s:3:\"◊\";s:6:\"spades\";s:3:\"♠\";s:5:\"clubs\";s:3:\"♣\";s:6:\"hearts\";s:3:\"♥\";s:5:\"diams\";s:3:\"♦\";}"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/EntityLookup.php",
    "content": "<?php\n\n/**\n * Object that provides entity lookup table from entity name to character\n */\nclass HTMLPurifier_EntityLookup {\n\n    /**\n     * Assoc array of entity name to character represented.\n     */\n    public $table;\n\n    /**\n     * Sets up the entity lookup table from the serialized file contents.\n     * @note The serialized contents are versioned, but were generated\n     *       using the maintenance script generate_entity_file.php\n     * @warning This is not in constructor to help enforce the Singleton\n     */\n    public function setup($file = false) {\n        if (!$file) {\n            $file = HTMLPURIFIER_PREFIX . '/HTMLPurifier/EntityLookup/entities.ser';\n        }\n        $this->table = unserialize(file_get_contents($file));\n    }\n\n    /**\n     * Retrieves sole instance of the object.\n     * @param Optional prototype of custom lookup table to overload with.\n     */\n    public static function instance($prototype = false) {\n        // no references, since PHP doesn't copy unless modified\n        static $instance = null;\n        if ($prototype) {\n            $instance = $prototype;\n        } elseif (!$instance) {\n            $instance = new HTMLPurifier_EntityLookup();\n            $instance->setup();\n        }\n        return $instance;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/EntityParser.php",
    "content": "<?php\n\n// if want to implement error collecting here, we'll need to use some sort\n// of global data (probably trigger_error) because it's impossible to pass\n// $config or $context to the callback functions.\n\n/**\n * Handles referencing and derefencing character entities\n */\nclass HTMLPurifier_EntityParser\n{\n\n    /**\n     * Reference to entity lookup table.\n     */\n    protected $_entity_lookup;\n\n    /**\n     * Callback regex string for parsing entities.\n     */\n    protected $_substituteEntitiesRegex =\n'/&(?:[#]x([a-fA-F0-9]+)|[#]0*(\\d+)|([A-Za-z_:][A-Za-z0-9.\\-_:]*));?/';\n//     1. hex             2. dec      3. string (XML style)\n\n\n    /**\n     * Decimal to parsed string conversion table for special entities.\n     */\n    protected $_special_dec2str =\n            array(\n                    34 => '\"',\n                    38 => '&',\n                    39 => \"'\",\n                    60 => '<',\n                    62 => '>'\n            );\n\n    /**\n     * Stripped entity names to decimal conversion table for special entities.\n     */\n    protected $_special_ent2dec =\n            array(\n                    'quot' => 34,\n                    'amp'  => 38,\n                    'lt'   => 60,\n                    'gt'   => 62\n            );\n\n    /**\n     * Substitutes non-special entities with their parsed equivalents. Since\n     * running this whenever you have parsed character is t3h 5uck, we run\n     * it before everything else.\n     *\n     * @param $string String to have non-special entities parsed.\n     * @returns Parsed string.\n     */\n    public function substituteNonSpecialEntities($string) {\n        // it will try to detect missing semicolons, but don't rely on it\n        return preg_replace_callback(\n            $this->_substituteEntitiesRegex,\n            array($this, 'nonSpecialEntityCallback'),\n            $string\n            );\n    }\n\n    /**\n     * Callback function for substituteNonSpecialEntities() that does the work.\n     *\n     * @param $matches  PCRE matches array, with 0 the entire match, and\n     *                  either index 1, 2 or 3 set with a hex value, dec value,\n     *                  or string (respectively).\n     * @returns Replacement string.\n     */\n\n    protected function nonSpecialEntityCallback($matches) {\n        // replaces all but big five\n        $entity = $matches[0];\n        $is_num = (@$matches[0][1] === '#');\n        if ($is_num) {\n            $is_hex = (@$entity[2] === 'x');\n            $code = $is_hex ? hexdec($matches[1]) : (int) $matches[2];\n\n            // abort for special characters\n            if (isset($this->_special_dec2str[$code]))  return $entity;\n\n            return HTMLPurifier_Encoder::unichr($code);\n        } else {\n            if (isset($this->_special_ent2dec[$matches[3]])) return $entity;\n            if (!$this->_entity_lookup) {\n                $this->_entity_lookup = HTMLPurifier_EntityLookup::instance();\n            }\n            if (isset($this->_entity_lookup->table[$matches[3]])) {\n                return $this->_entity_lookup->table[$matches[3]];\n            } else {\n                return $entity;\n            }\n        }\n    }\n\n    /**\n     * Substitutes only special entities with their parsed equivalents.\n     *\n     * @notice We try to avoid calling this function because otherwise, it\n     * would have to be called a lot (for every parsed section).\n     *\n     * @param $string String to have non-special entities parsed.\n     * @returns Parsed string.\n     */\n    public function substituteSpecialEntities($string) {\n        return preg_replace_callback(\n            $this->_substituteEntitiesRegex,\n            array($this, 'specialEntityCallback'),\n            $string);\n    }\n\n    /**\n     * Callback function for substituteSpecialEntities() that does the work.\n     *\n     * This callback has same syntax as nonSpecialEntityCallback().\n     *\n     * @param $matches  PCRE-style matches array, with 0 the entire match, and\n     *                  either index 1, 2 or 3 set with a hex value, dec value,\n     *                  or string (respectively).\n     * @returns Replacement string.\n     */\n    protected function specialEntityCallback($matches) {\n        $entity = $matches[0];\n        $is_num = (@$matches[0][1] === '#');\n        if ($is_num) {\n            $is_hex = (@$entity[2] === 'x');\n            $int = $is_hex ? hexdec($matches[1]) : (int) $matches[2];\n            return isset($this->_special_dec2str[$int]) ?\n                $this->_special_dec2str[$int] :\n                $entity;\n        } else {\n            return isset($this->_special_ent2dec[$matches[3]]) ?\n                $this->_special_ent2dec[$matches[3]] :\n                $entity;\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ErrorCollector.php",
    "content": "<?php\n\n/**\n * Error collection class that enables HTML Purifier to report HTML\n * problems back to the user\n */\nclass HTMLPurifier_ErrorCollector\n{\n\n    /**\n     * Identifiers for the returned error array. These are purposely numeric\n     * so list() can be used.\n     */\n    const LINENO   = 0;\n    const SEVERITY = 1;\n    const MESSAGE  = 2;\n    const CHILDREN = 3;\n\n    protected $errors;\n    protected $_current;\n    protected $_stacks = array(array());\n    protected $locale;\n    protected $generator;\n    protected $context;\n\n    protected $lines = array();\n\n    public function __construct($context) {\n        $this->locale    =& $context->get('Locale');\n        $this->context   = $context;\n        $this->_current  =& $this->_stacks[0];\n        $this->errors    =& $this->_stacks[0];\n    }\n\n    /**\n     * Sends an error message to the collector for later use\n     * @param $severity int Error severity, PHP error style (don't use E_USER_)\n     * @param $msg string Error message text\n     * @param $subst1 string First substitution for $msg\n     * @param $subst2 string ...\n     */\n    public function send($severity, $msg) {\n\n        $args = array();\n        if (func_num_args() > 2) {\n            $args = func_get_args();\n            array_shift($args);\n            unset($args[0]);\n        }\n\n        $token = $this->context->get('CurrentToken', true);\n        $line  = $token ? $token->line : $this->context->get('CurrentLine', true);\n        $col   = $token ? $token->col  : $this->context->get('CurrentCol',  true);\n        $attr  = $this->context->get('CurrentAttr', true);\n\n        // perform special substitutions, also add custom parameters\n        $subst = array();\n        if (!is_null($token)) {\n            $args['CurrentToken'] = $token;\n        }\n        if (!is_null($attr)) {\n            $subst['$CurrentAttr.Name'] = $attr;\n            if (isset($token->attr[$attr])) $subst['$CurrentAttr.Value'] = $token->attr[$attr];\n        }\n\n        if (empty($args)) {\n            $msg = $this->locale->getMessage($msg);\n        } else {\n            $msg = $this->locale->formatMessage($msg, $args);\n        }\n\n        if (!empty($subst)) $msg = strtr($msg, $subst);\n\n        // (numerically indexed)\n        $error = array(\n            self::LINENO   => $line,\n            self::SEVERITY => $severity,\n            self::MESSAGE  => $msg,\n            self::CHILDREN => array()\n        );\n        $this->_current[] = $error;\n\n\n        // NEW CODE BELOW ...\n\n        $struct = null;\n        // Top-level errors are either:\n        //  TOKEN type, if $value is set appropriately, or\n        //  \"syntax\" type, if $value is null\n        $new_struct = new HTMLPurifier_ErrorStruct();\n        $new_struct->type = HTMLPurifier_ErrorStruct::TOKEN;\n        if ($token) $new_struct->value = clone $token;\n        if (is_int($line) && is_int($col)) {\n            if (isset($this->lines[$line][$col])) {\n                $struct = $this->lines[$line][$col];\n            } else {\n                $struct = $this->lines[$line][$col] = $new_struct;\n            }\n            // These ksorts may present a performance problem\n            ksort($this->lines[$line], SORT_NUMERIC);\n        } else {\n            if (isset($this->lines[-1])) {\n                $struct = $this->lines[-1];\n            } else {\n                $struct = $this->lines[-1] = $new_struct;\n            }\n        }\n        ksort($this->lines, SORT_NUMERIC);\n\n        // Now, check if we need to operate on a lower structure\n        if (!empty($attr)) {\n            $struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr);\n            if (!$struct->value) {\n                $struct->value = array($attr, 'PUT VALUE HERE');\n            }\n        }\n        if (!empty($cssprop)) {\n            $struct = $struct->getChild(HTMLPurifier_ErrorStruct::CSSPROP, $cssprop);\n            if (!$struct->value) {\n                // if we tokenize CSS this might be a little more difficult to do\n                $struct->value = array($cssprop, 'PUT VALUE HERE');\n            }\n        }\n\n        // Ok, structs are all setup, now time to register the error\n        $struct->addError($severity, $msg);\n    }\n\n    /**\n     * Retrieves raw error data for custom formatter to use\n     * @param List of arrays in format of array(line of error,\n     *        error severity, error message,\n     *        recursive sub-errors array)\n     */\n    public function getRaw() {\n        return $this->errors;\n    }\n\n    /**\n     * Default HTML formatting implementation for error messages\n     * @param $config Configuration array, vital for HTML output nature\n     * @param $errors Errors array to display; used for recursion.\n     */\n    public function getHTMLFormatted($config, $errors = null) {\n        $ret = array();\n\n        $this->generator = new HTMLPurifier_Generator($config, $this->context);\n        if ($errors === null) $errors = $this->errors;\n\n        // 'At line' message needs to be removed\n\n        // generation code for new structure goes here. It needs to be recursive.\n        foreach ($this->lines as $line => $col_array) {\n            if ($line == -1) continue;\n            foreach ($col_array as $col => $struct) {\n                $this->_renderStruct($ret, $struct, $line, $col);\n            }\n        }\n        if (isset($this->lines[-1])) {\n            $this->_renderStruct($ret, $this->lines[-1]);\n        }\n\n        if (empty($errors)) {\n            return '<p>' . $this->locale->getMessage('ErrorCollector: No errors') . '</p>';\n        } else {\n            return '<ul><li>' . implode('</li><li>', $ret) . '</li></ul>';\n        }\n\n    }\n\n    private function _renderStruct(&$ret, $struct, $line = null, $col = null) {\n        $stack = array($struct);\n        $context_stack = array(array());\n        while ($current = array_pop($stack)) {\n            $context = array_pop($context_stack);\n            foreach ($current->errors as $error) {\n                list($severity, $msg) = $error;\n                $string = '';\n                $string .= '<div>';\n                // W3C uses an icon to indicate the severity of the error.\n                $error = $this->locale->getErrorName($severity);\n                $string .= \"<span class=\\\"error e$severity\\\"><strong>$error</strong></span> \";\n                if (!is_null($line) && !is_null($col)) {\n                    $string .= \"<em class=\\\"location\\\">Line $line, Column $col: </em> \";\n                } else {\n                    $string .= '<em class=\"location\">End of Document: </em> ';\n                }\n                $string .= '<strong class=\"description\">' . $this->generator->escape($msg) . '</strong> ';\n                $string .= '</div>';\n                // Here, have a marker for the character on the column appropriate.\n                // Be sure to clip extremely long lines.\n                //$string .= '<pre>';\n                //$string .= '';\n                //$string .= '</pre>';\n                $ret[] = $string;\n            }\n            foreach ($current->children as $type => $array) {\n                $context[] = $current;\n                $stack = array_merge($stack, array_reverse($array, true));\n                for ($i = count($array); $i > 0; $i--) {\n                    $context_stack[] = $context;\n                }\n            }\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/ErrorStruct.php",
    "content": "<?php\n\n/**\n * Records errors for particular segments of an HTML document such as tokens,\n * attributes or CSS properties. They can contain error structs (which apply\n * to components of what they represent), but their main purpose is to hold\n * errors applying to whatever struct is being used.\n */\nclass HTMLPurifier_ErrorStruct\n{\n\n    /**\n     * Possible values for $children first-key. Note that top-level structures\n     * are automatically token-level.\n     */\n    const TOKEN     = 0;\n    const ATTR      = 1;\n    const CSSPROP   = 2;\n\n    /**\n     * Type of this struct.\n     */\n    public $type;\n\n    /**\n     * Value of the struct we are recording errors for. There are various\n     * values for this:\n     *  - TOKEN: Instance of HTMLPurifier_Token\n     *  - ATTR: array('attr-name', 'value')\n     *  - CSSPROP: array('prop-name', 'value')\n     */\n    public $value;\n\n    /**\n     * Errors registered for this structure.\n     */\n    public $errors = array();\n\n    /**\n     * Child ErrorStructs that are from this structure. For example, a TOKEN\n     * ErrorStruct would contain ATTR ErrorStructs. This is a multi-dimensional\n     * array in structure: [TYPE]['identifier']\n     */\n    public $children = array();\n\n    public function getChild($type, $id) {\n        if (!isset($this->children[$type][$id])) {\n            $this->children[$type][$id] = new HTMLPurifier_ErrorStruct();\n            $this->children[$type][$id]->type = $type;\n        }\n        return $this->children[$type][$id];\n    }\n\n    public function addError($severity, $message) {\n        $this->errors[] = array($severity, $message);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Exception.php",
    "content": "<?php\n\n/**\n * Global exception class for HTML Purifier; any exceptions we throw\n * are from here.\n */\nclass HTMLPurifier_Exception extends Exception\n{\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Filter/ExtractStyleBlocks.php",
    "content": "<?php\n\n/**\n * This filter extracts <style> blocks from input HTML, cleans them up\n * using CSSTidy, and then places them in $purifier->context->get('StyleBlocks')\n * so they can be used elsewhere in the document.\n *\n * @note\n *      See tests/HTMLPurifier/Filter/ExtractStyleBlocksTest.php for\n *      sample usage.\n *\n * @note\n *      This filter can also be used on stylesheets not included in the\n *      document--something purists would probably prefer. Just directly\n *      call HTMLPurifier_Filter_ExtractStyleBlocks->cleanCSS()\n */\nclass HTMLPurifier_Filter_ExtractStyleBlocks extends HTMLPurifier_Filter\n{\n\n    public $name = 'ExtractStyleBlocks';\n    private $_styleMatches = array();\n    private $_tidy;\n\n    public function __construct() {\n        $this->_tidy = new csstidy();\n    }\n\n    /**\n     * Save the contents of CSS blocks to style matches\n     * @param $matches preg_replace style $matches array\n     */\n    protected function styleCallback($matches) {\n        $this->_styleMatches[] = $matches[1];\n    }\n\n    /**\n     * Removes inline <style> tags from HTML, saves them for later use\n     * @todo Extend to indicate non-text/css style blocks\n     */\n    public function preFilter($html, $config, $context) {\n        $tidy = $config->get('Filter.ExtractStyleBlocks.TidyImpl');\n        if ($tidy !== null) $this->_tidy = $tidy;\n        $html = preg_replace_callback('#<style(?:\\s.*)?>(.+)</style>#isU', array($this, 'styleCallback'), $html);\n        $style_blocks = $this->_styleMatches;\n        $this->_styleMatches = array(); // reset\n        $context->register('StyleBlocks', $style_blocks); // $context must not be reused\n        if ($this->_tidy) {\n            foreach ($style_blocks as &$style) {\n                $style = $this->cleanCSS($style, $config, $context);\n            }\n        }\n        return $html;\n    }\n\n    /**\n     * Takes CSS (the stuff found in <style>) and cleans it.\n     * @warning Requires CSSTidy <http://csstidy.sourceforge.net/>\n     * @param $css     CSS styling to clean\n     * @param $config  Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     * @return Cleaned CSS\n     */\n    public function cleanCSS($css, $config, $context) {\n        // prepare scope\n        $scope = $config->get('Filter.ExtractStyleBlocks.Scope');\n        if ($scope !== null) {\n            $scopes = array_map('trim', explode(',', $scope));\n        } else {\n            $scopes = array();\n        }\n        // remove comments from CSS\n        $css = trim($css);\n        if (strncmp('<!--', $css, 4) === 0) {\n            $css = substr($css, 4);\n        }\n        if (strlen($css) > 3 && substr($css, -3) == '-->') {\n            $css = substr($css, 0, -3);\n        }\n        $css = trim($css);\n        $this->_tidy->parse($css);\n        $css_definition = $config->getDefinition('CSS');\n        foreach ($this->_tidy->css as $k => $decls) {\n            // $decls are all CSS declarations inside an @ selector\n            $new_decls = array();\n            foreach ($decls as $selector => $style) {\n                $selector = trim($selector);\n                if ($selector === '') continue; // should not happen\n                if ($selector[0] === '+') {\n                    if ($selector !== '' && $selector[0] === '+') continue;\n                }\n                if (!empty($scopes)) {\n                    $new_selector = array(); // because multiple ones are possible\n                    $selectors = array_map('trim', explode(',', $selector));\n                    foreach ($scopes as $s1) {\n                        foreach ($selectors as $s2) {\n                            $new_selector[] = \"$s1 $s2\";\n                        }\n                    }\n                    $selector = implode(', ', $new_selector); // now it's a string\n                }\n                foreach ($style as $name => $value) {\n                    if (!isset($css_definition->info[$name])) {\n                        unset($style[$name]);\n                        continue;\n                    }\n                    $def = $css_definition->info[$name];\n                    $ret = $def->validate($value, $config, $context);\n                    if ($ret === false) unset($style[$name]);\n                    else $style[$name] = $ret;\n                }\n                $new_decls[$selector] = $style;\n            }\n            $this->_tidy->css[$k] = $new_decls;\n        }\n        // remove stuff that shouldn't be used, could be reenabled\n        // after security risks are analyzed\n        $this->_tidy->import = array();\n        $this->_tidy->charset = null;\n        $this->_tidy->namespace = null;\n        $css = $this->_tidy->print->plain();\n        // we are going to escape any special characters <>& to ensure\n        // that no funny business occurs (i.e. </style> in a font-family prop).\n        if ($config->get('Filter.ExtractStyleBlocks.Escaping')) {\n            $css = str_replace(\n                array('<',    '>',    '&'),\n                array('\\3C ', '\\3E ', '\\26 '),\n                $css\n            );\n        }\n        return $css;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Filter/YouTube.php",
    "content": "<?php\n\nclass HTMLPurifier_Filter_YouTube extends HTMLPurifier_Filter\n{\n\n    public $name = 'YouTube';\n\n    public function preFilter($html, $config, $context) {\n        $pre_regex = '#<object[^>]+>.+?'.\n            'http://www.youtube.com/v/([A-Za-z0-9\\-_]+).+?</object>#s';\n        $pre_replace = '<span class=\"youtube-embed\">\\1</span>';\n        return preg_replace($pre_regex, $pre_replace, $html);\n    }\n\n    public function postFilter($html, $config, $context) {\n        $post_regex = '#<span class=\"youtube-embed\">([A-Za-z0-9\\-_]+)</span>#';\n        return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html);\n    }\n\n    protected function armorUrl($url) {\n        return str_replace('--', '-&#45;', $url);\n    }\n\n    protected function postFilterCallback($matches) {\n        $url = $this->armorUrl($matches[1]);\n        return '<object width=\"425\" height=\"350\" type=\"application/x-shockwave-flash\" '.\n            'data=\"http://www.youtube.com/v/'.$url.'\">'.\n            '<param name=\"movie\" value=\"http://www.youtube.com/v/'.$url.'\"></param>'.\n            '<!--[if IE]>'.\n            '<embed src=\"http://www.youtube.com/v/'.$url.'\"'.\n            'type=\"application/x-shockwave-flash\"'.\n            'wmode=\"transparent\" width=\"425\" height=\"350\" />'.\n            '<![endif]-->'.\n            '</object>';\n\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Filter.php",
    "content": "<?php\n\n/**\n * Represents a pre or post processing filter on HTML Purifier's output\n *\n * Sometimes, a little ad-hoc fixing of HTML has to be done before\n * it gets sent through HTML Purifier: you can use filters to acheive\n * this effect. For instance, YouTube videos can be preserved using\n * this manner. You could have used a decorator for this task, but\n * PHP's support for them is not terribly robust, so we're going\n * to just loop through the filters.\n *\n * Filters should be exited first in, last out. If there are three filters,\n * named 1, 2 and 3, the order of execution should go 1->preFilter,\n * 2->preFilter, 3->preFilter, purify, 3->postFilter, 2->postFilter,\n * 1->postFilter.\n *\n * @note Methods are not declared abstract as it is perfectly legitimate\n *       for an implementation not to want anything to happen on a step\n */\n\nclass HTMLPurifier_Filter\n{\n\n    /**\n     * Name of the filter for identification purposes\n     */\n    public $name;\n\n    /**\n     * Pre-processor function, handles HTML before HTML Purifier\n     */\n    public function preFilter($html, $config, $context) {\n        return $html;\n    }\n\n    /**\n     * Post-processor function, handles HTML after HTML Purifier\n     */\n    public function postFilter($html, $config, $context) {\n        return $html;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Generator.php",
    "content": "<?php\n\n/**\n * Generates HTML from tokens.\n * @todo Refactor interface so that configuration/context is determined\n *       upon instantiation, no need for messy generateFromTokens() calls\n * @todo Make some of the more internal functions protected, and have\n *       unit tests work around that\n */\nclass HTMLPurifier_Generator\n{\n\n    /**\n     * Whether or not generator should produce XML output\n     */\n    private $_xhtml = true;\n\n    /**\n     * :HACK: Whether or not generator should comment the insides of <script> tags\n     */\n    private $_scriptFix = false;\n\n    /**\n     * Cache of HTMLDefinition during HTML output to determine whether or\n     * not attributes should be minimized.\n     */\n    private $_def;\n\n    /**\n     * Cache of %Output.SortAttr\n     */\n    private $_sortAttr;\n\n    /**\n     * Configuration for the generator\n     */\n    protected $config;\n\n    /**\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     */\n    public function __construct($config, $context) {\n        $this->config = $config;\n        $this->_scriptFix = $config->get('Output.CommentScriptContents');\n        $this->_sortAttr = $config->get('Output.SortAttr');\n        $this->_def = $config->getHTMLDefinition();\n        $this->_xhtml = $this->_def->doctype->xml;\n    }\n\n    /**\n     * Generates HTML from an array of tokens.\n     * @param $tokens Array of HTMLPurifier_Token\n     * @param $config HTMLPurifier_Config object\n     * @return Generated HTML\n     */\n    public function generateFromTokens($tokens) {\n        if (!$tokens) return '';\n\n        // Basic algorithm\n        $html = '';\n        for ($i = 0, $size = count($tokens); $i < $size; $i++) {\n            if ($this->_scriptFix && $tokens[$i]->name === 'script'\n                && $i + 2 < $size && $tokens[$i+2] instanceof HTMLPurifier_Token_End) {\n                // script special case\n                // the contents of the script block must be ONE token\n                // for this to work.\n                $html .= $this->generateFromToken($tokens[$i++]);\n                $html .= $this->generateScriptFromToken($tokens[$i++]);\n            }\n            $html .= $this->generateFromToken($tokens[$i]);\n        }\n\n        // Tidy cleanup\n        if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat')) {\n            $tidy = new Tidy;\n            $tidy->parseString($html, array(\n               'indent'=> true,\n               'output-xhtml' => $this->_xhtml,\n               'show-body-only' => true,\n               'indent-spaces' => 2,\n               'wrap' => 68,\n            ), 'utf8');\n            $tidy->cleanRepair();\n            $html = (string) $tidy; // explicit cast necessary\n        }\n\n        // Normalize newlines to system defined value\n        $nl = $this->config->get('Output.Newline');\n        if ($nl === null) $nl = PHP_EOL;\n        if ($nl !== \"\\n\") $html = str_replace(\"\\n\", $nl, $html);\n        return $html;\n    }\n\n    /**\n     * Generates HTML from a single token.\n     * @param $token HTMLPurifier_Token object.\n     * @return Generated HTML\n     */\n    public function generateFromToken($token) {\n        if (!$token instanceof HTMLPurifier_Token) {\n            trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING);\n            return '';\n\n        } elseif ($token instanceof HTMLPurifier_Token_Start) {\n            $attr = $this->generateAttributes($token->attr, $token->name);\n            return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';\n\n        } elseif ($token instanceof HTMLPurifier_Token_End) {\n            return '</' . $token->name . '>';\n\n        } elseif ($token instanceof HTMLPurifier_Token_Empty) {\n            $attr = $this->generateAttributes($token->attr, $token->name);\n             return '<' . $token->name . ($attr ? ' ' : '') . $attr .\n                ( $this->_xhtml ? ' /': '' ) // <br /> v. <br>\n                . '>';\n\n        } elseif ($token instanceof HTMLPurifier_Token_Text) {\n            return $this->escape($token->data, ENT_NOQUOTES);\n\n        } elseif ($token instanceof HTMLPurifier_Token_Comment) {\n            return '<!--' . $token->data . '-->';\n        } else {\n            return '';\n\n        }\n    }\n\n    /**\n     * Special case processor for the contents of script tags\n     * @warning This runs into problems if there's already a literal\n     *          --> somewhere inside the script contents.\n     */\n    public function generateScriptFromToken($token) {\n        if (!$token instanceof HTMLPurifier_Token_Text) return $this->generateFromToken($token);\n        // Thanks <http://lachy.id.au/log/2005/05/script-comments>\n        $data = preg_replace('#//\\s*$#', '', $token->data);\n        return '<!--//--><![CDATA[//><!--' . \"\\n\" . trim($data) . \"\\n\" . '//--><!]]>';\n    }\n\n    /**\n     * Generates attribute declarations from attribute array.\n     * @note This does not include the leading or trailing space.\n     * @param $assoc_array_of_attributes Attribute array\n     * @param $element Name of element attributes are for, used to check\n     *        attribute minimization.\n     * @return Generate HTML fragment for insertion.\n     */\n    public function generateAttributes($assoc_array_of_attributes, $element = false) {\n        $html = '';\n        if ($this->_sortAttr) ksort($assoc_array_of_attributes);\n        foreach ($assoc_array_of_attributes as $key => $value) {\n            if (!$this->_xhtml) {\n                // Remove namespaced attributes\n                if (strpos($key, ':') !== false) continue;\n                // Check if we should minimize the attribute: val=\"val\" -> val\n                if ($element && !empty($this->_def->info[$element]->attr[$key]->minimized)) {\n                    $html .= $key . ' ';\n                    continue;\n                }\n            }\n            $html .= $key.'=\"'.$this->escape($value).'\" ';\n        }\n        return rtrim($html);\n    }\n\n    /**\n     * Escapes raw text data.\n     * @todo This really ought to be protected, but until we have a facility\n     *       for properly generating HTML here w/o using tokens, it stays\n     *       public.\n     * @param $string String data to escape for HTML.\n     * @param $quote Quoting style, like htmlspecialchars. ENT_NOQUOTES is\n     *               permissible for non-attribute output.\n     * @return String escaped data.\n     */\n    public function escape($string, $quote = ENT_COMPAT) {\n        return htmlspecialchars($string, $quote, 'UTF-8');\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLDefinition.php",
    "content": "<?php\n\n/**\n * Definition of the purified HTML that describes allowed children,\n * attributes, and many other things.\n *\n * Conventions:\n *\n * All member variables that are prefixed with info\n * (including the main $info array) are used by HTML Purifier internals\n * and should not be directly edited when customizing the HTMLDefinition.\n * They can usually be set via configuration directives or custom\n * modules.\n *\n * On the other hand, member variables without the info prefix are used\n * internally by the HTMLDefinition and MUST NOT be used by other HTML\n * Purifier internals. Many of them, however, are public, and may be\n * edited by userspace code to tweak the behavior of HTMLDefinition.\n *\n * @note This class is inspected by Printer_HTMLDefinition; please\n *       update that class if things here change.\n *\n * @warning Directives that change this object's structure must be in\n *          the HTML or Attr namespace!\n */\nclass HTMLPurifier_HTMLDefinition extends HTMLPurifier_Definition\n{\n\n    // FULLY-PUBLIC VARIABLES ---------------------------------------------\n\n    /**\n     * Associative array of element names to HTMLPurifier_ElementDef\n     */\n    public $info = array();\n\n    /**\n     * Associative array of global attribute name to attribute definition.\n     */\n    public $info_global_attr = array();\n\n    /**\n     * String name of parent element HTML will be going into.\n     */\n    public $info_parent = 'div';\n\n    /**\n     * Definition for parent element, allows parent element to be a\n     * tag that's not allowed inside the HTML fragment.\n     */\n    public $info_parent_def;\n\n    /**\n     * String name of element used to wrap inline elements in block context\n     * @note This is rarely used except for BLOCKQUOTEs in strict mode\n     */\n    public $info_block_wrapper = 'p';\n\n    /**\n     * Associative array of deprecated tag name to HTMLPurifier_TagTransform\n     */\n    public $info_tag_transform = array();\n\n    /**\n     * Indexed list of HTMLPurifier_AttrTransform to be performed before validation.\n     */\n    public $info_attr_transform_pre = array();\n\n    /**\n     * Indexed list of HTMLPurifier_AttrTransform to be performed after validation.\n     */\n    public $info_attr_transform_post = array();\n\n    /**\n     * Nested lookup array of content set name (Block, Inline) to\n     * element name to whether or not it belongs in that content set.\n     */\n    public $info_content_sets = array();\n\n    /**\n     * Indexed list of HTMLPurifier_Injector to be used.\n     */\n    public $info_injector = array();\n\n    /**\n     * Doctype object\n     */\n    public $doctype;\n\n\n\n    // RAW CUSTOMIZATION STUFF --------------------------------------------\n\n    /**\n     * Adds a custom attribute to a pre-existing element\n     * @note This is strictly convenience, and does not have a corresponding\n     *       method in HTMLPurifier_HTMLModule\n     * @param $element_name String element name to add attribute to\n     * @param $attr_name String name of attribute\n     * @param $def Attribute definition, can be string or object, see\n     *             HTMLPurifier_AttrTypes for details\n     */\n    public function addAttribute($element_name, $attr_name, $def) {\n        $module = $this->getAnonymousModule();\n        if (!isset($module->info[$element_name])) {\n            $element = $module->addBlankElement($element_name);\n        } else {\n            $element = $module->info[$element_name];\n        }\n        $element->attr[$attr_name] = $def;\n    }\n\n    /**\n     * Adds a custom element to your HTML definition\n     * @note See HTMLPurifier_HTMLModule::addElement for detailed\n     *       parameter and return value descriptions.\n     */\n    public function addElement($element_name, $type, $contents, $attr_collections, $attributes = array()) {\n        $module = $this->getAnonymousModule();\n        // assume that if the user is calling this, the element\n        // is safe. This may not be a good idea\n        $element = $module->addElement($element_name, $type, $contents, $attr_collections, $attributes);\n        return $element;\n    }\n\n    /**\n     * Adds a blank element to your HTML definition, for overriding\n     * existing behavior\n     * @note See HTMLPurifier_HTMLModule::addBlankElement for detailed\n     *       parameter and return value descriptions.\n     */\n    public function addBlankElement($element_name) {\n        $module  = $this->getAnonymousModule();\n        $element = $module->addBlankElement($element_name);\n        return $element;\n    }\n\n    /**\n     * Retrieves a reference to the anonymous module, so you can\n     * bust out advanced features without having to make your own\n     * module.\n     */\n    public function getAnonymousModule() {\n        if (!$this->_anonModule) {\n            $this->_anonModule = new HTMLPurifier_HTMLModule();\n            $this->_anonModule->name = 'Anonymous';\n        }\n        return $this->_anonModule;\n    }\n\n    private $_anonModule;\n\n\n    // PUBLIC BUT INTERNAL VARIABLES --------------------------------------\n\n    public $type = 'HTML';\n    public $manager; /**< Instance of HTMLPurifier_HTMLModuleManager */\n\n    /**\n     * Performs low-cost, preliminary initialization.\n     */\n    public function __construct() {\n        $this->manager = new HTMLPurifier_HTMLModuleManager();\n    }\n\n    protected function doSetup($config) {\n        $this->processModules($config);\n        $this->setupConfigStuff($config);\n        unset($this->manager);\n\n        // cleanup some of the element definitions\n        foreach ($this->info as $k => $v) {\n            unset($this->info[$k]->content_model);\n            unset($this->info[$k]->content_model_type);\n        }\n    }\n\n    /**\n     * Extract out the information from the manager\n     */\n    protected function processModules($config) {\n\n        if ($this->_anonModule) {\n            // for user specific changes\n            // this is late-loaded so we don't have to deal with PHP4\n            // reference wonky-ness\n            $this->manager->addModule($this->_anonModule);\n            unset($this->_anonModule);\n        }\n\n        $this->manager->setup($config);\n        $this->doctype = $this->manager->doctype;\n\n        foreach ($this->manager->modules as $module) {\n            foreach($module->info_tag_transform as $k => $v) {\n                if ($v === false) unset($this->info_tag_transform[$k]);\n                else $this->info_tag_transform[$k] = $v;\n            }\n            foreach($module->info_attr_transform_pre as $k => $v) {\n                if ($v === false) unset($this->info_attr_transform_pre[$k]);\n                else $this->info_attr_transform_pre[$k] = $v;\n            }\n            foreach($module->info_attr_transform_post as $k => $v) {\n                if ($v === false) unset($this->info_attr_transform_post[$k]);\n                else $this->info_attr_transform_post[$k] = $v;\n            }\n            foreach ($module->info_injector as $k => $v) {\n                if ($v === false) unset($this->info_injector[$k]);\n                else $this->info_injector[$k] = $v;\n            }\n        }\n\n        $this->info = $this->manager->getElements();\n        $this->info_content_sets = $this->manager->contentSets->lookup;\n\n    }\n\n    /**\n     * Sets up stuff based on config. We need a better way of doing this.\n     */\n    protected function setupConfigStuff($config) {\n\n        $block_wrapper = $config->get('HTML.BlockWrapper');\n        if (isset($this->info_content_sets['Block'][$block_wrapper])) {\n            $this->info_block_wrapper = $block_wrapper;\n        } else {\n            trigger_error('Cannot use non-block element as block wrapper',\n                E_USER_ERROR);\n        }\n\n        $parent = $config->get('HTML.Parent');\n        $def = $this->manager->getElement($parent, true);\n        if ($def) {\n            $this->info_parent = $parent;\n            $this->info_parent_def = $def;\n        } else {\n            trigger_error('Cannot use unrecognized element as parent',\n                E_USER_ERROR);\n            $this->info_parent_def = $this->manager->getElement($this->info_parent, true);\n        }\n\n        // support template text\n        $support = \"(for information on implementing this, see the \".\n                   \"support forums) \";\n\n        // setup allowed elements -----------------------------------------\n\n        $allowed_elements = $config->get('HTML.AllowedElements');\n        $allowed_attributes = $config->get('HTML.AllowedAttributes'); // retrieve early\n\n        if (!is_array($allowed_elements) && !is_array($allowed_attributes)) {\n            $allowed = $config->get('HTML.Allowed');\n            if (is_string($allowed)) {\n                list($allowed_elements, $allowed_attributes) = $this->parseTinyMCEAllowedList($allowed);\n            }\n        }\n\n        if (is_array($allowed_elements)) {\n            foreach ($this->info as $name => $d) {\n                if(!isset($allowed_elements[$name])) unset($this->info[$name]);\n                unset($allowed_elements[$name]);\n            }\n            // emit errors\n            foreach ($allowed_elements as $element => $d) {\n                $element = htmlspecialchars($element); // PHP doesn't escape errors, be careful!\n                trigger_error(\"Element '$element' is not supported $support\", E_USER_WARNING);\n            }\n        }\n\n        // setup allowed attributes ---------------------------------------\n\n        $allowed_attributes_mutable = $allowed_attributes; // by copy!\n        if (is_array($allowed_attributes)) {\n\n            // This actually doesn't do anything, since we went away from\n            // global attributes. It's possible that userland code uses\n            // it, but HTMLModuleManager doesn't!\n            foreach ($this->info_global_attr as $attr => $x) {\n                $keys = array($attr, \"*@$attr\", \"*.$attr\");\n                $delete = true;\n                foreach ($keys as $key) {\n                    if ($delete && isset($allowed_attributes[$key])) {\n                        $delete = false;\n                    }\n                    if (isset($allowed_attributes_mutable[$key])) {\n                        unset($allowed_attributes_mutable[$key]);\n                    }\n                }\n                if ($delete) unset($this->info_global_attr[$attr]);\n            }\n\n            foreach ($this->info as $tag => $info) {\n                foreach ($info->attr as $attr => $x) {\n                    $keys = array(\"$tag@$attr\", $attr, \"*@$attr\", \"$tag.$attr\", \"*.$attr\");\n                    $delete = true;\n                    foreach ($keys as $key) {\n                        if ($delete && isset($allowed_attributes[$key])) {\n                            $delete = false;\n                        }\n                        if (isset($allowed_attributes_mutable[$key])) {\n                            unset($allowed_attributes_mutable[$key]);\n                        }\n                    }\n                    if ($delete) unset($this->info[$tag]->attr[$attr]);\n                }\n            }\n            // emit errors\n            foreach ($allowed_attributes_mutable as $elattr => $d) {\n                $bits = preg_split('/[.@]/', $elattr, 2);\n                $c = count($bits);\n                switch ($c) {\n                    case 2:\n                        if ($bits[0] !== '*') {\n                            $element = htmlspecialchars($bits[0]);\n                            $attribute = htmlspecialchars($bits[1]);\n                            if (!isset($this->info[$element])) {\n                                trigger_error(\"Cannot allow attribute '$attribute' if element '$element' is not allowed/supported $support\");\n                            } else {\n                                trigger_error(\"Attribute '$attribute' in element '$element' not supported $support\",\n                                    E_USER_WARNING);\n                            }\n                            break;\n                        }\n                        // otherwise fall through\n                    case 1:\n                        $attribute = htmlspecialchars($bits[0]);\n                        trigger_error(\"Global attribute '$attribute' is not \".\n                            \"supported in any elements $support\",\n                            E_USER_WARNING);\n                        break;\n                }\n            }\n\n        }\n\n        // setup forbidden elements ---------------------------------------\n\n        $forbidden_elements   = $config->get('HTML.ForbiddenElements');\n        $forbidden_attributes = $config->get('HTML.ForbiddenAttributes');\n\n        foreach ($this->info as $tag => $info) {\n            if (isset($forbidden_elements[$tag])) {\n                unset($this->info[$tag]);\n                continue;\n            }\n            foreach ($info->attr as $attr => $x) {\n                if (\n                    isset($forbidden_attributes[\"$tag@$attr\"]) ||\n                    isset($forbidden_attributes[\"*@$attr\"]) ||\n                    isset($forbidden_attributes[$attr])\n                ) {\n                    unset($this->info[$tag]->attr[$attr]);\n                    continue;\n                } // this segment might get removed eventually\n                elseif (isset($forbidden_attributes[\"$tag.$attr\"])) {\n                    // $tag.$attr are not user supplied, so no worries!\n                    trigger_error(\"Error with $tag.$attr: tag.attr syntax not supported for HTML.ForbiddenAttributes; use tag@attr instead\", E_USER_WARNING);\n                }\n            }\n        }\n        foreach ($forbidden_attributes as $key => $v) {\n            if (strlen($key) < 2) continue;\n            if ($key[0] != '*') continue;\n            if ($key[1] == '.') {\n                trigger_error(\"Error with $key: *.attr syntax not supported for HTML.ForbiddenAttributes; use attr instead\", E_USER_WARNING);\n            }\n        }\n\n        // setup injectors -----------------------------------------------------\n        foreach ($this->info_injector as $i => $injector) {\n            if ($injector->checkNeeded($config) !== false) {\n                // remove injector that does not have it's required\n                // elements/attributes present, and is thus not needed.\n                unset($this->info_injector[$i]);\n            }\n        }\n    }\n\n    /**\n     * Parses a TinyMCE-flavored Allowed Elements and Attributes list into\n     * separate lists for processing. Format is element[attr1|attr2],element2...\n     * @warning Although it's largely drawn from TinyMCE's implementation,\n     *      it is different, and you'll probably have to modify your lists\n     * @param $list String list to parse\n     * @param array($allowed_elements, $allowed_attributes)\n     * @todo Give this its own class, probably static interface\n     */\n    public function parseTinyMCEAllowedList($list) {\n\n        $list = str_replace(array(' ', \"\\t\"), '', $list);\n\n        $elements = array();\n        $attributes = array();\n\n        $chunks = preg_split('/(,|[\\n\\r]+)/', $list);\n        foreach ($chunks as $chunk) {\n            if (empty($chunk)) continue;\n            // remove TinyMCE element control characters\n            if (!strpos($chunk, '[')) {\n                $element = $chunk;\n                $attr = false;\n            } else {\n                list($element, $attr) = explode('[', $chunk);\n            }\n            if ($element !== '*') $elements[$element] = true;\n            if (!$attr) continue;\n            $attr = substr($attr, 0, strlen($attr) - 1); // remove trailing ]\n            $attr = explode('|', $attr);\n            foreach ($attr as $key) {\n                $attributes[\"$element.$key\"] = true;\n            }\n        }\n\n        return array($elements, $attributes);\n\n    }\n\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Bdo.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Bi-directional Text Module, defines elements that\n * declare directionality of content. Text Extension Module.\n */\nclass HTMLPurifier_HTMLModule_Bdo extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Bdo';\n    public $attr_collections = array(\n        'I18N' => array('dir' => false)\n    );\n\n    public function setup($config) {\n        $bdo = $this->addElement(\n            'bdo', 'Inline', 'Inline', array('Core', 'Lang'),\n            array(\n                'dir' => 'Enum#ltr,rtl', // required\n                // The Abstract Module specification has the attribute\n                // inclusions wrong for bdo: bdo allows Lang\n            )\n        );\n        $bdo->attr_transform_post['required-dir'] = new HTMLPurifier_AttrTransform_BdoDir();\n\n        $this->attr_collections['I18N']['dir'] = 'Enum#ltr,rtl';\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/CommonAttributes.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModule_CommonAttributes extends HTMLPurifier_HTMLModule\n{\n    public $name = 'CommonAttributes';\n\n    public $attr_collections = array(\n        'Core' => array(\n            0 => array('Style'),\n            // 'xml:space' => false,\n            'class' => 'Class',\n            'id' => 'ID',\n            'title' => 'CDATA',\n        ),\n        'Lang' => array(),\n        'I18N' => array(\n            0 => array('Lang'), // proprietary, for xml:lang/lang\n        ),\n        'Common' => array(\n            0 => array('Core', 'I18N')\n        )\n    );\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Edit.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Edit Module, defines editing-related elements. Text Extension\n * Module.\n */\nclass HTMLPurifier_HTMLModule_Edit extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Edit';\n\n    public function setup($config) {\n        $contents = 'Chameleon: #PCDATA | Inline ! #PCDATA | Flow';\n        $attr = array(\n            'cite' => 'URI',\n            // 'datetime' => 'Datetime', // not implemented\n        );\n        $this->addElement('del', 'Inline', $contents, 'Common', $attr);\n        $this->addElement('ins', 'Inline', $contents, 'Common', $attr);\n    }\n\n    // HTML 4.01 specifies that ins/del must not contain block\n    // elements when used in an inline context, chameleon is\n    // a complicated workaround to acheive this effect\n\n    // Inline context ! Block context (exclamation mark is\n    // separator, see getChildDef for parsing)\n\n    public $defines_child_def = true;\n    public function getChildDef($def) {\n        if ($def->content_model_type != 'chameleon') return false;\n        $value = explode('!', $def->content_model);\n        return new HTMLPurifier_ChildDef_Chameleon($value[0], $value[1]);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Forms.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Forms module, defines all form-related elements found in HTML 4.\n */\nclass HTMLPurifier_HTMLModule_Forms extends HTMLPurifier_HTMLModule\n{\n    public $name = 'Forms';\n    public $safe = false;\n\n    public $content_sets = array(\n        'Block' => 'Form',\n        'Inline' => 'Formctrl',\n    );\n\n    public function setup($config) {\n        $form = $this->addElement('form', 'Form',\n          'Required: Heading | List | Block | fieldset', 'Common', array(\n            'accept' => 'ContentTypes',\n            'accept-charset' => 'Charsets',\n            'action*' => 'URI',\n            'method' => 'Enum#get,post',\n            // really ContentType, but these two are the only ones used today\n            'enctype' => 'Enum#application/x-www-form-urlencoded,multipart/form-data',\n        ));\n        $form->excludes = array('form' => true);\n\n        $input = $this->addElement('input', 'Formctrl', 'Empty', 'Common', array(\n            'accept' => 'ContentTypes',\n            'accesskey' => 'Character',\n            'alt' => 'Text',\n            'checked' => 'Bool#checked',\n            'disabled' => 'Bool#disabled',\n            'maxlength' => 'Number',\n            'name' => 'CDATA',\n            'readonly' => 'Bool#readonly',\n            'size' => 'Number',\n            'src' => 'URI#embeds',\n            'tabindex' => 'Number',\n            'type' => 'Enum#text,password,checkbox,button,radio,submit,reset,file,hidden,image',\n            'value' => 'CDATA',\n        ));\n        $input->attr_transform_post[] = new HTMLPurifier_AttrTransform_Input();\n\n        $this->addElement('select', 'Formctrl', 'Required: optgroup | option', 'Common', array(\n            'disabled' => 'Bool#disabled',\n            'multiple' => 'Bool#multiple',\n            'name' => 'CDATA',\n            'size' => 'Number',\n            'tabindex' => 'Number',\n        ));\n\n        $this->addElement('option', false, 'Optional: #PCDATA', 'Common', array(\n            'disabled' => 'Bool#disabled',\n            'label' => 'Text',\n            'selected' => 'Bool#selected',\n            'value' => 'CDATA',\n        ));\n        // It's illegal for there to be more than one selected, but not\n        // be multiple. Also, no selected means undefined behavior. This might\n        // be difficult to implement; perhaps an injector, or a context variable.\n\n        $textarea = $this->addElement('textarea', 'Formctrl', 'Optional: #PCDATA', 'Common', array(\n            'accesskey' => 'Character',\n            'cols*' => 'Number',\n            'disabled' => 'Bool#disabled',\n            'name' => 'CDATA',\n            'readonly' => 'Bool#readonly',\n            'rows*' => 'Number',\n            'tabindex' => 'Number',\n        ));\n        $textarea->attr_transform_pre[] = new HTMLPurifier_AttrTransform_Textarea();\n\n        $button = $this->addElement('button', 'Formctrl', 'Optional: #PCDATA | Heading | List | Block | Inline', 'Common', array(\n            'accesskey' => 'Character',\n            'disabled' => 'Bool#disabled',\n            'name' => 'CDATA',\n            'tabindex' => 'Number',\n            'type' => 'Enum#button,submit,reset',\n            'value' => 'CDATA',\n        ));\n\n        // For exclusions, ideally we'd specify content sets, not literal elements\n        $button->excludes = $this->makeLookup(\n            'form', 'fieldset', // Form\n            'input', 'select', 'textarea', 'label', 'button', // Formctrl\n            'a' // as per HTML 4.01 spec, this is omitted by modularization\n        );\n\n        // Extra exclusion: img usemap=\"\" is not permitted within this element.\n        // We'll omit this for now, since we don't have any good way of\n        // indicating it yet.\n\n        // This is HIGHLY user-unfriendly; we need a custom child-def for this\n        $this->addElement('fieldset', 'Form', 'Custom: (#WS?,legend,(Flow|#PCDATA)*)', 'Common');\n\n        $label = $this->addElement('label', 'Formctrl', 'Optional: #PCDATA | Inline', 'Common', array(\n            'accesskey' => 'Character',\n            // 'for' => 'IDREF', // IDREF not implemented, cannot allow\n        ));\n        $label->excludes = array('label' => true);\n\n        $this->addElement('legend', false, 'Optional: #PCDATA | Inline', 'Common', array(\n            'accesskey' => 'Character',\n        ));\n\n        $this->addElement('optgroup', false, 'Required: option', 'Common', array(\n            'disabled' => 'Bool#disabled',\n            'label*' => 'Text',\n        ));\n\n        // Don't forget an injector for <isindex>. This one's a little complex\n        // because it maps to multiple elements.\n\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Hypertext.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Hypertext Module, defines hypertext links. Core Module.\n */\nclass HTMLPurifier_HTMLModule_Hypertext extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Hypertext';\n\n    public function setup($config) {\n        $a = $this->addElement(\n            'a', 'Inline', 'Inline', 'Common',\n            array(\n                // 'accesskey' => 'Character',\n                // 'charset' => 'Charset',\n                'href' => 'URI',\n                // 'hreflang' => 'LanguageCode',\n                'rel' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rel'),\n                'rev' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rev'),\n                // 'tabindex' => 'Number',\n                // 'type' => 'ContentType',\n            )\n        );\n        $a->formatting = true;\n        $a->excludes = array('a' => true);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Image.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Image Module provides basic image embedding.\n * @note There is specialized code for removing empty images in\n *       HTMLPurifier_Strategy_RemoveForeignElements\n */\nclass HTMLPurifier_HTMLModule_Image extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Image';\n\n    public function setup($config) {\n        $max = $config->get('HTML.MaxImgLength');\n        $img = $this->addElement(\n            'img', 'Inline', 'Empty', 'Common',\n            array(\n                'alt*' => 'Text',\n                // According to the spec, it's Length, but percents can\n                // be abused, so we allow only Pixels.\n                'height' => 'Pixels#' . $max,\n                'width'  => 'Pixels#' . $max,\n                'longdesc' => 'URI',\n                'src*' => new HTMLPurifier_AttrDef_URI(true), // embedded\n            )\n        );\n        if ($max === null || $config->get('HTML.Trusted')) {\n            $img->attr['height'] =\n            $img->attr['width'] = 'Length';\n        }\n\n        // kind of strange, but splitting things up would be inefficient\n        $img->attr_transform_pre[] =\n        $img->attr_transform_post[] =\n            new HTMLPurifier_AttrTransform_ImgRequired();\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Legacy.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Legacy module defines elements that were previously\n * deprecated.\n *\n * @note Not all legacy elements have been implemented yet, which\n *       is a bit of a reverse problem as compared to browsers! In\n *       addition, this legacy module may implement a bit more than\n *       mandated by XHTML 1.1.\n *\n * This module can be used in combination with TransformToStrict in order\n * to transform as many deprecated elements as possible, but retain\n * questionably deprecated elements that do not have good alternatives\n * as well as transform elements that don't have an implementation.\n * See docs/ref-strictness.txt for more details.\n */\n\nclass HTMLPurifier_HTMLModule_Legacy extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Legacy';\n\n    public function setup($config) {\n\n        $this->addElement('basefont', 'Inline', 'Empty', false, array(\n            'color' => 'Color',\n            'face' => 'Text', // extremely broad, we should\n            'size' => 'Text', // tighten it\n            'id' => 'ID'\n        ));\n        $this->addElement('center', 'Block', 'Flow', 'Common');\n        $this->addElement('dir', 'Block', 'Required: li', 'Common', array(\n            'compact' => 'Bool#compact'\n        ));\n        $this->addElement('font', 'Inline', 'Inline', array('Core', 'I18N'), array(\n            'color' => 'Color',\n            'face' => 'Text', // extremely broad, we should\n            'size' => 'Text', // tighten it\n        ));\n        $this->addElement('menu', 'Block', 'Required: li', 'Common', array(\n            'compact' => 'Bool#compact'\n        ));\n\n        $s = $this->addElement('s', 'Inline', 'Inline', 'Common');\n        $s->formatting = true;\n\n        $strike = $this->addElement('strike', 'Inline', 'Inline', 'Common');\n        $strike->formatting = true;\n\n        $u = $this->addElement('u', 'Inline', 'Inline', 'Common');\n        $u->formatting = true;\n\n        // setup modifications to old elements\n\n        $align = 'Enum#left,right,center,justify';\n\n        $address = $this->addBlankElement('address');\n        $address->content_model = 'Inline | #PCDATA | p';\n        $address->content_model_type = 'optional';\n        $address->child = false;\n\n        $blockquote = $this->addBlankElement('blockquote');\n        $blockquote->content_model = 'Flow | #PCDATA';\n        $blockquote->content_model_type = 'optional';\n        $blockquote->child = false;\n\n        $br = $this->addBlankElement('br');\n        $br->attr['clear'] = 'Enum#left,all,right,none';\n\n        $caption = $this->addBlankElement('caption');\n        $caption->attr['align'] = 'Enum#top,bottom,left,right';\n\n        $div = $this->addBlankElement('div');\n        $div->attr['align'] = $align;\n\n        $dl = $this->addBlankElement('dl');\n        $dl->attr['compact'] = 'Bool#compact';\n\n        for ($i = 1; $i <= 6; $i++) {\n            $h = $this->addBlankElement(\"h$i\");\n            $h->attr['align'] = $align;\n        }\n\n        $hr = $this->addBlankElement('hr');\n        $hr->attr['align'] = $align;\n        $hr->attr['noshade'] = 'Bool#noshade';\n        $hr->attr['size'] = 'Pixels';\n        $hr->attr['width'] = 'Length';\n\n        $img = $this->addBlankElement('img');\n        $img->attr['align'] = 'Enum#top,middle,bottom,left,right';\n        $img->attr['border'] = 'Pixels';\n        $img->attr['hspace'] = 'Pixels';\n        $img->attr['vspace'] = 'Pixels';\n\n        // figure out this integer business\n\n        $li = $this->addBlankElement('li');\n        $li->attr['value'] = new HTMLPurifier_AttrDef_Integer();\n        $li->attr['type']  = 'Enum#s:1,i,I,a,A,disc,square,circle';\n\n        $ol = $this->addBlankElement('ol');\n        $ol->attr['compact'] = 'Bool#compact';\n        $ol->attr['start'] = new HTMLPurifier_AttrDef_Integer();\n        $ol->attr['type'] = 'Enum#s:1,i,I,a,A';\n\n        $p = $this->addBlankElement('p');\n        $p->attr['align'] = $align;\n\n        $pre = $this->addBlankElement('pre');\n        $pre->attr['width'] = 'Number';\n\n        // script omitted\n\n        $table = $this->addBlankElement('table');\n        $table->attr['align'] = 'Enum#left,center,right';\n        $table->attr['bgcolor'] = 'Color';\n\n        $tr = $this->addBlankElement('tr');\n        $tr->attr['bgcolor'] = 'Color';\n\n        $th = $this->addBlankElement('th');\n        $th->attr['bgcolor'] = 'Color';\n        $th->attr['height'] = 'Length';\n        $th->attr['nowrap'] = 'Bool#nowrap';\n        $th->attr['width'] = 'Length';\n\n        $td = $this->addBlankElement('td');\n        $td->attr['bgcolor'] = 'Color';\n        $td->attr['height'] = 'Length';\n        $td->attr['nowrap'] = 'Bool#nowrap';\n        $td->attr['width'] = 'Length';\n\n        $ul = $this->addBlankElement('ul');\n        $ul->attr['compact'] = 'Bool#compact';\n        $ul->attr['type'] = 'Enum#square,disc,circle';\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/List.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 List Module, defines list-oriented elements. Core Module.\n */\nclass HTMLPurifier_HTMLModule_List extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'List';\n\n    // According to the abstract schema, the List content set is a fully formed\n    // one or more expr, but it invariably occurs in an optional declaration\n    // so we're not going to do that subtlety. It might cause trouble\n    // if a user defines \"List\" and expects that multiple lists are\n    // allowed to be specified, but then again, that's not very intuitive.\n    // Furthermore, the actual XML Schema may disagree. Regardless,\n    // we don't have support for such nested expressions without using\n    // the incredibly inefficient and draconic Custom ChildDef.\n\n    public $content_sets = array('Flow' => 'List');\n\n    public function setup($config) {\n        $this->addElement('ol', 'List', 'Required: li', 'Common');\n        $this->addElement('ul', 'List', 'Required: li', 'Common');\n        $this->addElement('dl', 'List', 'Required: dt | dd', 'Common');\n\n        $this->addElement('li', false, 'Flow', 'Common');\n\n        $this->addElement('dd', false, 'Flow', 'Common');\n        $this->addElement('dt', false, 'Inline', 'Common');\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Name.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModule_Name extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Name';\n\n    public function setup($config) {\n        $elements = array('a', 'applet', 'form', 'frame', 'iframe', 'img', 'map');\n        foreach ($elements as $name) {\n            $element = $this->addBlankElement($name);\n            $element->attr['name'] = 'CDATA';\n            if (!$config->get('HTML.Attr.Name.UseCDATA')) {\n                $element->attr_transform_post['NameSync'] = new HTMLPurifier_AttrTransform_NameSync();\n            }\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModule_NonXMLCommonAttributes extends HTMLPurifier_HTMLModule\n{\n    public $name = 'NonXMLCommonAttributes';\n\n    public $attr_collections = array(\n        'Lang' => array(\n            'lang' => 'LanguageCode',\n        )\n    );\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Object.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Object Module, defines elements for generic object inclusion\n * @warning Users will commonly use <embed> to cater to legacy browsers: this\n *      module does not allow this sort of behavior\n */\nclass HTMLPurifier_HTMLModule_Object extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Object';\n    public $safe = false;\n\n    public function setup($config) {\n\n        $this->addElement('object', 'Inline', 'Optional: #PCDATA | Flow | param', 'Common',\n            array(\n                'archive' => 'URI',\n                'classid' => 'URI',\n                'codebase' => 'URI',\n                'codetype' => 'Text',\n                'data' => 'URI',\n                'declare' => 'Bool#declare',\n                'height' => 'Length',\n                'name' => 'CDATA',\n                'standby' => 'Text',\n                'tabindex' => 'Number',\n                'type' => 'ContentType',\n                'width' => 'Length'\n            )\n        );\n\n        $this->addElement('param', false, 'Empty', false,\n            array(\n                'id' => 'ID',\n                'name*' => 'Text',\n                'type' => 'Text',\n                'value' => 'Text',\n                'valuetype' => 'Enum#data,ref,object'\n           )\n        );\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Presentation.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Presentation Module, defines simple presentation-related\n * markup. Text Extension Module.\n * @note The official XML Schema and DTD specs further divide this into\n *       two modules:\n *          - Block Presentation (hr)\n *          - Inline Presentation (b, big, i, small, sub, sup, tt)\n *       We have chosen not to heed this distinction, as content_sets\n *       provides satisfactory disambiguation.\n */\nclass HTMLPurifier_HTMLModule_Presentation extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Presentation';\n\n    public function setup($config) {\n        $this->addElement('hr',     'Block',  'Empty',  'Common');\n        $this->addElement('sub',    'Inline', 'Inline', 'Common');\n        $this->addElement('sup',    'Inline', 'Inline', 'Common');\n        $b = $this->addElement('b',      'Inline', 'Inline', 'Common');\n        $b->formatting = true;\n        $big = $this->addElement('big',    'Inline', 'Inline', 'Common');\n        $big->formatting = true;\n        $i = $this->addElement('i',      'Inline', 'Inline', 'Common');\n        $i->formatting = true;\n        $small = $this->addElement('small',  'Inline', 'Inline', 'Common');\n        $small->formatting = true;\n        $tt = $this->addElement('tt',     'Inline', 'Inline', 'Common');\n        $tt->formatting = true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Proprietary.php",
    "content": "<?php\n\n/**\n * Module defines proprietary tags and attributes in HTML.\n * @warning If this module is enabled, standards-compliance is off!\n */\nclass HTMLPurifier_HTMLModule_Proprietary extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Proprietary';\n\n    public function setup($config) {\n\n        $this->addElement('marquee', 'Inline', 'Flow', 'Common',\n            array(\n                'direction' => 'Enum#left,right,up,down',\n                'behavior' => 'Enum#alternate',\n                'width' => 'Length',\n                'height' => 'Length',\n                'scrolldelay' => 'Number',\n                'scrollamount' => 'Number',\n                'loop' => 'Number',\n                'bgcolor' => 'Color',\n                'hspace' => 'Pixels',\n                'vspace' => 'Pixels',\n            )\n        );\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Ruby.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Ruby Annotation Module, defines elements that indicate\n * short runs of text alongside base text for annotation or pronounciation.\n */\nclass HTMLPurifier_HTMLModule_Ruby extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Ruby';\n\n    public function setup($config) {\n        $this->addElement('ruby', 'Inline',\n            'Custom: ((rb, (rt | (rp, rt, rp))) | (rbc, rtc, rtc?))',\n            'Common');\n        $this->addElement('rbc', false, 'Required: rb', 'Common');\n        $this->addElement('rtc', false, 'Required: rt', 'Common');\n        $rb = $this->addElement('rb', false, 'Inline', 'Common');\n        $rb->excludes = array('ruby' => true);\n        $rt = $this->addElement('rt', false, 'Inline', 'Common', array('rbspan' => 'Number'));\n        $rt->excludes = array('ruby' => true);\n        $this->addElement('rp', false, 'Optional: #PCDATA', 'Common');\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/SafeEmbed.php",
    "content": "<?php\n\n/**\n * A \"safe\" embed module. See SafeObject. This is a proprietary element.\n */\nclass HTMLPurifier_HTMLModule_SafeEmbed extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'SafeEmbed';\n\n    public function setup($config) {\n\n        $max = $config->get('HTML.MaxImgLength');\n        $embed = $this->addElement(\n            'embed', 'Inline', 'Empty', 'Common',\n            array(\n                'src*' => 'URI#embedded',\n                'type' => 'Enum#application/x-shockwave-flash',\n                'width' => 'Pixels#' . $max,\n                'height' => 'Pixels#' . $max,\n                'allowscriptaccess' => 'Enum#never',\n                'allownetworking' => 'Enum#internal',\n                'wmode' => 'Enum#window',\n                'name' => 'ID',\n            )\n        );\n        $embed->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeEmbed();\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/SafeObject.php",
    "content": "<?php\n\n/**\n * A \"safe\" object module. In theory, objects permitted by this module will\n * be safe, and untrusted users can be allowed to embed arbitrary flash objects\n * (maybe other types too, but only Flash is supported as of right now).\n * Highly experimental.\n */\nclass HTMLPurifier_HTMLModule_SafeObject extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'SafeObject';\n\n    public function setup($config) {\n\n        // These definitions are not intrinsically safe: the attribute transforms\n        // are a vital part of ensuring safety.\n\n        $max = $config->get('HTML.MaxImgLength');\n        $object = $this->addElement(\n            'object',\n            'Inline',\n            'Optional: param | Flow | #PCDATA',\n            'Common',\n            array(\n                // While technically not required by the spec, we're forcing\n                // it to this value.\n                'type'   => 'Enum#application/x-shockwave-flash',\n                'width'  => 'Pixels#' . $max,\n                'height' => 'Pixels#' . $max,\n                'data'   => 'URI#embedded'\n            )\n        );\n        $object->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeObject();\n\n        $param = $this->addElement('param', false, 'Empty', false,\n            array(\n                'id' => 'ID',\n                'name*' => 'Text',\n                'value' => 'Text'\n            )\n        );\n        $param->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeParam();\n        $this->info_injector[] = 'SafeObject';\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Scripting.php",
    "content": "<?php\n\n/*\n\nWARNING: THIS MODULE IS EXTREMELY DANGEROUS AS IT ENABLES INLINE SCRIPTING\nINSIDE HTML PURIFIER DOCUMENTS. USE ONLY WITH TRUSTED USER INPUT!!!\n\n*/\n\n/**\n * XHTML 1.1 Scripting module, defines elements that are used to contain\n * information pertaining to executable scripts or the lack of support\n * for executable scripts.\n * @note This module does not contain inline scripting elements\n */\nclass HTMLPurifier_HTMLModule_Scripting extends HTMLPurifier_HTMLModule\n{\n    public $name = 'Scripting';\n    public $elements = array('script', 'noscript');\n    public $content_sets = array('Block' => 'script | noscript', 'Inline' => 'script | noscript');\n    public $safe = false;\n\n    public function setup($config) {\n        // TODO: create custom child-definition for noscript that\n        // auto-wraps stray #PCDATA in a similar manner to\n        // blockquote's custom definition (we would use it but\n        // blockquote's contents are optional while noscript's contents\n        // are required)\n\n        // TODO: convert this to new syntax, main problem is getting\n        // both content sets working\n\n        // In theory, this could be safe, but I don't see any reason to\n        // allow it.\n        $this->info['noscript'] = new HTMLPurifier_ElementDef();\n        $this->info['noscript']->attr = array( 0 => array('Common') );\n        $this->info['noscript']->content_model = 'Heading | List | Block';\n        $this->info['noscript']->content_model_type = 'required';\n\n        $this->info['script'] = new HTMLPurifier_ElementDef();\n        $this->info['script']->attr = array(\n            'defer' => new HTMLPurifier_AttrDef_Enum(array('defer')),\n            'src'   => new HTMLPurifier_AttrDef_URI(true),\n            'type'  => new HTMLPurifier_AttrDef_Enum(array('text/javascript'))\n        );\n        $this->info['script']->content_model = '#PCDATA';\n        $this->info['script']->content_model_type = 'optional';\n        $this->info['script']->attr_transform_pre['type'] =\n        $this->info['script']->attr_transform_post['type'] =\n            new HTMLPurifier_AttrTransform_ScriptRequired();\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/StyleAttribute.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Edit Module, defines editing-related elements. Text Extension\n * Module.\n */\nclass HTMLPurifier_HTMLModule_StyleAttribute extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'StyleAttribute';\n    public $attr_collections = array(\n        // The inclusion routine differs from the Abstract Modules but\n        // is in line with the DTD and XML Schemas.\n        'Style' => array('style' => false), // see constructor\n        'Core' => array(0 => array('Style'))\n    );\n\n    public function setup($config) {\n        $this->attr_collections['Style']['style'] = new HTMLPurifier_AttrDef_CSS();\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Tables.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Tables Module, fully defines accessible table elements.\n */\nclass HTMLPurifier_HTMLModule_Tables extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Tables';\n\n    public function setup($config) {\n\n        $this->addElement('caption', false, 'Inline', 'Common');\n\n        $this->addElement('table', 'Block',\n            new HTMLPurifier_ChildDef_Table(),  'Common',\n            array(\n                'border' => 'Pixels',\n                'cellpadding' => 'Length',\n                'cellspacing' => 'Length',\n                'frame' => 'Enum#void,above,below,hsides,lhs,rhs,vsides,box,border',\n                'rules' => 'Enum#none,groups,rows,cols,all',\n                'summary' => 'Text',\n                'width' => 'Length'\n            )\n        );\n\n        // common attributes\n        $cell_align = array(\n            'align' => 'Enum#left,center,right,justify,char',\n            'charoff' => 'Length',\n            'valign' => 'Enum#top,middle,bottom,baseline',\n        );\n\n        $cell_t = array_merge(\n            array(\n                'abbr'    => 'Text',\n                'colspan' => 'Number',\n                'rowspan' => 'Number',\n            ),\n            $cell_align\n        );\n        $this->addElement('td', false, 'Flow', 'Common', $cell_t);\n        $this->addElement('th', false, 'Flow', 'Common', $cell_t);\n\n        $this->addElement('tr', false, 'Required: td | th', 'Common', $cell_align);\n\n        $cell_col = array_merge(\n            array(\n                'span'  => 'Number',\n                'width' => 'MultiLength',\n            ),\n            $cell_align\n        );\n        $this->addElement('col',      false, 'Empty',         'Common', $cell_col);\n        $this->addElement('colgroup', false, 'Optional: col', 'Common', $cell_col);\n\n        $this->addElement('tbody', false, 'Required: tr', 'Common', $cell_align);\n        $this->addElement('thead', false, 'Required: tr', 'Common', $cell_align);\n        $this->addElement('tfoot', false, 'Required: tr', 'Common', $cell_align);\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Target.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Target Module, defines target attribute in link elements.\n */\nclass HTMLPurifier_HTMLModule_Target extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Target';\n\n    public function setup($config) {\n        $elements = array('a');\n        foreach ($elements as $name) {\n            $e = $this->addBlankElement($name);\n            $e->attr = array(\n                'target' => new HTMLPurifier_AttrDef_HTML_FrameTarget()\n            );\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Text.php",
    "content": "<?php\n\n/**\n * XHTML 1.1 Text Module, defines basic text containers. Core Module.\n * @note In the normative XML Schema specification, this module\n *       is further abstracted into the following modules:\n *          - Block Phrasal (address, blockquote, pre, h1, h2, h3, h4, h5, h6)\n *          - Block Structural (div, p)\n *          - Inline Phrasal (abbr, acronym, cite, code, dfn, em, kbd, q, samp, strong, var)\n *          - Inline Structural (br, span)\n *       This module, functionally, does not distinguish between these\n *       sub-modules, but the code is internally structured to reflect\n *       these distinctions.\n */\nclass HTMLPurifier_HTMLModule_Text extends HTMLPurifier_HTMLModule\n{\n\n    public $name = 'Text';\n    public $content_sets = array(\n        'Flow' => 'Heading | Block | Inline'\n    );\n\n    public function setup($config) {\n\n        // Inline Phrasal -------------------------------------------------\n        $this->addElement('abbr',    'Inline', 'Inline', 'Common');\n        $this->addElement('acronym', 'Inline', 'Inline', 'Common');\n        $this->addElement('cite',    'Inline', 'Inline', 'Common');\n        $this->addElement('dfn',     'Inline', 'Inline', 'Common');\n        $this->addElement('kbd',     'Inline', 'Inline', 'Common');\n        $this->addElement('q',       'Inline', 'Inline', 'Common', array('cite' => 'URI'));\n        $this->addElement('samp',    'Inline', 'Inline', 'Common');\n        $this->addElement('var',     'Inline', 'Inline', 'Common');\n\n        $em = $this->addElement('em',      'Inline', 'Inline', 'Common');\n        $em->formatting = true;\n\n        $strong = $this->addElement('strong',  'Inline', 'Inline', 'Common');\n        $strong->formatting = true;\n\n        $code = $this->addElement('code',    'Inline', 'Inline', 'Common');\n        $code->formatting = true;\n\n        // Inline Structural ----------------------------------------------\n        $this->addElement('span', 'Inline', 'Inline', 'Common');\n        $this->addElement('br',   'Inline', 'Empty',  'Core');\n\n        // Block Phrasal --------------------------------------------------\n        $this->addElement('address',     'Block', 'Inline', 'Common');\n        $this->addElement('blockquote',  'Block', 'Optional: Heading | Block | List', 'Common', array('cite' => 'URI') );\n        $pre = $this->addElement('pre', 'Block', 'Inline', 'Common');\n        $pre->excludes = $this->makeLookup(\n            'img', 'big', 'small', 'object', 'applet', 'font', 'basefont' );\n        $this->addElement('h1', 'Heading', 'Inline', 'Common');\n        $this->addElement('h2', 'Heading', 'Inline', 'Common');\n        $this->addElement('h3', 'Heading', 'Inline', 'Common');\n        $this->addElement('h4', 'Heading', 'Inline', 'Common');\n        $this->addElement('h5', 'Heading', 'Inline', 'Common');\n        $this->addElement('h6', 'Heading', 'Inline', 'Common');\n\n        // Block Structural -----------------------------------------------\n        $p = $this->addElement('p', 'Block', 'Inline', 'Common');\n        $p->autoclose = array_flip(array(\"address\", \"blockquote\", \"center\", \"dir\", \"div\", \"dl\", \"fieldset\", \"ol\", \"p\", \"ul\"));\n\n        $this->addElement('div', 'Block', 'Flow', 'Common');\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Tidy/Name.php",
    "content": "<?php\n\n/**\n * Name is deprecated, but allowed in strict doctypes, so onl\n */\nclass HTMLPurifier_HTMLModule_Tidy_Name extends HTMLPurifier_HTMLModule_Tidy\n{\n    public $name = 'Tidy_Name';\n    public $defaultLevel = 'heavy';\n    public function makeFixes() {\n\n        $r = array();\n\n        // @name for img, a -----------------------------------------------\n        // Technically, it's allowed even on strict, so we allow authors to use\n        // it. However, it's deprecated in future versions of XHTML.\n        $r['img@name'] =\n        $r['a@name'] = new HTMLPurifier_AttrTransform_Name();\n\n        return $r;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Tidy/Proprietary.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModule_Tidy_Proprietary extends HTMLPurifier_HTMLModule_Tidy\n{\n\n    public $name = 'Tidy_Proprietary';\n    public $defaultLevel = 'light';\n\n    public function makeFixes() {\n        $r = array();\n        $r['table@background'] = new HTMLPurifier_AttrTransform_Background();\n        $r['td@background']    = new HTMLPurifier_AttrTransform_Background();\n        $r['th@background']    = new HTMLPurifier_AttrTransform_Background();\n        $r['tr@background']    = new HTMLPurifier_AttrTransform_Background();\n        $r['thead@background'] = new HTMLPurifier_AttrTransform_Background();\n        $r['tfoot@background'] = new HTMLPurifier_AttrTransform_Background();\n        $r['tbody@background'] = new HTMLPurifier_AttrTransform_Background();\n        return $r;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Tidy/Strict.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModule_Tidy_Strict extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4\n{\n    public $name = 'Tidy_Strict';\n    public $defaultLevel = 'light';\n\n    public function makeFixes() {\n        $r = parent::makeFixes();\n        $r['blockquote#content_model_type'] = 'strictblockquote';\n        return $r;\n    }\n\n    public $defines_child_def = true;\n    public function getChildDef($def) {\n        if ($def->content_model_type != 'strictblockquote') return parent::getChildDef($def);\n        return new HTMLPurifier_ChildDef_StrictBlockquote($def->content_model);\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Tidy/Transitional.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModule_Tidy_Transitional extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4\n{\n    public $name = 'Tidy_Transitional';\n    public $defaultLevel = 'heavy';\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Tidy/XHTML.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModule_Tidy_XHTML extends HTMLPurifier_HTMLModule_Tidy\n{\n\n    public $name = 'Tidy_XHTML';\n    public $defaultLevel = 'medium';\n\n    public function makeFixes() {\n        $r = array();\n        $r['@lang'] = new HTMLPurifier_AttrTransform_Lang();\n        return $r;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4 extends HTMLPurifier_HTMLModule_Tidy\n{\n\n    public function makeFixes() {\n\n        $r = array();\n\n        // == deprecated tag transforms ===================================\n\n        $r['font']   = new HTMLPurifier_TagTransform_Font();\n        $r['menu']   = new HTMLPurifier_TagTransform_Simple('ul');\n        $r['dir']    = new HTMLPurifier_TagTransform_Simple('ul');\n        $r['center'] = new HTMLPurifier_TagTransform_Simple('div',  'text-align:center;');\n        $r['u']      = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:underline;');\n        $r['s']      = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');\n        $r['strike'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');\n\n        // == deprecated attribute transforms =============================\n\n        $r['caption@align'] =\n            new HTMLPurifier_AttrTransform_EnumToCSS('align', array(\n                // we're following IE's behavior, not Firefox's, due\n                // to the fact that no one supports caption-side:right,\n                // W3C included (with CSS 2.1). This is a slightly\n                // unreasonable attribute!\n                'left'   => 'text-align:left;',\n                'right'  => 'text-align:right;',\n                'top'    => 'caption-side:top;',\n                'bottom' => 'caption-side:bottom;' // not supported by IE\n            ));\n\n        // @align for img -------------------------------------------------\n        $r['img@align'] =\n            new HTMLPurifier_AttrTransform_EnumToCSS('align', array(\n                'left'   => 'float:left;',\n                'right'  => 'float:right;',\n                'top'    => 'vertical-align:top;',\n                'middle' => 'vertical-align:middle;',\n                'bottom' => 'vertical-align:baseline;',\n            ));\n\n        // @align for table -----------------------------------------------\n        $r['table@align'] =\n            new HTMLPurifier_AttrTransform_EnumToCSS('align', array(\n                'left'   => 'float:left;',\n                'center' => 'margin-left:auto;margin-right:auto;',\n                'right'  => 'float:right;'\n            ));\n\n        // @align for hr -----------------------------------------------\n        $r['hr@align'] =\n            new HTMLPurifier_AttrTransform_EnumToCSS('align', array(\n                // we use both text-align and margin because these work\n                // for different browsers (IE and Firefox, respectively)\n                // and the melange makes for a pretty cross-compatible\n                // solution\n                'left'   => 'margin-left:0;margin-right:auto;text-align:left;',\n                'center' => 'margin-left:auto;margin-right:auto;text-align:center;',\n                'right'  => 'margin-left:auto;margin-right:0;text-align:right;'\n            ));\n\n        // @align for h1, h2, h3, h4, h5, h6, p, div ----------------------\n        // {{{\n            $align_lookup = array();\n            $align_values = array('left', 'right', 'center', 'justify');\n            foreach ($align_values as $v) $align_lookup[$v] = \"text-align:$v;\";\n        // }}}\n        $r['h1@align'] =\n        $r['h2@align'] =\n        $r['h3@align'] =\n        $r['h4@align'] =\n        $r['h5@align'] =\n        $r['h6@align'] =\n        $r['p@align']  =\n        $r['div@align'] =\n            new HTMLPurifier_AttrTransform_EnumToCSS('align', $align_lookup);\n\n        // @bgcolor for table, tr, td, th ---------------------------------\n        $r['table@bgcolor'] =\n        $r['td@bgcolor'] =\n        $r['th@bgcolor'] =\n            new HTMLPurifier_AttrTransform_BgColor();\n\n        // @border for img ------------------------------------------------\n        $r['img@border'] = new HTMLPurifier_AttrTransform_Border();\n\n        // @clear for br --------------------------------------------------\n        $r['br@clear'] =\n            new HTMLPurifier_AttrTransform_EnumToCSS('clear', array(\n                'left'  => 'clear:left;',\n                'right' => 'clear:right;',\n                'all'   => 'clear:both;',\n                'none'  => 'clear:none;',\n            ));\n\n        // @height for td, th ---------------------------------------------\n        $r['td@height'] =\n        $r['th@height'] =\n            new HTMLPurifier_AttrTransform_Length('height');\n\n        // @hspace for img ------------------------------------------------\n        $r['img@hspace'] = new HTMLPurifier_AttrTransform_ImgSpace('hspace');\n\n        // @noshade for hr ------------------------------------------------\n        // this transformation is not precise but often good enough.\n        // different browsers use different styles to designate noshade\n        $r['hr@noshade'] =\n            new HTMLPurifier_AttrTransform_BoolToCSS(\n                'noshade',\n                'color:#808080;background-color:#808080;border:0;'\n            );\n\n        // @nowrap for td, th ---------------------------------------------\n        $r['td@nowrap'] =\n        $r['th@nowrap'] =\n            new HTMLPurifier_AttrTransform_BoolToCSS(\n                'nowrap',\n                'white-space:nowrap;'\n            );\n\n        // @size for hr  --------------------------------------------------\n        $r['hr@size'] = new HTMLPurifier_AttrTransform_Length('size', 'height');\n\n        // @type for li, ol, ul -------------------------------------------\n        // {{{\n            $ul_types = array(\n                'disc'   => 'list-style-type:disc;',\n                'square' => 'list-style-type:square;',\n                'circle' => 'list-style-type:circle;'\n            );\n            $ol_types = array(\n                '1'   => 'list-style-type:decimal;',\n                'i'   => 'list-style-type:lower-roman;',\n                'I'   => 'list-style-type:upper-roman;',\n                'a'   => 'list-style-type:lower-alpha;',\n                'A'   => 'list-style-type:upper-alpha;'\n            );\n            $li_types = $ul_types + $ol_types;\n        // }}}\n\n        $r['ul@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ul_types);\n        $r['ol@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ol_types, true);\n        $r['li@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $li_types, true);\n\n        // @vspace for img ------------------------------------------------\n        $r['img@vspace'] = new HTMLPurifier_AttrTransform_ImgSpace('vspace');\n\n        // @width for hr, td, th ------------------------------------------\n        $r['td@width'] =\n        $r['th@width'] =\n        $r['hr@width'] = new HTMLPurifier_AttrTransform_Length('width');\n\n        return $r;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/Tidy.php",
    "content": "<?php\n\n/**\n * Abstract class for a set of proprietary modules that clean up (tidy)\n * poorly written HTML.\n * @todo Figure out how to protect some of these methods/properties\n */\nclass HTMLPurifier_HTMLModule_Tidy extends HTMLPurifier_HTMLModule\n{\n\n    /**\n     * List of supported levels. Index zero is a special case \"no fixes\"\n     * level.\n     */\n    public $levels = array(0 => 'none', 'light', 'medium', 'heavy');\n\n    /**\n     * Default level to place all fixes in. Disabled by default\n     */\n    public $defaultLevel = null;\n\n    /**\n     * Lists of fixes used by getFixesForLevel(). Format is:\n     *      HTMLModule_Tidy->fixesForLevel[$level] = array('fix-1', 'fix-2');\n     */\n    public $fixesForLevel = array(\n        'light'  => array(),\n        'medium' => array(),\n        'heavy'  => array()\n    );\n\n    /**\n     * Lazy load constructs the module by determining the necessary\n     * fixes to create and then delegating to the populate() function.\n     * @todo Wildcard matching and error reporting when an added or\n     *       subtracted fix has no effect.\n     */\n    public function setup($config) {\n\n        // create fixes, initialize fixesForLevel\n        $fixes = $this->makeFixes();\n        $this->makeFixesForLevel($fixes);\n\n        // figure out which fixes to use\n        $level = $config->get('HTML.TidyLevel');\n        $fixes_lookup = $this->getFixesForLevel($level);\n\n        // get custom fix declarations: these need namespace processing\n        $add_fixes    = $config->get('HTML.TidyAdd');\n        $remove_fixes = $config->get('HTML.TidyRemove');\n\n        foreach ($fixes as $name => $fix) {\n            // needs to be refactored a little to implement globbing\n            if (\n                isset($remove_fixes[$name]) ||\n                (!isset($add_fixes[$name]) && !isset($fixes_lookup[$name]))\n            ) {\n                unset($fixes[$name]);\n            }\n        }\n\n        // populate this module with necessary fixes\n        $this->populate($fixes);\n\n    }\n\n    /**\n     * Retrieves all fixes per a level, returning fixes for that specific\n     * level as well as all levels below it.\n     * @param $level String level identifier, see $levels for valid values\n     * @return Lookup up table of fixes\n     */\n    public function getFixesForLevel($level) {\n        if ($level == $this->levels[0]) {\n            return array();\n        }\n        $activated_levels = array();\n        for ($i = 1, $c = count($this->levels); $i < $c; $i++) {\n            $activated_levels[] = $this->levels[$i];\n            if ($this->levels[$i] == $level) break;\n        }\n        if ($i == $c) {\n            trigger_error(\n                'Tidy level ' . htmlspecialchars($level) . ' not recognized',\n                E_USER_WARNING\n            );\n            return array();\n        }\n        $ret = array();\n        foreach ($activated_levels as $level) {\n            foreach ($this->fixesForLevel[$level] as $fix) {\n                $ret[$fix] = true;\n            }\n        }\n        return $ret;\n    }\n\n    /**\n     * Dynamically populates the $fixesForLevel member variable using\n     * the fixes array. It may be custom overloaded, used in conjunction\n     * with $defaultLevel, or not used at all.\n     */\n    public function makeFixesForLevel($fixes) {\n        if (!isset($this->defaultLevel)) return;\n        if (!isset($this->fixesForLevel[$this->defaultLevel])) {\n            trigger_error(\n                'Default level ' . $this->defaultLevel . ' does not exist',\n                E_USER_ERROR\n            );\n            return;\n        }\n        $this->fixesForLevel[$this->defaultLevel] = array_keys($fixes);\n    }\n\n    /**\n     * Populates the module with transforms and other special-case code\n     * based on a list of fixes passed to it\n     * @param $lookup Lookup table of fixes to activate\n     */\n    public function populate($fixes) {\n        foreach ($fixes as $name => $fix) {\n            // determine what the fix is for\n            list($type, $params) = $this->getFixType($name);\n            switch ($type) {\n                case 'attr_transform_pre':\n                case 'attr_transform_post':\n                    $attr = $params['attr'];\n                    if (isset($params['element'])) {\n                        $element = $params['element'];\n                        if (empty($this->info[$element])) {\n                            $e = $this->addBlankElement($element);\n                        } else {\n                            $e = $this->info[$element];\n                        }\n                    } else {\n                        $type = \"info_$type\";\n                        $e = $this;\n                    }\n                    // PHP does some weird parsing when I do\n                    // $e->$type[$attr], so I have to assign a ref.\n                    $f =& $e->$type;\n                    $f[$attr] = $fix;\n                    break;\n                case 'tag_transform':\n                    $this->info_tag_transform[$params['element']] = $fix;\n                    break;\n                case 'child':\n                case 'content_model_type':\n                    $element = $params['element'];\n                    if (empty($this->info[$element])) {\n                        $e = $this->addBlankElement($element);\n                    } else {\n                        $e = $this->info[$element];\n                    }\n                    $e->$type = $fix;\n                    break;\n                default:\n                    trigger_error(\"Fix type $type not supported\", E_USER_ERROR);\n                    break;\n            }\n        }\n    }\n\n    /**\n     * Parses a fix name and determines what kind of fix it is, as well\n     * as other information defined by the fix\n     * @param $name String name of fix\n     * @return array(string $fix_type, array $fix_parameters)\n     * @note $fix_parameters is type dependant, see populate() for usage\n     *       of these parameters\n     */\n    public function getFixType($name) {\n        // parse it\n        $property = $attr = null;\n        if (strpos($name, '#') !== false) list($name, $property) = explode('#', $name);\n        if (strpos($name, '@') !== false) list($name, $attr)     = explode('@', $name);\n\n        // figure out the parameters\n        $params = array();\n        if ($name !== '')    $params['element'] = $name;\n        if (!is_null($attr)) $params['attr'] = $attr;\n\n        // special case: attribute transform\n        if (!is_null($attr)) {\n            if (is_null($property)) $property = 'pre';\n            $type = 'attr_transform_' . $property;\n            return array($type, $params);\n        }\n\n        // special case: tag transform\n        if (is_null($property)) {\n            return array('tag_transform', $params);\n        }\n\n        return array($property, $params);\n\n    }\n\n    /**\n     * Defines all fixes the module will perform in a compact\n     * associative array of fix name to fix implementation.\n     */\n    public function makeFixes() {}\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule/XMLCommonAttributes.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModule_XMLCommonAttributes extends HTMLPurifier_HTMLModule\n{\n    public $name = 'XMLCommonAttributes';\n\n    public $attr_collections = array(\n        'Lang' => array(\n            'xml:lang' => 'LanguageCode',\n        )\n    );\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModule.php",
    "content": "<?php\n\n/**\n * Represents an XHTML 1.1 module, with information on elements, tags\n * and attributes.\n * @note Even though this is technically XHTML 1.1, it is also used for\n *       regular HTML parsing. We are using modulization as a convenient\n *       way to represent the internals of HTMLDefinition, and our\n *       implementation is by no means conforming and does not directly\n *       use the normative DTDs or XML schemas.\n * @note The public variables in a module should almost directly\n *       correspond to the variables in HTMLPurifier_HTMLDefinition.\n *       However, the prefix info carries no special meaning in these\n *       objects (include it anyway if that's the correspondence though).\n * @todo Consider making some member functions protected\n */\n\nclass HTMLPurifier_HTMLModule\n{\n\n    // -- Overloadable ----------------------------------------------------\n\n    /**\n     * Short unique string identifier of the module\n     */\n    public $name;\n\n    /**\n     * Informally, a list of elements this module changes. Not used in\n     * any significant way.\n     */\n    public $elements = array();\n\n    /**\n     * Associative array of element names to element definitions.\n     * Some definitions may be incomplete, to be merged in later\n     * with the full definition.\n     */\n    public $info = array();\n\n    /**\n     * Associative array of content set names to content set additions.\n     * This is commonly used to, say, add an A element to the Inline\n     * content set. This corresponds to an internal variable $content_sets\n     * and NOT info_content_sets member variable of HTMLDefinition.\n     */\n    public $content_sets = array();\n\n    /**\n     * Associative array of attribute collection names to attribute\n     * collection additions. More rarely used for adding attributes to\n     * the global collections. Example is the StyleAttribute module adding\n     * the style attribute to the Core. Corresponds to HTMLDefinition's\n     * attr_collections->info, since the object's data is only info,\n     * with extra behavior associated with it.\n     */\n    public $attr_collections = array();\n\n    /**\n     * Associative array of deprecated tag name to HTMLPurifier_TagTransform\n     */\n    public $info_tag_transform = array();\n\n    /**\n     * List of HTMLPurifier_AttrTransform to be performed before validation.\n     */\n    public $info_attr_transform_pre = array();\n\n    /**\n     * List of HTMLPurifier_AttrTransform to be performed after validation.\n     */\n    public $info_attr_transform_post = array();\n\n    /**\n     * List of HTMLPurifier_Injector to be performed during well-formedness fixing.\n     * An injector will only be invoked if all of it's pre-requisites are met;\n     * if an injector fails setup, there will be no error; it will simply be\n     * silently disabled.\n     */\n    public $info_injector = array();\n\n    /**\n     * Boolean flag that indicates whether or not getChildDef is implemented.\n     * For optimization reasons: may save a call to a function. Be sure\n     * to set it if you do implement getChildDef(), otherwise it will have\n     * no effect!\n     */\n    public $defines_child_def = false;\n\n    /**\n     * Boolean flag whether or not this module is safe. If it is not safe, all\n     * of its members are unsafe. Modules are safe by default (this might be\n     * slightly dangerous, but it doesn't make much sense to force HTML Purifier,\n     * which is based off of safe HTML, to explicitly say, \"This is safe,\" even\n     * though there are modules which are \"unsafe\")\n     *\n     * @note Previously, safety could be applied at an element level granularity.\n     *       We've removed this ability, so in order to add \"unsafe\" elements\n     *       or attributes, a dedicated module with this property set to false\n     *       must be used.\n     */\n    public $safe = true;\n\n    /**\n     * Retrieves a proper HTMLPurifier_ChildDef subclass based on\n     * content_model and content_model_type member variables of\n     * the HTMLPurifier_ElementDef class. There is a similar function\n     * in HTMLPurifier_HTMLDefinition.\n     * @param $def HTMLPurifier_ElementDef instance\n     * @return HTMLPurifier_ChildDef subclass\n     */\n    public function getChildDef($def) {return false;}\n\n    // -- Convenience -----------------------------------------------------\n\n    /**\n     * Convenience function that sets up a new element\n     * @param $element Name of element to add\n     * @param $type What content set should element be registered to?\n     *              Set as false to skip this step.\n     * @param $contents Allowed children in form of:\n     *              \"$content_model_type: $content_model\"\n     * @param $attr_includes What attribute collections to register to\n     *              element?\n     * @param $attr What unique attributes does the element define?\n     * @note See ElementDef for in-depth descriptions of these parameters.\n     * @return Created element definition object, so you\n     *         can set advanced parameters\n     */\n    public function addElement($element, $type, $contents, $attr_includes = array(), $attr = array()) {\n        $this->elements[] = $element;\n        // parse content_model\n        list($content_model_type, $content_model) = $this->parseContents($contents);\n        // merge in attribute inclusions\n        $this->mergeInAttrIncludes($attr, $attr_includes);\n        // add element to content sets\n        if ($type) $this->addElementToContentSet($element, $type);\n        // create element\n        $this->info[$element] = HTMLPurifier_ElementDef::create(\n            $content_model, $content_model_type, $attr\n        );\n        // literal object $contents means direct child manipulation\n        if (!is_string($contents)) $this->info[$element]->child = $contents;\n        return $this->info[$element];\n    }\n\n    /**\n     * Convenience function that creates a totally blank, non-standalone\n     * element.\n     * @param $element Name of element to create\n     * @return Created element\n     */\n    public function addBlankElement($element) {\n        if (!isset($this->info[$element])) {\n            $this->elements[] = $element;\n            $this->info[$element] = new HTMLPurifier_ElementDef();\n            $this->info[$element]->standalone = false;\n        } else {\n            trigger_error(\"Definition for $element already exists in module, cannot redefine\");\n        }\n        return $this->info[$element];\n    }\n\n    /**\n     * Convenience function that registers an element to a content set\n     * @param Element to register\n     * @param Name content set (warning: case sensitive, usually upper-case\n     *        first letter)\n     */\n    public function addElementToContentSet($element, $type) {\n        if (!isset($this->content_sets[$type])) $this->content_sets[$type] = '';\n        else $this->content_sets[$type] .= ' | ';\n        $this->content_sets[$type] .= $element;\n    }\n\n    /**\n     * Convenience function that transforms single-string contents\n     * into separate content model and content model type\n     * @param $contents Allowed children in form of:\n     *                  \"$content_model_type: $content_model\"\n     * @note If contents is an object, an array of two nulls will be\n     *       returned, and the callee needs to take the original $contents\n     *       and use it directly.\n     */\n    public function parseContents($contents) {\n        if (!is_string($contents)) return array(null, null); // defer\n        switch ($contents) {\n            // check for shorthand content model forms\n            case 'Empty':\n                return array('empty', '');\n            case 'Inline':\n                return array('optional', 'Inline | #PCDATA');\n            case 'Flow':\n                return array('optional', 'Flow | #PCDATA');\n        }\n        list($content_model_type, $content_model) = explode(':', $contents);\n        $content_model_type = strtolower(trim($content_model_type));\n        $content_model = trim($content_model);\n        return array($content_model_type, $content_model);\n    }\n\n    /**\n     * Convenience function that merges a list of attribute includes into\n     * an attribute array.\n     * @param $attr Reference to attr array to modify\n     * @param $attr_includes Array of includes / string include to merge in\n     */\n    public function mergeInAttrIncludes(&$attr, $attr_includes) {\n        if (!is_array($attr_includes)) {\n            if (empty($attr_includes)) $attr_includes = array();\n            else $attr_includes = array($attr_includes);\n        }\n        $attr[0] = $attr_includes;\n    }\n\n    /**\n     * Convenience function that generates a lookup table with boolean\n     * true as value.\n     * @param $list List of values to turn into a lookup\n     * @note You can also pass an arbitrary number of arguments in\n     *       place of the regular argument\n     * @return Lookup array equivalent of list\n     */\n    public function makeLookup($list) {\n        if (is_string($list)) $list = func_get_args();\n        $ret = array();\n        foreach ($list as $value) {\n            if (is_null($value)) continue;\n            $ret[$value] = true;\n        }\n        return $ret;\n    }\n\n    /**\n     * Lazy load construction of the module after determining whether\n     * or not it's needed, and also when a finalized configuration object\n     * is available.\n     * @param $config Instance of HTMLPurifier_Config\n     */\n    public function setup($config) {}\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/HTMLModuleManager.php",
    "content": "<?php\n\nclass HTMLPurifier_HTMLModuleManager\n{\n\n    /**\n     * Instance of HTMLPurifier_DoctypeRegistry\n     */\n    public $doctypes;\n\n    /**\n     * Instance of current doctype\n     */\n    public $doctype;\n\n    /**\n     * Instance of HTMLPurifier_AttrTypes\n     */\n    public $attrTypes;\n\n    /**\n     * Active instances of modules for the specified doctype are\n     * indexed, by name, in this array.\n     */\n    public $modules = array();\n\n    /**\n     * Array of recognized HTMLPurifier_Module instances, indexed by\n     * module's class name. This array is usually lazy loaded, but a\n     * user can overload a module by pre-emptively registering it.\n     */\n    public $registeredModules = array();\n\n    /**\n     * List of extra modules that were added by the user using addModule().\n     * These get unconditionally merged into the current doctype, whatever\n     * it may be.\n     */\n    public $userModules = array();\n\n    /**\n     * Associative array of element name to list of modules that have\n     * definitions for the element; this array is dynamically filled.\n     */\n    public $elementLookup = array();\n\n    /** List of prefixes we should use for registering small names */\n    public $prefixes = array('HTMLPurifier_HTMLModule_');\n\n    public $contentSets;     /**< Instance of HTMLPurifier_ContentSets */\n    public $attrCollections; /**< Instance of HTMLPurifier_AttrCollections */\n\n    /** If set to true, unsafe elements and attributes will be allowed */\n    public $trusted = false;\n\n    public function __construct() {\n\n        // editable internal objects\n        $this->attrTypes = new HTMLPurifier_AttrTypes();\n        $this->doctypes  = new HTMLPurifier_DoctypeRegistry();\n\n        // setup basic modules\n        $common = array(\n            'CommonAttributes', 'Text', 'Hypertext', 'List',\n            'Presentation', 'Edit', 'Bdo', 'Tables', 'Image',\n            'StyleAttribute',\n            // Unsafe:\n            'Scripting', 'Object',  'Forms',\n            // Sorta legacy, but present in strict:\n            'Name',\n        );\n        $transitional = array('Legacy', 'Target');\n        $xml = array('XMLCommonAttributes');\n        $non_xml = array('NonXMLCommonAttributes');\n\n        // setup basic doctypes\n        $this->doctypes->register(\n            'HTML 4.01 Transitional', false,\n            array_merge($common, $transitional, $non_xml),\n            array('Tidy_Transitional', 'Tidy_Proprietary'),\n            array(),\n            '-//W3C//DTD HTML 4.01 Transitional//EN',\n            'http://www.w3.org/TR/html4/loose.dtd'\n        );\n\n        $this->doctypes->register(\n            'HTML 4.01 Strict', false,\n            array_merge($common, $non_xml),\n            array('Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),\n            array(),\n            '-//W3C//DTD HTML 4.01//EN',\n            'http://www.w3.org/TR/html4/strict.dtd'\n        );\n\n        $this->doctypes->register(\n            'XHTML 1.0 Transitional', true,\n            array_merge($common, $transitional, $xml, $non_xml),\n            array('Tidy_Transitional', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Name'),\n            array(),\n            '-//W3C//DTD XHTML 1.0 Transitional//EN',\n            'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'\n        );\n\n        $this->doctypes->register(\n            'XHTML 1.0 Strict', true,\n            array_merge($common, $xml, $non_xml),\n            array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),\n            array(),\n            '-//W3C//DTD XHTML 1.0 Strict//EN',\n            'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'\n        );\n\n        $this->doctypes->register(\n            'XHTML 1.1', true,\n            array_merge($common, $xml, array('Ruby')),\n            array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Strict', 'Tidy_Name'), // Tidy_XHTML1_1\n            array(),\n            '-//W3C//DTD XHTML 1.1//EN',\n            'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'\n        );\n\n    }\n\n    /**\n     * Registers a module to the recognized module list, useful for\n     * overloading pre-existing modules.\n     * @param $module Mixed: string module name, with or without\n     *                HTMLPurifier_HTMLModule prefix, or instance of\n     *                subclass of HTMLPurifier_HTMLModule.\n     * @param $overload Boolean whether or not to overload previous modules.\n     *                  If this is not set, and you do overload a module,\n     *                  HTML Purifier will complain with a warning.\n     * @note This function will not call autoload, you must instantiate\n     *       (and thus invoke) autoload outside the method.\n     * @note If a string is passed as a module name, different variants\n     *       will be tested in this order:\n     *          - Check for HTMLPurifier_HTMLModule_$name\n     *          - Check all prefixes with $name in order they were added\n     *          - Check for literal object name\n     *          - Throw fatal error\n     *       If your object name collides with an internal class, specify\n     *       your module manually. All modules must have been included\n     *       externally: registerModule will not perform inclusions for you!\n     */\n    public function registerModule($module, $overload = false) {\n        if (is_string($module)) {\n            // attempt to load the module\n            $original_module = $module;\n            $ok = false;\n            foreach ($this->prefixes as $prefix) {\n                $module = $prefix . $original_module;\n                if (class_exists($module)) {\n                    $ok = true;\n                    break;\n                }\n            }\n            if (!$ok) {\n                $module = $original_module;\n                if (!class_exists($module)) {\n                    trigger_error($original_module . ' module does not exist',\n                        E_USER_ERROR);\n                    return;\n                }\n            }\n            $module = new $module();\n        }\n        if (empty($module->name)) {\n            trigger_error('Module instance of ' . get_class($module) . ' must have name');\n            return;\n        }\n        if (!$overload && isset($this->registeredModules[$module->name])) {\n            trigger_error('Overloading ' . $module->name . ' without explicit overload parameter', E_USER_WARNING);\n        }\n        $this->registeredModules[$module->name] = $module;\n    }\n\n    /**\n     * Adds a module to the current doctype by first registering it,\n     * and then tacking it on to the active doctype\n     */\n    public function addModule($module) {\n        $this->registerModule($module);\n        if (is_object($module)) $module = $module->name;\n        $this->userModules[] = $module;\n    }\n\n    /**\n     * Adds a class prefix that registerModule() will use to resolve a\n     * string name to a concrete class\n     */\n    public function addPrefix($prefix) {\n        $this->prefixes[] = $prefix;\n    }\n\n    /**\n     * Performs processing on modules, after being called you may\n     * use getElement() and getElements()\n     * @param $config Instance of HTMLPurifier_Config\n     */\n    public function setup($config) {\n\n        $this->trusted = $config->get('HTML.Trusted');\n\n        // generate\n        $this->doctype = $this->doctypes->make($config);\n        $modules = $this->doctype->modules;\n\n        // take out the default modules that aren't allowed\n        $lookup = $config->get('HTML.AllowedModules');\n        $special_cases = $config->get('HTML.CoreModules');\n\n        if (is_array($lookup)) {\n            foreach ($modules as $k => $m) {\n                if (isset($special_cases[$m])) continue;\n                if (!isset($lookup[$m])) unset($modules[$k]);\n            }\n        }\n\n        // add proprietary module (this gets special treatment because\n        // it is completely removed from doctypes, etc.)\n        if ($config->get('HTML.Proprietary')) {\n            $modules[] = 'Proprietary';\n        }\n\n        // add SafeObject/Safeembed modules\n        if ($config->get('HTML.SafeObject')) {\n            $modules[] = 'SafeObject';\n        }\n        if ($config->get('HTML.SafeEmbed')) {\n            $modules[] = 'SafeEmbed';\n        }\n\n        // merge in custom modules\n        $modules = array_merge($modules, $this->userModules);\n\n        foreach ($modules as $module) {\n            $this->processModule($module);\n            $this->modules[$module]->setup($config);\n        }\n\n        foreach ($this->doctype->tidyModules as $module) {\n            $this->processModule($module);\n            $this->modules[$module]->setup($config);\n        }\n\n        // prepare any injectors\n        foreach ($this->modules as $module) {\n            $n = array();\n            foreach ($module->info_injector as $i => $injector) {\n                if (!is_object($injector)) {\n                    $class = \"HTMLPurifier_Injector_$injector\";\n                    $injector = new $class;\n                }\n                $n[$injector->name] = $injector;\n            }\n            $module->info_injector = $n;\n        }\n\n        // setup lookup table based on all valid modules\n        foreach ($this->modules as $module) {\n            foreach ($module->info as $name => $def) {\n                if (!isset($this->elementLookup[$name])) {\n                    $this->elementLookup[$name] = array();\n                }\n                $this->elementLookup[$name][] = $module->name;\n            }\n        }\n\n        // note the different choice\n        $this->contentSets = new HTMLPurifier_ContentSets(\n            // content set assembly deals with all possible modules,\n            // not just ones deemed to be \"safe\"\n            $this->modules\n        );\n        $this->attrCollections = new HTMLPurifier_AttrCollections(\n            $this->attrTypes,\n            // there is no way to directly disable a global attribute,\n            // but using AllowedAttributes or simply not including\n            // the module in your custom doctype should be sufficient\n            $this->modules\n        );\n    }\n\n    /**\n     * Takes a module and adds it to the active module collection,\n     * registering it if necessary.\n     */\n    public function processModule($module) {\n        if (!isset($this->registeredModules[$module]) || is_object($module)) {\n            $this->registerModule($module);\n        }\n        $this->modules[$module] = $this->registeredModules[$module];\n    }\n\n    /**\n     * Retrieves merged element definitions.\n     * @return Array of HTMLPurifier_ElementDef\n     */\n    public function getElements() {\n\n        $elements = array();\n        foreach ($this->modules as $module) {\n            if (!$this->trusted && !$module->safe) continue;\n            foreach ($module->info as $name => $v) {\n                if (isset($elements[$name])) continue;\n                $elements[$name] = $this->getElement($name);\n            }\n        }\n\n        // remove dud elements, this happens when an element that\n        // appeared to be safe actually wasn't\n        foreach ($elements as $n => $v) {\n            if ($v === false) unset($elements[$n]);\n        }\n\n        return $elements;\n\n    }\n\n    /**\n     * Retrieves a single merged element definition\n     * @param $name Name of element\n     * @param $trusted Boolean trusted overriding parameter: set to true\n     *                 if you want the full version of an element\n     * @return Merged HTMLPurifier_ElementDef\n     * @note You may notice that modules are getting iterated over twice (once\n     *       in getElements() and once here). This\n     *       is because\n     */\n    public function getElement($name, $trusted = null) {\n\n        if (!isset($this->elementLookup[$name])) {\n            return false;\n        }\n\n        // setup global state variables\n        $def = false;\n        if ($trusted === null) $trusted = $this->trusted;\n\n        // iterate through each module that has registered itself to this\n        // element\n        foreach($this->elementLookup[$name] as $module_name) {\n\n            $module = $this->modules[$module_name];\n\n            // refuse to create/merge from a module that is deemed unsafe--\n            // pretend the module doesn't exist--when trusted mode is not on.\n            if (!$trusted && !$module->safe) {\n                continue;\n            }\n\n            // clone is used because, ideally speaking, the original\n            // definition should not be modified. Usually, this will\n            // make no difference, but for consistency's sake\n            $new_def = clone $module->info[$name];\n\n            if (!$def && $new_def->standalone) {\n                $def = $new_def;\n            } elseif ($def) {\n                // This will occur even if $new_def is standalone. In practice,\n                // this will usually result in a full replacement.\n                $def->mergeIn($new_def);\n            } else {\n                // :TODO:\n                // non-standalone definitions that don't have a standalone\n                // to merge into could be deferred to the end\n                continue;\n            }\n\n            // attribute value expansions\n            $this->attrCollections->performInclusions($def->attr);\n            $this->attrCollections->expandIdentifiers($def->attr, $this->attrTypes);\n\n            // descendants_are_inline, for ChildDef_Chameleon\n            if (is_string($def->content_model) &&\n                strpos($def->content_model, 'Inline') !== false) {\n                if ($name != 'del' && $name != 'ins') {\n                    // this is for you, ins/del\n                    $def->descendants_are_inline = true;\n                }\n            }\n\n            $this->contentSets->generateChildDef($def, $module);\n        }\n\n        // This can occur if there is a blank definition, but no base to\n        // mix it in with\n        if (!$def) return false;\n\n        // add information on required attributes\n        foreach ($def->attr as $attr_name => $attr_def) {\n            if ($attr_def->required) {\n                $def->required_attr[] = $attr_name;\n            }\n        }\n\n        return $def;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/IDAccumulator.php",
    "content": "<?php\n\n/**\n * Component of HTMLPurifier_AttrContext that accumulates IDs to prevent dupes\n * @note In Slashdot-speak, dupe means duplicate.\n * @note The default constructor does not accept $config or $context objects:\n *       use must use the static build() factory method to perform initialization.\n */\nclass HTMLPurifier_IDAccumulator\n{\n\n    /**\n     * Lookup table of IDs we've accumulated.\n     * @public\n     */\n    public $ids = array();\n\n    /**\n     * Builds an IDAccumulator, also initializing the default blacklist\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     * @return Fully initialized HTMLPurifier_IDAccumulator\n     */\n    public static function build($config, $context) {\n        $id_accumulator = new HTMLPurifier_IDAccumulator();\n        $id_accumulator->load($config->get('Attr.IDBlacklist'));\n        return $id_accumulator;\n    }\n\n    /**\n     * Add an ID to the lookup table.\n     * @param $id ID to be added.\n     * @return Bool status, true if success, false if there's a dupe\n     */\n    public function add($id) {\n        if (isset($this->ids[$id])) return false;\n        return $this->ids[$id] = true;\n    }\n\n    /**\n     * Load a list of IDs into the lookup table\n     * @param $array_of_ids Array of IDs to load\n     * @note This function doesn't care about duplicates\n     */\n    public function load($array_of_ids) {\n        foreach ($array_of_ids as $id) {\n            $this->ids[$id] = true;\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Injector/AutoParagraph.php",
    "content": "<?php\n\n/**\n * Injector that auto paragraphs text in the root node based on\n * double-spacing.\n * @todo Ensure all states are unit tested, including variations as well.\n * @todo Make a graph of the flow control for this Injector.\n */\nclass HTMLPurifier_Injector_AutoParagraph extends HTMLPurifier_Injector\n{\n\n    public $name = 'AutoParagraph';\n    public $needed = array('p');\n\n    private function _pStart() {\n        $par = new HTMLPurifier_Token_Start('p');\n        $par->armor['MakeWellFormed_TagClosedError'] = true;\n        return $par;\n    }\n\n    public function handleText(&$token) {\n        $text = $token->data;\n        // Does the current parent allow <p> tags?\n        if ($this->allowsElement('p')) {\n            if (empty($this->currentNesting) || strpos($text, \"\\n\\n\") !== false) {\n                // Note that we have differing behavior when dealing with text\n                // in the anonymous root node, or a node inside the document.\n                // If the text as a double-newline, the treatment is the same;\n                // if it doesn't, see the next if-block if you're in the document.\n\n                $i = $nesting = null;\n                if (!$this->forwardUntilEndToken($i, $current, $nesting) && $token->is_whitespace) {\n                    // State 1.1: ...    ^ (whitespace, then document end)\n                    //               ----\n                    // This is a degenerate case\n                } else {\n                    // State 1.2: PAR1\n                    //            ----\n\n                    // State 1.3: PAR1\\n\\nPAR2\n                    //            ------------\n\n                    // State 1.4: <div>PAR1\\n\\nPAR2 (see State 2)\n                    //                 ------------\n                    $token = array($this->_pStart());\n                    $this->_splitText($text, $token);\n                }\n            } else {\n                // State 2:   <div>PAR1... (similar to 1.4)\n                //                 ----\n\n                // We're in an element that allows paragraph tags, but we're not\n                // sure if we're going to need them.\n                if ($this->_pLookAhead()) {\n                    // State 2.1: <div>PAR1<b>PAR1\\n\\nPAR2\n                    //                 ----\n                    // Note: This will always be the first child, since any\n                    // previous inline element would have triggered this very\n                    // same routine, and found the double newline. One possible\n                    // exception would be a comment.\n                    $token = array($this->_pStart(), $token);\n                } else {\n                    // State 2.2.1: <div>PAR1<div>\n                    //                   ----\n\n                    // State 2.2.2: <div>PAR1<b>PAR1</b></div>\n                    //                   ----\n                }\n            }\n        // Is the current parent a <p> tag?\n        } elseif (\n            !empty($this->currentNesting) &&\n            $this->currentNesting[count($this->currentNesting)-1]->name == 'p'\n        ) {\n            // State 3.1: ...<p>PAR1\n            //                  ----\n\n            // State 3.2: ...<p>PAR1\\n\\nPAR2\n            //                  ------------\n            $token = array();\n            $this->_splitText($text, $token);\n        // Abort!\n        } else {\n            // State 4.1: ...<b>PAR1\n            //                  ----\n\n            // State 4.2: ...<b>PAR1\\n\\nPAR2\n            //                  ------------\n        }\n    }\n\n    public function handleElement(&$token) {\n        // We don't have to check if we're already in a <p> tag for block\n        // tokens, because the tag would have been autoclosed by MakeWellFormed.\n        if ($this->allowsElement('p')) {\n            if (!empty($this->currentNesting)) {\n                if ($this->_isInline($token)) {\n                    // State 1: <div>...<b>\n                    //                  ---\n\n                    // Check if this token is adjacent to the parent token\n                    // (seek backwards until token isn't whitespace)\n                    $i = null;\n                    $this->backward($i, $prev);\n\n                    if (!$prev instanceof HTMLPurifier_Token_Start) {\n                        // Token wasn't adjacent\n\n                        if (\n                            $prev instanceof HTMLPurifier_Token_Text &&\n                            substr($prev->data, -2) === \"\\n\\n\"\n                        ) {\n                            // State 1.1.4: <div><p>PAR1</p>\\n\\n<b>\n                            //                                  ---\n\n                            // Quite frankly, this should be handled by splitText\n                            $token = array($this->_pStart(), $token);\n                        } else {\n                            // State 1.1.1: <div><p>PAR1</p><b>\n                            //                              ---\n\n                            // State 1.1.2: <div><br /><b>\n                            //                         ---\n\n                            // State 1.1.3: <div>PAR<b>\n                            //                      ---\n                        }\n\n                    } else {\n                        // State 1.2.1: <div><b>\n                        //                   ---\n\n                        // Lookahead to see if <p> is needed.\n                        if ($this->_pLookAhead()) {\n                            // State 1.3.1: <div><b>PAR1\\n\\nPAR2\n                            //                   ---\n                            $token = array($this->_pStart(), $token);\n                        } else {\n                            // State 1.3.2: <div><b>PAR1</b></div>\n                            //                   ---\n\n                            // State 1.3.3: <div><b>PAR1</b><div></div>\\n\\n</div>\n                            //                   ---\n                        }\n                    }\n                } else {\n                    // State 2.3: ...<div>\n                    //               -----\n                }\n            } else {\n                if ($this->_isInline($token)) {\n                    // State 3.1: <b>\n                    //            ---\n                    // This is where the {p} tag is inserted, not reflected in\n                    // inputTokens yet, however.\n                    $token = array($this->_pStart(), $token);\n                } else {\n                    // State 3.2: <div>\n                    //            -----\n                }\n\n                $i = null;\n                if ($this->backward($i, $prev)) {\n                    if (\n                        !$prev instanceof HTMLPurifier_Token_Text\n                    ) {\n                        // State 3.1.1: ...</p>{p}<b>\n                        //                        ---\n\n                        // State 3.2.1: ...</p><div>\n                        //                     -----\n\n                        if (!is_array($token)) $token = array($token);\n                        array_unshift($token, new HTMLPurifier_Token_Text(\"\\n\\n\"));\n                    } else {\n                        // State 3.1.2: ...</p>\\n\\n{p}<b>\n                        //                            ---\n\n                        // State 3.2.2: ...</p>\\n\\n<div>\n                        //                         -----\n\n                        // Note: PAR<ELEM> cannot occur because PAR would have been\n                        // wrapped in <p> tags.\n                    }\n                }\n            }\n        } else {\n            // State 2.2: <ul><li>\n            //                ----\n\n            // State 2.4: <p><b>\n            //               ---\n        }\n    }\n\n    /**\n     * Splits up a text in paragraph tokens and appends them\n     * to the result stream that will replace the original\n     * @param $data String text data that will be processed\n     *    into paragraphs\n     * @param $result Reference to array of tokens that the\n     *    tags will be appended onto\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     */\n    private function _splitText($data, &$result) {\n        $raw_paragraphs = explode(\"\\n\\n\", $data);\n        $paragraphs  = array(); // without empty paragraphs\n        $needs_start = false;\n        $needs_end   = false;\n\n        $c = count($raw_paragraphs);\n        if ($c == 1) {\n            // There were no double-newlines, abort quickly. In theory this\n            // should never happen.\n            $result[] = new HTMLPurifier_Token_Text($data);\n            return;\n        }\n        for ($i = 0; $i < $c; $i++) {\n            $par = $raw_paragraphs[$i];\n            if (trim($par) !== '') {\n                $paragraphs[] = $par;\n            } else {\n                if ($i == 0) {\n                    // Double newline at the front\n                    if (empty($result)) {\n                        // The empty result indicates that the AutoParagraph\n                        // injector did not add any start paragraph tokens.\n                        // This means that we have been in a paragraph for\n                        // a while, and the newline means we should start a new one.\n                        $result[] = new HTMLPurifier_Token_End('p');\n                        $result[] = new HTMLPurifier_Token_Text(\"\\n\\n\");\n                        // However, the start token should only be added if\n                        // there is more processing to be done (i.e. there are\n                        // real paragraphs in here). If there are none, the\n                        // next start paragraph tag will be handled by the\n                        // next call to the injector\n                        $needs_start = true;\n                    } else {\n                        // We just started a new paragraph!\n                        // Reinstate a double-newline for presentation's sake, since\n                        // it was in the source code.\n                        array_unshift($result, new HTMLPurifier_Token_Text(\"\\n\\n\"));\n                    }\n                } elseif ($i + 1 == $c) {\n                    // Double newline at the end\n                    // There should be a trailing </p> when we're finally done.\n                    $needs_end = true;\n                }\n            }\n        }\n\n        // Check if this was just a giant blob of whitespace. Move this earlier,\n        // perhaps?\n        if (empty($paragraphs)) {\n            return;\n        }\n\n        // Add the start tag indicated by \\n\\n at the beginning of $data\n        if ($needs_start) {\n            $result[] = $this->_pStart();\n        }\n\n        // Append the paragraphs onto the result\n        foreach ($paragraphs as $par) {\n            $result[] = new HTMLPurifier_Token_Text($par);\n            $result[] = new HTMLPurifier_Token_End('p');\n            $result[] = new HTMLPurifier_Token_Text(\"\\n\\n\");\n            $result[] = $this->_pStart();\n        }\n\n        // Remove trailing start token; Injector will handle this later if\n        // it was indeed needed. This prevents from needing to do a lookahead,\n        // at the cost of a lookbehind later.\n        array_pop($result);\n\n        // If there is no need for an end tag, remove all of it and let\n        // MakeWellFormed close it later.\n        if (!$needs_end) {\n            array_pop($result); // removes \\n\\n\n            array_pop($result); // removes </p>\n        }\n\n    }\n\n    /**\n     * Returns true if passed token is inline (and, ergo, allowed in\n     * paragraph tags)\n     */\n    private function _isInline($token) {\n        return isset($this->htmlDefinition->info['p']->child->elements[$token->name]);\n    }\n\n    /**\n     * Looks ahead in the token list and determines whether or not we need\n     * to insert a <p> tag.\n     */\n    private function _pLookAhead() {\n        $this->current($i, $current);\n        if ($current instanceof HTMLPurifier_Token_Start) $nesting = 1;\n        else $nesting = 0;\n        $ok = false;\n        while ($this->forwardUntilEndToken($i, $current, $nesting)) {\n            $result = $this->_checkNeedsP($current);\n            if ($result !== null) {\n                $ok = $result;\n                break;\n            }\n        }\n        return $ok;\n    }\n\n    /**\n     * Determines if a particular token requires an earlier inline token\n     * to get a paragraph. This should be used with _forwardUntilEndToken\n     */\n    private function _checkNeedsP($current) {\n        if ($current instanceof HTMLPurifier_Token_Start){\n            if (!$this->_isInline($current)) {\n                // <div>PAR1<div>\n                //      ----\n                // Terminate early, since we hit a block element\n                return false;\n            }\n        } elseif ($current instanceof HTMLPurifier_Token_Text) {\n            if (strpos($current->data, \"\\n\\n\") !== false) {\n                // <div>PAR1<b>PAR1\\n\\nPAR2\n                //      ----\n                return true;\n            } else {\n                // <div>PAR1<b>PAR1...\n                //      ----\n            }\n        }\n        return null;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Injector/DisplayLinkURI.php",
    "content": "<?php\n\n/**\n * Injector that displays the URL of an anchor instead of linking to it, in addition to showing the text of the link.\n */\nclass HTMLPurifier_Injector_DisplayLinkURI extends HTMLPurifier_Injector\n{\n\n    public $name = 'DisplayLinkURI';\n    public $needed = array('a');\n\n    public function handleElement(&$token) {\n    }\n\n    public function handleEnd(&$token) {\n        if (isset($token->start->attr['href'])){\n            $url = $token->start->attr['href'];\n            unset($token->start->attr['href']);\n            $token = array($token, new HTMLPurifier_Token_Text(\" ($url)\"));\n        } else {\n            // nothing to display\n        }\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Injector/Linkify.php",
    "content": "<?php\n\n/**\n * Injector that converts http, https and ftp text URLs to actual links.\n */\nclass HTMLPurifier_Injector_Linkify extends HTMLPurifier_Injector\n{\n\n    public $name = 'Linkify';\n    public $needed = array('a' => array('href'));\n\n    public function handleText(&$token) {\n        if (!$this->allowsElement('a')) return;\n\n        if (strpos($token->data, '://') === false) {\n            // our really quick heuristic failed, abort\n            // this may not work so well if we want to match things like\n            // \"google.com\", but then again, most people don't\n            return;\n        }\n\n        // there is/are URL(s). Let's split the string:\n        // Note: this regex is extremely permissive\n        $bits = preg_split('#((?:https?|ftp)://[^\\s\\'\"<>()]+)#S', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);\n\n        $token = array();\n\n        // $i = index\n        // $c = count\n        // $l = is link\n        for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {\n            if (!$l) {\n                if ($bits[$i] === '') continue;\n                $token[] = new HTMLPurifier_Token_Text($bits[$i]);\n            } else {\n                $token[] = new HTMLPurifier_Token_Start('a', array('href' => $bits[$i]));\n                $token[] = new HTMLPurifier_Token_Text($bits[$i]);\n                $token[] = new HTMLPurifier_Token_End('a');\n            }\n        }\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Injector/PurifierLinkify.php",
    "content": "<?php\n\n/**\n * Injector that converts configuration directive syntax %Namespace.Directive\n * to links\n */\nclass HTMLPurifier_Injector_PurifierLinkify extends HTMLPurifier_Injector\n{\n\n    public $name = 'PurifierLinkify';\n    public $docURL;\n    public $needed = array('a' => array('href'));\n\n    public function prepare($config, $context) {\n        $this->docURL = $config->get('AutoFormat.PurifierLinkify.DocURL');\n        return parent::prepare($config, $context);\n    }\n\n    public function handleText(&$token) {\n        if (!$this->allowsElement('a')) return;\n        if (strpos($token->data, '%') === false) return;\n\n        $bits = preg_split('#%([a-z0-9]+\\.[a-z0-9]+)#Si', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);\n        $token = array();\n\n        // $i = index\n        // $c = count\n        // $l = is link\n        for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {\n            if (!$l) {\n                if ($bits[$i] === '') continue;\n                $token[] = new HTMLPurifier_Token_Text($bits[$i]);\n            } else {\n                $token[] = new HTMLPurifier_Token_Start('a',\n                    array('href' => str_replace('%s', $bits[$i], $this->docURL)));\n                $token[] = new HTMLPurifier_Token_Text('%' . $bits[$i]);\n                $token[] = new HTMLPurifier_Token_End('a');\n            }\n        }\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Injector/RemoveEmpty.php",
    "content": "<?php\n\nclass HTMLPurifier_Injector_RemoveEmpty extends HTMLPurifier_Injector\n{\n\n    private $context, $config, $attrValidator, $removeNbsp, $removeNbspExceptions;\n\n    public function prepare($config, $context) {\n        parent::prepare($config, $context);\n        $this->config = $config;\n        $this->context = $context;\n        $this->removeNbsp = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp');\n        $this->removeNbspExceptions = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions');\n        $this->attrValidator = new HTMLPurifier_AttrValidator();\n    }\n\n    public function handleElement(&$token) {\n        if (!$token instanceof HTMLPurifier_Token_Start) return;\n        $next = false;\n        for ($i = $this->inputIndex + 1, $c = count($this->inputTokens); $i < $c; $i++) {\n            $next = $this->inputTokens[$i];\n            if ($next instanceof HTMLPurifier_Token_Text) {\n                if ($next->is_whitespace) continue;\n                if ($this->removeNbsp && !isset($this->removeNbspExceptions[$token->name])) {\n                    $plain = str_replace(\"\\xC2\\xA0\", \"\", $next->data);\n                    $isWsOrNbsp = $plain === '' || ctype_space($plain);\n                    if ($isWsOrNbsp) continue;\n                }\n            }\n            break;\n        }\n        if (!$next || ($next instanceof HTMLPurifier_Token_End && $next->name == $token->name)) {\n            if ($token->name == 'colgroup') return;\n            $this->attrValidator->validateToken($token, $this->config, $this->context);\n            $token->armor['ValidateAttributes'] = true;\n            if (isset($token->attr['id']) || isset($token->attr['name'])) return;\n            $token = $i - $this->inputIndex + 1;\n            for ($b = $this->inputIndex - 1; $b > 0; $b--) {\n                $prev = $this->inputTokens[$b];\n                if ($prev instanceof HTMLPurifier_Token_Text && $prev->is_whitespace) continue;\n                break;\n            }\n            // This is safe because we removed the token that triggered this.\n            $this->rewind($b - 1);\n            return;\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Injector/SafeObject.php",
    "content": "<?php\n\n/**\n * Adds important param elements to inside of object in order to make\n * things safe.\n */\nclass HTMLPurifier_Injector_SafeObject extends HTMLPurifier_Injector\n{\n    public $name = 'SafeObject';\n    public $needed = array('object', 'param');\n\n    protected $objectStack = array();\n    protected $paramStack  = array();\n\n    // Keep this synchronized with AttrTransform/SafeParam.php\n    protected $addParam = array(\n        'allowScriptAccess' => 'never',\n        'allowNetworking' => 'internal',\n    );\n    protected $allowedParam = array(\n        'wmode' => true,\n        'movie' => true,\n    );\n\n    public function prepare($config, $context) {\n        parent::prepare($config, $context);\n    }\n\n    public function handleElement(&$token) {\n        if ($token->name == 'object') {\n            $this->objectStack[] = $token;\n            $this->paramStack[] = array();\n            $new = array($token);\n            foreach ($this->addParam as $name => $value) {\n                $new[] = new HTMLPurifier_Token_Empty('param', array('name' => $name, 'value' => $value));\n            }\n            $token = $new;\n        } elseif ($token->name == 'param') {\n            $nest = count($this->currentNesting) - 1;\n            if ($nest >= 0 && $this->currentNesting[$nest]->name === 'object') {\n                $i = count($this->objectStack) - 1;\n                if (!isset($token->attr['name'])) {\n                    $token = false;\n                    return;\n                }\n                $n = $token->attr['name'];\n                // We need this fix because YouTube doesn't supply a data\n                // attribute, which we need if a type is specified. This is\n                // *very* Flash specific.\n                if (!isset($this->objectStack[$i]->attr['data']) && $token->attr['name'] == 'movie') {\n                    $this->objectStack[$i]->attr['data'] = $token->attr['value'];\n                }\n                // Check if the parameter is the correct value but has not\n                // already been added\n                if (\n                    !isset($this->paramStack[$i][$n]) &&\n                    isset($this->addParam[$n]) &&\n                    $token->attr['name'] === $this->addParam[$n]\n                ) {\n                    // keep token, and add to param stack\n                    $this->paramStack[$i][$n] = true;\n                } elseif (isset($this->allowedParam[$n])) {\n                    // keep token, don't do anything to it\n                    // (could possibly check for duplicates here)\n                } else {\n                    $token = false;\n                }\n            } else {\n                // not directly inside an object, DENY!\n                $token = false;\n            }\n        }\n    }\n\n    public function handleEnd(&$token) {\n        // This is the WRONG way of handling the object and param stacks;\n        // we should be inserting them directly on the relevant object tokens\n        // so that the global stack handling handles it.\n        if ($token->name == 'object') {\n            array_pop($this->objectStack);\n            array_pop($this->paramStack);\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Injector.php",
    "content": "<?php\n\n/**\n * Injects tokens into the document while parsing for well-formedness.\n * This enables \"formatter-like\" functionality such as auto-paragraphing,\n * smiley-ification and linkification to take place.\n *\n * A note on how handlers create changes; this is done by assigning a new\n * value to the $token reference. These values can take a variety of forms and\n * are best described HTMLPurifier_Strategy_MakeWellFormed->processToken()\n * documentation.\n *\n * @todo Allow injectors to request a re-run on their output. This\n *       would help if an operation is recursive.\n */\nabstract class HTMLPurifier_Injector\n{\n\n    /**\n     * Advisory name of injector, this is for friendly error messages\n     */\n    public $name;\n\n    /**\n     * Instance of HTMLPurifier_HTMLDefinition\n     */\n    protected $htmlDefinition;\n\n    /**\n     * Reference to CurrentNesting variable in Context. This is an array\n     * list of tokens that we are currently \"inside\"\n     */\n    protected $currentNesting;\n\n    /**\n     * Reference to InputTokens variable in Context. This is an array\n     * list of the input tokens that are being processed.\n     */\n    protected $inputTokens;\n\n    /**\n     * Reference to InputIndex variable in Context. This is an integer\n     * array index for $this->inputTokens that indicates what token\n     * is currently being processed.\n     */\n    protected $inputIndex;\n\n    /**\n     * Array of elements and attributes this injector creates and therefore\n     * need to be allowed by the definition. Takes form of\n     * array('element' => array('attr', 'attr2'), 'element2')\n     */\n    public $needed = array();\n\n    /**\n     * Index of inputTokens to rewind to.\n     */\n    protected $rewind = false;\n\n    /**\n     * Rewind to a spot to re-perform processing. This is useful if you\n     * deleted a node, and now need to see if this change affected any\n     * earlier nodes. Rewinding does not affect other injectors, and can\n     * result in infinite loops if not used carefully.\n     * @warning HTML Purifier will prevent you from fast-forwarding with this\n     *          function.\n     */\n    public function rewind($index) {\n        $this->rewind = $index;\n    }\n\n    /**\n     * Retrieves rewind, and then unsets it.\n     */\n    public function getRewind() {\n        $r = $this->rewind;\n        $this->rewind = false;\n        return $r;\n    }\n\n    /**\n     * Prepares the injector by giving it the config and context objects:\n     * this allows references to important variables to be made within\n     * the injector. This function also checks if the HTML environment\n     * will work with the Injector (see checkNeeded()).\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     * @return Boolean false if success, string of missing needed element/attribute if failure\n     */\n    public function prepare($config, $context) {\n        $this->htmlDefinition = $config->getHTMLDefinition();\n        // Even though this might fail, some unit tests ignore this and\n        // still test checkNeeded, so be careful. Maybe get rid of that\n        // dependency.\n        $result = $this->checkNeeded($config);\n        if ($result !== false) return $result;\n        $this->currentNesting =& $context->get('CurrentNesting');\n        $this->inputTokens    =& $context->get('InputTokens');\n        $this->inputIndex     =& $context->get('InputIndex');\n        return false;\n    }\n\n    /**\n     * This function checks if the HTML environment\n     * will work with the Injector: if p tags are not allowed, the\n     * Auto-Paragraphing injector should not be enabled.\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     * @return Boolean false if success, string of missing needed element/attribute if failure\n     */\n    public function checkNeeded($config) {\n        $def = $config->getHTMLDefinition();\n        foreach ($this->needed as $element => $attributes) {\n            if (is_int($element)) $element = $attributes;\n            if (!isset($def->info[$element])) return $element;\n            if (!is_array($attributes)) continue;\n            foreach ($attributes as $name) {\n                if (!isset($def->info[$element]->attr[$name])) return \"$element.$name\";\n            }\n        }\n        return false;\n    }\n\n    /**\n     * Tests if the context node allows a certain element\n     * @param $name Name of element to test for\n     * @return True if element is allowed, false if it is not\n     */\n    public function allowsElement($name) {\n        if (!empty($this->currentNesting)) {\n            $parent_token = array_pop($this->currentNesting);\n            $this->currentNesting[] = $parent_token;\n            $parent = $this->htmlDefinition->info[$parent_token->name];\n        } else {\n            $parent = $this->htmlDefinition->info_parent_def;\n        }\n        if (!isset($parent->child->elements[$name]) || isset($parent->excludes[$name])) {\n            return false;\n        }\n        // check for exclusion\n        for ($i = count($this->currentNesting) - 2; $i >= 0; $i--) {\n            $node = $this->currentNesting[$i];\n            $def  = $this->htmlDefinition->info[$node->name];\n            if (isset($def->excludes[$name])) return false;\n        }\n        return true;\n    }\n\n    /**\n     * Iterator function, which starts with the next token and continues until\n     * you reach the end of the input tokens.\n     * @warning Please prevent previous references from interfering with this\n     *          functions by setting $i = null beforehand!\n     * @param &$i Current integer index variable for inputTokens\n     * @param &$current Current token variable. Do NOT use $token, as that variable is also a reference\n     */\n    protected function forward(&$i, &$current) {\n        if ($i === null) $i = $this->inputIndex + 1;\n        else $i++;\n        if (!isset($this->inputTokens[$i])) return false;\n        $current = $this->inputTokens[$i];\n        return true;\n    }\n\n    /**\n     * Similar to _forward, but accepts a third parameter $nesting (which\n     * should be initialized at 0) and stops when we hit the end tag\n     * for the node $this->inputIndex starts in.\n     */\n    protected function forwardUntilEndToken(&$i, &$current, &$nesting) {\n        $result = $this->forward($i, $current);\n        if (!$result) return false;\n        if ($nesting === null) $nesting = 0;\n        if     ($current instanceof HTMLPurifier_Token_Start) $nesting++;\n        elseif ($current instanceof HTMLPurifier_Token_End) {\n            if ($nesting <= 0) return false;\n            $nesting--;\n        }\n        return true;\n    }\n\n    /**\n     * Iterator function, starts with the previous token and continues until\n     * you reach the beginning of input tokens.\n     * @warning Please prevent previous references from interfering with this\n     *          functions by setting $i = null beforehand!\n     * @param &$i Current integer index variable for inputTokens\n     * @param &$current Current token variable. Do NOT use $token, as that variable is also a reference\n     */\n    protected function backward(&$i, &$current) {\n        if ($i === null) $i = $this->inputIndex - 1;\n        else $i--;\n        if ($i < 0) return false;\n        $current = $this->inputTokens[$i];\n        return true;\n    }\n\n    /**\n     * Initializes the iterator at the current position. Use in a do {} while;\n     * loop to force the _forward and _backward functions to start at the\n     * current location.\n     * @warning Please prevent previous references from interfering with this\n     *          functions by setting $i = null beforehand!\n     * @param &$i Current integer index variable for inputTokens\n     * @param &$current Current token variable. Do NOT use $token, as that variable is also a reference\n     */\n    protected function current(&$i, &$current) {\n        if ($i === null) $i = $this->inputIndex;\n        $current = $this->inputTokens[$i];\n    }\n\n    /**\n     * Handler that is called when a text token is processed\n     */\n    public function handleText(&$token) {}\n\n    /**\n     * Handler that is called when a start or empty token is processed\n     */\n    public function handleElement(&$token) {}\n\n    /**\n     * Handler that is called when an end token is processed\n     */\n    public function handleEnd(&$token) {\n        $this->notifyEnd($token);\n    }\n\n    /**\n     * Notifier that is called when an end token is processed\n     * @note This differs from handlers in that the token is read-only\n     * @deprecated\n     */\n    public function notifyEnd($token) {}\n\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Language/classes/en-x-test.php",
    "content": "<?php\n\n// private class for unit testing\n\nclass HTMLPurifier_Language_en_x_test extends HTMLPurifier_Language\n{\n\n\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Language/messages/en-x-test.php",
    "content": "<?php\n\n// private language message file for unit testing purposes\n\n$fallback = 'en';\n\n$messages = array(\n    'HTMLPurifier' => 'HTML Purifier X'\n);\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Language/messages/en-x-testmini.php",
    "content": "<?php\n\n// private language message file for unit testing purposes\n// this language file has no class associated with it\n\n$fallback = 'en';\n\n$messages = array(\n    'HTMLPurifier' => 'HTML Purifier XNone'\n);\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Language/messages/en.php",
    "content": "<?php\n\n$fallback = false;\n\n$messages = array(\n\n'HTMLPurifier' => 'HTML Purifier',\n\n// for unit testing purposes\n'LanguageFactoryTest: Pizza' => 'Pizza',\n'LanguageTest: List' => '$1',\n'LanguageTest: Hash' => '$1.Keys; $1.Values',\n\n'Item separator' => ', ',\n'Item separator last' => ' and ', // non-Harvard style\n\n'ErrorCollector: No errors' => 'No errors detected. However, because error reporting is still incomplete, there may have been errors that the error collector was not notified of; please inspect the output HTML carefully.',\n'ErrorCollector: At line'   => ' at line $line',\n'ErrorCollector: Incidental errors'  => 'Incidental errors',\n\n'Lexer: Unclosed comment'      => 'Unclosed comment',\n'Lexer: Unescaped lt'          => 'Unescaped less-than sign (<) should be &lt;',\n'Lexer: Missing gt'            => 'Missing greater-than sign (>), previous less-than sign (<) should be escaped',\n'Lexer: Missing attribute key' => 'Attribute declaration has no key',\n'Lexer: Missing end quote'     => 'Attribute declaration has no end quote',\n\n'Strategy_RemoveForeignElements: Tag transform'              => '<$1> element transformed into $CurrentToken.Serialized',\n'Strategy_RemoveForeignElements: Missing required attribute' => '$CurrentToken.Compact element missing required attribute $1',\n'Strategy_RemoveForeignElements: Foreign element to text'    => 'Unrecognized $CurrentToken.Serialized tag converted to text',\n'Strategy_RemoveForeignElements: Foreign element removed'    => 'Unrecognized $CurrentToken.Serialized tag removed',\n'Strategy_RemoveForeignElements: Comment removed'            => 'Comment containing \"$CurrentToken.Data\" removed',\n'Strategy_RemoveForeignElements: Foreign meta element removed' => 'Unrecognized $CurrentToken.Serialized meta tag and all descendants removed',\n'Strategy_RemoveForeignElements: Token removed to end'       => 'Tags and text starting from $1 element where removed to end',\n'Strategy_RemoveForeignElements: Trailing hyphen in comment removed' => 'Trailing hyphen(s) in comment removed',\n'Strategy_RemoveForeignElements: Hyphens in comment collapsed' => 'Double hyphens in comments are not allowed, and were collapsed into single hyphens',\n\n'Strategy_MakeWellFormed: Unnecessary end tag removed' => 'Unnecessary $CurrentToken.Serialized tag removed',\n'Strategy_MakeWellFormed: Unnecessary end tag to text' => 'Unnecessary $CurrentToken.Serialized tag converted to text',\n'Strategy_MakeWellFormed: Tag auto closed'             => '$1.Compact started on line $1.Line auto-closed by $CurrentToken.Compact',\n'Strategy_MakeWellFormed: Tag carryover'               => '$1.Compact started on line $1.Line auto-continued into $CurrentToken.Compact',\n'Strategy_MakeWellFormed: Stray end tag removed'       => 'Stray $CurrentToken.Serialized tag removed',\n'Strategy_MakeWellFormed: Stray end tag to text'       => 'Stray $CurrentToken.Serialized tag converted to text',\n'Strategy_MakeWellFormed: Tag closed by element end'   => '$1.Compact tag started on line $1.Line closed by end of $CurrentToken.Serialized',\n'Strategy_MakeWellFormed: Tag closed by document end'  => '$1.Compact tag started on line $1.Line closed by end of document',\n\n'Strategy_FixNesting: Node removed'          => '$CurrentToken.Compact node removed',\n'Strategy_FixNesting: Node excluded'         => '$CurrentToken.Compact node removed due to descendant exclusion by ancestor element',\n'Strategy_FixNesting: Node reorganized'      => 'Contents of $CurrentToken.Compact node reorganized to enforce its content model',\n'Strategy_FixNesting: Node contents removed' => 'Contents of $CurrentToken.Compact node removed',\n\n'AttrValidator: Attributes transformed' => 'Attributes on $CurrentToken.Compact transformed from $1.Keys to $2.Keys',\n'AttrValidator: Attribute removed' => '$CurrentAttr.Name attribute on $CurrentToken.Compact removed',\n\n);\n\n$errorNames = array(\n    E_ERROR   => 'Error',\n    E_WARNING => 'Warning',\n    E_NOTICE  => 'Notice'\n);\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Language.php",
    "content": "<?php\n\n/**\n * Represents a language and defines localizable string formatting and\n * other functions, as well as the localized messages for HTML Purifier.\n */\nclass HTMLPurifier_Language\n{\n\n    /**\n     * ISO 639 language code of language. Prefers shortest possible version\n     */\n    public $code = 'en';\n\n    /**\n     * Fallback language code\n     */\n    public $fallback = false;\n\n    /**\n     * Array of localizable messages\n     */\n    public $messages = array();\n\n    /**\n     * Array of localizable error codes\n     */\n    public $errorNames = array();\n\n    /**\n     * True if no message file was found for this language, so English\n     * is being used instead. Check this if you'd like to notify the\n     * user that they've used a non-supported language.\n     */\n    public $error = false;\n\n    /**\n     * Has the language object been loaded yet?\n     * @todo Make it private, fix usage in HTMLPurifier_LanguageTest\n     */\n    public $_loaded = false;\n\n    /**\n     * Instances of HTMLPurifier_Config and HTMLPurifier_Context\n     */\n    protected $config, $context;\n\n    public function __construct($config, $context) {\n        $this->config  = $config;\n        $this->context = $context;\n    }\n\n    /**\n     * Loads language object with necessary info from factory cache\n     * @note This is a lazy loader\n     */\n    public function load() {\n        if ($this->_loaded) return;\n        $factory = HTMLPurifier_LanguageFactory::instance();\n        $factory->loadLanguage($this->code);\n        foreach ($factory->keys as $key) {\n            $this->$key = $factory->cache[$this->code][$key];\n        }\n        $this->_loaded = true;\n    }\n\n    /**\n     * Retrieves a localised message.\n     * @param $key string identifier of message\n     * @return string localised message\n     */\n    public function getMessage($key) {\n        if (!$this->_loaded) $this->load();\n        if (!isset($this->messages[$key])) return \"[$key]\";\n        return $this->messages[$key];\n    }\n\n    /**\n     * Retrieves a localised error name.\n     * @param $int integer error number, corresponding to PHP's error\n     *             reporting\n     * @return string localised message\n     */\n    public function getErrorName($int) {\n        if (!$this->_loaded) $this->load();\n        if (!isset($this->errorNames[$int])) return \"[Error: $int]\";\n        return $this->errorNames[$int];\n    }\n\n    /**\n     * Converts an array list into a string readable representation\n     */\n    public function listify($array) {\n        $sep      = $this->getMessage('Item separator');\n        $sep_last = $this->getMessage('Item separator last');\n        $ret = '';\n        for ($i = 0, $c = count($array); $i < $c; $i++) {\n            if ($i == 0) {\n            } elseif ($i + 1 < $c) {\n                $ret .= $sep;\n            } else {\n                $ret .= $sep_last;\n            }\n            $ret .= $array[$i];\n        }\n        return $ret;\n    }\n\n    /**\n     * Formats a localised message with passed parameters\n     * @param $key string identifier of message\n     * @param $args Parameters to substitute in\n     * @return string localised message\n     * @todo Implement conditionals? Right now, some messages make\n     *     reference to line numbers, but those aren't always available\n     */\n    public function formatMessage($key, $args = array()) {\n        if (!$this->_loaded) $this->load();\n        if (!isset($this->messages[$key])) return \"[$key]\";\n        $raw = $this->messages[$key];\n        $subst = array();\n        $generator = false;\n        foreach ($args as $i => $value) {\n            if (is_object($value)) {\n                if ($value instanceof HTMLPurifier_Token) {\n                    // factor this out some time\n                    if (!$generator) $generator = $this->context->get('Generator');\n                    if (isset($value->name)) $subst['$'.$i.'.Name'] = $value->name;\n                    if (isset($value->data)) $subst['$'.$i.'.Data'] = $value->data;\n                    $subst['$'.$i.'.Compact'] =\n                    $subst['$'.$i.'.Serialized'] = $generator->generateFromToken($value);\n                    // a more complex algorithm for compact representation\n                    // could be introduced for all types of tokens. This\n                    // may need to be factored out into a dedicated class\n                    if (!empty($value->attr)) {\n                        $stripped_token = clone $value;\n                        $stripped_token->attr = array();\n                        $subst['$'.$i.'.Compact'] = $generator->generateFromToken($stripped_token);\n                    }\n                    $subst['$'.$i.'.Line'] = $value->line ? $value->line : 'unknown';\n                }\n                continue;\n            } elseif (is_array($value)) {\n                $keys = array_keys($value);\n                if (array_keys($keys) === $keys) {\n                    // list\n                    $subst['$'.$i] = $this->listify($value);\n                } else {\n                    // associative array\n                    // no $i implementation yet, sorry\n                    $subst['$'.$i.'.Keys'] = $this->listify($keys);\n                    $subst['$'.$i.'.Values'] = $this->listify(array_values($value));\n                }\n                continue;\n            }\n            $subst['$' . $i] = $value;\n        }\n        return strtr($raw, $subst);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/LanguageFactory.php",
    "content": "<?php\n\n/**\n * Class responsible for generating HTMLPurifier_Language objects, managing\n * caching and fallbacks.\n * @note Thanks to MediaWiki for the general logic, although this version\n *       has been entirely rewritten\n * @todo Serialized cache for languages\n */\nclass HTMLPurifier_LanguageFactory\n{\n\n    /**\n     * Cache of language code information used to load HTMLPurifier_Language objects\n     * Structure is: $factory->cache[$language_code][$key] = $value\n     * @value array map\n     */\n    public $cache;\n\n    /**\n     * Valid keys in the HTMLPurifier_Language object. Designates which\n     * variables to slurp out of a message file.\n     * @value array list\n     */\n    public $keys = array('fallback', 'messages', 'errorNames');\n\n    /**\n     * Instance of HTMLPurifier_AttrDef_Lang to validate language codes\n     * @value object HTMLPurifier_AttrDef_Lang\n     */\n    protected $validator;\n\n    /**\n     * Cached copy of dirname(__FILE__), directory of current file without\n     * trailing slash\n     * @value string filename\n     */\n    protected $dir;\n\n    /**\n     * Keys whose contents are a hash map and can be merged\n     * @value array lookup\n     */\n    protected $mergeable_keys_map = array('messages' => true, 'errorNames' => true);\n\n    /**\n     * Keys whose contents are a list and can be merged\n     * @value array lookup\n     */\n    protected $mergeable_keys_list = array();\n\n    /**\n     * Retrieve sole instance of the factory.\n     * @param $prototype Optional prototype to overload sole instance with,\n     *                   or bool true to reset to default factory.\n     */\n    public static function instance($prototype = null) {\n        static $instance = null;\n        if ($prototype !== null) {\n            $instance = $prototype;\n        } elseif ($instance === null || $prototype == true) {\n            $instance = new HTMLPurifier_LanguageFactory();\n            $instance->setup();\n        }\n        return $instance;\n    }\n\n    /**\n     * Sets up the singleton, much like a constructor\n     * @note Prevents people from getting this outside of the singleton\n     */\n    public function setup() {\n        $this->validator = new HTMLPurifier_AttrDef_Lang();\n        $this->dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier';\n    }\n\n    /**\n     * Creates a language object, handles class fallbacks\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     * @param $code Code to override configuration with. Private parameter.\n     */\n    public function create($config, $context, $code = false) {\n\n        // validate language code\n        if ($code === false) {\n            $code = $this->validator->validate(\n              $config->get('Core.Language'), $config, $context\n            );\n        } else {\n            $code = $this->validator->validate($code, $config, $context);\n        }\n        if ($code === false) $code = 'en'; // malformed code becomes English\n\n        $pcode = str_replace('-', '_', $code); // make valid PHP classname\n        static $depth = 0; // recursion protection\n\n        if ($code == 'en') {\n            $lang = new HTMLPurifier_Language($config, $context);\n        } else {\n            $class = 'HTMLPurifier_Language_' . $pcode;\n            $file  = $this->dir . '/Language/classes/' . $code . '.php';\n            if (file_exists($file) || class_exists($class, false)) {\n                $lang = new $class($config, $context);\n            } else {\n                // Go fallback\n                $raw_fallback = $this->getFallbackFor($code);\n                $fallback = $raw_fallback ? $raw_fallback : 'en';\n                $depth++;\n                $lang = $this->create($config, $context, $fallback);\n                if (!$raw_fallback) {\n                    $lang->error = true;\n                }\n                $depth--;\n            }\n        }\n\n        $lang->code = $code;\n\n        return $lang;\n\n    }\n\n    /**\n     * Returns the fallback language for language\n     * @note Loads the original language into cache\n     * @param $code string language code\n     */\n    public function getFallbackFor($code) {\n        $this->loadLanguage($code);\n        return $this->cache[$code]['fallback'];\n    }\n\n    /**\n     * Loads language into the cache, handles message file and fallbacks\n     * @param $code string language code\n     */\n    public function loadLanguage($code) {\n        static $languages_seen = array(); // recursion guard\n\n        // abort if we've already loaded it\n        if (isset($this->cache[$code])) return;\n\n        // generate filename\n        $filename = $this->dir . '/Language/messages/' . $code . '.php';\n\n        // default fallback : may be overwritten by the ensuing include\n        $fallback = ($code != 'en') ? 'en' : false;\n\n        // load primary localisation\n        if (!file_exists($filename)) {\n            // skip the include: will rely solely on fallback\n            $filename = $this->dir . '/Language/messages/en.php';\n            $cache = array();\n        } else {\n            include $filename;\n            $cache = compact($this->keys);\n        }\n\n        // load fallback localisation\n        if (!empty($fallback)) {\n\n            // infinite recursion guard\n            if (isset($languages_seen[$code])) {\n                trigger_error('Circular fallback reference in language ' .\n                    $code, E_USER_ERROR);\n                $fallback = 'en';\n            }\n            $language_seen[$code] = true;\n\n            // load the fallback recursively\n            $this->loadLanguage($fallback);\n            $fallback_cache = $this->cache[$fallback];\n\n            // merge fallback with current language\n            foreach ( $this->keys as $key ) {\n                if (isset($cache[$key]) && isset($fallback_cache[$key])) {\n                    if (isset($this->mergeable_keys_map[$key])) {\n                        $cache[$key] = $cache[$key] + $fallback_cache[$key];\n                    } elseif (isset($this->mergeable_keys_list[$key])) {\n                        $cache[$key] = array_merge( $fallback_cache[$key], $cache[$key] );\n                    }\n                } else {\n                    $cache[$key] = $fallback_cache[$key];\n                }\n            }\n\n        }\n\n        // save to cache for later retrieval\n        $this->cache[$code] = $cache;\n\n        return;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Length.php",
    "content": "<?php\n\n/**\n * Represents a measurable length, with a string numeric magnitude\n * and a unit. This object is immutable.\n */\nclass HTMLPurifier_Length\n{\n\n    /**\n     * String numeric magnitude.\n     */\n    protected $n;\n\n    /**\n     * String unit. False is permitted if $n = 0.\n     */\n    protected $unit;\n\n    /**\n     * Whether or not this length is valid. Null if not calculated yet.\n     */\n    protected $isValid;\n\n    /**\n     * Lookup array of units recognized by CSS 2.1\n     */\n    protected static $allowedUnits = array(\n        'em' => true, 'ex' => true, 'px' => true, 'in' => true,\n        'cm' => true, 'mm' => true, 'pt' => true, 'pc' => true\n    );\n\n    /**\n     * @param number $n Magnitude\n     * @param string $u Unit\n     */\n    public function __construct($n = '0', $u = false) {\n        $this->n = (string) $n;\n        $this->unit = $u !== false ? (string) $u : false;\n    }\n\n    /**\n     * @param string $s Unit string, like '2em' or '3.4in'\n     * @warning Does not perform validation.\n     */\n    static public function make($s) {\n        if ($s instanceof HTMLPurifier_Length) return $s;\n        $n_length = strspn($s, '1234567890.+-');\n        $n = substr($s, 0, $n_length);\n        $unit = substr($s, $n_length);\n        if ($unit === '') $unit = false;\n        return new HTMLPurifier_Length($n, $unit);\n    }\n\n    /**\n     * Validates the number and unit.\n     */\n    protected function validate() {\n        // Special case:\n        if ($this->n === '+0' || $this->n === '-0') $this->n = '0';\n        if ($this->n === '0' && $this->unit === false) return true;\n        if (!ctype_lower($this->unit)) $this->unit = strtolower($this->unit);\n        if (!isset(HTMLPurifier_Length::$allowedUnits[$this->unit])) return false;\n        // Hack:\n        $def = new HTMLPurifier_AttrDef_CSS_Number();\n        $result = $def->validate($this->n, false, false);\n        if ($result === false) return false;\n        $this->n = $result;\n        return true;\n    }\n\n    /**\n     * Returns string representation of number.\n     */\n    public function toString() {\n        if (!$this->isValid()) return false;\n        return $this->n . $this->unit;\n    }\n\n    /**\n     * Retrieves string numeric magnitude.\n     */\n    public function getN() {return $this->n;}\n\n    /**\n     * Retrieves string unit.\n     */\n    public function getUnit() {return $this->unit;}\n\n    /**\n     * Returns true if this length unit is valid.\n     */\n    public function isValid() {\n        if ($this->isValid === null) $this->isValid = $this->validate();\n        return $this->isValid;\n    }\n\n    /**\n     * Compares two lengths, and returns 1 if greater, -1 if less and 0 if equal.\n     * @warning If both values are too large or small, this calculation will\n     *          not work properly\n     */\n    public function compareTo($l) {\n        if ($l === false) return false;\n        if ($l->unit !== $this->unit) {\n            $converter = new HTMLPurifier_UnitConverter();\n            $l = $converter->convert($l, $this->unit);\n            if ($l === false) return false;\n        }\n        return $this->n - $l->n;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Lexer/DOMLex.php",
    "content": "<?php\n\n/**\n * Parser that uses PHP 5's DOM extension (part of the core).\n *\n * In PHP 5, the DOM XML extension was revamped into DOM and added to the core.\n * It gives us a forgiving HTML parser, which we use to transform the HTML\n * into a DOM, and then into the tokens.  It is blazingly fast (for large\n * documents, it performs twenty times faster than\n * HTMLPurifier_Lexer_DirectLex,and is the default choice for PHP 5.\n *\n * @note Any empty elements will have empty tokens associated with them, even if\n * this is prohibited by the spec. This is cannot be fixed until the spec\n * comes into play.\n *\n * @note PHP's DOM extension does not actually parse any entities, we use\n *       our own function to do that.\n *\n * @warning DOM tends to drop whitespace, which may wreak havoc on indenting.\n *          If this is a huge problem, due to the fact that HTML is hand\n *          edited and you are unable to get a parser cache that caches the\n *          the output of HTML Purifier while keeping the original HTML lying\n *          around, you may want to run Tidy on the resulting output or use\n *          HTMLPurifier_DirectLex\n */\n\nclass HTMLPurifier_Lexer_DOMLex extends HTMLPurifier_Lexer\n{\n\n    private $factory;\n\n    public function __construct() {\n        // setup the factory\n        parent::__construct();\n        $this->factory = new HTMLPurifier_TokenFactory();\n    }\n\n    public function tokenizeHTML($html, $config, $context) {\n\n        $html = $this->normalize($html, $config, $context);\n\n        // attempt to armor stray angled brackets that cannot possibly\n        // form tags and thus are probably being used as emoticons\n        if ($config->get('Core.AggressivelyFixLt')) {\n            $char = '[^a-z!\\/]';\n            $comment = \"/<!--(.*?)(-->|\\z)/is\";\n            $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html);\n            do {\n                $old = $html;\n                $html = preg_replace(\"/<($char)/i\", '&lt;\\\\1', $html);\n            } while ($html !== $old);\n            $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments\n        }\n\n        // preprocess html, essential for UTF-8\n        $html = $this->wrapHTML($html, $config, $context);\n\n        $doc = new DOMDocument();\n        $doc->encoding = 'UTF-8'; // theoretically, the above has this covered\n\n        set_error_handler(array($this, 'muteErrorHandler'));\n        $doc->loadHTML($html);\n        restore_error_handler();\n\n        $tokens = array();\n        $this->tokenizeDOM(\n            $doc->getElementsByTagName('html')->item(0)-> // <html>\n                  getElementsByTagName('body')->item(0)-> //   <body>\n                  getElementsByTagName('div')->item(0)    //     <div>\n            , $tokens);\n        return $tokens;\n    }\n\n    /**\n     * Recursive function that tokenizes a node, putting it into an accumulator.\n     *\n     * @param $node     DOMNode to be tokenized.\n     * @param $tokens   Array-list of already tokenized tokens.\n     * @param $collect  Says whether or start and close are collected, set to\n     *                  false at first recursion because it's the implicit DIV\n     *                  tag you're dealing with.\n     * @returns Tokens of node appended to previously passed tokens.\n     */\n    protected function tokenizeDOM($node, &$tokens, $collect = false) {\n\n        // intercept non element nodes. WE MUST catch all of them,\n        // but we're not getting the character reference nodes because\n        // those should have been preprocessed\n        if ($node->nodeType === XML_TEXT_NODE) {\n            $tokens[] = $this->factory->createText($node->data);\n            return;\n        } elseif ($node->nodeType === XML_CDATA_SECTION_NODE) {\n            // undo libxml's special treatment of <script> and <style> tags\n            $last = end($tokens);\n            $data = $node->data;\n            // (note $node->tagname is already normalized)\n            if ($last instanceof HTMLPurifier_Token_Start && ($last->name == 'script' || $last->name == 'style')) {\n                $new_data = trim($data);\n                if (substr($new_data, 0, 4) === '<!--') {\n                    $data = substr($new_data, 4);\n                    if (substr($data, -3) === '-->') {\n                        $data = substr($data, 0, -3);\n                    } else {\n                        // Highly suspicious! Not sure what to do...\n                    }\n                }\n            }\n            $tokens[] = $this->factory->createText($this->parseData($data));\n            return;\n        } elseif ($node->nodeType === XML_COMMENT_NODE) {\n            // this is code is only invoked for comments in script/style in versions\n            // of libxml pre-2.6.28 (regular comments, of course, are still\n            // handled regularly)\n            $tokens[] = $this->factory->createComment($node->data);\n            return;\n        } elseif (\n            // not-well tested: there may be other nodes we have to grab\n            $node->nodeType !== XML_ELEMENT_NODE\n        ) {\n            return;\n        }\n\n        $attr = $node->hasAttributes() ?\n            $this->transformAttrToAssoc($node->attributes) :\n            array();\n\n        // We still have to make sure that the element actually IS empty\n        if (!$node->childNodes->length) {\n            if ($collect) {\n                $tokens[] = $this->factory->createEmpty($node->tagName, $attr);\n            }\n        } else {\n            if ($collect) { // don't wrap on first iteration\n                $tokens[] = $this->factory->createStart(\n                    $tag_name = $node->tagName, // somehow, it get's dropped\n                    $attr\n                );\n            }\n            foreach ($node->childNodes as $node) {\n                // remember, it's an accumulator. Otherwise, we'd have\n                // to use array_merge\n                $this->tokenizeDOM($node, $tokens, true);\n            }\n            if ($collect) {\n                $tokens[] = $this->factory->createEnd($tag_name);\n            }\n        }\n\n    }\n\n    /**\n     * Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.\n     *\n     * @param $attribute_list DOMNamedNodeMap of DOMAttr objects.\n     * @returns Associative array of attributes.\n     */\n    protected function transformAttrToAssoc($node_map) {\n        // NamedNodeMap is documented very well, so we're using undocumented\n        // features, namely, the fact that it implements Iterator and\n        // has a ->length attribute\n        if ($node_map->length === 0) return array();\n        $array = array();\n        foreach ($node_map as $attr) {\n            $array[$attr->name] = $attr->value;\n        }\n        return $array;\n    }\n\n    /**\n     * An error handler that mutes all errors\n     */\n    public function muteErrorHandler($errno, $errstr) {}\n\n    /**\n     * Callback function for undoing escaping of stray angled brackets\n     * in comments\n     */\n    public function callbackUndoCommentSubst($matches) {\n        return '<!--' . strtr($matches[1], array('&amp;'=>'&','&lt;'=>'<')) . $matches[2];\n    }\n\n    /**\n     * Callback function that entity-izes ampersands in comments so that\n     * callbackUndoCommentSubst doesn't clobber them\n     */\n    public function callbackArmorCommentEntities($matches) {\n        return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];\n    }\n\n    /**\n     * Wraps an HTML fragment in the necessary HTML\n     */\n    protected function wrapHTML($html, $config, $context) {\n        $def = $config->getDefinition('HTML');\n        $ret = '';\n\n        if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {\n            $ret .= '<!DOCTYPE html ';\n            if (!empty($def->doctype->dtdPublic)) $ret .= 'PUBLIC \"' . $def->doctype->dtdPublic . '\" ';\n            if (!empty($def->doctype->dtdSystem)) $ret .= '\"' . $def->doctype->dtdSystem . '\" ';\n            $ret .= '>';\n        }\n\n        $ret .= '<html><head>';\n        $ret .= '<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />';\n        // No protection if $html contains a stray </div>!\n        $ret .= '</head><body><div>'.$html.'</div></body></html>';\n        return $ret;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Lexer/DirectLex.php",
    "content": "<?php\n\n/**\n * Our in-house implementation of a parser.\n *\n * A pure PHP parser, DirectLex has absolutely no dependencies, making\n * it a reasonably good default for PHP4.  Written with efficiency in mind,\n * it can be four times faster than HTMLPurifier_Lexer_PEARSax3, although it\n * pales in comparison to HTMLPurifier_Lexer_DOMLex.\n *\n * @todo Reread XML spec and document differences.\n */\nclass HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer\n{\n\n    public $tracksLineNumbers = true;\n\n    /**\n     * Whitespace characters for str(c)spn.\n     */\n    protected $_whitespace = \"\\x20\\x09\\x0D\\x0A\";\n\n    /**\n     * Callback function for script CDATA fudge\n     * @param $matches, in form of array(opening tag, contents, closing tag)\n     */\n    protected function scriptCallback($matches) {\n        return $matches[1] . htmlspecialchars($matches[2], ENT_COMPAT, 'UTF-8') . $matches[3];\n    }\n\n    public function tokenizeHTML($html, $config, $context) {\n\n        // special normalization for script tags without any armor\n        // our \"armor\" heurstic is a < sign any number of whitespaces after\n        // the first script tag\n        if ($config->get('HTML.Trusted')) {\n            $html = preg_replace_callback('#(<script[^>]*>)(\\s*[^<].+?)(</script>)#si',\n                array($this, 'scriptCallback'), $html);\n        }\n\n        $html = $this->normalize($html, $config, $context);\n\n        $cursor = 0; // our location in the text\n        $inside_tag = false; // whether or not we're parsing the inside of a tag\n        $array = array(); // result array\n\n        // This is also treated to mean maintain *column* numbers too\n        $maintain_line_numbers = $config->get('Core.MaintainLineNumbers');\n\n        if ($maintain_line_numbers === null) {\n            // automatically determine line numbering by checking\n            // if error collection is on\n            $maintain_line_numbers = $config->get('Core.CollectErrors');\n        }\n\n        if ($maintain_line_numbers) {\n            $current_line = 1;\n            $current_col  = 0;\n            $length = strlen($html);\n        } else {\n            $current_line = false;\n            $current_col  = false;\n            $length = false;\n        }\n        $context->register('CurrentLine', $current_line);\n        $context->register('CurrentCol',  $current_col);\n        $nl = \"\\n\";\n        // how often to manually recalculate. This will ALWAYS be right,\n        // but it's pretty wasteful. Set to 0 to turn off\n        $synchronize_interval = $config->get('Core.DirectLexLineNumberSyncInterval');\n\n        $e = false;\n        if ($config->get('Core.CollectErrors')) {\n            $e =& $context->get('ErrorCollector');\n        }\n\n        // for testing synchronization\n        $loops = 0;\n\n        while(++$loops) {\n\n            // $cursor is either at the start of a token, or inside of\n            // a tag (i.e. there was a < immediately before it), as indicated\n            // by $inside_tag\n\n            if ($maintain_line_numbers) {\n\n                // $rcursor, however, is always at the start of a token.\n                $rcursor = $cursor - (int) $inside_tag;\n\n                // Column number is cheap, so we calculate it every round.\n                // We're interested at the *end* of the newline string, so\n                // we need to add strlen($nl) == 1 to $nl_pos before subtracting it\n                // from our \"rcursor\" position.\n                $nl_pos = strrpos($html, $nl, $rcursor - $length);\n                $current_col = $rcursor - (is_bool($nl_pos) ? 0 : $nl_pos + 1);\n\n                // recalculate lines\n                if (\n                    $synchronize_interval &&  // synchronization is on\n                    $cursor > 0 &&            // cursor is further than zero\n                    $loops % $synchronize_interval === 0 // time to synchronize!\n                ) {\n                    $current_line = 1 + $this->substrCount($html, $nl, 0, $cursor);\n                }\n\n            }\n\n            $position_next_lt = strpos($html, '<', $cursor);\n            $position_next_gt = strpos($html, '>', $cursor);\n\n            // triggers on \"<b>asdf</b>\" but not \"asdf <b></b>\"\n            // special case to set up context\n            if ($position_next_lt === $cursor) {\n                $inside_tag = true;\n                $cursor++;\n            }\n\n            if (!$inside_tag && $position_next_lt !== false) {\n                // We are not inside tag and there still is another tag to parse\n                $token = new\n                    HTMLPurifier_Token_Text(\n                        $this->parseData(\n                            substr(\n                                $html, $cursor, $position_next_lt - $cursor\n                            )\n                        )\n                    );\n                if ($maintain_line_numbers) {\n                    $token->rawPosition($current_line, $current_col);\n                    $current_line += $this->substrCount($html, $nl, $cursor, $position_next_lt - $cursor);\n                }\n                $array[] = $token;\n                $cursor  = $position_next_lt + 1;\n                $inside_tag = true;\n                continue;\n            } elseif (!$inside_tag) {\n                // We are not inside tag but there are no more tags\n                // If we're already at the end, break\n                if ($cursor === strlen($html)) break;\n                // Create Text of rest of string\n                $token = new\n                    HTMLPurifier_Token_Text(\n                        $this->parseData(\n                            substr(\n                                $html, $cursor\n                            )\n                        )\n                    );\n                if ($maintain_line_numbers) $token->rawPosition($current_line, $current_col);\n                $array[] = $token;\n                break;\n            } elseif ($inside_tag && $position_next_gt !== false) {\n                // We are in tag and it is well formed\n                // Grab the internals of the tag\n                $strlen_segment = $position_next_gt - $cursor;\n\n                if ($strlen_segment < 1) {\n                    // there's nothing to process!\n                    $token = new HTMLPurifier_Token_Text('<');\n                    $cursor++;\n                    continue;\n                }\n\n                $segment = substr($html, $cursor, $strlen_segment);\n\n                if ($segment === false) {\n                    // somehow, we attempted to access beyond the end of\n                    // the string, defense-in-depth, reported by Nate Abele\n                    break;\n                }\n\n                // Check if it's a comment\n                if (\n                    substr($segment, 0, 3) === '!--'\n                ) {\n                    // re-determine segment length, looking for -->\n                    $position_comment_end = strpos($html, '-->', $cursor);\n                    if ($position_comment_end === false) {\n                        // uh oh, we have a comment that extends to\n                        // infinity. Can't be helped: set comment\n                        // end position to end of string\n                        if ($e) $e->send(E_WARNING, 'Lexer: Unclosed comment');\n                        $position_comment_end = strlen($html);\n                        $end = true;\n                    } else {\n                        $end = false;\n                    }\n                    $strlen_segment = $position_comment_end - $cursor;\n                    $segment = substr($html, $cursor, $strlen_segment);\n                    $token = new\n                        HTMLPurifier_Token_Comment(\n                            substr(\n                                $segment, 3, $strlen_segment - 3\n                            )\n                        );\n                    if ($maintain_line_numbers) {\n                        $token->rawPosition($current_line, $current_col);\n                        $current_line += $this->substrCount($html, $nl, $cursor, $strlen_segment);\n                    }\n                    $array[] = $token;\n                    $cursor = $end ? $position_comment_end : $position_comment_end + 3;\n                    $inside_tag = false;\n                    continue;\n                }\n\n                // Check if it's an end tag\n                $is_end_tag = (strpos($segment,'/') === 0);\n                if ($is_end_tag) {\n                    $type = substr($segment, 1);\n                    $token = new HTMLPurifier_Token_End($type);\n                    if ($maintain_line_numbers) {\n                        $token->rawPosition($current_line, $current_col);\n                        $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);\n                    }\n                    $array[] = $token;\n                    $inside_tag = false;\n                    $cursor = $position_next_gt + 1;\n                    continue;\n                }\n\n                // Check leading character is alnum, if not, we may\n                // have accidently grabbed an emoticon. Translate into\n                // text and go our merry way\n                if (!ctype_alpha($segment[0])) {\n                    // XML:  $segment[0] !== '_' && $segment[0] !== ':'\n                    if ($e) $e->send(E_NOTICE, 'Lexer: Unescaped lt');\n                    $token = new HTMLPurifier_Token_Text('<');\n                    if ($maintain_line_numbers) {\n                        $token->rawPosition($current_line, $current_col);\n                        $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);\n                    }\n                    $array[] = $token;\n                    $inside_tag = false;\n                    continue;\n                }\n\n                // Check if it is explicitly self closing, if so, remove\n                // trailing slash. Remember, we could have a tag like <br>, so\n                // any later token processing scripts must convert improperly\n                // classified EmptyTags from StartTags.\n                $is_self_closing = (strrpos($segment,'/') === $strlen_segment-1);\n                if ($is_self_closing) {\n                    $strlen_segment--;\n                    $segment = substr($segment, 0, $strlen_segment);\n                }\n\n                // Check if there are any attributes\n                $position_first_space = strcspn($segment, $this->_whitespace);\n\n                if ($position_first_space >= $strlen_segment) {\n                    if ($is_self_closing) {\n                        $token = new HTMLPurifier_Token_Empty($segment);\n                    } else {\n                        $token = new HTMLPurifier_Token_Start($segment);\n                    }\n                    if ($maintain_line_numbers) {\n                        $token->rawPosition($current_line, $current_col);\n                        $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);\n                    }\n                    $array[] = $token;\n                    $inside_tag = false;\n                    $cursor = $position_next_gt + 1;\n                    continue;\n                }\n\n                // Grab out all the data\n                $type = substr($segment, 0, $position_first_space);\n                $attribute_string =\n                    trim(\n                        substr(\n                            $segment, $position_first_space\n                        )\n                    );\n                if ($attribute_string) {\n                    $attr = $this->parseAttributeString(\n                                    $attribute_string\n                                  , $config, $context\n                              );\n                } else {\n                    $attr = array();\n                }\n\n                if ($is_self_closing) {\n                    $token = new HTMLPurifier_Token_Empty($type, $attr);\n                } else {\n                    $token = new HTMLPurifier_Token_Start($type, $attr);\n                }\n                if ($maintain_line_numbers) {\n                    $token->rawPosition($current_line, $current_col);\n                    $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);\n                }\n                $array[] = $token;\n                $cursor = $position_next_gt + 1;\n                $inside_tag = false;\n                continue;\n            } else {\n                // inside tag, but there's no ending > sign\n                if ($e) $e->send(E_WARNING, 'Lexer: Missing gt');\n                $token = new\n                    HTMLPurifier_Token_Text(\n                        '<' .\n                        $this->parseData(\n                            substr($html, $cursor)\n                        )\n                    );\n                if ($maintain_line_numbers) $token->rawPosition($current_line, $current_col);\n                // no cursor scroll? Hmm...\n                $array[] = $token;\n                break;\n            }\n            break;\n        }\n\n        $context->destroy('CurrentLine');\n        $context->destroy('CurrentCol');\n        return $array;\n    }\n\n    /**\n     * PHP 5.0.x compatible substr_count that implements offset and length\n     */\n    protected function substrCount($haystack, $needle, $offset, $length) {\n        static $oldVersion;\n        if ($oldVersion === null) {\n            $oldVersion = version_compare(PHP_VERSION, '5.1', '<');\n        }\n        if ($oldVersion) {\n            $haystack = substr($haystack, $offset, $length);\n            return substr_count($haystack, $needle);\n        } else {\n            return substr_count($haystack, $needle, $offset, $length);\n        }\n    }\n\n    /**\n     * Takes the inside of an HTML tag and makes an assoc array of attributes.\n     *\n     * @param $string Inside of tag excluding name.\n     * @returns Assoc array of attributes.\n     */\n    public function parseAttributeString($string, $config, $context) {\n        $string = (string) $string; // quick typecast\n\n        if ($string == '') return array(); // no attributes\n\n        $e = false;\n        if ($config->get('Core.CollectErrors')) {\n            $e =& $context->get('ErrorCollector');\n        }\n\n        // let's see if we can abort as quickly as possible\n        // one equal sign, no spaces => one attribute\n        $num_equal = substr_count($string, '=');\n        $has_space = strpos($string, ' ');\n        if ($num_equal === 0 && !$has_space) {\n            // bool attribute\n            return array($string => $string);\n        } elseif ($num_equal === 1 && !$has_space) {\n            // only one attribute\n            list($key, $quoted_value) = explode('=', $string);\n            $quoted_value = trim($quoted_value);\n            if (!$key) {\n                if ($e) $e->send(E_ERROR, 'Lexer: Missing attribute key');\n                return array();\n            }\n            if (!$quoted_value) return array($key => '');\n            $first_char = @$quoted_value[0];\n            $last_char  = @$quoted_value[strlen($quoted_value)-1];\n\n            $same_quote = ($first_char == $last_char);\n            $open_quote = ($first_char == '\"' || $first_char == \"'\");\n\n            if ( $same_quote && $open_quote) {\n                // well behaved\n                $value = substr($quoted_value, 1, strlen($quoted_value) - 2);\n            } else {\n                // not well behaved\n                if ($open_quote) {\n                    if ($e) $e->send(E_ERROR, 'Lexer: Missing end quote');\n                    $value = substr($quoted_value, 1);\n                } else {\n                    $value = $quoted_value;\n                }\n            }\n            if ($value === false) $value = '';\n            return array($key => $value);\n        }\n\n        // setup loop environment\n        $array  = array(); // return assoc array of attributes\n        $cursor = 0; // current position in string (moves forward)\n        $size   = strlen($string); // size of the string (stays the same)\n\n        // if we have unquoted attributes, the parser expects a terminating\n        // space, so let's guarantee that there's always a terminating space.\n        $string .= ' ';\n\n        while(true) {\n\n            if ($cursor >= $size) {\n                break;\n            }\n\n            $cursor += ($value = strspn($string, $this->_whitespace, $cursor));\n            // grab the key\n\n            $key_begin = $cursor; //we're currently at the start of the key\n\n            // scroll past all characters that are the key (not whitespace or =)\n            $cursor += strcspn($string, $this->_whitespace . '=', $cursor);\n\n            $key_end = $cursor; // now at the end of the key\n\n            $key = substr($string, $key_begin, $key_end - $key_begin);\n\n            if (!$key) {\n                if ($e) $e->send(E_ERROR, 'Lexer: Missing attribute key');\n                $cursor += strcspn($string, $this->_whitespace, $cursor + 1); // prevent infinite loop\n                continue; // empty key\n            }\n\n            // scroll past all whitespace\n            $cursor += strspn($string, $this->_whitespace, $cursor);\n\n            if ($cursor >= $size) {\n                $array[$key] = $key;\n                break;\n            }\n\n            // if the next character is an equal sign, we've got a regular\n            // pair, otherwise, it's a bool attribute\n            $first_char = @$string[$cursor];\n\n            if ($first_char == '=') {\n                // key=\"value\"\n\n                $cursor++;\n                $cursor += strspn($string, $this->_whitespace, $cursor);\n\n                if ($cursor === false) {\n                    $array[$key] = '';\n                    break;\n                }\n\n                // we might be in front of a quote right now\n\n                $char = @$string[$cursor];\n\n                if ($char == '\"' || $char == \"'\") {\n                    // it's quoted, end bound is $char\n                    $cursor++;\n                    $value_begin = $cursor;\n                    $cursor = strpos($string, $char, $cursor);\n                    $value_end = $cursor;\n                } else {\n                    // it's not quoted, end bound is whitespace\n                    $value_begin = $cursor;\n                    $cursor += strcspn($string, $this->_whitespace, $cursor);\n                    $value_end = $cursor;\n                }\n\n                // we reached a premature end\n                if ($cursor === false) {\n                    $cursor = $size;\n                    $value_end = $cursor;\n                }\n\n                $value = substr($string, $value_begin, $value_end - $value_begin);\n                if ($value === false) $value = '';\n                $array[$key] = $this->parseData($value);\n                $cursor++;\n\n            } else {\n                // boolattr\n                if ($key !== '') {\n                    $array[$key] = $key;\n                } else {\n                    // purely theoretical\n                    if ($e) $e->send(E_ERROR, 'Lexer: Missing attribute key');\n                }\n\n            }\n        }\n        return $array;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Lexer/PEARSax3.php",
    "content": "<?php\n\n/**\n * Proof-of-concept lexer that uses the PEAR package XML_HTMLSax3 to parse HTML.\n *\n * PEAR, not suprisingly, also has a SAX parser for HTML.  I don't know\n * very much about implementation, but it's fairly well written.  However, that\n * abstraction comes at a price: performance. You need to have it installed,\n * and if the API changes, it might break our adapter. Not sure whether or not\n * it's UTF-8 aware, but it has some entity parsing trouble (in all areas,\n * text and attributes).\n *\n * Quite personally, I don't recommend using the PEAR class, and the defaults\n * don't use it. The unit tests do perform the tests on the SAX parser too, but\n * whatever it does for poorly formed HTML is up to it.\n *\n * @todo Generalize so that XML_HTMLSax is also supported.\n *\n * @warning Entity-resolution inside attributes is broken.\n */\n\nclass HTMLPurifier_Lexer_PEARSax3 extends HTMLPurifier_Lexer\n{\n\n    /**\n     * Internal accumulator array for SAX parsers.\n     */\n    protected $tokens = array();\n\n    public function tokenizeHTML($string, $config, $context) {\n\n        $this->tokens = array();\n\n        $string = $this->normalize($string, $config, $context);\n\n        $parser = new XML_HTMLSax3();\n        $parser->set_object($this);\n        $parser->set_element_handler('openHandler','closeHandler');\n        $parser->set_data_handler('dataHandler');\n        $parser->set_escape_handler('escapeHandler');\n\n        // doesn't seem to work correctly for attributes\n        $parser->set_option('XML_OPTION_ENTITIES_PARSED', 1);\n\n        $parser->parse($string);\n\n        return $this->tokens;\n\n    }\n\n    /**\n     * Open tag event handler, interface is defined by PEAR package.\n     */\n    public function openHandler(&$parser, $name, $attrs, $closed) {\n        // entities are not resolved in attrs\n        foreach ($attrs as $key => $attr) {\n            $attrs[$key] = $this->parseData($attr);\n        }\n        if ($closed) {\n            $this->tokens[] = new HTMLPurifier_Token_Empty($name, $attrs);\n        } else {\n            $this->tokens[] = new HTMLPurifier_Token_Start($name, $attrs);\n        }\n        return true;\n    }\n\n    /**\n     * Close tag event handler, interface is defined by PEAR package.\n     */\n    public function closeHandler(&$parser, $name) {\n        // HTMLSax3 seems to always send empty tags an extra close tag\n        // check and ignore if you see it:\n        // [TESTME] to make sure it doesn't overreach\n        if ($this->tokens[count($this->tokens)-1] instanceof HTMLPurifier_Token_Empty) {\n            return true;\n        }\n        $this->tokens[] = new HTMLPurifier_Token_End($name);\n        return true;\n    }\n\n    /**\n     * Data event handler, interface is defined by PEAR package.\n     */\n    public function dataHandler(&$parser, $data) {\n        $this->tokens[] = new HTMLPurifier_Token_Text($data);\n        return true;\n    }\n\n    /**\n     * Escaped text handler, interface is defined by PEAR package.\n     */\n    public function escapeHandler(&$parser, $data) {\n        if (strpos($data, '--') === 0) {\n            $this->tokens[] = new HTMLPurifier_Token_Comment($data);\n        }\n        // CDATA is handled elsewhere, but if it was handled here:\n        //if (strpos($data, '[CDATA[') === 0) {\n        //    $this->tokens[] = new HTMLPurifier_Token_Text(\n        //        substr($data, 7, strlen($data) - 9) );\n        //}\n        return true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Lexer/PH5P.php",
    "content": "<?php\n\n/**\n * Experimental HTML5-based parser using Jeroen van der Meer's PH5P library.\n * Occupies space in the HTML5 pseudo-namespace, which may cause conflicts.\n * \n * @note\n *    Recent changes to PHP's DOM extension have resulted in some fatal\n *    error conditions with the original version of PH5P. Pending changes,\n *    this lexer will punt to DirectLex if DOM throughs an exception.\n */\n\nclass HTMLPurifier_Lexer_PH5P extends HTMLPurifier_Lexer_DOMLex {\n    \n    public function tokenizeHTML($html, $config, $context) {\n        $new_html = $this->normalize($html, $config, $context);\n        $new_html = $this->wrapHTML($new_html, $config, $context);\n        try {\n            $parser = new HTML5($new_html);\n            $doc = $parser->save();\n        } catch (DOMException $e) {\n            // Uh oh, it failed. Punt to DirectLex.\n            $lexer = new HTMLPurifier_Lexer_DirectLex();\n            $context->register('PH5PError', $e); // save the error, so we can detect it\n            return $lexer->tokenizeHTML($html, $config, $context); // use original HTML\n        }\n        $tokens = array();\n        $this->tokenizeDOM(\n            $doc->getElementsByTagName('html')->item(0)-> // <html>\n                  getElementsByTagName('body')->item(0)-> //   <body>\n                  getElementsByTagName('div')->item(0)    //     <div>\n            , $tokens);\n        return $tokens;\n    }\n    \n}\n\n/*\n\nCopyright 2007 Jeroen van der Meer <http://jero.net/> \n\nPermission is hereby granted, free of charge, to any person obtaining a \ncopy of this software and associated documentation files (the \n\"Software\"), to deal in the Software without restriction, including \nwithout limitation the rights to use, copy, modify, merge, publish, \ndistribute, sublicense, and/or sell copies of the Software, and to \npermit persons to whom the Software is furnished to do so, subject to \nthe following conditions: \n\nThe above copyright notice and this permission notice shall be included \nin all copies or substantial portions of the Software. \n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS \nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY \nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE \nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \n\n*/\n\nclass HTML5 {\n    private $data;\n    private $char;\n    private $EOF;\n    private $state;\n    private $tree;\n    private $token;\n    private $content_model;\n    private $escape = false;\n    private $entities = array('AElig;','AElig','AMP;','AMP','Aacute;','Aacute',\n    'Acirc;','Acirc','Agrave;','Agrave','Alpha;','Aring;','Aring','Atilde;',\n    'Atilde','Auml;','Auml','Beta;','COPY;','COPY','Ccedil;','Ccedil','Chi;',\n    'Dagger;','Delta;','ETH;','ETH','Eacute;','Eacute','Ecirc;','Ecirc','Egrave;',\n    'Egrave','Epsilon;','Eta;','Euml;','Euml','GT;','GT','Gamma;','Iacute;',\n    'Iacute','Icirc;','Icirc','Igrave;','Igrave','Iota;','Iuml;','Iuml','Kappa;',\n    'LT;','LT','Lambda;','Mu;','Ntilde;','Ntilde','Nu;','OElig;','Oacute;',\n    'Oacute','Ocirc;','Ocirc','Ograve;','Ograve','Omega;','Omicron;','Oslash;',\n    'Oslash','Otilde;','Otilde','Ouml;','Ouml','Phi;','Pi;','Prime;','Psi;',\n    'QUOT;','QUOT','REG;','REG','Rho;','Scaron;','Sigma;','THORN;','THORN',\n    'TRADE;','Tau;','Theta;','Uacute;','Uacute','Ucirc;','Ucirc','Ugrave;',\n    'Ugrave','Upsilon;','Uuml;','Uuml','Xi;','Yacute;','Yacute','Yuml;','Zeta;',\n    'aacute;','aacute','acirc;','acirc','acute;','acute','aelig;','aelig',\n    'agrave;','agrave','alefsym;','alpha;','amp;','amp','and;','ang;','apos;',\n    'aring;','aring','asymp;','atilde;','atilde','auml;','auml','bdquo;','beta;',\n    'brvbar;','brvbar','bull;','cap;','ccedil;','ccedil','cedil;','cedil',\n    'cent;','cent','chi;','circ;','clubs;','cong;','copy;','copy','crarr;',\n    'cup;','curren;','curren','dArr;','dagger;','darr;','deg;','deg','delta;',\n    'diams;','divide;','divide','eacute;','eacute','ecirc;','ecirc','egrave;',\n    'egrave','empty;','emsp;','ensp;','epsilon;','equiv;','eta;','eth;','eth',\n    'euml;','euml','euro;','exist;','fnof;','forall;','frac12;','frac12',\n    'frac14;','frac14','frac34;','frac34','frasl;','gamma;','ge;','gt;','gt',\n    'hArr;','harr;','hearts;','hellip;','iacute;','iacute','icirc;','icirc',\n    'iexcl;','iexcl','igrave;','igrave','image;','infin;','int;','iota;',\n    'iquest;','iquest','isin;','iuml;','iuml','kappa;','lArr;','lambda;','lang;',\n    'laquo;','laquo','larr;','lceil;','ldquo;','le;','lfloor;','lowast;','loz;',\n    'lrm;','lsaquo;','lsquo;','lt;','lt','macr;','macr','mdash;','micro;','micro',\n    'middot;','middot','minus;','mu;','nabla;','nbsp;','nbsp','ndash;','ne;',\n    'ni;','not;','not','notin;','nsub;','ntilde;','ntilde','nu;','oacute;',\n    'oacute','ocirc;','ocirc','oelig;','ograve;','ograve','oline;','omega;',\n    'omicron;','oplus;','or;','ordf;','ordf','ordm;','ordm','oslash;','oslash',\n    'otilde;','otilde','otimes;','ouml;','ouml','para;','para','part;','permil;',\n    'perp;','phi;','pi;','piv;','plusmn;','plusmn','pound;','pound','prime;',\n    'prod;','prop;','psi;','quot;','quot','rArr;','radic;','rang;','raquo;',\n    'raquo','rarr;','rceil;','rdquo;','real;','reg;','reg','rfloor;','rho;',\n    'rlm;','rsaquo;','rsquo;','sbquo;','scaron;','sdot;','sect;','sect','shy;',\n    'shy','sigma;','sigmaf;','sim;','spades;','sub;','sube;','sum;','sup1;',\n    'sup1','sup2;','sup2','sup3;','sup3','sup;','supe;','szlig;','szlig','tau;',\n    'there4;','theta;','thetasym;','thinsp;','thorn;','thorn','tilde;','times;',\n    'times','trade;','uArr;','uacute;','uacute','uarr;','ucirc;','ucirc',\n    'ugrave;','ugrave','uml;','uml','upsih;','upsilon;','uuml;','uuml','weierp;',\n    'xi;','yacute;','yacute','yen;','yen','yuml;','yuml','zeta;','zwj;','zwnj;');\n\n    const PCDATA    = 0;\n    const RCDATA    = 1;\n    const CDATA     = 2;\n    const PLAINTEXT = 3;\n\n    const DOCTYPE  = 0;\n    const STARTTAG = 1;\n    const ENDTAG   = 2;\n    const COMMENT  = 3;\n    const CHARACTR = 4;\n    const EOF      = 5;\n\n    public function __construct($data) {\n        $data = str_replace(\"\\r\\n\", \"\\n\", $data);\n        $data = str_replace(\"\\r\", null, $data);\n\n        $this->data = $data;\n        $this->char = -1;\n        $this->EOF  = strlen($data);\n        $this->tree = new HTML5TreeConstructer;\n        $this->content_model = self::PCDATA;\n\n        $this->state = 'data';\n\n        while($this->state !== null) {\n            $this->{$this->state.'State'}();\n        }\n    }\n\n    public function save() {\n        return $this->tree->save();\n    }\n\n    private function char() {\n        return ($this->char < $this->EOF)\n            ? $this->data[$this->char]\n            : false;\n    }\n\n    private function character($s, $l = 0) {\n        if($s + $l < $this->EOF) {\n            if($l === 0) {\n                return $this->data[$s];\n            } else {\n                return substr($this->data, $s, $l);\n            }\n        }\n    }\n\n    private function characters($char_class, $start) {\n        return preg_replace('#^(['.$char_class.']+).*#s', '\\\\1', substr($this->data, $start));\n    }\n\n    private function dataState() {\n        // Consume the next input character\n        $this->char++;\n        $char = $this->char();\n\n        if($char === '&' && ($this->content_model === self::PCDATA || $this->content_model === self::RCDATA)) {\n            /* U+0026 AMPERSAND (&)\n            When the content model flag is set to one of the PCDATA or RCDATA\n            states: switch to the entity data state. Otherwise: treat it as per\n            the \"anything else\"    entry below. */\n            $this->state = 'entityData';\n\n        } elseif($char === '-') {\n            /* If the content model flag is set to either the RCDATA state or\n            the CDATA state, and the escape flag is false, and there are at\n            least three characters before this one in the input stream, and the\n            last four characters in the input stream, including this one, are\n            U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS,\n            and U+002D HYPHEN-MINUS (\"<!--\"), then set the escape flag to true. */\n            if(($this->content_model === self::RCDATA || $this->content_model ===\n            self::CDATA) && $this->escape === false &&\n            $this->char >= 3 && $this->character($this->char - 4, 4) === '<!--') {\n                $this->escape = true;\n            }\n\n            /* In any case, emit the input character as a character token. Stay\n            in the data state. */\n            $this->emitToken(array(\n                'type' => self::CHARACTR,\n                'data' => $char\n            ));\n\n        /* U+003C LESS-THAN SIGN (<) */\n        } elseif($char === '<' && ($this->content_model === self::PCDATA ||\n        (($this->content_model === self::RCDATA ||\n        $this->content_model === self::CDATA) && $this->escape === false))) {\n            /* When the content model flag is set to the PCDATA state: switch\n            to the tag open state.\n\n            When the content model flag is set to either the RCDATA state or\n            the CDATA state and the escape flag is false: switch to the tag\n            open state.\n\n            Otherwise: treat it as per the \"anything else\" entry below. */\n            $this->state = 'tagOpen';\n\n        /* U+003E GREATER-THAN SIGN (>) */\n        } elseif($char === '>') {\n            /* If the content model flag is set to either the RCDATA state or\n            the CDATA state, and the escape flag is true, and the last three\n            characters in the input stream including this one are U+002D\n            HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN (\"-->\"),\n            set the escape flag to false. */\n            if(($this->content_model === self::RCDATA ||\n            $this->content_model === self::CDATA) && $this->escape === true &&\n            $this->character($this->char, 3) === '-->') {\n                $this->escape = false;\n            }\n\n            /* In any case, emit the input character as a character token.\n            Stay in the data state. */\n            $this->emitToken(array(\n                'type' => self::CHARACTR,\n                'data' => $char\n            ));\n\n        } elseif($this->char === $this->EOF) {\n            /* EOF\n            Emit an end-of-file token. */\n            $this->EOF();\n\n        } elseif($this->content_model === self::PLAINTEXT) {\n            /* When the content model flag is set to the PLAINTEXT state\n            THIS DIFFERS GREATLY FROM THE SPEC: Get the remaining characters of\n            the text and emit it as a character token. */\n            $this->emitToken(array(\n                'type' => self::CHARACTR,\n                'data' => substr($this->data, $this->char)\n            ));\n\n            $this->EOF();\n\n        } else {\n            /* Anything else\n            THIS DIFFERS GREATLY FROM THE SPEC: Get as many character that\n            otherwise would also be treated as a character token and emit it\n            as a single character token. Stay in the data state. */\n            $len  = strcspn($this->data, '<&', $this->char);\n            $char = substr($this->data, $this->char, $len);\n            $this->char += $len - 1;\n\n            $this->emitToken(array(\n                'type' => self::CHARACTR,\n                'data' => $char\n            ));\n\n            $this->state = 'data';\n        }\n    }\n\n    private function entityDataState() {\n        // Attempt to consume an entity.\n        $entity = $this->entity();\n\n        // If nothing is returned, emit a U+0026 AMPERSAND character token.\n        // Otherwise, emit the character token that was returned.\n        $char = (!$entity) ? '&' : $entity;\n        $this->emitToken(array(\n            'type' => self::CHARACTR,\n            'data' => $char\n        ));\n\n        // Finally, switch to the data state.\n        $this->state = 'data';\n    }\n\n    private function tagOpenState() {\n        switch($this->content_model) {\n            case self::RCDATA:\n            case self::CDATA:\n                /* If the next input character is a U+002F SOLIDUS (/) character,\n                consume it and switch to the close tag open state. If the next\n                input character is not a U+002F SOLIDUS (/) character, emit a\n                U+003C LESS-THAN SIGN character token and switch to the data\n                state to process the next input character. */\n                if($this->character($this->char + 1) === '/') {\n                    $this->char++;\n                    $this->state = 'closeTagOpen';\n\n                } else {\n                    $this->emitToken(array(\n                        'type' => self::CHARACTR,\n                        'data' => '<'\n                    ));\n\n                    $this->state = 'data';\n                }\n            break;\n\n            case self::PCDATA:\n                // If the content model flag is set to the PCDATA state\n                // Consume the next input character:\n                $this->char++;\n                $char = $this->char();\n\n                if($char === '!') {\n                    /* U+0021 EXCLAMATION MARK (!)\n                    Switch to the markup declaration open state. */\n                    $this->state = 'markupDeclarationOpen';\n\n                } elseif($char === '/') {\n                    /* U+002F SOLIDUS (/)\n                    Switch to the close tag open state. */\n                    $this->state = 'closeTagOpen';\n\n                } elseif(preg_match('/^[A-Za-z]$/', $char)) {\n                    /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z\n                    Create a new start tag token, set its tag name to the lowercase\n                    version of the input character (add 0x0020 to the character's code\n                    point), then switch to the tag name state. (Don't emit the token\n                    yet; further details will be filled in before it is emitted.) */\n                    $this->token = array(\n                        'name'  => strtolower($char),\n                        'type'  => self::STARTTAG,\n                        'attr'  => array()\n                    );\n\n                    $this->state = 'tagName';\n\n                } elseif($char === '>') {\n                    /* U+003E GREATER-THAN SIGN (>)\n                    Parse error. Emit a U+003C LESS-THAN SIGN character token and a\n                    U+003E GREATER-THAN SIGN character token. Switch to the data state. */\n                    $this->emitToken(array(\n                        'type' => self::CHARACTR,\n                        'data' => '<>'\n                    ));\n\n                    $this->state = 'data';\n\n                } elseif($char === '?') {\n                    /* U+003F QUESTION MARK (?)\n                    Parse error. Switch to the bogus comment state. */\n                    $this->state = 'bogusComment';\n\n                } else {\n                    /* Anything else\n                    Parse error. Emit a U+003C LESS-THAN SIGN character token and\n                    reconsume the current input character in the data state. */\n                    $this->emitToken(array(\n                        'type' => self::CHARACTR,\n                        'data' => '<'\n                    ));\n\n                    $this->char--;\n                    $this->state = 'data';\n                }\n            break;\n        }\n    }\n\n    private function closeTagOpenState() {\n        $next_node = strtolower($this->characters('A-Za-z', $this->char + 1));\n        $the_same = count($this->tree->stack) > 0 && $next_node === end($this->tree->stack)->nodeName;\n\n        if(($this->content_model === self::RCDATA || $this->content_model === self::CDATA) &&\n        (!$the_same || ($the_same && (!preg_match('/[\\t\\n\\x0b\\x0c >\\/]/',\n        $this->character($this->char + 1 + strlen($next_node))) || $this->EOF === $this->char)))) {\n            /* If the content model flag is set to the RCDATA or CDATA states then\n            examine the next few characters. If they do not match the tag name of\n            the last start tag token emitted (case insensitively), or if they do but\n            they are not immediately followed by one of the following characters:\n                * U+0009 CHARACTER TABULATION\n                * U+000A LINE FEED (LF)\n                * U+000B LINE TABULATION\n                * U+000C FORM FEED (FF)\n                * U+0020 SPACE\n                * U+003E GREATER-THAN SIGN (>)\n                * U+002F SOLIDUS (/)\n                * EOF\n            ...then there is a parse error. Emit a U+003C LESS-THAN SIGN character\n            token, a U+002F SOLIDUS character token, and switch to the data state\n            to process the next input character. */\n            $this->emitToken(array(\n                'type' => self::CHARACTR,\n                'data' => '</'\n            ));\n\n            $this->state = 'data';\n\n        } else {\n            /* Otherwise, if the content model flag is set to the PCDATA state,\n            or if the next few characters do match that tag name, consume the\n            next input character: */\n            $this->char++;\n            $char = $this->char();\n\n            if(preg_match('/^[A-Za-z]$/', $char)) {\n                /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z\n                Create a new end tag token, set its tag name to the lowercase version\n                of the input character (add 0x0020 to the character's code point), then\n                switch to the tag name state. (Don't emit the token yet; further details\n                will be filled in before it is emitted.) */\n                $this->token = array(\n                    'name'  => strtolower($char),\n                    'type'  => self::ENDTAG\n                );\n\n                $this->state = 'tagName';\n\n            } elseif($char === '>') {\n                /* U+003E GREATER-THAN SIGN (>)\n                Parse error. Switch to the data state. */\n                $this->state = 'data';\n\n            } elseif($this->char === $this->EOF) {\n                /* EOF\n                Parse error. Emit a U+003C LESS-THAN SIGN character token and a U+002F\n                SOLIDUS character token. Reconsume the EOF character in the data state. */\n                $this->emitToken(array(\n                    'type' => self::CHARACTR,\n                    'data' => '</'\n                ));\n\n                $this->char--;\n                $this->state = 'data';\n\n            } else {\n                /* Parse error. Switch to the bogus comment state. */\n                $this->state = 'bogusComment';\n            }\n        }\n    }\n\n    private function tagNameState() {\n        // Consume the next input character:\n        $this->char++;\n        $char = $this->character($this->char);\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            /* U+0009 CHARACTER TABULATION\n            U+000A LINE FEED (LF)\n            U+000B LINE TABULATION\n            U+000C FORM FEED (FF)\n            U+0020 SPACE\n            Switch to the before attribute name state. */\n            $this->state = 'beforeAttributeName';\n\n        } elseif($char === '>') {\n            /* U+003E GREATER-THAN SIGN (>)\n            Emit the current tag token. Switch to the data state. */\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } elseif($this->char === $this->EOF) {\n            /* EOF\n            Parse error. Emit the current tag token. Reconsume the EOF\n            character in the data state. */\n            $this->emitToken($this->token);\n\n            $this->char--;\n            $this->state = 'data';\n\n        } elseif($char === '/') {\n            /* U+002F SOLIDUS (/)\n            Parse error unless this is a permitted slash. Switch to the before\n            attribute name state. */\n            $this->state = 'beforeAttributeName';\n\n        } else {\n            /* Anything else\n            Append the current input character to the current tag token's tag name.\n            Stay in the tag name state. */\n            $this->token['name'] .= strtolower($char);\n            $this->state = 'tagName';\n        }\n    }\n\n    private function beforeAttributeNameState() {\n        // Consume the next input character:\n        $this->char++;\n        $char = $this->character($this->char);\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            /* U+0009 CHARACTER TABULATION\n            U+000A LINE FEED (LF)\n            U+000B LINE TABULATION\n            U+000C FORM FEED (FF)\n            U+0020 SPACE\n            Stay in the before attribute name state. */\n            $this->state = 'beforeAttributeName';\n\n        } elseif($char === '>') {\n            /* U+003E GREATER-THAN SIGN (>)\n            Emit the current tag token. Switch to the data state. */\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } elseif($char === '/') {\n            /* U+002F SOLIDUS (/)\n            Parse error unless this is a permitted slash. Stay in the before\n            attribute name state. */\n            $this->state = 'beforeAttributeName';\n\n        } elseif($this->char === $this->EOF) {\n            /* EOF\n            Parse error. Emit the current tag token. Reconsume the EOF\n            character in the data state. */\n            $this->emitToken($this->token);\n\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            /* Anything else\n            Start a new attribute in the current tag token. Set that attribute's\n            name to the current input character, and its value to the empty string.\n            Switch to the attribute name state. */\n            $this->token['attr'][] = array(\n                'name'  => strtolower($char),\n                'value' => null\n            );\n\n            $this->state = 'attributeName';\n        }\n    }\n\n    private function attributeNameState() {\n        // Consume the next input character:\n        $this->char++;\n        $char = $this->character($this->char);\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            /* U+0009 CHARACTER TABULATION\n            U+000A LINE FEED (LF)\n            U+000B LINE TABULATION\n            U+000C FORM FEED (FF)\n            U+0020 SPACE\n            Stay in the before attribute name state. */\n            $this->state = 'afterAttributeName';\n\n        } elseif($char === '=') {\n            /* U+003D EQUALS SIGN (=)\n            Switch to the before attribute value state. */\n            $this->state = 'beforeAttributeValue';\n\n        } elseif($char === '>') {\n            /* U+003E GREATER-THAN SIGN (>)\n            Emit the current tag token. Switch to the data state. */\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } elseif($char === '/' && $this->character($this->char + 1) !== '>') {\n            /* U+002F SOLIDUS (/)\n            Parse error unless this is a permitted slash. Switch to the before\n            attribute name state. */\n            $this->state = 'beforeAttributeName';\n\n        } elseif($this->char === $this->EOF) {\n            /* EOF\n            Parse error. Emit the current tag token. Reconsume the EOF\n            character in the data state. */\n            $this->emitToken($this->token);\n\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            /* Anything else\n            Append the current input character to the current attribute's name.\n            Stay in the attribute name state. */\n            $last = count($this->token['attr']) - 1;\n            $this->token['attr'][$last]['name'] .= strtolower($char);\n\n            $this->state = 'attributeName';\n        }\n    }\n\n    private function afterAttributeNameState() {\n        // Consume the next input character:\n        $this->char++;\n        $char = $this->character($this->char);\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            /* U+0009 CHARACTER TABULATION\n            U+000A LINE FEED (LF)\n            U+000B LINE TABULATION\n            U+000C FORM FEED (FF)\n            U+0020 SPACE\n            Stay in the after attribute name state. */\n            $this->state = 'afterAttributeName';\n\n        } elseif($char === '=') {\n            /* U+003D EQUALS SIGN (=)\n            Switch to the before attribute value state. */\n            $this->state = 'beforeAttributeValue';\n\n        } elseif($char === '>') {\n            /* U+003E GREATER-THAN SIGN (>)\n            Emit the current tag token. Switch to the data state. */\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } elseif($char === '/' && $this->character($this->char + 1) !== '>') {\n            /* U+002F SOLIDUS (/)\n            Parse error unless this is a permitted slash. Switch to the\n            before attribute name state. */\n            $this->state = 'beforeAttributeName';\n\n        } elseif($this->char === $this->EOF) {\n            /* EOF\n            Parse error. Emit the current tag token. Reconsume the EOF\n            character in the data state. */\n            $this->emitToken($this->token);\n\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            /* Anything else\n            Start a new attribute in the current tag token. Set that attribute's\n            name to the current input character, and its value to the empty string.\n            Switch to the attribute name state. */\n            $this->token['attr'][] = array(\n                'name'  => strtolower($char),\n                'value' => null\n            );\n\n            $this->state = 'attributeName';\n        }\n    }\n\n    private function beforeAttributeValueState() {\n        // Consume the next input character:\n        $this->char++;\n        $char = $this->character($this->char);\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            /* U+0009 CHARACTER TABULATION\n            U+000A LINE FEED (LF)\n            U+000B LINE TABULATION\n            U+000C FORM FEED (FF)\n            U+0020 SPACE\n            Stay in the before attribute value state. */\n            $this->state = 'beforeAttributeValue';\n\n        } elseif($char === '\"') {\n            /* U+0022 QUOTATION MARK (\")\n            Switch to the attribute value (double-quoted) state. */\n            $this->state = 'attributeValueDoubleQuoted';\n\n        } elseif($char === '&') {\n            /* U+0026 AMPERSAND (&)\n            Switch to the attribute value (unquoted) state and reconsume\n            this input character. */\n            $this->char--;\n            $this->state = 'attributeValueUnquoted';\n\n        } elseif($char === '\\'') {\n            /* U+0027 APOSTROPHE (')\n            Switch to the attribute value (single-quoted) state. */\n            $this->state = 'attributeValueSingleQuoted';\n\n        } elseif($char === '>') {\n            /* U+003E GREATER-THAN SIGN (>)\n            Emit the current tag token. Switch to the data state. */\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } else {\n            /* Anything else\n            Append the current input character to the current attribute's value.\n            Switch to the attribute value (unquoted) state. */\n            $last = count($this->token['attr']) - 1;\n            $this->token['attr'][$last]['value'] .= $char;\n\n            $this->state = 'attributeValueUnquoted';\n        }\n    }\n\n    private function attributeValueDoubleQuotedState() {\n        // Consume the next input character:\n        $this->char++;\n        $char = $this->character($this->char);\n\n        if($char === '\"') {\n            /* U+0022 QUOTATION MARK (\")\n            Switch to the before attribute name state. */\n            $this->state = 'beforeAttributeName';\n\n        } elseif($char === '&') {\n            /* U+0026 AMPERSAND (&)\n            Switch to the entity in attribute value state. */\n            $this->entityInAttributeValueState('double');\n\n        } elseif($this->char === $this->EOF) {\n            /* EOF\n            Parse error. Emit the current tag token. Reconsume the character\n            in the data state. */\n            $this->emitToken($this->token);\n\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            /* Anything else\n            Append the current input character to the current attribute's value.\n            Stay in the attribute value (double-quoted) state. */\n            $last = count($this->token['attr']) - 1;\n            $this->token['attr'][$last]['value'] .= $char;\n\n            $this->state = 'attributeValueDoubleQuoted';\n        }\n    }\n\n    private function attributeValueSingleQuotedState() {\n        // Consume the next input character:\n        $this->char++;\n        $char = $this->character($this->char);\n\n        if($char === '\\'') {\n            /* U+0022 QUOTATION MARK (')\n            Switch to the before attribute name state. */\n            $this->state = 'beforeAttributeName';\n\n        } elseif($char === '&') {\n            /* U+0026 AMPERSAND (&)\n            Switch to the entity in attribute value state. */\n            $this->entityInAttributeValueState('single');\n\n        } elseif($this->char === $this->EOF) {\n            /* EOF\n            Parse error. Emit the current tag token. Reconsume the character\n            in the data state. */\n            $this->emitToken($this->token);\n\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            /* Anything else\n            Append the current input character to the current attribute's value.\n            Stay in the attribute value (single-quoted) state. */\n            $last = count($this->token['attr']) - 1;\n            $this->token['attr'][$last]['value'] .= $char;\n\n            $this->state = 'attributeValueSingleQuoted';\n        }\n    }\n\n    private function attributeValueUnquotedState() {\n        // Consume the next input character:\n        $this->char++;\n        $char = $this->character($this->char);\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            /* U+0009 CHARACTER TABULATION\n            U+000A LINE FEED (LF)\n            U+000B LINE TABULATION\n            U+000C FORM FEED (FF)\n            U+0020 SPACE\n            Switch to the before attribute name state. */\n            $this->state = 'beforeAttributeName';\n\n        } elseif($char === '&') {\n            /* U+0026 AMPERSAND (&)\n            Switch to the entity in attribute value state. */\n            $this->entityInAttributeValueState();\n\n        } elseif($char === '>') {\n            /* U+003E GREATER-THAN SIGN (>)\n            Emit the current tag token. Switch to the data state. */\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } else {\n            /* Anything else\n            Append the current input character to the current attribute's value.\n            Stay in the attribute value (unquoted) state. */\n            $last = count($this->token['attr']) - 1;\n            $this->token['attr'][$last]['value'] .= $char;\n\n            $this->state = 'attributeValueUnquoted';\n        }\n    }\n\n    private function entityInAttributeValueState() {\n        // Attempt to consume an entity.\n        $entity = $this->entity();\n\n        // If nothing is returned, append a U+0026 AMPERSAND character to the\n        // current attribute's value. Otherwise, emit the character token that\n        // was returned.\n        $char = (!$entity)\n            ? '&'\n            : $entity;\n\n        $last = count($this->token['attr']) - 1;\n        $this->token['attr'][$last]['value'] .= $char;\n    }\n\n    private function bogusCommentState() {\n        /* Consume every character up to the first U+003E GREATER-THAN SIGN\n        character (>) or the end of the file (EOF), whichever comes first. Emit\n        a comment token whose data is the concatenation of all the characters\n        starting from and including the character that caused the state machine\n        to switch into the bogus comment state, up to and including the last\n        consumed character before the U+003E character, if any, or up to the\n        end of the file otherwise. (If the comment was started by the end of\n        the file (EOF), the token is empty.) */\n        $data = $this->characters('^>', $this->char);\n        $this->emitToken(array(\n            'data' => $data,\n            'type' => self::COMMENT\n        ));\n\n        $this->char += strlen($data);\n\n        /* Switch to the data state. */\n        $this->state = 'data';\n\n        /* If the end of the file was reached, reconsume the EOF character. */\n        if($this->char === $this->EOF) {\n            $this->char = $this->EOF - 1;\n        }\n    }\n\n    private function markupDeclarationOpenState() {\n        /* If the next two characters are both U+002D HYPHEN-MINUS (-)\n        characters, consume those two characters, create a comment token whose\n        data is the empty string, and switch to the comment state. */\n        if($this->character($this->char + 1, 2) === '--') {\n            $this->char += 2;\n            $this->state = 'comment';\n            $this->token = array(\n                'data' => null,\n                'type' => self::COMMENT\n            );\n\n        /* Otherwise if the next seven chacacters are a case-insensitive match\n        for the word \"DOCTYPE\", then consume those characters and switch to the\n        DOCTYPE state. */\n        } elseif(strtolower($this->character($this->char + 1, 7)) === 'doctype') {\n            $this->char += 7;\n            $this->state = 'doctype';\n\n        /* Otherwise, is is a parse error. Switch to the bogus comment state.\n        The next character that is consumed, if any, is the first character\n        that will be in the comment. */\n        } else {\n            $this->char++;\n            $this->state = 'bogusComment';\n        }\n    }\n\n    private function commentState() {\n        /* Consume the next input character: */\n        $this->char++;\n        $char = $this->char();\n\n        /* U+002D HYPHEN-MINUS (-) */\n        if($char === '-') {\n            /* Switch to the comment dash state  */\n            $this->state = 'commentDash';\n\n        /* EOF */\n        } elseif($this->char === $this->EOF) {\n            /* Parse error. Emit the comment token. Reconsume the EOF character\n            in the data state. */\n            $this->emitToken($this->token);\n            $this->char--;\n            $this->state = 'data';\n\n        /* Anything else */\n        } else {\n            /* Append the input character to the comment token's data. Stay in\n            the comment state. */\n            $this->token['data'] .= $char;\n        }\n    }\n\n    private function commentDashState() {\n        /* Consume the next input character: */\n        $this->char++;\n        $char = $this->char();\n\n        /* U+002D HYPHEN-MINUS (-) */\n        if($char === '-') {\n            /* Switch to the comment end state  */\n            $this->state = 'commentEnd';\n\n        /* EOF */\n        } elseif($this->char === $this->EOF) {\n            /* Parse error. Emit the comment token. Reconsume the EOF character\n            in the data state. */\n            $this->emitToken($this->token);\n            $this->char--;\n            $this->state = 'data';\n\n        /* Anything else */\n        } else {\n            /* Append a U+002D HYPHEN-MINUS (-) character and the input\n            character to the comment token's data. Switch to the comment state. */\n            $this->token['data'] .= '-'.$char;\n            $this->state = 'comment';\n        }\n    }\n\n    private function commentEndState() {\n        /* Consume the next input character: */\n        $this->char++;\n        $char = $this->char();\n\n        if($char === '>') {\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } elseif($char === '-') {\n            $this->token['data'] .= '-';\n\n        } elseif($this->char === $this->EOF) {\n            $this->emitToken($this->token);\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            $this->token['data'] .= '--'.$char;\n            $this->state = 'comment';\n        }\n    }\n\n    private function doctypeState() {\n        /* Consume the next input character: */\n        $this->char++;\n        $char = $this->char();\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            $this->state = 'beforeDoctypeName';\n\n        } else {\n            $this->char--;\n            $this->state = 'beforeDoctypeName';\n        }\n    }\n\n    private function beforeDoctypeNameState() {\n        /* Consume the next input character: */\n        $this->char++;\n        $char = $this->char();\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            // Stay in the before DOCTYPE name state.\n\n        } elseif(preg_match('/^[a-z]$/', $char)) {\n            $this->token = array(\n                'name' => strtoupper($char),\n                'type' => self::DOCTYPE,\n                'error' => true\n            );\n\n            $this->state = 'doctypeName';\n\n        } elseif($char === '>') {\n            $this->emitToken(array(\n                'name' => null,\n                'type' => self::DOCTYPE,\n                'error' => true\n            ));\n\n            $this->state = 'data';\n\n        } elseif($this->char === $this->EOF) {\n            $this->emitToken(array(\n                'name' => null,\n                'type' => self::DOCTYPE,\n                'error' => true\n            ));\n\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            $this->token = array(\n                'name' => $char,\n                'type' => self::DOCTYPE,\n                'error' => true\n            );\n\n            $this->state = 'doctypeName';\n        }\n    }\n\n    private function doctypeNameState() {\n        /* Consume the next input character: */\n        $this->char++;\n        $char = $this->char();\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            $this->state = 'AfterDoctypeName';\n\n        } elseif($char === '>') {\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } elseif(preg_match('/^[a-z]$/', $char)) {\n            $this->token['name'] .= strtoupper($char);\n\n        } elseif($this->char === $this->EOF) {\n            $this->emitToken($this->token);\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            $this->token['name'] .= $char;\n        }\n\n        $this->token['error'] = ($this->token['name'] === 'HTML')\n            ? false\n            : true;\n    }\n\n    private function afterDoctypeNameState() {\n        /* Consume the next input character: */\n        $this->char++;\n        $char = $this->char();\n\n        if(preg_match('/^[\\t\\n\\x0b\\x0c ]$/', $char)) {\n            // Stay in the DOCTYPE name state.\n\n        } elseif($char === '>') {\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } elseif($this->char === $this->EOF) {\n            $this->emitToken($this->token);\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            $this->token['error'] = true;\n            $this->state = 'bogusDoctype';\n        }\n    }\n\n    private function bogusDoctypeState() {\n        /* Consume the next input character: */\n        $this->char++;\n        $char = $this->char();\n\n        if($char === '>') {\n            $this->emitToken($this->token);\n            $this->state = 'data';\n\n        } elseif($this->char === $this->EOF) {\n            $this->emitToken($this->token);\n            $this->char--;\n            $this->state = 'data';\n\n        } else {\n            // Stay in the bogus DOCTYPE state.\n        }\n    }\n\n    private function entity() {\n        $start = $this->char;\n\n        // This section defines how to consume an entity. This definition is\n        // used when parsing entities in text and in attributes.\n\n        // The behaviour depends on the identity of the next character (the\n        // one immediately after the U+0026 AMPERSAND character): \n\n        switch($this->character($this->char + 1)) {\n            // U+0023 NUMBER SIGN (#)\n            case '#':\n\n                // The behaviour further depends on the character after the\n                // U+0023 NUMBER SIGN:\n                switch($this->character($this->char + 1)) {\n                    // U+0078 LATIN SMALL LETTER X\n                    // U+0058 LATIN CAPITAL LETTER X\n                    case 'x':\n                    case 'X':\n                        // Follow the steps below, but using the range of\n                        // characters U+0030 DIGIT ZERO through to U+0039 DIGIT\n                        // NINE, U+0061 LATIN SMALL LETTER A through to U+0066\n                        // LATIN SMALL LETTER F, and U+0041 LATIN CAPITAL LETTER\n                        // A, through to U+0046 LATIN CAPITAL LETTER F (in other\n                        // words, 0-9, A-F, a-f).\n                        $char = 1;\n                        $char_class = '0-9A-Fa-f';\n                    break;\n\n                    // Anything else\n                    default:\n                        // Follow the steps below, but using the range of\n                        // characters U+0030 DIGIT ZERO through to U+0039 DIGIT\n                        // NINE (i.e. just 0-9).\n                        $char = 0;\n                        $char_class = '0-9';\n                    break;\n                }\n\n                // Consume as many characters as match the range of characters\n                // given above.\n                $this->char++;\n                $e_name = $this->characters($char_class, $this->char + $char + 1);\n                $entity = $this->character($start, $this->char);\n                $cond = strlen($e_name) > 0;\n\n                // The rest of the parsing happens bellow.\n            break;\n\n            // Anything else\n            default:\n                // Consume the maximum number of characters possible, with the\n                // consumed characters case-sensitively matching one of the\n                // identifiers in the first column of the entities table.\n                $e_name = $this->characters('0-9A-Za-z;', $this->char + 1);\n                $len = strlen($e_name);\n\n                for($c = 1; $c <= $len; $c++) {\n                    $id = substr($e_name, 0, $c);\n                    $this->char++;\n\n                    if(in_array($id, $this->entities)) {\n                        if ($e_name[$c-1] !== ';') {\n                            if ($c < $len && $e_name[$c] == ';') {\n                                $this->char++; // consume extra semicolon\n                            }\n                        }\n                        $entity = $id;\n                        break;\n                    }\n                }\n\n                $cond = isset($entity);\n                // The rest of the parsing happens bellow.\n            break;\n        }\n\n        if(!$cond) {\n            // If no match can be made, then this is a parse error. No\n            // characters are consumed, and nothing is returned.\n            $this->char = $start;\n            return false;\n        }\n\n        // Return a character token for the character corresponding to the\n        // entity name (as given by the second column of the entities table).\n        return html_entity_decode('&'.$entity.';', ENT_QUOTES, 'UTF-8');\n    }\n\n    private function emitToken($token) {\n        $emit = $this->tree->emitToken($token);\n\n        if(is_int($emit)) {\n            $this->content_model = $emit;\n\n        } elseif($token['type'] === self::ENDTAG) {\n            $this->content_model = self::PCDATA;\n        }\n    }\n\n    private function EOF() {\n        $this->state = null;\n        $this->tree->emitToken(array(\n            'type' => self::EOF\n        ));\n    }\n}\n\nclass HTML5TreeConstructer {\n    public $stack = array();\n\n    private $phase;\n    private $mode;\n    private $dom;\n    private $foster_parent = null;\n    private $a_formatting  = array();\n\n    private $head_pointer = null;\n    private $form_pointer = null;\n\n    private $scoping = array('button','caption','html','marquee','object','table','td','th');\n    private $formatting = array('a','b','big','em','font','i','nobr','s','small','strike','strong','tt','u');\n    private $special = array('address','area','base','basefont','bgsound',\n    'blockquote','body','br','center','col','colgroup','dd','dir','div','dl',\n    'dt','embed','fieldset','form','frame','frameset','h1','h2','h3','h4','h5',\n    'h6','head','hr','iframe','image','img','input','isindex','li','link',\n    'listing','menu','meta','noembed','noframes','noscript','ol','optgroup',\n    'option','p','param','plaintext','pre','script','select','spacer','style',\n    'tbody','textarea','tfoot','thead','title','tr','ul','wbr');\n\n    // The different phases.\n    const INIT_PHASE = 0;\n    const ROOT_PHASE = 1;\n    const MAIN_PHASE = 2;\n    const END_PHASE  = 3;\n\n    // The different insertion modes for the main phase.\n    const BEFOR_HEAD = 0;\n    const IN_HEAD    = 1;\n    const AFTER_HEAD = 2;\n    const IN_BODY    = 3;\n    const IN_TABLE   = 4;\n    const IN_CAPTION = 5;\n    const IN_CGROUP  = 6;\n    const IN_TBODY   = 7;\n    const IN_ROW     = 8;\n    const IN_CELL    = 9;\n    const IN_SELECT  = 10;\n    const AFTER_BODY = 11;\n    const IN_FRAME   = 12;\n    const AFTR_FRAME = 13;\n\n    // The different types of elements.\n    const SPECIAL    = 0;\n    const SCOPING    = 1;\n    const FORMATTING = 2;\n    const PHRASING   = 3;\n\n    const MARKER     = 0;\n\n    public function __construct() {\n        $this->phase = self::INIT_PHASE;\n        $this->mode = self::BEFOR_HEAD;\n        $this->dom = new DOMDocument;\n\n        $this->dom->encoding = 'UTF-8';\n        $this->dom->preserveWhiteSpace = true;\n        $this->dom->substituteEntities = true;\n        $this->dom->strictErrorChecking = false;\n    }\n\n    // Process tag tokens\n    public function emitToken($token) {\n        switch($this->phase) {\n            case self::INIT_PHASE: return $this->initPhase($token); break;\n            case self::ROOT_PHASE: return $this->rootElementPhase($token); break;\n            case self::MAIN_PHASE: return $this->mainPhase($token); break;\n            case self::END_PHASE : return $this->trailingEndPhase($token); break;\n        }\n    }\n\n    private function initPhase($token) {\n        /* Initially, the tree construction stage must handle each token\n        emitted from the tokenisation stage as follows: */\n\n        /* A DOCTYPE token that is marked as being in error\n        A comment token\n        A start tag token\n        An end tag token\n        A character token that is not one of one of U+0009 CHARACTER TABULATION,\n            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n            or U+0020 SPACE\n        An end-of-file token */\n        if((isset($token['error']) && $token['error']) ||\n        $token['type'] === HTML5::COMMENT ||\n        $token['type'] === HTML5::STARTTAG ||\n        $token['type'] === HTML5::ENDTAG ||\n        $token['type'] === HTML5::EOF ||\n        ($token['type'] === HTML5::CHARACTR && isset($token['data']) &&\n        !preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data']))) {\n            /* This specification does not define how to handle this case. In\n            particular, user agents may ignore the entirety of this specification\n            altogether for such documents, and instead invoke special parse modes\n            with a greater emphasis on backwards compatibility. */\n\n            $this->phase = self::ROOT_PHASE;\n            return $this->rootElementPhase($token);\n\n        /* A DOCTYPE token marked as being correct */\n        } elseif(isset($token['error']) && !$token['error']) {\n            /* Append a DocumentType node to the Document  node, with the name\n            attribute set to the name given in the DOCTYPE token (which will be\n            \"HTML\"), and the other attributes specific to DocumentType objects\n            set to null, empty lists, or the empty string as appropriate. */\n            $doctype = new DOMDocumentType(null, null, 'HTML');\n\n            /* Then, switch to the root element phase of the tree construction\n            stage. */\n            $this->phase = self::ROOT_PHASE;\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE */\n        } elseif(isset($token['data']) && preg_match('/^[\\t\\n\\x0b\\x0c ]+$/',\n        $token['data'])) {\n            /* Append that character  to the Document node. */\n            $text = $this->dom->createTextNode($token['data']);\n            $this->dom->appendChild($text);\n        }\n    }\n\n    private function rootElementPhase($token) {\n        /* After the initial phase, as each token is emitted from the tokenisation\n        stage, it must be processed as described in this section. */\n\n        /* A DOCTYPE token */\n        if($token['type'] === HTML5::DOCTYPE) {\n            // Parse error. Ignore the token.\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the Document object with the data\n            attribute set to the data given in the comment token. */\n            $comment = $this->dom->createComment($token['data']);\n            $this->dom->appendChild($comment);\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE */\n        } elseif($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) {\n            /* Append that character  to the Document node. */\n            $text = $this->dom->createTextNode($token['data']);\n            $this->dom->appendChild($text);\n\n        /* A character token that is not one of U+0009 CHARACTER TABULATION,\n            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED\n            (FF), or U+0020 SPACE\n        A start tag token\n        An end tag token\n        An end-of-file token */\n        } elseif(($token['type'] === HTML5::CHARACTR &&\n        !preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) ||\n        $token['type'] === HTML5::STARTTAG ||\n        $token['type'] === HTML5::ENDTAG ||\n        $token['type'] === HTML5::EOF) {\n            /* Create an HTMLElement node with the tag name html, in the HTML\n            namespace. Append it to the Document object. Switch to the main\n            phase and reprocess the current token. */\n            $html = $this->dom->createElement('html');\n            $this->dom->appendChild($html);\n            $this->stack[] = $html;\n\n            $this->phase = self::MAIN_PHASE;\n            return $this->mainPhase($token);\n        }\n    }\n\n    private function mainPhase($token) {\n        /* Tokens in the main phase must be handled as follows: */\n\n        /* A DOCTYPE token */\n        if($token['type'] === HTML5::DOCTYPE) {\n            // Parse error. Ignore the token.\n\n        /* A start tag token with the tag name \"html\" */\n        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'html') {\n            /* If this start tag token was not the first start tag token, then\n            it is a parse error. */\n\n            /* For each attribute on the token, check to see if the attribute\n            is already present on the top element of the stack of open elements.\n            If it is not, add the attribute and its corresponding value to that\n            element. */\n            foreach($token['attr'] as $attr) {\n                if(!$this->stack[0]->hasAttribute($attr['name'])) {\n                    $this->stack[0]->setAttribute($attr['name'], $attr['value']);\n                }\n            }\n\n        /* An end-of-file token */\n        } elseif($token['type'] === HTML5::EOF) {\n            /* Generate implied end tags. */\n            $this->generateImpliedEndTags();\n\n        /* Anything else. */\n        } else {\n            /* Depends on the insertion mode: */\n            switch($this->mode) {\n                case self::BEFOR_HEAD: return $this->beforeHead($token); break;\n                case self::IN_HEAD:    return $this->inHead($token); break;\n                case self::AFTER_HEAD: return $this->afterHead($token); break;\n                case self::IN_BODY:    return $this->inBody($token); break;\n                case self::IN_TABLE:   return $this->inTable($token); break;\n                case self::IN_CAPTION: return $this->inCaption($token); break;\n                case self::IN_CGROUP:  return $this->inColumnGroup($token); break;\n                case self::IN_TBODY:   return $this->inTableBody($token); break;\n                case self::IN_ROW:     return $this->inRow($token); break;\n                case self::IN_CELL:    return $this->inCell($token); break;\n                case self::IN_SELECT:  return $this->inSelect($token); break;\n                case self::AFTER_BODY: return $this->afterBody($token); break;\n                case self::IN_FRAME:   return $this->inFrameset($token); break;\n                case self::AFTR_FRAME: return $this->afterFrameset($token); break;\n                case self::END_PHASE:  return $this->trailingEndPhase($token); break;\n            }\n        }\n    }\n\n    private function beforeHead($token) {\n        /* Handle the token as follows: */\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE */\n        if($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) {\n            /* Append the character to the current node. */\n            $this->insertText($token['data']);\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the current node with the data attribute\n            set to the data given in the comment token. */\n            $this->insertComment($token['data']);\n\n        /* A start tag token with the tag name \"head\" */\n        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') {\n            /* Create an element for the token, append the new element to the\n            current node and push it onto the stack of open elements. */\n            $element = $this->insertElement($token);\n\n            /* Set the head element pointer to this new element node. */\n            $this->head_pointer = $element;\n\n            /* Change the insertion mode to \"in head\". */\n            $this->mode = self::IN_HEAD;\n\n        /* A start tag token whose tag name is one of: \"base\", \"link\", \"meta\",\n        \"script\", \"style\", \"title\". Or an end tag with the tag name \"html\".\n        Or a character token that is not one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE. Or any other start tag token */\n        } elseif($token['type'] === HTML5::STARTTAG ||\n        ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') ||\n        ($token['type'] === HTML5::CHARACTR && !preg_match('/^[\\t\\n\\x0b\\x0c ]$/',\n        $token['data']))) {\n            /* Act as if a start tag token with the tag name \"head\" and no\n            attributes had been seen, then reprocess the current token. */\n            $this->beforeHead(array(\n                'name' => 'head',\n                'type' => HTML5::STARTTAG,\n                'attr' => array()\n            ));\n\n            return $this->inHead($token);\n\n        /* Any other end tag */\n        } elseif($token['type'] === HTML5::ENDTAG) {\n            /* Parse error. Ignore the token. */\n        }\n    }\n\n    private function inHead($token) {\n        /* Handle the token as follows: */\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE.\n\n        THIS DIFFERS FROM THE SPEC: If the current node is either a title, style\n        or script element, append the character to the current node regardless\n        of its content. */\n        if(($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) || (\n        $token['type'] === HTML5::CHARACTR && in_array(end($this->stack)->nodeName,\n        array('title', 'style', 'script')))) {\n            /* Append the character to the current node. */\n            $this->insertText($token['data']);\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the current node with the data attribute\n            set to the data given in the comment token. */\n            $this->insertComment($token['data']);\n\n        } elseif($token['type'] === HTML5::ENDTAG &&\n        in_array($token['name'], array('title', 'style', 'script'))) {\n            array_pop($this->stack);\n            return HTML5::PCDATA;\n\n        /* A start tag with the tag name \"title\" */\n        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'title') {\n            /* Create an element for the token and append the new element to the\n            node pointed to by the head element pointer, or, if that is null\n            (innerHTML case), to the current node. */\n            if($this->head_pointer !== null) {\n                $element = $this->insertElement($token, false);\n                $this->head_pointer->appendChild($element);\n\n            } else {\n                $element = $this->insertElement($token);\n            }\n\n            /* Switch the tokeniser's content model flag  to the RCDATA state. */\n            return HTML5::RCDATA;\n\n        /* A start tag with the tag name \"style\" */\n        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'style') {\n            /* Create an element for the token and append the new element to the\n            node pointed to by the head element pointer, or, if that is null\n            (innerHTML case), to the current node. */\n            if($this->head_pointer !== null) {\n                $element = $this->insertElement($token, false);\n                $this->head_pointer->appendChild($element);\n\n            } else {\n                $this->insertElement($token);\n            }\n\n            /* Switch the tokeniser's content model flag  to the CDATA state. */\n            return HTML5::CDATA;\n\n        /* A start tag with the tag name \"script\" */\n        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'script') {\n            /* Create an element for the token. */\n            $element = $this->insertElement($token, false);\n            $this->head_pointer->appendChild($element);\n\n            /* Switch the tokeniser's content model flag  to the CDATA state. */\n            return HTML5::CDATA;\n\n        /* A start tag with the tag name \"base\", \"link\", or \"meta\" */\n        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],\n        array('base', 'link', 'meta'))) {\n            /* Create an element for the token and append the new element to the\n            node pointed to by the head element pointer, or, if that is null\n            (innerHTML case), to the current node. */\n            if($this->head_pointer !== null) {\n                $element = $this->insertElement($token, false);\n                $this->head_pointer->appendChild($element);\n                array_pop($this->stack);\n\n            } else {\n                $this->insertElement($token);\n            }\n\n        /* An end tag with the tag name \"head\" */\n        } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'head') {\n            /* If the current node is a head element, pop the current node off\n            the stack of open elements. */\n            if($this->head_pointer->isSameNode(end($this->stack))) {\n                array_pop($this->stack);\n\n            /* Otherwise, this is a parse error. */\n            } else {\n                // k\n            }\n\n            /* Change the insertion mode to \"after head\". */\n            $this->mode = self::AFTER_HEAD;\n\n        /* A start tag with the tag name \"head\" or an end tag except \"html\". */\n        } elseif(($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') ||\n        ($token['type'] === HTML5::ENDTAG && $token['name'] !== 'html')) {\n            // Parse error. Ignore the token.\n\n        /* Anything else */\n        } else {\n            /* If the current node is a head element, act as if an end tag\n            token with the tag name \"head\" had been seen. */\n            if($this->head_pointer->isSameNode(end($this->stack))) {\n                $this->inHead(array(\n                    'name' => 'head',\n                    'type' => HTML5::ENDTAG\n                ));\n\n            /* Otherwise, change the insertion mode to \"after head\". */\n            } else {\n                $this->mode = self::AFTER_HEAD;\n            }\n\n            /* Then, reprocess the current token. */\n            return $this->afterHead($token);\n        }\n    }\n\n    private function afterHead($token) {\n        /* Handle the token as follows: */\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE */\n        if($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) {\n            /* Append the character to the current node. */\n            $this->insertText($token['data']);\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the current node with the data attribute\n            set to the data given in the comment token. */\n            $this->insertComment($token['data']);\n\n        /* A start tag token with the tag name \"body\" */\n        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'body') {\n            /* Insert a body element for the token. */\n            $this->insertElement($token);\n\n            /* Change the insertion mode to \"in body\". */\n            $this->mode = self::IN_BODY;\n\n        /* A start tag token with the tag name \"frameset\" */\n        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'frameset') {\n            /* Insert a frameset element for the token. */\n            $this->insertElement($token);\n\n            /* Change the insertion mode to \"in frameset\". */\n            $this->mode = self::IN_FRAME;\n\n        /* A start tag token whose tag name is one of: \"base\", \"link\", \"meta\",\n        \"script\", \"style\", \"title\" */\n        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],\n        array('base', 'link', 'meta', 'script', 'style', 'title'))) {\n            /* Parse error. Switch the insertion mode back to \"in head\" and\n            reprocess the token. */\n            $this->mode = self::IN_HEAD;\n            return $this->inHead($token);\n\n        /* Anything else */\n        } else {\n            /* Act as if a start tag token with the tag name \"body\" and no\n            attributes had been seen, and then reprocess the current token. */\n            $this->afterHead(array(\n                'name' => 'body',\n                'type' => HTML5::STARTTAG,\n                'attr' => array()\n            ));\n\n            return $this->inBody($token);\n        }\n    }\n\n    private function inBody($token) {\n        /* Handle the token as follows: */\n\n        switch($token['type']) {\n            /* A character token */\n            case HTML5::CHARACTR:\n                /* Reconstruct the active formatting elements, if any. */\n                $this->reconstructActiveFormattingElements();\n\n                /* Append the token's character to the current node. */\n                $this->insertText($token['data']);\n            break;\n\n            /* A comment token */\n            case HTML5::COMMENT:\n                /* Append a Comment node to the current node with the data\n                attribute set to the data given in the comment token. */\n                $this->insertComment($token['data']);\n            break;\n\n            case HTML5::STARTTAG:\n            switch($token['name']) {\n                /* A start tag token whose tag name is one of: \"script\",\n                \"style\" */\n                case 'script': case 'style':\n                    /* Process the token as if the insertion mode had been \"in\n                    head\". */\n                    return $this->inHead($token);\n                break;\n\n                /* A start tag token whose tag name is one of: \"base\", \"link\",\n                \"meta\", \"title\" */\n                case 'base': case 'link': case 'meta': case 'title':\n                    /* Parse error. Process the token as if the insertion mode\n                    had    been \"in head\". */\n                    return $this->inHead($token);\n                break;\n\n                /* A start tag token with the tag name \"body\" */\n                case 'body':\n                    /* Parse error. If the second element on the stack of open\n                    elements is not a body element, or, if the stack of open\n                    elements has only one node on it, then ignore the token.\n                    (innerHTML case) */\n                    if(count($this->stack) === 1 || $this->stack[1]->nodeName !== 'body') {\n                        // Ignore\n\n                    /* Otherwise, for each attribute on the token, check to see\n                    if the attribute is already present on the body element (the\n                    second element)    on the stack of open elements. If it is not,\n                    add the attribute and its corresponding value to that\n                    element. */\n                    } else {\n                        foreach($token['attr'] as $attr) {\n                            if(!$this->stack[1]->hasAttribute($attr['name'])) {\n                                $this->stack[1]->setAttribute($attr['name'], $attr['value']);\n                            }\n                        }\n                    }\n                break;\n\n                /* A start tag whose tag name is one of: \"address\",\n                \"blockquote\", \"center\", \"dir\", \"div\", \"dl\", \"fieldset\",\n                \"listing\", \"menu\", \"ol\", \"p\", \"ul\" */\n                case 'address': case 'blockquote': case 'center': case 'dir':\n                case 'div': case 'dl': case 'fieldset': case 'listing':\n                case 'menu': case 'ol': case 'p': case 'ul':\n                    /* If the stack of open elements has a p element in scope,\n                    then act as if an end tag with the tag name p had been\n                    seen. */\n                    if($this->elementInScope('p')) {\n                        $this->emitToken(array(\n                            'name' => 'p',\n                            'type' => HTML5::ENDTAG\n                        ));\n                    }\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n                break;\n\n                /* A start tag whose tag name is \"form\" */\n                case 'form':\n                    /* If the form element pointer is not null, ignore the\n                    token with a parse error. */\n                    if($this->form_pointer !== null) {\n                        // Ignore.\n\n                    /* Otherwise: */\n                    } else {\n                        /* If the stack of open elements has a p element in\n                        scope, then act as if an end tag with the tag name p\n                        had been seen. */\n                        if($this->elementInScope('p')) {\n                            $this->emitToken(array(\n                                'name' => 'p',\n                                'type' => HTML5::ENDTAG\n                            ));\n                        }\n\n                        /* Insert an HTML element for the token, and set the\n                        form element pointer to point to the element created. */\n                        $element = $this->insertElement($token);\n                        $this->form_pointer = $element;\n                    }\n                break;\n\n                /* A start tag whose tag name is \"li\", \"dd\" or \"dt\" */\n                case 'li': case 'dd': case 'dt':\n                    /* If the stack of open elements has a p  element in scope,\n                    then act as if an end tag with the tag name p had been\n                    seen. */\n                    if($this->elementInScope('p')) {\n                        $this->emitToken(array(\n                            'name' => 'p',\n                            'type' => HTML5::ENDTAG\n                        ));\n                    }\n\n                    $stack_length = count($this->stack) - 1;\n\n                    for($n = $stack_length; 0 <= $n; $n--) {\n                        /* 1. Initialise node to be the current node (the\n                        bottommost node of the stack). */\n                        $stop = false;\n                        $node = $this->stack[$n];\n                        $cat  = $this->getElementCategory($node->tagName);\n\n                        /* 2. If node is an li, dd or dt element, then pop all\n                        the    nodes from the current node up to node, including\n                        node, then stop this algorithm. */\n                        if($token['name'] === $node->tagName ||    ($token['name'] !== 'li'\n                        && ($node->tagName === 'dd' || $node->tagName === 'dt'))) {\n                            for($x = $stack_length; $x >= $n ; $x--) {\n                                array_pop($this->stack);\n                            }\n\n                            break;\n                        }\n\n                        /* 3. If node is not in the formatting category, and is\n                        not    in the phrasing category, and is not an address or\n                        div element, then stop this algorithm. */\n                        if($cat !== self::FORMATTING && $cat !== self::PHRASING &&\n                        $node->tagName !== 'address' && $node->tagName !== 'div') {\n                            break;\n                        }\n                    }\n\n                    /* Finally, insert an HTML element with the same tag\n                    name as the    token's. */\n                    $this->insertElement($token);\n                break;\n\n                /* A start tag token whose tag name is \"plaintext\" */\n                case 'plaintext':\n                    /* If the stack of open elements has a p  element in scope,\n                    then act as if an end tag with the tag name p had been\n                    seen. */\n                    if($this->elementInScope('p')) {\n                        $this->emitToken(array(\n                            'name' => 'p',\n                            'type' => HTML5::ENDTAG\n                        ));\n                    }\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n\n                    return HTML5::PLAINTEXT;\n                break;\n\n                /* A start tag whose tag name is one of: \"h1\", \"h2\", \"h3\", \"h4\",\n                \"h5\", \"h6\" */\n                case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':\n                    /* If the stack of open elements has a p  element in scope,\n                    then act as if an end tag with the tag name p had been seen. */\n                    if($this->elementInScope('p')) {\n                        $this->emitToken(array(\n                            'name' => 'p',\n                            'type' => HTML5::ENDTAG\n                        ));\n                    }\n\n                    /* If the stack of open elements has in scope an element whose\n                    tag name is one of \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", or \"h6\", then\n                    this is a parse error; pop elements from the stack until an\n                    element with one of those tag names has been popped from the\n                    stack. */\n                    while($this->elementInScope(array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))) {\n                        array_pop($this->stack);\n                    }\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n                break;\n\n                /* A start tag whose tag name is \"a\" */\n                case 'a':\n                    /* If the list of active formatting elements contains\n                    an element whose tag name is \"a\" between the end of the\n                    list and the last marker on the list (or the start of\n                    the list if there is no marker on the list), then this\n                    is a parse error; act as if an end tag with the tag name\n                    \"a\" had been seen, then remove that element from the list\n                    of active formatting elements and the stack of open\n                    elements if the end tag didn't already remove it (it\n                    might not have if the element is not in table scope). */\n                    $leng = count($this->a_formatting);\n\n                    for($n = $leng - 1; $n >= 0; $n--) {\n                        if($this->a_formatting[$n] === self::MARKER) {\n                            break;\n\n                        } elseif($this->a_formatting[$n]->nodeName === 'a') {\n                            $this->emitToken(array(\n                                'name' => 'a',\n                                'type' => HTML5::ENDTAG\n                            ));\n                            break;\n                        }\n                    }\n\n                    /* Reconstruct the active formatting elements, if any. */\n                    $this->reconstructActiveFormattingElements();\n\n                    /* Insert an HTML element for the token. */\n                    $el = $this->insertElement($token);\n\n                    /* Add that element to the list of active formatting\n                    elements. */\n                    $this->a_formatting[] = $el;\n                break;\n\n                /* A start tag whose tag name is one of: \"b\", \"big\", \"em\", \"font\",\n                \"i\", \"nobr\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\" */\n                case 'b': case 'big': case 'em': case 'font': case 'i':\n                case 'nobr': case 's': case 'small': case 'strike':\n                case 'strong': case 'tt': case 'u':\n                    /* Reconstruct the active formatting elements, if any. */\n                    $this->reconstructActiveFormattingElements();\n\n                    /* Insert an HTML element for the token. */\n                    $el = $this->insertElement($token);\n\n                    /* Add that element to the list of active formatting\n                    elements. */\n                    $this->a_formatting[] = $el;\n                break;\n\n                /* A start tag token whose tag name is \"button\" */\n                case 'button':\n                    /* If the stack of open elements has a button element in scope,\n                    then this is a parse error; act as if an end tag with the tag\n                    name \"button\" had been seen, then reprocess the token. (We don't\n                    do that. Unnecessary.) */\n                    if($this->elementInScope('button')) {\n                        $this->inBody(array(\n                            'name' => 'button',\n                            'type' => HTML5::ENDTAG\n                        ));\n                    }\n\n                    /* Reconstruct the active formatting elements, if any. */\n                    $this->reconstructActiveFormattingElements();\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n\n                    /* Insert a marker at the end of the list of active\n                    formatting elements. */\n                    $this->a_formatting[] = self::MARKER;\n                break;\n\n                /* A start tag token whose tag name is one of: \"marquee\", \"object\" */\n                case 'marquee': case 'object':\n                    /* Reconstruct the active formatting elements, if any. */\n                    $this->reconstructActiveFormattingElements();\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n\n                    /* Insert a marker at the end of the list of active\n                    formatting elements. */\n                    $this->a_formatting[] = self::MARKER;\n                break;\n\n                /* A start tag token whose tag name is \"xmp\" */\n                case 'xmp':\n                    /* Reconstruct the active formatting elements, if any. */\n                    $this->reconstructActiveFormattingElements();\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n\n                    /* Switch the content model flag to the CDATA state. */\n                    return HTML5::CDATA;\n                break;\n\n                /* A start tag whose tag name is \"table\" */\n                case 'table':\n                    /* If the stack of open elements has a p element in scope,\n                    then act as if an end tag with the tag name p had been seen. */\n                    if($this->elementInScope('p')) {\n                        $this->emitToken(array(\n                            'name' => 'p',\n                            'type' => HTML5::ENDTAG\n                        ));\n                    }\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n\n                    /* Change the insertion mode to \"in table\". */\n                    $this->mode = self::IN_TABLE;\n                break;\n\n                /* A start tag whose tag name is one of: \"area\", \"basefont\",\n                \"bgsound\", \"br\", \"embed\", \"img\", \"param\", \"spacer\", \"wbr\" */\n                case 'area': case 'basefont': case 'bgsound': case 'br':\n                case 'embed': case 'img': case 'param': case 'spacer':\n                case 'wbr':\n                    /* Reconstruct the active formatting elements, if any. */\n                    $this->reconstructActiveFormattingElements();\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n\n                    /* Immediately pop the current node off the stack of open elements. */\n                    array_pop($this->stack);\n                break;\n\n                /* A start tag whose tag name is \"hr\" */\n                case 'hr':\n                    /* If the stack of open elements has a p element in scope,\n                    then act as if an end tag with the tag name p had been seen. */\n                    if($this->elementInScope('p')) {\n                        $this->emitToken(array(\n                            'name' => 'p',\n                            'type' => HTML5::ENDTAG\n                        ));\n                    }\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n\n                    /* Immediately pop the current node off the stack of open elements. */\n                    array_pop($this->stack);\n                break;\n\n                /* A start tag whose tag name is \"image\" */\n                case 'image':\n                    /* Parse error. Change the token's tag name to \"img\" and\n                    reprocess it. (Don't ask.) */\n                    $token['name'] = 'img';\n                    return $this->inBody($token);\n                break;\n\n                /* A start tag whose tag name is \"input\" */\n                case 'input':\n                    /* Reconstruct the active formatting elements, if any. */\n                    $this->reconstructActiveFormattingElements();\n\n                    /* Insert an input element for the token. */\n                    $element = $this->insertElement($token, false);\n\n                    /* If the form element pointer is not null, then associate the\n                    input element with the form element pointed to by the form\n                    element pointer. */\n                    $this->form_pointer !== null\n                        ? $this->form_pointer->appendChild($element)\n                        : end($this->stack)->appendChild($element);\n\n                    /* Pop that input element off the stack of open elements. */\n                    array_pop($this->stack);\n                break;\n\n                /* A start tag whose tag name is \"isindex\" */\n                case 'isindex':\n                    /* Parse error. */\n                    // w/e\n\n                    /* If the form element pointer is not null,\n                    then ignore the token. */\n                    if($this->form_pointer === null) {\n                        /* Act as if a start tag token with the tag name \"form\" had\n                        been seen. */\n                        $this->inBody(array(\n                            'name' => 'body',\n                            'type' => HTML5::STARTTAG,\n                            'attr' => array()\n                        ));\n\n                        /* Act as if a start tag token with the tag name \"hr\" had\n                        been seen. */\n                        $this->inBody(array(\n                            'name' => 'hr',\n                            'type' => HTML5::STARTTAG,\n                            'attr' => array()\n                        ));\n\n                        /* Act as if a start tag token with the tag name \"p\" had\n                        been seen. */\n                        $this->inBody(array(\n                            'name' => 'p',\n                            'type' => HTML5::STARTTAG,\n                            'attr' => array()\n                        ));\n\n                        /* Act as if a start tag token with the tag name \"label\"\n                        had been seen. */\n                        $this->inBody(array(\n                            'name' => 'label',\n                            'type' => HTML5::STARTTAG,\n                            'attr' => array()\n                        ));\n\n                        /* Act as if a stream of character tokens had been seen. */\n                        $this->insertText('This is a searchable index. '.\n                        'Insert your search keywords here: ');\n\n                        /* Act as if a start tag token with the tag name \"input\"\n                        had been seen, with all the attributes from the \"isindex\"\n                        token, except with the \"name\" attribute set to the value\n                        \"isindex\" (ignoring any explicit \"name\" attribute). */\n                        $attr = $token['attr'];\n                        $attr[] = array('name' => 'name', 'value' => 'isindex');\n\n                        $this->inBody(array(\n                            'name' => 'input',\n                            'type' => HTML5::STARTTAG,\n                            'attr' => $attr\n                        ));\n\n                        /* Act as if a stream of character tokens had been seen\n                        (see below for what they should say). */\n                        $this->insertText('This is a searchable index. '.\n                        'Insert your search keywords here: ');\n\n                        /* Act as if an end tag token with the tag name \"label\"\n                        had been seen. */\n                        $this->inBody(array(\n                            'name' => 'label',\n                            'type' => HTML5::ENDTAG\n                        ));\n\n                        /* Act as if an end tag token with the tag name \"p\" had\n                        been seen. */\n                        $this->inBody(array(\n                            'name' => 'p',\n                            'type' => HTML5::ENDTAG\n                        ));\n\n                        /* Act as if a start tag token with the tag name \"hr\" had\n                        been seen. */\n                        $this->inBody(array(\n                            'name' => 'hr',\n                            'type' => HTML5::ENDTAG\n                        ));\n\n                        /* Act as if an end tag token with the tag name \"form\" had\n                        been seen. */\n                        $this->inBody(array(\n                            'name' => 'form',\n                            'type' => HTML5::ENDTAG\n                        ));\n                    }\n                break;\n\n                /* A start tag whose tag name is \"textarea\" */\n                case 'textarea':\n                    $this->insertElement($token);\n\n                    /* Switch the tokeniser's content model flag to the\n                    RCDATA state. */\n                    return HTML5::RCDATA;\n                break;\n\n                /* A start tag whose tag name is one of: \"iframe\", \"noembed\",\n                \"noframes\" */\n                case 'iframe': case 'noembed': case 'noframes':\n                    $this->insertElement($token);\n\n                    /* Switch the tokeniser's content model flag to the CDATA state. */\n                    return HTML5::CDATA;\n                break;\n\n                /* A start tag whose tag name is \"select\" */\n                case 'select':\n                    /* Reconstruct the active formatting elements, if any. */\n                    $this->reconstructActiveFormattingElements();\n\n                    /* Insert an HTML element for the token. */\n                    $this->insertElement($token);\n\n                    /* Change the insertion mode to \"in select\". */\n                    $this->mode = self::IN_SELECT;\n                break;\n\n                /* A start or end tag whose tag name is one of: \"caption\", \"col\",\n                \"colgroup\", \"frame\", \"frameset\", \"head\", \"option\", \"optgroup\",\n                \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\". */\n                case 'caption': case 'col': case 'colgroup': case 'frame':\n                case 'frameset': case 'head': case 'option': case 'optgroup':\n                case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead':\n                case 'tr':\n                    // Parse error. Ignore the token.\n                break;\n\n                /* A start or end tag whose tag name is one of: \"event-source\",\n                \"section\", \"nav\", \"article\", \"aside\", \"header\", \"footer\",\n                \"datagrid\", \"command\" */\n                case 'event-source': case 'section': case 'nav': case 'article':\n                case 'aside': case 'header': case 'footer': case 'datagrid':\n                case 'command':\n                    // Work in progress!\n                break;\n\n                /* A start tag token not covered by the previous entries */\n                default:\n                    /* Reconstruct the active formatting elements, if any. */\n                    $this->reconstructActiveFormattingElements();\n\n                    $this->insertElement($token, true, true);\n                break;\n            }\n            break;\n\n            case HTML5::ENDTAG:\n            switch($token['name']) {\n                /* An end tag with the tag name \"body\" */\n                case 'body':\n                    /* If the second element in the stack of open elements is\n                    not a body element, this is a parse error. Ignore the token.\n                    (innerHTML case) */\n                    if(count($this->stack) < 2 || $this->stack[1]->nodeName !== 'body') {\n                        // Ignore.\n\n                    /* If the current node is not the body element, then this\n                    is a parse error. */\n                    } elseif(end($this->stack)->nodeName !== 'body') {\n                        // Parse error.\n                    }\n\n                    /* Change the insertion mode to \"after body\". */\n                    $this->mode = self::AFTER_BODY;\n                break;\n\n                /* An end tag with the tag name \"html\" */\n                case 'html':\n                    /* Act as if an end tag with tag name \"body\" had been seen,\n                    then, if that token wasn't ignored, reprocess the current\n                    token. */\n                    $this->inBody(array(\n                        'name' => 'body',\n                        'type' => HTML5::ENDTAG\n                    ));\n\n                    return $this->afterBody($token);\n                break;\n\n                /* An end tag whose tag name is one of: \"address\", \"blockquote\",\n                \"center\", \"dir\", \"div\", \"dl\", \"fieldset\", \"listing\", \"menu\",\n                \"ol\", \"pre\", \"ul\" */\n                case 'address': case 'blockquote': case 'center': case 'dir':\n                case 'div': case 'dl': case 'fieldset': case 'listing':\n                case 'menu': case 'ol': case 'pre': case 'ul':\n                    /* If the stack of open elements has an element in scope\n                    with the same tag name as that of the token, then generate\n                    implied end tags. */\n                    if($this->elementInScope($token['name'])) {\n                        $this->generateImpliedEndTags();\n\n                        /* Now, if the current node is not an element with\n                        the same tag name as that of the token, then this\n                        is a parse error. */\n                        // w/e\n\n                        /* If the stack of open elements has an element in\n                        scope with the same tag name as that of the token,\n                        then pop elements from this stack until an element\n                        with that tag name has been popped from the stack. */\n                        for($n = count($this->stack) - 1; $n >= 0; $n--) {\n                            if($this->stack[$n]->nodeName === $token['name']) {\n                                $n = -1;\n                            }\n\n                            array_pop($this->stack);\n                        }\n                    }\n                break;\n\n                /* An end tag whose tag name is \"form\" */\n                case 'form':\n                    /* If the stack of open elements has an element in scope\n                    with the same tag name as that of the token, then generate\n                    implied    end tags. */\n                    if($this->elementInScope($token['name'])) {\n                        $this->generateImpliedEndTags();\n\n                    } \n\n                    if(end($this->stack)->nodeName !== $token['name']) {\n                        /* Now, if the current node is not an element with the\n                        same tag name as that of the token, then this is a parse\n                        error. */\n                        // w/e\n\n                    } else {\n                        /* Otherwise, if the current node is an element with\n                        the same tag name as that of the token pop that element\n                        from the stack. */\n                        array_pop($this->stack);\n                    }\n\n                    /* In any case, set the form element pointer to null. */\n                    $this->form_pointer = null;\n                break;\n\n                /* An end tag whose tag name is \"p\" */\n                case 'p':\n                    /* If the stack of open elements has a p element in scope,\n                    then generate implied end tags, except for p elements. */\n                    if($this->elementInScope('p')) {\n                        $this->generateImpliedEndTags(array('p'));\n\n                        /* If the current node is not a p element, then this is\n                        a parse error. */\n                        // k\n\n                        /* If the stack of open elements has a p element in\n                        scope, then pop elements from this stack until the stack\n                        no longer has a p element in scope. */\n                        for($n = count($this->stack) - 1; $n >= 0; $n--) {\n                            if($this->elementInScope('p')) {\n                                array_pop($this->stack);\n\n                            } else {\n                                break;\n                            }\n                        }\n                    }\n                break;\n\n                /* An end tag whose tag name is \"dd\", \"dt\", or \"li\" */\n                case 'dd': case 'dt': case 'li':\n                    /* If the stack of open elements has an element in scope\n                    whose tag name matches the tag name of the token, then\n                    generate implied end tags, except for elements with the\n                    same tag name as the token. */\n                    if($this->elementInScope($token['name'])) {\n                        $this->generateImpliedEndTags(array($token['name']));\n\n                        /* If the current node is not an element with the same\n                        tag name as the token, then this is a parse error. */\n                        // w/e\n\n                        /* If the stack of open elements has an element in scope\n                        whose tag name matches the tag name of the token, then\n                        pop elements from this stack until an element with that\n                        tag name has been popped from the stack. */\n                        for($n = count($this->stack) - 1; $n >= 0; $n--) {\n                            if($this->stack[$n]->nodeName === $token['name']) {\n                                $n = -1;\n                            }\n\n                            array_pop($this->stack);\n                        }\n                    }\n                break;\n\n                /* An end tag whose tag name is one of: \"h1\", \"h2\", \"h3\", \"h4\",\n                \"h5\", \"h6\" */\n                case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':\n                    $elements = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6');\n\n                    /* If the stack of open elements has in scope an element whose\n                    tag name is one of \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", or \"h6\", then\n                    generate implied end tags. */\n                    if($this->elementInScope($elements)) {\n                        $this->generateImpliedEndTags();\n\n                        /* Now, if the current node is not an element with the same\n                        tag name as that of the token, then this is a parse error. */\n                        // w/e\n\n                        /* If the stack of open elements has in scope an element\n                        whose tag name is one of \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", or\n                        \"h6\", then pop elements from the stack until an element\n                        with one of those tag names has been popped from the stack. */\n                        while($this->elementInScope($elements)) {\n                            array_pop($this->stack);\n                        }\n                    }\n                break;\n\n                /* An end tag whose tag name is one of: \"a\", \"b\", \"big\", \"em\",\n                \"font\", \"i\", \"nobr\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\" */\n                case 'a': case 'b': case 'big': case 'em': case 'font':\n                case 'i': case 'nobr': case 's': case 'small': case 'strike':\n                case 'strong': case 'tt': case 'u':\n                    /* 1. Let the formatting element be the last element in\n                    the list of active formatting elements that:\n                        * is between the end of the list and the last scope\n                        marker in the list, if any, or the start of the list\n                        otherwise, and\n                        * has the same tag name as the token.\n                    */\n                    while(true) {\n                        for($a = count($this->a_formatting) - 1; $a >= 0; $a--) {\n                            if($this->a_formatting[$a] === self::MARKER) {\n                                break;\n\n                            } elseif($this->a_formatting[$a]->tagName === $token['name']) {\n                                $formatting_element = $this->a_formatting[$a];\n                                $in_stack = in_array($formatting_element, $this->stack, true);\n                                $fe_af_pos = $a;\n                                break;\n                            }\n                        }\n\n                        /* If there is no such node, or, if that node is\n                        also in the stack of open elements but the element\n                        is not in scope, then this is a parse error. Abort\n                        these steps. The token is ignored. */\n                        if(!isset($formatting_element) || ($in_stack &&\n                        !$this->elementInScope($token['name']))) {\n                            break;\n\n                        /* Otherwise, if there is such a node, but that node\n                        is not in the stack of open elements, then this is a\n                        parse error; remove the element from the list, and\n                        abort these steps. */\n                        } elseif(isset($formatting_element) && !$in_stack) {\n                            unset($this->a_formatting[$fe_af_pos]);\n                            $this->a_formatting = array_merge($this->a_formatting);\n                            break;\n                        }\n\n                        /* 2. Let the furthest block be the topmost node in the\n                        stack of open elements that is lower in the stack\n                        than the formatting element, and is not an element in\n                        the phrasing or formatting categories. There might\n                        not be one. */\n                        $fe_s_pos = array_search($formatting_element, $this->stack, true);\n                        $length = count($this->stack);\n\n                        for($s = $fe_s_pos + 1; $s < $length; $s++) {\n                            $category = $this->getElementCategory($this->stack[$s]->nodeName);\n\n                            if($category !== self::PHRASING && $category !== self::FORMATTING) {\n                                $furthest_block = $this->stack[$s];\n                            }\n                        }\n\n                        /* 3. If there is no furthest block, then the UA must\n                        skip the subsequent steps and instead just pop all\n                        the nodes from the bottom of the stack of open\n                        elements, from the current node up to the formatting\n                        element, and remove the formatting element from the\n                        list of active formatting elements. */\n                        if(!isset($furthest_block)) {\n                            for($n = $length - 1; $n >= $fe_s_pos; $n--) {\n                                array_pop($this->stack);\n                            }\n\n                            unset($this->a_formatting[$fe_af_pos]);\n                            $this->a_formatting = array_merge($this->a_formatting);\n                            break;\n                        }\n\n                        /* 4. Let the common ancestor be the element\n                        immediately above the formatting element in the stack\n                        of open elements. */\n                        $common_ancestor = $this->stack[$fe_s_pos - 1];\n\n                        /* 5. If the furthest block has a parent node, then\n                        remove the furthest block from its parent node. */\n                        if($furthest_block->parentNode !== null) {\n                            $furthest_block->parentNode->removeChild($furthest_block);\n                        }\n\n                        /* 6. Let a bookmark note the position of the\n                        formatting element in the list of active formatting\n                        elements relative to the elements on either side\n                        of it in the list. */\n                        $bookmark = $fe_af_pos;\n\n                        /* 7. Let node and last node  be the furthest block.\n                        Follow these steps: */\n                        $node = $furthest_block;\n                        $last_node = $furthest_block;\n\n                        while(true) {\n                            for($n = array_search($node, $this->stack, true) - 1; $n >= 0; $n--) {\n                                /* 7.1 Let node be the element immediately\n                                prior to node in the stack of open elements. */\n                                $node = $this->stack[$n];\n\n                                /* 7.2 If node is not in the list of active\n                                formatting elements, then remove node from\n                                the stack of open elements and then go back\n                                to step 1. */\n                                if(!in_array($node, $this->a_formatting, true)) {\n                                    unset($this->stack[$n]);\n                                    $this->stack = array_merge($this->stack);\n\n                                } else {\n                                    break;\n                                }\n                            }\n\n                            /* 7.3 Otherwise, if node is the formatting\n                            element, then go to the next step in the overall\n                            algorithm. */\n                            if($node === $formatting_element) {\n                                break;\n\n                            /* 7.4 Otherwise, if last node is the furthest\n                            block, then move the aforementioned bookmark to\n                            be immediately after the node in the list of\n                            active formatting elements. */\n                            } elseif($last_node === $furthest_block) {\n                                $bookmark = array_search($node, $this->a_formatting, true) + 1;\n                            }\n\n                            /* 7.5 If node has any children, perform a\n                            shallow clone of node, replace the entry for\n                            node in the list of active formatting elements\n                            with an entry for the clone, replace the entry\n                            for node in the stack of open elements with an\n                            entry for the clone, and let node be the clone. */\n                            if($node->hasChildNodes()) {\n                                $clone = $node->cloneNode();\n                                $s_pos = array_search($node, $this->stack, true);\n                                $a_pos = array_search($node, $this->a_formatting, true);\n\n                                $this->stack[$s_pos] = $clone;\n                                $this->a_formatting[$a_pos] = $clone;\n                                $node = $clone;\n                            }\n\n                            /* 7.6 Insert last node into node, first removing\n                            it from its previous parent node if any. */\n                            if($last_node->parentNode !== null) {\n                                $last_node->parentNode->removeChild($last_node);\n                            }\n\n                            $node->appendChild($last_node);\n\n                            /* 7.7 Let last node be node. */\n                            $last_node = $node;\n                        }\n\n                        /* 8. Insert whatever last node ended up being in\n                        the previous step into the common ancestor node,\n                        first removing it from its previous parent node if\n                        any. */\n                        if($last_node->parentNode !== null) {\n                            $last_node->parentNode->removeChild($last_node);\n                        }\n\n                        $common_ancestor->appendChild($last_node);\n\n                        /* 9. Perform a shallow clone of the formatting\n                        element. */\n                        $clone = $formatting_element->cloneNode();\n\n                        /* 10. Take all of the child nodes of the furthest\n                        block and append them to the clone created in the\n                        last step. */\n                        while($furthest_block->hasChildNodes()) {\n                            $child = $furthest_block->firstChild;\n                            $furthest_block->removeChild($child);\n                            $clone->appendChild($child);\n                        }\n\n                        /* 11. Append that clone to the furthest block. */\n                        $furthest_block->appendChild($clone);\n\n                        /* 12. Remove the formatting element from the list\n                        of active formatting elements, and insert the clone\n                        into the list of active formatting elements at the\n                        position of the aforementioned bookmark. */\n                        $fe_af_pos = array_search($formatting_element, $this->a_formatting, true);\n                        unset($this->a_formatting[$fe_af_pos]);\n                        $this->a_formatting = array_merge($this->a_formatting);\n\n                        $af_part1 = array_slice($this->a_formatting, 0, $bookmark - 1);\n                        $af_part2 = array_slice($this->a_formatting, $bookmark, count($this->a_formatting));\n                        $this->a_formatting = array_merge($af_part1, array($clone), $af_part2);\n\n                        /* 13. Remove the formatting element from the stack\n                        of open elements, and insert the clone into the stack\n                        of open elements immediately after (i.e. in a more\n                        deeply nested position than) the position of the\n                        furthest block in that stack. */\n                        $fe_s_pos = array_search($formatting_element, $this->stack, true);\n                        $fb_s_pos = array_search($furthest_block, $this->stack, true);\n                        unset($this->stack[$fe_s_pos]);\n\n                        $s_part1 = array_slice($this->stack, 0, $fb_s_pos);\n                        $s_part2 = array_slice($this->stack, $fb_s_pos + 1, count($this->stack));\n                        $this->stack = array_merge($s_part1, array($clone), $s_part2);\n\n                        /* 14. Jump back to step 1 in this series of steps. */\n                        unset($formatting_element, $fe_af_pos, $fe_s_pos, $furthest_block);\n                    }\n                break;\n\n                /* An end tag token whose tag name is one of: \"button\",\n                \"marquee\", \"object\" */\n                case 'button': case 'marquee': case 'object':\n                    /* If the stack of open elements has an element in scope whose\n                    tag name matches the tag name of the token, then generate implied\n                    tags. */\n                    if($this->elementInScope($token['name'])) {\n                        $this->generateImpliedEndTags();\n\n                        /* Now, if the current node is not an element with the same\n                        tag name as the token, then this is a parse error. */\n                        // k\n\n                        /* Now, if the stack of open elements has an element in scope\n                        whose tag name matches the tag name of the token, then pop\n                        elements from the stack until that element has been popped from\n                        the stack, and clear the list of active formatting elements up\n                        to the last marker. */\n                        for($n = count($this->stack) - 1; $n >= 0; $n--) {\n                            if($this->stack[$n]->nodeName === $token['name']) {\n                                $n = -1;\n                            }\n\n                            array_pop($this->stack);\n                        }\n\n                        $marker = end(array_keys($this->a_formatting, self::MARKER, true));\n\n                        for($n = count($this->a_formatting) - 1; $n > $marker; $n--) {\n                            array_pop($this->a_formatting);\n                        }\n                    }\n                break;\n\n                /* Or an end tag whose tag name is one of: \"area\", \"basefont\",\n                \"bgsound\", \"br\", \"embed\", \"hr\", \"iframe\", \"image\", \"img\",\n                \"input\", \"isindex\", \"noembed\", \"noframes\", \"param\", \"select\",\n                \"spacer\", \"table\", \"textarea\", \"wbr\" */\n                case 'area': case 'basefont': case 'bgsound': case 'br':\n                case 'embed': case 'hr': case 'iframe': case 'image':\n                case 'img': case 'input': case 'isindex': case 'noembed':\n                case 'noframes': case 'param': case 'select': case 'spacer':\n                case 'table': case 'textarea': case 'wbr':\n                    // Parse error. Ignore the token.\n                break;\n\n                /* An end tag token not covered by the previous entries */\n                default:\n                    for($n = count($this->stack) - 1; $n >= 0; $n--) {\n                        /* Initialise node to be the current node (the bottommost\n                        node of the stack). */\n                        $node = end($this->stack);\n\n                        /* If node has the same tag name as the end tag token,\n                        then: */\n                        if($token['name'] === $node->nodeName) {\n                            /* Generate implied end tags. */\n                            $this->generateImpliedEndTags();\n\n                            /* If the tag name of the end tag token does not\n                            match the tag name of the current node, this is a\n                            parse error. */\n                            // k\n\n                            /* Pop all the nodes from the current node up to\n                            node, including node, then stop this algorithm. */\n                            for($x = count($this->stack) - $n; $x >= $n; $x--) {\n                                array_pop($this->stack);\n                            }\n                                    \n                        } else {\n                            $category = $this->getElementCategory($node);\n\n                            if($category !== self::SPECIAL && $category !== self::SCOPING) {\n                                /* Otherwise, if node is in neither the formatting\n                                category nor the phrasing category, then this is a\n                                parse error. Stop this algorithm. The end tag token\n                                is ignored. */\n                                return false;\n                            }\n                        }\n                    }\n                break;\n            }\n            break;\n        }\n    }\n\n    private function inTable($token) {\n        $clear = array('html', 'table');\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE */\n        if($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) {\n            /* Append the character to the current node. */\n            $text = $this->dom->createTextNode($token['data']);\n            end($this->stack)->appendChild($text);\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the current node with the data\n            attribute set to the data given in the comment token. */\n            $comment = $this->dom->createComment($token['data']);\n            end($this->stack)->appendChild($comment);\n\n        /* A start tag whose tag name is \"caption\" */\n        } elseif($token['type'] === HTML5::STARTTAG &&\n        $token['name'] === 'caption') {\n            /* Clear the stack back to a table context. */\n            $this->clearStackToTableContext($clear);\n\n            /* Insert a marker at the end of the list of active\n            formatting elements. */\n            $this->a_formatting[] = self::MARKER;\n\n            /* Insert an HTML element for the token, then switch the\n            insertion mode to \"in caption\". */\n            $this->insertElement($token);\n            $this->mode = self::IN_CAPTION;\n\n        /* A start tag whose tag name is \"colgroup\" */\n        } elseif($token['type'] === HTML5::STARTTAG &&\n        $token['name'] === 'colgroup') {\n            /* Clear the stack back to a table context. */\n            $this->clearStackToTableContext($clear);\n\n            /* Insert an HTML element for the token, then switch the\n            insertion mode to \"in column group\". */\n            $this->insertElement($token);\n            $this->mode = self::IN_CGROUP;\n\n        /* A start tag whose tag name is \"col\" */\n        } elseif($token['type'] === HTML5::STARTTAG &&\n        $token['name'] === 'col') {\n            $this->inTable(array(\n                'name' => 'colgroup',\n                'type' => HTML5::STARTTAG,\n                'attr' => array()\n            ));\n\n            $this->inColumnGroup($token);\n\n        /* A start tag whose tag name is one of: \"tbody\", \"tfoot\", \"thead\" */\n        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],\n        array('tbody', 'tfoot', 'thead'))) {\n            /* Clear the stack back to a table context. */\n            $this->clearStackToTableContext($clear);\n\n            /* Insert an HTML element for the token, then switch the insertion\n            mode to \"in table body\". */\n            $this->insertElement($token);\n            $this->mode = self::IN_TBODY;\n\n        /* A start tag whose tag name is one of: \"td\", \"th\", \"tr\" */\n        } elseif($token['type'] === HTML5::STARTTAG &&\n        in_array($token['name'], array('td', 'th', 'tr'))) {\n            /* Act as if a start tag token with the tag name \"tbody\" had been\n            seen, then reprocess the current token. */\n            $this->inTable(array(\n                'name' => 'tbody',\n                'type' => HTML5::STARTTAG,\n                'attr' => array()\n            ));\n\n            return $this->inTableBody($token);\n\n        /* A start tag whose tag name is \"table\" */\n        } elseif($token['type'] === HTML5::STARTTAG &&\n        $token['name'] === 'table') {\n            /* Parse error. Act as if an end tag token with the tag name \"table\"\n            had been seen, then, if that token wasn't ignored, reprocess the\n            current token. */\n            $this->inTable(array(\n                'name' => 'table',\n                'type' => HTML5::ENDTAG\n            ));\n\n            return $this->mainPhase($token);\n\n        /* An end tag whose tag name is \"table\" */\n        } elseif($token['type'] === HTML5::ENDTAG &&\n        $token['name'] === 'table') {\n            /* If the stack of open elements does not have an element in table\n            scope with the same tag name as the token, this is a parse error.\n            Ignore the token. (innerHTML case) */\n            if(!$this->elementInScope($token['name'], true)) {\n                return false;\n\n            /* Otherwise: */\n            } else {\n                /* Generate implied end tags. */\n                $this->generateImpliedEndTags();\n\n                /* Now, if the current node is not a table element, then this\n                is a parse error. */\n                // w/e\n\n                /* Pop elements from this stack until a table element has been\n                popped from the stack. */\n                while(true) {\n                    $current = end($this->stack)->nodeName;\n                    array_pop($this->stack);\n\n                    if($current === 'table') {\n                        break;\n                    }\n                }\n\n                /* Reset the insertion mode appropriately. */\n                $this->resetInsertionMode();\n            }\n\n        /* An end tag whose tag name is one of: \"body\", \"caption\", \"col\",\n        \"colgroup\", \"html\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\" */\n        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],\n        array('body', 'caption', 'col', 'colgroup', 'html', 'tbody', 'td',\n        'tfoot', 'th', 'thead', 'tr'))) {\n            // Parse error. Ignore the token.\n\n        /* Anything else */\n        } else {\n            /* Parse error. Process the token as if the insertion mode was \"in\n            body\", with the following exception: */\n\n            /* If the current node is a table, tbody, tfoot, thead, or tr\n            element, then, whenever a node would be inserted into the current\n            node, it must instead be inserted into the foster parent element. */\n            if(in_array(end($this->stack)->nodeName,\n            array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {\n                /* The foster parent element is the parent element of the last\n                table element in the stack of open elements, if there is a\n                table element and it has such a parent element. If there is no\n                table element in the stack of open elements (innerHTML case),\n                then the foster parent element is the first element in the\n                stack of open elements (the html  element). Otherwise, if there\n                is a table element in the stack of open elements, but the last\n                table element in the stack of open elements has no parent, or\n                its parent node is not an element, then the foster parent\n                element is the element before the last table element in the\n                stack of open elements. */\n                for($n = count($this->stack) - 1; $n >= 0; $n--) {\n                    if($this->stack[$n]->nodeName === 'table') {\n                        $table = $this->stack[$n];\n                        break;\n                    }\n                }\n\n                if(isset($table) && $table->parentNode !== null) {\n                    $this->foster_parent = $table->parentNode;\n\n                } elseif(!isset($table)) {\n                    $this->foster_parent = $this->stack[0];\n\n                } elseif(isset($table) && ($table->parentNode === null ||\n                $table->parentNode->nodeType !== XML_ELEMENT_NODE)) {\n                    $this->foster_parent = $this->stack[$n - 1];\n                }\n            }\n\n            $this->inBody($token);\n        }\n    }\n\n    private function inCaption($token) {\n        /* An end tag whose tag name is \"caption\" */\n        if($token['type'] === HTML5::ENDTAG && $token['name'] === 'caption') {\n            /* If the stack of open elements does not have an element in table\n            scope with the same tag name as the token, this is a parse error.\n            Ignore the token. (innerHTML case) */\n            if(!$this->elementInScope($token['name'], true)) {\n                // Ignore\n\n            /* Otherwise: */\n            } else {\n                /* Generate implied end tags. */\n                $this->generateImpliedEndTags();\n\n                /* Now, if the current node is not a caption element, then this\n                is a parse error. */\n                // w/e\n\n                /* Pop elements from this stack until a caption element has\n                been popped from the stack. */\n                while(true) {\n                    $node = end($this->stack)->nodeName;\n                    array_pop($this->stack);\n\n                    if($node === 'caption') {\n                        break;\n                    }\n                }\n\n                /* Clear the list of active formatting elements up to the last\n                marker. */\n                $this->clearTheActiveFormattingElementsUpToTheLastMarker();\n\n                /* Switch the insertion mode to \"in table\". */\n                $this->mode = self::IN_TABLE;\n            }\n\n        /* A start tag whose tag name is one of: \"caption\", \"col\", \"colgroup\",\n        \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\", or an end tag whose tag\n        name is \"table\" */\n        } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],\n        array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',\n        'thead', 'tr'))) || ($token['type'] === HTML5::ENDTAG &&\n        $token['name'] === 'table')) {\n            /* Parse error. Act as if an end tag with the tag name \"caption\"\n            had been seen, then, if that token wasn't ignored, reprocess the\n            current token. */\n            $this->inCaption(array(\n                'name' => 'caption',\n                'type' => HTML5::ENDTAG\n            ));\n\n            return $this->inTable($token);\n\n        /* An end tag whose tag name is one of: \"body\", \"col\", \"colgroup\",\n        \"html\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\" */\n        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],\n        array('body', 'col', 'colgroup', 'html', 'tbody', 'tfoot', 'th',\n        'thead', 'tr'))) {\n            // Parse error. Ignore the token.\n\n        /* Anything else */\n        } else {\n            /* Process the token as if the insertion mode was \"in body\". */\n            $this->inBody($token);\n        }\n    }\n\n    private function inColumnGroup($token) {\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE */\n        if($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) {\n            /* Append the character to the current node. */\n            $text = $this->dom->createTextNode($token['data']);\n            end($this->stack)->appendChild($text);\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the current node with the data\n            attribute set to the data given in the comment token. */\n            $comment = $this->dom->createComment($token['data']);\n            end($this->stack)->appendChild($comment);\n\n        /* A start tag whose tag name is \"col\" */\n        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'col') {\n            /* Insert a col element for the token. Immediately pop the current\n            node off the stack of open elements. */\n            $this->insertElement($token);\n            array_pop($this->stack);\n\n        /* An end tag whose tag name is \"colgroup\" */\n        } elseif($token['type'] === HTML5::ENDTAG &&\n        $token['name'] === 'colgroup') {\n            /* If the current node is the root html element, then this is a\n            parse error, ignore the token. (innerHTML case) */\n            if(end($this->stack)->nodeName === 'html') {\n                // Ignore\n\n            /* Otherwise, pop the current node (which will be a colgroup\n            element) from the stack of open elements. Switch the insertion\n            mode to \"in table\". */\n            } else {\n                array_pop($this->stack);\n                $this->mode = self::IN_TABLE;\n            }\n\n        /* An end tag whose tag name is \"col\" */\n        } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'col') {\n            /* Parse error. Ignore the token. */\n\n        /* Anything else */\n        } else {\n            /* Act as if an end tag with the tag name \"colgroup\" had been seen,\n            and then, if that token wasn't ignored, reprocess the current token. */\n            $this->inColumnGroup(array(\n                'name' => 'colgroup',\n                'type' => HTML5::ENDTAG\n            ));\n\n            return $this->inTable($token);\n        }\n    }\n\n    private function inTableBody($token) {\n        $clear = array('tbody', 'tfoot', 'thead', 'html');\n\n        /* A start tag whose tag name is \"tr\" */\n        if($token['type'] === HTML5::STARTTAG && $token['name'] === 'tr') {\n            /* Clear the stack back to a table body context. */\n            $this->clearStackToTableContext($clear);\n\n            /* Insert a tr element for the token, then switch the insertion\n            mode to \"in row\". */\n            $this->insertElement($token);\n            $this->mode = self::IN_ROW;\n\n        /* A start tag whose tag name is one of: \"th\", \"td\" */\n        } elseif($token['type'] === HTML5::STARTTAG &&\n        ($token['name'] === 'th' ||    $token['name'] === 'td')) {\n            /* Parse error. Act as if a start tag with the tag name \"tr\" had\n            been seen, then reprocess the current token. */\n            $this->inTableBody(array(\n                'name' => 'tr',\n                'type' => HTML5::STARTTAG,\n                'attr' => array()\n            ));\n\n            return $this->inRow($token);\n\n        /* An end tag whose tag name is one of: \"tbody\", \"tfoot\", \"thead\" */\n        } elseif($token['type'] === HTML5::ENDTAG &&\n        in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {\n            /* If the stack of open elements does not have an element in table\n            scope with the same tag name as the token, this is a parse error.\n            Ignore the token. */\n            if(!$this->elementInScope($token['name'], true)) {\n                // Ignore\n\n            /* Otherwise: */\n            } else {\n                /* Clear the stack back to a table body context. */\n                $this->clearStackToTableContext($clear);\n\n                /* Pop the current node from the stack of open elements. Switch\n                the insertion mode to \"in table\". */\n                array_pop($this->stack);\n                $this->mode = self::IN_TABLE;\n            }\n\n        /* A start tag whose tag name is one of: \"caption\", \"col\", \"colgroup\",\n        \"tbody\", \"tfoot\", \"thead\", or an end tag whose tag name is \"table\" */\n        } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],\n        array('caption', 'col', 'colgroup', 'tbody', 'tfoor', 'thead'))) ||\n        ($token['type'] === HTML5::STARTTAG && $token['name'] === 'table')) {\n            /* If the stack of open elements does not have a tbody, thead, or\n            tfoot element in table scope, this is a parse error. Ignore the\n            token. (innerHTML case) */\n            if(!$this->elementInScope(array('tbody', 'thead', 'tfoot'), true)) {\n                // Ignore.\n\n            /* Otherwise: */\n            } else {\n                /* Clear the stack back to a table body context. */\n                $this->clearStackToTableContext($clear);\n\n                /* Act as if an end tag with the same tag name as the current\n                node (\"tbody\", \"tfoot\", or \"thead\") had been seen, then\n                reprocess the current token. */\n                $this->inTableBody(array(\n                    'name' => end($this->stack)->nodeName,\n                    'type' => HTML5::ENDTAG\n                ));\n\n                return $this->mainPhase($token);\n            }\n\n        /* An end tag whose tag name is one of: \"body\", \"caption\", \"col\",\n        \"colgroup\", \"html\", \"td\", \"th\", \"tr\" */\n        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],\n        array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {\n            /* Parse error. Ignore the token. */\n\n        /* Anything else */\n        } else {\n            /* Process the token as if the insertion mode was \"in table\". */\n            $this->inTable($token);\n        }\n    }\n\n    private function inRow($token) {\n        $clear = array('tr', 'html');\n\n        /* A start tag whose tag name is one of: \"th\", \"td\" */\n        if($token['type'] === HTML5::STARTTAG &&\n        ($token['name'] === 'th' || $token['name'] === 'td')) {\n            /* Clear the stack back to a table row context. */\n            $this->clearStackToTableContext($clear);\n\n            /* Insert an HTML element for the token, then switch the insertion\n            mode to \"in cell\". */\n            $this->insertElement($token);\n            $this->mode = self::IN_CELL;\n\n            /* Insert a marker at the end of the list of active formatting\n            elements. */\n            $this->a_formatting[] = self::MARKER;\n\n        /* An end tag whose tag name is \"tr\" */\n        } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'tr') {\n            /* If the stack of open elements does not have an element in table\n            scope with the same tag name as the token, this is a parse error.\n            Ignore the token. (innerHTML case) */\n            if(!$this->elementInScope($token['name'], true)) {\n                // Ignore.\n\n            /* Otherwise: */\n            } else {\n                /* Clear the stack back to a table row context. */\n                $this->clearStackToTableContext($clear);\n\n                /* Pop the current node (which will be a tr element) from the\n                stack of open elements. Switch the insertion mode to \"in table\n                body\". */\n                array_pop($this->stack);\n                $this->mode = self::IN_TBODY;\n            }\n\n        /* A start tag whose tag name is one of: \"caption\", \"col\", \"colgroup\",\n        \"tbody\", \"tfoot\", \"thead\", \"tr\" or an end tag whose tag name is \"table\" */\n        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],\n        array('caption', 'col', 'colgroup', 'tbody', 'tfoot', 'thead', 'tr'))) {\n            /* Act as if an end tag with the tag name \"tr\" had been seen, then,\n            if that token wasn't ignored, reprocess the current token. */\n            $this->inRow(array(\n                'name' => 'tr',\n                'type' => HTML5::ENDTAG\n            ));\n\n            return $this->inCell($token);\n\n        /* An end tag whose tag name is one of: \"tbody\", \"tfoot\", \"thead\" */\n        } elseif($token['type'] === HTML5::ENDTAG &&\n        in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {\n            /* If the stack of open elements does not have an element in table\n            scope with the same tag name as the token, this is a parse error.\n            Ignore the token. */\n            if(!$this->elementInScope($token['name'], true)) {\n                // Ignore.\n\n            /* Otherwise: */\n            } else {\n                /* Otherwise, act as if an end tag with the tag name \"tr\" had\n                been seen, then reprocess the current token. */\n                $this->inRow(array(\n                    'name' => 'tr',\n                    'type' => HTML5::ENDTAG\n                ));\n\n                return $this->inCell($token);\n            }\n\n        /* An end tag whose tag name is one of: \"body\", \"caption\", \"col\",\n        \"colgroup\", \"html\", \"td\", \"th\" */\n        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],\n        array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {\n            /* Parse error. Ignore the token. */\n\n        /* Anything else */\n        } else {\n            /* Process the token as if the insertion mode was \"in table\". */\n            $this->inTable($token);\n        }\n    }\n\n    private function inCell($token) {\n        /* An end tag whose tag name is one of: \"td\", \"th\" */\n        if($token['type'] === HTML5::ENDTAG &&\n        ($token['name'] === 'td' || $token['name'] === 'th')) {\n            /* If the stack of open elements does not have an element in table\n            scope with the same tag name as that of the token, then this is a\n            parse error and the token must be ignored. */\n            if(!$this->elementInScope($token['name'], true)) {\n                // Ignore.\n\n            /* Otherwise: */\n            } else {\n                /* Generate implied end tags, except for elements with the same\n                tag name as the token. */\n                $this->generateImpliedEndTags(array($token['name']));\n\n                /* Now, if the current node is not an element with the same tag\n                name as the token, then this is a parse error. */\n                // k\n\n                /* Pop elements from this stack until an element with the same\n                tag name as the token has been popped from the stack. */\n                while(true) {\n                    $node = end($this->stack)->nodeName;\n                    array_pop($this->stack);\n\n                    if($node === $token['name']) {\n                        break;\n                    }\n                }\n\n                /* Clear the list of active formatting elements up to the last\n                marker. */\n                $this->clearTheActiveFormattingElementsUpToTheLastMarker();\n\n                /* Switch the insertion mode to \"in row\". (The current node\n                will be a tr element at this point.) */\n                $this->mode = self::IN_ROW;\n            }\n\n        /* A start tag whose tag name is one of: \"caption\", \"col\", \"colgroup\",\n        \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\" */\n        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],\n        array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',\n        'thead', 'tr'))) {\n            /* If the stack of open elements does not have a td or th element\n            in table scope, then this is a parse error; ignore the token.\n            (innerHTML case) */\n            if(!$this->elementInScope(array('td', 'th'), true)) {\n                // Ignore.\n\n            /* Otherwise, close the cell (see below) and reprocess the current\n            token. */\n            } else {\n                $this->closeCell();\n                return $this->inRow($token);\n            }\n\n        /* A start tag whose tag name is one of: \"caption\", \"col\", \"colgroup\",\n        \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\" */\n        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],\n        array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',\n        'thead', 'tr'))) {\n            /* If the stack of open elements does not have a td or th element\n            in table scope, then this is a parse error; ignore the token.\n            (innerHTML case) */\n            if(!$this->elementInScope(array('td', 'th'), true)) {\n                // Ignore.\n\n            /* Otherwise, close the cell (see below) and reprocess the current\n            token. */\n            } else {\n                $this->closeCell();\n                return $this->inRow($token);\n            }\n\n        /* An end tag whose tag name is one of: \"body\", \"caption\", \"col\",\n        \"colgroup\", \"html\" */\n        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],\n        array('body', 'caption', 'col', 'colgroup', 'html'))) {\n            /* Parse error. Ignore the token. */\n\n        /* An end tag whose tag name is one of: \"table\", \"tbody\", \"tfoot\",\n        \"thead\", \"tr\" */\n        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],\n        array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {\n            /* If the stack of open elements does not have an element in table\n            scope with the same tag name as that of the token (which can only\n            happen for \"tbody\", \"tfoot\" and \"thead\", or, in the innerHTML case),\n            then this is a parse error and the token must be ignored. */\n            if(!$this->elementInScope($token['name'], true)) {\n                // Ignore.\n\n            /* Otherwise, close the cell (see below) and reprocess the current\n            token. */\n            } else {\n                $this->closeCell();\n                return $this->inRow($token);\n            }\n\n        /* Anything else */\n        } else {\n            /* Process the token as if the insertion mode was \"in body\". */\n            $this->inBody($token);\n        }\n    }\n\n    private function inSelect($token) {\n        /* Handle the token as follows: */\n\n        /* A character token */\n        if($token['type'] === HTML5::CHARACTR) {\n            /* Append the token's character to the current node. */\n            $this->insertText($token['data']);\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the current node with the data\n            attribute set to the data given in the comment token. */\n            $this->insertComment($token['data']);\n\n        /* A start tag token whose tag name is \"option\" */\n        } elseif($token['type'] === HTML5::STARTTAG &&\n        $token['name'] === 'option') {\n            /* If the current node is an option element, act as if an end tag\n            with the tag name \"option\" had been seen. */\n            if(end($this->stack)->nodeName === 'option') {\n                $this->inSelect(array(\n                    'name' => 'option',\n                    'type' => HTML5::ENDTAG\n                ));\n            }\n\n            /* Insert an HTML element for the token. */\n            $this->insertElement($token);\n\n        /* A start tag token whose tag name is \"optgroup\" */\n        } elseif($token['type'] === HTML5::STARTTAG &&\n        $token['name'] === 'optgroup') {\n            /* If the current node is an option element, act as if an end tag\n            with the tag name \"option\" had been seen. */\n            if(end($this->stack)->nodeName === 'option') {\n                $this->inSelect(array(\n                    'name' => 'option',\n                    'type' => HTML5::ENDTAG\n                ));\n            }\n\n            /* If the current node is an optgroup element, act as if an end tag\n            with the tag name \"optgroup\" had been seen. */\n            if(end($this->stack)->nodeName === 'optgroup') {\n                $this->inSelect(array(\n                    'name' => 'optgroup',\n                    'type' => HTML5::ENDTAG\n                ));\n            }\n\n            /* Insert an HTML element for the token. */\n            $this->insertElement($token);\n\n        /* An end tag token whose tag name is \"optgroup\" */\n        } elseif($token['type'] === HTML5::ENDTAG &&\n        $token['name'] === 'optgroup') {\n            /* First, if the current node is an option element, and the node\n            immediately before it in the stack of open elements is an optgroup\n            element, then act as if an end tag with the tag name \"option\" had\n            been seen. */\n            $elements_in_stack = count($this->stack);\n\n            if($this->stack[$elements_in_stack - 1]->nodeName === 'option' &&\n            $this->stack[$elements_in_stack - 2]->nodeName === 'optgroup') {\n                $this->inSelect(array(\n                    'name' => 'option',\n                    'type' => HTML5::ENDTAG\n                ));\n            }\n\n            /* If the current node is an optgroup element, then pop that node\n            from the stack of open elements. Otherwise, this is a parse error,\n            ignore the token. */\n            if($this->stack[$elements_in_stack - 1] === 'optgroup') {\n                array_pop($this->stack);\n            }\n\n        /* An end tag token whose tag name is \"option\" */\n        } elseif($token['type'] === HTML5::ENDTAG &&\n        $token['name'] === 'option') {\n            /* If the current node is an option element, then pop that node\n            from the stack of open elements. Otherwise, this is a parse error,\n            ignore the token. */\n            if(end($this->stack)->nodeName === 'option') {\n                array_pop($this->stack);\n            }\n\n        /* An end tag whose tag name is \"select\" */\n        } elseif($token['type'] === HTML5::ENDTAG &&\n        $token['name'] === 'select') {\n            /* If the stack of open elements does not have an element in table\n            scope with the same tag name as the token, this is a parse error.\n            Ignore the token. (innerHTML case) */\n            if(!$this->elementInScope($token['name'], true)) {\n                // w/e\n\n            /* Otherwise: */\n            } else {\n                /* Pop elements from the stack of open elements until a select\n                element has been popped from the stack. */\n                while(true) {\n                    $current = end($this->stack)->nodeName;\n                    array_pop($this->stack);\n\n                    if($current === 'select') {\n                        break;\n                    }\n                }\n\n                /* Reset the insertion mode appropriately. */\n                $this->resetInsertionMode();\n            }\n\n        /* A start tag whose tag name is \"select\" */\n        } elseif($token['name'] === 'select' &&\n        $token['type'] === HTML5::STARTTAG) {\n            /* Parse error. Act as if the token had been an end tag with the\n            tag name \"select\" instead. */\n            $this->inSelect(array(\n                'name' => 'select',\n                'type' => HTML5::ENDTAG\n            ));\n\n        /* An end tag whose tag name is one of: \"caption\", \"table\", \"tbody\",\n        \"tfoot\", \"thead\", \"tr\", \"td\", \"th\" */\n        } elseif(in_array($token['name'], array('caption', 'table', 'tbody',\n        'tfoot', 'thead', 'tr', 'td', 'th')) && $token['type'] === HTML5::ENDTAG) {\n            /* Parse error. */\n            // w/e\n\n            /* If the stack of open elements has an element in table scope with\n            the same tag name as that of the token, then act as if an end tag\n            with the tag name \"select\" had been seen, and reprocess the token.\n            Otherwise, ignore the token. */\n            if($this->elementInScope($token['name'], true)) {\n                $this->inSelect(array(\n                    'name' => 'select',\n                    'type' => HTML5::ENDTAG\n                ));\n\n                $this->mainPhase($token);\n            }\n\n        /* Anything else */\n        } else {\n            /* Parse error. Ignore the token. */\n        }\n    }\n\n    private function afterBody($token) {\n        /* Handle the token as follows: */\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE */\n        if($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) {\n            /* Process the token as it would be processed if the insertion mode\n            was \"in body\". */\n            $this->inBody($token);\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the first element in the stack of open\n            elements (the html element), with the data attribute set to the\n            data given in the comment token. */\n            $comment = $this->dom->createComment($token['data']);\n            $this->stack[0]->appendChild($comment);\n\n        /* An end tag with the tag name \"html\" */\n        } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') {\n            /* If the parser was originally created in order to handle the\n            setting of an element's innerHTML attribute, this is a parse error;\n            ignore the token. (The element will be an html element in this\n            case.) (innerHTML case) */\n\n            /* Otherwise, switch to the trailing end phase. */\n            $this->phase = self::END_PHASE;\n\n        /* Anything else */\n        } else {\n            /* Parse error. Set the insertion mode to \"in body\" and reprocess\n            the token. */\n            $this->mode = self::IN_BODY;\n            return $this->inBody($token);\n        }\n    }\n\n    private function inFrameset($token) {\n        /* Handle the token as follows: */\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */\n        if($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) {\n            /* Append the character to the current node. */\n            $this->insertText($token['data']);\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the current node with the data\n            attribute set to the data given in the comment token. */\n            $this->insertComment($token['data']);\n\n        /* A start tag with the tag name \"frameset\" */\n        } elseif($token['name'] === 'frameset' &&\n        $token['type'] === HTML5::STARTTAG) {\n            $this->insertElement($token);\n\n        /* An end tag with the tag name \"frameset\" */\n        } elseif($token['name'] === 'frameset' &&\n        $token['type'] === HTML5::ENDTAG) {\n            /* If the current node is the root html element, then this is a\n            parse error; ignore the token. (innerHTML case) */\n            if(end($this->stack)->nodeName === 'html') {\n                // Ignore\n\n            } else {\n                /* Otherwise, pop the current node from the stack of open\n                elements. */\n                array_pop($this->stack);\n\n                /* If the parser was not originally created in order to handle\n                the setting of an element's innerHTML attribute (innerHTML case),\n                and the current node is no longer a frameset element, then change\n                the insertion mode to \"after frameset\". */\n                $this->mode = self::AFTR_FRAME;\n            }\n\n        /* A start tag with the tag name \"frame\" */\n        } elseif($token['name'] === 'frame' &&\n        $token['type'] === HTML5::STARTTAG) {\n            /* Insert an HTML element for the token. */\n            $this->insertElement($token);\n\n            /* Immediately pop the current node off the stack of open elements. */\n            array_pop($this->stack);\n\n        /* A start tag with the tag name \"noframes\" */\n        } elseif($token['name'] === 'noframes' &&\n        $token['type'] === HTML5::STARTTAG) {\n            /* Process the token as if the insertion mode had been \"in body\". */\n            $this->inBody($token);\n\n        /* Anything else */\n        } else {\n            /* Parse error. Ignore the token. */\n        }\n    }\n\n    private function afterFrameset($token) {\n        /* Handle the token as follows: */\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */\n        if($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) {\n            /* Append the character to the current node. */\n            $this->insertText($token['data']);\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the current node with the data\n            attribute set to the data given in the comment token. */\n            $this->insertComment($token['data']);\n\n        /* An end tag with the tag name \"html\" */\n        } elseif($token['name'] === 'html' &&\n        $token['type'] === HTML5::ENDTAG) {\n            /* Switch to the trailing end phase. */\n            $this->phase = self::END_PHASE;\n\n        /* A start tag with the tag name \"noframes\" */\n        } elseif($token['name'] === 'noframes' &&\n        $token['type'] === HTML5::STARTTAG) {\n            /* Process the token as if the insertion mode had been \"in body\". */\n            $this->inBody($token);\n\n        /* Anything else */\n        } else {\n            /* Parse error. Ignore the token. */\n        }\n    }\n\n    private function trailingEndPhase($token) {\n        /* After the main phase, as each token is emitted from the tokenisation\n        stage, it must be processed as described in this section. */\n\n        /* A DOCTYPE token */\n        if($token['type'] === HTML5::DOCTYPE) {\n            // Parse error. Ignore the token.\n\n        /* A comment token */\n        } elseif($token['type'] === HTML5::COMMENT) {\n            /* Append a Comment node to the Document object with the data\n            attribute set to the data given in the comment token. */\n            $comment = $this->dom->createComment($token['data']);\n            $this->dom->appendChild($comment);\n\n        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE */\n        } elseif($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) {\n            /* Process the token as it would be processed in the main phase. */\n            $this->mainPhase($token);\n\n        /* A character token that is not one of U+0009 CHARACTER TABULATION,\n        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\n        or U+0020 SPACE. Or a start tag token. Or an end tag token. */\n        } elseif(($token['type'] === HTML5::CHARACTR &&\n        preg_match('/^[\\t\\n\\x0b\\x0c ]+$/', $token['data'])) ||\n        $token['type'] === HTML5::STARTTAG || $token['type'] === HTML5::ENDTAG) {\n            /* Parse error. Switch back to the main phase and reprocess the\n            token. */\n            $this->phase = self::MAIN_PHASE;\n            return $this->mainPhase($token);\n\n        /* An end-of-file token */\n        } elseif($token['type'] === HTML5::EOF) {\n            /* OMG DONE!! */\n        }\n    }\n\n    private function insertElement($token, $append = true, $check = false) {\n        // Proprietary workaround for libxml2's limitations with tag names\n        if ($check) {\n            // Slightly modified HTML5 tag-name modification,\n            // removing anything that's not an ASCII letter, digit, or hyphen\n            $token['name'] = preg_replace('/[^a-z0-9-]/i', '', $token['name']);\n            // Remove leading hyphens and numbers\n            $token['name'] = ltrim($token['name'], '-0..9');\n            // In theory, this should ever be needed, but just in case\n            if ($token['name'] === '') $token['name'] = 'span'; // arbitrary generic choice\n        }\n        \n        $el = $this->dom->createElement($token['name']);\n\n        foreach($token['attr'] as $attr) {\n            if(!$el->hasAttribute($attr['name'])) {\n                $el->setAttribute($attr['name'], $attr['value']);\n            }\n        }\n\n        $this->appendToRealParent($el);\n        $this->stack[] = $el;\n\n        return $el;\n    }\n\n    private function insertText($data) {\n        $text = $this->dom->createTextNode($data);\n        $this->appendToRealParent($text);\n    }\n\n    private function insertComment($data) {\n        $comment = $this->dom->createComment($data);\n        $this->appendToRealParent($comment);\n    }\n\n    private function appendToRealParent($node) {\n        if($this->foster_parent === null) {\n            end($this->stack)->appendChild($node);\n\n        } elseif($this->foster_parent !== null) {\n            /* If the foster parent element is the parent element of the\n            last table element in the stack of open elements, then the new\n            node must be inserted immediately before the last table element\n            in the stack of open elements in the foster parent element;\n            otherwise, the new node must be appended to the foster parent\n            element. */\n            for($n = count($this->stack) - 1; $n >= 0; $n--) {\n                if($this->stack[$n]->nodeName === 'table' &&\n                $this->stack[$n]->parentNode !== null) {\n                    $table = $this->stack[$n];\n                    break;\n                }\n            }\n\n            if(isset($table) && $this->foster_parent->isSameNode($table->parentNode))\n                $this->foster_parent->insertBefore($node, $table);\n            else\n                $this->foster_parent->appendChild($node);\n\n            $this->foster_parent = null;\n        }\n    }\n\n    private function elementInScope($el, $table = false) {\n        if(is_array($el)) {\n            foreach($el as $element) {\n                if($this->elementInScope($element, $table)) {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        $leng = count($this->stack);\n\n        for($n = 0; $n < $leng; $n++) {\n            /* 1. Initialise node to be the current node (the bottommost node of\n            the stack). */\n            $node = $this->stack[$leng - 1 - $n];\n\n            if($node->tagName === $el) {\n                /* 2. If node is the target node, terminate in a match state. */\n                return true;\n\n            } elseif($node->tagName === 'table') {\n                /* 3. Otherwise, if node is a table element, terminate in a failure\n                state. */\n                return false;\n\n            } elseif($table === true && in_array($node->tagName, array('caption', 'td',\n            'th', 'button', 'marquee', 'object'))) {\n                /* 4. Otherwise, if the algorithm is the \"has an element in scope\"\n                variant (rather than the \"has an element in table scope\" variant),\n                and node is one of the following, terminate in a failure state. */\n                return false;\n\n            } elseif($node === $node->ownerDocument->documentElement) {\n                /* 5. Otherwise, if node is an html element (root element), terminate\n                in a failure state. (This can only happen if the node is the topmost\n                node of the    stack of open elements, and prevents the next step from\n                being invoked if there are no more elements in the stack.) */\n                return false;\n            }\n\n            /* Otherwise, set node to the previous entry in the stack of open\n            elements and return to step 2. (This will never fail, since the loop\n            will always terminate in the previous step if the top of the stack\n            is reached.) */\n        }\n    }\n\n    private function reconstructActiveFormattingElements() {\n        /* 1. If there are no entries in the list of active formatting elements,\n        then there is nothing to reconstruct; stop this algorithm. */\n        $formatting_elements = count($this->a_formatting);\n\n        if($formatting_elements === 0) {\n            return false;\n        }\n\n        /* 3. Let entry be the last (most recently added) element in the list\n        of active formatting elements. */\n        $entry = end($this->a_formatting);\n\n        /* 2. If the last (most recently added) entry in the list of active\n        formatting elements is a marker, or if it is an element that is in the\n        stack of open elements, then there is nothing to reconstruct; stop this\n        algorithm. */\n        if($entry === self::MARKER || in_array($entry, $this->stack, true)) {\n            return false;\n        }\n\n        for($a = $formatting_elements - 1; $a >= 0; true) {\n            /* 4. If there are no entries before entry in the list of active\n            formatting elements, then jump to step 8. */\n            if($a === 0) {\n                $step_seven = false;\n                break;\n            }\n\n            /* 5. Let entry be the entry one earlier than entry in the list of\n            active formatting elements. */\n            $a--;\n            $entry = $this->a_formatting[$a];\n\n            /* 6. If entry is neither a marker nor an element that is also in\n            thetack of open elements, go to step 4. */\n            if($entry === self::MARKER || in_array($entry, $this->stack, true)) {\n                break;\n            }\n        }\n\n        while(true) {\n            /* 7. Let entry be the element one later than entry in the list of\n            active formatting elements. */\n            if(isset($step_seven) && $step_seven === true) {\n                $a++;\n                $entry = $this->a_formatting[$a];\n            }\n\n            /* 8. Perform a shallow clone of the element entry to obtain clone. */\n            $clone = $entry->cloneNode();\n\n            /* 9. Append clone to the current node and push it onto the stack\n            of open elements  so that it is the new current node. */\n            end($this->stack)->appendChild($clone);\n            $this->stack[] = $clone;\n\n            /* 10. Replace the entry for entry in the list with an entry for\n            clone. */\n            $this->a_formatting[$a] = $clone;\n\n            /* 11. If the entry for clone in the list of active formatting\n            elements is not the last entry in the list, return to step 7. */\n            if(end($this->a_formatting) !== $clone) {\n                $step_seven = true;\n            } else {\n                break;\n            }\n        }\n    }\n\n    private function clearTheActiveFormattingElementsUpToTheLastMarker() {\n        /* When the steps below require the UA to clear the list of active\n        formatting elements up to the last marker, the UA must perform the\n        following steps: */\n\n        while(true) {\n            /* 1. Let entry be the last (most recently added) entry in the list\n            of active formatting elements. */\n            $entry = end($this->a_formatting);\n\n            /* 2. Remove entry from the list of active formatting elements. */\n            array_pop($this->a_formatting);\n\n            /* 3. If entry was a marker, then stop the algorithm at this point.\n            The list has been cleared up to the last marker. */\n            if($entry === self::MARKER) {\n                break;\n            }\n        }\n    }\n\n    private function generateImpliedEndTags($exclude = array()) {\n        /* When the steps below require the UA to generate implied end tags,\n        then, if the current node is a dd element, a dt element, an li element,\n        a p element, a td element, a th  element, or a tr element, the UA must\n        act as if an end tag with the respective tag name had been seen and\n        then generate implied end tags again. */\n        $node = end($this->stack);\n        $elements = array_diff(array('dd', 'dt', 'li', 'p', 'td', 'th', 'tr'), $exclude);\n\n        while(in_array(end($this->stack)->nodeName, $elements)) {\n            array_pop($this->stack);\n        }\n    }\n\n    private function getElementCategory($node) {\n        $name = $node->tagName;\n        if(in_array($name, $this->special))\n            return self::SPECIAL;\n\n        elseif(in_array($name, $this->scoping))\n            return self::SCOPING;\n\n        elseif(in_array($name, $this->formatting))\n            return self::FORMATTING;\n\n        else\n            return self::PHRASING;\n    }\n\n    private function clearStackToTableContext($elements) {\n        /* When the steps above require the UA to clear the stack back to a\n        table context, it means that the UA must, while the current node is not\n        a table element or an html element, pop elements from the stack of open\n        elements. If this causes any elements to be popped from the stack, then\n        this is a parse error. */\n        while(true) {\n            $node = end($this->stack)->nodeName;\n\n            if(in_array($node, $elements)) {\n                break;\n            } else {\n                array_pop($this->stack);\n            }\n        }\n    }\n\n    private function resetInsertionMode() {\n        /* 1. Let last be false. */\n        $last = false;\n        $leng = count($this->stack);\n\n        for($n = $leng - 1; $n >= 0; $n--) {\n            /* 2. Let node be the last node in the stack of open elements. */\n            $node = $this->stack[$n];\n\n            /* 3. If node is the first node in the stack of open elements, then\n            set last to true. If the element whose innerHTML  attribute is being\n            set is neither a td  element nor a th element, then set node to the\n            element whose innerHTML  attribute is being set. (innerHTML  case) */\n            if($this->stack[0]->isSameNode($node)) {\n                $last = true;\n            }\n\n            /* 4. If node is a select element, then switch the insertion mode to\n            \"in select\" and abort these steps. (innerHTML case) */\n            if($node->nodeName === 'select') {\n                $this->mode = self::IN_SELECT;\n                break;\n\n            /* 5. If node is a td or th element, then switch the insertion mode\n            to \"in cell\" and abort these steps. */\n            } elseif($node->nodeName === 'td' || $node->nodeName === 'th') {\n                $this->mode = self::IN_CELL;\n                break;\n\n            /* 6. If node is a tr element, then switch the insertion mode to\n            \"in    row\" and abort these steps. */\n            } elseif($node->nodeName === 'tr') {\n                $this->mode = self::IN_ROW;\n                break;\n\n            /* 7. If node is a tbody, thead, or tfoot element, then switch the\n            insertion mode to \"in table body\" and abort these steps. */\n            } elseif(in_array($node->nodeName, array('tbody', 'thead', 'tfoot'))) {\n                $this->mode = self::IN_TBODY;\n                break;\n\n            /* 8. If node is a caption element, then switch the insertion mode\n            to \"in caption\" and abort these steps. */\n            } elseif($node->nodeName === 'caption') {\n                $this->mode = self::IN_CAPTION;\n                break;\n\n            /* 9. If node is a colgroup element, then switch the insertion mode\n            to \"in column group\" and abort these steps. (innerHTML case) */\n            } elseif($node->nodeName === 'colgroup') {\n                $this->mode = self::IN_CGROUP;\n                break;\n\n            /* 10. If node is a table element, then switch the insertion mode\n            to \"in table\" and abort these steps. */\n            } elseif($node->nodeName === 'table') {\n                $this->mode = self::IN_TABLE;\n                break;\n\n            /* 11. If node is a head element, then switch the insertion mode\n            to \"in body\" (\"in body\"! not \"in head\"!) and abort these steps.\n            (innerHTML case) */\n            } elseif($node->nodeName === 'head') {\n                $this->mode = self::IN_BODY;\n                break;\n\n            /* 12. If node is a body element, then switch the insertion mode to\n            \"in body\" and abort these steps. */\n            } elseif($node->nodeName === 'body') {\n                $this->mode = self::IN_BODY;\n                break;\n\n            /* 13. If node is a frameset element, then switch the insertion\n            mode to \"in frameset\" and abort these steps. (innerHTML case) */\n            } elseif($node->nodeName === 'frameset') {\n                $this->mode = self::IN_FRAME;\n                break;\n\n            /* 14. If node is an html element, then: if the head element\n            pointer is null, switch the insertion mode to \"before head\",\n            otherwise, switch the insertion mode to \"after head\". In either\n            case, abort these steps. (innerHTML case) */\n            } elseif($node->nodeName === 'html') {\n                $this->mode = ($this->head_pointer === null)\n                    ? self::BEFOR_HEAD\n                    : self::AFTER_HEAD;\n\n                break;\n\n            /* 15. If last is true, then set the insertion mode to \"in body\"\n            and    abort these steps. (innerHTML case) */\n            } elseif($last) {\n                $this->mode = self::IN_BODY;\n                break;\n            }\n        }\n    }\n\n    private function closeCell() {\n        /* If the stack of open elements has a td or th element in table scope,\n        then act as if an end tag token with that tag name had been seen. */\n        foreach(array('td', 'th') as $cell) {\n            if($this->elementInScope($cell, true)) {\n                $this->inCell(array(\n                    'name' => $cell,\n                    'type' => HTML5::ENDTAG\n                ));\n\n                break;\n            }\n        }\n    }\n\n    public function save() {\n        return $this->dom;\n    }\n}\n?>\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Lexer.php",
    "content": "<?php\n\n/**\n * Forgivingly lexes HTML (SGML-style) markup into tokens.\n *\n * A lexer parses a string of SGML-style markup and converts them into\n * corresponding tokens.  It doesn't check for well-formedness, although its\n * internal mechanism may make this automatic (such as the case of\n * HTMLPurifier_Lexer_DOMLex).  There are several implementations to choose\n * from.\n *\n * A lexer is HTML-oriented: it might work with XML, but it's not\n * recommended, as we adhere to a subset of the specification for optimization\n * reasons. This might change in the future. Also, most tokenizers are not\n * expected to handle DTDs or PIs.\n *\n * This class should not be directly instantiated, but you may use create() to\n * retrieve a default copy of the lexer.  Being a supertype, this class\n * does not actually define any implementation, but offers commonly used\n * convenience functions for subclasses.\n *\n * @note The unit tests will instantiate this class for testing purposes, as\n *       many of the utility functions require a class to be instantiated.\n *       This means that, even though this class is not runnable, it will\n *       not be declared abstract.\n *\n * @par\n *\n * @note\n * We use tokens rather than create a DOM representation because DOM would:\n *\n * @par\n *  -# Require more processing and memory to create,\n *  -# Is not streamable, and\n *  -# Has the entire document structure (html and body not needed).\n *\n * @par\n * However, DOM is helpful in that it makes it easy to move around nodes\n * without a lot of lookaheads to see when a tag is closed. This is a\n * limitation of the token system and some workarounds would be nice.\n */\nclass HTMLPurifier_Lexer\n{\n\n    /**\n     * Whether or not this lexer implements line-number/column-number tracking.\n     * If it does, set to true.\n     */\n    public $tracksLineNumbers = false;\n\n    // -- STATIC ----------------------------------------------------------\n\n    /**\n     * Retrieves or sets the default Lexer as a Prototype Factory.\n     *\n     * By default HTMLPurifier_Lexer_DOMLex will be returned. There are\n     * a few exceptions involving special features that only DirectLex\n     * implements.\n     *\n     * @note The behavior of this class has changed, rather than accepting\n     *       a prototype object, it now accepts a configuration object.\n     *       To specify your own prototype, set %Core.LexerImpl to it.\n     *       This change in behavior de-singletonizes the lexer object.\n     *\n     * @param $config Instance of HTMLPurifier_Config\n     * @return Concrete lexer.\n     */\n    public static function create($config) {\n\n        if (!($config instanceof HTMLPurifier_Config)) {\n            $lexer = $config;\n            trigger_error(\"Passing a prototype to\n              HTMLPurifier_Lexer::create() is deprecated, please instead\n              use %Core.LexerImpl\", E_USER_WARNING);\n        } else {\n            $lexer = $config->get('Core.LexerImpl');\n        }\n\n        $needs_tracking =\n            $config->get('Core.MaintainLineNumbers') ||\n            $config->get('Core.CollectErrors');\n\n        $inst = null;\n        if (is_object($lexer)) {\n            $inst = $lexer;\n        } else {\n\n            if (is_null($lexer)) { do {\n                // auto-detection algorithm\n\n                if ($needs_tracking) {\n                    $lexer = 'DirectLex';\n                    break;\n                }\n\n                if (\n                    class_exists('DOMDocument') &&\n                    method_exists('DOMDocument', 'loadHTML') &&\n                    !extension_loaded('domxml')\n                ) {\n                    // check for DOM support, because while it's part of the\n                    // core, it can be disabled compile time. Also, the PECL\n                    // domxml extension overrides the default DOM, and is evil\n                    // and nasty and we shan't bother to support it\n                    $lexer = 'DOMLex';\n                } else {\n                    $lexer = 'DirectLex';\n                }\n\n            } while(0); } // do..while so we can break\n\n            // instantiate recognized string names\n            switch ($lexer) {\n                case 'DOMLex':\n                    $inst = new HTMLPurifier_Lexer_DOMLex();\n                    break;\n                case 'DirectLex':\n                    $inst = new HTMLPurifier_Lexer_DirectLex();\n                    break;\n                case 'PH5P':\n                    $inst = new HTMLPurifier_Lexer_PH5P();\n                    break;\n                default:\n                    throw new HTMLPurifier_Exception(\"Cannot instantiate unrecognized Lexer type \" . htmlspecialchars($lexer));\n            }\n        }\n\n        if (!$inst) throw new HTMLPurifier_Exception('No lexer was instantiated');\n\n        // once PHP DOM implements native line numbers, or we\n        // hack out something using XSLT, remove this stipulation\n        if ($needs_tracking && !$inst->tracksLineNumbers) {\n            throw new HTMLPurifier_Exception('Cannot use lexer that does not support line numbers with Core.MaintainLineNumbers or Core.CollectErrors (use DirectLex instead)');\n        }\n\n        return $inst;\n\n    }\n\n    // -- CONVENIENCE MEMBERS ---------------------------------------------\n\n    public function __construct() {\n        $this->_entity_parser = new HTMLPurifier_EntityParser();\n    }\n\n    /**\n     * Most common entity to raw value conversion table for special entities.\n     */\n    protected $_special_entity2str =\n            array(\n                    '&quot;' => '\"',\n                    '&amp;'  => '&',\n                    '&lt;'   => '<',\n                    '&gt;'   => '>',\n                    '&#39;'  => \"'\",\n                    '&#039;' => \"'\",\n                    '&#x27;' => \"'\"\n            );\n\n    /**\n     * Parses special entities into the proper characters.\n     *\n     * This string will translate escaped versions of the special characters\n     * into the correct ones.\n     *\n     * @warning\n     * You should be able to treat the output of this function as\n     * completely parsed, but that's only because all other entities should\n     * have been handled previously in substituteNonSpecialEntities()\n     *\n     * @param $string String character data to be parsed.\n     * @returns Parsed character data.\n     */\n    public function parseData($string) {\n\n        // following functions require at least one character\n        if ($string === '') return '';\n\n        // subtracts amps that cannot possibly be escaped\n        $num_amp = substr_count($string, '&') - substr_count($string, '& ') -\n            ($string[strlen($string)-1] === '&' ? 1 : 0);\n\n        if (!$num_amp) return $string; // abort if no entities\n        $num_esc_amp = substr_count($string, '&amp;');\n        $string = strtr($string, $this->_special_entity2str);\n\n        // code duplication for sake of optimization, see above\n        $num_amp_2 = substr_count($string, '&') - substr_count($string, '& ') -\n            ($string[strlen($string)-1] === '&' ? 1 : 0);\n\n        if ($num_amp_2 <= $num_esc_amp) return $string;\n\n        // hmm... now we have some uncommon entities. Use the callback.\n        $string = $this->_entity_parser->substituteSpecialEntities($string);\n        return $string;\n    }\n\n    /**\n     * Lexes an HTML string into tokens.\n     *\n     * @param $string String HTML.\n     * @return HTMLPurifier_Token array representation of HTML.\n     */\n    public function tokenizeHTML($string, $config, $context) {\n        trigger_error('Call to abstract class', E_USER_ERROR);\n    }\n\n    /**\n     * Translates CDATA sections into regular sections (through escaping).\n     *\n     * @param $string HTML string to process.\n     * @returns HTML with CDATA sections escaped.\n     */\n    protected static function escapeCDATA($string) {\n        return preg_replace_callback(\n            '/<!\\[CDATA\\[(.+?)\\]\\]>/s',\n            array('HTMLPurifier_Lexer', 'CDATACallback'),\n            $string\n        );\n    }\n\n    /**\n     * Special CDATA case that is especially convoluted for <script>\n     */\n    protected static function escapeCommentedCDATA($string) {\n        return preg_replace_callback(\n            '#<!--//--><!\\[CDATA\\[//><!--(.+?)//--><!\\]\\]>#s',\n            array('HTMLPurifier_Lexer', 'CDATACallback'),\n            $string\n        );\n    }\n\n    /**\n     * Callback function for escapeCDATA() that does the work.\n     *\n     * @warning Though this is public in order to let the callback happen,\n     *          calling it directly is not recommended.\n     * @params $matches PCRE matches array, with index 0 the entire match\n     *                  and 1 the inside of the CDATA section.\n     * @returns Escaped internals of the CDATA section.\n     */\n    protected static function CDATACallback($matches) {\n        // not exactly sure why the character set is needed, but whatever\n        return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');\n    }\n\n    /**\n     * Takes a piece of HTML and normalizes it by converting entities, fixing\n     * encoding, extracting bits, and other good stuff.\n     * @todo Consider making protected\n     */\n    public function normalize($html, $config, $context) {\n\n        // normalize newlines to \\n\n        $html = str_replace(\"\\r\\n\", \"\\n\", $html);\n        $html = str_replace(\"\\r\", \"\\n\", $html);\n\n        if ($config->get('HTML.Trusted')) {\n            // escape convoluted CDATA\n            $html = $this->escapeCommentedCDATA($html);\n        }\n\n        // escape CDATA\n        $html = $this->escapeCDATA($html);\n\n        // extract body from document if applicable\n        if ($config->get('Core.ConvertDocumentToFragment')) {\n            $html = $this->extractBody($html);\n        }\n\n        // expand entities that aren't the big five\n        $html = $this->_entity_parser->substituteNonSpecialEntities($html);\n\n        // clean into wellformed UTF-8 string for an SGML context: this has\n        // to be done after entity expansion because the entities sometimes\n        // represent non-SGML characters (horror, horror!)\n        $html = HTMLPurifier_Encoder::cleanUTF8($html);\n\n        return $html;\n    }\n\n    /**\n     * Takes a string of HTML (fragment or document) and returns the content\n     * @todo Consider making protected\n     */\n    public function extractBody($html) {\n        $matches = array();\n        $result = preg_match('!<body[^>]*>(.*)</body>!is', $html, $matches);\n        if ($result) {\n            return $matches[1];\n        } else {\n            return $html;\n        }\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/PercentEncoder.php",
    "content": "<?php\n\n/**\n * Class that handles operations involving percent-encoding in URIs.\n *\n * @warning\n *      Be careful when reusing instances of PercentEncoder. The object\n *      you use for normalize() SHOULD NOT be used for encode(), or\n *      vice-versa.\n */\nclass HTMLPurifier_PercentEncoder\n{\n\n    /**\n     * Reserved characters to preserve when using encode().\n     */\n    protected $preserve = array();\n\n    /**\n     * String of characters that should be preserved while using encode().\n     */\n    public function __construct($preserve = false) {\n        // unreserved letters, ought to const-ify\n        for ($i = 48; $i <= 57;  $i++) $this->preserve[$i] = true; // digits\n        for ($i = 65; $i <= 90;  $i++) $this->preserve[$i] = true; // upper-case\n        for ($i = 97; $i <= 122; $i++) $this->preserve[$i] = true; // lower-case\n        $this->preserve[45] = true; // Dash         -\n        $this->preserve[46] = true; // Period       .\n        $this->preserve[95] = true; // Underscore   _\n        $this->preserve[126]= true; // Tilde        ~\n\n        // extra letters not to escape\n        if ($preserve !== false) {\n            for ($i = 0, $c = strlen($preserve); $i < $c; $i++) {\n                $this->preserve[ord($preserve[$i])] = true;\n            }\n        }\n    }\n\n    /**\n     * Our replacement for urlencode, it encodes all non-reserved characters,\n     * as well as any extra characters that were instructed to be preserved.\n     * @note\n     *      Assumes that the string has already been normalized, making any\n     *      and all percent escape sequences valid. Percents will not be\n     *      re-escaped, regardless of their status in $preserve\n     * @param $string String to be encoded\n     * @return Encoded string.\n     */\n    public function encode($string) {\n        $ret = '';\n        for ($i = 0, $c = strlen($string); $i < $c; $i++) {\n            if ($string[$i] !== '%' && !isset($this->preserve[$int = ord($string[$i])]) ) {\n                $ret .= '%' . sprintf('%02X', $int);\n            } else {\n                $ret .= $string[$i];\n            }\n        }\n        return $ret;\n    }\n\n    /**\n     * Fix up percent-encoding by decoding unreserved characters and normalizing.\n     * @warning This function is affected by $preserve, even though the\n     *          usual desired behavior is for this not to preserve those\n     *          characters. Be careful when reusing instances of PercentEncoder!\n     * @param $string String to normalize\n     */\n    public function normalize($string) {\n        if ($string == '') return '';\n        $parts = explode('%', $string);\n        $ret = array_shift($parts);\n        foreach ($parts as $part) {\n            $length = strlen($part);\n            if ($length < 2) {\n                $ret .= '%25' . $part;\n                continue;\n            }\n            $encoding = substr($part, 0, 2);\n            $text     = substr($part, 2);\n            if (!ctype_xdigit($encoding)) {\n                $ret .= '%25' . $part;\n                continue;\n            }\n            $int = hexdec($encoding);\n            if (isset($this->preserve[$int])) {\n                $ret .= chr($int) . $text;\n                continue;\n            }\n            $encoding = strtoupper($encoding);\n            $ret .= '%' . $encoding . $text;\n        }\n        return $ret;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Printer/CSSDefinition.php",
    "content": "<?php\n\nclass HTMLPurifier_Printer_CSSDefinition extends HTMLPurifier_Printer\n{\n\n    protected $def;\n\n    public function render($config) {\n        $this->def = $config->getCSSDefinition();\n        $ret = '';\n\n        $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));\n        $ret .= $this->start('table');\n\n        $ret .= $this->element('caption', 'Properties ($info)');\n\n        $ret .= $this->start('thead');\n        $ret .= $this->start('tr');\n        $ret .= $this->element('th', 'Property', array('class' => 'heavy'));\n        $ret .= $this->element('th', 'Definition', array('class' => 'heavy', 'style' => 'width:auto;'));\n        $ret .= $this->end('tr');\n        $ret .= $this->end('thead');\n\n        ksort($this->def->info);\n        foreach ($this->def->info as $property => $obj) {\n            $name = $this->getClass($obj, 'AttrDef_');\n            $ret .= $this->row($property, $name);\n        }\n\n        $ret .= $this->end('table');\n        $ret .= $this->end('div');\n\n        return $ret;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Printer/ConfigForm.css",
    "content": "\n.hp-config {}\n\n.hp-config tbody th {text-align:right; padding-right:0.5em;}\n.hp-config thead, .hp-config .namespace {background:#3C578C; color:#FFF;}\n.hp-config .namespace th {text-align:center;}\n.hp-config .verbose {display:none;}\n.hp-config .controls {text-align:center;}\n\n/* vim: et sw=4 sts=4 */\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Printer/ConfigForm.js",
    "content": "function toggleWriteability(id_of_patient, checked) {\n    document.getElementById(id_of_patient).disabled = checked;\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Printer/ConfigForm.php",
    "content": "<?php\n\n/**\n * @todo Rewrite to use Interchange objects\n */\nclass HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer\n{\n\n    /**\n     * Printers for specific fields\n     */\n    protected $fields = array();\n\n    /**\n     * Documentation URL, can have fragment tagged on end\n     */\n    protected $docURL;\n\n    /**\n     * Name of form element to stuff config in\n     */\n    protected $name;\n\n    /**\n     * Whether or not to compress directive names, clipping them off\n     * after a certain amount of letters. False to disable or integer letters\n     * before clipping.\n     */\n    protected $compress = false;\n\n    /**\n     * @param $name Form element name for directives to be stuffed into\n     * @param $doc_url String documentation URL, will have fragment tagged on\n     * @param $compress Integer max length before compressing a directive name, set to false to turn off\n     */\n    public function __construct(\n        $name, $doc_url = null, $compress = false\n    ) {\n        parent::__construct();\n        $this->docURL = $doc_url;\n        $this->name   = $name;\n        $this->compress = $compress;\n        // initialize sub-printers\n        $this->fields[0]    = new HTMLPurifier_Printer_ConfigForm_default();\n        $this->fields[HTMLPurifier_VarParser::BOOL]       = new HTMLPurifier_Printer_ConfigForm_bool();\n    }\n\n    /**\n     * Sets default column and row size for textareas in sub-printers\n     * @param $cols Integer columns of textarea, null to use default\n     * @param $rows Integer rows of textarea, null to use default\n     */\n    public function setTextareaDimensions($cols = null, $rows = null) {\n        if ($cols) $this->fields['default']->cols = $cols;\n        if ($rows) $this->fields['default']->rows = $rows;\n    }\n\n    /**\n     * Retrieves styling, in case it is not accessible by webserver\n     */\n    public static function getCSS() {\n        return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css');\n    }\n\n    /**\n     * Retrieves JavaScript, in case it is not accessible by webserver\n     */\n    public static function getJavaScript() {\n        return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js');\n    }\n\n    /**\n     * Returns HTML output for a configuration form\n     * @param $config Configuration object of current form state, or an array\n     *        where [0] has an HTML namespace and [1] is being rendered.\n     * @param $allowed Optional namespace(s) and directives to restrict form to.\n     */\n    public function render($config, $allowed = true, $render_controls = true) {\n        if (is_array($config) && isset($config[0])) {\n            $gen_config = $config[0];\n            $config = $config[1];\n        } else {\n            $gen_config = $config;\n        }\n\n        $this->config = $config;\n        $this->genConfig = $gen_config;\n        $this->prepareGenerator($gen_config);\n\n        $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $config->def);\n        $all = array();\n        foreach ($allowed as $key) {\n            list($ns, $directive) = $key;\n            $all[$ns][$directive] = $config->get($ns .'.'. $directive);\n        }\n\n        $ret = '';\n        $ret .= $this->start('table', array('class' => 'hp-config'));\n        $ret .= $this->start('thead');\n        $ret .= $this->start('tr');\n            $ret .= $this->element('th', 'Directive', array('class' => 'hp-directive'));\n            $ret .= $this->element('th', 'Value', array('class' => 'hp-value'));\n        $ret .= $this->end('tr');\n        $ret .= $this->end('thead');\n        foreach ($all as $ns => $directives) {\n            $ret .= $this->renderNamespace($ns, $directives);\n        }\n        if ($render_controls) {\n             $ret .= $this->start('tbody');\n             $ret .= $this->start('tr');\n                 $ret .= $this->start('td', array('colspan' => 2, 'class' => 'controls'));\n                     $ret .= $this->elementEmpty('input', array('type' => 'submit', 'value' => 'Submit'));\n                     $ret .= '[<a href=\"?\">Reset</a>]';\n                 $ret .= $this->end('td');\n             $ret .= $this->end('tr');\n             $ret .= $this->end('tbody');\n        }\n        $ret .= $this->end('table');\n        return $ret;\n    }\n\n    /**\n     * Renders a single namespace\n     * @param $ns String namespace name\n     * @param $directive Associative array of directives to values\n     */\n    protected function renderNamespace($ns, $directives) {\n        $ret = '';\n        $ret .= $this->start('tbody', array('class' => 'namespace'));\n        $ret .= $this->start('tr');\n            $ret .= $this->element('th', $ns, array('colspan' => 2));\n        $ret .= $this->end('tr');\n        $ret .= $this->end('tbody');\n        $ret .= $this->start('tbody');\n        foreach ($directives as $directive => $value) {\n            $ret .= $this->start('tr');\n            $ret .= $this->start('th');\n            if ($this->docURL) {\n                $url = str_replace('%s', urlencode(\"$ns.$directive\"), $this->docURL);\n                $ret .= $this->start('a', array('href' => $url));\n            }\n                $attr = array('for' => \"{$this->name}:$ns.$directive\");\n\n                // crop directive name if it's too long\n                if (!$this->compress || (strlen($directive) < $this->compress)) {\n                    $directive_disp = $directive;\n                } else {\n                    $directive_disp = substr($directive, 0, $this->compress - 2) . '...';\n                    $attr['title'] = $directive;\n                }\n\n                $ret .= $this->element(\n                    'label',\n                    $directive_disp,\n                    // component printers must create an element with this id\n                    $attr\n                );\n            if ($this->docURL) $ret .= $this->end('a');\n            $ret .= $this->end('th');\n\n            $ret .= $this->start('td');\n                $def = $this->config->def->info[\"$ns.$directive\"];\n                if (is_int($def)) {\n                    $allow_null = $def < 0;\n                    $type = abs($def);\n                } else {\n                    $type = $def->type;\n                    $allow_null = isset($def->allow_null);\n                }\n                if (!isset($this->fields[$type])) $type = 0; // default\n                $type_obj = $this->fields[$type];\n                if ($allow_null) {\n                    $type_obj = new HTMLPurifier_Printer_ConfigForm_NullDecorator($type_obj);\n                }\n                $ret .= $type_obj->render($ns, $directive, $value, $this->name, array($this->genConfig, $this->config));\n            $ret .= $this->end('td');\n            $ret .= $this->end('tr');\n        }\n        $ret .= $this->end('tbody');\n        return $ret;\n    }\n\n}\n\n/**\n * Printer decorator for directives that accept null\n */\nclass HTMLPurifier_Printer_ConfigForm_NullDecorator extends HTMLPurifier_Printer {\n    /**\n     * Printer being decorated\n     */\n    protected $obj;\n    /**\n     * @param $obj Printer to decorate\n     */\n    public function __construct($obj) {\n        parent::__construct();\n        $this->obj = $obj;\n    }\n    public function render($ns, $directive, $value, $name, $config) {\n        if (is_array($config) && isset($config[0])) {\n            $gen_config = $config[0];\n            $config = $config[1];\n        } else {\n            $gen_config = $config;\n        }\n        $this->prepareGenerator($gen_config);\n\n        $ret = '';\n        $ret .= $this->start('label', array('for' => \"$name:Null_$ns.$directive\"));\n        $ret .= $this->element('span', \"$ns.$directive:\", array('class' => 'verbose'));\n        $ret .= $this->text(' Null/Disabled');\n        $ret .= $this->end('label');\n        $attr = array(\n            'type' => 'checkbox',\n            'value' => '1',\n            'class' => 'null-toggle',\n            'name' => \"$name\".\"[Null_$ns.$directive]\",\n            'id' => \"$name:Null_$ns.$directive\",\n            'onclick' => \"toggleWriteability('$name:$ns.$directive',checked)\" // INLINE JAVASCRIPT!!!!\n        );\n        if ($this->obj instanceof HTMLPurifier_Printer_ConfigForm_bool) {\n            // modify inline javascript slightly\n            $attr['onclick'] = \"toggleWriteability('$name:Yes_$ns.$directive',checked);toggleWriteability('$name:No_$ns.$directive',checked)\";\n        }\n        if ($value === null) $attr['checked'] = 'checked';\n        $ret .= $this->elementEmpty('input', $attr);\n        $ret .= $this->text(' or ');\n        $ret .= $this->elementEmpty('br');\n        $ret .= $this->obj->render($ns, $directive, $value, $name, array($gen_config, $config));\n        return $ret;\n    }\n}\n\n/**\n * Swiss-army knife configuration form field printer\n */\nclass HTMLPurifier_Printer_ConfigForm_default extends HTMLPurifier_Printer {\n    public $cols = 18;\n    public $rows = 5;\n    public function render($ns, $directive, $value, $name, $config) {\n        if (is_array($config) && isset($config[0])) {\n            $gen_config = $config[0];\n            $config = $config[1];\n        } else {\n            $gen_config = $config;\n        }\n        $this->prepareGenerator($gen_config);\n        // this should probably be split up a little\n        $ret = '';\n        $def = $config->def->info[\"$ns.$directive\"];\n        if (is_int($def)) {\n            $type = abs($def);\n        } else {\n            $type = $def->type;\n        }\n        if (is_array($value)) {\n            switch ($type) {\n                case HTMLPurifier_VarParser::LOOKUP:\n                    $array = $value;\n                    $value = array();\n                    foreach ($array as $val => $b) {\n                        $value[] = $val;\n                    }\n                case HTMLPurifier_VarParser::ALIST:\n                    $value = implode(PHP_EOL, $value);\n                    break;\n                case HTMLPurifier_VarParser::HASH:\n                    $nvalue = '';\n                    foreach ($value as $i => $v) {\n                        $nvalue .= \"$i:$v\" . PHP_EOL;\n                    }\n                    $value = $nvalue;\n                    break;\n                default:\n                    $value = '';\n            }\n        }\n        if ($type === HTMLPurifier_VarParser::MIXED) {\n            return 'Not supported';\n            $value = serialize($value);\n        }\n        $attr = array(\n            'name' => \"$name\".\"[$ns.$directive]\",\n            'id' => \"$name:$ns.$directive\"\n        );\n        if ($value === null) $attr['disabled'] = 'disabled';\n        if (isset($def->allowed)) {\n            $ret .= $this->start('select', $attr);\n            foreach ($def->allowed as $val => $b) {\n                $attr = array();\n                if ($value == $val) $attr['selected'] = 'selected';\n                $ret .= $this->element('option', $val, $attr);\n            }\n            $ret .= $this->end('select');\n        } elseif (\n            $type === HTMLPurifier_VarParser::TEXT ||\n            $type === HTMLPurifier_VarParser::ITEXT ||\n            $type === HTMLPurifier_VarParser::ALIST ||\n            $type === HTMLPurifier_VarParser::HASH ||\n            $type === HTMLPurifier_VarParser::LOOKUP\n        ) {\n            $attr['cols'] = $this->cols;\n            $attr['rows'] = $this->rows;\n            $ret .= $this->start('textarea', $attr);\n            $ret .= $this->text($value);\n            $ret .= $this->end('textarea');\n        } else {\n            $attr['value'] = $value;\n            $attr['type'] = 'text';\n            $ret .= $this->elementEmpty('input', $attr);\n        }\n        return $ret;\n    }\n}\n\n/**\n * Bool form field printer\n */\nclass HTMLPurifier_Printer_ConfigForm_bool extends HTMLPurifier_Printer {\n    public function render($ns, $directive, $value, $name, $config) {\n        if (is_array($config) && isset($config[0])) {\n            $gen_config = $config[0];\n            $config = $config[1];\n        } else {\n            $gen_config = $config;\n        }\n        $this->prepareGenerator($gen_config);\n        $ret = '';\n        $ret .= $this->start('div', array('id' => \"$name:$ns.$directive\"));\n\n        $ret .= $this->start('label', array('for' => \"$name:Yes_$ns.$directive\"));\n        $ret .= $this->element('span', \"$ns.$directive:\", array('class' => 'verbose'));\n        $ret .= $this->text(' Yes');\n        $ret .= $this->end('label');\n\n        $attr = array(\n            'type' => 'radio',\n            'name' => \"$name\".\"[$ns.$directive]\",\n            'id' => \"$name:Yes_$ns.$directive\",\n            'value' => '1'\n        );\n        if ($value === true) $attr['checked'] = 'checked';\n        if ($value === null) $attr['disabled'] = 'disabled';\n        $ret .= $this->elementEmpty('input', $attr);\n\n        $ret .= $this->start('label', array('for' => \"$name:No_$ns.$directive\"));\n        $ret .= $this->element('span', \"$ns.$directive:\", array('class' => 'verbose'));\n        $ret .= $this->text(' No');\n        $ret .= $this->end('label');\n\n        $attr = array(\n            'type' => 'radio',\n            'name' => \"$name\".\"[$ns.$directive]\",\n            'id' => \"$name:No_$ns.$directive\",\n            'value' => '0'\n        );\n        if ($value === false) $attr['checked'] = 'checked';\n        if ($value === null) $attr['disabled'] = 'disabled';\n        $ret .= $this->elementEmpty('input', $attr);\n\n        $ret .= $this->end('div');\n\n        return $ret;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Printer/HTMLDefinition.php",
    "content": "<?php\n\nclass HTMLPurifier_Printer_HTMLDefinition extends HTMLPurifier_Printer\n{\n\n    /**\n     * Instance of HTMLPurifier_HTMLDefinition, for easy access\n     */\n    protected $def;\n\n    public function render($config) {\n        $ret = '';\n        $this->config =& $config;\n\n        $this->def = $config->getHTMLDefinition();\n\n        $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));\n\n        $ret .= $this->renderDoctype();\n        $ret .= $this->renderEnvironment();\n        $ret .= $this->renderContentSets();\n        $ret .= $this->renderInfo();\n\n        $ret .= $this->end('div');\n\n        return $ret;\n    }\n\n    /**\n     * Renders the Doctype table\n     */\n    protected function renderDoctype() {\n        $doctype = $this->def->doctype;\n        $ret = '';\n        $ret .= $this->start('table');\n        $ret .= $this->element('caption', 'Doctype');\n        $ret .= $this->row('Name', $doctype->name);\n        $ret .= $this->row('XML', $doctype->xml ? 'Yes' : 'No');\n        $ret .= $this->row('Default Modules', implode($doctype->modules, ', '));\n        $ret .= $this->row('Default Tidy Modules', implode($doctype->tidyModules, ', '));\n        $ret .= $this->end('table');\n        return $ret;\n    }\n\n\n    /**\n     * Renders environment table, which is miscellaneous info\n     */\n    protected function renderEnvironment() {\n        $def = $this->def;\n\n        $ret = '';\n\n        $ret .= $this->start('table');\n        $ret .= $this->element('caption', 'Environment');\n\n        $ret .= $this->row('Parent of fragment', $def->info_parent);\n        $ret .= $this->renderChildren($def->info_parent_def->child);\n        $ret .= $this->row('Block wrap name', $def->info_block_wrapper);\n\n        $ret .= $this->start('tr');\n            $ret .= $this->element('th', 'Global attributes');\n            $ret .= $this->element('td', $this->listifyAttr($def->info_global_attr),0,0);\n        $ret .= $this->end('tr');\n\n        $ret .= $this->start('tr');\n            $ret .= $this->element('th', 'Tag transforms');\n            $list = array();\n            foreach ($def->info_tag_transform as $old => $new) {\n                $new = $this->getClass($new, 'TagTransform_');\n                $list[] = \"<$old> with $new\";\n            }\n            $ret .= $this->element('td', $this->listify($list));\n        $ret .= $this->end('tr');\n\n        $ret .= $this->start('tr');\n            $ret .= $this->element('th', 'Pre-AttrTransform');\n            $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_pre));\n        $ret .= $this->end('tr');\n\n        $ret .= $this->start('tr');\n            $ret .= $this->element('th', 'Post-AttrTransform');\n            $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_post));\n        $ret .= $this->end('tr');\n\n        $ret .= $this->end('table');\n        return $ret;\n    }\n\n    /**\n     * Renders the Content Sets table\n     */\n    protected function renderContentSets() {\n        $ret = '';\n        $ret .= $this->start('table');\n        $ret .= $this->element('caption', 'Content Sets');\n        foreach ($this->def->info_content_sets as $name => $lookup) {\n            $ret .= $this->heavyHeader($name);\n            $ret .= $this->start('tr');\n            $ret .= $this->element('td', $this->listifyTagLookup($lookup));\n            $ret .= $this->end('tr');\n        }\n        $ret .= $this->end('table');\n        return $ret;\n    }\n\n    /**\n     * Renders the Elements ($info) table\n     */\n    protected function renderInfo() {\n        $ret = '';\n        $ret .= $this->start('table');\n        $ret .= $this->element('caption', 'Elements ($info)');\n        ksort($this->def->info);\n        $ret .= $this->heavyHeader('Allowed tags', 2);\n        $ret .= $this->start('tr');\n        $ret .= $this->element('td', $this->listifyTagLookup($this->def->info), array('colspan' => 2));\n        $ret .= $this->end('tr');\n        foreach ($this->def->info as $name => $def) {\n            $ret .= $this->start('tr');\n                $ret .= $this->element('th', \"<$name>\", array('class'=>'heavy', 'colspan' => 2));\n            $ret .= $this->end('tr');\n            $ret .= $this->start('tr');\n                $ret .= $this->element('th', 'Inline content');\n                $ret .= $this->element('td', $def->descendants_are_inline ? 'Yes' : 'No');\n            $ret .= $this->end('tr');\n            if (!empty($def->excludes)) {\n                $ret .= $this->start('tr');\n                    $ret .= $this->element('th', 'Excludes');\n                    $ret .= $this->element('td', $this->listifyTagLookup($def->excludes));\n                $ret .= $this->end('tr');\n            }\n            if (!empty($def->attr_transform_pre)) {\n                $ret .= $this->start('tr');\n                    $ret .= $this->element('th', 'Pre-AttrTransform');\n                    $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_pre));\n                $ret .= $this->end('tr');\n            }\n            if (!empty($def->attr_transform_post)) {\n                $ret .= $this->start('tr');\n                    $ret .= $this->element('th', 'Post-AttrTransform');\n                    $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_post));\n                $ret .= $this->end('tr');\n            }\n            if (!empty($def->auto_close)) {\n                $ret .= $this->start('tr');\n                    $ret .= $this->element('th', 'Auto closed by');\n                    $ret .= $this->element('td', $this->listifyTagLookup($def->auto_close));\n                $ret .= $this->end('tr');\n            }\n            $ret .= $this->start('tr');\n                $ret .= $this->element('th', 'Allowed attributes');\n                $ret .= $this->element('td',$this->listifyAttr($def->attr), array(), 0);\n            $ret .= $this->end('tr');\n\n            if (!empty($def->required_attr)) {\n                $ret .= $this->row('Required attributes', $this->listify($def->required_attr));\n            }\n\n            $ret .= $this->renderChildren($def->child);\n        }\n        $ret .= $this->end('table');\n        return $ret;\n    }\n\n    /**\n     * Renders a row describing the allowed children of an element\n     * @param $def HTMLPurifier_ChildDef of pertinent element\n     */\n    protected function renderChildren($def) {\n        $context = new HTMLPurifier_Context();\n        $ret = '';\n        $ret .= $this->start('tr');\n            $elements = array();\n            $attr = array();\n            if (isset($def->elements)) {\n                if ($def->type == 'strictblockquote') {\n                    $def->validateChildren(array(), $this->config, $context);\n                }\n                $elements = $def->elements;\n            }\n            if ($def->type == 'chameleon') {\n                $attr['rowspan'] = 2;\n            } elseif ($def->type == 'empty') {\n                $elements = array();\n            } elseif ($def->type == 'table') {\n                $elements = array_flip(array('col', 'caption', 'colgroup', 'thead',\n                    'tfoot', 'tbody', 'tr'));\n            }\n            $ret .= $this->element('th', 'Allowed children', $attr);\n\n            if ($def->type == 'chameleon') {\n\n                $ret .= $this->element('td',\n                    '<em>Block</em>: ' .\n                    $this->escape($this->listifyTagLookup($def->block->elements)),0,0);\n                $ret .= $this->end('tr');\n                $ret .= $this->start('tr');\n                $ret .= $this->element('td',\n                    '<em>Inline</em>: ' .\n                    $this->escape($this->listifyTagLookup($def->inline->elements)),0,0);\n\n            } elseif ($def->type == 'custom') {\n\n                $ret .= $this->element('td', '<em>'.ucfirst($def->type).'</em>: ' .\n                    $def->dtd_regex);\n\n            } else {\n                $ret .= $this->element('td',\n                    '<em>'.ucfirst($def->type).'</em>: ' .\n                    $this->escape($this->listifyTagLookup($elements)),0,0);\n            }\n        $ret .= $this->end('tr');\n        return $ret;\n    }\n\n    /**\n     * Listifies a tag lookup table.\n     * @param $array Tag lookup array in form of array('tagname' => true)\n     */\n    protected function listifyTagLookup($array) {\n        ksort($array);\n        $list = array();\n        foreach ($array as $name => $discard) {\n            if ($name !== '#PCDATA' && !isset($this->def->info[$name])) continue;\n            $list[] = $name;\n        }\n        return $this->listify($list);\n    }\n\n    /**\n     * Listifies a list of objects by retrieving class names and internal state\n     * @param $array List of objects\n     * @todo Also add information about internal state\n     */\n    protected function listifyObjectList($array) {\n        ksort($array);\n        $list = array();\n        foreach ($array as $discard => $obj) {\n            $list[] = $this->getClass($obj, 'AttrTransform_');\n        }\n        return $this->listify($list);\n    }\n\n    /**\n     * Listifies a hash of attributes to AttrDef classes\n     * @param $array Array hash in form of array('attrname' => HTMLPurifier_AttrDef)\n     */\n    protected function listifyAttr($array) {\n        ksort($array);\n        $list = array();\n        foreach ($array as $name => $obj) {\n            if ($obj === false) continue;\n            $list[] = \"$name&nbsp;=&nbsp;<i>\" . $this->getClass($obj, 'AttrDef_') . '</i>';\n        }\n        return $this->listify($list);\n    }\n\n    /**\n     * Creates a heavy header row\n     */\n    protected function heavyHeader($text, $num = 1) {\n        $ret = '';\n        $ret .= $this->start('tr');\n        $ret .= $this->element('th', $text, array('colspan' => $num, 'class' => 'heavy'));\n        $ret .= $this->end('tr');\n        return $ret;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Printer.php",
    "content": "<?php\n\n// OUT OF DATE, NEEDS UPDATING!\n// USE XMLWRITER!\n\nclass HTMLPurifier_Printer\n{\n\n    /**\n     * Instance of HTMLPurifier_Generator for HTML generation convenience funcs\n     */\n    protected $generator;\n\n    /**\n     * Instance of HTMLPurifier_Config, for easy access\n     */\n    protected $config;\n\n    /**\n     * Initialize $generator.\n     */\n    public function __construct() {\n    }\n\n    /**\n     * Give generator necessary configuration if possible\n     */\n    public function prepareGenerator($config) {\n        $all = $config->getAll();\n        $context = new HTMLPurifier_Context();\n        $this->generator = new HTMLPurifier_Generator($config, $context);\n    }\n\n    /**\n     * Main function that renders object or aspect of that object\n     * @note Parameters vary depending on printer\n     */\n    // function render() {}\n\n    /**\n     * Returns a start tag\n     * @param $tag Tag name\n     * @param $attr Attribute array\n     */\n    protected function start($tag, $attr = array()) {\n        return $this->generator->generateFromToken(\n                    new HTMLPurifier_Token_Start($tag, $attr ? $attr : array())\n               );\n    }\n\n    /**\n     * Returns an end teg\n     * @param $tag Tag name\n     */\n    protected function end($tag) {\n        return $this->generator->generateFromToken(\n                    new HTMLPurifier_Token_End($tag)\n               );\n    }\n\n    /**\n     * Prints a complete element with content inside\n     * @param $tag Tag name\n     * @param $contents Element contents\n     * @param $attr Tag attributes\n     * @param $escape Bool whether or not to escape contents\n     */\n    protected function element($tag, $contents, $attr = array(), $escape = true) {\n        return $this->start($tag, $attr) .\n               ($escape ? $this->escape($contents) : $contents) .\n               $this->end($tag);\n    }\n\n    protected function elementEmpty($tag, $attr = array()) {\n        return $this->generator->generateFromToken(\n            new HTMLPurifier_Token_Empty($tag, $attr)\n        );\n    }\n\n    protected function text($text) {\n        return $this->generator->generateFromToken(\n            new HTMLPurifier_Token_Text($text)\n        );\n    }\n\n    /**\n     * Prints a simple key/value row in a table.\n     * @param $name Key\n     * @param $value Value\n     */\n    protected function row($name, $value) {\n        if (is_bool($value)) $value = $value ? 'On' : 'Off';\n        return\n            $this->start('tr') . \"\\n\" .\n                $this->element('th', $name) . \"\\n\" .\n                $this->element('td', $value) . \"\\n\" .\n            $this->end('tr')\n        ;\n    }\n\n    /**\n     * Escapes a string for HTML output.\n     * @param $string String to escape\n     */\n    protected function escape($string) {\n        $string = HTMLPurifier_Encoder::cleanUTF8($string);\n        $string = htmlspecialchars($string, ENT_COMPAT, 'UTF-8');\n        return $string;\n    }\n\n    /**\n     * Takes a list of strings and turns them into a single list\n     * @param $array List of strings\n     * @param $polite Bool whether or not to add an end before the last\n     */\n    protected function listify($array, $polite = false) {\n        if (empty($array)) return 'None';\n        $ret = '';\n        $i = count($array);\n        foreach ($array as $value) {\n            $i--;\n            $ret .= $value;\n            if ($i > 0 && !($polite && $i == 1)) $ret .= ', ';\n            if ($polite && $i == 1) $ret .= 'and ';\n        }\n        return $ret;\n    }\n\n    /**\n     * Retrieves the class of an object without prefixes, as well as metadata\n     * @param $obj Object to determine class of\n     * @param $prefix Further prefix to remove\n     */\n    protected function getClass($obj, $sec_prefix = '') {\n        static $five = null;\n        if ($five === null) $five = version_compare(PHP_VERSION, '5', '>=');\n        $prefix = 'HTMLPurifier_' . $sec_prefix;\n        if (!$five) $prefix = strtolower($prefix);\n        $class = str_replace($prefix, '', get_class($obj));\n        $lclass = strtolower($class);\n        $class .= '(';\n        switch ($lclass) {\n            case 'enum':\n                $values = array();\n                foreach ($obj->valid_values as $value => $bool) {\n                    $values[] = $value;\n                }\n                $class .= implode(', ', $values);\n                break;\n            case 'css_composite':\n                $values = array();\n                foreach ($obj->defs as $def) {\n                    $values[] = $this->getClass($def, $sec_prefix);\n                }\n                $class .= implode(', ', $values);\n                break;\n            case 'css_multiple':\n                $class .= $this->getClass($obj->single, $sec_prefix) . ', ';\n                $class .= $obj->max;\n                break;\n            case 'css_denyelementdecorator':\n                $class .= $this->getClass($obj->def, $sec_prefix) . ', ';\n                $class .= $obj->element;\n                break;\n            case 'css_importantdecorator':\n                $class .= $this->getClass($obj->def, $sec_prefix);\n                if ($obj->allow) $class .= ', !important';\n                break;\n        }\n        $class .= ')';\n        return $class;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/PropertyList.php",
    "content": "<?php\n\n/**\n * Generic property list implementation\n */\nclass HTMLPurifier_PropertyList\n{\n    /**\n     * Internal data-structure for properties\n     */\n    protected $data = array();\n\n    /**\n     * Parent plist\n     */\n    protected $parent;\n\n    protected $cache;\n\n    public function __construct($parent = null) {\n        $this->parent = $parent;\n    }\n\n    /**\n     * Recursively retrieves the value for a key\n     */\n    public function get($name) {\n        if ($this->has($name)) return $this->data[$name];\n        // possible performance bottleneck, convert to iterative if necessary\n        if ($this->parent) return $this->parent->get($name);\n        throw new HTMLPurifier_Exception(\"Key '$name' not found\");\n    }\n\n    /**\n     * Sets the value of a key, for this plist\n     */\n    public function set($name, $value) {\n        $this->data[$name] = $value;\n    }\n\n    /**\n     * Returns true if a given key exists\n     */\n    public function has($name) {\n        return array_key_exists($name, $this->data);\n    }\n\n    /**\n     * Resets a value to the value of it's parent, usually the default. If\n     * no value is specified, the entire plist is reset.\n     */\n    public function reset($name = null) {\n        if ($name == null) $this->data = array();\n        else unset($this->data[$name]);\n    }\n\n    /**\n     * Squashes this property list and all of its property lists into a single\n     * array, and returns the array. This value is cached by default.\n     * @param $force If true, ignores the cache and regenerates the array.\n     */\n    public function squash($force = false) {\n        if ($this->cache !== null && !$force) return $this->cache;\n        if ($this->parent) {\n            return $this->cache = array_merge($this->parent->squash($force), $this->data);\n        } else {\n            return $this->cache = $this->data;\n        }\n    }\n\n    /**\n     * Returns the parent plist.\n     */\n    public function getParent() {\n        return $this->parent;\n    }\n\n    /**\n     * Sets the parent plist.\n     */\n    public function setParent($plist) {\n        $this->parent = $plist;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/PropertyListIterator.php",
    "content": "<?php\n\n/**\n * Property list iterator. Do not instantiate this class directly.\n */\nclass HTMLPurifier_PropertyListIterator extends FilterIterator\n{\n\n    protected $l;\n    protected $filter;\n\n    /**\n     * @param $data Array of data to iterate over\n     * @param $filter Optional prefix to only allow values of\n     */\n    public function __construct(Iterator $iterator, $filter = null) {\n        parent::__construct($iterator);\n        $this->l = strlen($filter);\n        $this->filter = $filter;\n    }\n\n    public function accept() {\n        $key = $this->getInnerIterator()->key();\n        if( strncmp($key, $this->filter, $this->l) !== 0 ) {\n            return false;\n        }\n        return true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Strategy/Composite.php",
    "content": "<?php\n\n/**\n * Composite strategy that runs multiple strategies on tokens.\n */\nabstract class HTMLPurifier_Strategy_Composite extends HTMLPurifier_Strategy\n{\n\n    /**\n     * List of strategies to run tokens through.\n     */\n    protected $strategies = array();\n\n    abstract public function __construct();\n\n    public function execute($tokens, $config, $context) {\n        foreach ($this->strategies as $strategy) {\n            $tokens = $strategy->execute($tokens, $config, $context);\n        }\n        return $tokens;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Strategy/Core.php",
    "content": "<?php\n\n/**\n * Core strategy composed of the big four strategies.\n */\nclass HTMLPurifier_Strategy_Core extends HTMLPurifier_Strategy_Composite\n{\n\n    public function __construct() {\n        $this->strategies[] = new HTMLPurifier_Strategy_RemoveForeignElements();\n        $this->strategies[] = new HTMLPurifier_Strategy_MakeWellFormed();\n        $this->strategies[] = new HTMLPurifier_Strategy_FixNesting();\n        $this->strategies[] = new HTMLPurifier_Strategy_ValidateAttributes();\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Strategy/FixNesting.php",
    "content": "<?php\n\n/**\n * Takes a well formed list of tokens and fixes their nesting.\n *\n * HTML elements dictate which elements are allowed to be their children,\n * for example, you can't have a p tag in a span tag.  Other elements have\n * much more rigorous definitions: tables, for instance, require a specific\n * order for their elements.  There are also constraints not expressible by\n * document type definitions, such as the chameleon nature of ins/del\n * tags and global child exclusions.\n *\n * The first major objective of this strategy is to iterate through all the\n * nodes (not tokens) of the list of tokens and determine whether or not\n * their children conform to the element's definition.  If they do not, the\n * child definition may optionally supply an amended list of elements that\n * is valid or require that the entire node be deleted (and the previous\n * node rescanned).\n *\n * The second objective is to ensure that explicitly excluded elements of\n * an element do not appear in its children.  Code that accomplishes this\n * task is pervasive through the strategy, though the two are distinct tasks\n * and could, theoretically, be seperated (although it's not recommended).\n *\n * @note Whether or not unrecognized children are silently dropped or\n *       translated into text depends on the child definitions.\n *\n * @todo Enable nodes to be bubbled out of the structure.\n */\n\nclass HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy\n{\n\n    public function execute($tokens, $config, $context) {\n        //####################################################################//\n        // Pre-processing\n\n        // get a copy of the HTML definition\n        $definition = $config->getHTMLDefinition();\n\n        // insert implicit \"parent\" node, will be removed at end.\n        // DEFINITION CALL\n        $parent_name = $definition->info_parent;\n        array_unshift($tokens, new HTMLPurifier_Token_Start($parent_name));\n        $tokens[] = new HTMLPurifier_Token_End($parent_name);\n\n        // setup the context variable 'IsInline', for chameleon processing\n        // is 'false' when we are not inline, 'true' when it must always\n        // be inline, and an integer when it is inline for a certain\n        // branch of the document tree\n        $is_inline = $definition->info_parent_def->descendants_are_inline;\n        $context->register('IsInline', $is_inline);\n\n        // setup error collector\n        $e =& $context->get('ErrorCollector', true);\n\n        //####################################################################//\n        // Loop initialization\n\n        // stack that contains the indexes of all parents,\n        // $stack[count($stack)-1] being the current parent\n        $stack = array();\n\n        // stack that contains all elements that are excluded\n        // it is organized by parent elements, similar to $stack,\n        // but it is only populated when an element with exclusions is\n        // processed, i.e. there won't be empty exclusions.\n        $exclude_stack = array();\n\n        // variable that contains the start token while we are processing\n        // nodes. This enables error reporting to do its job\n        $start_token = false;\n        $context->register('CurrentToken', $start_token);\n\n        //####################################################################//\n        // Loop\n\n        // iterate through all start nodes. Determining the start node\n        // is complicated so it has been omitted from the loop construct\n        for ($i = 0, $size = count($tokens) ; $i < $size; ) {\n\n            //################################################################//\n            // Gather information on children\n\n            // child token accumulator\n            $child_tokens = array();\n\n            // scroll to the end of this node, report number, and collect\n            // all children\n            for ($j = $i, $depth = 0; ; $j++) {\n                if ($tokens[$j] instanceof HTMLPurifier_Token_Start) {\n                    $depth++;\n                    // skip token assignment on first iteration, this is the\n                    // token we currently are on\n                    if ($depth == 1) continue;\n                } elseif ($tokens[$j] instanceof HTMLPurifier_Token_End) {\n                    $depth--;\n                    // skip token assignment on last iteration, this is the\n                    // end token of the token we're currently on\n                    if ($depth == 0) break;\n                }\n                $child_tokens[] = $tokens[$j];\n            }\n\n            // $i is index of start token\n            // $j is index of end token\n\n            $start_token = $tokens[$i]; // to make token available via CurrentToken\n\n            //################################################################//\n            // Gather information on parent\n\n            // calculate parent information\n            if ($count = count($stack)) {\n                $parent_index = $stack[$count-1];\n                $parent_name  = $tokens[$parent_index]->name;\n                if ($parent_index == 0) {\n                    $parent_def   = $definition->info_parent_def;\n                } else {\n                    $parent_def   = $definition->info[$parent_name];\n                }\n            } else {\n                // processing as if the parent were the \"root\" node\n                // unknown info, it won't be used anyway, in the future,\n                // we may want to enforce one element only (this is\n                // necessary for HTML Purifier to clean entire documents\n                $parent_index = $parent_name = $parent_def = null;\n            }\n\n            // calculate context\n            if ($is_inline === false) {\n                // check if conditions make it inline\n                if (!empty($parent_def) && $parent_def->descendants_are_inline) {\n                    $is_inline = $count - 1;\n                }\n            } else {\n                // check if we're out of inline\n                if ($count === $is_inline) {\n                    $is_inline = false;\n                }\n            }\n\n            //################################################################//\n            // Determine whether element is explicitly excluded SGML-style\n\n            // determine whether or not element is excluded by checking all\n            // parent exclusions. The array should not be very large, two\n            // elements at most.\n            $excluded = false;\n            if (!empty($exclude_stack)) {\n                foreach ($exclude_stack as $lookup) {\n                    if (isset($lookup[$tokens[$i]->name])) {\n                        $excluded = true;\n                        // no need to continue processing\n                        break;\n                    }\n                }\n            }\n\n            //################################################################//\n            // Perform child validation\n\n            if ($excluded) {\n                // there is an exclusion, remove the entire node\n                $result = false;\n                $excludes = array(); // not used, but good to initialize anyway\n            } else {\n                // DEFINITION CALL\n                if ($i === 0) {\n                    // special processing for the first node\n                    $def = $definition->info_parent_def;\n                } else {\n                    $def = $definition->info[$tokens[$i]->name];\n\n                }\n\n                if (!empty($def->child)) {\n                    // have DTD child def validate children\n                    $result = $def->child->validateChildren(\n                        $child_tokens, $config, $context);\n                } else {\n                    // weird, no child definition, get rid of everything\n                    $result = false;\n                }\n\n                // determine whether or not this element has any exclusions\n                $excludes = $def->excludes;\n            }\n\n            // $result is now a bool or array\n\n            //################################################################//\n            // Process result by interpreting $result\n\n            if ($result === true || $child_tokens === $result) {\n                // leave the node as is\n\n                // register start token as a parental node start\n                $stack[] = $i;\n\n                // register exclusions if there are any\n                if (!empty($excludes)) $exclude_stack[] = $excludes;\n\n                // move cursor to next possible start node\n                $i++;\n\n            } elseif($result === false) {\n                // remove entire node\n\n                if ($e) {\n                    if ($excluded) {\n                        $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');\n                    } else {\n                        $e->send(E_ERROR, 'Strategy_FixNesting: Node removed');\n                    }\n                }\n\n                // calculate length of inner tokens and current tokens\n                $length = $j - $i + 1;\n\n                // perform removal\n                array_splice($tokens, $i, $length);\n\n                // update size\n                $size -= $length;\n\n                // there is no start token to register,\n                // current node is now the next possible start node\n                // unless it turns out that we need to do a double-check\n\n                // this is a rought heuristic that covers 100% of HTML's\n                // cases and 99% of all other cases. A child definition\n                // that would be tricked by this would be something like:\n                // ( | a b c) where it's all or nothing. Fortunately,\n                // our current implementation claims that that case would\n                // not allow empty, even if it did\n                if (!$parent_def->child->allow_empty) {\n                    // we need to do a double-check\n                    $i = $parent_index;\n                    array_pop($stack);\n                }\n\n                // PROJECTED OPTIMIZATION: Process all children elements before\n                // reprocessing parent node.\n\n            } else {\n                // replace node with $result\n\n                // calculate length of inner tokens\n                $length = $j - $i - 1;\n\n                if ($e) {\n                    if (empty($result) && $length) {\n                        $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');\n                    } else {\n                        $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');\n                    }\n                }\n\n                // perform replacement\n                array_splice($tokens, $i + 1, $length, $result);\n\n                // update size\n                $size -= $length;\n                $size += count($result);\n\n                // register start token as a parental node start\n                $stack[] = $i;\n\n                // register exclusions if there are any\n                if (!empty($excludes)) $exclude_stack[] = $excludes;\n\n                // move cursor to next possible start node\n                $i++;\n\n            }\n\n            //################################################################//\n            // Scroll to next start node\n\n            // We assume, at this point, that $i is the index of the token\n            // that is the first possible new start point for a node.\n\n            // Test if the token indeed is a start tag, if not, move forward\n            // and test again.\n            $size = count($tokens);\n            while ($i < $size and !$tokens[$i] instanceof HTMLPurifier_Token_Start) {\n                if ($tokens[$i] instanceof HTMLPurifier_Token_End) {\n                    // pop a token index off the stack if we ended a node\n                    array_pop($stack);\n                    // pop an exclusion lookup off exclusion stack if\n                    // we ended node and that node had exclusions\n                    if ($i == 0 || $i == $size - 1) {\n                        // use specialized var if it's the super-parent\n                        $s_excludes = $definition->info_parent_def->excludes;\n                    } else {\n                        $s_excludes = $definition->info[$tokens[$i]->name]->excludes;\n                    }\n                    if ($s_excludes) {\n                        array_pop($exclude_stack);\n                    }\n                }\n                $i++;\n            }\n\n        }\n\n        //####################################################################//\n        // Post-processing\n\n        // remove implicit parent tokens at the beginning and end\n        array_shift($tokens);\n        array_pop($tokens);\n\n        // remove context variables\n        $context->destroy('IsInline');\n        $context->destroy('CurrentToken');\n\n        //####################################################################//\n        // Return\n\n        return $tokens;\n\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Strategy/MakeWellFormed.php",
    "content": "<?php\n\n/**\n * Takes tokens makes them well-formed (balance end tags, etc.)\n */\nclass HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy\n{\n\n    /**\n     * Array stream of tokens being processed.\n     */\n    protected $tokens;\n\n    /**\n     * Current index in $tokens.\n     */\n    protected $t;\n\n    /**\n     * Current nesting of elements.\n     */\n    protected $stack;\n\n    /**\n     * Injectors active in this stream processing.\n     */\n    protected $injectors;\n\n    /**\n     * Current instance of HTMLPurifier_Config.\n     */\n    protected $config;\n\n    /**\n     * Current instance of HTMLPurifier_Context.\n     */\n    protected $context;\n\n    public function execute($tokens, $config, $context) {\n\n        $definition = $config->getHTMLDefinition();\n\n        // local variables\n        $generator = new HTMLPurifier_Generator($config, $context);\n        $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');\n        $e = $context->get('ErrorCollector', true);\n        $t = false; // token index\n        $i = false; // injector index\n        $token      = false; // the current token\n        $reprocess  = false; // whether or not to reprocess the same token\n        $stack = array();\n\n        // member variables\n        $this->stack   =& $stack;\n        $this->t       =& $t;\n        $this->tokens  =& $tokens;\n        $this->config  = $config;\n        $this->context = $context;\n\n        // context variables\n        $context->register('CurrentNesting', $stack);\n        $context->register('InputIndex',     $t);\n        $context->register('InputTokens',    $tokens);\n        $context->register('CurrentToken',   $token);\n\n        // -- begin INJECTOR --\n\n        $this->injectors = array();\n\n        $injectors = $config->getBatch('AutoFormat');\n        $def_injectors = $definition->info_injector;\n        $custom_injectors = $injectors['Custom'];\n        unset($injectors['Custom']); // special case\n        foreach ($injectors as $injector => $b) {\n            // XXX: Fix with a legitimate lookup table of enabled filters\n            if (strpos($injector, '.') !== false) continue;\n            $injector = \"HTMLPurifier_Injector_$injector\";\n            if (!$b) continue;\n            $this->injectors[] = new $injector;\n        }\n        foreach ($def_injectors as $injector) {\n            // assumed to be objects\n            $this->injectors[] = $injector;\n        }\n        foreach ($custom_injectors as $injector) {\n            if (is_string($injector)) {\n                $injector = \"HTMLPurifier_Injector_$injector\";\n                $injector = new $injector;\n            }\n            $this->injectors[] = $injector;\n        }\n\n        // give the injectors references to the definition and context\n        // variables for performance reasons\n        foreach ($this->injectors as $ix => $injector) {\n            $error = $injector->prepare($config, $context);\n            if (!$error) continue;\n            array_splice($this->injectors, $ix, 1); // rm the injector\n            trigger_error(\"Cannot enable {$injector->name} injector because $error is not allowed\", E_USER_WARNING);\n        }\n\n        // -- end INJECTOR --\n\n        // a note on punting:\n        //      In order to reduce code duplication, whenever some code needs\n        //      to make HTML changes in order to make things \"correct\", the\n        //      new HTML gets sent through the purifier, regardless of its\n        //      status. This means that if we add a start token, because it\n        //      was totally necessary, we don't have to update nesting; we just\n        //      punt ($reprocess = true; continue;) and it does that for us.\n\n        // isset is in loop because $tokens size changes during loop exec\n        for (\n            $t = 0;\n            $t == 0 || isset($tokens[$t - 1]);\n            // only increment if we don't need to reprocess\n            $reprocess ? $reprocess = false : $t++\n        ) {\n\n            // check for a rewind\n            if (is_int($i) && $i >= 0) {\n                // possibility: disable rewinding if the current token has a\n                // rewind set on it already. This would offer protection from\n                // infinite loop, but might hinder some advanced rewinding.\n                $rewind_to = $this->injectors[$i]->getRewind();\n                if (is_int($rewind_to) && $rewind_to < $t) {\n                    if ($rewind_to < 0) $rewind_to = 0;\n                    while ($t > $rewind_to) {\n                        $t--;\n                        $prev = $tokens[$t];\n                        // indicate that other injectors should not process this token,\n                        // but we need to reprocess it\n                        unset($prev->skip[$i]);\n                        $prev->rewind = $i;\n                        if ($prev instanceof HTMLPurifier_Token_Start) array_pop($this->stack);\n                        elseif ($prev instanceof HTMLPurifier_Token_End) $this->stack[] = $prev->start;\n                    }\n                }\n                $i = false;\n            }\n\n            // handle case of document end\n            if (!isset($tokens[$t])) {\n                // kill processing if stack is empty\n                if (empty($this->stack)) break;\n\n                // peek\n                $top_nesting = array_pop($this->stack);\n                $this->stack[] = $top_nesting;\n\n                // send error\n                if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {\n                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);\n                }\n\n                // append, don't splice, since this is the end\n                $tokens[] = new HTMLPurifier_Token_End($top_nesting->name);\n\n                // punt!\n                $reprocess = true;\n                continue;\n            }\n\n            $token = $tokens[$t];\n\n            //echo '<br>'; printTokens($tokens, $t); printTokens($this->stack);\n\n            // quick-check: if it's not a tag, no need to process\n            if (empty($token->is_tag)) {\n                if ($token instanceof HTMLPurifier_Token_Text) {\n                    foreach ($this->injectors as $i => $injector) {\n                        if (isset($token->skip[$i])) continue;\n                        if ($token->rewind !== null && $token->rewind !== $i) continue;\n                        $injector->handleText($token);\n                        $this->processToken($token, $i);\n                        $reprocess = true;\n                        break;\n                    }\n                }\n                // another possibility is a comment\n                continue;\n            }\n\n            if (isset($definition->info[$token->name])) {\n                $type = $definition->info[$token->name]->child->type;\n            } else {\n                $type = false; // Type is unknown, treat accordingly\n            }\n\n            // quick tag checks: anything that's *not* an end tag\n            $ok = false;\n            if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {\n                // claims to be a start tag but is empty\n                $token = new HTMLPurifier_Token_Empty($token->name, $token->attr);\n                $ok = true;\n            } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) {\n                // claims to be empty but really is a start tag\n                $this->swap(new HTMLPurifier_Token_End($token->name));\n                $this->insertBefore(new HTMLPurifier_Token_Start($token->name, $token->attr));\n                // punt (since we had to modify the input stream in a non-trivial way)\n                $reprocess = true;\n                continue;\n            } elseif ($token instanceof HTMLPurifier_Token_Empty) {\n                // real empty token\n                $ok = true;\n            } elseif ($token instanceof HTMLPurifier_Token_Start) {\n                // start tag\n\n                // ...unless they also have to close their parent\n                if (!empty($this->stack)) {\n\n                    $parent = array_pop($this->stack);\n                    $this->stack[] = $parent;\n\n                    if (isset($definition->info[$parent->name])) {\n                        $elements = $definition->info[$parent->name]->child->getAllowedElements($config);\n                        $autoclose = !isset($elements[$token->name]);\n                    } else {\n                        $autoclose = false;\n                    }\n\n                    $carryover = false;\n                    if ($autoclose && $definition->info[$parent->name]->formatting) {\n                        $carryover = true;\n                    }\n\n                    if ($autoclose) {\n                        // errors need to be updated\n                        $new_token = new HTMLPurifier_Token_End($parent->name);\n                        $new_token->start = $parent;\n                        if ($carryover) {\n                            $element = clone $parent;\n                            $element->armor['MakeWellFormed_TagClosedError'] = true;\n                            $element->carryover = true;\n                            $this->processToken(array($new_token, $token, $element));\n                        } else {\n                            $this->insertBefore($new_token);\n                        }\n                        if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) {\n                            if (!$carryover) {\n                                $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);\n                            } else {\n                                $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent);\n                            }\n                        }\n                        $reprocess = true;\n                        continue;\n                    }\n\n                }\n                $ok = true;\n            }\n\n            if ($ok) {\n                foreach ($this->injectors as $i => $injector) {\n                    if (isset($token->skip[$i])) continue;\n                    if ($token->rewind !== null && $token->rewind !== $i) continue;\n                    $injector->handleElement($token);\n                    $this->processToken($token, $i);\n                    $reprocess = true;\n                    break;\n                }\n                if (!$reprocess) {\n                    // ah, nothing interesting happened; do normal processing\n                    $this->swap($token);\n                    if ($token instanceof HTMLPurifier_Token_Start) {\n                        $this->stack[] = $token;\n                    } elseif ($token instanceof HTMLPurifier_Token_End) {\n                        throw new HTMLPurifier_Exception('Improper handling of end tag in start code; possible error in MakeWellFormed');\n                    }\n                }\n                continue;\n            }\n\n            // sanity check: we should be dealing with a closing tag\n            if (!$token instanceof HTMLPurifier_Token_End) {\n                throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');\n            }\n\n            // make sure that we have something open\n            if (empty($this->stack)) {\n                if ($escape_invalid_tags) {\n                    if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');\n                    $this->swap(new HTMLPurifier_Token_Text(\n                        $generator->generateFromToken($token)\n                    ));\n                } else {\n                    $this->remove();\n                    if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');\n                }\n                $reprocess = true;\n                continue;\n            }\n\n            // first, check for the simplest case: everything closes neatly.\n            // Eventually, everything passes through here; if there are problems\n            // we modify the input stream accordingly and then punt, so that\n            // the tokens get processed again.\n            $current_parent = array_pop($this->stack);\n            if ($current_parent->name == $token->name) {\n                $token->start = $current_parent;\n                foreach ($this->injectors as $i => $injector) {\n                    if (isset($token->skip[$i])) continue;\n                    if ($token->rewind !== null && $token->rewind !== $i) continue;\n                    $injector->handleEnd($token);\n                    $this->processToken($token, $i);\n                    $this->stack[] = $current_parent;\n                    $reprocess = true;\n                    break;\n                }\n                continue;\n            }\n\n            // okay, so we're trying to close the wrong tag\n\n            // undo the pop previous pop\n            $this->stack[] = $current_parent;\n\n            // scroll back the entire nest, trying to find our tag.\n            // (feature could be to specify how far you'd like to go)\n            $size = count($this->stack);\n            // -2 because -1 is the last element, but we already checked that\n            $skipped_tags = false;\n            for ($j = $size - 2; $j >= 0; $j--) {\n                if ($this->stack[$j]->name == $token->name) {\n                    $skipped_tags = array_slice($this->stack, $j);\n                    break;\n                }\n            }\n\n            // we didn't find the tag, so remove\n            if ($skipped_tags === false) {\n                if ($escape_invalid_tags) {\n                    $this->swap(new HTMLPurifier_Token_Text(\n                        $generator->generateFromToken($token)\n                    ));\n                    if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text');\n                } else {\n                    $this->remove();\n                    if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');\n                }\n                $reprocess = true;\n                continue;\n            }\n\n            // do errors, in REVERSE $j order: a,b,c with </a></b></c>\n            $c = count($skipped_tags);\n            if ($e) {\n                for ($j = $c - 1; $j > 0; $j--) {\n                    // notice we exclude $j == 0, i.e. the current ending tag, from\n                    // the errors...\n                    if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) {\n                        $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]);\n                    }\n                }\n            }\n\n            // insert tags, in FORWARD $j order: c,b,a with </a></b></c>\n            $replace = array($token);\n            for ($j = 1; $j < $c; $j++) {\n                // ...as well as from the insertions\n                $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);\n                $new_token->start = $skipped_tags[$j];\n                array_unshift($replace, $new_token);\n                if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) {\n                    $element = clone $skipped_tags[$j];\n                    $element->carryover = true;\n                    $element->armor['MakeWellFormed_TagClosedError'] = true;\n                    $replace[] = $element;\n                }\n            }\n            $this->processToken($replace);\n            $reprocess = true;\n            continue;\n        }\n\n        $context->destroy('CurrentNesting');\n        $context->destroy('InputTokens');\n        $context->destroy('InputIndex');\n        $context->destroy('CurrentToken');\n\n        unset($this->injectors, $this->stack, $this->tokens, $this->t);\n        return $tokens;\n    }\n\n    /**\n     * Processes arbitrary token values for complicated substitution patterns.\n     * In general:\n     *\n     * If $token is an array, it is a list of tokens to substitute for the\n     * current token. These tokens then get individually processed. If there\n     * is a leading integer in the list, that integer determines how many\n     * tokens from the stream should be removed.\n     *\n     * If $token is a regular token, it is swapped with the current token.\n     *\n     * If $token is false, the current token is deleted.\n     *\n     * If $token is an integer, that number of tokens (with the first token\n     * being the current one) will be deleted.\n     *\n     * @param $token Token substitution value\n     * @param $injector Injector that performed the substitution; default is if\n     *        this is not an injector related operation.\n     */\n    protected function processToken($token, $injector = -1) {\n\n        // normalize forms of token\n        if (is_object($token)) $token = array(1, $token);\n        if (is_int($token))    $token = array($token);\n        if ($token === false)  $token = array(1);\n        if (!is_array($token)) throw new HTMLPurifier_Exception('Invalid token type from injector');\n        if (!is_int($token[0])) array_unshift($token, 1);\n        if ($token[0] === 0) throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');\n\n        // $token is now an array with the following form:\n        // array(number nodes to delete, new node 1, new node 2, ...)\n\n        $delete = array_shift($token);\n        $old = array_splice($this->tokens, $this->t, $delete, $token);\n\n        if ($injector > -1) {\n            // determine appropriate skips\n            $oldskip = isset($old[0]) ? $old[0]->skip : array();\n            foreach ($token as $object) {\n                $object->skip = $oldskip;\n                $object->skip[$injector] = true;\n            }\n        }\n\n    }\n\n    /**\n     * Inserts a token before the current token. Cursor now points to this token\n     */\n    private function insertBefore($token) {\n        array_splice($this->tokens, $this->t, 0, array($token));\n    }\n\n    /**\n     * Removes current token. Cursor now points to new token occupying previously\n     * occupied space.\n     */\n    private function remove() {\n        array_splice($this->tokens, $this->t, 1);\n    }\n\n    /**\n     * Swap current token with new token. Cursor points to new token (no change).\n     */\n    private function swap($token) {\n        $this->tokens[$this->t] = $token;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Strategy/RemoveForeignElements.php",
    "content": "<?php\n\n/**\n * Removes all unrecognized tags from the list of tokens.\n *\n * This strategy iterates through all the tokens and removes unrecognized\n * tokens. If a token is not recognized but a TagTransform is defined for\n * that element, the element will be transformed accordingly.\n */\n\nclass HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy\n{\n\n    public function execute($tokens, $config, $context) {\n        $definition = $config->getHTMLDefinition();\n        $generator = new HTMLPurifier_Generator($config, $context);\n        $result = array();\n\n        $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');\n        $remove_invalid_img  = $config->get('Core.RemoveInvalidImg');\n\n        // currently only used to determine if comments should be kept\n        $trusted = $config->get('HTML.Trusted');\n\n        $remove_script_contents = $config->get('Core.RemoveScriptContents');\n        $hidden_elements     = $config->get('Core.HiddenElements');\n\n        // remove script contents compatibility\n        if ($remove_script_contents === true) {\n            $hidden_elements['script'] = true;\n        } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) {\n            unset($hidden_elements['script']);\n        }\n\n        $attr_validator = new HTMLPurifier_AttrValidator();\n\n        // removes tokens until it reaches a closing tag with its value\n        $remove_until = false;\n\n        // converts comments into text tokens when this is equal to a tag name\n        $textify_comments = false;\n\n        $token = false;\n        $context->register('CurrentToken', $token);\n\n        $e = false;\n        if ($config->get('Core.CollectErrors')) {\n            $e =& $context->get('ErrorCollector');\n        }\n\n        foreach($tokens as $token) {\n            if ($remove_until) {\n                if (empty($token->is_tag) || $token->name !== $remove_until) {\n                    continue;\n                }\n            }\n            if (!empty( $token->is_tag )) {\n                // DEFINITION CALL\n\n                // before any processing, try to transform the element\n                if (\n                    isset($definition->info_tag_transform[$token->name])\n                ) {\n                    $original_name = $token->name;\n                    // there is a transformation for this tag\n                    // DEFINITION CALL\n                    $token = $definition->\n                                info_tag_transform[$token->name]->\n                                    transform($token, $config, $context);\n                    if ($e) $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name);\n                }\n\n                if (isset($definition->info[$token->name])) {\n\n                    // mostly everything's good, but\n                    // we need to make sure required attributes are in order\n                    if (\n                        ($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) &&\n                        $definition->info[$token->name]->required_attr &&\n                        ($token->name != 'img' || $remove_invalid_img) // ensure config option still works\n                    ) {\n                        $attr_validator->validateToken($token, $config, $context);\n                        $ok = true;\n                        foreach ($definition->info[$token->name]->required_attr as $name) {\n                            if (!isset($token->attr[$name])) {\n                                $ok = false;\n                                break;\n                            }\n                        }\n                        if (!$ok) {\n                            if ($e) $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Missing required attribute', $name);\n                            continue;\n                        }\n                        $token->armor['ValidateAttributes'] = true;\n                    }\n\n                    if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) {\n                        $textify_comments = $token->name;\n                    } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) {\n                        $textify_comments = false;\n                    }\n\n                } elseif ($escape_invalid_tags) {\n                    // invalid tag, generate HTML representation and insert in\n                    if ($e) $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text');\n                    $token = new HTMLPurifier_Token_Text(\n                        $generator->generateFromToken($token)\n                    );\n                } else {\n                    // check if we need to destroy all of the tag's children\n                    // CAN BE GENERICIZED\n                    if (isset($hidden_elements[$token->name])) {\n                        if ($token instanceof HTMLPurifier_Token_Start) {\n                            $remove_until = $token->name;\n                        } elseif ($token instanceof HTMLPurifier_Token_Empty) {\n                            // do nothing: we're still looking\n                        } else {\n                            $remove_until = false;\n                        }\n                        if ($e) $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed');\n                    } else {\n                        if ($e) $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed');\n                    }\n                    continue;\n                }\n            } elseif ($token instanceof HTMLPurifier_Token_Comment) {\n                // textify comments in script tags when they are allowed\n                if ($textify_comments !== false) {\n                    $data = $token->data;\n                    $token = new HTMLPurifier_Token_Text($data);\n                } elseif ($trusted) {\n                    // keep, but perform comment cleaning\n                    if ($e) {\n                        // perform check whether or not there's a trailing hyphen\n                        if (substr($token->data, -1) == '-') {\n                            $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Trailing hyphen in comment removed');\n                        }\n                    }\n                    $token->data = rtrim($token->data, '-');\n                    $found_double_hyphen = false;\n                    while (strpos($token->data, '--') !== false) {\n                        if ($e && !$found_double_hyphen) {\n                            $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Hyphens in comment collapsed');\n                        }\n                        $found_double_hyphen = true; // prevent double-erroring\n                        $token->data = str_replace('--', '-', $token->data);\n                    }\n                } else {\n                    // strip comments\n                    if ($e) $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed');\n                    continue;\n                }\n            } elseif ($token instanceof HTMLPurifier_Token_Text) {\n            } else {\n                continue;\n            }\n            $result[] = $token;\n        }\n        if ($remove_until && $e) {\n            // we removed tokens until the end, throw error\n            $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Token removed to end', $remove_until);\n        }\n\n        $context->destroy('CurrentToken');\n\n        return $result;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Strategy/ValidateAttributes.php",
    "content": "<?php\n\n/**\n * Validate all attributes in the tokens.\n */\n\nclass HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy\n{\n\n    public function execute($tokens, $config, $context) {\n\n        // setup validator\n        $validator = new HTMLPurifier_AttrValidator();\n\n        $token = false;\n        $context->register('CurrentToken', $token);\n\n        foreach ($tokens as $key => $token) {\n\n            // only process tokens that have attributes,\n            //   namely start and empty tags\n            if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) continue;\n\n            // skip tokens that are armored\n            if (!empty($token->armor['ValidateAttributes'])) continue;\n\n            // note that we have no facilities here for removing tokens\n            $validator->validateToken($token, $config, $context);\n\n            $tokens[$key] = $token; // for PHP 4\n        }\n        $context->destroy('CurrentToken');\n\n        return $tokens;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Strategy.php",
    "content": "<?php\n\n/**\n * Supertype for classes that define a strategy for modifying/purifying tokens.\n *\n * While HTMLPurifier's core purpose is fixing HTML into something proper,\n * strategies provide plug points for extra configuration or even extra\n * features, such as custom tags, custom parsing of text, etc.\n */\n\n\nabstract class HTMLPurifier_Strategy\n{\n\n    /**\n     * Executes the strategy on the tokens.\n     *\n     * @param $tokens Array of HTMLPurifier_Token objects to be operated on.\n     * @param $config Configuration options\n     * @returns Processed array of token objects.\n     */\n    abstract public function execute($tokens, $config, $context);\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/StringHash.php",
    "content": "<?php\n\n/**\n * This is in almost every respect equivalent to an array except\n * that it keeps track of which keys were accessed.\n *\n * @warning For the sake of backwards compatibility with early versions\n *     of PHP 5, you must not use the $hash[$key] syntax; if you do\n *     our version of offsetGet is never called.\n */\nclass HTMLPurifier_StringHash extends ArrayObject\n{\n    protected $accessed = array();\n\n    /**\n     * Retrieves a value, and logs the access.\n     */\n    public function offsetGet($index) {\n        $this->accessed[$index] = true;\n        return parent::offsetGet($index);\n    }\n\n    /**\n     * Returns a lookup array of all array indexes that have been accessed.\n     * @return Array in form array($index => true).\n     */\n    public function getAccessed() {\n        return $this->accessed;\n    }\n\n    /**\n     * Resets the access array.\n     */\n    public function resetAccessed() {\n        $this->accessed = array();\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/StringHashParser.php",
    "content": "<?php\n\n/**\n * Parses string hash files. File format is as such:\n *\n *      DefaultKeyValue\n *      KEY: Value\n *      KEY2: Value2\n *      --MULTILINE-KEY--\n *      Multiline\n *      value.\n *\n * Which would output something similar to:\n *\n *      array(\n *          'ID' => 'DefaultKeyValue',\n *          'KEY' => 'Value',\n *          'KEY2' => 'Value2',\n *          'MULTILINE-KEY' => \"Multiline\\nvalue.\\n\",\n *      )\n *\n * We use this as an easy to use file-format for configuration schema\n * files, but the class itself is usage agnostic.\n *\n * You can use ---- to forcibly terminate parsing of a single string-hash;\n * this marker is used in multi string-hashes to delimit boundaries.\n */\nclass HTMLPurifier_StringHashParser\n{\n\n    public $default = 'ID';\n\n    /**\n     * Parses a file that contains a single string-hash.\n     */\n    public function parseFile($file) {\n        if (!file_exists($file)) return false;\n        $fh = fopen($file, 'r');\n        if (!$fh) return false;\n        $ret = $this->parseHandle($fh);\n        fclose($fh);\n        return $ret;\n    }\n\n    /**\n     * Parses a file that contains multiple string-hashes delimited by '----'\n     */\n    public function parseMultiFile($file) {\n        if (!file_exists($file)) return false;\n        $ret = array();\n        $fh = fopen($file, 'r');\n        if (!$fh) return false;\n        while (!feof($fh)) {\n            $ret[] = $this->parseHandle($fh);\n        }\n        fclose($fh);\n        return $ret;\n    }\n\n    /**\n     * Internal parser that acepts a file handle.\n     * @note While it's possible to simulate in-memory parsing by using\n     *       custom stream wrappers, if such a use-case arises we should\n     *       factor out the file handle into its own class.\n     * @param $fh File handle with pointer at start of valid string-hash\n     *            block.\n     */\n    protected function parseHandle($fh) {\n        $state   = false;\n        $single  = false;\n        $ret     = array();\n        do {\n            $line = fgets($fh);\n            if ($line === false) break;\n            $line = rtrim($line, \"\\n\\r\");\n            if (!$state && $line === '') continue;\n            if ($line === '----') break;\n            if (strncmp('--#', $line, 3) === 0) {\n                // Comment\n                continue;\n            } elseif (strncmp('--', $line, 2) === 0) {\n                // Multiline declaration\n                $state = trim($line, '- ');\n                if (!isset($ret[$state])) $ret[$state] = '';\n                continue;\n            } elseif (!$state) {\n                $single = true;\n                if (strpos($line, ':') !== false) {\n                    // Single-line declaration\n                    list($state, $line) = explode(':', $line, 2);\n                    $line = trim($line);\n                } else {\n                    // Use default declaration\n                    $state  = $this->default;\n                }\n            }\n            if ($single) {\n                $ret[$state] = $line;\n                $single = false;\n                $state  = false;\n            } else {\n                $ret[$state] .= \"$line\\n\";\n            }\n        } while (!feof($fh));\n        return $ret;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/TagTransform/Font.php",
    "content": "<?php\n\n/**\n * Transforms FONT tags to the proper form (SPAN with CSS styling)\n *\n * This transformation takes the three proprietary attributes of FONT and\n * transforms them into their corresponding CSS attributes.  These are color,\n * face, and size.\n *\n * @note Size is an interesting case because it doesn't map cleanly to CSS.\n *       Thanks to\n *       http://style.cleverchimp.com/font_size_intervals/altintervals.html\n *       for reasonable mappings.\n * @warning This doesn't work completely correctly; specifically, this\n *          TagTransform operates before well-formedness is enforced, so\n *          the \"active formatting elements\" algorithm doesn't get applied.\n */\nclass HTMLPurifier_TagTransform_Font extends HTMLPurifier_TagTransform\n{\n\n    public $transform_to = 'span';\n\n    protected $_size_lookup = array(\n        '0' => 'xx-small',\n        '1' => 'xx-small',\n        '2' => 'small',\n        '3' => 'medium',\n        '4' => 'large',\n        '5' => 'x-large',\n        '6' => 'xx-large',\n        '7' => '300%',\n        '-1' => 'smaller',\n        '-2' => '60%',\n        '+1' => 'larger',\n        '+2' => '150%',\n        '+3' => '200%',\n        '+4' => '300%'\n    );\n\n    public function transform($tag, $config, $context) {\n\n        if ($tag instanceof HTMLPurifier_Token_End) {\n            $new_tag = clone $tag;\n            $new_tag->name = $this->transform_to;\n            return $new_tag;\n        }\n\n        $attr = $tag->attr;\n        $prepend_style = '';\n\n        // handle color transform\n        if (isset($attr['color'])) {\n            $prepend_style .= 'color:' . $attr['color'] . ';';\n            unset($attr['color']);\n        }\n\n        // handle face transform\n        if (isset($attr['face'])) {\n            $prepend_style .= 'font-family:' . $attr['face'] . ';';\n            unset($attr['face']);\n        }\n\n        // handle size transform\n        if (isset($attr['size'])) {\n            // normalize large numbers\n            if ($attr['size']{0} == '+' || $attr['size']{0} == '-') {\n                $size = (int) $attr['size'];\n                if ($size < -2) $attr['size'] = '-2';\n                if ($size > 4)  $attr['size'] = '+4';\n            } else {\n                $size = (int) $attr['size'];\n                if ($size > 7) $attr['size'] = '7';\n            }\n            if (isset($this->_size_lookup[$attr['size']])) {\n                $prepend_style .= 'font-size:' .\n                  $this->_size_lookup[$attr['size']] . ';';\n            }\n            unset($attr['size']);\n        }\n\n        if ($prepend_style) {\n            $attr['style'] = isset($attr['style']) ?\n                $prepend_style . $attr['style'] :\n                $prepend_style;\n        }\n\n        $new_tag = clone $tag;\n        $new_tag->name = $this->transform_to;\n        $new_tag->attr = $attr;\n\n        return $new_tag;\n\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/TagTransform/Simple.php",
    "content": "<?php\n\n/**\n * Simple transformation, just change tag name to something else,\n * and possibly add some styling. This will cover most of the deprecated\n * tag cases.\n */\nclass HTMLPurifier_TagTransform_Simple extends HTMLPurifier_TagTransform\n{\n\n    protected $style;\n\n    /**\n     * @param $transform_to Tag name to transform to.\n     * @param $style CSS style to add to the tag\n     */\n    public function __construct($transform_to, $style = null) {\n        $this->transform_to = $transform_to;\n        $this->style = $style;\n    }\n\n    public function transform($tag, $config, $context) {\n        $new_tag = clone $tag;\n        $new_tag->name = $this->transform_to;\n        if (!is_null($this->style) &&\n            ($new_tag instanceof HTMLPurifier_Token_Start || $new_tag instanceof HTMLPurifier_Token_Empty)\n        ) {\n            $this->prependCSS($new_tag->attr, $this->style);\n        }\n        return $new_tag;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/TagTransform.php",
    "content": "<?php\n\n/**\n * Defines a mutation of an obsolete tag into a valid tag.\n */\nabstract class HTMLPurifier_TagTransform\n{\n\n    /**\n     * Tag name to transform the tag to.\n     */\n    public $transform_to;\n\n    /**\n     * Transforms the obsolete tag into the valid tag.\n     * @param $tag Tag to be transformed.\n     * @param $config Mandatory HTMLPurifier_Config object\n     * @param $context Mandatory HTMLPurifier_Context object\n     */\n    abstract public function transform($tag, $config, $context);\n\n    /**\n     * Prepends CSS properties to the style attribute, creating the\n     * attribute if it doesn't exist.\n     * @warning Copied over from AttrTransform, be sure to keep in sync\n     * @param $attr Attribute array to process (passed by reference)\n     * @param $css CSS to prepend\n     */\n    protected function prependCSS(&$attr, $css) {\n        $attr['style'] = isset($attr['style']) ? $attr['style'] : '';\n        $attr['style'] = $css . $attr['style'];\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Token/Comment.php",
    "content": "<?php\n\n/**\n * Concrete comment token class. Generally will be ignored.\n */\nclass HTMLPurifier_Token_Comment extends HTMLPurifier_Token\n{\n    public $data; /**< Character data within comment. */\n    public $is_whitespace = true;\n    /**\n     * Transparent constructor.\n     *\n     * @param $data String comment data.\n     */\n    public function __construct($data, $line = null, $col = null) {\n        $this->data = $data;\n        $this->line = $line;\n        $this->col  = $col;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Token/Empty.php",
    "content": "<?php\n\n/**\n * Concrete empty token class.\n */\nclass HTMLPurifier_Token_Empty extends HTMLPurifier_Token_Tag\n{\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Token/End.php",
    "content": "<?php\n\n/**\n * Concrete end token class.\n *\n * @warning This class accepts attributes even though end tags cannot. This\n * is for optimization reasons, as under normal circumstances, the Lexers\n * do not pass attributes.\n */\nclass HTMLPurifier_Token_End extends HTMLPurifier_Token_Tag\n{\n    /**\n     * Token that started this node. Added by MakeWellFormed. Please\n     * do not edit this!\n     */\n    public $start;\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Token/Start.php",
    "content": "<?php\n\n/**\n * Concrete start token class.\n */\nclass HTMLPurifier_Token_Start extends HTMLPurifier_Token_Tag\n{\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Token/Tag.php",
    "content": "<?php\n\n/**\n * Abstract class of a tag token (start, end or empty), and its behavior.\n */\nclass HTMLPurifier_Token_Tag extends HTMLPurifier_Token\n{\n    /**\n     * Static bool marker that indicates the class is a tag.\n     *\n     * This allows us to check objects with <tt>!empty($obj->is_tag)</tt>\n     * without having to use a function call <tt>is_a()</tt>.\n     */\n    public $is_tag = true;\n\n    /**\n     * The lower-case name of the tag, like 'a', 'b' or 'blockquote'.\n     *\n     * @note Strictly speaking, XML tags are case sensitive, so we shouldn't\n     * be lower-casing them, but these tokens cater to HTML tags, which are\n     * insensitive.\n     */\n    public $name;\n\n    /**\n     * Associative array of the tag's attributes.\n     */\n    public $attr = array();\n\n    /**\n     * Non-overloaded constructor, which lower-cases passed tag name.\n     *\n     * @param $name String name.\n     * @param $attr Associative array of attributes.\n     */\n    public function __construct($name, $attr = array(), $line = null, $col = null) {\n        $this->name = ctype_lower($name) ? $name : strtolower($name);\n        foreach ($attr as $key => $value) {\n            // normalization only necessary when key is not lowercase\n            if (!ctype_lower($key)) {\n                $new_key = strtolower($key);\n                if (!isset($attr[$new_key])) {\n                    $attr[$new_key] = $attr[$key];\n                }\n                if ($new_key !== $key) {\n                    unset($attr[$key]);\n                }\n            }\n        }\n        $this->attr = $attr;\n        $this->line = $line;\n        $this->col  = $col;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Token/Text.php",
    "content": "<?php\n\n/**\n * Concrete text token class.\n *\n * Text tokens comprise of regular parsed character data (PCDATA) and raw\n * character data (from the CDATA sections). Internally, their\n * data is parsed with all entities expanded. Surprisingly, the text token\n * does have a \"tag name\" called #PCDATA, which is how the DTD represents it\n * in permissible child nodes.\n */\nclass HTMLPurifier_Token_Text extends HTMLPurifier_Token\n{\n\n    public $name = '#PCDATA'; /**< PCDATA tag name compatible with DTD. */\n    public $data; /**< Parsed character data of text. */\n    public $is_whitespace; /**< Bool indicating if node is whitespace. */\n\n    /**\n     * Constructor, accepts data and determines if it is whitespace.\n     *\n     * @param $data String parsed character data.\n     */\n    public function __construct($data, $line = null, $col = null) {\n        $this->data = $data;\n        $this->is_whitespace = ctype_space($data);\n        $this->line = $line;\n        $this->col  = $col;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/Token.php",
    "content": "<?php\n\n/**\n * Abstract base token class that all others inherit from.\n */\nclass HTMLPurifier_Token {\n    public $line; /**< Line number node was on in source document. Null if unknown. */\n    public $col;  /**< Column of line node was on in source document. Null if unknown. */\n\n    /**\n     * Lookup array of processing that this token is exempt from.\n     * Currently, valid values are \"ValidateAttributes\" and\n     * \"MakeWellFormed_TagClosedError\"\n     */\n    public $armor = array();\n\n    /**\n     * Used during MakeWellFormed.\n     */\n    public $skip;\n    public $rewind;\n    public $carryover;\n\n    public function __get($n) {\n      if ($n === 'type') {\n        trigger_error('Deprecated type property called; use instanceof', E_USER_NOTICE);\n        switch (get_class($this)) {\n          case 'HTMLPurifier_Token_Start':      return 'start';\n          case 'HTMLPurifier_Token_Empty':      return 'empty';\n          case 'HTMLPurifier_Token_End':        return 'end';\n          case 'HTMLPurifier_Token_Text':       return 'text';\n          case 'HTMLPurifier_Token_Comment':    return 'comment';\n          default: return null;\n        }\n      }\n    }\n\n    /**\n     * Sets the position of the token in the source document.\n     */\n    public function position($l = null, $c = null) {\n        $this->line = $l;\n        $this->col  = $c;\n    }\n\n    /**\n     * Convenience function for DirectLex settings line/col position.\n     */\n    public function rawPosition($l, $c) {\n        if ($c === -1) $l++;\n        $this->line = $l;\n        $this->col  = $c;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/TokenFactory.php",
    "content": "<?php\n\n/**\n * Factory for token generation.\n *\n * @note Doing some benchmarking indicates that the new operator is much\n *       slower than the clone operator (even discounting the cost of the\n *       constructor).  This class is for that optimization.\n *       Other then that, there's not much point as we don't\n *       maintain parallel HTMLPurifier_Token hierarchies (the main reason why\n *       you'd want to use an abstract factory).\n * @todo Port DirectLex to use this\n */\nclass HTMLPurifier_TokenFactory\n{\n\n    /**\n     * Prototypes that will be cloned.\n     * @private\n     */\n    // p stands for prototype\n    private $p_start, $p_end, $p_empty, $p_text, $p_comment;\n\n    /**\n     * Generates blank prototypes for cloning.\n     */\n    public function __construct() {\n        $this->p_start  = new HTMLPurifier_Token_Start('', array());\n        $this->p_end    = new HTMLPurifier_Token_End('');\n        $this->p_empty  = new HTMLPurifier_Token_Empty('', array());\n        $this->p_text   = new HTMLPurifier_Token_Text('');\n        $this->p_comment= new HTMLPurifier_Token_Comment('');\n    }\n\n    /**\n     * Creates a HTMLPurifier_Token_Start.\n     * @param $name Tag name\n     * @param $attr Associative array of attributes\n     * @return Generated HTMLPurifier_Token_Start\n     */\n    public function createStart($name, $attr = array()) {\n        $p = clone $this->p_start;\n        $p->__construct($name, $attr);\n        return $p;\n    }\n\n    /**\n     * Creates a HTMLPurifier_Token_End.\n     * @param $name Tag name\n     * @return Generated HTMLPurifier_Token_End\n     */\n    public function createEnd($name) {\n        $p = clone $this->p_end;\n        $p->__construct($name);\n        return $p;\n    }\n\n    /**\n     * Creates a HTMLPurifier_Token_Empty.\n     * @param $name Tag name\n     * @param $attr Associative array of attributes\n     * @return Generated HTMLPurifier_Token_Empty\n     */\n    public function createEmpty($name, $attr = array()) {\n        $p = clone $this->p_empty;\n        $p->__construct($name, $attr);\n        return $p;\n    }\n\n    /**\n     * Creates a HTMLPurifier_Token_Text.\n     * @param $data Data of text token\n     * @return Generated HTMLPurifier_Token_Text\n     */\n    public function createText($data) {\n        $p = clone $this->p_text;\n        $p->__construct($data);\n        return $p;\n    }\n\n    /**\n     * Creates a HTMLPurifier_Token_Comment.\n     * @param $data Data of comment token\n     * @return Generated HTMLPurifier_Token_Comment\n     */\n    public function createComment($data) {\n        $p = clone $this->p_comment;\n        $p->__construct($data);\n        return $p;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URI.php",
    "content": "<?php\n\n/**\n * HTML Purifier's internal representation of a URI.\n * @note\n *      Internal data-structures are completely escaped. If the data needs\n *      to be used in a non-URI context (which is very unlikely), be sure\n *      to decode it first. The URI may not necessarily be well-formed until\n *      validate() is called.\n */\nclass HTMLPurifier_URI\n{\n\n    public $scheme, $userinfo, $host, $port, $path, $query, $fragment;\n\n    /**\n     * @note Automatically normalizes scheme and port\n     */\n    public function __construct($scheme, $userinfo, $host, $port, $path, $query, $fragment) {\n        $this->scheme = is_null($scheme) || ctype_lower($scheme) ? $scheme : strtolower($scheme);\n        $this->userinfo = $userinfo;\n        $this->host = $host;\n        $this->port = is_null($port) ? $port : (int) $port;\n        $this->path = $path;\n        $this->query = $query;\n        $this->fragment = $fragment;\n    }\n\n    /**\n     * Retrieves a scheme object corresponding to the URI's scheme/default\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     * @return Scheme object appropriate for validating this URI\n     */\n    public function getSchemeObj($config, $context) {\n        $registry = HTMLPurifier_URISchemeRegistry::instance();\n        if ($this->scheme !== null) {\n            $scheme_obj = $registry->getScheme($this->scheme, $config, $context);\n            if (!$scheme_obj) return false; // invalid scheme, clean it out\n        } else {\n            // no scheme: retrieve the default one\n            $def = $config->getDefinition('URI');\n            $scheme_obj = $registry->getScheme($def->defaultScheme, $config, $context);\n            if (!$scheme_obj) {\n                // something funky happened to the default scheme object\n                trigger_error(\n                    'Default scheme object \"' . $def->defaultScheme . '\" was not readable',\n                    E_USER_WARNING\n                );\n                return false;\n            }\n        }\n        return $scheme_obj;\n    }\n\n    /**\n     * Generic validation method applicable for all schemes. May modify\n     * this URI in order to get it into a compliant form.\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     * @return True if validation/filtering succeeds, false if failure\n     */\n    public function validate($config, $context) {\n\n        // ABNF definitions from RFC 3986\n        $chars_sub_delims = '!$&\\'()*+,;=';\n        $chars_gen_delims = ':/?#[]@';\n        $chars_pchar = $chars_sub_delims . ':@';\n\n        // validate scheme (MUST BE FIRST!)\n        if (!is_null($this->scheme) && is_null($this->host)) {\n            $def = $config->getDefinition('URI');\n            if ($def->defaultScheme === $this->scheme) {\n                $this->scheme = null;\n            }\n        }\n\n        // validate host\n        if (!is_null($this->host)) {\n            $host_def = new HTMLPurifier_AttrDef_URI_Host();\n            $this->host = $host_def->validate($this->host, $config, $context);\n            if ($this->host === false) $this->host = null;\n        }\n\n        // validate username\n        if (!is_null($this->userinfo)) {\n            $encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . ':');\n            $this->userinfo = $encoder->encode($this->userinfo);\n        }\n\n        // validate port\n        if (!is_null($this->port)) {\n            if ($this->port < 1 || $this->port > 65535) $this->port = null;\n        }\n\n        // validate path\n        $path_parts = array();\n        $segments_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/');\n        if (!is_null($this->host)) {\n            // path-abempty (hier and relative)\n            $this->path = $segments_encoder->encode($this->path);\n        } elseif ($this->path !== '' && $this->path[0] === '/') {\n            // path-absolute (hier and relative)\n            if (strlen($this->path) >= 2 && $this->path[1] === '/') {\n                // This shouldn't ever happen!\n                $this->path = '';\n            } else {\n                $this->path = $segments_encoder->encode($this->path);\n            }\n        } elseif (!is_null($this->scheme) && $this->path !== '') {\n            // path-rootless (hier)\n            // Short circuit evaluation means we don't need to check nz\n            $this->path = $segments_encoder->encode($this->path);\n        } elseif (is_null($this->scheme) && $this->path !== '') {\n            // path-noscheme (relative)\n            // (once again, not checking nz)\n            $segment_nc_encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . '@');\n            $c = strpos($this->path, '/');\n            if ($c !== false) {\n                $this->path =\n                    $segment_nc_encoder->encode(substr($this->path, 0, $c)) .\n                    $segments_encoder->encode(substr($this->path, $c));\n            } else {\n                $this->path = $segment_nc_encoder->encode($this->path);\n            }\n        } else {\n            // path-empty (hier and relative)\n            $this->path = ''; // just to be safe\n        }\n\n        // qf = query and fragment\n        $qf_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/?');\n\n        if (!is_null($this->query)) {\n            $this->query = $qf_encoder->encode($this->query);\n        }\n\n        if (!is_null($this->fragment)) {\n            $this->fragment = $qf_encoder->encode($this->fragment);\n        }\n\n        return true;\n\n    }\n\n    /**\n     * Convert URI back to string\n     * @return String URI appropriate for output\n     */\n    public function toString() {\n        // reconstruct authority\n        $authority = null;\n        if (!is_null($this->host)) {\n            $authority = '';\n            if(!is_null($this->userinfo)) $authority .= $this->userinfo . '@';\n            $authority .= $this->host;\n            if(!is_null($this->port))     $authority .= ':' . $this->port;\n        }\n\n        // reconstruct the result\n        $result = '';\n        if (!is_null($this->scheme))    $result .= $this->scheme . ':';\n        if (!is_null($authority))       $result .=  '//' . $authority;\n        $result .= $this->path;\n        if (!is_null($this->query))     $result .= '?' . $this->query;\n        if (!is_null($this->fragment))  $result .= '#' . $this->fragment;\n\n        return $result;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIDefinition.php",
    "content": "<?php\n\nclass HTMLPurifier_URIDefinition extends HTMLPurifier_Definition\n{\n\n    public $type = 'URI';\n    protected $filters = array();\n    protected $postFilters = array();\n    protected $registeredFilters = array();\n\n    /**\n     * HTMLPurifier_URI object of the base specified at %URI.Base\n     */\n    public $base;\n\n    /**\n     * String host to consider \"home\" base, derived off of $base\n     */\n    public $host;\n\n    /**\n     * Name of default scheme based on %URI.DefaultScheme and %URI.Base\n     */\n    public $defaultScheme;\n\n    public function __construct() {\n        $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternal());\n        $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternalResources());\n        $this->registerFilter(new HTMLPurifier_URIFilter_HostBlacklist());\n        $this->registerFilter(new HTMLPurifier_URIFilter_MakeAbsolute());\n        $this->registerFilter(new HTMLPurifier_URIFilter_Munge());\n    }\n\n    public function registerFilter($filter) {\n        $this->registeredFilters[$filter->name] = $filter;\n    }\n\n    public function addFilter($filter, $config) {\n        $r = $filter->prepare($config);\n        if ($r === false) return; // null is ok, for backwards compat\n        if ($filter->post) {\n            $this->postFilters[$filter->name] = $filter;\n        } else {\n            $this->filters[$filter->name] = $filter;\n        }\n    }\n\n    protected function doSetup($config) {\n        $this->setupMemberVariables($config);\n        $this->setupFilters($config);\n    }\n\n    protected function setupFilters($config) {\n        foreach ($this->registeredFilters as $name => $filter) {\n            $conf = $config->get('URI.' . $name);\n            if ($conf !== false && $conf !== null) {\n                $this->addFilter($filter, $config);\n            }\n        }\n        unset($this->registeredFilters);\n    }\n\n    protected function setupMemberVariables($config) {\n        $this->host = $config->get('URI.Host');\n        $base_uri = $config->get('URI.Base');\n        if (!is_null($base_uri)) {\n            $parser = new HTMLPurifier_URIParser();\n            $this->base = $parser->parse($base_uri);\n            $this->defaultScheme = $this->base->scheme;\n            if (is_null($this->host)) $this->host = $this->base->host;\n        }\n        if (is_null($this->defaultScheme)) $this->defaultScheme = $config->get('URI.DefaultScheme');\n    }\n\n    public function filter(&$uri, $config, $context) {\n        foreach ($this->filters as $name => $f) {\n            $result = $f->filter($uri, $config, $context);\n            if (!$result) return false;\n        }\n        return true;\n    }\n\n    public function postFilter(&$uri, $config, $context) {\n        foreach ($this->postFilters as $name => $f) {\n            $result = $f->filter($uri, $config, $context);\n            if (!$result) return false;\n        }\n        return true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIFilter/DisableExternal.php",
    "content": "<?php\n\nclass HTMLPurifier_URIFilter_DisableExternal extends HTMLPurifier_URIFilter\n{\n    public $name = 'DisableExternal';\n    protected $ourHostParts = false;\n    public function prepare($config) {\n        $our_host = $config->getDefinition('URI')->host;\n        if ($our_host !== null) $this->ourHostParts = array_reverse(explode('.', $our_host));\n    }\n    public function filter(&$uri, $config, $context) {\n        if (is_null($uri->host)) return true;\n        if ($this->ourHostParts === false) return false;\n        $host_parts = array_reverse(explode('.', $uri->host));\n        foreach ($this->ourHostParts as $i => $x) {\n            if (!isset($host_parts[$i])) return false;\n            if ($host_parts[$i] != $this->ourHostParts[$i]) return false;\n        }\n        return true;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIFilter/DisableExternalResources.php",
    "content": "<?php\n\nclass HTMLPurifier_URIFilter_DisableExternalResources extends HTMLPurifier_URIFilter_DisableExternal\n{\n    public $name = 'DisableExternalResources';\n    public function filter(&$uri, $config, $context) {\n        if (!$context->get('EmbeddedURI', true)) return true;\n        return parent::filter($uri, $config, $context);\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIFilter/HostBlacklist.php",
    "content": "<?php\n\nclass HTMLPurifier_URIFilter_HostBlacklist extends HTMLPurifier_URIFilter\n{\n    public $name = 'HostBlacklist';\n    protected $blacklist = array();\n    public function prepare($config) {\n        $this->blacklist = $config->get('URI.HostBlacklist');\n        return true;\n    }\n    public function filter(&$uri, $config, $context) {\n        foreach($this->blacklist as $blacklisted_host_fragment) {\n            if (strpos($uri->host, $blacklisted_host_fragment) !== false) {\n                return false;\n            }\n        }\n        return true;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIFilter/MakeAbsolute.php",
    "content": "<?php\n\n// does not support network paths\n\nclass HTMLPurifier_URIFilter_MakeAbsolute extends HTMLPurifier_URIFilter\n{\n    public $name = 'MakeAbsolute';\n    protected $base;\n    protected $basePathStack = array();\n    public function prepare($config) {\n        $def = $config->getDefinition('URI');\n        $this->base = $def->base;\n        if (is_null($this->base)) {\n            trigger_error('URI.MakeAbsolute is being ignored due to lack of value for URI.Base configuration', E_USER_WARNING);\n            return false;\n        }\n        $this->base->fragment = null; // fragment is invalid for base URI\n        $stack = explode('/', $this->base->path);\n        array_pop($stack); // discard last segment\n        $stack = $this->_collapseStack($stack); // do pre-parsing\n        $this->basePathStack = $stack;\n        return true;\n    }\n    public function filter(&$uri, $config, $context) {\n        if (is_null($this->base)) return true; // abort early\n        if (\n            $uri->path === '' && is_null($uri->scheme) &&\n            is_null($uri->host) && is_null($uri->query) && is_null($uri->fragment)\n        ) {\n            // reference to current document\n            $uri = clone $this->base;\n            return true;\n        }\n        if (!is_null($uri->scheme)) {\n            // absolute URI already: don't change\n            if (!is_null($uri->host)) return true;\n            $scheme_obj = $uri->getSchemeObj($config, $context);\n            if (!$scheme_obj) {\n                // scheme not recognized\n                return false;\n            }\n            if (!$scheme_obj->hierarchical) {\n                // non-hierarchal URI with explicit scheme, don't change\n                return true;\n            }\n            // special case: had a scheme but always is hierarchical and had no authority\n        }\n        if (!is_null($uri->host)) {\n            // network path, don't bother\n            return true;\n        }\n        if ($uri->path === '') {\n            $uri->path = $this->base->path;\n        } elseif ($uri->path[0] !== '/') {\n            // relative path, needs more complicated processing\n            $stack = explode('/', $uri->path);\n            $new_stack = array_merge($this->basePathStack, $stack);\n            if ($new_stack[0] !== '' && !is_null($this->base->host)) {\n                array_unshift($new_stack, '');\n            }\n            $new_stack = $this->_collapseStack($new_stack);\n            $uri->path = implode('/', $new_stack);\n        } else {\n            // absolute path, but still we should collapse\n            $uri->path = implode('/', $this->_collapseStack(explode('/', $uri->path)));\n        }\n        // re-combine\n        $uri->scheme = $this->base->scheme;\n        if (is_null($uri->userinfo)) $uri->userinfo = $this->base->userinfo;\n        if (is_null($uri->host))     $uri->host     = $this->base->host;\n        if (is_null($uri->port))     $uri->port     = $this->base->port;\n        return true;\n    }\n\n    /**\n     * Resolve dots and double-dots in a path stack\n     */\n    private function _collapseStack($stack) {\n        $result = array();\n        $is_folder = false;\n        for ($i = 0; isset($stack[$i]); $i++) {\n            $is_folder = false;\n            // absorb an internally duplicated slash\n            if ($stack[$i] == '' && $i && isset($stack[$i+1])) continue;\n            if ($stack[$i] == '..') {\n                if (!empty($result)) {\n                    $segment = array_pop($result);\n                    if ($segment === '' && empty($result)) {\n                        // error case: attempted to back out too far:\n                        // restore the leading slash\n                        $result[] = '';\n                    } elseif ($segment === '..') {\n                        $result[] = '..'; // cannot remove .. with ..\n                    }\n                } else {\n                    // relative path, preserve the double-dots\n                    $result[] = '..';\n                }\n                $is_folder = true;\n                continue;\n            }\n            if ($stack[$i] == '.') {\n                // silently absorb\n                $is_folder = true;\n                continue;\n            }\n            $result[] = $stack[$i];\n        }\n        if ($is_folder) $result[] = '';\n        return $result;\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIFilter/Munge.php",
    "content": "<?php\n\nclass HTMLPurifier_URIFilter_Munge extends HTMLPurifier_URIFilter\n{\n    public $name = 'Munge';\n    public $post = true;\n    private $target, $parser, $doEmbed, $secretKey;\n\n    protected $replace = array();\n\n    public function prepare($config) {\n        $this->target    = $config->get('URI.' . $this->name);\n        $this->parser    = new HTMLPurifier_URIParser();\n        $this->doEmbed   = $config->get('URI.MungeResources');\n        $this->secretKey = $config->get('URI.MungeSecretKey');\n        return true;\n    }\n    public function filter(&$uri, $config, $context) {\n        if ($context->get('EmbeddedURI', true) && !$this->doEmbed) return true;\n\n        $scheme_obj = $uri->getSchemeObj($config, $context);\n        if (!$scheme_obj) return true; // ignore unknown schemes, maybe another postfilter did it\n        if (is_null($uri->host) || empty($scheme_obj->browsable)) {\n            return true;\n        }\n        // don't redirect if target host is our host\n        if ($uri->host === $config->getDefinition('URI')->host) {\n            return true;\n        }\n\n        $this->makeReplace($uri, $config, $context);\n        $this->replace = array_map('rawurlencode', $this->replace);\n\n        $new_uri = strtr($this->target, $this->replace);\n        $new_uri = $this->parser->parse($new_uri);\n        // don't redirect if the target host is the same as the\n        // starting host\n        if ($uri->host === $new_uri->host) return true;\n        $uri = $new_uri; // overwrite\n        return true;\n    }\n\n    protected function makeReplace($uri, $config, $context) {\n        $string = $uri->toString();\n        // always available\n        $this->replace['%s'] = $string;\n        $this->replace['%r'] = $context->get('EmbeddedURI', true);\n        $token = $context->get('CurrentToken', true);\n        $this->replace['%n'] = $token ? $token->name : null;\n        $this->replace['%m'] = $context->get('CurrentAttr', true);\n        $this->replace['%p'] = $context->get('CurrentCSSProperty', true);\n        // not always available\n        if ($this->secretKey) $this->replace['%t'] = sha1($this->secretKey . ':' . $string);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIFilter.php",
    "content": "<?php\n\n/**\n * Chainable filters for custom URI processing.\n *\n * These filters can perform custom actions on a URI filter object,\n * including transformation or blacklisting.\n *\n * @warning This filter is called before scheme object validation occurs.\n *          Make sure, if you require a specific scheme object, you\n *          you check that it exists. This allows filters to convert\n *          proprietary URI schemes into regular ones.\n */\nabstract class HTMLPurifier_URIFilter\n{\n\n    /**\n     * Unique identifier of filter\n     */\n    public $name;\n\n    /**\n     * True if this filter should be run after scheme validation.\n     */\n    public $post = false;\n\n    /**\n     * Performs initialization for the filter\n     */\n    public function prepare($config) {return true;}\n\n    /**\n     * Filter a URI object\n     * @param $uri Reference to URI object variable\n     * @param $config Instance of HTMLPurifier_Config\n     * @param $context Instance of HTMLPurifier_Context\n     * @return bool Whether or not to continue processing: false indicates\n     *         URL is no good, true indicates continue processing. Note that\n     *         all changes are committed directly on the URI object\n     */\n    abstract public function filter(&$uri, $config, $context);\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIParser.php",
    "content": "<?php\n\n/**\n * Parses a URI into the components and fragment identifier as specified\n * by RFC 3986.\n */\nclass HTMLPurifier_URIParser\n{\n\n    /**\n     * Instance of HTMLPurifier_PercentEncoder to do normalization with.\n     */\n    protected $percentEncoder;\n\n    public function __construct() {\n        $this->percentEncoder = new HTMLPurifier_PercentEncoder();\n    }\n\n    /**\n     * Parses a URI.\n     * @param $uri string URI to parse\n     * @return HTMLPurifier_URI representation of URI. This representation has\n     *         not been validated yet and may not conform to RFC.\n     */\n    public function parse($uri) {\n\n        $uri = $this->percentEncoder->normalize($uri);\n\n        // Regexp is as per Appendix B.\n        // Note that [\"<>] are an addition to the RFC's recommended\n        // characters, because they represent external delimeters.\n        $r_URI = '!'.\n            '(([^:/?#\"<>]+):)?'. // 2. Scheme\n            '(//([^/?#\"<>]*))?'. // 4. Authority\n            '([^?#\"<>]*)'.       // 5. Path\n            '(\\?([^#\"<>]*))?'.   // 7. Query\n            '(#([^\"<>]*))?'.     // 8. Fragment\n            '!';\n\n        $matches = array();\n        $result = preg_match($r_URI, $uri, $matches);\n\n        if (!$result) return false; // *really* invalid URI\n\n        // seperate out parts\n        $scheme     = !empty($matches[1]) ? $matches[2] : null;\n        $authority  = !empty($matches[3]) ? $matches[4] : null;\n        $path       = $matches[5]; // always present, can be empty\n        $query      = !empty($matches[6]) ? $matches[7] : null;\n        $fragment   = !empty($matches[8]) ? $matches[9] : null;\n\n        // further parse authority\n        if ($authority !== null) {\n            $r_authority = \"/^((.+?)@)?(\\[[^\\]]+\\]|[^:]*)(:(\\d*))?/\";\n            $matches = array();\n            preg_match($r_authority, $authority, $matches);\n            $userinfo   = !empty($matches[1]) ? $matches[2] : null;\n            $host       = !empty($matches[3]) ? $matches[3] : '';\n            $port       = !empty($matches[4]) ? (int) $matches[5] : null;\n        } else {\n            $port = $host = $userinfo = null;\n        }\n\n        return new HTMLPurifier_URI(\n            $scheme, $userinfo, $host, $port, $path, $query, $fragment);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIScheme/ftp.php",
    "content": "<?php\n\n/**\n * Validates ftp (File Transfer Protocol) URIs as defined by generic RFC 1738.\n */\nclass HTMLPurifier_URIScheme_ftp extends HTMLPurifier_URIScheme {\n\n    public $default_port = 21;\n    public $browsable = true; // usually\n    public $hierarchical = true;\n\n    public function validate(&$uri, $config, $context) {\n        parent::validate($uri, $config, $context);\n        $uri->query    = null;\n\n        // typecode check\n        $semicolon_pos = strrpos($uri->path, ';'); // reverse\n        if ($semicolon_pos !== false) {\n            $type = substr($uri->path, $semicolon_pos + 1); // no semicolon\n            $uri->path = substr($uri->path, 0, $semicolon_pos);\n            $type_ret = '';\n            if (strpos($type, '=') !== false) {\n                // figure out whether or not the declaration is correct\n                list($key, $typecode) = explode('=', $type, 2);\n                if ($key !== 'type') {\n                    // invalid key, tack it back on encoded\n                    $uri->path .= '%3B' . $type;\n                } elseif ($typecode === 'a' || $typecode === 'i' || $typecode === 'd') {\n                    $type_ret = \";type=$typecode\";\n                }\n            } else {\n                $uri->path .= '%3B' . $type;\n            }\n            $uri->path = str_replace(';', '%3B', $uri->path);\n            $uri->path .= $type_ret;\n        }\n\n        return true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIScheme/http.php",
    "content": "<?php\n\n/**\n * Validates http (HyperText Transfer Protocol) as defined by RFC 2616\n */\nclass HTMLPurifier_URIScheme_http extends HTMLPurifier_URIScheme {\n\n    public $default_port = 80;\n    public $browsable = true;\n    public $hierarchical = true;\n\n    public function validate(&$uri, $config, $context) {\n        parent::validate($uri, $config, $context);\n        $uri->userinfo = null;\n        return true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIScheme/https.php",
    "content": "<?php\n\n/**\n * Validates https (Secure HTTP) according to http scheme.\n */\nclass HTMLPurifier_URIScheme_https extends HTMLPurifier_URIScheme_http {\n\n    public $default_port = 443;\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIScheme/mailto.php",
    "content": "<?php\n\n// VERY RELAXED! Shouldn't cause problems, not even Firefox checks if the\n// email is valid, but be careful!\n\n/**\n * Validates mailto (for E-mail) according to RFC 2368\n * @todo Validate the email address\n * @todo Filter allowed query parameters\n */\n\nclass HTMLPurifier_URIScheme_mailto extends HTMLPurifier_URIScheme {\n\n    public $browsable = false;\n\n    public function validate(&$uri, $config, $context) {\n        parent::validate($uri, $config, $context);\n        $uri->userinfo = null;\n        $uri->host     = null;\n        $uri->port     = null;\n        // we need to validate path against RFC 2368's addr-spec\n        return true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIScheme/news.php",
    "content": "<?php\n\n/**\n * Validates news (Usenet) as defined by generic RFC 1738\n */\nclass HTMLPurifier_URIScheme_news extends HTMLPurifier_URIScheme {\n\n    public $browsable = false;\n\n    public function validate(&$uri, $config, $context) {\n        parent::validate($uri, $config, $context);\n        $uri->userinfo = null;\n        $uri->host     = null;\n        $uri->port     = null;\n        $uri->query    = null;\n        // typecode check needed on path\n        return true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIScheme/nntp.php",
    "content": "<?php\n\n/**\n * Validates nntp (Network News Transfer Protocol) as defined by generic RFC 1738\n */\nclass HTMLPurifier_URIScheme_nntp extends HTMLPurifier_URIScheme {\n\n    public $default_port = 119;\n    public $browsable = false;\n\n    public function validate(&$uri, $config, $context) {\n        parent::validate($uri, $config, $context);\n        $uri->userinfo = null;\n        $uri->query    = null;\n        return true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URIScheme.php",
    "content": "<?php\n\n/**\n * Validator for the components of a URI for a specific scheme\n */\nclass HTMLPurifier_URIScheme\n{\n\n    /**\n     * Scheme's default port (integer)\n     */\n    public $default_port = null;\n\n    /**\n     * Whether or not URIs of this schem are locatable by a browser\n     * http and ftp are accessible, while mailto and news are not.\n     */\n    public $browsable = false;\n\n    /**\n     * Whether or not the URI always uses <hier_part>, resolves edge cases\n     * with making relative URIs absolute\n     */\n    public $hierarchical = false;\n\n    /**\n     * Validates the components of a URI\n     * @note This implementation should be called by children if they define\n     *       a default port, as it does port processing.\n     * @param $uri Instance of HTMLPurifier_URI\n     * @param $config HTMLPurifier_Config object\n     * @param $context HTMLPurifier_Context object\n     * @return Bool success or failure\n     */\n    public function validate(&$uri, $config, $context) {\n        if ($this->default_port == $uri->port) $uri->port = null;\n        return true;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/URISchemeRegistry.php",
    "content": "<?php\n\n/**\n * Registry for retrieving specific URI scheme validator objects.\n */\nclass HTMLPurifier_URISchemeRegistry\n{\n\n    /**\n     * Retrieve sole instance of the registry.\n     * @param $prototype Optional prototype to overload sole instance with,\n     *                   or bool true to reset to default registry.\n     * @note Pass a registry object $prototype with a compatible interface and\n     *       the function will copy it and return it all further times.\n     */\n    public static function instance($prototype = null) {\n        static $instance = null;\n        if ($prototype !== null) {\n            $instance = $prototype;\n        } elseif ($instance === null || $prototype == true) {\n            $instance = new HTMLPurifier_URISchemeRegistry();\n        }\n        return $instance;\n    }\n\n    /**\n     * Cache of retrieved schemes.\n     */\n    protected $schemes = array();\n\n    /**\n     * Retrieves a scheme validator object\n     * @param $scheme String scheme name like http or mailto\n     * @param $config HTMLPurifier_Config object\n     * @param $config HTMLPurifier_Context object\n     */\n    public function getScheme($scheme, $config, $context) {\n        if (!$config) $config = HTMLPurifier_Config::createDefault();\n\n        // important, otherwise attacker could include arbitrary file\n        $allowed_schemes = $config->get('URI.AllowedSchemes');\n        if (!$config->get('URI.OverrideAllowedSchemes') &&\n            !isset($allowed_schemes[$scheme])\n        ) {\n            return;\n        }\n\n        if (isset($this->schemes[$scheme])) return $this->schemes[$scheme];\n        if (!isset($allowed_schemes[$scheme])) return;\n\n        $class = 'HTMLPurifier_URIScheme_' . $scheme;\n        if (!class_exists($class)) return;\n        $this->schemes[$scheme] = new $class();\n        return $this->schemes[$scheme];\n    }\n\n    /**\n     * Registers a custom scheme to the cache, bypassing reflection.\n     * @param $scheme Scheme name\n     * @param $scheme_obj HTMLPurifier_URIScheme object\n     */\n    public function register($scheme, $scheme_obj) {\n        $this->schemes[$scheme] = $scheme_obj;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/UnitConverter.php",
    "content": "<?php\n\n/**\n * Class for converting between different unit-lengths as specified by\n * CSS.\n */\nclass HTMLPurifier_UnitConverter\n{\n\n    const ENGLISH = 1;\n    const METRIC = 2;\n    const DIGITAL = 3;\n\n    /**\n     * Units information array. Units are grouped into measuring systems\n     * (English, Metric), and are assigned an integer representing\n     * the conversion factor between that unit and the smallest unit in\n     * the system. Numeric indexes are actually magical constants that\n     * encode conversion data from one system to the next, with a O(n^2)\n     * constraint on memory (this is generally not a problem, since\n     * the number of measuring systems is small.)\n     */\n    protected static $units = array(\n        self::ENGLISH => array(\n            'px' => 3, // This is as per CSS 2.1 and Firefox. Your mileage may vary\n            'pt' => 4,\n            'pc' => 48,\n            'in' => 288,\n            self::METRIC => array('pt', '0.352777778', 'mm'),\n        ),\n        self::METRIC => array(\n            'mm' => 1,\n            'cm' => 10,\n            self::ENGLISH => array('mm', '2.83464567', 'pt'),\n        ),\n    );\n\n    /**\n     * Minimum bcmath precision for output.\n     */\n    protected $outputPrecision;\n\n    /**\n     * Bcmath precision for internal calculations.\n     */\n    protected $internalPrecision;\n\n    /**\n     * Whether or not BCMath is available\n     */\n    private $bcmath;\n\n    public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false) {\n        $this->outputPrecision = $output_precision;\n        $this->internalPrecision = $internal_precision;\n        $this->bcmath = !$force_no_bcmath && function_exists('bcmul');\n    }\n\n    /**\n     * Converts a length object of one unit into another unit.\n     * @param HTMLPurifier_Length $length\n     *      Instance of HTMLPurifier_Length to convert. You must validate()\n     *      it before passing it here!\n     * @param string $to_unit\n     *      Unit to convert to.\n     * @note\n     *      About precision: This conversion function pays very special\n     *      attention to the incoming precision of values and attempts\n     *      to maintain a number of significant figure. Results are\n     *      fairly accurate up to nine digits. Some caveats:\n     *          - If a number is zero-padded as a result of this significant\n     *            figure tracking, the zeroes will be eliminated.\n     *          - If a number contains less than four sigfigs ($outputPrecision)\n     *            and this causes some decimals to be excluded, those\n     *            decimals will be added on.\n     */\n    public function convert($length, $to_unit) {\n\n        if (!$length->isValid()) return false;\n\n        $n    = $length->getN();\n        $unit = $length->getUnit();\n\n        if ($n === '0' || $unit === false) {\n            return new HTMLPurifier_Length('0', false);\n        }\n\n        $state = $dest_state = false;\n        foreach (self::$units as $k => $x) {\n            if (isset($x[$unit])) $state = $k;\n            if (isset($x[$to_unit])) $dest_state = $k;\n        }\n        if (!$state || !$dest_state) return false;\n\n        // Some calculations about the initial precision of the number;\n        // this will be useful when we need to do final rounding.\n        $sigfigs = $this->getSigFigs($n);\n        if ($sigfigs < $this->outputPrecision) $sigfigs = $this->outputPrecision;\n\n        // BCMath's internal precision deals only with decimals. Use\n        // our default if the initial number has no decimals, or increase\n        // it by how ever many decimals, thus, the number of guard digits\n        // will always be greater than or equal to internalPrecision.\n        $log = (int) floor(log(abs($n), 10));\n        $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision\n\n        for ($i = 0; $i < 2; $i++) {\n\n            // Determine what unit IN THIS SYSTEM we need to convert to\n            if ($dest_state === $state) {\n                // Simple conversion\n                $dest_unit = $to_unit;\n            } else {\n                // Convert to the smallest unit, pending a system shift\n                $dest_unit = self::$units[$state][$dest_state][0];\n            }\n\n            // Do the conversion if necessary\n            if ($dest_unit !== $unit) {\n                $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp);\n                $n = $this->mul($n, $factor, $cp);\n                $unit = $dest_unit;\n            }\n\n            // Output was zero, so bail out early. Shouldn't ever happen.\n            if ($n === '') {\n                $n = '0';\n                $unit = $to_unit;\n                break;\n            }\n\n            // It was a simple conversion, so bail out\n            if ($dest_state === $state) {\n                break;\n            }\n\n            if ($i !== 0) {\n                // Conversion failed! Apparently, the system we forwarded\n                // to didn't have this unit. This should never happen!\n                return false;\n            }\n\n            // Pre-condition: $i == 0\n\n            // Perform conversion to next system of units\n            $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp);\n            $unit = self::$units[$state][$dest_state][2];\n            $state = $dest_state;\n\n            // One more loop around to convert the unit in the new system.\n\n        }\n\n        // Post-condition: $unit == $to_unit\n        if ($unit !== $to_unit) return false;\n\n        // Useful for debugging:\n        //echo \"<pre>n\";\n        //echo \"$n\\nsigfigs = $sigfigs\\nnew_log = $new_log\\nlog = $log\\nrp = $rp\\n</pre>\\n\";\n\n        $n = $this->round($n, $sigfigs);\n        if (strpos($n, '.') !== false) $n = rtrim($n, '0');\n        $n = rtrim($n, '.');\n\n        return new HTMLPurifier_Length($n, $unit);\n    }\n\n    /**\n     * Returns the number of significant figures in a string number.\n     * @param string $n Decimal number\n     * @return int number of sigfigs\n     */\n    public function getSigFigs($n) {\n        $n = ltrim($n, '0+-');\n        $dp = strpos($n, '.'); // decimal position\n        if ($dp === false) {\n            $sigfigs = strlen(rtrim($n, '0'));\n        } else {\n            $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character\n            if ($dp !== 0) $sigfigs--;\n        }\n        return $sigfigs;\n    }\n\n    /**\n     * Adds two numbers, using arbitrary precision when available.\n     */\n    private function add($s1, $s2, $scale) {\n        if ($this->bcmath) return bcadd($s1, $s2, $scale);\n        else return $this->scale($s1 + $s2, $scale);\n    }\n\n    /**\n     * Multiples two numbers, using arbitrary precision when available.\n     */\n    private function mul($s1, $s2, $scale) {\n        if ($this->bcmath) return bcmul($s1, $s2, $scale);\n        else return $this->scale($s1 * $s2, $scale);\n    }\n\n    /**\n     * Divides two numbers, using arbitrary precision when available.\n     */\n    private function div($s1, $s2, $scale) {\n        if ($this->bcmath) return bcdiv($s1, $s2, $scale);\n        else return $this->scale($s1 / $s2, $scale);\n    }\n\n    /**\n     * Rounds a number according to the number of sigfigs it should have,\n     * using arbitrary precision when available.\n     */\n    private function round($n, $sigfigs) {\n        $new_log = (int) floor(log(abs($n), 10)); // Number of digits left of decimal - 1\n        $rp = $sigfigs - $new_log - 1; // Number of decimal places needed\n        $neg = $n < 0 ? '-' : ''; // Negative sign\n        if ($this->bcmath) {\n            if ($rp >= 0) {\n                $n = bcadd($n, $neg . '0.' .  str_repeat('0', $rp) . '5', $rp + 1);\n                $n = bcdiv($n, '1', $rp);\n            } else {\n                // This algorithm partially depends on the standardized\n                // form of numbers that comes out of bcmath.\n                $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0);\n                $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1);\n            }\n            return $n;\n        } else {\n            return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1);\n        }\n    }\n\n    /**\n     * Scales a float to $scale digits right of decimal point, like BCMath.\n     */\n    private function scale($r, $scale) {\n        if ($scale < 0) {\n            // The f sprintf type doesn't support negative numbers, so we\n            // need to cludge things manually. First get the string.\n            $r = sprintf('%.0f', (float) $r);\n            // Due to floating point precision loss, $r will more than likely\n            // look something like 4652999999999.9234. We grab one more digit\n            // than we need to precise from $r and then use that to round\n            // appropriately.\n            $precise = (string) round(substr($r, 0, strlen($r) + $scale), -1);\n            // Now we return it, truncating the zero that was rounded off.\n            return substr($precise, 0, -1) . str_repeat('0', -$scale + 1);\n        }\n        return sprintf('%.' . $scale . 'f', (float) $r);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/VarParser/Flexible.php",
    "content": "<?php\n\n/**\n * Performs safe variable parsing based on types which can be used by\n * users. This may not be able to represent all possible data inputs,\n * however.\n */\nclass HTMLPurifier_VarParser_Flexible extends HTMLPurifier_VarParser\n{\n\n    protected function parseImplementation($var, $type, $allow_null) {\n        if ($allow_null && $var === null) return null;\n        switch ($type) {\n            // Note: if code \"breaks\" from the switch, it triggers a generic\n            // exception to be thrown. Specific errors can be specifically\n            // done here.\n            case self::MIXED :\n            case self::ISTRING :\n            case self::STRING :\n            case self::TEXT :\n            case self::ITEXT :\n                return $var;\n            case self::INT :\n                if (is_string($var) && ctype_digit($var)) $var = (int) $var;\n                return $var;\n            case self::FLOAT :\n                if ((is_string($var) && is_numeric($var)) || is_int($var)) $var = (float) $var;\n                return $var;\n            case self::BOOL :\n                if (is_int($var) && ($var === 0 || $var === 1)) {\n                    $var = (bool) $var;\n                } elseif (is_string($var)) {\n                    if ($var == 'on' || $var == 'true' || $var == '1') {\n                        $var = true;\n                    } elseif ($var == 'off' || $var == 'false' || $var == '0') {\n                        $var = false;\n                    } else {\n                        throw new HTMLPurifier_VarParserException(\"Unrecognized value '$var' for $type\");\n                    }\n                }\n                return $var;\n            case self::ALIST :\n            case self::HASH :\n            case self::LOOKUP :\n                if (is_string($var)) {\n                    // special case: technically, this is an array with\n                    // a single empty string item, but having an empty\n                    // array is more intuitive\n                    if ($var == '') return array();\n                    if (strpos($var, \"\\n\") === false && strpos($var, \"\\r\") === false) {\n                        // simplistic string to array method that only works\n                        // for simple lists of tag names or alphanumeric characters\n                        $var = explode(',',$var);\n                    } else {\n                        $var = preg_split('/(,|[\\n\\r]+)/', $var);\n                    }\n                    // remove spaces\n                    foreach ($var as $i => $j) $var[$i] = trim($j);\n                    if ($type === self::HASH) {\n                        // key:value,key2:value2\n                        $nvar = array();\n                        foreach ($var as $keypair) {\n                            $c = explode(':', $keypair, 2);\n                            if (!isset($c[1])) continue;\n                            $nvar[$c[0]] = $c[1];\n                        }\n                        $var = $nvar;\n                    }\n                }\n                if (!is_array($var)) break;\n                $keys = array_keys($var);\n                if ($keys === array_keys($keys)) {\n                    if ($type == self::ALIST) return $var;\n                    elseif ($type == self::LOOKUP) {\n                        $new = array();\n                        foreach ($var as $key) {\n                            $new[$key] = true;\n                        }\n                        return $new;\n                    } else break;\n                }\n                if ($type === self::LOOKUP) {\n                    foreach ($var as $key => $value) {\n                        $var[$key] = true;\n                    }\n                }\n                return $var;\n            default:\n                $this->errorInconsistent(__CLASS__, $type);\n        }\n        $this->errorGeneric($var, $type);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/VarParser/Native.php",
    "content": "<?php\n\n/**\n * This variable parser uses PHP's internal code engine. Because it does\n * this, it can represent all inputs; however, it is dangerous and cannot\n * be used by users.\n */\nclass HTMLPurifier_VarParser_Native extends HTMLPurifier_VarParser\n{\n\n    protected function parseImplementation($var, $type, $allow_null) {\n        return $this->evalExpression($var);\n    }\n\n    protected function evalExpression($expr) {\n        $var = null;\n        $result = eval(\"\\$var = $expr;\");\n        if ($result === false) {\n            throw new HTMLPurifier_VarParserException(\"Fatal error in evaluated code\");\n        }\n        return $var;\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/VarParser.php",
    "content": "<?php\n\n/**\n * Parses string representations into their corresponding native PHP\n * variable type. The base implementation does a simple type-check.\n */\nclass HTMLPurifier_VarParser\n{\n\n    const STRING    = 1;\n    const ISTRING   = 2;\n    const TEXT      = 3;\n    const ITEXT     = 4;\n    const INT       = 5;\n    const FLOAT     = 6;\n    const BOOL      = 7;\n    const LOOKUP    = 8;\n    const ALIST     = 9;\n    const HASH      = 10;\n    const MIXED     = 11;\n\n    /**\n     * Lookup table of allowed types. Mainly for backwards compatibility, but\n     * also convenient for transforming string type names to the integer constants.\n     */\n    static public $types = array(\n        'string'    => self::STRING,\n        'istring'   => self::ISTRING,\n        'text'      => self::TEXT,\n        'itext'     => self::ITEXT,\n        'int'       => self::INT,\n        'float'     => self::FLOAT,\n        'bool'      => self::BOOL,\n        'lookup'    => self::LOOKUP,\n        'list'      => self::ALIST,\n        'hash'      => self::HASH,\n        'mixed'     => self::MIXED\n    );\n\n    /**\n     * Lookup table of types that are string, and can have aliases or\n     * allowed value lists.\n     */\n    static public $stringTypes = array(\n        self::STRING    => true,\n        self::ISTRING   => true,\n        self::TEXT      => true,\n        self::ITEXT     => true,\n    );\n\n    /**\n     * Validate a variable according to type. Throws\n     * HTMLPurifier_VarParserException if invalid.\n     * It may return NULL as a valid type if $allow_null is true.\n     *\n     * @param $var Variable to validate\n     * @param $type Type of variable, see HTMLPurifier_VarParser->types\n     * @param $allow_null Whether or not to permit null as a value\n     * @return Validated and type-coerced variable\n     */\n    final public function parse($var, $type, $allow_null = false) {\n        if (is_string($type)) {\n            if (!isset(HTMLPurifier_VarParser::$types[$type])) {\n                throw new HTMLPurifier_VarParserException(\"Invalid type '$type'\");\n            } else {\n                $type = HTMLPurifier_VarParser::$types[$type];\n            }\n        }\n        $var = $this->parseImplementation($var, $type, $allow_null);\n        if ($allow_null && $var === null) return null;\n        // These are basic checks, to make sure nothing horribly wrong\n        // happened in our implementations.\n        switch ($type) {\n            case (self::STRING):\n            case (self::ISTRING):\n            case (self::TEXT):\n            case (self::ITEXT):\n                if (!is_string($var)) break;\n                if ($type == self::ISTRING || $type == self::ITEXT) $var = strtolower($var);\n                return $var;\n            case (self::INT):\n                if (!is_int($var)) break;\n                return $var;\n            case (self::FLOAT):\n                if (!is_float($var)) break;\n                return $var;\n            case (self::BOOL):\n                if (!is_bool($var)) break;\n                return $var;\n            case (self::LOOKUP):\n            case (self::ALIST):\n            case (self::HASH):\n                if (!is_array($var)) break;\n                if ($type === self::LOOKUP) {\n                    foreach ($var as $k) if ($k !== true) $this->error('Lookup table contains value other than true');\n                } elseif ($type === self::ALIST) {\n                    $keys = array_keys($var);\n                    if (array_keys($keys) !== $keys) $this->error('Indices for list are not uniform');\n                }\n                return $var;\n            case (self::MIXED):\n                return $var;\n            default:\n                $this->errorInconsistent(get_class($this), $type);\n        }\n        $this->errorGeneric($var, $type);\n    }\n\n    /**\n     * Actually implements the parsing. Base implementation is to not\n     * do anything to $var. Subclasses should overload this!\n     */\n    protected function parseImplementation($var, $type, $allow_null) {\n        return $var;\n    }\n\n    /**\n     * Throws an exception.\n     */\n    protected function error($msg) {\n        throw new HTMLPurifier_VarParserException($msg);\n    }\n\n    /**\n     * Throws an inconsistency exception.\n     * @note This should not ever be called. It would be called if we\n     *       extend the allowed values of HTMLPurifier_VarParser without\n     *       updating subclasses.\n     */\n    protected function errorInconsistent($class, $type) {\n        throw new HTMLPurifier_Exception(\"Inconsistency in $class: \".HTMLPurifier_VarParser::getTypeName($type).\" not implemented\");\n    }\n\n    /**\n     * Generic error for if a type didn't work.\n     */\n    protected function errorGeneric($var, $type) {\n        $vtype = gettype($var);\n        $this->error(\"Expected type \".HTMLPurifier_VarParser::getTypeName($type).\", got $vtype\");\n    }\n\n    static public function getTypeName($type) {\n        static $lookup;\n        if (!$lookup) {\n            // Lazy load the alternative lookup table\n            $lookup = array_flip(HTMLPurifier_VarParser::$types);\n        }\n        if (!isset($lookup[$type])) return 'unknown';\n        return $lookup[$type];\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier/VarParserException.php",
    "content": "<?php\n\n/**\n * Exception type for HTMLPurifier_VarParser\n */\nclass HTMLPurifier_VarParserException extends HTMLPurifier_Exception\n{\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier.auto.php",
    "content": "<?php\n\n/**\n * This is a stub include that automatically configures the include path.\n */\n\nset_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path() );\nrequire_once 'HTMLPurifier/Bootstrap.php';\nrequire_once 'HTMLPurifier.autoload.php';\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier.autoload.php",
    "content": "<?php\n\n/**\n * @file\n * Convenience file that registers autoload handler for HTML Purifier.\n */\n\nif (function_exists('spl_autoload_register') && function_exists('spl_autoload_unregister')) {\n    // We need unregister for our pre-registering functionality\n    HTMLPurifier_Bootstrap::registerAutoload();\n    if (function_exists('__autoload')) {\n        // Be polite and ensure that userland autoload gets retained\n        spl_autoload_register('__autoload');\n    }\n} elseif (!function_exists('__autoload')) {\n    function __autoload($class) {\n        return HTMLPurifier_Bootstrap::autoload($class);\n    }\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier.func.php",
    "content": "<?php\n\n/**\n * @file\n * Defines a function wrapper for HTML Purifier for quick use.\n * @note ''HTMLPurifier()'' is NOT the same as ''new HTMLPurifier()''\n */\n\n/**\n * Purify HTML.\n * @param $html String HTML to purify\n * @param $config Configuration to use, can be any value accepted by\n *        HTMLPurifier_Config::create()\n */\nfunction HTMLPurifier($html, $config = null) {\n    static $purifier = false;\n    if (!$purifier) {\n        $purifier = new HTMLPurifier();\n    }\n    return $purifier->purify($html, $config);\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier.includes.php",
    "content": "<?php\n\n/**\n * @file\n * This file was auto-generated by generate-includes.php and includes all of\n * the core files required by HTML Purifier. Use this if performance is a\n * primary concern and you are using an opcode cache. PLEASE DO NOT EDIT THIS\n * FILE, changes will be overwritten the next time the script is run.\n *\n * @version 4.0.0\n *\n * @warning\n *      You must *not* include any other HTML Purifier files before this file,\n *      because 'require' not 'require_once' is used.\n *\n * @warning\n *      This file requires that the include path contains the HTML Purifier\n *      library directory; this is not auto-set.\n */\n\nrequire 'HTMLPurifier.php';\nrequire 'HTMLPurifier/AttrCollections.php';\nrequire 'HTMLPurifier/AttrDef.php';\nrequire 'HTMLPurifier/AttrTransform.php';\nrequire 'HTMLPurifier/AttrTypes.php';\nrequire 'HTMLPurifier/AttrValidator.php';\nrequire 'HTMLPurifier/Bootstrap.php';\nrequire 'HTMLPurifier/Definition.php';\nrequire 'HTMLPurifier/CSSDefinition.php';\nrequire 'HTMLPurifier/ChildDef.php';\nrequire 'HTMLPurifier/Config.php';\nrequire 'HTMLPurifier/ConfigSchema.php';\nrequire 'HTMLPurifier/ContentSets.php';\nrequire 'HTMLPurifier/Context.php';\nrequire 'HTMLPurifier/DefinitionCache.php';\nrequire 'HTMLPurifier/DefinitionCacheFactory.php';\nrequire 'HTMLPurifier/Doctype.php';\nrequire 'HTMLPurifier/DoctypeRegistry.php';\nrequire 'HTMLPurifier/ElementDef.php';\nrequire 'HTMLPurifier/Encoder.php';\nrequire 'HTMLPurifier/EntityLookup.php';\nrequire 'HTMLPurifier/EntityParser.php';\nrequire 'HTMLPurifier/ErrorCollector.php';\nrequire 'HTMLPurifier/ErrorStruct.php';\nrequire 'HTMLPurifier/Exception.php';\nrequire 'HTMLPurifier/Filter.php';\nrequire 'HTMLPurifier/Generator.php';\nrequire 'HTMLPurifier/HTMLDefinition.php';\nrequire 'HTMLPurifier/HTMLModule.php';\nrequire 'HTMLPurifier/HTMLModuleManager.php';\nrequire 'HTMLPurifier/IDAccumulator.php';\nrequire 'HTMLPurifier/Injector.php';\nrequire 'HTMLPurifier/Language.php';\nrequire 'HTMLPurifier/LanguageFactory.php';\nrequire 'HTMLPurifier/Length.php';\nrequire 'HTMLPurifier/Lexer.php';\nrequire 'HTMLPurifier/PercentEncoder.php';\nrequire 'HTMLPurifier/PropertyList.php';\nrequire 'HTMLPurifier/PropertyListIterator.php';\nrequire 'HTMLPurifier/Strategy.php';\nrequire 'HTMLPurifier/StringHash.php';\nrequire 'HTMLPurifier/StringHashParser.php';\nrequire 'HTMLPurifier/TagTransform.php';\nrequire 'HTMLPurifier/Token.php';\nrequire 'HTMLPurifier/TokenFactory.php';\nrequire 'HTMLPurifier/URI.php';\nrequire 'HTMLPurifier/URIDefinition.php';\nrequire 'HTMLPurifier/URIFilter.php';\nrequire 'HTMLPurifier/URIParser.php';\nrequire 'HTMLPurifier/URIScheme.php';\nrequire 'HTMLPurifier/URISchemeRegistry.php';\nrequire 'HTMLPurifier/UnitConverter.php';\nrequire 'HTMLPurifier/VarParser.php';\nrequire 'HTMLPurifier/VarParserException.php';\nrequire 'HTMLPurifier/AttrDef/CSS.php';\nrequire 'HTMLPurifier/AttrDef/Enum.php';\nrequire 'HTMLPurifier/AttrDef/Integer.php';\nrequire 'HTMLPurifier/AttrDef/Lang.php';\nrequire 'HTMLPurifier/AttrDef/Switch.php';\nrequire 'HTMLPurifier/AttrDef/Text.php';\nrequire 'HTMLPurifier/AttrDef/URI.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Number.php';\nrequire 'HTMLPurifier/AttrDef/CSS/AlphaValue.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Background.php';\nrequire 'HTMLPurifier/AttrDef/CSS/BackgroundPosition.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Border.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Color.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Composite.php';\nrequire 'HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Filter.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Font.php';\nrequire 'HTMLPurifier/AttrDef/CSS/FontFamily.php';\nrequire 'HTMLPurifier/AttrDef/CSS/ImportantDecorator.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Length.php';\nrequire 'HTMLPurifier/AttrDef/CSS/ListStyle.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Multiple.php';\nrequire 'HTMLPurifier/AttrDef/CSS/Percentage.php';\nrequire 'HTMLPurifier/AttrDef/CSS/TextDecoration.php';\nrequire 'HTMLPurifier/AttrDef/CSS/URI.php';\nrequire 'HTMLPurifier/AttrDef/HTML/Bool.php';\nrequire 'HTMLPurifier/AttrDef/HTML/Nmtokens.php';\nrequire 'HTMLPurifier/AttrDef/HTML/Class.php';\nrequire 'HTMLPurifier/AttrDef/HTML/Color.php';\nrequire 'HTMLPurifier/AttrDef/HTML/FrameTarget.php';\nrequire 'HTMLPurifier/AttrDef/HTML/ID.php';\nrequire 'HTMLPurifier/AttrDef/HTML/Pixels.php';\nrequire 'HTMLPurifier/AttrDef/HTML/Length.php';\nrequire 'HTMLPurifier/AttrDef/HTML/LinkTypes.php';\nrequire 'HTMLPurifier/AttrDef/HTML/MultiLength.php';\nrequire 'HTMLPurifier/AttrDef/URI/Email.php';\nrequire 'HTMLPurifier/AttrDef/URI/Host.php';\nrequire 'HTMLPurifier/AttrDef/URI/IPv4.php';\nrequire 'HTMLPurifier/AttrDef/URI/IPv6.php';\nrequire 'HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php';\nrequire 'HTMLPurifier/AttrTransform/Background.php';\nrequire 'HTMLPurifier/AttrTransform/BdoDir.php';\nrequire 'HTMLPurifier/AttrTransform/BgColor.php';\nrequire 'HTMLPurifier/AttrTransform/BoolToCSS.php';\nrequire 'HTMLPurifier/AttrTransform/Border.php';\nrequire 'HTMLPurifier/AttrTransform/EnumToCSS.php';\nrequire 'HTMLPurifier/AttrTransform/ImgRequired.php';\nrequire 'HTMLPurifier/AttrTransform/ImgSpace.php';\nrequire 'HTMLPurifier/AttrTransform/Input.php';\nrequire 'HTMLPurifier/AttrTransform/Lang.php';\nrequire 'HTMLPurifier/AttrTransform/Length.php';\nrequire 'HTMLPurifier/AttrTransform/Name.php';\nrequire 'HTMLPurifier/AttrTransform/NameSync.php';\nrequire 'HTMLPurifier/AttrTransform/SafeEmbed.php';\nrequire 'HTMLPurifier/AttrTransform/SafeObject.php';\nrequire 'HTMLPurifier/AttrTransform/SafeParam.php';\nrequire 'HTMLPurifier/AttrTransform/ScriptRequired.php';\nrequire 'HTMLPurifier/AttrTransform/Textarea.php';\nrequire 'HTMLPurifier/ChildDef/Chameleon.php';\nrequire 'HTMLPurifier/ChildDef/Custom.php';\nrequire 'HTMLPurifier/ChildDef/Empty.php';\nrequire 'HTMLPurifier/ChildDef/Required.php';\nrequire 'HTMLPurifier/ChildDef/Optional.php';\nrequire 'HTMLPurifier/ChildDef/StrictBlockquote.php';\nrequire 'HTMLPurifier/ChildDef/Table.php';\nrequire 'HTMLPurifier/DefinitionCache/Decorator.php';\nrequire 'HTMLPurifier/DefinitionCache/Null.php';\nrequire 'HTMLPurifier/DefinitionCache/Serializer.php';\nrequire 'HTMLPurifier/DefinitionCache/Decorator/Cleanup.php';\nrequire 'HTMLPurifier/DefinitionCache/Decorator/Memory.php';\nrequire 'HTMLPurifier/HTMLModule/Bdo.php';\nrequire 'HTMLPurifier/HTMLModule/CommonAttributes.php';\nrequire 'HTMLPurifier/HTMLModule/Edit.php';\nrequire 'HTMLPurifier/HTMLModule/Forms.php';\nrequire 'HTMLPurifier/HTMLModule/Hypertext.php';\nrequire 'HTMLPurifier/HTMLModule/Image.php';\nrequire 'HTMLPurifier/HTMLModule/Legacy.php';\nrequire 'HTMLPurifier/HTMLModule/List.php';\nrequire 'HTMLPurifier/HTMLModule/Name.php';\nrequire 'HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php';\nrequire 'HTMLPurifier/HTMLModule/Object.php';\nrequire 'HTMLPurifier/HTMLModule/Presentation.php';\nrequire 'HTMLPurifier/HTMLModule/Proprietary.php';\nrequire 'HTMLPurifier/HTMLModule/Ruby.php';\nrequire 'HTMLPurifier/HTMLModule/SafeEmbed.php';\nrequire 'HTMLPurifier/HTMLModule/SafeObject.php';\nrequire 'HTMLPurifier/HTMLModule/Scripting.php';\nrequire 'HTMLPurifier/HTMLModule/StyleAttribute.php';\nrequire 'HTMLPurifier/HTMLModule/Tables.php';\nrequire 'HTMLPurifier/HTMLModule/Target.php';\nrequire 'HTMLPurifier/HTMLModule/Text.php';\nrequire 'HTMLPurifier/HTMLModule/Tidy.php';\nrequire 'HTMLPurifier/HTMLModule/XMLCommonAttributes.php';\nrequire 'HTMLPurifier/HTMLModule/Tidy/Name.php';\nrequire 'HTMLPurifier/HTMLModule/Tidy/Proprietary.php';\nrequire 'HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php';\nrequire 'HTMLPurifier/HTMLModule/Tidy/Strict.php';\nrequire 'HTMLPurifier/HTMLModule/Tidy/Transitional.php';\nrequire 'HTMLPurifier/HTMLModule/Tidy/XHTML.php';\nrequire 'HTMLPurifier/Injector/AutoParagraph.php';\nrequire 'HTMLPurifier/Injector/DisplayLinkURI.php';\nrequire 'HTMLPurifier/Injector/Linkify.php';\nrequire 'HTMLPurifier/Injector/PurifierLinkify.php';\nrequire 'HTMLPurifier/Injector/RemoveEmpty.php';\nrequire 'HTMLPurifier/Injector/SafeObject.php';\nrequire 'HTMLPurifier/Lexer/DOMLex.php';\nrequire 'HTMLPurifier/Lexer/DirectLex.php';\nrequire 'HTMLPurifier/Strategy/Composite.php';\nrequire 'HTMLPurifier/Strategy/Core.php';\nrequire 'HTMLPurifier/Strategy/FixNesting.php';\nrequire 'HTMLPurifier/Strategy/MakeWellFormed.php';\nrequire 'HTMLPurifier/Strategy/RemoveForeignElements.php';\nrequire 'HTMLPurifier/Strategy/ValidateAttributes.php';\nrequire 'HTMLPurifier/TagTransform/Font.php';\nrequire 'HTMLPurifier/TagTransform/Simple.php';\nrequire 'HTMLPurifier/Token/Comment.php';\nrequire 'HTMLPurifier/Token/Tag.php';\nrequire 'HTMLPurifier/Token/Empty.php';\nrequire 'HTMLPurifier/Token/End.php';\nrequire 'HTMLPurifier/Token/Start.php';\nrequire 'HTMLPurifier/Token/Text.php';\nrequire 'HTMLPurifier/URIFilter/DisableExternal.php';\nrequire 'HTMLPurifier/URIFilter/DisableExternalResources.php';\nrequire 'HTMLPurifier/URIFilter/HostBlacklist.php';\nrequire 'HTMLPurifier/URIFilter/MakeAbsolute.php';\nrequire 'HTMLPurifier/URIFilter/Munge.php';\nrequire 'HTMLPurifier/URIScheme/ftp.php';\nrequire 'HTMLPurifier/URIScheme/http.php';\nrequire 'HTMLPurifier/URIScheme/https.php';\nrequire 'HTMLPurifier/URIScheme/mailto.php';\nrequire 'HTMLPurifier/URIScheme/news.php';\nrequire 'HTMLPurifier/URIScheme/nntp.php';\nrequire 'HTMLPurifier/VarParser/Flexible.php';\nrequire 'HTMLPurifier/VarParser/Native.php';\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier.kses.php",
    "content": "<?php\n\n/**\n * @file\n * Emulation layer for code that used kses(), substituting in HTML Purifier.\n */\n\nrequire_once dirname(__FILE__) . '/HTMLPurifier.auto.php';\n\nfunction kses($string, $allowed_html, $allowed_protocols = null) {\n    $config = HTMLPurifier_Config::createDefault();\n    $allowed_elements = array();\n    $allowed_attributes = array();\n    foreach ($allowed_html as $element => $attributes) {\n        $allowed_elements[$element] = true;\n        foreach ($attributes as $attribute => $x) {\n            $allowed_attributes[\"$element.$attribute\"] = true;\n        }\n    }\n    $config->set('HTML.AllowedElements', $allowed_elements);\n    $config->set('HTML.AllowedAttributes', $allowed_attributes);\n    $allowed_schemes = array();\n    if ($allowed_protocols !== null) {\n        $config->set('URI.AllowedSchemes', $allowed_protocols);\n    }\n    $purifier = new HTMLPurifier($config);\n    return $purifier->purify($string);\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier.path.php",
    "content": "<?php\n\n/**\n * @file\n * Convenience stub file that adds HTML Purifier's library file to the path\n * without any other side-effects.\n */\n\nset_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path() );\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier.php",
    "content": "<?php\n\n/*! @mainpage\n *\n * HTML Purifier is an HTML filter that will take an arbitrary snippet of\n * HTML and rigorously test, validate and filter it into a version that\n * is safe for output onto webpages. It achieves this by:\n *\n *  -# Lexing (parsing into tokens) the document,\n *  -# Executing various strategies on the tokens:\n *      -# Removing all elements not in the whitelist,\n *      -# Making the tokens well-formed,\n *      -# Fixing the nesting of the nodes, and\n *      -# Validating attributes of the nodes; and\n *  -# Generating HTML from the purified tokens.\n *\n * However, most users will only need to interface with the HTMLPurifier\n * and HTMLPurifier_Config.\n */\n\n/*\n    HTML Purifier 4.0.0 - Standards Compliant HTML Filtering\n    Copyright (C) 2006-2008 Edward Z. Yang\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n\n/**\n * Facade that coordinates HTML Purifier's subsystems in order to purify HTML.\n *\n * @note There are several points in which configuration can be specified\n *       for HTML Purifier.  The precedence of these (from lowest to\n *       highest) is as follows:\n *          -# Instance: new HTMLPurifier($config)\n *          -# Invocation: purify($html, $config)\n *       These configurations are entirely independent of each other and\n *       are *not* merged (this behavior may change in the future).\n *\n * @todo We need an easier way to inject strategies using the configuration\n *       object.\n */\nclass HTMLPurifier\n{\n\n    /** Version of HTML Purifier */\n    public $version = '4.0.0';\n\n    /** Constant with version of HTML Purifier */\n    const VERSION = '4.0.0';\n\n    /** Global configuration object */\n    public $config;\n\n    /** Array of extra HTMLPurifier_Filter objects to run on HTML, for backwards compatibility */\n    private $filters = array();\n\n    /** Single instance of HTML Purifier */\n    private static $instance;\n\n    protected $strategy, $generator;\n\n    /**\n     * Resultant HTMLPurifier_Context of last run purification. Is an array\n     * of contexts if the last called method was purifyArray().\n     */\n    public $context;\n\n    /**\n     * Initializes the purifier.\n     * @param $config Optional HTMLPurifier_Config object for all instances of\n     *                the purifier, if omitted, a default configuration is\n     *                supplied (which can be overridden on a per-use basis).\n     *                The parameter can also be any type that\n     *                HTMLPurifier_Config::create() supports.\n     */\n    public function __construct($config = null) {\n\n        $this->config = HTMLPurifier_Config::create($config);\n\n        $this->strategy     = new HTMLPurifier_Strategy_Core();\n\n    }\n\n    /**\n     * Adds a filter to process the output. First come first serve\n     * @param $filter HTMLPurifier_Filter object\n     */\n    public function addFilter($filter) {\n        trigger_error('HTMLPurifier->addFilter() is deprecated, use configuration directives in the Filter namespace or Filter.Custom', E_USER_WARNING);\n        $this->filters[] = $filter;\n    }\n\n    /**\n     * Filters an HTML snippet/document to be XSS-free and standards-compliant.\n     *\n     * @param $html String of HTML to purify\n     * @param $config HTMLPurifier_Config object for this operation, if omitted,\n     *                defaults to the config object specified during this\n     *                object's construction. The parameter can also be any type\n     *                that HTMLPurifier_Config::create() supports.\n     * @return Purified HTML\n     */\n    public function purify($html, $config = null) {\n\n        // :TODO: make the config merge in, instead of replace\n        $config = $config ? HTMLPurifier_Config::create($config) : $this->config;\n\n        // implementation is partially environment dependant, partially\n        // configuration dependant\n        $lexer = HTMLPurifier_Lexer::create($config);\n\n        $context = new HTMLPurifier_Context();\n\n        // setup HTML generator\n        $this->generator = new HTMLPurifier_Generator($config, $context);\n        $context->register('Generator', $this->generator);\n\n        // set up global context variables\n        if ($config->get('Core.CollectErrors')) {\n            // may get moved out if other facilities use it\n            $language_factory = HTMLPurifier_LanguageFactory::instance();\n            $language = $language_factory->create($config, $context);\n            $context->register('Locale', $language);\n\n            $error_collector = new HTMLPurifier_ErrorCollector($context);\n            $context->register('ErrorCollector', $error_collector);\n        }\n\n        // setup id_accumulator context, necessary due to the fact that\n        // AttrValidator can be called from many places\n        $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);\n        $context->register('IDAccumulator', $id_accumulator);\n\n        $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context);\n\n        // setup filters\n        $filter_flags = $config->getBatch('Filter');\n        $custom_filters = $filter_flags['Custom'];\n        unset($filter_flags['Custom']);\n        $filters = array();\n        foreach ($filter_flags as $filter => $flag) {\n            if (!$flag) continue;\n            if (strpos($filter, '.') !== false) continue;\n            $class = \"HTMLPurifier_Filter_$filter\";\n            $filters[] = new $class;\n        }\n        foreach ($custom_filters as $filter) {\n            // maybe \"HTMLPurifier_Filter_$filter\", but be consistent with AutoFormat\n            $filters[] = $filter;\n        }\n        $filters = array_merge($filters, $this->filters);\n        // maybe prepare(), but later\n\n        for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) {\n            $html = $filters[$i]->preFilter($html, $config, $context);\n        }\n\n        // purified HTML\n        $html =\n            $this->generator->generateFromTokens(\n                // list of tokens\n                $this->strategy->execute(\n                    // list of un-purified tokens\n                    $lexer->tokenizeHTML(\n                        // un-purified HTML\n                        $html, $config, $context\n                    ),\n                    $config, $context\n                )\n            );\n\n        for ($i = $filter_size - 1; $i >= 0; $i--) {\n            $html = $filters[$i]->postFilter($html, $config, $context);\n        }\n\n        $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context);\n        $this->context =& $context;\n        return $html;\n    }\n\n    /**\n     * Filters an array of HTML snippets\n     * @param $config Optional HTMLPurifier_Config object for this operation.\n     *                See HTMLPurifier::purify() for more details.\n     * @return Array of purified HTML\n     */\n    public function purifyArray($array_of_html, $config = null) {\n        $context_array = array();\n        foreach ($array_of_html as $key => $html) {\n            $array_of_html[$key] = $this->purify($html, $config);\n            $context_array[$key] = $this->context;\n        }\n        $this->context = $context_array;\n        return $array_of_html;\n    }\n\n    /**\n     * Singleton for enforcing just one HTML Purifier in your system\n     * @param $prototype Optional prototype HTMLPurifier instance to\n     *                   overload singleton with, or HTMLPurifier_Config\n     *                   instance to configure the generated version with.\n     */\n    public static function instance($prototype = null) {\n        if (!self::$instance || $prototype) {\n            if ($prototype instanceof HTMLPurifier) {\n                self::$instance = $prototype;\n            } elseif ($prototype) {\n                self::$instance = new HTMLPurifier($prototype);\n            } else {\n                self::$instance = new HTMLPurifier();\n            }\n        }\n        return self::$instance;\n    }\n\n    /**\n     * @note Backwards compatibility, see instance()\n     */\n    public static function getInstance($prototype = null) {\n        return HTMLPurifier::instance($prototype);\n    }\n\n}\n\n// vim: et sw=4 sts=4\n"
  },
  {
    "path": "libraries/purifier/HTMLPurifier.safe-includes.php",
    "content": "<?php\n\n/**\n * @file\n * This file was auto-generated by generate-includes.php and includes all of\n * the core files required by HTML Purifier. This is a convenience stub that\n * includes all files using dirname(__FILE__) and require_once. PLEASE DO NOT\n * EDIT THIS FILE, changes will be overwritten the next time the script is run.\n *\n * Changes to include_path are not necessary.\n */\n\n$__dir = dirname(__FILE__);\n\nrequire_once $__dir . '/HTMLPurifier.php';\nrequire_once $__dir . '/HTMLPurifier/AttrCollections.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTypes.php';\nrequire_once $__dir . '/HTMLPurifier/AttrValidator.php';\nrequire_once $__dir . '/HTMLPurifier/Bootstrap.php';\nrequire_once $__dir . '/HTMLPurifier/Definition.php';\nrequire_once $__dir . '/HTMLPurifier/CSSDefinition.php';\nrequire_once $__dir . '/HTMLPurifier/ChildDef.php';\nrequire_once $__dir . '/HTMLPurifier/Config.php';\nrequire_once $__dir . '/HTMLPurifier/ConfigSchema.php';\nrequire_once $__dir . '/HTMLPurifier/ContentSets.php';\nrequire_once $__dir . '/HTMLPurifier/Context.php';\nrequire_once $__dir . '/HTMLPurifier/DefinitionCache.php';\nrequire_once $__dir . '/HTMLPurifier/DefinitionCacheFactory.php';\nrequire_once $__dir . '/HTMLPurifier/Doctype.php';\nrequire_once $__dir . '/HTMLPurifier/DoctypeRegistry.php';\nrequire_once $__dir . '/HTMLPurifier/ElementDef.php';\nrequire_once $__dir . '/HTMLPurifier/Encoder.php';\nrequire_once $__dir . '/HTMLPurifier/EntityLookup.php';\nrequire_once $__dir . '/HTMLPurifier/EntityParser.php';\nrequire_once $__dir . '/HTMLPurifier/ErrorCollector.php';\nrequire_once $__dir . '/HTMLPurifier/ErrorStruct.php';\nrequire_once $__dir . '/HTMLPurifier/Exception.php';\nrequire_once $__dir . '/HTMLPurifier/Filter.php';\nrequire_once $__dir . '/HTMLPurifier/Generator.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLDefinition.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModuleManager.php';\nrequire_once $__dir . '/HTMLPurifier/IDAccumulator.php';\nrequire_once $__dir . '/HTMLPurifier/Injector.php';\nrequire_once $__dir . '/HTMLPurifier/Language.php';\nrequire_once $__dir . '/HTMLPurifier/LanguageFactory.php';\nrequire_once $__dir . '/HTMLPurifier/Length.php';\nrequire_once $__dir . '/HTMLPurifier/Lexer.php';\nrequire_once $__dir . '/HTMLPurifier/PercentEncoder.php';\nrequire_once $__dir . '/HTMLPurifier/PropertyList.php';\nrequire_once $__dir . '/HTMLPurifier/PropertyListIterator.php';\nrequire_once $__dir . '/HTMLPurifier/Strategy.php';\nrequire_once $__dir . '/HTMLPurifier/StringHash.php';\nrequire_once $__dir . '/HTMLPurifier/StringHashParser.php';\nrequire_once $__dir . '/HTMLPurifier/TagTransform.php';\nrequire_once $__dir . '/HTMLPurifier/Token.php';\nrequire_once $__dir . '/HTMLPurifier/TokenFactory.php';\nrequire_once $__dir . '/HTMLPurifier/URI.php';\nrequire_once $__dir . '/HTMLPurifier/URIDefinition.php';\nrequire_once $__dir . '/HTMLPurifier/URIFilter.php';\nrequire_once $__dir . '/HTMLPurifier/URIParser.php';\nrequire_once $__dir . '/HTMLPurifier/URIScheme.php';\nrequire_once $__dir . '/HTMLPurifier/URISchemeRegistry.php';\nrequire_once $__dir . '/HTMLPurifier/UnitConverter.php';\nrequire_once $__dir . '/HTMLPurifier/VarParser.php';\nrequire_once $__dir . '/HTMLPurifier/VarParserException.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/Enum.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/Integer.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/Lang.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/Switch.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/Text.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/URI.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Number.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/AlphaValue.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Background.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Border.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Color.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Composite.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Filter.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Font.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/FontFamily.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Length.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/ListStyle.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Multiple.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/Percentage.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/TextDecoration.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/CSS/URI.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/Bool.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/Nmtokens.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/Class.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/Color.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/FrameTarget.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/ID.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/Pixels.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/Length.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/LinkTypes.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/HTML/MultiLength.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/URI/Email.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/URI/Host.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/URI/IPv4.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/URI/IPv6.php';\nrequire_once $__dir . '/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/Background.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/BdoDir.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/BgColor.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/BoolToCSS.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/Border.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/EnumToCSS.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/ImgRequired.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/ImgSpace.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/Input.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/Lang.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/Length.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/Name.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/NameSync.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/SafeEmbed.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/SafeObject.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/SafeParam.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/ScriptRequired.php';\nrequire_once $__dir . '/HTMLPurifier/AttrTransform/Textarea.php';\nrequire_once $__dir . '/HTMLPurifier/ChildDef/Chameleon.php';\nrequire_once $__dir . '/HTMLPurifier/ChildDef/Custom.php';\nrequire_once $__dir . '/HTMLPurifier/ChildDef/Empty.php';\nrequire_once $__dir . '/HTMLPurifier/ChildDef/Required.php';\nrequire_once $__dir . '/HTMLPurifier/ChildDef/Optional.php';\nrequire_once $__dir . '/HTMLPurifier/ChildDef/StrictBlockquote.php';\nrequire_once $__dir . '/HTMLPurifier/ChildDef/Table.php';\nrequire_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator.php';\nrequire_once $__dir . '/HTMLPurifier/DefinitionCache/Null.php';\nrequire_once $__dir . '/HTMLPurifier/DefinitionCache/Serializer.php';\nrequire_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php';\nrequire_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator/Memory.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Bdo.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/CommonAttributes.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Edit.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Forms.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Hypertext.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Image.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Legacy.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/List.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Name.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Object.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Presentation.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Proprietary.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Ruby.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/SafeEmbed.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/SafeObject.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Scripting.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/StyleAttribute.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Tables.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Target.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Text.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Tidy.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/XMLCommonAttributes.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Name.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Proprietary.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Strict.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Transitional.php';\nrequire_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/XHTML.php';\nrequire_once $__dir . '/HTMLPurifier/Injector/AutoParagraph.php';\nrequire_once $__dir . '/HTMLPurifier/Injector/DisplayLinkURI.php';\nrequire_once $__dir . '/HTMLPurifier/Injector/Linkify.php';\nrequire_once $__dir . '/HTMLPurifier/Injector/PurifierLinkify.php';\nrequire_once $__dir . '/HTMLPurifier/Injector/RemoveEmpty.php';\nrequire_once $__dir . '/HTMLPurifier/Injector/SafeObject.php';\nrequire_once $__dir . '/HTMLPurifier/Lexer/DOMLex.php';\nrequire_once $__dir . '/HTMLPurifier/Lexer/DirectLex.php';\nrequire_once $__dir . '/HTMLPurifier/Strategy/Composite.php';\nrequire_once $__dir . '/HTMLPurifier/Strategy/Core.php';\nrequire_once $__dir . '/HTMLPurifier/Strategy/FixNesting.php';\nrequire_once $__dir . '/HTMLPurifier/Strategy/MakeWellFormed.php';\nrequire_once $__dir . '/HTMLPurifier/Strategy/RemoveForeignElements.php';\nrequire_once $__dir . '/HTMLPurifier/Strategy/ValidateAttributes.php';\nrequire_once $__dir . '/HTMLPurifier/TagTransform/Font.php';\nrequire_once $__dir . '/HTMLPurifier/TagTransform/Simple.php';\nrequire_once $__dir . '/HTMLPurifier/Token/Comment.php';\nrequire_once $__dir . '/HTMLPurifier/Token/Tag.php';\nrequire_once $__dir . '/HTMLPurifier/Token/Empty.php';\nrequire_once $__dir . '/HTMLPurifier/Token/End.php';\nrequire_once $__dir . '/HTMLPurifier/Token/Start.php';\nrequire_once $__dir . '/HTMLPurifier/Token/Text.php';\nrequire_once $__dir . '/HTMLPurifier/URIFilter/DisableExternal.php';\nrequire_once $__dir . '/HTMLPurifier/URIFilter/DisableExternalResources.php';\nrequire_once $__dir . '/HTMLPurifier/URIFilter/HostBlacklist.php';\nrequire_once $__dir . '/HTMLPurifier/URIFilter/MakeAbsolute.php';\nrequire_once $__dir . '/HTMLPurifier/URIFilter/Munge.php';\nrequire_once $__dir . '/HTMLPurifier/URIScheme/ftp.php';\nrequire_once $__dir . '/HTMLPurifier/URIScheme/http.php';\nrequire_once $__dir . '/HTMLPurifier/URIScheme/https.php';\nrequire_once $__dir . '/HTMLPurifier/URIScheme/mailto.php';\nrequire_once $__dir . '/HTMLPurifier/URIScheme/news.php';\nrequire_once $__dir . '/HTMLPurifier/URIScheme/nntp.php';\nrequire_once $__dir . '/HTMLPurifier/VarParser/Flexible.php';\nrequire_once $__dir . '/HTMLPurifier/VarParser/Native.php';\n"
  },
  {
    "path": "libraries/score.php",
    "content": "<?php\n\nfunction score($activity = 'none',$id = 0,$userid = 0) {\n\n\tif ($userid == 0) { $userid = $_SESSION['userid']; }\n\n\t$points = 0;\n\n\tswitch ($activity) {\n\t\tcase 'q_downvoter':\n\t\t\t$points = -1;\n\t\tbreak;\n\n\t\tcase 'q_downvoted':\n\t\t\t$points = -2;\n\t\tbreak;\n\n\t\tcase 'q_upvoted':\n\t\t\t$points = 10;\n\t\tbreak;\n\n\t\tcase 'q_upvoted_removed':\n\t\t\t$points = -10;\n\t\tbreak;\n\n\t\tcase 'q_downvoter_removed':\n\t\t\t$points = 1;\n\t\tbreak;\n\n\t\tcase 'q_downvoted_removed':\n\t\t\t$points = 2;\n\t\tbreak;\n\n\t\tcase 'a_downvoter':\n\t\t\t$points = -1;\n\t\tbreak;\n\n\t\tcase 'a_downvoted':\n\t\t\t$points = -2;\n\t\tbreak;\n\n\t\tcase 'a_upvoted':\n\t\t\t$points = 10;\n\t\tbreak;\n\n\t\tcase 'a_upvoted_removed':\n\t\t\t$points = -10;\n\t\tbreak;\n\n\t\tcase 'a_downvoter_removed':\n\t\t\t$points = 1;\n\t\tbreak;\n\n\t\tcase 'a_downvoted_removed':\n\t\t\t$points = 2;\n\t\tbreak;\n\n\t\tcase 'a_accepter':\n\t\t\t$points = 2;\n\t\tbreak;\n\t\t\n\t\tcase 'a_accepted':\n\t\t\t$points = 15;\n\t\tbreak;\n\n\t\tcase 'a_accepted_removed':\n\t\t\t$points = -15;\n\t\tbreak;\n\n\t\tcase 'kb_posted':\n\t\t\t$points = 10;\n\t\tbreak;\n\n\t\tcase 'kb_posted_removed':\n\t\t\t$points = -10;\n\t\tbreak;\n\n\t\tcase 'c_upvoted':\n\t\t\t$points = 5;\n\t\tbreak;\n\n\t\tcase 'c_upvoted_removed':\n\t\t\t$points = -5;\n\t\tbreak;\n\n\t\tcase 'none':\n\n\t\tbreak;\n\t}\n\t\n\tif ($points != 0) {\n\t\t$sql = (\"insert into activities (userid,activity,points,activityid,created) values ('\".escape($userid).\"','\".escape($activity).\"','\".escape($points).\"','\".escape($id).\"',NOW())\");\n\t\t$query = mysql_query($sql);\n\t\techo mysql_error();\n\t}\n\t\n\tif ($points >= 0) {\n\t\t$points = \"+\".$points;\n\t}\n\n\t$sql = (\"update users set points = points\".escape($points).\" where id = '\".escape($userid).\"' and (points\".escape($points).\") > 1\");\n\t$query = mysql_query($sql);\n\techo mysql_error();\n}\n"
  },
  {
    "path": "libraries/shared.php",
    "content": "<?php\n\nfunction generateLink($controller,$action) {\n\treturn basePath().'/'.$controller.'/'.$action;\n}\n\nfunction noRender() {\n\tglobal $noRender;\n\t$noRender = true;\n}\n\nfunction authenticate($force = 0) {\n\tglobal $template;\n\tglobal $controller;\n\tglobal $action;\n\n\t$loggedin = 0;\n\n\tif (!empty($_SESSION['email']) && !empty($_SESSION['password'])) {\n\n\t\t$sql = (\"select id,name,points from users where email = '\".escape($_SESSION['email']).\"' and password = '\".escape($_SESSION['password']).\"'\");\n\t\t$query = mysql_query($sql);\n\t\t$user = mysql_fetch_array($query);\n\n\t\tif ($user['id'] > 0) {\n\t\t\t$_SESSION['points'] = $user['points'];\n\t\t\t$_SESSION['name'] = $user['name'];\n\t\t\t$loggedin = 1;\n\t\t} \t\t \n\t}\n\n\t\n\tif (($force == 1 || ALLOW_VISITORS == 0) && $loggedin == 0 && ($controller != 'users' && ($action != 'validate' || $action != 'create' || $action != 'register'))) {\n\t\t$template->overrideController('users');\n\t\t$template->overrideAction('login');\n\t\t$template->set('link',getLink());\n\t\t$controller = \"users\";\n\t\t$action = \"login\";\n\t}\n\t\n\tif ($loggedin == 0) {\n\t\t$_SESSION['userid'] = '';\n\t}\n}\n\nfunction getLink() {\n\t$s = empty($_SERVER[\"HTTPS\"]) ? '' : ($_SERVER[\"HTTPS\"] == \"on\") ? \"s\" : \"\";\n\t$protocol = substr(strtolower($_SERVER[\"SERVER_PROTOCOL\"]), 0, strpos(strtolower($_SERVER[\"SERVER_PROTOCOL\"]), \"/\")) . $s;\n\t$port = ($_SERVER[\"SERVER_PORT\"] == \"80\") ? \"\" : (\":\".$_SERVER[\"SERVER_PORT\"]);\n\treturn $protocol . \"://\" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];\n}\n\nfunction sanitize($input,$type = \"old\") {\n\t\n\tswitch ($type) {\n\tcase \"int\": \n\t\t$input = filter_var($input, FILTER_SANITIZE_NUMBER_INT);\n\tbreak;\n\n\tcase \"string\": \n\t\t$input = filter_var($input, FILTER_SANITIZE_STRING);\n\tbreak;\n\n\tcase \"url\": \n\t\t$input = filter_var($input, FILTER_SANITIZE_URL);\n\tbreak;\n\n\tcase \"email\":\n\t\t$input = strtolower(filter_var($input, FILTER_SANITIZE_EMAIL));\n\tbreak;\n\n\tcase \"markdown\":\n\n\t\tinclude_once ROOT.DS.'libraries'.DS.'purifier'.DS.'HTMLPurifier.auto.php';\n\t\t$purifier = new HTMLPurifier();\n\t\t$input = $purifier->purify($input);\n\t\n\tbreak;\n\n\tcase \"comment\":\n\t\t$input = htmlentities($input, ENT_QUOTES);\n\tbreak;\n\n\tcase \"old\":\n\t\techo \"Old version of sanitize called\";\n\t\texit();\n\tbreak;\n\n\t}\n\n\treturn $input;\n}\n\n\nfunction escape($input) {\n\t$input = mysql_real_escape_string($input);\n\treturn $input;\n}\n\nfunction createSlug($input) {\n\t$input = filter_var($input, FILTER_SANITIZE_STRING);\n\t$input = trim($input);\n\t$input = preg_replace(\"/ /\",\"-\",$input);\n\t$input = preg_replace(\"/[^+A-Za-z0-9\\.\\-]/\", \"\", $input); \n\treturn strtolower($input);\n}\n\nfunction fetchURL($url) {\n  $options = array(\n        CURLOPT_RETURNTRANSFER => true,     // return web page\n        CURLOPT_HEADER         => false,    // don't return headers\n        CURLOPT_FOLLOWLOCATION => true,     // follow redirects\n        CURLOPT_ENCODING       => \"\",       // handle all encodings\n        CURLOPT_USERAGENT      => \"spider\", // who am i\n        CURLOPT_AUTOREFERER    => true,     // set referer on redirect\n        CURLOPT_CONNECTTIMEOUT => 10,      // timeout on connect\n        CURLOPT_TIMEOUT        => 10,      // timeout on response\n        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects\n    );\n\n    $ch      = curl_init( $url );\n    curl_setopt_array( $ch, $options );\n    $content = curl_exec( $ch );\n    $err     = curl_errno( $ch );\n    $errmsg  = curl_error( $ch );\n    $header  = curl_getinfo( $ch );\n    curl_close( $ch );\n\n    return $content;\n}\n\nfunction db() {\n\t$dbh = mysql_connect(SERVERNAME.':'.SERVERPORT,DBUSERNAME,DBPASSWORD);\n\treturn mysql_selectdb(DBNAME,$dbh);\n}\n\nfunction basePath() {\n\treturn BASE_PATH;\n}\n\nfunction basePathNS() {\n\treturn BASE_DIR;\n}\n\nfunction datify($date) {\n\treturn date('g:iA M dS', strtotime($date));\n}\n\nfunction datifyunix($date) {\n\treturn date('g:iA M dS', $date);\n}\n\nfunction highlight($c,$q){ \n$q=explode(' ',str_replace(array('','\\\\','+','*','?','[','^',']','$','(',')','{','}','=','!','<','>','|',':','#','-','_'),'',$q));\nfor($i=0;$i<sizeOf($q);$i++) \n\t$c=preg_replace(\"/($q[$i])(?![^<]*>)/i\",\"<span class=\\\"highlight\\\">\\${1}</span>\",$c);\nreturn $c;}\n\n\n function excerpt($text, $phrase, $radius = 100, $ending = \"...\") { \n \n  \n         $phraseLen = strlen($phrase); \n       if ($radius < $phraseLen) { \n             $radius = $phraseLen; \n         } \n\n\t\t $phrases = explode (' ',$phrase);\n\t\t \n\t\t foreach ($phrases as $phrase) {\n\t\t\t $pos = strpos(strtolower($text), strtolower($phrase)); \n\t\t\t if ($pos > -1) break;\n\t\t }\n  \n         $startPos = 0; \n         if ($pos > $radius) { \n             $startPos = $pos - $radius; \n         } \n  \n         $textLen = strlen($text); \n  \n         $endPos = $pos + $phraseLen + $radius; \n         if ($endPos >= $textLen) { \n             $endPos = $textLen; \n         } \n  \n         $excerpt = substr($text, $startPos, $endPos - $startPos); \n         if ($startPos != 0) { \n             $excerpt = substr_replace($excerpt, $ending, 0, $phraseLen); \n         } \n  \n         if ($endPos != $textLen) { \n             $excerpt = substr_replace($excerpt, $ending, -$phraseLen); \n         } \n  \n         return $excerpt; \n   } \n\nfunction truncate ($text, $length = 200, $ending = \"...\") {\n\tif (strlen($text) <= $length) { \n\t\treturn $text; \n\t} else { \n\t\t$truncate = substr($text, 0, $length - strlen($ending)).$ending; \n\t\treturn $truncate;\n\t} \n}\n\ndb();\nauthenticate();\n"
  },
  {
    "path": "libraries/template.class.php",
    "content": "<?php\nclass Template {\n\t\n\tprotected $variables = array();\n\tprotected $_controller;\n\tprotected $_action;\n\t\n\tfunction __construct($controller,$action) {\n\t\t$this->_controller = $controller;\n\t\t$this->_action = $action;\n\t}\n\n\t/** Set Variables **/\n\n\tfunction set($name,$value) {\n\t\t$this->variables[$name] = $value;\n\t}\n\n\tfunction overrideController($controller) {\n\t\t$this->_controller = $controller;\n\t}\n\n\tfunction overrideAction($action) {\n\t\t$this->_action = $action;\n\t}\n\n\t/** Display Template **/\n\t\n    function render($doNotRenderHeader = 0) {\n\t\t\n\t\textract($this->variables);\n\t\t\n\t\tif ($doNotRenderHeader == 0) {\n\t\t\t\n\t\t\tif (file_exists(ROOT . DS . 'views' . DS . $this->_controller . DS . 'header.php')) {\n\t\t\t\tinclude (ROOT . DS . 'views' . DS . $this->_controller . DS . 'header.php');\n\t\t\t} else {\n\t\t\t\tinclude (ROOT . DS . 'views' . DS . 'header.php');\n\t\t\t}\n\t\t}\n\n\t\tif (file_exists(ROOT . DS . 'views' . DS . $this->_controller . DS . $this->_action . '.php')) {\n\t\t\tinclude (ROOT . DS . 'views' . DS . $this->_controller . DS . $this->_action . '.php');\t\t \n\t\t}\n\t\t\t\n\t\tif ($doNotRenderHeader == 0) {\n\t\t\tif (file_exists(ROOT . DS . DS . $this->_controller . DS . 'footer.php')) {\n\t\t\t\tinclude (ROOT . DS . DS . $this->_controller . DS . 'footer.php');\n\t\t\t} else {\n\t\t\t\tinclude (ROOT . DS . 'views' . DS . 'footer.php');\n\t\t\t}\n\t\t}\n\t\texit();\n    }\n\n}"
  },
  {
    "path": "libraries/timeago.php",
    "content": "<?php \nfunction timeAgo($datefrom,$dateto=-1)\n{\n// Defaults and assume if 0 is passed in that\n// its an error rather than the epoch\n\nif($datefrom<=0) { return \"A long time ago\"; }\nif($dateto==-1) { $dateto = time(); }\n\n// Calculate the difference in seconds betweeen\n// the two timestamps\n$difference = $dateto - $datefrom;\n\nif ($difference < 0 ) {\nreturn 'n/a';\n}\n// If difference is less than 60 seconds,\n// seconds is a good interval of choice\n\nif($difference < 60)\n{\n$interval = \"s\";\n}\n\n// If difference is between 60 seconds and\n// 60 minutes, minutes is a good interval\nelseif($difference >= 60 && $difference<60*60)\n{\n$interval = \"n\";\n}\n\n// If difference is between 1 hour and 24 hours\n// hours is a good interval\nelseif($difference >= 60*60 && $difference<60*60*24)\n{\n$interval = \"h\";\n}\n\n// If difference is between 1 day and 7 days\n// days is a good interval\nelseif($difference >= 60*60*24 && $difference<60*60*24*7)\n{\n$interval = \"d\";\n}\n\n// If difference is between 1 week and 30 days\n// weeks is a good interval\nelseif($difference >= 60*60*24*7 && $difference <\n60*60*24*30)\n{\n$interval = \"ww\";\n}\n\n// If difference is between 30 days and 365 days\n// months is a good interval, again, the same thing\n// applies, if the 29th February happens to exist\n// between your 2 dates, the function will return\n// the 'incorrect' value for a day\nelseif($difference >= 60*60*24*30 && $difference <\n60*60*24*365)\n{\n$interval = \"m\";\n}\n\n// If difference is greater than or equal to 365\n// days, return year. This will be incorrect if\n// for example, you call the function on the 28th April\n// 2008 passing in 29th April 2007. It will return\n// 1 year ago when in actual fact (yawn!) not quite\n// a year has gone by\nelseif($difference >= 60*60*24*365)\n{\n$interval = \"y\";\n}\n\n// Based on the interval, determine the\n// number of units between the two dates\n// From this point on, you would be hard\n// pushed telling the difference between\n// this function and DateDiff. If the $datediff\n// returned is 1, be sure to return the singular\n// of the unit, e.g. 'day' rather 'days'\n\nswitch($interval)\n{\ncase \"m\":\n$months_difference = floor($difference / 60 / 60 / 24 /\n29);\nwhile (mktime(date(\"H\", $datefrom), date(\"i\", $datefrom),\ndate(\"s\", $datefrom), date(\"n\", $datefrom)+($months_difference),\ndate(\"j\", $dateto), date(\"Y\", $datefrom)) < $dateto)\n{\n$months_difference++;\n}\n$datediff = $months_difference;\n\n// We need this in here because it is possible\n// to have an 'm' interval and a months\n// difference of 12 because we are using 29 days\n// in a month\n\nif($datediff==12)\n{\n$datediff--;\n}\n\n$res = ($datediff==1) ? \"$datediff mnth\" : \"$datediff\nmnths\";\n$res = datifyunix($datefrom);\nbreak;\n\ncase \"y\":\n$datediff = floor($difference / 60 / 60 / 24 / 365);\n$res = ($datediff==1) ? \"$datediff yr\" : \"$datediff\nyrs\";\n\n$res = datifyunix($datefrom);\nbreak;\n\ncase \"d\":\n$datediff = floor($difference / 60 / 60 / 24);\n$res = ($datediff==1) ? \"$datediff day ago\" : \"$datediff\ndays ago\";\nbreak;\n\ncase \"ww\":\n$datediff = floor($difference / 60 / 60 / 24 / 7);\n$res = ($datediff==1) ? \"$datediff wk\" : \"$datediff\nwks\";\n$res = datifyunix($datefrom);\nbreak;\n\ncase \"h\":\n$datediff = floor($difference / 60 / 60);\n$res = ($datediff==1) ? \"$datediff hr ago\" : \"$datediff\nhrs ago\";\nbreak;\n\ncase \"n\":\n$datediff = floor($difference / 60);\n$res = ($datediff==1) ? \"$datediff min ago\" :\n\"$datediff mins ago\";\nbreak;\n\ncase \"s\":\n$datediff = $difference;\n$res = ($datediff==1) ? \"$datediff sec ago\" :\n\"$datediff secs ago\";\nbreak;\n}\nreturn $res;\n}\n\n\n\n\n\n\n\nfunction TimeHours($datefrom,$dateto=-1)\n{\n// Defaults and assume if 0 is passed in that\n// its an error rather than the epoch\n\nif($dateto==-1) { $dateto = time(); }\n\n\n// Calculate the difference in seconds betweeen\n// the two timestamps\n$difference = $dateto - $datefrom;\n\nif ($difference < 0 ) {\nreturn 'n/a';\n}\n// If difference is less than 60 seconds,\n// seconds is a good interval of choice\n\nif($difference < 60)\n{\n$interval = \"s\";\n}\n\n// If difference is between 60 seconds and\n// 60 minutes, minutes is a good interval\nelseif($difference >= 60 && $difference<60*60)\n{\n$interval = \"n\";\n}\n\n// If difference is between 1 hour and 24 hours\n// hours is a good interval\nelseif($difference >= 60*60 )\n{\n$interval = \"h\";\n}\n\nswitch($interval)\n{\ncase \"m\":\n$months_difference = floor($difference / 60 / 60 / 24 /\n29);\nwhile (mktime(date(\"H\", $datefrom), date(\"i\", $datefrom),\ndate(\"s\", $datefrom), date(\"n\", $datefrom)+($months_difference),\ndate(\"j\", $dateto), date(\"Y\", $datefrom)) < $dateto)\n{\n$months_difference++;\n}\n$datediff = $months_difference;\n\n// We need this in here because it is possible\n// to have an 'm' interval and a months\n// difference of 12 because we are using 29 days\n// in a month\n\nif($datediff==12)\n{\n$datediff--;\n}\n\n$res = ($datediff==1) ? \"$datediff mnth\" : \"$datediff\nmnths\";\nbreak;\n\ncase \"y\":\n$datediff = floor($difference / 60 / 60 / 24 / 365);\n$res = ($datediff==1) ? \"$datediff yr\" : \"$datediff\nyrs\";\nbreak;\n\ncase \"d\":\n$datediff = floor($difference / 60 / 60 / 24);\n$res = ($datediff==1) ? \"$datediff day\" : \"$datediff\ndays\";\nbreak;\n\ncase \"ww\":\n$datediff = floor($difference / 60 / 60 / 24 / 7);\n$res = ($datediff==1) ? \"$datediff wk\" : \"$datediff\nwks\";\nbreak;\n\ncase \"h\":\n$datediff = floor($difference / 60 / 60);\n$res = ($datediff==1) ? \"$datediff hr\" : \"$datediff\nhrs\";\nbreak;\n\ncase \"n\":\n$datediff = floor($difference / 60);\n$res = ($datediff==1) ? \"$datediff min\" :\n\"$datediff mins\";\nbreak;\n\ncase \"s\":\n$datediff = $difference;\n$res = ($datediff==1) ? \"$datediff sec\" :\n\"$datediff secs\";\nbreak;\n}\nreturn $res;\n}\n"
  },
  {
    "path": "views/answers/edit.php",
    "content": "<form action=\"<?php echo generateLink(\"answers\",\"update\");?>\" method=\"post\">\n\n<h1>Edit Your Answer</h1>\n\n<div id=\"wmd-editor\" class=\"wmd-panel\">\n<div id=\"wmd-button-bar\"></div>\n<textarea id=\"wmd-input\" name=\"description\" ><?php echo $description;?></textarea>\n</div>\n<div id=\"wmd-preview\" class=\"wmd-panel\"></div>\n \n<br/><br/>\n<input type=\"hidden\" name=\"id\" value=\"<?php echo $answerid;?>\">\n<input type=\"submit\" value=\"Update Answer\" class=\"button\">\n</form>"
  },
  {
    "path": "views/comments/post.php",
    "content": "<div class=\"comment\">\n<?php echo $comment;?> - <a href=\"<?php echo basePath();?>/users/<?php echo $userid;?>/<?php echo $username;?>\"><?php echo $username;?></a>\n</div>"
  },
  {
    "path": "views/footer.php",
    "content": "</div>\n<div id=\"rightpanel\">\n<div style=\"text-align:right;\"><a href=\"<?php echo basePath();?>/\" style=\"border-bottom:0px;\"><img src=\"<?php echo basePathNS();?>/img/logo.gif\"></a></div>\n<div style=\"clear:both\"></div>\n\n<?php if (!empty($_SESSION['userid'])):?>\n\t<div class=\"userlogin\">\n\t\t<div style=\"float:left\"><img src=\"http://www.gravatar.com/avatar/<?php echo md5(trim(strtolower($_SESSION['email'])));?>?d=monsterid&s=70\" style=\"border:1px solid #ccc\"></div><div style=\"float:left;padding-left:10px;\"><h3 style=\"padding-left:0px\"><?php echo $_SESSION['name'];?> | <?php echo $_SESSION['points'];?></h3>\n\t\t<a href=\"<?php echo basePath();?>/users/edit\">Edit Profile</a><br/>\n\t\t<a href=\"<?php echo basePath();?>/users/logout\">Logout</a></div>\n\t\t<div style=\"clear:both\"></div>\n\t</div>\n<?php else:?>\n\t<?php if (empty($loginpage)):?>\n\t<div class=\"userlogin\">\n\t\t<form action=\"<?php echo generateLink(\"users\",\"validate\");?>\" method=\"post\">\n\t\t<h3>E-mail</h3>\n\t\t<input type=\"textbox\" class=\"textbox\" name=\"email\" style=\"width:215px;\"/>\n\t\t<h3>Password</h3>\n\t\t<input type=\"password\" class=\"textbox\" name=\"password\" style=\"width:215px;\"/>\n\t\t<input type=\"hidden\" name=\"returnurl\" value=\"<?php echo getLink();?>\">\n\t\t<div style=\"padding-top:10px\"><input type=\"submit\" value=\"Login\" class=\"button\"> or <i><a href=\"<?php echo basePath();?>/users/register\">click here to register</a></i>\n\t\t</form>\n\t</div>\n\t<?php endif;?>\n<?php endif;?>\n</div>\n<div style=\"clear:both\"></div>\n</div>\n<div style=\"clear:both\">&nbsp;</div>\n<div class=\"footer\">\n<!-- Copyright Notice Do Not Remove -->\nPowered by Qwench<br/>Copyright <?php echo date(\"Y\");?> <a href=\"http://www.inscripts.com\" target=\"_blank\">Inscripts</a>\n<!-- Copyright Notice Do Not Remove -->\n</div>\n</body>\n</html>"
  },
  {
    "path": "views/header.php",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html>\n\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/> \n<head>\n<title>Qwench</title>\n<link type=\"text/css\" rel=\"stylesheet\" href=\"<?php echo basePathNS();?>/css/main.css\">\n<link type=\"text/css\" rel=\"stylesheet\" href=\"<?php echo basePathNS();?>/css/tagscomplete.css\">\n\n<script src=\"<?php echo basePathNS();?>/js/jquery.js\"></script>\n<script src=\"<?php echo basePathNS();?>/js/tagscomplete.js\"></script>\n<script src=\"<?php echo basePathNS();?>/js/fancyalert.js\"></script>\n\n\n<script type=\"text/javascript\" src=\"<?php echo basePathNS();?>/js/prettify/prettify.js\"></script>\n\n<link href=\"<?php echo basePathNS();?>/css/prettify.css\" type=\"text/css\" rel=\"stylesheet\" />\n\n\n<?php if(!empty($js)):?><?php echo $js;?><?php endif;?>\n</head>\n<body onload=\"prettyPrint()\">\n<div id=\"navigation\"><div class=\"navcenter\">\n\n<form action=\"<?php echo basePath();?>/questions\" method=\"get\" style=\"float:left;width:420px;text-align:left;\"><input type=\"textbox\" name=\"search\" style=\"color: #999\" value=\"<?php if (!empty($searchstring)):?><?php echo $searchstring;?><?php endif?>\"></form>\n\n<div style=\"float:right;border-left: 1px solid #13a1c9;border-right: 1px solid #45c9e9;\"><ol><li><a href=\"<?php echo basePath();?>/\">Home</a></li><li><a href=\"<?php echo basePath();?>/questions\">Questions</a></li><li><a href=\"<?php echo basePath();?>/tags\">Tags</a></li><li><a href=\"<?php echo basePath();?>/users\">Users</a></li><li><a href=\"<?php echo basePath();?>/questions?type=unanswered\">Unanswered</a></li><li><a href=\"<?php echo basePath();?>/questions/ask\">Ask or Contribute</a></li></ol></div>\n\n</div>\n<div style=\"clear:both\"></div>\n</div>\n\n<div id=\"container\">\n\t<div id=\"leftpanel\">"
  },
  {
    "path": "views/helpers/getuser.php",
    "content": "<div class=\"userbox\"> \n<a href=\"<?php echo basePath();?>/users/view/<?php echo $user['id'];?>/<?php echo createSlug($user['name']);?>\"><?php echo $user['name'];?> | <?php echo $user['points'];?></a> \n</div>"
  },
  {
    "path": "views/questions/ask.php",
    "content": "\n<script>\nfunction fanswer() {\n\tvar checked = $('#answercheck').attr('checked')?1:0;\n\n\tif (checked == 1) {\n\t\t$(\"#askquestion\").val('Contribute');\n\t} else {\n\t\t$(\"#askquestion\").val('Ask Question');\n\t}\n}\n\nfunction cform() {\n\tvar title = '';\n\tvar description = '';\n\ttitle = $(\"#title\").val();\n\tdescription = $(\"#wmd-input\").val();\n \n\n\tif (title.length < 15) {\n\t\t$(\"#title\").addClass('textalert');\n\t\t$.fancyalert('Your title must be atleast 15 characters in length');\n\t\t$(\"#title\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#title\").removeClass('textalert');\n\t}\n\n\tif (description.length < 15) {\n\t\t$(\"#wmd-input\").addClass('textalert');\n\t\t$.fancyalert('Your description must be atleast 15 characters in length');\n\t\t$(\"#wmd-input\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#wmd-input\").removeClass('textalert');\n\t}\n\n\treturn true;\n}\n</script>\n\n<form action=\"<?php echo generateLink(\"questions\",\"post\");?>\" method=\"post\" onsubmit=\"javascript:return cform();\">\n\n<h1>What would you like to ask or contribute?</h1>\n<input type=\"textbox\" placeholder=\"Title for your question\" class=\"textbox\" name=\"title\" id=\"title\" tabindex=\"1\"/><br/>\n \n\n<div id=\"wmd-editor\" class=\"wmd-panel\" style=\"padding-top:10px\">\n<div id=\"wmd-button-bar\"></div>\n<textarea id=\"wmd-input\" name=\"description\" tabindex=\"2\" ></textarea>\n</div>\n<div id=\"wmd-preview\" class=\"markdown\"></div>\n \n\n<h3 style=\"padding-top:20px\">Share a Link</h3>\n<input type=\"textbox\" class=\"textbox\" name=\"link\" id=\"link\" tabindex=\"3\"/><br/>\n\n<h3>Tags</h3>\n<select class=\"textbox\" placeholder=\"Tag your question\" name=\"tags\" id=\"tags\" tabindex=\"4\"/></select>\n<br/>\n<input type=\"checkbox\" id=\"answercheck\" name=\"answercheck\" value=\"1\" onclick=\"fanswer();\" tabindex=\"4\"> Make this a knowledge-base article\n<br/><br/>\n<input type=\"submit\" value=\"Ask Question\" class=\"button\" id=\"askquestion\" tabindex=\"5\">\n</form>"
  },
  {
    "path": "views/questions/cache.php",
    "content": "<base href=\"<?php echo $cachelink;?>\">\n<?php echo $cache;?>\n<div style=\"position:absolute;background-color:#21a5ca;color:#ffffff;font-weight:bold;font-family:verdana,arial;padding:4px;top:0;right:0;font-size:10px;padding-left:10px;padding-right:10px;\">Cached Version of <?php echo $cachelink;?></div>"
  },
  {
    "path": "views/questions/edit.php",
    "content": "<script>\n\nfunction cform() {\n\tvar title = '';\n\tvar description = '';\n\ttitle = $(\"#title\").val();\n\tdescription = $(\"#wmd-input\").val();\n \n\n\tif (title.length < 15) {\n\t\t$(\"#title\").addClass('textalert');\n\t\t$.fancyalert('Your title must be atleast 15 characters in length');\n\t\t$(\"#title\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#title\").removeClass('textalert');\n\t}\n\n\tif (description.length < 15) {\n\t\t$(\"#wmd-input\").addClass('textalert');\n\t\t$.fancyalert('Your description must be atleast 15 characters in length');\n\t\t$(\"#wmd-input\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#wmd-input\").removeClass('textalert');\n\t}\n\n\treturn true;\n}\n</script>\n\n<form action=\"<?php echo generateLink(\"questions\",\"update\");?>\" method=\"post\" onsubmit=\"javascript:return cform();\">\n\n<h1>Edit Your Question</h1>\n<input type=\"textbox\" class=\"textbox\" name=\"title\" id=\"title\" value=\"<?php echo $title;?>\"/><br/>\n\n<div id=\"wmd-editor\" class=\"wmd-panel\" style=\"padding-top:20px\">\n<div id=\"wmd-button-bar\"></div>\n<textarea id=\"wmd-input\" name=\"description\" ><?php echo $description;?></textarea>\n</div>\n<div id=\"wmd-preview\" class=\"markdown\"></div>\n \n\n<h3 style=\"padding-top:20px\">Share a Link</h3>\n<input type=\"textbox\" class=\"textbox\" name=\"link\" id=\"link\" value=\"<?php echo $link;?>\"/><br/>\n\n<h3>Tags</h3>\n<select class=\"textbox\" name=\"tags\" id=\"tags\"/>\n<?php foreach ($tags as $tag):?>\n<option value=\"<?php echo $tag;?>\" class=\"selected\"><?php echo $tag;?></option>\n<?php endforeach;?>\n</select>\n<br/>\n<input type=\"checkbox\" id=\"answercheck\" name=\"answercheck\" value=\"1\" tabindex=\"4\" <?php if ($kb) { echo \"checked\"; }?>> Make this a knowledge-base article\n<br/><br/>\n<input type=\"hidden\" name=\"id\" value=\"<?php echo $questionid;?>\">\n<input type=\"submit\" value=\"Update\" class=\"button\">\n</form>"
  },
  {
    "path": "views/questions/index.php",
    "content": "<h1><?php if($nopagination != 1):?><?php echo $questionscount;?> <?php endif;?>Questions <i><?php echo $extratitle;?></i></h1>\n\n<div style=\"clear:both\"></div>\n<?php if ($questionscount != 0):?>\n\n<?php if($nopagination != 1):?>\n<div class=\"questionsgrid_toppagination\">\n<div style=\"clear:both\"></div>\n<?php if($questionscount > QUESTIONS_PER_PAGE  && $nopagination != 1):?>\n<div class=\"pagination\" style=\"margin-left:5px;\"><?php echo $pagination;?></div>\n<?php endif;?>\n<div class=\"pagination\" style=\"margin-left:5px;float:right;margin-right:5px;\"><?php echo $orderOptions;?></div>\n<div style=\"clear:both\"></div>\n</div> \n<?php endif;?>\n\n<div style=\"clear:both;height:30px;\"></div>\n<?php foreach ($questions as $question):?>\n\n<div class=\"questionsview_userbox\">\n<?php echo getUser($question['userid']);?>\n</div>\n\n<div class=\"questionsview_details\">\n<span style=\"color:#999\" title=\"<?php echo datify($question['created']);?>\"><?php echo timeAgo(strtotime($question['created']));?></span>\n</div>\n \n<?php if ($question['kb']):?>\n<div class=\"questionsview_details\">\n<?php echo $question['answers'];?> cmts | <?php echo $question['votes'];?> votes\n</div>\n<?php else:?>\n<div class=\"questionsview_details q\">\n<?php echo $question['answers'];?> ans | <?php echo $question['votes'];?> votes\n</div>\n<?php endif;?>\n\n \n\n<div class=\"questionsview_answer\" id=\"a<?php echo $question['id'];?>\">\n<div class=\"questionsgrid_title\">\n<a href=\"<?php echo basePath();?>/questions/view/<?php echo $question['id'];?>/<?php echo $question['slug'];?>\"><?php echo $question['title'];?></a>\n<br/><span class=\"questionsgrid_description\"><a href=\"<?php echo basePath();?>/questions/view/<?php echo $question['id'];?>/<?php echo $question['slug'];?>\"><?php echo $question['description'];?></a></span>\n<div style=\"clear:both\"></div>\n\n</div>\n\n<ul class=\"holder noborder\">\n<?php foreach ($question['tags'] as $tag):?>\n<li class=\"bit-box nopadding\"><a href=\"<?php echo basePath();?>/questions?tag=<?php echo $tag;?>\"><?php echo $tag;?></a></li>\n<?php endforeach;?>\n</ul>\n\n<div style=\"clear:both;\"></div>\n</div>\n<?php endforeach;?>\n\n<?php if($nopagination != 1):?>\n<div class=\"questionsgrid_bottompagination\">\n<div style=\"clear:both\"></div>\n<?php if($questionscount > QUESTIONS_PER_PAGE):?>\n<div class=\"pagination\" style=\"margin-left:5px;\"><?php echo $pagination;?></div>\n<?php endif;?>\n<div class=\"pagination\" style=\"margin-left:5px;float:right;margin-right:5px;\"><?php echo $orderOptions;?></div>\n\n<div style=\"clear:both\"></div>\n</div> \n<?php endif;?>\n\n<?php else:?><h3>Sorry, we could not find what you were looking for. You may want to have a look at \n<a href=\"<?php echo basePath();?>/tags\">tags</a>. <br/><br/> Or <a href=\"<?php echo basePath();?>/questions/ask\">ask questions</a>.</h3><?php endif;?>"
  },
  {
    "path": "views/questions/view.php",
    "content": "<script>\nfunction cform() { \n\tvar description = '';\n \n\tdescription = $(\"#wmd-input\").val();\n \n\tif (description.length < 15) {\n\t\t$(\"#wmd-input\").addClass('textalert');\n\t\t$.fancyalert('Your <?php if ($kb):?>comment<?php else:?>answer<?php endif;?> must be atleast 15 characters in length');\n\t\t$(\"#wmd-input\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#wmd-input\").removeClass('textalert');\n\t}\n\n\treturn true;\n}\n</script>\n\n<h1><?php echo $title;?></h1>\n\n<div style=\"clear:both\"></div>\n\n<div class=\"questionsview_userbox\">\n<?php echo getUser($userid);?>\n</div>\n\n<div class=\"questionsview_details\"><span style=\"color:#999\"><?php echo timeAgo(strtotime($created));?></span></div>\n\n<?php if ($userid == $_SESSION['userid']):?>\n<div class=\"questionsview_options\"><a href=\"<?php echo basePath();?>/questions/edit/<?php echo $id;?>\">edit</a></div>\n<?php endif;?>\n \n\n<div class=\"questionsview_question\" id=\"q<?php echo $id;?>\">\n<div class=\"questionsview_rating\">\n<div class=\"questionsview_box\"><div class=\"questionsview_up<?php if($pvote) { echo \" voteselected\"; }?>\">˄</div><div class=\"questionsview_vote\"><?php echo $votes;?></div><div class=\"questionsview_down<?php if($nvote) { echo \" voteselected\"; }?>\">˅</div>\n\n<div class=\"questionsview_fave<?php if($fave) { echo \" voteselected\"; }?>\">★</div>\n</div>\n</div>\n\n<div class=\"questionsview_questiondescription\">\n\n\n<div class=\"markdown\"><?php echo $description;?></div>\n\n<?php if (!empty($link)):?>\n<p><br/><?php echo $link;?> <?php if ($cache):?><em><a href=\"<?php echo basePath();?>/questions/cache/<?php echo $id;?>\" target=\"_blank\">(view cache)</a></em><?php endif;?></p>\n<?php endif;?>\n\n\n<ul class=\"holder noborder\">\n<?php foreach ($tags as $tag):?>\n<li class=\"bit-box nopadding\"><a href=\"<?php echo basePath();?>/questions?tag=<?php echo $tag;?>\"><?php echo $tag;?></a></li>\n<?php endforeach;?>\n</ul>\n\n\n<div class=\"comments\">\n<div id=\"comments_q<?php echo $id;?>\">\n\n<?php foreach($comments as $comment):?>\n<div class=\"comment\">\n<div class=\"comment_text\"><?php echo $comment['comment'];?> - <a href=\"<?php echo basePath();?>/users/<?php echo $comment['userid'];?>/<?php echo $comment['username'];?>\"><?php echo $comment['username'];?></a></div>\n\n<div class=\"commentdel\" id=\"commentdel_<?php echo $comment['id'];?>\"><?php if ($comment['userid'] == $_SESSION['userid']) { echo \"x\"; }?></div>\n\n<div class=\"commentfave <?php if ($comment['voted'] > 0) { echo \"voteselected\"; }?>\" id=\"commentfave_<?php echo $comment['id'];?>\">♥</div><div class=\"commentfavevotes\"><?php if ($comment['votes'] != 0) { echo $comment['votes']; }?></div>\n<div style=\"clear:both;\"></div>\n</div>\n<?php endforeach;?>\n\n</div>\n<div id=\"comment_q<?php echo $id;?>\" class=\"commentsadd\">\n<span style=\"float:left\"><a href=\"javascript:void(0)\" onclick=\"javascript:comment('q<?php echo $id;?>')\">Add comment</a></span>\n\n<span style=\"float:right\" style=\"display:none\" class=\"viewallcomments\"><a href=\"javascript:void(0)\" onclick=\"javascript:viewallcomments('q<?php echo $id;?>')\"></a></span>\n</div>\n</div>\n<div style=\"height:30px;\"></div>\n</div>\n\n\n\n<div style=\"clear:both\"></div>\n</div>\n\n\n<?php if ($answerscount != 0):?>\n\n<div class=\"toppagination\">\n<div style=\"clear:both\"></div>\n<?php if($answerscount > ANSWERS_PER_PAGE):?>\n<div class=\"pagination\" style=\"margin-left:5px;\"><?php echo $pagination;?></div>\n<?php endif;?>\n<div class=\"pagination\" style=\"margin-left:5px;float:right;margin-right:5px;\"><?php echo $orderOptions;?></div>\n<div style=\"clear:both\"></div>\n</div>\n\n<div>\n<div style=\"float:left\"><h2><?php echo $answerscount;?><?php if ($kb):?> Comments<?php else:?> Answers<?php endif;?></h2></div>\n\n<div style=\"clear:both\"></div>\n</div>\n\n\n\n\n<?php foreach ($answers as $answer):?>\n\n<div class=\"questionsview_userbox\">\n<?php echo getUser($answer['userid']);?>\n</div>\n\n<div class=\"questionsview_details\"><span style=\"color:#999\"><?php echo timeAgo(strtotime($answer['created']));?></span>\n</div>\n\n<?php if ($answer['userid'] == $_SESSION['userid']):?>\n<div class=\"questionsview_options\"><a href=\"<?php echo basePath();?>/answers/edit/<?php echo $answer['id'];?>\">edit</a></div>\n<?php endif;?>\n\n<?php if(!$kb):?>\n<?php if($answer['accepted']):?>\n<div class=\"questionsview_accepted\">\nAccepted Answer</span>\n</div>\n<?php elseif($userid == $_SESSION['userid']):?>\n<div class=\"questionsview_accept\">\n<a href=\"<?php echo basePath();?>/answers/accept?id=<?php echo $answer['id'];?>\">Accept this answer</a>\n</div>\n<?php endif;?>\n<?php endif;?>\n\n<div class=\"questionsview_answer\" id=\"a<?php echo $answer['id'];?>\">\n<div class=\"questionsview_rating\">\n<div class=\"questionsview_box\"><div class=\"questionsview_up<?php if($answer['pvote']) { echo \" voteselected\"; }?>\">˄</div><div class=\"questionsview_vote\"><?php echo $answer['votes'];?></div><div class=\"questionsview_down<?php if($answer['nvote']) { echo \" voteselected\"; }?>\">˅</div>\n</div>\n\n\n\n</div>\n<div class=\"questionsview_answerdescription\">\n<div class=\"markdown\"><?php echo $answer['description'];?></div>\n\n<div class=\"comments\">\n<div id=\"comments_a<?php echo $answer['id'];?>\">\n\n<?php foreach($answer['comments'] as $comment):?>\n<div class=\"comment\">\n<div class=\"comment_text\"><?php echo $comment['comment'];?> - <a href=\"<?php echo basePath();?>/users/<?php echo $comment['userid'];?>/<?php echo $comment['username'];?>\"><?php echo $comment['username'];?></a></div>\n\n<div class=\"commentdel\" id=\"commentdel_<?php echo $comment['id'];?>\"><?php if ($comment['userid'] == $_SESSION['userid']) { echo \"x\"; }?></div>\n\n<div class=\"commentfave <?php if ($comment['voted'] > 0) { echo \"voteselected\"; }?>\" id=\"commentfave_<?php echo $comment['id'];?>\">♥</div><div class=\"commentfavevotes\"><?php if ($comment['votes'] != 0) { echo $comment['votes']; }?></div>\n<div style=\"clear:both;\"></div>\n</div>\n<?php endforeach;?>\n\n\n\n</div>\n<div id=\"comment_a<?php echo $answer['id'];?>\" class=\"commentsadd\">\n\n<span style=\"float:left\"><a href=\"javascript:void(0)\" onclick=\"javascript:comment('a<?php echo $answer['id'];?>')\">Add comment</a></span>\n<span style=\"float:right\" style=\"display:none\" class=\"viewallcomments\"><a href=\"javascript:void(0)\" onclick=\"javascript:viewallcomments('a<?php echo $answer['id'];?>')\"></a></span>\n\n</div>\n</div>\n\n<div style=\"height:20px;\"></div>\n</div>\n\n\n<div style=\"clear:both;\"></div>\n</div>\n<?php endforeach;?>\n\n<div class=\"bottompagination\">\n<div style=\"clear:both\"></div>\n<?php if($answerscount > ANSWERS_PER_PAGE):?>\n<div class=\"pagination\" style=\"margin-left:5px;\"><?php echo $pagination;?></div>\n<?php endif;?>\n<div class=\"pagination\" style=\"margin-left:5px;float:right;margin-right:5px;\"><?php echo $orderOptions;?></div>\n<div style=\"clear:both\"></div>\n</div>\n\n<?php else:?><h3><?php if ($kb):?>No comments on this article as yet.<?php else:?>No answers as yet. Be the first to write an answer.<?php endif;?></h3><?php endif;?>\n\n<?php if ($_SESSION['userid'] != ''):?>\n<div class=\"questionsview_form\">\n<form action=\"<?php echo generateLink(\"answers\",\"post\");?>\" method=\"post\"  onsubmit=\"javascript:return cform();\">\n\n<h2 style=\"padding-top:0px;padding-bottom:16px;\"><?php if ($kb):?>Add a comment<?php else:?>Answer Question<?php endif;?></h2>\n\n<div id=\"wmd-editor\" class=\"wmd-panel\">\n<div id=\"wmd-button-bar\"></div>\n<textarea id=\"wmd-input\" name=\"description\" ></textarea>\n</div>\n<div id=\"wmd-preview\" class=\"markdown\"></div>\n\n<br/><br/>\n<input type=\"hidden\" name=\"questionid\" value=\"<?php echo $id;?>\">\n<input type=\"submit\" value=\"Answer Question\" class=\"button\">\n</form>\n</div>\n<?php endif;?>"
  },
  {
    "path": "views/tags/index.php",
    "content": "<h1><?php echo $count;?> Tags</h1>\n\n<div style=\"clear:both\"></div>\n\n<div class=\"tags_list\">\n<ul class=\"holder noborder\">\n<?php foreach ($tags as $tag):?>\n<li class=\"bit-box nopadding\"><a href=\"<?php echo basePath();?>/questions?tag=<?php echo $tag['tag'];?>\"><?php echo $tag['tag'];?></a> x <?php echo $tag['count'];?></li>\n<?php endforeach;?>\n</ul>\n</div>"
  },
  {
    "path": "views/users/edit.php",
    "content": "\n<script>\nfunction cform() {\n\tvar name = '';\n\tvar email = '';\n\tvar password = '';\n\tname = $(\"#name\").val();\n\temail = $(\"#email\").val();\n\tpassword = $(\"#password\").val();\n \n\n\tif (name.length < 1 || name.length > 100) {\n\t\t$(\"#name\").addClass('textalert');\n\t\t$.fancyalert('Please enter your name');\n\t\t$(\"#name\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#name\").removeClass('textalert');\n\t}\n\t\n\tif (email.length < 1 || email.length > 100) {\n\t\t$(\"#email\").addClass('textalert');\n\t\t$.fancyalert('Please enter your e-mail');\n\t\t$(\"#email\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#email\").removeClass('textalert');\n\t}\n\n\t\n\treturn true;\n}\n</script>\n\n<form action=\"<?php echo generateLink(\"users\",\"update\");?>\" method=\"post\" onsubmit=\"javascript:return cform();\">\n\n<h1>Edit Profile</h1>\n\n<h3>Name</h3>\n<input type=\"textbox\" class=\"textbox\" name=\"name\" id=\"name\" value=\"<?php echo $user['name'];?>\"/><br/>\n\n<h3>E-mail</h3>\n<input type=\"textbox\" class=\"textbox\" name=\"email\" id=\"email\" value=\"<?php echo $user['email'];?>\"/><br/>\n\n<h3>Password <span style=\"font-size:10px\">(Leave blank if you do not want to update)</span></h3> \n<input type=\"password\" class=\"textbox\" name=\"password\" id=\"password\" value=\"\"/></select>\n\n<br/><br/>\n<input type=\"submit\" value=\"Update Profile\" class=\"button\">\n</form>"
  },
  {
    "path": "views/users/index.php",
    "content": "<h1><?php echo $count;?> Users</h1>\n\n<div style=\"clear:both\"></div>\n\n<div class=\"tags_list\">\n<ul class=\"holder noborder\">\n<?php foreach ($users as $user):?>\n<li class=\"bit-box nopadding\"><a href=\"<?php echo basePath();?>/users/view/<?php echo $user['id'];?>/<?php echo createSlug($user['name']);?>\"><?php echo $user['name'];?></a> <?php echo $user['points'];?></li>\n<?php endforeach;?>\n</ul>\n</div>"
  },
  {
    "path": "views/users/login.php",
    "content": "<form action=\"<?php echo generateLink(\"users\",\"validate\");?>\" method=\"post\">\n\n<h1>Login</h1>\n\n<h3>E-mail</h3>\n<input type=\"textbox\" class=\"textbox\" name=\"email\" id=\"email\" style=\"width:300px;\"/><br/>\n\n<h3>Password</h3>\n<input type=\"password\" class=\"textbox\" name=\"password\" id=\"password\" style=\"width:300px;\"/></select>\n\n<br/><br/>\n<input type=\"submit\" value=\"Login\" class=\"button\">\n<input type=\"hidden\" name=\"returnurl\" value=\"<?php if (!empty($link)) {echo $link;}?>\">\n</form>"
  },
  {
    "path": "views/users/logout.php",
    "content": "<h1>You have successfully logged out</h1>\n<script>setTimeout(\"location.href = '<?php echo basePath();?>'\",3000);</script>"
  },
  {
    "path": "views/users/register.php",
    "content": "\n<script>\nfunction cform() {\n\tvar name = '';\n\tvar email = '';\n\tvar password = '';\n\tname = $(\"#name\").val();\n\temail = $(\"#email\").val();\n\tpassword = $(\"#password\").val();\n \n\n\tif (name.length < 1 || name.length > 100) {\n\t\t$(\"#name\").addClass('textalert');\n\t\t$.fancyalert('Please enter your name');\n\t\t$(\"#name\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#name\").removeClass('textalert');\n\t}\n\t\n\tif (email.length < 1 || email.length > 100) {\n\t\t$(\"#email\").addClass('textalert');\n\t\t$.fancyalert('Please enter your e-mail');\n\t\t$(\"#email\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#email\").removeClass('textalert');\n\t}\n\n\t\n\tif (password.length < 1 || password.length > 100) {\n\t\t$(\"#namepassword\").addClass('textalert');\n\t\t$.fancyalert('Please enter your password');\n\t\t$(\"#password\").focus();\n\t\treturn false;\n\t} else {\n\t\t$(\"#password\").removeClass('textalert');\n\t}\n\n\n\treturn true;\n}\n</script>\n\n<form action=\"<?php echo generateLink(\"users\",\"create\");?>\" method=\"post\" onsubmit=\"javascript:return cform();\">\n\n<h1>Register</h1>\n\n<h3>Name</h3>\n<input type=\"textbox\" placeholder=\"Your diplayname\" class=\"textbox\" name=\"name\" id=\"name\"/><br/>\n\n<h3>E-mail</h3>\n<input type=\"textbox\" placeholder=\"A valid email address (for Gravatar)\" class=\"textbox\" name=\"email\" id=\"email\"/><br/>\n\n<h3>Password</h3>\n<input type=\"password\" class=\"textbox\" name=\"password\" id=\"password\"/></select>\n\n<br/><br/>\n<input type=\"submit\" value=\"Register\" class=\"button\">\n</form>"
  },
  {
    "path": "views/users/view.php",
    "content": "<h1><?php echo $user['name'];?></h1>\n\n<h3>Points: <?php echo $user['points'];?></h3>\n"
  },
  {
    "path": "web.config",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n    <system.webServer>\n        <rewrite>\n            <rules>\n                <rule name=\"Imported Rule 1\" stopProcessing=\"true\">\n                    <match url=\"^(.*)$\" ignoreCase=\"false\" />\n                    <conditions logicalGrouping=\"MatchAll\">\n                        <add input=\"{REQUEST_FILENAME}\" matchType=\"IsDirectory\" ignoreCase=\"false\" negate=\"true\" />\n                        <add input=\"{REQUEST_FILENAME}\" matchType=\"IsFile\" ignoreCase=\"false\" negate=\"true\" />\n                    </conditions>\n                    <action type=\"Rewrite\" url=\"index.php/{R:1}\" appendQueryString=\"true\" />\n                </rule>\n            </rules>\n        </rewrite>\n    </system.webServer>\n</configuration>\n"
  }
]