PageRenderTime 50ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/gforge/plugins/wiki/www/lib/stdlib.php

https://github.com/neymanna/fusionforge
PHP | 2469 lines | 1275 code | 160 blank | 1034 comment | 259 complexity | 957181b75e6a602c7a6739ed0367d3d8 MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. <?php //rcs_id('$Id: stdlib.php,v 1.251 2006/03/19 15:01:00 rurban Exp $');
  2. /*
  3. Copyright 1999,2000,2001,2002,2004,2005 $ThePhpWikiProgrammingTeam
  4. This file is part of PhpWiki.
  5. PhpWiki is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. PhpWiki is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with PhpWiki; if not, write to the Free Software
  15. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. */
  17. /*
  18. Standard functions for Wiki functionality
  19. WikiURL ($pagename, $args, $get_abs_url)
  20. AbsoluteURL ($url)
  21. IconForLink ($protocol_or_url)
  22. PossiblyGlueIconToText($proto_or_url, $text)
  23. IsSafeURL($url)
  24. LinkURL ($url, $linktext)
  25. LinkImage ($url, $alt)
  26. SplitQueryArgs ($query_args)
  27. LinkPhpwikiURL ($url, $text, $basepage)
  28. ConvertOldMarkup ($content, $markup_type = "block")
  29. MangleXmlIdentifier($str)
  30. UnMangleXmlIdentifier($str)
  31. class Stack { push($item), pop(), cnt(), top() }
  32. class Alert { show() }
  33. class WikiPageName {getParent(),isValid(),getWarnings() }
  34. expand_tabs($str, $tab_width = 8)
  35. SplitPagename ($page)
  36. NoSuchRevision ($request, $page, $version)
  37. TimezoneOffset ($time, $no_colon)
  38. Iso8601DateTime ($time)
  39. Rfc2822DateTime ($time)
  40. ParseRfc1123DateTime ($timestr)
  41. CTime ($time)
  42. ByteFormatter ($bytes = 0, $longformat = false)
  43. __printf ($fmt)
  44. __sprintf ($fmt)
  45. __vsprintf ($fmt, $args)
  46. file_mtime ($filename)
  47. sort_file_mtime ($a, $b)
  48. class fileSet {fileSet($directory, $filepattern = false),
  49. getFiles($exclude=false, $sortby=false, $limit=false) }
  50. class ListRegexExpand { listMatchCallback($item, $key),
  51. expandRegex ($index, &$pages) }
  52. glob_to_pcre ($glob)
  53. glob_match ($glob, $against, $case_sensitive = true)
  54. explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
  55. explodePageList ($input, $perm = false)
  56. isa ($object, $class)
  57. can ($object, $method)
  58. function_usable ($function_name)
  59. wikihash ($x)
  60. better_srand ($seed = '')
  61. count_all ($arg)
  62. isSubPage ($pagename)
  63. subPageSlice ($pagename, $pos)
  64. phpwiki_version ()
  65. isWikiWord ($word)
  66. obj2hash ($obj, $exclude = false, $fields = false)
  67. isUtf8String ($s)
  68. fixTitleEncoding ($s)
  69. url_get_contents ($uri)
  70. GenerateId ($name)
  71. firstNWordsOfContent ($n, $content)
  72. extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
  73. isExternalReferrer()
  74. function: LinkInterWikiLink($link, $linktext)
  75. moved to: lib/interwiki.php
  76. function: linkExistingWikiWord($wikiword, $linktext, $version)
  77. moved to: lib/Theme.php
  78. function: LinkUnknownWikiWord($wikiword, $linktext)
  79. moved to: lib/Theme.php
  80. function: UpdateRecentChanges($dbi, $pagename, $isnewpage)
  81. gone see: lib/plugin/RecentChanges.php
  82. */
  83. if (defined('_PHPWIKI_STDLIB_LOADED')) return;
  84. else define('_PHPWIKI_STDLIB_LOADED', true);
  85. define('MAX_PAGENAME_LENGTH', 100);
  86. /**
  87. * Convert string to a valid XML identifier.
  88. *
  89. * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
  90. *
  91. * We would like to have, e.g. named anchors within wiki pages
  92. * names like "Table of Contents" --- clearly not a valid XML
  93. * fragment identifier.
  94. *
  95. * This function implements a one-to-one map from {any string}
  96. * to {valid XML identifiers}.
  97. *
  98. * It does this by
  99. * converting all bytes not in [A-Za-z0-9:_-],
  100. * and any leading byte not in [A-Za-z] to 'xbb.',
  101. * where 'bb' is the hexadecimal representation of the
  102. * character.
  103. *
  104. * As a special case, the empty string is converted to 'empty.'
  105. *
  106. * @param string $str
  107. * @return string
  108. */
  109. function MangleXmlIdentifier($str) {
  110. if (!$str)
  111. return 'empty.';
  112. return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
  113. "'x' . sprintf('%02x', ord('\\0')) . '.'",
  114. $str);
  115. }
  116. function UnMangleXmlIdentifier($str) {
  117. if ($str == 'empty.')
  118. return '';
  119. return preg_replace('/x(\w\w)\./e',
  120. "sprintf('%c', hex('\\0'))",
  121. $str);
  122. }
  123. /**
  124. * Returns a name for the WIKI_ID cookie that should be unique on the host.
  125. * But for it to be unique you must have set a unique WIKI_NAME in your
  126. * configuration file.
  127. * @return string The name of the WIKI_ID cookie to use for this wiki.
  128. */
  129. function GetCookieName() {
  130. return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
  131. }
  132. /**
  133. * Generates a valid URL for a given Wiki pagename.
  134. * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
  135. * If a WikiDB_Page object function will extract the name to link to.
  136. * If a WikiDB_PageRevision object function will extract the name to link to.
  137. * @param array $args
  138. * @param boolean $get_abs_url Default value is false.
  139. * @return string The absolute URL to the page passed as $pagename.
  140. */
  141. function WikiURL($pagename, $args = '', $get_abs_url = false) {
  142. $anchor = false;
  143. if (is_object($pagename)) {
  144. if (isa($pagename, 'WikiDB_Page')) {
  145. $pagename = $pagename->getName();
  146. }
  147. elseif (isa($pagename, 'WikiDB_PageRevision')) {
  148. $page = $pagename->getPage();
  149. $args['version'] = $pagename->getVersion();
  150. $pagename = $page->getName();
  151. }
  152. elseif (isa($pagename, 'WikiPageName')) {
  153. $anchor = $pagename->anchor;
  154. $pagename = $pagename->name;
  155. } else { // php5
  156. $anchor = $pagename->anchor;
  157. $pagename = $pagename->name;
  158. }
  159. }
  160. if (!$get_abs_url and DEBUG and $GLOBALS['request']->getArg('start_debug')) {
  161. if (!$args)
  162. $args = 'start_debug=' . $GLOBALS['request']->getArg('start_debug');
  163. elseif (is_array($args))
  164. $args['start_debug'] = $GLOBALS['request']->getArg('start_debug');
  165. else
  166. $args .= '&amp;start_debug=' . $GLOBALS['request']->getArg('start_debug');
  167. }
  168. if (is_array($args)) {
  169. $enc_args = array();
  170. foreach ($args as $key => $val) {
  171. // avoid default args
  172. if (USE_PATH_INFO and $key == 'pagename')
  173. ;
  174. elseif ($key == 'action' and $val == 'browse')
  175. ;
  176. elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
  177. $enc_args[] = urlencode($key) . '=' . urlencode($val);
  178. }
  179. $args = join('&', $enc_args);
  180. }
  181. if (USE_PATH_INFO or !empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX)) {
  182. $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
  183. $url = $url . preg_replace('/%2f/i', '/', rawurlencode($pagename));
  184. if (!empty($GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX))
  185. $url .= $GLOBALS['WikiTheme']->HTML_DUMP_SUFFIX;
  186. if ($args)
  187. $url .= "?$args";
  188. }
  189. else {
  190. $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
  191. $url .= "?pagename=" . rawurlencode($pagename);
  192. if ($args)
  193. $url .= "&$args";
  194. }
  195. if ($anchor)
  196. $url .= "#" . MangleXmlIdentifier($anchor);
  197. return $url;
  198. }
  199. /** Convert relative URL to absolute URL.
  200. *
  201. * This converts a relative URL to one of PhpWiki's support files
  202. * to an absolute one.
  203. *
  204. * @param string $url
  205. * @return string Absolute URL
  206. */
  207. function AbsoluteURL ($url) {
  208. if (preg_match('/^https?:/', $url))
  209. return $url;
  210. if ($url[0] != '/') {
  211. $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
  212. while ($base != '/' and substr($url, 0, 3) == "../") {
  213. $url = substr($url, 3);
  214. $base = dirname($base);
  215. }
  216. if ($base != '/')
  217. $base .= '/';
  218. $url = $base . $url;
  219. }
  220. return SERVER_URL . $url;
  221. }
  222. function DataURL ($url) {
  223. if (preg_match('/^https?:/', $url))
  224. return $url;
  225. $url = NormalizeWebFileName($url);
  226. if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
  227. $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
  228. return AbsoluteURL($url);
  229. }
  230. /**
  231. * Generates icon in front of links.
  232. *
  233. * @param string $protocol_or_url URL or protocol to determine which icon to use.
  234. *
  235. * @return HtmlElement HtmlElement object that contains data to create img link to
  236. * icon for use with url or protocol passed to the function. False if no img to be
  237. * displayed.
  238. */
  239. function IconForLink($protocol_or_url) {
  240. global $WikiTheme;
  241. if (0 and $filename_suffix == false) {
  242. // display apache style icon for file type instead of protocol icon
  243. // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
  244. // - document: html, htm, text, txt, rtf, pdf, doc
  245. // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
  246. // - audio: mp3,mp2,aiff,aif,au
  247. // - multimedia: mpeg,mpg,mov,qt
  248. } else {
  249. list ($proto) = explode(':', $protocol_or_url, 2);
  250. $src = $WikiTheme->getLinkIconURL($proto);
  251. if ($src)
  252. return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
  253. else
  254. return false;
  255. }
  256. }
  257. /**
  258. * Glue icon in front of or after text.
  259. * Pref: 'noLinkIcons' - ignore icon if set
  260. * Theme: 'LinkIcons' - 'yes' at front
  261. * - 'no' display no icon
  262. * - 'front' display at left
  263. * - 'after' display at right
  264. *
  265. * @param string $protocol_or_url Protocol or URL. Used to determine the
  266. * proper icon.
  267. * @param string $text The text.
  268. * @return XmlContent.
  269. */
  270. function PossiblyGlueIconToText($proto_or_url, $text) {
  271. global $request, $WikiTheme;
  272. if ($request->getPref('noLinkIcons'))
  273. return $text;
  274. $icon = IconForLink($proto_or_url);
  275. if (!$icon)
  276. return $text;
  277. if ($where = $WikiTheme->getLinkIconAttr()) {
  278. if ($where == 'no') return $text;
  279. if ($where != 'after') $where = 'front';
  280. } else {
  281. $where = 'front';
  282. }
  283. if ($where == 'after') {
  284. // span the icon only to the last word (tie them together),
  285. // to let the previous words wrap on line breaks.
  286. if (!is_object($text)) {
  287. preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
  288. list (, $prefix, $last_word) = $m;
  289. }
  290. else {
  291. $last_word = $text;
  292. $prefix = false;
  293. }
  294. $text = HTML::span(array('style' => 'white-space: nowrap'),
  295. $last_word, HTML::Raw('&nbsp;'), $icon);
  296. if ($prefix)
  297. $text = HTML($prefix, $text);
  298. return $text;
  299. }
  300. // span the icon only to the first word (tie them together),
  301. // to let the next words wrap on line breaks
  302. if (!is_object($text)) {
  303. preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
  304. list (, $first_word, $tail) = $m;
  305. }
  306. else {
  307. $first_word = $text;
  308. $tail = false;
  309. }
  310. $text = HTML::span(array('style' => 'white-space: nowrap'),
  311. $icon, $first_word);
  312. if ($tail)
  313. $text = HTML($text, $tail);
  314. return $text;
  315. }
  316. /**
  317. * Determines if the url passed to function is safe, by detecting if the characters
  318. * '<', '>', or '"' are present.
  319. * Check against their urlencoded values also.
  320. *
  321. * @param string $url URL to check for unsafe characters.
  322. * @return boolean True if same, false else.
  323. */
  324. function IsSafeURL($url) {
  325. return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
  326. }
  327. /**
  328. * Generates an HtmlElement object to store data for a link.
  329. *
  330. * @param string $url URL that the link will point to.
  331. * @param string $linktext Text to be displayed as link.
  332. * @return HtmlElement HtmlElement object that contains data to construct an html link.
  333. */
  334. function LinkURL($url, $linktext = '') {
  335. // FIXME: Is this needed (or sufficient?)
  336. if(! IsSafeURL($url)) {
  337. $link = HTML::strong(HTML::u(array('class' => 'baduri'),
  338. _("BAD URL -- remove all of <, >, \"")));
  339. }
  340. else {
  341. if (!$linktext)
  342. $linktext = preg_replace("/mailto:/A", "", $url);
  343. $args = array('href' => $url);
  344. if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
  345. $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
  346. $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
  347. }
  348. $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
  349. return $link;
  350. }
  351. /**
  352. * Inline Images
  353. *
  354. * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
  355. * Disallows sizes which are too small.
  356. * Spammers may use such (typically invisible) image attributes to higher their GoogleRank.
  357. *
  358. * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
  359. */
  360. function LinkImage($url, $alt = false) {
  361. $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
  362. // Disallow tags in img src urls. Typical CSS attacks.
  363. // FIXME: Is this needed (or sufficient?)
  364. if(! IsSafeURL($url)) {
  365. $link = HTML::strong(HTML::u(array('class' => 'baduri'),
  366. _("BAD URL -- remove all of <, >, \"")));
  367. } else {
  368. // support new syntax: [image.jpg size=50% border=n]
  369. if (!preg_match("/\.(".$force_img.")/i", $url))
  370. $ori_url = $url;
  371. $arr = split(' ',$url);
  372. if (count($arr) > 1) {
  373. $url = $arr[0];
  374. }
  375. if (empty($alt)) $alt = basename($url);
  376. $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
  377. if (count($arr) > 1) {
  378. array_shift($arr);
  379. foreach ($arr as $attr) {
  380. if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
  381. $link->setAttr('width',$m[1]);
  382. $link->setAttr('height',$m[1]);
  383. }
  384. if (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
  385. $link->setAttr('width',$m[1]);
  386. $link->setAttr('height',$m[2]);
  387. }
  388. if (preg_match('/^border=(\d+)$/',$attr,$m))
  389. $link->setAttr('border',$m[1]);
  390. if (preg_match('/^align=(\w+)$/',$attr,$m))
  391. $link->setAttr('align',$m[1]);
  392. if (preg_match('/^hspace=(\d+)$/',$attr,$m))
  393. $link->setAttr('hspace',$m[1]);
  394. if (preg_match('/^vspace=(\d+)$/',$attr,$m))
  395. $link->setAttr('vspace',$m[1]);
  396. }
  397. }
  398. // Check width and height as spam countermeasure
  399. if (($width = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
  400. //$width = (int) $width; // px or % or other suffix
  401. //$height = (int) $height;
  402. if (($width < 3 and $height < 10) or
  403. ($height < 3 and $width < 20) or
  404. ($height < 7 and $width < 7))
  405. {
  406. trigger_error(_("Invalid image size"), E_USER_WARNING);
  407. return '';
  408. }
  409. } else {
  410. // Older php versions crash here with certain png's:
  411. // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
  412. // http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
  413. // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
  414. if (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
  415. ; // it's safe to assume that this will fail.
  416. elseif (!DISABLE_GETIMAGESIZE and ($size = @getimagesize($url))) {
  417. $width = $size[0];
  418. $height = $size[1];
  419. if (($width < 3 and $height < 10)
  420. or ($height < 3 and $width < 20)
  421. or ($height < 7 and $width < 7))
  422. {
  423. trigger_error(_("Invalid image size"), E_USER_WARNING);
  424. return '';
  425. }
  426. }
  427. }
  428. }
  429. $link->setAttr('class', 'inlineimage');
  430. /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
  431. * png|jpg|gif|jpeg|bmp|pl|cgi
  432. * Note: Allow cgi's (pl,cgi) returning images.
  433. */
  434. if (!preg_match("/\.(".$force_img.")/i", $url)) {
  435. //HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
  436. // => HTML::object(array('src' => $url)) ...;
  437. return ImgObject($link, $ori_url);
  438. }
  439. return $link;
  440. }
  441. /**
  442. * <object> / <embed> tags instead of <img> for all non-image extensions allowed via INLINE_IMAGES
  443. * Called by LinkImage(), not directly.
  444. * Syntax: [image.svg size=50% border=n align= hspace= vspace= width= height=]
  445. * $alt may be an alternate img
  446. * TODO: Need to unify with WikiPluginCached::embedObject()
  447. *
  448. * Note that Safari 1.0 will crash with <object>, so use only <embed>
  449. * http://www.alleged.org.uk/pdc/2002/svg-object.html
  450. */
  451. function ImgObject($img, $url) {
  452. // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
  453. $args = split(' ', $url);
  454. if (count($args) >= 1) {
  455. $url = array_shift($args);
  456. foreach ($args as $attr) {
  457. if (preg_match('/^type=(\S+)$/',$attr,$m))
  458. $img->setAttr('type', $m[1]);
  459. if (preg_match('/^data=(\S+)$/',$attr,$m))
  460. $img->setAttr('data', $m[1]);
  461. }
  462. }
  463. $type = $img->getAttr('type');
  464. if (!$type) {
  465. // TODO: map extension to mime-types if type is not given and php < 4.3
  466. if (function_exists('mime_content_type'))
  467. $type = mime_content_type($url);
  468. }
  469. $link = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)));
  470. $link->setAttr('class', 'inlineobject');
  471. if (isBrowserSafari()) {
  472. return HTML::embed($link->_attr);
  473. }
  474. $link->pushContent(HTML::embed($link->_attr));
  475. return $link;
  476. }
  477. class Stack {
  478. // var in php5 deprecated
  479. function Stack() {
  480. $this->items = array();
  481. $this->size = 0;
  482. }
  483. function push($item) {
  484. $this->items[$this->size] = $item;
  485. $this->size++;
  486. return true;
  487. }
  488. function pop() {
  489. if ($this->size == 0) {
  490. return false; // stack is empty
  491. }
  492. $this->size--;
  493. return $this->items[$this->size];
  494. }
  495. function cnt() {
  496. return $this->size;
  497. }
  498. function top() {
  499. if($this->size)
  500. return $this->items[$this->size - 1];
  501. else
  502. return '';
  503. }
  504. }
  505. // end class definition
  506. function SplitQueryArgs ($query_args = '')
  507. {
  508. // FIXME: use the arg-seperator which might not be &
  509. $split_args = split('&', $query_args);
  510. $args = array();
  511. while (list($key, $val) = each($split_args))
  512. if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
  513. $args[$m[1]] = $m[2];
  514. return $args;
  515. }
  516. function LinkPhpwikiURL($url, $text = '', $basepage = false) {
  517. $args = array();
  518. if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
  519. return HTML::strong(array('class' => 'rawurl'),
  520. HTML::u(array('class' => 'baduri'),
  521. _("BAD phpwiki: URL")));
  522. }
  523. if ($m[1])
  524. $pagename = urldecode($m[1]);
  525. $qargs = $m[2];
  526. if (empty($pagename) &&
  527. preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
  528. // Convert old style links (to not break diff links in
  529. // RecentChanges).
  530. $pagename = urldecode($m[2]);
  531. $args = array("action" => $m[1]);
  532. }
  533. else {
  534. $args = SplitQueryArgs($qargs);
  535. }
  536. if (empty($pagename))
  537. $pagename = $GLOBALS['request']->getArg('pagename');
  538. if (isset($args['action']) && $args['action'] == 'browse')
  539. unset($args['action']);
  540. /*FIXME:
  541. if (empty($args['action']))
  542. $class = 'wikilink';
  543. else if (is_safe_action($args['action']))
  544. $class = 'wikiaction';
  545. */
  546. if (empty($args['action']) || is_safe_action($args['action']))
  547. $class = 'wikiaction';
  548. else {
  549. // Don't allow administrative links on unlocked pages.
  550. $dbi = $GLOBALS['request']->getDbh();
  551. $page = $dbi->getPage($basepage ? $basepage : $pagename);
  552. if (!$page->get('locked'))
  553. return HTML::span(array('class' => 'wikiunsafe'),
  554. HTML::u(_("Lock page to enable link")));
  555. $class = 'wikiadmin';
  556. }
  557. if (!$text)
  558. $text = HTML::span(array('class' => 'rawurl'), $url);
  559. $wikipage = new WikiPageName($pagename);
  560. if (!$wikipage->isValid()) {
  561. global $WikiTheme;
  562. return $WikiTheme->linkBadWikiWord($wikipage, $url);
  563. }
  564. return HTML::a(array('href' => WikiURL($pagename, $args),
  565. 'class' => $class),
  566. $text);
  567. }
  568. /**
  569. * A class to assist in parsing wiki pagenames.
  570. *
  571. * Now with subpages and anchors, parsing and passing around
  572. * pagenames is more complicated. This should help.
  573. */
  574. class WikiPageName
  575. {
  576. /** Short name for page.
  577. *
  578. * This is the value of $name passed to the constructor.
  579. * (For use, e.g. as a default label for links to the page.)
  580. */
  581. //var $shortName;
  582. /** The full page name.
  583. *
  584. * This is the full name of the page (without anchor).
  585. */
  586. //var $name;
  587. /** The anchor.
  588. *
  589. * This is the referenced anchor within the page, or the empty string.
  590. */
  591. //var $anchor;
  592. /** Constructor
  593. *
  594. * @param mixed $name Page name.
  595. * WikiDB_Page, WikiDB_PageRevision, or string.
  596. * This can be a relative subpage name (like '/SubPage'),
  597. * or can be the empty string to refer to the $basename.
  598. *
  599. * @param string $anchor For links to anchors in page.
  600. *
  601. * @param mixed $basename Page name from which to interpret
  602. * relative or other non-fully-specified page names.
  603. */
  604. function WikiPageName($name, $basename=false, $anchor=false) {
  605. if (is_string($name)) {
  606. $this->shortName = $name;
  607. if (strstr($name, ':')) {
  608. list($moniker, $this->shortName) = split (":", $name, 2);
  609. $map = getInterwikiMap(); // allow overrides to custom maps
  610. if (isset($map->_map[$moniker])) {
  611. $url = $map->_map[$moniker];
  612. if (strstr($url, '%s'))
  613. $url = sprintf($url, $this->shortName);
  614. else
  615. $url .= $this->shortName;
  616. // expand Talk or User, but not to absolute urls!
  617. if (strstr($url, '//')) {
  618. if ($moniker == 'Talk')
  619. $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
  620. elseif ($moniker == 'User')
  621. $name = $name;
  622. } else {
  623. $name = $url;
  624. }
  625. if (strstr($name, '?'))
  626. list($name, $dummy) = split("?", $name, 2);
  627. }
  628. }
  629. // FIXME: We should really fix the cause for "/PageName" in the WikiDB
  630. if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
  631. if ($basename)
  632. $name = $this->_pagename($basename) . $name;
  633. else {
  634. $name = $this->_normalize_bad_pagename($name);
  635. $this->shortName = $name;
  636. }
  637. }
  638. }
  639. else {
  640. $name = $this->_pagename($name);
  641. $this->shortName = $name;
  642. }
  643. $this->name = $this->_check($name);
  644. $this->anchor = (string)$anchor;
  645. }
  646. function getName() {
  647. return $this->name;
  648. }
  649. function getParent() {
  650. $name = $this->name;
  651. if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
  652. return false;
  653. return substr($name, 0, -strlen($tail));
  654. }
  655. function isValid($strict = false) {
  656. if ($strict)
  657. return !isset($this->_errors);
  658. return (is_string($this->name) and $this->name != '');
  659. }
  660. function getWarnings() {
  661. $warnings = array();
  662. if (isset($this->_warnings))
  663. $warnings = array_merge($warnings, $this->_warnings);
  664. if (isset($this->_errors))
  665. $warnings = array_merge($warnings, $this->_errors);
  666. if (!$warnings)
  667. return false;
  668. return sprintf(_("'%s': Bad page name: %s"),
  669. $this->shortName, join(', ', $warnings));
  670. }
  671. function _pagename($page) {
  672. if (isa($page, 'WikiDB_Page'))
  673. return $page->getName();
  674. elseif (isa($page, 'WikiDB_PageRevision'))
  675. return $page->getPageName();
  676. elseif (isa($page, 'WikiPageName'))
  677. return $page->name;
  678. // '0' or e.g. '1984' should be allowed though
  679. if (!is_string($page) and !is_integer($page)) {
  680. trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
  681. $page, gettype($page), get_class($page)),
  682. E_USER_NOTICE);
  683. }
  684. //assert(is_string($page));
  685. return $page;
  686. }
  687. function _normalize_bad_pagename($name) {
  688. trigger_error("Bad pagename: " . $name, E_USER_WARNING);
  689. // Punt... You really shouldn't get here.
  690. if (empty($name)) {
  691. global $request;
  692. return $request->getArg('pagename');
  693. }
  694. assert($name[0] == SUBPAGE_SEPARATOR);
  695. $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
  696. return substr($name, 1);
  697. }
  698. function _check($pagename) {
  699. // Compress internal white-space to single space character.
  700. $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
  701. if ($pagename != $orig)
  702. $this->_warnings[] = _("White space converted to single space");
  703. // Delete any control characters.
  704. if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file') {
  705. $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
  706. if ($pagename != $orig)
  707. $this->_errors[] = _("Control characters not allowed");
  708. }
  709. // Strip leading and trailing white-space.
  710. $pagename = trim($pagename);
  711. $orig = $pagename;
  712. while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
  713. $pagename = substr($pagename, 1);
  714. if ($pagename != $orig)
  715. $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
  716. // ";" is urlencoded, so safe from php arg-delim problems
  717. /*if (strstr($pagename, ';')) {
  718. $this->_warnings[] = _("';' is deprecated");
  719. $pagename = str_replace(';', '', $pagename);
  720. }*/
  721. // not only for SQL, also to restrict url length
  722. if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
  723. $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
  724. $this->_errors[] = _("too long");
  725. }
  726. // disallow some chars only on file and cvs
  727. if ((DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file')
  728. and preg_match('/(:|\.\.)/', $pagename, $m)) {
  729. $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
  730. $pagename = str_replace('..', '', $pagename);
  731. $pagename = str_replace(':', '', $pagename);
  732. }
  733. return $pagename;
  734. }
  735. }
  736. /**
  737. * Convert old page markup to new-style markup.
  738. *
  739. * @param string $text Old-style wiki markup.
  740. *
  741. * @param string $markup_type
  742. * One of: <dl>
  743. * <dt><code>"block"</code> <dd>Convert all markup.
  744. * <dt><code>"inline"</code> <dd>Convert only inline markup.
  745. * <dt><code>"links"</code> <dd>Convert only link markup.
  746. * </dl>
  747. *
  748. * @return string New-style wiki markup.
  749. *
  750. * @bugs Footnotes don't work quite as before (esp if there are
  751. * multiple references to the same footnote. But close enough,
  752. * probably for now....
  753. * @bugs Apache2 and IIS crash with OldTextFormattingRules or
  754. * AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
  755. * It only crashes with CreateToc so far, but other pages (not in pgsrc) are
  756. * also known to crash, even with Apache1.
  757. */
  758. function ConvertOldMarkup ($text, $markup_type = "block") {
  759. static $subs;
  760. static $block_re;
  761. // FIXME:
  762. // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
  763. // AnciennesR%E8glesDeFormatage crashes.
  764. // It only crashes with CreateToc so far, but other pages (not in pgsrc) are
  765. // also known to crash, even with Apache1.
  766. $debug_skip = false;
  767. // I suspect this only to crash with Apache2 and IIS.
  768. if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
  769. and preg_match("/plugin CreateToc/", $text))
  770. {
  771. trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
  772. ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
  773. ._("Skipped."), E_USER_WARNING);
  774. $debug_skip = true;
  775. //if (!DEBUG) return $text;
  776. return $text;
  777. }
  778. if (empty($subs)) {
  779. /*****************************************************************
  780. * Conversions for inline markup:
  781. */
  782. // escape tilde's
  783. $orig[] = '/~/';
  784. $repl[] = '~~';
  785. // escape escaped brackets
  786. $orig[] = '/\[\[/';
  787. $repl[] = '~[';
  788. // change ! escapes to ~'s.
  789. global $WikiNameRegexp, $request;
  790. $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
  791. // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
  792. if (check_php_version(4,3,9)) {
  793. $map = getInterwikiMap();
  794. if ($map_regex = $map->getRegexp())
  795. $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
  796. }
  797. $bang_esc[] = $WikiNameRegexp;
  798. $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
  799. $repl[] = '~\\1';
  800. $subs["links"] = array($orig, $repl);
  801. // Temporarily URL-encode pairs of underscores in links to hide
  802. // them from the re for bold markup.
  803. $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
  804. $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
  805. // Escape '<'s
  806. //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
  807. //$repl[] = '~<';
  808. // Convert footnote references.
  809. $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
  810. $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
  811. // Convert old style emphases to HTML style emphasis.
  812. $orig[] = '/__(.*?)__/';
  813. $repl[] = '<strong>\\1</strong>';
  814. $orig[] = "/''(.*?)''/";
  815. $repl[] = '<em>\\1</em>';
  816. // Escape nestled markup.
  817. $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
  818. $repl[] = '~\\0';
  819. // in old markup headings only allowed at beginning of line
  820. $orig[] = '/!/';
  821. $repl[] = '~!';
  822. // Convert URL-encoded pairs of underscores in links back to
  823. // real underscores after bold markup has been converted.
  824. $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
  825. $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
  826. $subs["inline"] = array($orig, $repl);
  827. /*****************************************************************
  828. * Patterns which match block markup constructs which take
  829. * special handling...
  830. */
  831. // Indented blocks
  832. $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
  833. // Tables
  834. $blockpats[] = '\|(?:.*\n\|)*';
  835. // List items
  836. $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
  837. // Footnote definitions
  838. $blockpats[] = '\[\s*(\d+)\s*\]';
  839. if (!$debug_skip) {
  840. // Plugins
  841. $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
  842. }
  843. // Section Title
  844. $blockpats[] = '!{1,3}[^!]';
  845. /*
  846. removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
  847. this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
  848. */
  849. $block_re = ( '/\A((?:.|\n)*?)(^(?:'
  850. . join("|", $blockpats)
  851. . ').*$)\n?/m' );
  852. }
  853. if ($markup_type != "block") {
  854. list ($orig, $repl) = $subs[$markup_type];
  855. return preg_replace($orig, $repl, $text);
  856. }
  857. else {
  858. list ($orig, $repl) = $subs['inline'];
  859. $out = '';
  860. //FIXME:
  861. // php crashes here in the 2nd paragraph of OldTextFormattingRules,
  862. // AnciennesR%E8glesDeFormatage and more
  863. // See http://www.pcre.org/pcre.txt LIMITATIONS
  864. while (preg_match($block_re, $text, $m)) {
  865. $text = substr($text, strlen($m[0]));
  866. list (,$leading_text, $block) = $m;
  867. $suffix = "\n";
  868. if (strchr(" \t", $block[0])) {
  869. // Indented block
  870. $prefix = "<pre>\n";
  871. $suffix = "\n</pre>\n";
  872. }
  873. elseif ($block[0] == '|') {
  874. // Old-style table
  875. $prefix = "<?plugin OldStyleTable\n";
  876. $suffix = "\n?>\n";
  877. }
  878. elseif (strchr("#*;", $block[0])) {
  879. // Old-style list item
  880. preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
  881. list (,$ind,$bullet) = $m;
  882. $block = substr($block, strlen($m[0]));
  883. $indent = str_repeat(' ', strlen($ind));
  884. if ($bullet[0] == ';') {
  885. //$term = ltrim(substr($bullet, 1));
  886. //return $indent . $term . "\n" . $indent . ' ';
  887. $prefix = $ind . $bullet;
  888. }
  889. else
  890. $prefix = $indent . $bullet . ' ';
  891. }
  892. elseif ($block[0] == '[') {
  893. // Footnote definition
  894. preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
  895. $footnum = $m[1];
  896. $block = substr($block, strlen($m[0]));
  897. $prefix = "#[|ftnt_${footnum}]~[[${footnum}|#ftnt_ref_${footnum}]~] ";
  898. }
  899. elseif ($block[0] == '<') {
  900. // Plugin.
  901. // HACK: no inline markup...
  902. $prefix = $block;
  903. $block = '';
  904. }
  905. elseif ($block[0] == '!') {
  906. // Section heading
  907. preg_match('/^!{1,3}/', $block, $m);
  908. $prefix = $m[0];
  909. $block = substr($block, strlen($m[0]));
  910. }
  911. else {
  912. // AAck!
  913. assert(0);
  914. }
  915. if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
  916. if ($block) $block = preg_replace($orig, $repl, $block);
  917. $out .= $leading_text;
  918. $out .= $prefix;
  919. $out .= $block;
  920. $out .= $suffix;
  921. }
  922. return $out . preg_replace($orig, $repl, $text);
  923. }
  924. }
  925. /**
  926. * Expand tabs in string.
  927. *
  928. * Converts all tabs to (the appropriate number of) spaces.
  929. *
  930. * @param string $str
  931. * @param integer $tab_width
  932. * @return string
  933. */
  934. function expand_tabs($str, $tab_width = 8) {
  935. $split = split("\t", $str);
  936. $tail = array_pop($split);
  937. $expanded = "\n";
  938. foreach ($split as $hunk) {
  939. $expanded .= $hunk;
  940. $pos = strlen(strrchr($expanded, "\n")) - 1;
  941. $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
  942. }
  943. return substr($expanded, 1) . $tail;
  944. }
  945. /**
  946. * Split WikiWords in page names.
  947. *
  948. * It has been deemed useful to split WikiWords (into "Wiki Words") in
  949. * places like page titles. This is rumored to help search engines
  950. * quite a bit.
  951. *
  952. * @param $page string The page name.
  953. *
  954. * @return string The split name.
  955. */
  956. function SplitPagename ($page) {
  957. if (preg_match("/\s/", $page))
  958. return $page; // Already split --- don't split any more.
  959. // This algorithm is specialized for several languages.
  960. // (Thanks to Pierrick MEIGNEN)
  961. // Improvements for other languages welcome.
  962. static $RE;
  963. if (!isset($RE)) {
  964. // This mess splits between a lower-case letter followed by
  965. // either an upper-case or a numeral; except that it wont
  966. // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
  967. switch ($GLOBALS['LANG']) {
  968. case 'en':
  969. case 'it':
  970. case 'es':
  971. case 'de':
  972. $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
  973. break;
  974. case 'fr':
  975. $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
  976. break;
  977. }
  978. $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
  979. // This the single-letter words 'I' and 'A' from any following
  980. // capitalized words.
  981. switch ($GLOBALS['LANG']) {
  982. case 'en':
  983. $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
  984. break;
  985. case 'fr':
  986. $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
  987. break;
  988. }
  989. // Split numerals from following letters.
  990. $RE[] = '/(\d)([[:alpha:]])/';
  991. // Split at subpage seperators. TBD in Theme.php
  992. $RE[] = "/([^${sep}]+)(${sep})/";
  993. foreach ($RE as $key)
  994. $RE[$key] = pcre_fix_posix_classes($key);
  995. }
  996. foreach ($RE as $regexp) {
  997. $page = preg_replace($regexp, '\\1 \\2', $page);
  998. }
  999. return $page;
  1000. }
  1001. function NoSuchRevision (&$request, $page, $version) {
  1002. $html = HTML(HTML::h2(_("Revision Not Found")),
  1003. HTML::p(fmt("I'm sorry. Version %d of %s is not in the database.",
  1004. $version, WikiLink($page, 'auto'))));
  1005. include_once('lib/Template.php');
  1006. GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
  1007. $request->finish();
  1008. }
  1009. /**
  1010. * Get time offset for local time zone.
  1011. *
  1012. * @param $time time_t Get offset for this time. Default: now.
  1013. * @param $no_colon boolean Don't put colon between hours and minutes.
  1014. * @return string Offset as a string in the format +HH:MM.
  1015. */
  1016. function TimezoneOffset ($time = false, $no_colon = false) {
  1017. if ($time === false)
  1018. $time = time();
  1019. $secs = date('Z', $time);
  1020. if ($secs < 0) {
  1021. $sign = '-';
  1022. $secs = -$secs;
  1023. }
  1024. else {
  1025. $sign = '+';
  1026. }
  1027. $colon = $no_colon ? '' : ':';
  1028. $mins = intval(($secs + 30) / 60);
  1029. return sprintf("%s%02d%s%02d",
  1030. $sign, $mins / 60, $colon, $mins % 60);
  1031. }
  1032. /**
  1033. * Format time in ISO-8601 format.
  1034. *
  1035. * @param $time time_t Time. Default: now.
  1036. * @return string Date and time in ISO-8601 format.
  1037. */
  1038. function Iso8601DateTime ($time = false) {
  1039. if ($time === false)
  1040. $time = time();
  1041. $tzoff = TimezoneOffset($time);
  1042. $date = date('Y-m-d', $time);
  1043. $time = date('H:i:s', $time);
  1044. return $date . 'T' . $time . $tzoff;
  1045. }
  1046. /**
  1047. * Format time in RFC-2822 format.
  1048. *
  1049. * @param $time time_t Time. Default: now.
  1050. * @return string Date and time in RFC-2822 format.
  1051. */
  1052. function Rfc2822DateTime ($time = false) {
  1053. if ($time === false)
  1054. $time = time();
  1055. return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
  1056. }
  1057. /**
  1058. * Format time in RFC-1123 format.
  1059. *
  1060. * @param $time time_t Time. Default: now.
  1061. * @return string Date and time in RFC-1123 format.
  1062. */
  1063. function Rfc1123DateTime ($time = false) {
  1064. if ($time === false)
  1065. $time = time();
  1066. return gmdate('D, d M Y H:i:s \G\M\T', $time);
  1067. }
  1068. /** Parse date in RFC-1123 format.
  1069. *
  1070. * According to RFC 1123 we must accept dates in the following
  1071. * formats:
  1072. *
  1073. * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
  1074. * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
  1075. * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
  1076. *
  1077. * (Though we're only allowed to generate dates in the first format.)
  1078. */
  1079. function ParseRfc1123DateTime ($timestr) {
  1080. $timestr = trim($timestr);
  1081. if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
  1082. .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
  1083. $timestr, $m)) {
  1084. list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
  1085. }
  1086. elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
  1087. .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
  1088. $timestr, $m)) {
  1089. list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
  1090. if ($year < 70) $year += 2000;
  1091. elseif ($year < 100) $year += 1900;
  1092. }
  1093. elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
  1094. .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
  1095. $timestr, $m)) {
  1096. list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
  1097. }
  1098. else {
  1099. // Parse failed.
  1100. return false;
  1101. }
  1102. $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
  1103. if ($time == -1)
  1104. return false; // failed
  1105. return $time;
  1106. }
  1107. /**
  1108. * Format time to standard 'ctime' format.
  1109. *
  1110. * @param $time time_t Time. Default: now.
  1111. * @return string Date and time.
  1112. */
  1113. function CTime ($time = false)
  1114. {
  1115. if ($time === false)
  1116. $time = time();
  1117. return date("D M j H:i:s Y", $time);
  1118. }
  1119. /**
  1120. * Format number as kilobytes or bytes.
  1121. * Short format is used for PageList
  1122. * Long format is used in PageInfo
  1123. *
  1124. * @param $bytes int. Default: 0.
  1125. * @param $longformat bool. Default: false.
  1126. * @return class FormattedText (XmlElement.php).
  1127. */
  1128. function ByteFormatter ($bytes = 0, $longformat = false) {
  1129. if ($bytes < 0)
  1130. return fmt("-???");
  1131. if ($bytes < 1024) {
  1132. if (! $longformat)
  1133. $size = fmt("%s b", $bytes);
  1134. else
  1135. $size = fmt("%s bytes", $bytes);
  1136. }
  1137. else {
  1138. $kb = round($bytes / 1024, 1);
  1139. if (! $longformat)
  1140. $size = fmt("%s k", $kb);
  1141. else
  1142. $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
  1143. }
  1144. return $size;
  1145. }
  1146. /**
  1147. * Internationalized printf.
  1148. *
  1149. * This is essentially the same as PHP's built-in printf
  1150. * with the following exceptions:
  1151. * <ol>
  1152. * <li> It passes the format string through gettext().
  1153. * <li> It supports the argument reordering extensions.
  1154. * </ol>
  1155. *
  1156. * Example:
  1157. *
  1158. * In php code, use:
  1159. * <pre>
  1160. * __printf("Differences between versions %s and %s of %s",
  1161. * $new_link, $old_link, $page_link);
  1162. * </pre>
  1163. *
  1164. * Then in locale/po/de.po, one can reorder the printf arguments:
  1165. *
  1166. * <pre>
  1167. * msgid "Differences between %s and %s of %s."
  1168. * msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
  1169. * </pre>
  1170. *
  1171. * (Note that while PHP tries to expand $vars within double-quotes,
  1172. * the values in msgstr undergo no such expansion, so the '$'s
  1173. * okay...)
  1174. *
  1175. * One shouldn't use reordered arguments in the default format string.
  1176. * Backslashes in the default string would be necessary to escape the
  1177. * '$'s, and they'll cause all kinds of trouble....
  1178. */
  1179. function __printf ($fmt) {
  1180. $args = func_get_args();
  1181. array_shift($args);
  1182. echo __vsprintf($fmt, $args);
  1183. }
  1184. /**
  1185. * Internationalized sprintf.
  1186. *
  1187. * This is essentially the same as PHP's built-in printf with the
  1188. * following exceptions:
  1189. *
  1190. * <ol>
  1191. * <li> It passes the format string through gettext().
  1192. * <li> It supports the argument reordering extensions.
  1193. * </ol>
  1194. *
  1195. * @see __printf
  1196. */
  1197. function __sprintf ($fmt) {
  1198. $args = func_get_args();
  1199. array_shift($args);
  1200. return __vsprintf($fmt, $args);
  1201. }
  1202. /**
  1203. * Internationalized vsprintf.
  1204. *
  1205. * This is essentially the same as PHP's built-in printf with the
  1206. * following exceptions:
  1207. *
  1208. * <ol>
  1209. * <li> It passes the format string through gettext().
  1210. * <li> It supports the argument reordering extensions.
  1211. * </ol>
  1212. *
  1213. * @see __printf
  1214. */
  1215. function __vsprintf ($fmt, $args) {
  1216. $fmt = gettext($fmt);
  1217. // PHP's sprintf doesn't support variable with specifiers,
  1218. // like sprintf("%*s", 10, "x"); --- so we won't either.
  1219. if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
  1220. // Format string has '%2$s' style argument reordering.
  1221. // PHP doesn't support this.
  1222. if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
  1223. // literal variable name substitution only to keep locale
  1224. // strings uncluttered
  1225. trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
  1226. '%1\$s','%s'), E_USER_WARNING); //php+locale error
  1227. $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
  1228. $newargs = array();
  1229. // Reorder arguments appropriately.
  1230. foreach($m[1] as $argnum) {
  1231. if ($argnum < 1 || $argnum > count($args))
  1232. trigger_error(sprintf(_("%s: argument index out of range"),
  1233. $argnum), E_USER_WARNING);
  1234. $newargs[] = $args[$argnum - 1];
  1235. }
  1236. $args = $newargs;
  1237. }
  1238. // Not all PHP's have vsprintf, so...
  1239. array_unshift($args, $fmt);
  1240. return call_user_func_array('sprintf', $args);
  1241. }
  1242. function file_mtime ($filename) {
  1243. if ($stat = @stat($filename))
  1244. return $stat[9];
  1245. else
  1246. return false;
  1247. }
  1248. function sort_file_mtime ($a, $b) {
  1249. $ma = file_mtime($a);
  1250. $mb = file_mtime($b);
  1251. if (!$ma or !$mb or $ma == $mb) return 0;
  1252. return ($ma > $mb) ? -1 : 1;
  1253. }
  1254. class fileSet {
  1255. /**
  1256. * Build an array in $this->_fileList of files from $dirname.
  1257. * Subdirectories are not traversed.
  1258. *
  1259. * (This was a function LoadDir in lib/loadsave.php)
  1260. * See also http://www.php.net/manual/en/function.readdir.php
  1261. */
  1262. function getFiles($exclude=false, $sortby=false, $limit=false) {
  1263. $list = $this->_fileList;
  1264. if ($sortby) {
  1265. require_once('lib/PageList.php');
  1266. switch (Pagelist::sortby($sortby, 'db')) {
  1267. case 'pagename ASC': break;
  1268. case 'pagename DESC':
  1269. $list = array_reverse($list);
  1270. break;
  1271. case 'mtime ASC':
  1272. usort($list,'sort_file_mtime');
  1273. break;
  1274. case 'mtime DESC':
  1275. usort($list,'sort_file_mtime');
  1276. $list = array_reverse($list);
  1277. break;
  1278. }
  1279. }
  1280. if ($limit)
  1281. return array_splice($list, 0, $limit);
  1282. return $list;
  1283. }
  1284. function _filenameSelector($filename) {
  1285. if (! $this->_pattern )
  1286. return true;
  1287. else {
  1288. if (! $this->_pcre_pattern )
  1289. $this->_pcre_pattern = glob_to_pcre($this->_pattern);
  1290. return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'),
  1291. $filename);
  1292. }
  1293. }
  1294. function fileSet($directory, $filepattern = false) {
  1295. $this->_fileList = array();
  1296. $this->_pattern = $filepattern;
  1297. if ($filepattern)
  1298. $this->_pcre_pattern = glob_to_pcre($this->_pattern);
  1299. $this->_case = !isWindows();
  1300. $this->_pathsep = '/';
  1301. if (empty($directory)) {
  1302. trigger_error(sprintf(_("%s is empty."), 'directoryname'),
  1303. E_USER_NOTICE);
  1304. return; // early return
  1305. }
  1306. @ $dir_handle = opendir($dir=$directory);
  1307. if (empty($dir_handle)) {
  1308. trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
  1309. $dir), E_USER_NOTICE);
  1310. return; // early return
  1311. }
  1312. while ($filename = readdir($dir_handle)) {
  1313. if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
  1314. continue;
  1315. if ($this->_filenameSelector($filename)) {
  1316. array_push($this->_fileList, "$filename");
  1317. //trigger_error(sprintf(_("found file %s"), $filename),
  1318. // E_USER_NOTICE); //debugging
  1319. }
  1320. }
  1321. closedir($dir_handle);
  1322. }
  1323. };
  1324. // File globbing
  1325. // expands a list containing regex's to its matching entries
  1326. class ListRegexExpand {
  1327. //var $match, $list, $index, $case_sensitive;
  1328. function ListRegexExpand (&$list, $match, $case_sensitive = true) {
  1329. $this->match = $match;
  1330. $this->list = &$list;
  1331. $this->case_sensitive = $case_sensitive;
  1332. //$this->index = false;
  1333. }
  1334. function listMatchCallback ($item, $key) {
  1335. $quoted = str_replace('/','\/',$item);
  1336. if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
  1337. $quoted)) {
  1338. unset($this->list[$this->index]);
  1339. $this->list[] = $item;
  1340. }
  1341. }
  1342. function expandRegex ($index, &$pages) {
  1343. $this->index = $index;
  1344. array_walk($pages, array($this, 'listMatchCallback'));
  1345. return $this->list;
  1346. }
  1347. }
  1348. // Convert fileglob to regex style:
  1349. // Convert some wildcards to pcre style, escape the rest
  1350. // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
  1351. // Fixed bug #994994: "/" in $glob.
  1352. function glob_to_pcre ($glob) {
  1353. // check simple case: no need to escape
  1354. $escape = '\[](){}=!<>|:/';
  1355. if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
  1356. r…

Large files files are truncated, but you can click here to view the full file