[ Index ]

PHP Cross Reference of Nucleus CMS v3.51 code documentation

title

Body

[close]

/nucleus/libs/ -> globalfunctions.php (source)

   1  <?php
   2  
   3  /*

   4   * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)

   5   * Copyright (C) 2002-2009 The Nucleus Group

   6   *

   7   * This program is free software; you can redistribute it and/or

   8   * modify it under the terms of the GNU General Public License

   9   * as published by the Free Software Foundation; either version 2

  10   * of the License, or (at your option) any later version.

  11   * (see nucleus/documentation/index.html#license for more info)

  12   */
  13  /**

  14   * @license http://nucleuscms.org/license.txt GNU General Public License

  15   * @copyright Copyright (C) 2002-2009 The Nucleus Group

  16   * @version $Id: globalfunctions.php 1421 2009-11-01 13:45:44Z kaigreve $

  17  

  18   */
  19  
  20  // needed if we include globalfunctions from install.php

  21  global $nucleus, $CONF, $DIR_LIBS, $DIR_LANG, $manager, $member;
  22  
  23  $nucleus['version'] = 'v3.51';
  24  $nucleus['codename'] = '';
  25  
  26  checkVars(array('nucleus', 'CONF', 'DIR_LIBS', 'MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE', 'DIR_LANG', 'DIR_PLUGINS', 'HTTP_GET_VARS', 'HTTP_POST_VARS', 'HTTP_COOKIE_VARS', 'HTTP_ENV_VARS', 'HTTP_SESSION_VARS', 'HTTP_POST_FILES', 'HTTP_SERVER_VARS', 'GLOBALS', 'argv', 'argc', '_GET', '_POST', '_COOKIE', '_ENV', '_SESSION', '_SERVER', '_FILES'));
  27  
  28  $CONF['debug'] = 0;
  29  if ($CONF['debug']) {
  30      error_reporting(E_ALL); // report all errors!

  31  } else {
  32      ini_set('display_errors','0');
  33      error_reporting(E_ERROR | E_WARNING | E_PARSE);
  34  }
  35  
  36  /*

  37      Indicates when Nucleus should display startup errors. Set to 1 if you want

  38      the error enabled (default), false otherwise

  39  

  40      alertOnHeadersSent

  41          Displays an error when visiting a public Nucleus page and headers have

  42          been sent out to early. This usually indicates an error in either a

  43          configuration file or a language file, and could cause Nucleus to

  44          malfunction

  45      alertOnSecurityRisk

  46          Displays an error only when visiting the admin area, and when one or

  47          more of the installation files (install.php, install.sql, upgrades/

  48          directory) are still on the server.

  49  */
  50  
  51  $CONF['alertOnHeadersSent']  = 1;
  52  $CONF['alertOnSecurityRisk'] = 1;
  53  /*$CONF['ItemURL']           = $CONF['Self'];

  54  $CONF['ArchiveURL']          = $CONF['Self'];

  55  $CONF['ArchiveListURL']      = $CONF['Self'];

  56  $CONF['MemberURL']           = $CONF['Self'];

  57  $CONF['SearchURL']           = $CONF['Self'];

  58  $CONF['BlogURL']             = $CONF['Self'];

  59  $CONF['CategoryURL']         = $CONF['Self'];

  60  

  61  // switch URLMode back to normal when $CONF['Self'] ends in .php

  62  // this avoids urls like index.php/item/13/index.php/item/15

  63  if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {

  64      $CONF['URLMode'] = 'normal';

  65  }*/
  66  
  67  if (getNucleusPatchLevel() > 0) {
  68      $nucleus['version'] .= '/' . getNucleusPatchLevel();
  69  }
  70  
  71  // Avoid notices

  72  if (!isset($CONF['installscript'])) {
  73      $CONF['installscript'] = 0;
  74  }
  75  
  76  // we will use postVar, getVar, ... methods instead of HTTP_GET_VARS or _GET

  77  if ($CONF['installscript'] != 1) { // vars were already included in install.php
  78      if (phpversion() >= '4.1.0') {
  79          include_once ($DIR_LIBS . 'vars4.1.0.php');
  80      } else {
  81          include_once ($DIR_LIBS . 'vars4.0.6.php');
  82      }
  83  }
  84  
  85  // sanitize option

  86  $bLoggingSanitizedResult=0;
  87  $bSanitizeAndContinue=0;
  88  
  89  $orgRequestURI = serverVar('REQUEST_URI');
  90  sanitizeParams();
  91  
  92  // get all variables that can come from the request and put them in the global scope

  93  $blogid       = requestVar('blogid');
  94  $itemid       = intRequestVar('itemid');
  95  $catid        = intRequestVar('catid');
  96  $skinid       = requestVar('skinid');
  97  $memberid     = requestVar('memberid');
  98  $archivelist  = requestVar('archivelist');
  99  $imagepopup   = requestVar('imagepopup');
 100  $archive      = requestVar('archive');
 101  $query        = requestVar('query');
 102  $highlight    = requestVar('highlight');
 103  $amount       = requestVar('amount');
 104  $action       = requestVar('action');
 105  $nextaction   = requestVar('nextaction');
 106  $maxresults   = requestVar('maxresults');
 107  $startpos     = intRequestVar('startpos');
 108  $errormessage = '';
 109  $error        = '';
 110  $special      = requestVar('special');
 111  $virtualpath  = ((getVar('virtualpath') != null) ? getVar('virtualpath') : serverVar('PATH_INFO'));
 112  
 113  if (!headers_sent() ) {
 114      header('Generator: Nucleus CMS ' . $nucleus['version']);
 115  }
 116  
 117  // include core classes that are needed for login & plugin handling

 118  // added for 3.5 sql_* wrapper

 119  global $MYSQL_HANDLER;
 120  if (!isset($MYSQL_HANDLER))
 121      $MYSQL_HANDLER = array('mysql','');
 122  if ($MYSQL_HANDLER[0] == '')
 123      $MYSQL_HANDLER[0] = 'mysql';
 124  include_once($DIR_LIBS . 'sql/'.$MYSQL_HANDLER[0].'.php');
 125  // end new for 3.5 sql_* wrapper

 126  include_once ($DIR_LIBS . 'mysql.php');
 127  include ($DIR_LIBS . 'MEMBER.php');
 128  include ($DIR_LIBS . 'ACTIONLOG.php');
 129  include ($DIR_LIBS . 'MANAGER.php');
 130  include ($DIR_LIBS . 'PLUGIN.php');
 131  
 132  $manager =& MANAGER::instance();
 133  
 134  // make sure there's no unnecessary escaping:

 135  //set_magic_quotes_runtime(0);

 136  if (version_compare(PHP_VERSION, '5.3.0', '<')) {
 137      ini_set('magic_quotes_runtime', '0');
 138  }
 139  
 140  // Avoid notices

 141  if (!isset($CONF['UsingAdminArea'])) {
 142      $CONF['UsingAdminArea'] = 0;
 143  }
 144  
 145  // only needed when updating logs

 146  if ($CONF['UsingAdminArea']) {
 147      include ($DIR_LIBS . 'xmlrpc.inc.php');  // XML-RPC client classes

 148      include_once ($DIR_LIBS . 'ADMIN.php');
 149  }
 150  
 151  // connect to database

 152  sql_connect();
 153  $SQLCount = 0;
 154  
 155  // logs sanitized result if need

 156  if ($orgRequestURI!==serverVar('REQUEST_URI')) {
 157      $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
 158      $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
 159      if ($bLoggingSanitizedResult) {
 160          addToLog(WARNING, $msg);
 161      }
 162      if (!$bSanitizeAndContinue) {
 163          die("");
 164      }
 165  }
 166  
 167  // makes sure database connection gets closed on script termination

 168  register_shutdown_function('sql_disconnect');
 169  
 170  // read config

 171  getConfig();
 172  
 173  // Properly set $CONF['Self'] and others if it's not set... usually when we are access from admin menu

 174  if (!isset($CONF['Self'])) {
 175      $CONF['Self'] = $CONF['IndexURL'];
 176      // strip trailing /

 177      if ($CONF['Self'][strlen($CONF['Self']) -1] == "/") {
 178          $CONF['Self'] = substr($CONF['Self'], 0, strlen($CONF['Self']) -1);
 179      }
 180  
 181  /*    $CONF['ItemURL']        = $CONF['Self'];

 182      $CONF['ArchiveURL']     = $CONF['Self'];

 183      $CONF['ArchiveListURL'] = $CONF['Self'];

 184      $CONF['MemberURL']      = $CONF['Self'];

 185      $CONF['SearchURL']      = $CONF['Self'];

 186      $CONF['BlogURL']        = $CONF['Self'];

 187      $CONF['CategoryURL']    = $CONF['Self'];*/
 188  }
 189  
 190  $CONF['ItemURL'] = $CONF['Self'];
 191  $CONF['ArchiveURL'] = $CONF['Self'];
 192  $CONF['ArchiveListURL'] = $CONF['Self'];
 193  $CONF['MemberURL'] = $CONF['Self'];
 194  $CONF['SearchURL'] = $CONF['Self'];
 195  $CONF['BlogURL'] = $CONF['Self'];
 196  $CONF['CategoryURL'] = $CONF['Self'];
 197  
 198  // switch URLMode back to normal when $CONF['Self'] ends in .php

 199  // this avoids urls like index.php/item/13/index.php/item/15

 200  if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {
 201      $CONF['URLMode'] = 'normal';
 202  }
 203  
 204  // automatically use simpler toolbar for mozilla

 205  if (($CONF['DisableJsTools'] == 0) && strstr(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') && strstr(serverVar('HTTP_USER_AGENT'), 'Gecko') ) {
 206      $CONF['DisableJsTools'] = 2;
 207  }
 208  
 209  // login if cookies set

 210  $member = new MEMBER();
 211  
 212  // secure cookie key settings (either 'none', 0, 8, 16, 24, or 32)

 213  if (!isset($CONF['secureCookieKey'])) $CONF['secureCookieKey']=24;
 214  switch($CONF['secureCookieKey']){
 215  case 8:
 216      $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
 217      break;
 218  case 16:
 219      $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
 220      break;
 221  case 24:
 222      $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
 223      break;
 224  case 32:
 225      $CONF['secureCookieKeyIP']=serverVar('REMOTE_ADDR');
 226      break;
 227  default:
 228      $CONF['secureCookieKeyIP']='';
 229  }
 230  
 231  // login/logout when required or renew cookies

 232  if ($action == 'login') {
 233      // Form Authentication

 234      $login = postVar('login');
 235      $pw = postVar('password');
 236      $shared = intPostVar('shared'); // shared computer or not

 237  
 238      $pw=substr($pw,0,40); // avoid md5 collision by using a long key

 239  
 240      if ($member->login($login, $pw) ) {
 241  
 242          $member->newCookieKey();
 243          $member->setCookies($shared);
 244  
 245          if ($CONF['secureCookieKey']!=='none') {
 246              // secure cookie key

 247              $member->setCookieKey(md5($member->getCookieKey().$CONF['secureCookieKeyIP']));
 248              $member->write();
 249          }
 250  
 251          // allows direct access to parts of the admin area after logging in

 252          if ($nextaction) {
 253              $action = $nextaction;
 254          }
 255  
 256          $manager->notify('LoginSuccess', array('member' => &$member, 'username' => $login) );
 257          $errormessage = '';
 258          ACTIONLOG::add(INFO, "Login successful for $login (sharedpc=$shared)");
 259      } else {
 260          // errormessage for [%errordiv%]

 261          $errormessage = 'Login failed for ' . $login;
 262  
 263          $manager->notify('LoginFailed', array('username' => $login) );
 264          ACTIONLOG::add(INFO, $errormessage);
 265      }
 266  /*

 267  

 268  Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details

 269  

 270  } elseif (serverVar('PHP_AUTH_USER') && serverVar('PHP_AUTH_PW')) {

 271      // HTTP Authentication

 272      $login  = serverVar('PHP_AUTH_USER');

 273      $pw     = serverVar('PHP_AUTH_PW');

 274  

 275      if ($member->login($login, $pw) ) {

 276          $manager->notify('LoginSuccess',array('member' => &$member));

 277          ACTIONLOG::add(INFO, "HTTP authentication successful for $login");

 278      } else {

 279          $manager->notify('LoginFailed',array('username' => $login));

 280          ACTIONLOG::add(INFO, 'HTTP authentication failed for ' . $login);

 281  

 282          //Since bad credentials, generate an apropriate error page

 283          header("WWW-Authenticate: Basic realm=\"Nucleus CMS {$nucleus['version']}\"");

 284          header('HTTP/1.0 401 Unauthorized');

 285          echo 'Invalid username or password';

 286          exit;

 287      }

 288  */
 289  
 290  } elseif (($action == 'logout') && (!headers_sent() ) && cookieVar($CONF['CookiePrefix'] . 'user') ) {
 291      // remove cookies on logout

 292      setcookie($CONF['CookiePrefix'] . 'user', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
 293      setcookie($CONF['CookiePrefix'] . 'loginkey', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
 294      $manager->notify('Logout', array('username' => cookieVar($CONF['CookiePrefix'] . 'user') ) );
 295  } elseif (cookieVar($CONF['CookiePrefix'] . 'user') ) {
 296      // Cookie Authentication

 297      $ck=cookieVar($CONF['CookiePrefix'] . 'loginkey');
 298      // secure cookie key

 299      $ck=substr($ck,0,32); // avoid md5 collision by using a long key

 300      if ($CONF['secureCookieKey']!=='none') $ck=md5($ck.$CONF['secureCookieKeyIP']);
 301      $res = $member->cookielogin(cookieVar($CONF['CookiePrefix'] . 'user'), $ck );
 302      unset($ck);
 303  
 304      // renew cookies when not on a shared computer

 305      if ($res && (cookieVar($CONF['CookiePrefix'] . 'sharedpc') != 1) && (!headers_sent() ) ) {
 306          $member->setCookieKey(cookieVar($CONF['CookiePrefix'] . 'loginkey'));
 307          $member->setCookies();
 308      }
 309  }
 310  
 311  // login completed

 312  $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );
 313  ticketForPlugin();
 314  
 315  // first, let's see if the site is disabled or not. always allow admin area access.

 316  if ($CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea']) {
 317      redirect($CONF['DisableSiteURL']);
 318      exit;
 319  }
 320  
 321  // load other classes

 322  include ($DIR_LIBS . 'PARSER.php');
 323  include ($DIR_LIBS . 'SKIN.php');
 324  include ($DIR_LIBS . 'TEMPLATE.php');
 325  include ($DIR_LIBS . 'BLOG.php');
 326  include ($DIR_LIBS . 'BODYACTIONS.php');
 327  include ($DIR_LIBS . 'COMMENTS.php');
 328  include ($DIR_LIBS . 'COMMENT.php');
 329  //include($DIR_LIBS . 'ITEM.php');

 330  include ($DIR_LIBS . 'NOTIFICATION.php');
 331  include ($DIR_LIBS . 'BAN.php');
 332  include ($DIR_LIBS . 'PAGEFACTORY.php');
 333  include ($DIR_LIBS . 'SEARCH.php');
 334  include ($DIR_LIBS . 'entity.php');
 335  
 336  
 337  // set lastVisit cookie (if allowed)

 338  if (!headers_sent() ) {
 339      if ($CONF['LastVisit']) {
 340          setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
 341      } else {
 342          setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
 343      }
 344  }
 345  
 346  // read language file, only after user has been initialized

 347  $language = getLanguageName();
 348  //include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');

 349  include($DIR_LANG . preg_replace( '@\\|/@', '', $language) . '.php');
 350  
 351  /*

 352      Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details

 353  

 354  // To remove after v2.5 is released and language files have been updated.

 355  // Including this makes sure that language files for v2.5beta can still be used for v2.5final

 356  // without having weird _SETTINGS_EXTAUTH string showing up in the admin area.

 357  if (!defined('_MEMBERS_BYPASS'))

 358  {

 359      define('_SETTINGS_EXTAUTH',         'Enable External Authentication');

 360      define('_WARNING_EXTAUTH',          'Warning: Enable only if needed.');

 361      define('_MEMBERS_BYPASS',           'Use External Authentication');

 362  }

 363  

 364  */
 365  
 366  // make sure the archivetype skinvar keeps working when _ARCHIVETYPE_XXX not defined

 367  if (!defined('_ARCHIVETYPE_MONTH') ) {
 368      define('_ARCHIVETYPE_DAY', 'day');
 369      define('_ARCHIVETYPE_MONTH', 'month');
 370      define('_ARCHIVETYPE_YEAR', 'year');
 371  }
 372  
 373  // decode path_info

 374  if ($CONF['URLMode'] == 'pathinfo') {
 375      // initialize keywords if this hasn't been done before

 376      if (!isset($CONF['ItemKey']) || $CONF['ItemKey'] == '') {
 377          $CONF['ItemKey'] = 'item';
 378      }
 379  
 380      if (!isset($CONF['ArchiveKey']) || $CONF['ArchiveKey'] == '') {
 381          $CONF['ArchiveKey'] = 'archive';
 382      }
 383  
 384      if (!isset($CONF['ArchivesKey']) || $CONF['ArchivesKey'] == '') {
 385          $CONF['ArchivesKey'] = 'archives';
 386      }
 387  
 388      if (!isset($CONF['MemberKey']) || $CONF['MemberKey'] == '') {
 389          $CONF['MemberKey'] = 'member';
 390      }
 391  
 392      if (!isset($CONF['BlogKey']) || $CONF['BlogKey'] == '') {
 393          $CONF['BlogKey'] = 'blog';
 394      }
 395  
 396      if (!isset($CONF['CategoryKey']) || $CONF['CategoryKey'] == '') {
 397          $CONF['CategoryKey'] = 'category';
 398      }
 399  
 400      if (!isset($CONF['SpecialskinKey']) || $CONF['SpecialskinKey'] == '') {
 401          $CONF['SpecialskinKey'] = 'special';
 402      }
 403  
 404      $parsed = false;
 405      $manager->notify(
 406          'ParseURL',
 407          array(
 408              'type' => basename(serverVar('SCRIPT_NAME') ), // e.g. item, blog, ...
 409              'info' => $virtualpath,
 410              'complete' => &$parsed
 411          )
 412      );
 413  
 414      if (!$parsed) {
 415          // default implementation

 416          $data = explode("/", $virtualpath );
 417          for ($i = 0; $i < sizeof($data); $i++) {
 418              switch ($data[$i]) {
 419                  case $CONF['ItemKey']: // item/1 (blogid)
 420                      $i++;
 421  
 422                      if ($i < sizeof($data) ) {
 423                          $itemid = intval($data[$i]);
 424                      }
 425                      break;
 426  
 427                  case $CONF['ArchivesKey']: // archives/1 (blogid)
 428                      $i++;
 429  
 430                      if ($i < sizeof($data) ) {
 431                          $archivelist = intval($data[$i]);
 432                      }
 433                      break;
 434  
 435                  case $CONF['ArchiveKey']: // two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid)
 436                      if ((($i + 1) < sizeof($data) ) && (!strstr($data[$i + 1], '-') ) ) {
 437                          $blogid = intval($data[++$i]);
 438                      }
 439  
 440                      $i++;
 441  
 442                      if ($i < sizeof($data) ) {
 443                          $archive = $data[$i];
 444                      }
 445                      break;
 446  
 447                  case 'blogid': // blogid/1
 448                  case $CONF['BlogKey']: // blog/1
 449                      $i++;
 450  
 451                      if ($i < sizeof($data) ) {
 452                          $blogid = intval($data[$i]);
 453                      }
 454                      break;
 455  
 456                  case $CONF['CategoryKey']: // category/1 (catid)
 457                  case 'catid':
 458                      $i++;
 459  
 460                      if ($i < sizeof($data) ) {
 461                          $catid = intval($data[$i]);
 462                      }
 463                      break;
 464  
 465                  case $CONF['MemberKey']:
 466                      $i++;
 467  
 468                      if ($i < sizeof($data) ) {
 469                          $memberid = intval($data[$i]);
 470                      }
 471                      break;
 472  
 473                  case $CONF['SpecialskinKey']:
 474                      $i++;
 475  
 476                      if ($i < sizeof($data) ) {
 477                          $_REQUEST['special'] = $data[$i];
 478                      }
 479                      break;
 480  
 481                  default:
 482                      // skip...

 483              }
 484          }
 485      }
 486  }
 487  
 488  function intPostVar($name) {
 489      return intval(postVar($name) );
 490  }
 491  
 492  function intGetVar($name) {
 493      return intval(getVar($name) );
 494  }
 495  
 496  function intRequestVar($name) {
 497      return intval(requestVar($name) );
 498  }
 499  
 500  function intCookieVar($name) {
 501      return intval(cookieVar($name) );
 502  }
 503  
 504  /**

 505    * returns the currently used version (100 = 1.00, 101 = 1.01, etc...)

 506    */
 507  function getNucleusVersion() {
 508      return 351;
 509  }
 510  
 511  /**

 512   * power users can install patches in between nucleus releases. These patches

 513   * usually add new functionality in the plugin API and allow those to

 514   * be tested without having to install CVS.

 515   */
 516  function getNucleusPatchLevel() {
 517      return 0;
 518  }
 519  
 520  /**

 521   * returns the latest version available for download from nucleuscms.org 

 522   * or false if unable to attain data

 523   * format will be major.minor/patachlevel

 524   * e.g. 3.41 or 3.41/02

 525   */
 526  function getLatestVersion() {
 527      if (!function_exists('curl_init')) return false;
 528      $crl = curl_init();
 529      $timeout = 5;
 530      curl_setopt ($crl, CURLOPT_URL,'http://nucleuscms.org/version_check.php');
 531      curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
 532      curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
 533      $ret = curl_exec($crl);
 534      curl_close($crl);
 535      return $ret;
 536  
 537  }
 538  
 539  /**

 540    * Connects to mysql server

 541    */
 542  /* moved to $DIR_LIBS/sql/*.php handler files

 543  function sql_connect() {

 544      global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN;

 545  

 546      $MYSQL_CONN = @mysql_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD) or startUpError('<p>Could not connect to MySQL database.</p>', 'Connect Error');

 547      mysql_select_db($MYSQL_DATABASE) or startUpError('<p>Could not select database: ' . mysql_error() . '</p>', 'Connect Error');

 548  

 549      return $MYSQL_CONN;

 550  }*/
 551  
 552  /**

 553   * returns a prefixed nucleus table name

 554   */
 555  function sql_table($name) {
 556      global $MYSQL_PREFIX;
 557  
 558      if ($MYSQL_PREFIX) {
 559          return $MYSQL_PREFIX . 'nucleus_' . $name;
 560      } else {
 561          return 'nucleus_' . $name;
 562      }
 563  }
 564  
 565  function sendContentType($contenttype, $pagetype = '', $charset = _CHARSET) {
 566      global $manager, $CONF;
 567  
 568      if (!headers_sent() ) {
 569          // if content type is application/xhtml+xml, only send it to browsers

 570          // that can handle it (IE6 cannot). Otherwise, send text/html

 571  
 572          // v2.5: For admin area pages, keep sending text/html (unless it's a debug version)

 573          //       application/xhtml+xml still causes too much problems with the javascript implementations

 574  
 575          // v3.3: ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,

 576          //       application/xhtml+xml seems to be working, so we're going to use it if we can.

 577          if (
 578                  ($contenttype == 'application/xhtml+xml')
 579              &&  (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') )
 580              ) {
 581              $contenttype = 'text/html';
 582          }
 583          $manager->notify(
 584              'PreSendContentType',
 585              array(
 586                  'contentType' => &$contenttype,
 587                  'charset' => &$charset,
 588                  'pageType' => $pagetype
 589              )
 590          );
 591          // strip strange characters

 592          $contenttype = preg_replace('|[^a-z0-9-+./]|i', '', $contenttype);
 593          $charset = preg_replace('|[^a-z0-9-_]|i', '', $charset);
 594  
 595          if ($charset != '') {
 596              header('Content-Type: ' . $contenttype . '; charset=' . $charset);
 597          } else {
 598              header('Content-Type: ' . $contenttype);
 599          }
 600      }
 601  }
 602  
 603  /**

 604   * Errors before the database connection has been made - moved to 

 605   */
 606  /* moved to $DIR_LIBS/sql/*.php handler files

 607  function startUpError($msg, $title) {

 608  

 609  

 610      ?>

 611      <html xmlns="http://www.w3.org/1999/xhtml">

 612          <head><title><?php echo htmlspecialchars($title)?></title></head>

 613  

 614          <body>

 615              <h1><?php echo htmlspecialchars($title)?></h1>

 616              <?php echo $msg?>

 617          </body>

 618      </html>

 619      <?php   exit;

 620  }*/
 621  
 622  /**

 623    * disconnects from SQL server

 624    */
 625  /* moved to $DIR_LIBS/sql/*.php handler files

 626  function sql_disconnect() {

 627      @mysql_close();

 628  }*/
 629  
 630  /**

 631    * executes an SQL query

 632    */
 633  /* moved to $DIR_LIBS/sql/*.php handler files

 634  function sql_query($query) {

 635      global $SQLCount;

 636      $SQLCount++;

 637      $res = mysql_query($query) or print("mySQL error with query $query: " . mysql_error() . '<p />');

 638      return $res;

 639  }*/
 640  
 641  
 642  /**

 643   * Highlights a specific query in a given HTML text (not within HTML tags) and returns it

 644   *

 645   * @param $text

 646   *        text to be highlighted

 647   * @param $expression

 648   *        regular expression to be matched (can be an array of expressions as well)

 649   * @param $highlight

 650   *        highlight to be used (use \\0 to indicate the matched expression)

 651   *

 652   */
 653  function highlight($text, $expression, $highlight) {
 654      if (!$highlight || !$expression) {
 655          return $text;
 656      }
 657  
 658      if (is_array($expression) && (count($expression) == 0) ) {
 659          return $text;
 660      }
 661  
 662      // add a tag in front (is needed for preg_match_all to work correct)

 663      $text = '<!--h-->' . $text;
 664  
 665      // split the HTML up so we have HTML tags

 666      // $matches[0][i] = HTML + text

 667      // $matches[1][i] = HTML

 668      // $matches[2][i] = text

 669      preg_match_all('/(<[^>]+>)([^<>]*)/', $text, $matches);
 670  
 671      // throw it all together again while applying the highlight to the text pieces

 672      $result = '';
 673      for ($i = 0; $i < sizeof($matches[2]); $i++) {
 674          if ($i != 0) {
 675              $result .= $matches[1][$i];
 676          }
 677  
 678          if (is_array($expression) ) {
 679              foreach ($expression as $regex) {
 680                  if ($regex) {
 681                      $matches[2][$i] = @eregi_replace($regex, $highlight, $matches[2][$i]);
 682                  }
 683              }
 684  
 685              $result .= $matches[2][$i];
 686          } else {
 687              $result .= @eregi_replace($expression, $highlight, $matches[2][$i]);
 688          }
 689      }
 690  
 691      return $result;
 692  }
 693  
 694  /**

 695   * Parses a query into an array of expressions that can be passed on to the highlight method

 696   */
 697  function parseHighlight($query) {
 698      // TODO: add more intelligent splitting logic

 699  
 700      // get rid of quotes

 701      $query = preg_replace('/\'|"/', '', $query);
 702  
 703      if (!$query) {
 704          return array();
 705      }
 706  
 707      $aHighlight = explode(' ', $query);
 708  
 709      for ($i = 0; $i < count($aHighlight); $i++) {
 710          $aHighlight[$i] = trim($aHighlight[$i]);
 711  
 712          if (strlen($aHighlight[$i]) < 3) {
 713              unset($aHighlight[$i]);
 714          }
 715      }
 716  
 717      if (count($aHighlight) == 1) {
 718          return $aHighlight[0];
 719      } else {
 720          return $aHighlight;
 721      }
 722  }
 723  
 724  /**

 725    * Checks if email address is valid

 726    */
 727  function isValidMailAddress($address) {
 728      if (preg_match('/^[a-zA-Z+0-9\._-]+@[a-zA-Z0-9\._-]+\.[A-Za-z]{2,5}$/', $address)) {
 729          return 1;
 730      } else {
 731          return 0;
 732      }
 733  }
 734  
 735  
 736  // some helper functions

 737  function getBlogIDFromName($name) {
 738      return quickQuery('SELECT bnumber as result FROM ' . sql_table('blog') . ' WHERE bshortname="' . addslashes($name) . '"');
 739  }
 740  
 741  function getBlogNameFromID($id) {
 742      return quickQuery('SELECT bname as result FROM ' . sql_table('blog') . ' WHERE bnumber=' . intval($id) );
 743  }
 744  
 745  function getBlogIDFromItemID($itemid) {
 746      return quickQuery('SELECT iblog as result FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid) );
 747  }
 748  
 749  function getBlogIDFromCommentID($commentid) {
 750      return quickQuery('SELECT cblog as result FROM ' . sql_table('comment') . ' WHERE cnumber=' . intval($commentid) );
 751  }
 752  
 753  function getBlogIDFromCatID($catid) {
 754      return quickQuery('SELECT cblog as result FROM ' . sql_table('category') . ' WHERE catid=' . intval($catid) );
 755  }
 756  
 757  function getCatIDFromName($name) {
 758      return quickQuery('SELECT catid as result FROM ' . sql_table('category') . ' WHERE cname="' . addslashes($name) . '"');
 759  }
 760  
 761  function quickQuery($q) {
 762      $res = sql_query($q);
 763      $obj = sql_fetch_object($res);
 764      return $obj->result;
 765  }
 766  
 767  function getPluginNameFromPid($pid) {
 768      $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );
 769      $obj = sql_fetch_object($res);
 770      return $obj->pfile;
 771  //    return isset($obj->pfile) ? $obj->pfile : false;

 772  }
 773  
 774  function selector() {
 775      global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;
 776      global $archive, $skinid, $blog, $memberinfo, $CONF, $member;
 777      global $imagepopup, $catid, $special;
 778      global $manager;
 779  
 780      $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
 781      $action = requestVar('action');
 782  
 783      if (in_array($action, $actionNames) ) {
 784          global $DIR_LIBS, $errormessage;
 785          include_once ($DIR_LIBS . 'ACTION.php');
 786          $a = new ACTION();
 787          $errorInfo = $a->doAction($action);
 788  
 789          if ($errorInfo) {
 790              $errormessage = $errorInfo['message'];
 791          }
 792      }
 793  
 794      // show error when headers already sent out

 795      if (headers_sent() && $CONF['alertOnHeadersSent']) {
 796  
 797          // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)

 798          if (function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') ) {
 799              headers_sent($hsFile, $hsLine);
 800              $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
 801          } else {
 802              $extraInfo = '';
 803          }
 804  
 805          startUpError(
 806              '<p>The page headers have already been sent out' . $extraInfo . '. This could cause Nucleus not to work in the expected way.</p><p>Usually, this is caused by spaces or newlines at the end of the <code>config.php</code> file, at the end of the language file or at the end of a plugin file. Please check this and try again.</p><p>If you don\'t want to see this error message again, without solving the problem, set <code>$CONF[\'alertOnHeadersSent\']</code> in <code>globalfunctions.php</code> to <code>0</code></p>',
 807              'Page headers already sent'
 808          );
 809          exit;
 810      }
 811  
 812      // make is so ?archivelist without blogname or blogid shows the archivelist

 813      // for the default weblog

 814      if (serverVar('QUERY_STRING') == 'archivelist') {
 815          $archivelist = $CONF['DefaultBlog'];
 816      }
 817  
 818      // now decide which type of skin we need

 819      if ($itemid) {
 820          // itemid given -> only show that item

 821          $type = 'item';
 822  
 823          if (!$manager->existsItem($itemid,0,0) ) {
 824              doError(_ERROR_NOSUCHITEM);
 825          }
 826  
 827          global $itemidprev, $itemidnext, $catid, $itemtitlenext, $itemtitleprev;
 828  
 829          // 1. get timestamp, blogid and catid for item

 830          $query = 'SELECT itime, iblog, icat FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid);
 831          $res = sql_query($query);
 832          $obj = sql_fetch_object($res);
 833  
 834          // if a different blog id has been set through the request or selectBlog(),

 835          // deny access

 836  
 837  
 838  
 839          if ($blogid && (intval($blogid) != $obj->iblog) ) {
 840  
 841  
 842  
 843  
 844  
 845  
 846  
 847  
 848  
 849              doError(_ERROR_NOSUCHITEM);
 850  
 851          }
 852  
 853          // if a category has been selected which doesn't match the item, ignore the

 854          // category. #85

 855          if (($catid != 0) && ($catid != $obj->icat) ) {
 856              $catid = 0;
 857          }
 858  
 859          $blogid = $obj->iblog;
 860          $timestamp = strtotime($obj->itime);
 861  
 862          $b =& $manager->getBlog($blogid);
 863  
 864          if ($b->isValidCategory($catid) ) {
 865              $catextra = ' and icat=' . $catid;
 866          } else {
 867              $catextra = '';
 868          }
 869  
 870          // get previous itemid and title

 871          $query = 'SELECT inumber, ititle FROM ' . sql_table('item') . ' WHERE itime<' . mysqldate($timestamp) . ' and idraft=0 and iblog=' . $blogid . $catextra . ' ORDER BY itime DESC LIMIT 1';
 872          $res = sql_query($query);
 873  
 874          $obj = sql_fetch_object($res);
 875  
 876          if ($obj) {
 877              $itemidprev = $obj->inumber;
 878              $itemtitleprev = $obj->ititle;
 879          }
 880  
 881          // get next itemid and title

 882          $query = 'SELECT inumber, ititle FROM ' . sql_table('item') . ' WHERE itime>' . mysqldate($timestamp) . ' and itime <= ' . mysqldate($b->getCorrectTime()) . ' and idraft=0 and iblog=' . $blogid . $catextra . ' ORDER BY itime ASC LIMIT 1';
 883          $res = sql_query($query);
 884  
 885          $obj = sql_fetch_object($res);
 886  
 887          if ($obj) {
 888              $itemidnext = $obj->inumber;
 889              $itemtitlenext = $obj->ititle;
 890          }
 891  
 892      } elseif ($archive) {
 893          // show archive

 894          $type = 'archive';
 895  
 896          // get next and prev month links ...

 897          global $archivenext, $archiveprev, $archivetype, $archivenextexists, $archiveprevexists;
 898  
 899          // sql queries for the timestamp of the first and the last published item

 900          $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime ASC";
 901          $first_timestamp=quickQuery ($query);
 902          $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime DESC";
 903          $last_timestamp=quickQuery ($query);
 904  
 905          sscanf($archive, '%d-%d-%d', $y, $m, $d);
 906  
 907          if ($d != 0) {
 908              $archivetype = _ARCHIVETYPE_DAY;
 909              $t = mktime(0, 0, 0, $m, $d, $y);
 910              // one day has 24 * 60 * 60 = 86400 seconds

 911              $archiveprev = strftime('%Y-%m-%d', $t - 86400 );
 912              // check for published items

 913              if ($t > $first_timestamp) {
 914                  $archiveprevexists = true;
 915              }
 916              else {
 917                  $archiveprevexists = false;
 918              }
 919  
 920              // one day later

 921              $t += 86400;
 922              $archivenext = strftime('%Y-%m-%d', $t);
 923              if ($t < $last_timestamp) {
 924                  $archivenextexists = true;
 925              }
 926              else {
 927                  $archivenextexists = false;
 928              }
 929  
 930          } elseif ($m == 0) {
 931              $archivetype = _ARCHIVETYPE_YEAR;
 932              $t = mktime(0, 0, 0, 12, 31, $y - 1);
 933              // one day before is in the previous year

 934              $archiveprev = strftime('%Y', $t);
 935              if ($t > $first_timestamp) {
 936                  $archiveprevexists = true;
 937              }
 938              else {
 939                  $archiveprevexists = false;
 940              }
 941  
 942              // timestamp for the next year

 943              $t = mktime(0, 0, 0, 1, 1, $y + 1);
 944              $archivenext = strftime('%Y', $t);
 945              if ($t < $last_timestamp) {
 946                  $archivenextexists = true;
 947              }
 948              else {
 949                  $archivenextexists = false;
 950              }
 951          } else {
 952              $archivetype = _ARCHIVETYPE_MONTH;
 953              $t = mktime(0, 0, 0, $m, 1, $y);
 954              // one day before is in the previous month

 955              $archiveprev = strftime('%Y-%m', $t - 86400);
 956              if ($t > $first_timestamp) {
 957                  $archiveprevexists = true;
 958              }
 959              else {
 960                  $archiveprevexists = false;
 961              }
 962  
 963              // timestamp for the next month

 964              $t = mktime(0, 0, 0, $m+1, 1, $y);
 965              $archivenext = strftime('%Y-%m', $t);
 966              if ($t < $last_timestamp) {
 967                  $archivenextexists = true;
 968              }
 969              else {
 970                  $archivenextexists = false;
 971              }
 972          }
 973  
 974      } elseif ($archivelist) {
 975          $type = 'archivelist';
 976  
 977          if (is_numeric($archivelist)) {
 978              $blogid = intVal($archivelist);
 979          } else {
 980              $blogid = getBlogIDFromName($archivelist);
 981          }
 982  
 983          if (!$blogid) {
 984              doError(_ERROR_NOSUCHBLOG);
 985          }
 986  
 987      } elseif ($query) {
 988          global $startpos;
 989          $type = 'search';
 990          $query = stripslashes($query);
 991  
 992  
 993  
 994  
 995  
 996  
 997  
 998  
 999  
1000  
1001  
1002  
1003  
1004  
1005  
1006  
1007  
1008  
1009  
1010  
1011  
1012  
1013  
1014          if (is_numeric($blogid)) {
1015              $blogid = intVal($blogid);
1016          } else {
1017              $blogid = getBlogIDFromName($blogid);
1018          }
1019  
1020          if (!$blogid) {
1021              doError(_ERROR_NOSUCHBLOG);
1022          }
1023  
1024      } elseif ($memberid) {
1025          $type = 'member';
1026  
1027          if (!MEMBER::existsID($memberid) ) {
1028              doError(_ERROR_NOSUCHMEMBER);
1029          }
1030  
1031          $memberinfo = $manager->getMember($memberid);
1032  
1033      } elseif ($imagepopup) {
1034          // media object (images etc.)

1035          $type = 'imagepopup';
1036  
1037          // TODO: check if media-object exists

1038          // TODO: set some vars?

1039      } else {
1040          // show regular index page

1041          global $startpos;
1042          $type = 'index';
1043      }
1044  
1045      // any type of skin with catid

1046      if ($catid && !$blogid) {
1047          $blogid = getBlogIDFromCatID($catid);
1048      }
1049  
1050      // decide which blog should be displayed

1051      if (!$blogid) {
1052          $blogid = $CONF['DefaultBlog'];
1053      }
1054  
1055      $b =& $manager->getBlog($blogid);
1056      $blog = $b; // references can't be placed in global variables?

1057  
1058      if (!$blog->isValid) {
1059          doError(_ERROR_NOSUCHBLOG);
1060      }
1061  
1062      // set catid if necessary

1063      if ($catid) {
1064          // check if the category is valid

1065          if (!$blog->isValidCategory($catid)) {
1066              doError(_ERROR_NOSUCHCATEGORY);
1067          } else {
1068              $blog->setSelectedCategory($catid);
1069          }
1070      }
1071  
1072      // decide which skin should be used

1073      if ($skinid != '' && ($skinid == 0) ) {
1074          selectSkin($skinid);
1075      }
1076  
1077      if (!$skinid) {
1078          $skinid = $blog->getDefaultSkin();
1079      }
1080  
1081      //$special = requestVar('special'); //get at top of file as global

1082      if (!empty($special) && isValidShortName($special)) {
1083          $type = strtolower($special);
1084      }
1085  
1086      $skin = new SKIN($skinid);
1087  
1088      if (!$skin->isValid) {
1089          doError(_ERROR_NOSUCHSKIN);
1090      }
1091  
1092      // parse the skin

1093      $skin->parse($type);
1094  
1095      // check to see we should throw JustPosted event

1096      $blog->checkJustPosted();
1097  }
1098  
1099  /**

1100    * Show error skin with given message. An optional skin-object to use can be given

1101    */
1102  function doError($msg, $skin = '') {
1103      global $errormessage, $CONF, $skinid, $blogid, $manager;
1104  
1105      if ($skin == '') {
1106  
1107          if (SKIN::existsID($skinid) ) {
1108              $skin = new SKIN($skinid);
1109          } elseif ($manager->existsBlogID($blogid) ) {
1110              $blog =& $manager->getBlog($blogid);
1111              $skin = new SKIN($blog->getDefaultSkin() );
1112          } elseif ($CONF['DefaultBlog']) {
1113              $blog =& $manager->getBlog($CONF['DefaultBlog']);
1114              $skin = new SKIN($blog->getDefaultSkin() );
1115          } else {
1116              // this statement should actually never be executed

1117              $skin = new SKIN($CONF['BaseSkin']);
1118          }
1119  
1120      }
1121  
1122      $skinid = $skin->id;
1123      $errormessage = $msg;
1124      $skin->parse('error');
1125      exit;
1126  }
1127  
1128  function getConfig() {
1129      global $CONF;
1130  
1131      $query = 'SELECT * FROM ' . sql_table('config');
1132      $res = sql_query($query);
1133  
1134      while ($obj = sql_fetch_object($res) ) {
1135          $CONF[$obj->name] = $obj->value;
1136      }
1137  }
1138  
1139  // some checks for names of blogs, categories, templates, members, ...

1140  function isValidShortName($name) {
1141      return eregi('^[a-z0-9]+$', $name);
1142  }
1143  
1144  function isValidDisplayName($name) {
1145      return eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name);
1146  }
1147  
1148  function isValidCategoryName($name) {
1149      return 1;
1150  }
1151  
1152  function isValidTemplateName($name) {
1153      return eregi('^[a-z0-9/]+$', $name);
1154  }
1155  
1156  function isValidSkinName($name) {
1157      return eregi('^[a-z0-9/]+$', $name);
1158  }
1159  
1160  // add and remove linebreaks

1161  function addBreaks($var) {
1162      return nl2br($var);
1163  }
1164  
1165  function removeBreaks($var) {
1166      return preg_replace("/<br \/>([\r\n])/", "$1", $var);
1167  }
1168  
1169  // shortens a text string to maxlength ($toadd) is what needs to be added

1170  // at the end (end length is <= $maxlength)

1171  function shorten($text, $maxlength, $toadd) {
1172      // 1. remove entities...

1173      $trans = get_html_translation_table(HTML_ENTITIES);
1174  
1175      $trans = array_flip($trans);
1176      $text = strtr($text, $trans);
1177  
1178      // 2. the actual shortening

1179      if (strlen($text) > $maxlength) {
1180          $text = substr($text, 0, $maxlength - strlen($toadd) ) . $toadd;
1181  
1182      }
1183  
1184      return $text;
1185  }
1186  
1187  /**

1188    * Converts a unix timestamp to a mysql DATETIME format, and places

1189    * quotes around it.

1190    */
1191  function mysqldate($timestamp) {
1192      return '"' . date('Y-m-d H:i:s', $timestamp) . '"';
1193  }
1194  
1195  /**

1196    * functions for use in index.php

1197    */
1198  function selectBlog($shortname) {
1199      global $blogid, $archivelist;
1200      $blogid = getBlogIDFromName($shortname);
1201  
1202      // also force archivelist variable, if it is set

1203      if ($archivelist) {
1204          $archivelist = $blogid;
1205      }
1206  }
1207  
1208  function selectSkin($skinname) {
1209      global $skinid;
1210      $skinid = SKIN::getIdFromName($skinname);
1211  }
1212  
1213  /**

1214   * Can take either a category ID or a category name (be aware that

1215   * multiple categories can have the same name)

1216   */
1217  function selectCategory($cat) {
1218      global $catid;
1219      if (is_numeric($cat) ) {
1220          $catid = intval($cat);
1221      } else {
1222          $catid = getCatIDFromName($cat);
1223      }
1224  }
1225  
1226  function selectItem($id) {
1227      global $itemid;
1228      $itemid = intval($id);
1229  }
1230  
1231  // force the use of a language file (warning: can cause warnings)

1232  function selectLanguage($language) {
1233      global $DIR_LANG;
1234  //    include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');

1235      include($DIR_LANG . preg_replace( '@\\|/@', '', $language) . '.php');
1236  }
1237  
1238  function parseFile($filename, $includeMode = 'normal', $includePrefix = '') {
1239      $handler = new ACTIONS('fileparser');
1240      $parser = new PARSER(SKIN::getAllowedActionsForType('fileparser'), $handler);
1241      $handler->parser =& $parser;
1242  
1243      // set IncludeMode properties of parser

1244      PARSER::setProperty('IncludeMode', $includeMode);
1245      PARSER::setProperty('IncludePrefix', $includePrefix);
1246  
1247      if (!file_exists($filename) ) {
1248          doError('A file is missing');
1249      }
1250  
1251      $fsize = filesize($filename);
1252  
1253      if ($fsize <= 0) {
1254          return;
1255      }
1256  
1257      // read file

1258      $fd = fopen ($filename, 'r');
1259      $contents = fread ($fd, $fsize);
1260      fclose ($fd);
1261  
1262      // parse file contents

1263      $parser->parse($contents);
1264  }
1265  
1266  /**

1267    * Outputs a debug message

1268    */
1269  function debug($msg) {
1270      echo '<p><b>' . $msg . "</b></p>\n";
1271  }
1272  
1273  // shortcut

1274  function addToLog($level, $msg) {
1275      ACTIONLOG::add($level, $msg);
1276  }
1277  
1278  // shows a link to help file

1279  function help($id) {
1280      echo helpHtml($id);
1281  }
1282  
1283  function helpHtml($id) {
1284      global $CONF;
1285      return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';
1286  }
1287  
1288  function helplink($id) {
1289      global $CONF;
1290      return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event &amp;&amp; event.preventDefault) event.preventDefault(); return help(this.href);">';
1291  }
1292  
1293  function getMailFooter() {
1294      $message = "\n\n-----------------------------";
1295      $message .=  "\n   Powered by Nucleus CMS";
1296      $message .=  "\n(http://www.nucleuscms.org/)";
1297      return $message;
1298  }
1299  
1300  /**

1301    * Returns the name of the language to use

1302    * preference priority: member - site

1303    * defaults to english when no good language found

1304    *

1305    * checks if file exists, etc...

1306    */
1307  function getLanguageName() {
1308      global $CONF, $member;
1309  
1310      if ($member && $member->isLoggedIn() ) {
1311          // try to use members language

1312          $memlang = $member->getLanguage();
1313  
1314          if (($memlang != '') && (checkLanguage($memlang) ) ) {
1315              return $memlang;
1316          }
1317      }
1318  
1319      // use default language

1320      if (checkLanguage($CONF['Language']) ) {
1321          return $CONF['Language'];
1322      } else {
1323          return 'english';
1324      }
1325  }
1326  
1327  /**

1328    * Includes a PHP file. This method can be called while parsing templates and skins

1329    */
1330  function includephp($filename) {
1331      // make predefined variables global, so most simple scripts can be used here

1332  
1333      // apache (names taken from PHP doc)

1334      global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
1335      global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
1336      global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
1337      global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
1338      global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
1339      global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
1340      global $REQUEST_URI;
1341  
1342      // php (taken from PHP doc)

1343      global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
1344      global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
1345  
1346      // other

1347      global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
1348  
1349      if (@file_exists($filename) ) {
1350          include($filename);
1351      }
1352  }
1353  
1354  /**

1355    * Checks if a certain language/plugin exists

1356    */
1357  function checkLanguage($lang) {
1358      global $DIR_LANG ;
1359  //    return file_exists($DIR_LANG . ereg_replace( '[\\|/]', '', $lang) . '.php');

1360      return file_exists($DIR_LANG . preg_replace( '@\\|/@', '', $lang) . '.php');
1361  }
1362  
1363  function checkPlugin($plug) {
1364      global $DIR_PLUGINS;
1365      return file_exists($DIR_PLUGINS . ereg_replace( '[\\|/]', '', $plug) . '.php');
1366  //    return file_exists($DIR_PLUGINS . preg_replace( '@\\|/@', '', $plug) . '.php');

1367  }
1368  
1369  /**

1370    * Centralisation of the functions that generate links

1371    */
1372  function createItemLink($itemid, $extra = '') {
1373      return createLink('item', array('itemid' => $itemid, 'extra' => $extra) );
1374  }
1375  
1376  function createMemberLink($memberid, $extra = '') {
1377      return createLink('member', array('memberid' => $memberid, 'extra' => $extra) );
1378  }
1379  
1380  function createCategoryLink($catid, $extra = '') {
1381      return createLink('category', array('catid' => $catid, 'extra' => $extra) );
1382  }
1383  
1384  function createArchiveListLink($blogid = '', $extra = '') {
1385      return createLink('archivelist', array('blogid' => $blogid, 'extra' => $extra) );
1386  }
1387  
1388  function createArchiveLink($blogid, $archive, $extra = '') {
1389      return createLink('archive', array('blogid' => $blogid, 'archive' => $archive, 'extra' => $extra) );
1390  }
1391  
1392  function createBlogidLink($blogid, $params = '') {
1393      return createLink('blog', array('blogid' => $blogid, 'extra' => $params) );
1394  }
1395  
1396  function createLink($type, $params) {
1397      global $manager, $CONF;
1398  
1399      $generatedURL = '';
1400      $usePathInfo = ($CONF['URLMode'] == 'pathinfo');
1401  
1402      // ask plugins first

1403      $created = false;
1404  
1405      if ($usePathInfo) {
1406          $manager->notify(
1407              'GenerateURL',
1408              array(
1409                  'type' => $type,
1410                  'params' => $params,
1411                  'completed' => &$created,
1412                  'url' => &$url
1413              )
1414          );
1415      }
1416  
1417      // if a plugin created the URL, return it

1418      if ($created) {
1419          return $url;
1420      }
1421  
1422      // default implementation

1423      switch ($type) {
1424          case 'item':
1425              if ($usePathInfo) {
1426                  $url = $CONF['ItemURL'] . '/' . $CONF['ItemKey'] . '/' . $params['itemid'];
1427              } else {
1428                  $url = $CONF['ItemURL'] . '?itemid=' . $params['itemid'];
1429              }
1430              break;
1431  
1432          case 'member':
1433              if ($usePathInfo) {
1434                  $url = $CONF['MemberURL'] . '/' . $CONF['MemberKey'] . '/' . $params['memberid'];
1435              } else {
1436                  $url = $CONF['MemberURL'] . '?memberid=' . $params['memberid'];
1437              }
1438              break;
1439  
1440          case 'category':
1441              if ($usePathInfo) {
1442                  $url = $CONF['CategoryURL'] . '/' . $CONF['CategoryKey'] . '/' . $params['catid'];
1443              } else {
1444                  $url = $CONF['CategoryURL'] . '?catid=' . $params['catid'];
1445              }
1446              break;
1447  
1448          case 'archivelist':
1449              if (!$params['blogid']) {
1450                  $params['blogid'] = $CONF['DefaultBlog'];
1451              }
1452  
1453              if ($usePathInfo) {
1454                  $url = $CONF['ArchiveListURL'] . '/' . $CONF['ArchivesKey'] . '/' . $params['blogid'];
1455              } else {
1456                  $url = $CONF['ArchiveListURL'] . '?archivelist=' . $params['blogid'];
1457              }
1458              break;
1459  
1460          case 'archive':
1461              if ($usePathInfo) {
1462                  $url = $CONF['ArchiveURL'] . '/' . $CONF['ArchiveKey'] . '/'.$params['blogid'].'/' . $params['archive'];
1463              } else {
1464                  $url = $CONF['ArchiveURL'] . '?blogid='.$params['blogid'].'&amp;archive=' . $params['archive'];
1465              }
1466              break;
1467  
1468          case 'blog':
1469              if ($usePathInfo) {
1470                  $url = $CONF['BlogURL'] . '/' . $CONF['BlogKey'] . '/' . $params['blogid'];
1471              } else {
1472                  $url = $CONF['BlogURL'] . '?blogid=' . $params['blogid'];
1473              }
1474              break;
1475      }
1476  
1477      return addLinkParams($url, (isset($params['extra'])? $params['extra'] : null));
1478  }
1479  
1480  function createBlogLink($url, $params) {
1481      global $CONF;
1482      if ($CONF['URLMode'] == 'normal') {
1483          if (strpos($url, '?') === FALSE && is_array($params)) {
1484              $fParam = reset($params);
1485              $fKey   = key($params);
1486              array_shift($params);
1487              $url .= '?' . $fKey . '=' . $fParam;
1488          }
1489      } elseif ($CONF['URLMode'] == 'pathinfo' && substr($url, -1) == '/') {
1490          $url = substr($url, 0, -1);
1491      }
1492      return addLinkParams($url, $params);
1493  }
1494  
1495  function addLinkParams($link, $params) {
1496      global $CONF;
1497  
1498      if (is_array($params) ) {
1499  
1500          if ($CONF['URLMode'] == 'pathinfo') {
1501  
1502              foreach ($params as $param => $value) {
1503                  $link .= '/' . $param . '/' . urlencode($value);
1504              }
1505  
1506          } else {
1507  
1508              foreach ($params as $param => $value) {
1509                  $link .= '&amp;' . $param . '=' . urlencode($value);
1510              }
1511  
1512          }
1513      }
1514  
1515      return $link;
1516  }
1517  
1518  /**

1519   * @param $querystr

1520   *        querystring to alter (e.g. foo=1&bar=2&x=y)

1521   * @param $param

1522   *        name of parameter to change (e.g. 'foo')

1523   * @param $value

1524   *        New value for that parameter (e.g. 3)

1525   * @result

1526   *        altered query string (for the examples above: foo=3&bar=2&x=y)

1527   */
1528  function alterQueryStr($querystr, $param, $value) {
1529      $vars = explode('&', $querystr);
1530      $set  = false;
1531  
1532      for ($i = 0; $i < count($vars); $i++) {
1533          $v = explode('=', $vars[$i]);
1534  
1535          if ($v[0] == $param) {
1536              $v[1] = $value;
1537              $vars[$i] = implode('=', $v);
1538              $set = true;
1539              break;
1540          }
1541      }
1542  
1543      if (!$set) {
1544          $vars[] = $param . '=' . $value;
1545      }
1546  
1547      return ltrim(implode('&', $vars), '&');
1548  }
1549  
1550  // passes one variable as hidden input field (multiple fields for arrays)

1551  // @see passRequestVars in varsx.x.x.php

1552  function passVar($key, $value) {
1553      // array ?

1554      if (is_array($value) ) {
1555          for ($i = 0; $i < sizeof($value); $i++) {
1556              passVar($key . '[' . $i . ']', $value[$i]);
1557          }
1558  
1559          return;
1560      }
1561  
1562      // other values: do stripslashes if needed

1563      ?><input type="hidden" name="<?php echo htmlspecialchars($key)?>" value="<?php echo htmlspecialchars(undoMagic($value) )?>" /><?php
1564  }
1565  
1566  /*

1567      Date format functions (to be used from [%date(..)%] skinvars

1568  */
1569  function formatDate($format, $timestamp, $defaultFormat, &$blog) {
1570      // apply blog offset (#42)

1571      $boffset = $blog ? $blog->getTimeOffset() * 3600 : 0;
1572      $offset = date('Z', $timestamp) + $boffset;
1573  
1574      switch ($format) {
1575          case 'rfc822':
1576              if ($offset >= 0) {
1577                  $tz = '+';
1578              } else {
1579                  $tz = '-';
1580                  $offset = -$offset;
1581              }
1582  
1583              $tz .= sprintf("%02d%02d", floor($offset / 3600), round(($offset % 3600) / 60) );
1584              return date('D, j M Y H:i:s ', $timestamp) . $tz;
1585  
1586          case 'rfc822GMT':
1587              $timestamp -= $offset;
1588              return date('D, j M Y H:i:s ', $timestamp) . 'GMT';
1589  
1590          case 'utc':
1591              $timestamp -= $offset;
1592              return date('Y-m-d\TH:i:s\Z', $timestamp);
1593  
1594          case 'iso8601':
1595              if ($offset >= 0) {
1596                  $tz = '+';
1597              } else {
1598                  $tz = '-';
1599                  $offset = -$offset;
1600              }
1601              $tz .= sprintf("%02d:%02d", floor($offset / 3600), round(($offset % 3600) / 60) );
1602              return date('Y-m-d\TH:i:s', $timestamp) . $tz;
1603  
1604          default :
1605              return strftime($format ? $format : $defaultFormat, $timestamp);
1606      }
1607  }
1608  
1609  function checkVars($aVars) {
1610      global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;
1611  
1612      foreach ($aVars as $varName) {
1613  
1614          if (phpversion() >= '4.1.0') {
1615  
1616              if (   isset($_GET[$varName])
1617                  || isset($_POST[$varName])
1618                  || isset($_COOKIE[$varName])
1619                  || isset($_ENV[$varName])
1620                  || isset($_SESSION[$varName])
1621                  || isset($_FILES[$varName])
1622              ) {
1623                  die('Sorry. An error occurred.');
1624              }
1625  
1626          } else {
1627  
1628              if (   isset($HTTP_GET_VARS[$varName])
1629                  || isset($HTTP_POST_VARS[$varName])
1630                  || isset($HTTP_COOKIE_VARS[$varName])
1631                  || isset($HTTP_ENV_VARS[$varName])
1632                  || isset($HTTP_SESSION_VARS[$varName])
1633                  || isset($HTTP_POST_FILES[$varName])
1634              ) {
1635                  die('Sorry. An error occurred.');
1636              }
1637  
1638          }
1639      }
1640  }
1641  
1642  
1643  /**

1644   * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.

1645   * to avoid XSS

1646   */
1647  function sanitizeParams()
1648  {
1649      global $HTTP_SERVER_VARS;
1650  
1651      $array = array();
1652      $str = '';
1653      $frontParam = '';
1654  
1655      // REQUEST_URI of $HTTP_SERVER_VARS

1656      $str =& $HTTP_SERVER_VARS["REQUEST_URI"];
1657      serverStringToArray($str, $array, $frontParam);
1658      sanitizeArray($array);
1659      arrayToServerString($array, $frontParam, $str);
1660  
1661      // QUERY_STRING of $HTTP_SERVER_VARS

1662      $str =& $HTTP_SERVER_VARS["QUERY_STRING"];
1663      serverStringToArray($str, $array, $frontParam);
1664      sanitizeArray($array);
1665      arrayToServerString($array, $frontParam, $str);
1666  
1667      if (phpversion() >= '4.1.0') {
1668          // REQUEST_URI of $_SERVER

1669          $str =& $_SERVER["REQUEST_URI"];
1670          serverStringToArray($str, $array, $frontParam);
1671          sanitizeArray($array);
1672          arrayToServerString($array, $frontParam, $str);
1673  
1674          // QUERY_STRING of $_SERVER

1675          $str =& $_SERVER["QUERY_STRING"];
1676          serverStringToArray($str, $array, $frontParam);
1677          sanitizeArray($array);
1678          arrayToServerString($array, $frontParam, $str);
1679      }
1680  
1681      // $_GET

1682      convArrayForSanitizing($_GET, $array);
1683      sanitizeArray($array);
1684      revertArrayForSanitizing($array, $_GET);
1685  
1686      // $_REQUEST (only GET param)

1687      convArrayForSanitizing($_REQUEST, $array);
1688      sanitizeArray($array);
1689      revertArrayForSanitizing($array, $_REQUEST);
1690  }
1691  
1692  /**

1693   * Check ticket when not checked in plugin's admin page

1694   * to avoid CSRF.

1695   * Also avoid the access to plugin/index.php by guest user.

1696   */
1697  function ticketForPlugin(){
1698      global $CONF,$DIR_PLUGINS,$member,$ticketforplugin;
1699  
1700      /* initialize */

1701      $ticketforplugin=array();
1702      $ticketforplugin['ticket']=false;
1703  
1704      /* Check if using plugin's php file. */

1705      if ($p_translated=serverVar('PATH_TRANSLATED')) {
1706          if (!file_exists($p_translated)) $p_translated='';
1707      }
1708      if (!$p_translated) {
1709          $p_translated=serverVar('SCRIPT_FILENAME');
1710          if (!file_exists($p_translated)) {
1711              header("HTTP/1.0 404 Not Found");
1712              exit('');
1713          }
1714      }
1715      $p_translated=str_replace('\\','/',$p_translated);
1716      $d_plugins=str_replace('\\','/',$DIR_PLUGINS);
1717      if (strpos($p_translated,$d_plugins)!==0) return;// This isn't plugin php file.

1718  
1719      /* Solve the plugin php file or admin directory */

1720      $phppath=substr($p_translated,strlen($d_plugins));
1721      $phppath=preg_replace('!^/!','',$phppath);// Remove the first "/" if exists.

1722      $path=preg_replace('/^NP_(.*)\.php$/','$1',$phppath); // Remove the first "NP_" and the last ".php" if exists.

1723      $path=preg_replace('!^([^/]*)/(.*)$!','$1',$path); // Remove the "/" and beyond.

1724  
1725      /* Solve the plugin name. */

1726      $plugins=array();
1727      $query='SELECT pfile FROM '.sql_table('plugin');
1728      $res=sql_query($query);
1729      while($row=sql_fetch_row($res)) {
1730          $name=substr($row[0],3);
1731          $plugins[strtolower($name)]=$name;
1732      }
1733      sql_free_result($res);
1734      if ($plugins[$path]) $plugin_name=$plugins[$path];
1735      else if (in_array($path,$plugins)) $plugin_name=$path;
1736      else {
1737          header("HTTP/1.0 404 Not Found");
1738          exit('');
1739      }
1740  
1741      /* Return if not index.php */

1742      if ( $phppath!=strtolower($plugin_name).'/'
1743          && $phppath!=strtolower($plugin_name).'/index.php' ) return;
1744  
1745      /* Exit if not logged in. */

1746      if ( !$member->isLoggedIn() ) exit("You aren't logged in.");
1747  
1748      global $manager,$DIR_LIBS,$DIR_LANG,$HTTP_GET_VARS,$HTTP_POST_VARS;
1749  
1750      /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */

1751      if (!($p_translated=serverVar('PATH_TRANSLATED'))) $p_translated=serverVar('SCRIPT_FILENAME');
1752      if ($file=@file($p_translated)) {
1753          $prevline='';
1754          foreach($file as $line) {
1755              if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i',$prevline.$line)) return;
1756              $prevline=$line;
1757          }
1758      }
1759  
1760      /* Show a form if not valid ticket */

1761      if ( ( strstr(serverVar('REQUEST_URI'),'?') || serverVar('QUERY_STRING')
1762              || strtoupper(serverVar('REQUEST_METHOD'))=='POST' )
1763                  && (!$manager->checkTicket()) ){
1764  
1765          if (!class_exists('PluginAdmin')) {
1766              $language = getLanguageName();
1767  //            include($DIR_LANG . ereg_replace( '[\\|/]', '', $language) . '.php');

1768              include($DIR_LANG . preg_replace( '@\\|/@', '', $language) . '.php');
1769              include ($DIR_LIBS . 'PLUGINADMIN.php');
1770          }
1771          if (!(function_exists('mb_strimwidth') || extension_loaded('mbstring'))) {
1772              if (file_exists($DIR_LIBS.'mb_emulator/mb-emulator.php')) {
1773                  global $mbemu_internals;
1774                  include_once($DIR_LIBS.'mb_emulator/mb-emulator.php');
1775              }
1776          }
1777          $oPluginAdmin = new PluginAdmin($plugin_name);
1778          $oPluginAdmin->start();
1779          echo '<p>' . _ERROR_BADTICKET . "</p>\n";
1780  
1781          /* Show the form to confirm action */

1782          // PHP 4.0.x support

1783          $get=  (isset($_GET))  ? $_GET  : $HTTP_GET_VARS;
1784          $post= (isset($_POST)) ? $_POST : $HTTP_POST_VARS;
1785          // Resolve URI and QUERY_STRING

1786          if ($uri=serverVar('REQUEST_URI')) {
1787              list($uri,$qstring)=explode('?',$uri);
1788          } else {
1789              if ( !($uri=serverVar('PHP_SELF')) ) $uri=serverVar('SCRIPT_NAME');
1790              $qstring=serverVar('QUERY_STRING');
1791          }
1792          if ($qstring) $qstring='?'.$qstring;
1793          echo '<p>'._SETTINGS_UPDATE.' : '._QMENU_PLUGINS.' <span style="color:red;">'.
1794              htmlspecialchars($plugin_name)."</span> ?</p>\n";
1795          switch(strtoupper(serverVar('REQUEST_METHOD'))){
1796          case 'POST':
1797              echo '<form method="POST" action="'.htmlspecialchars($uri.$qstring).'">';
1798              $manager->addTicketHidden();
1799              _addInputTags($post);
1800              break;
1801          case 'GET':
1802              echo '<form method="GET" action="'.htmlspecialchars($uri).'">';
1803              $manager->addTicketHidden();
1804              _addInputTags($get);
1805          default:
1806              break;
1807          }
1808          echo '<input type="submit" value="'._YES.'" />&nbsp;&nbsp;&nbsp;&nbsp;';
1809          echo '<input type="button" value="'._NO.'" onclick="history.back(); return false;" />';
1810          echo "</form>\n";
1811  
1812          $oPluginAdmin->end();
1813          exit;
1814      }
1815  
1816      /* Create new ticket */

1817      $ticket=$manager->addTicketToUrl('');
1818      $ticketforplugin['ticket']=substr($ticket,strpos($ticket,'ticket=')+7);
1819  }
1820  function _addInputTags(&$keys,$prefix=''){
1821      foreach($keys as $key=>$value){
1822          if ($prefix) $key=$prefix.'['.$key.']';
1823          if (is_array($value)) _addInputTags($value,$key);
1824          else {
1825              if (get_magic_quotes_gpc()) $value=stripslashes($value);
1826              if ($key=='ticket') continue;
1827              echo '<input type="hidden" name="'.htmlspecialchars($key).
1828                  '" value="'.htmlspecialchars($value).'" />'."\n";
1829          }
1830      }
1831  }
1832  
1833  /**

1834   * Convert the server string such as $_SERVER['REQUEST_URI']

1835   * to arry like arry['blogid']=1 and array['page']=2 etc.

1836   */
1837  function serverStringToArray($str, &$array, &$frontParam)
1838  {
1839      // init param

1840      $array = array();
1841      $fronParam = "";
1842  
1843      // split front param, e.g. /index.php, and others, e.g. blogid=1&page=2

1844      if (strstr($str, "?")){
1845          list($frontParam, $args) = preg_split("/\?/", $str, 2);
1846      }
1847      else {
1848          $args = $str;
1849          $frontParam = "";
1850      }
1851  
1852      // If there is no args like blogid=1&page=2, return

1853      if (!strstr($str, "=") && !strlen($frontParam)) {
1854          $frontParam = $str;
1855          return;
1856      }
1857  
1858      $array = explode("&", $args);
1859  }
1860  
1861  /**

1862   * Convert array like array['blogid'] to server string

1863   * such as $_SERVER['REQUEST_URI']

1864   */
1865  function arrayToServerString($array, $frontParam, &$str)
1866  {
1867      if (strstr($str, "?")) {
1868          $str = $frontParam . "?";
1869      } else {
1870          $str = $frontParam;
1871      }
1872      if (count($array)) {
1873          $str .= implode("&", $array);
1874      }
1875  }
1876  
1877  /**

1878   * Sanitize array parameters.

1879   * This function checks both key and value.

1880   * - check key if it inclues " (double quote),  remove from array

1881   * - check value if it includes \ (escape sequece), remove remaining string

1882   */
1883  function sanitizeArray(&$array)
1884  {
1885      $excludeListForSanitization = array('query');
1886  //    $excludeListForSanitization = array();

1887  
1888      foreach ($array as $k => $v) {
1889  
1890          // split to key and value

1891          list($key, $val) = preg_split("/=/", $v, 2);
1892          if (!isset($val)) {
1893              continue;
1894          }
1895  
1896          // when magic quotes is on, need to use stripslashes,

1897          // and then addslashes

1898          if (get_magic_quotes_gpc()) {
1899              $val = stripslashes($val);
1900          }
1901          $val = addslashes($val);
1902  
1903          // if $key is included in exclude list, skip this param

1904          if (!in_array($key, $excludeListForSanitization)) {
1905  
1906              // check value

1907              if (strpos($val, '\\')) {
1908                  list($val, $tmp) = explode('\\', $val);
1909              }
1910              
1911              // remove control code etc.

1912              $val = strtr($val, "\0\r\n<>'\"", "       ");
1913  
1914              // check key

1915              if (preg_match('/\"/i', $key)) {
1916                  unset($array[$k]);
1917                  continue;
1918              }
1919  
1920              // set sanitized info

1921              $array[$k] = sprintf("%s=%s", $key, $val);
1922          }
1923      }
1924  }
1925  
1926  /**

1927   * Convert array for sanitizeArray function

1928   */
1929  function convArrayForSanitizing($src, &$array)
1930  {
1931      $array = array();
1932      foreach ($src as $key => $val) {
1933          if (key_exists($key, $_GET)) {
1934              array_push($array, sprintf("%s=%s", $key, $val));
1935          }
1936      }
1937  }
1938  
1939  /**

1940   * Revert array after sanitizeArray function

1941   */
1942  function revertArrayForSanitizing($array, &$dst)
1943  {
1944      foreach ($array as $v) {
1945          list($key, $val) = preg_split("/=/", $v, 2);
1946          $dst[$key] = $val;
1947      }
1948  }
1949  
1950  /**

1951   * Stops processing the request and redirects to the given URL.

1952   * - no actual contents should have been sent to the output yet

1953   * - the URL will be stripped of illegal or dangerous characters

1954   */
1955  function redirect($url) {
1956      $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%*]|i', '', $url);
1957      header('Location: ' . $url);
1958      exit;
1959  }
1960  
1961  /**

1962   * Strip HTML tags from a string

1963   * This function is a bit more intelligent than a regular call to strip_tags(),

1964   * because it also deletes the contents of certain tags and cleans up any

1965   * unneeded whitespace.

1966   */
1967  function stringStripTags ($string) {
1968      $string = preg_replace("/<del[^>]*>.+<\/del[^>]*>/isU", '', $string);
1969      $string = preg_replace("/<script[^>]*>.+<\/script[^>]*>/isU", '', $string);
1970      $string = preg_replace("/<style[^>]*>.+<\/style[^>]*>/isU", '', $string);
1971      $string = str_replace('>', '> ', $string);
1972      $string = str_replace('<', ' <', $string);
1973      $string = strip_tags($string);
1974      $string = preg_replace("/\s+/", " ", $string);
1975      $string = trim($string);
1976      return $string;
1977  }
1978  
1979  /**

1980   * Make a string containing HTML safe for use in a HTML attribute

1981   * Tags are stripped and entities are normalized

1982   */
1983  function stringToAttribute ($string) {
1984      $string = stringStripTags($string);
1985      $string = entity::named_to_numeric($string);
1986      $string = entity::normalize_numeric($string);
1987  
1988      if (strtoupper(_CHARSET) == 'UTF-8') {
1989          $string = entity::numeric_to_utf8($string);
1990      }
1991  
1992      $string = entity::specialchars($string, 'html');
1993      $string = entity::numeric_to_named($string);
1994      return $string;
1995  }
1996  
1997  /**

1998   * Make a string containing HTML safe for use in a XML document

1999   * Tags are stripped, entities are normalized and named entities are

2000   * converted to numeric entities.

2001   */
2002  function stringToXML ($string) {
2003      $string = stringStripTags($string);
2004      $string = entity::named_to_numeric($string);
2005      $string = entity::normalize_numeric($string);
2006  
2007      if (strtoupper(_CHARSET) == 'UTF-8') {
2008          $string = entity::numeric_to_utf8($string);
2009      }
2010  
2011      $string = entity::specialchars($string, 'xml');
2012      return $string;
2013  }
2014  
2015  // START: functions from the end of file BLOG.php

2016  // used for mail notification (html -> text)

2017  function toAscii($html) {
2018      // strip off most tags

2019      $html = strip_tags($html,'<a>');
2020      $to_replace = "/<a[^>]*href=[\"\']([^\"^']*)[\"\'][^>]*>([^<]*)<\/a>/i";
2021      _links_init();
2022      $ascii = preg_replace_callback ($to_replace, '_links_add', $html);
2023      $ascii .= "\n\n" . _links_list();
2024      return strip_tags($ascii);
2025  }
2026  
2027  function _links_init() {
2028     global $tmp_links;
2029     $tmp_links = array();
2030  }
2031  
2032  function _links_add($match) {
2033     global $tmp_links;
2034     array_push($tmp_links, $match[1]);
2035     return $match[2] . ' [' . sizeof($tmp_links) .']';
2036  }
2037  
2038  function _links_list() {
2039     global $tmp_links;
2040     $output = '';
2041     $i = 1;
2042     foreach ($tmp_links as $current) {
2043        $output .= "[$i] $current\n";
2044        $i++;
2045     }
2046     return $output;
2047  }
2048  // END: functions from the end of file BLOG.php

2049  
2050  // START: functions from the end of file ADMIN.php

2051  /**

2052   * @todo document this

2053   */
2054  function encode_desc(&$data)
2055  {
2056      $to_entities = get_html_translation_table(HTML_ENTITIES);
2057  
2058      $from_entities = array_flip($to_entities);
2059  
2060      $data = strtr($data,$from_entities);
2061      $data = strtr($data,$to_entities);
2062  
2063      return $data;
2064  }
2065  
2066  /**

2067   * Returns the Javascript code for a bookmarklet that works on most modern browsers

2068   *

2069   * @param blogid

2070   */
2071  function getBookmarklet($blogid) {
2072      global $CONF;
2073  
2074      // normal

2075      $document = 'document';
2076      $bookmarkletline = "javascript:Q='';x=".$document.";y=window;if(x.selection){Q=x.selection.createRange().text;}else if(y.getSelection){Q=y.getSelection();}else if(x.getSelection){Q=x.getSelection();}wingm=window.open('";
2077      $bookmarkletline .= $CONF['AdminURL'] . "bookmarklet.php?blogid=$blogid";
2078      $bookmarkletline .="&logtext='+escape(Q)+'&loglink='+escape(x.location.href)+'&loglinktitle='+escape(x.title),'nucleusbm','scrollbars=yes,width=600,height=550,left=10,top=10,status=yes,resizable=yes');wingm.focus();";
2079  
2080      return $bookmarkletline;
2081  }
2082  // END: functions from the end of file ADMIN.php

2083  
2084  /**

2085   * Returns a variable or null if not set

2086   *

2087   * @param mixed Variable

2088   * @return mixed Variable

2089   */
2090  function ifset(&$var) {
2091      if (isset($var)) {
2092          return $var;
2093      }
2094  
2095      return null;
2096  }
2097  
2098  /**

2099   * Returns number of subscriber to an event

2100   *

2101   * @param event

2102   * @return number of subscriber(s)

2103   */
2104  function numberOfEventSubscriber($event) {
2105      $query = 'SELECT COUNT(*) as count FROM ' . sql_table('plugin_event') . ' WHERE event=\'' . $event . '\'';
2106      $res = sql_query($query);
2107      $obj = sql_fetch_object($res);
2108      return $obj->count;
2109  }
2110  
2111  function selectSpecialSkinType($id) {
2112      global $special;
2113      $special = strtolower($id);
2114  }
2115  
2116  ?>


Generated: Sun Aug 1 03:56:06 2010
Open Source related documentation for developers.