[ Index ]

PHP Cross Reference of Nucleus CMS 3.64

title

Body

[close]

/nucleus3.64/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 1507 2011-03-14 16:59:39Z ftruscot $
  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.64';
  24  $nucleus['codename'] = '';
  25  
  26  // check and die if someone is trying to override internal globals (when register_globals turn on)
  27  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'));
  28  
  29  $CONF['debug'] = 0;
  30  if ($CONF['debug']) {
  31      error_reporting(E_ALL); // report all errors!
  32  } else {
  33      ini_set('display_errors','0');
  34      error_reporting(E_ERROR | E_WARNING | E_PARSE);
  35  }
  36  
  37  /*
  38      Indicates when Nucleus should display startup errors. Set to 1 if you want
  39      the error enabled (default), false otherwise
  40  
  41      alertOnHeadersSent
  42          Displays an error when visiting a public Nucleus page and headers have
  43          been sent out to early. This usually indicates an error in either a
  44          configuration file or a language file, and could cause Nucleus to
  45          malfunction
  46      alertOnSecurityRisk
  47          Displays an error only when visiting the admin area, and when one or
  48          more of the installation files (install.php, install.sql, upgrades/
  49          directory) are still on the server.
  50  */
  51  
  52  if (!isset($CONF['alertOnHeadersSent']) || (isset($CONF['alertOnHeadersSent'])&& $CONF['alertOnHeadersSent'] !== 0))
  53  {
  54      $CONF['alertOnHeadersSent']  = 1;
  55  }
  56  $CONF['alertOnSecurityRisk'] = 1;
  57  /*$CONF['ItemURL']           = $CONF['Self'];
  58  $CONF['ArchiveURL']          = $CONF['Self'];
  59  $CONF['ArchiveListURL']      = $CONF['Self'];
  60  $CONF['MemberURL']           = $CONF['Self'];
  61  $CONF['SearchURL']           = $CONF['Self'];
  62  $CONF['BlogURL']             = $CONF['Self'];
  63  $CONF['CategoryURL']         = $CONF['Self'];
  64  
  65  // switch URLMode back to normal when $CONF['Self'] ends in .php
  66  // this avoids urls like index.php/item/13/index.php/item/15
  67  if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {
  68      $CONF['URLMode'] = 'normal';
  69  }*/
  70  
  71  /*
  72      Set these to 1 to allow viewing of future items or draft items
  73      Should really never do this, but can be useful for some plugins that might need to
  74      Could cause some other issues if you use future posts otr drafts
  75      So use with care
  76  */
  77  $CONF['allowDrafts'] = 0;
  78  $CONF['allowFuture'] = 0;
  79  
  80  if (getNucleusPatchLevel() > 0) {
  81      $nucleus['version'] .= '/' . getNucleusPatchLevel();
  82  }
  83  
  84  // Avoid notices
  85  if (!isset($CONF['installscript'])) {
  86      $CONF['installscript'] = 0;
  87  }
  88  
  89  // we will use postVar, getVar, ... methods instead of HTTP_GET_VARS or _GET
  90  if ($CONF['installscript'] != 1) { // vars were already included in install.php
  91      if (phpversion() >= '4.1.0') {
  92          include_once ($DIR_LIBS . 'vars4.1.0.php');
  93      } else {
  94          include_once ($DIR_LIBS . 'vars4.0.6.php');
  95      }
  96  }
  97  
  98  // sanitize option
  99  $bLoggingSanitizedResult=0;
 100  $bSanitizeAndContinue=0;
 101  
 102  $orgRequestURI = serverVar('REQUEST_URI');
 103  sanitizeParams();
 104  
 105  // get all variables that can come from the request and put them in the global scope
 106  $blogid       = requestVar('blogid');
 107  $itemid       = intRequestVar('itemid');
 108  $catid        = intRequestVar('catid');
 109  $skinid       = requestVar('skinid');
 110  $memberid     = requestVar('memberid');
 111  $archivelist  = requestVar('archivelist');
 112  $imagepopup   = requestVar('imagepopup');
 113  $archive      = requestVar('archive');
 114  $query        = requestVar('query');
 115  $highlight    = requestVar('highlight');
 116  $amount       = requestVar('amount');
 117  $action       = requestVar('action');
 118  $nextaction   = requestVar('nextaction');
 119  $maxresults   = requestVar('maxresults');
 120  $startpos     = intRequestVar('startpos');
 121  $errormessage = '';
 122  $error        = '';
 123  $special      = requestVar('special');
 124  $virtualpath  = ((getVar('virtualpath') != null) ? getVar('virtualpath') : serverVar('PATH_INFO'));
 125  
 126  if (!headers_sent() ) {
 127      header('Generator: Nucleus CMS ' . $nucleus['version']);
 128  }
 129  
 130  // include core classes that are needed for login & plugin handling
 131  include_once ($DIR_LIBS . 'mysql.php');
 132  // added for 3.5 sql_* wrapper
 133  global $MYSQL_HANDLER;
 134  if (!isset($MYSQL_HANDLER))
 135      $MYSQL_HANDLER = array('mysql','');
 136  if ($MYSQL_HANDLER[0] == '')
 137      $MYSQL_HANDLER[0] = 'mysql';
 138  include_once($DIR_LIBS . 'sql/'.$MYSQL_HANDLER[0].'.php');
 139  // end new for 3.5 sql_* wrapper
 140  include ($DIR_LIBS . 'MEMBER.php');
 141  include ($DIR_LIBS . 'ACTIONLOG.php');
 142  include ($DIR_LIBS . 'MANAGER.php');
 143  include ($DIR_LIBS . 'PLUGIN.php');
 144  
 145  $manager =& MANAGER::instance();
 146  
 147  // make sure there's no unnecessary escaping:
 148  //set_magic_quotes_runtime(0);
 149  if (version_compare(PHP_VERSION, '5.3.0', '<')) {
 150      ini_set('magic_quotes_runtime', '0');
 151  }
 152  
 153  // Avoid notices
 154  if (!isset($CONF['UsingAdminArea'])) {
 155      $CONF['UsingAdminArea'] = 0;
 156  }
 157  
 158  // only needed when updating logs
 159  if ($CONF['UsingAdminArea']) {
 160      include ($DIR_LIBS . 'xmlrpc.inc.php');  // XML-RPC client classes
 161      include_once ($DIR_LIBS . 'ADMIN.php');
 162  }
 163  
 164  // connect to database
 165  sql_connect();
 166  $SQLCount = 0;
 167  
 168  // logs sanitized result if need
 169  if ($orgRequestURI!==serverVar('REQUEST_URI')) {
 170      $msg = "Sanitized [" . serverVar('REMOTE_ADDR') . "] ";
 171      $msg .= $orgRequestURI . " -> " . serverVar('REQUEST_URI');
 172      if ($bLoggingSanitizedResult) {
 173          addToLog(WARNING, $msg);
 174      }
 175      if (!$bSanitizeAndContinue) {
 176          die("");
 177      }
 178  }
 179  
 180  // makes sure database connection gets closed on script termination
 181  register_shutdown_function('sql_disconnect');
 182  
 183  // read config
 184  getConfig();
 185  
 186  // Properly set $CONF['Self'] and others if it's not set... usually when we are access from admin menu
 187  if (!isset($CONF['Self'])) {
 188      $CONF['Self'] = $CONF['IndexURL'];
 189      // strip trailing /
 190      if ($CONF['Self'][strlen($CONF['Self']) -1] == "/") {
 191          $CONF['Self'] = substr($CONF['Self'], 0, strlen($CONF['Self']) -1);
 192      }
 193  
 194  /*    $CONF['ItemURL']        = $CONF['Self'];
 195      $CONF['ArchiveURL']     = $CONF['Self'];
 196      $CONF['ArchiveListURL'] = $CONF['Self'];
 197      $CONF['MemberURL']      = $CONF['Self'];
 198      $CONF['SearchURL']      = $CONF['Self'];
 199      $CONF['BlogURL']        = $CONF['Self'];
 200      $CONF['CategoryURL']    = $CONF['Self'];*/
 201  }
 202  
 203  $CONF['ItemURL'] = $CONF['Self'];
 204  $CONF['ArchiveURL'] = $CONF['Self'];
 205  $CONF['ArchiveListURL'] = $CONF['Self'];
 206  $CONF['MemberURL'] = $CONF['Self'];
 207  $CONF['SearchURL'] = $CONF['Self'];
 208  $CONF['BlogURL'] = $CONF['Self'];
 209  $CONF['CategoryURL'] = $CONF['Self'];
 210  
 211  // switch URLMode back to normal when $CONF['Self'] ends in .php
 212  // this avoids urls like index.php/item/13/index.php/item/15
 213  if (!isset($CONF['URLMode']) || (($CONF['URLMode'] == 'pathinfo') && (substr($CONF['Self'], strlen($CONF['Self']) - 4) == '.php'))) {
 214      $CONF['URLMode'] = 'normal';
 215  }
 216  
 217  // automatically use simpler toolbar for mozilla
 218  if (($CONF['DisableJsTools'] == 0) && strstr(serverVar('HTTP_USER_AGENT'), 'Mozilla/5.0') && strstr(serverVar('HTTP_USER_AGENT'), 'Gecko') ) {
 219      $CONF['DisableJsTools'] = 2;
 220  }
 221  
 222  // login if cookies set
 223  $member = new MEMBER();
 224  
 225  // secure cookie key settings (either 'none', 0, 8, 16, 24, or 32)
 226  if (!isset($CONF['secureCookieKey'])) $CONF['secureCookieKey']=24;
 227  switch($CONF['secureCookieKey']){
 228  case 8:
 229      $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
 230      break;
 231  case 16:
 232      $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
 233      break;
 234  case 24:
 235      $CONF['secureCookieKeyIP']=preg_replace('/\.[0-9]+$/','',serverVar('REMOTE_ADDR'));
 236      break;
 237  case 32:
 238      $CONF['secureCookieKeyIP']=serverVar('REMOTE_ADDR');
 239      break;
 240  default:
 241      $CONF['secureCookieKeyIP']='';
 242  }
 243  
 244  // login/logout when required or renew cookies
 245  if ($action == 'login') {
 246      // Form Authentication
 247      $login = postVar('login');
 248      $pw = postVar('password');
 249      $shared = intPostVar('shared'); // shared computer or not
 250  
 251      $pw=substr($pw,0,40); // avoid md5 collision by using a long key
 252  
 253      if ($member->login($login, $pw) ) {
 254  
 255          $member->newCookieKey();
 256          $member->setCookies($shared);
 257  
 258          if ($CONF['secureCookieKey']!=='none') {
 259              // secure cookie key
 260              $member->setCookieKey(md5($member->getCookieKey().$CONF['secureCookieKeyIP']));
 261              $member->write();
 262          }
 263  
 264          // allows direct access to parts of the admin area after logging in
 265          if ($nextaction) {
 266              $action = $nextaction;
 267          }
 268  
 269          $manager->notify('LoginSuccess', array('member' => &$member, 'username' => $login) );
 270          $errormessage = '';
 271          ACTIONLOG::add(INFO, "Login successful for $login (sharedpc=$shared)");
 272      } else {
 273          // errormessage for [%errordiv%]
 274          $trimlogin = trim($login);
 275          if (empty($trimlogin))
 276          {
 277              $errormessage = "Please enter a username.";
 278          }
 279          else 
 280          {
 281              $errormessage = 'Login failed for ' . $login;
 282          } 
 283  
 284          $manager->notify('LoginFailed', array('username' => $login) );
 285          ACTIONLOG::add(INFO, $errormessage);
 286      }
 287  /*
 288  
 289  Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
 290  
 291  } elseif (serverVar('PHP_AUTH_USER') && serverVar('PHP_AUTH_PW')) {
 292      // HTTP Authentication
 293      $login  = serverVar('PHP_AUTH_USER');
 294      $pw     = serverVar('PHP_AUTH_PW');
 295  
 296      if ($member->login($login, $pw) ) {
 297          $manager->notify('LoginSuccess',array('member' => &$member));
 298          ACTIONLOG::add(INFO, "HTTP authentication successful for $login");
 299      } else {
 300          $manager->notify('LoginFailed',array('username' => $login));
 301          ACTIONLOG::add(INFO, 'HTTP authentication failed for ' . $login);
 302  
 303          //Since bad credentials, generate an apropriate error page
 304          header("WWW-Authenticate: Basic realm=\"Nucleus CMS {$nucleus['version']}\"");
 305          header('HTTP/1.0 401 Unauthorized');
 306          echo 'Invalid username or password';
 307          exit;
 308      }
 309  */
 310  
 311  } elseif (($action == 'logout') && (!headers_sent() ) && cookieVar($CONF['CookiePrefix'] . 'user') ) {
 312      // remove cookies on logout
 313      setcookie($CONF['CookiePrefix'] . 'user', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
 314      setcookie($CONF['CookiePrefix'] . 'loginkey', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
 315      $manager->notify('Logout', array('username' => cookieVar($CONF['CookiePrefix'] . 'user') ) );
 316  } elseif (cookieVar($CONF['CookiePrefix'] . 'user') ) {
 317      // Cookie Authentication
 318      $ck=cookieVar($CONF['CookiePrefix'] . 'loginkey');
 319      // secure cookie key
 320      $ck=substr($ck,0,32); // avoid md5 collision by using a long key
 321      if ($CONF['secureCookieKey']!=='none') $ck=md5($ck.$CONF['secureCookieKeyIP']);
 322      $res = $member->cookielogin(cookieVar($CONF['CookiePrefix'] . 'user'), $ck );
 323      unset($ck);
 324  
 325      // renew cookies when not on a shared computer
 326      if ($res && (cookieVar($CONF['CookiePrefix'] . 'sharedpc') != 1) && (!headers_sent() ) ) {
 327          $member->setCookieKey(cookieVar($CONF['CookiePrefix'] . 'loginkey'));
 328          $member->setCookies();
 329      }
 330  }
 331  
 332  // login completed
 333  $manager->notify('PostAuthentication', array('loggedIn' => $member->isLoggedIn() ) );
 334  ticketForPlugin();
 335  
 336  // first, let's see if the site is disabled or not. always allow admin area access.
 337  if ($CONF['DisableSite'] && !$member->isAdmin() && !$CONF['UsingAdminArea']) {
 338      redirect($CONF['DisableSiteURL']);
 339      exit;
 340  }
 341  
 342  // load other classes
 343  include ($DIR_LIBS . 'PARSER.php');
 344  include ($DIR_LIBS . 'SKIN.php');
 345  include ($DIR_LIBS . 'TEMPLATE.php');
 346  include ($DIR_LIBS . 'BLOG.php');
 347  include ($DIR_LIBS . 'BODYACTIONS.php');
 348  include ($DIR_LIBS . 'COMMENTS.php');
 349  include ($DIR_LIBS . 'COMMENT.php');
 350  //include($DIR_LIBS . 'ITEM.php');
 351  include ($DIR_LIBS . 'NOTIFICATION.php');
 352  include ($DIR_LIBS . 'BAN.php');
 353  include ($DIR_LIBS . 'PAGEFACTORY.php');
 354  include ($DIR_LIBS . 'SEARCH.php');
 355  include ($DIR_LIBS . 'entity.php');
 356  
 357  
 358  // set lastVisit cookie (if allowed)
 359  if (!headers_sent() ) {
 360      if ($CONF['LastVisit']) {
 361          setcookie($CONF['CookiePrefix'] . 'lastVisit', time(), time() + 2592000, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
 362      } else {
 363          setcookie($CONF['CookiePrefix'] . 'lastVisit', '', (time() - 2592000), $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);
 364      }
 365  }
 366  
 367  // read language file, only after user has been initialized
 368  $language = getLanguageName();
 369  
 370  # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
 371  # original ereg_replace: ereg_replace( '[\\|/]', '', $language) . '.php')
 372  # important note that '\' must be matched with '\\\\' in preg* expressions
 373  
 374  include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');
 375  
 376  /*
 377      Backed out for now: See http://forum.nucleuscms.org/viewtopic.php?t=3684 for details
 378  
 379  // To remove after v2.5 is released and language files have been updated.
 380  // Including this makes sure that language files for v2.5beta can still be used for v2.5final
 381  // without having weird _SETTINGS_EXTAUTH string showing up in the admin area.
 382  if (!defined('_MEMBERS_BYPASS'))
 383  {
 384      define('_SETTINGS_EXTAUTH',         'Enable External Authentication');
 385      define('_WARNING_EXTAUTH',          'Warning: Enable only if needed.');
 386      define('_MEMBERS_BYPASS',           'Use External Authentication');
 387  }
 388  
 389  */
 390  
 391  // make sure the archivetype skinvar keeps working when _ARCHIVETYPE_XXX not defined
 392  if (!defined('_ARCHIVETYPE_MONTH') )
 393  {
 394      define('_ARCHIVETYPE_DAY', 'day');
 395      define('_ARCHIVETYPE_MONTH', 'month');
 396      define('_ARCHIVETYPE_YEAR', 'year');
 397  }
 398  
 399  // decode path_info
 400  if ($CONF['URLMode'] == 'pathinfo') {
 401      // initialize keywords if this hasn't been done before
 402      if (!isset($CONF['ItemKey']) || $CONF['ItemKey'] == '') {
 403          $CONF['ItemKey'] = 'item';
 404      }
 405  
 406      if (!isset($CONF['ArchiveKey']) || $CONF['ArchiveKey'] == '') {
 407          $CONF['ArchiveKey'] = 'archive';
 408      }
 409  
 410      if (!isset($CONF['ArchivesKey']) || $CONF['ArchivesKey'] == '') {
 411          $CONF['ArchivesKey'] = 'archives';
 412      }
 413  
 414      if (!isset($CONF['MemberKey']) || $CONF['MemberKey'] == '') {
 415          $CONF['MemberKey'] = 'member';
 416      }
 417  
 418      if (!isset($CONF['BlogKey']) || $CONF['BlogKey'] == '') {
 419          $CONF['BlogKey'] = 'blog';
 420      }
 421  
 422      if (!isset($CONF['CategoryKey']) || $CONF['CategoryKey'] == '') {
 423          $CONF['CategoryKey'] = 'category';
 424      }
 425  
 426      if (!isset($CONF['SpecialskinKey']) || $CONF['SpecialskinKey'] == '') {
 427          $CONF['SpecialskinKey'] = 'special';
 428      }
 429  
 430      $parsed = false;
 431      $manager->notify(
 432          'ParseURL',
 433          array(
 434              'type' => basename(serverVar('SCRIPT_NAME') ), // e.g. item, blog, ...
 435              'info' => $virtualpath,
 436              'complete' => &$parsed
 437          )
 438      );
 439  
 440      if (!$parsed) {
 441          // default implementation
 442          $data = explode("/", $virtualpath );
 443          for ($i = 0; $i < sizeof($data); $i++) {
 444              switch ($data[$i]) {
 445                  case $CONF['ItemKey']: // item/1 (blogid)
 446                      $i++;
 447  
 448                      if ($i < sizeof($data) ) {
 449                          $itemid = intval($data[$i]);
 450                      }
 451                      break;
 452  
 453                  case $CONF['ArchivesKey']: // archives/1 (blogid)
 454                      $i++;
 455  
 456                      if ($i < sizeof($data) ) {
 457                          $archivelist = intval($data[$i]);
 458                      }
 459                      break;
 460  
 461                  case $CONF['ArchiveKey']: // two possibilities: archive/yyyy-mm or archive/1/yyyy-mm (with blogid)
 462                      if ((($i + 1) < sizeof($data) ) && (!strstr($data[$i + 1], '-') ) ) {
 463                          $blogid = intval($data[++$i]);
 464                      }
 465  
 466                      $i++;
 467  
 468                      if ($i < sizeof($data) ) {
 469                          $archive = $data[$i];
 470                      }
 471                      break;
 472  
 473                  case 'blogid': // blogid/1
 474                  case $CONF['BlogKey']: // blog/1
 475                      $i++;
 476  
 477                      if ($i < sizeof($data) ) {
 478                          $blogid = intval($data[$i]);
 479                      }
 480                      break;
 481  
 482                  case $CONF['CategoryKey']: // category/1 (catid)
 483                  case 'catid':
 484                      $i++;
 485  
 486                      if ($i < sizeof($data) ) {
 487                          $catid = intval($data[$i]);
 488                      }
 489                      break;
 490  
 491                  case $CONF['MemberKey']:
 492                      $i++;
 493  
 494                      if ($i < sizeof($data) ) {
 495                          $memberid = intval($data[$i]);
 496                      }
 497                      break;
 498  
 499                  case $CONF['SpecialskinKey']:
 500                      $i++;
 501  
 502                      if ($i < sizeof($data) ) {
 503                          $special = $data[$i];
 504                          $_REQUEST['special'] = $special;    
 505                      }
 506                      break;
 507  
 508                  default:
 509                      // skip...
 510              }
 511          }
 512      }
 513  }
 514  /*     PostParseURL is a place to cleanup any of the path-related global variables before the selector function is run.
 515      It has 2 values in the data in case the original virtualpath is needed, but most the use will be in tweaking
 516      global variables to clean up (scrub out catid or add catid) or to set someother global variable based on
 517      the values of something like catid or itemid
 518      New in 3.60
 519  */
 520  $manager->notify(
 521      'PostParseURL',
 522      array(
 523          'type' => basename(serverVar('SCRIPT_NAME') ), // e.g. item, blog, ...
 524          'info' => $virtualpath
 525      )
 526  );
 527  
 528  function include_libs($file,$once=true,$require=true){
 529         global $DIR_LIBS;
 530         if (!is_dir($DIR_LIBS)) exit;
 531         if ($once && $require) require_once($DIR_LIBS.$file);
 532         elseif ($once && !$require) include_once($DIR_LIBS.$file);
 533         elseif ($require) require($DIR_LIBS.$file);
 534         else include($DIR_LIBS.$file);
 535  }
 536  
 537  function include_plugins($file,$once=true,$require=true){
 538         global $DIR_PLUGINS;
 539         if (!is_dir($DIR_PLUGINS)) exit;
 540         if ($once && $require) require_once($DIR_PLUGINS.$file);
 541         elseif ($once && !$require) include_once($DIR_PLUGINS.$file);
 542         elseif ($require) require($DIR_PLUGINS.$file);
 543         else include($DIR_PLUGINS.$file);
 544  }
 545  
 546  function intPostVar($name) {
 547      return intval(postVar($name) );
 548  }
 549  
 550  function intGetVar($name) {
 551      return intval(getVar($name) );
 552  }
 553  
 554  function intRequestVar($name) {
 555      return intval(requestVar($name) );
 556  }
 557  
 558  function intCookieVar($name) {
 559      return intval(cookieVar($name) );
 560  }
 561  
 562  /**
 563    * returns the currently used version (100 = 1.00, 101 = 1.01, etc...)
 564    */
 565  function getNucleusVersion() {
 566      return 364;
 567  }
 568  
 569  /**
 570   * power users can install patches in between nucleus releases. These patches
 571   * usually add new functionality in the plugin API and allow those to
 572   * be tested without having to install CVS.
 573   */
 574  function getNucleusPatchLevel() {
 575      return 0;
 576  }
 577  
 578  /**
 579   * returns the latest version available for download from nucleuscms.org
 580   * or false if unable to attain data
 581   * format will be major.minor/patachlevel
 582   * e.g. 3.41 or 3.41/02
 583   */
 584  function getLatestVersion() {
 585      if (!function_exists('curl_init')) return false;
 586      $crl = curl_init();
 587      $timeout = 5;
 588      curl_setopt ($crl, CURLOPT_URL,'http://nucleuscms.org/version_check.php');
 589      curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
 590      curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
 591      $ret = curl_exec($crl);
 592      curl_close($crl);
 593      return $ret;
 594  
 595  }
 596  
 597  /**
 598    * Connects to mysql server
 599    */
 600  /* moved to $DIR_LIBS/sql/*.php handler files
 601  function sql_connect() {
 602      global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN;
 603  
 604      $MYSQL_CONN = @mysql_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD) or startUpError('<p>Could not connect to MySQL database.</p>', 'Connect Error');
 605      mysql_select_db($MYSQL_DATABASE) or startUpError('<p>Could not select database: ' . mysql_error() . '</p>', 'Connect Error');
 606  
 607      return $MYSQL_CONN;
 608  }*/
 609  
 610  /**
 611   * returns a prefixed nucleus table name
 612   */
 613  function sql_table($name) {
 614      global $MYSQL_PREFIX;
 615  
 616      if ($MYSQL_PREFIX) {
 617          return $MYSQL_PREFIX . 'nucleus_' . $name;
 618      } else {
 619          return 'nucleus_' . $name;
 620      }
 621  }
 622  
 623  function sendContentType($contenttype, $pagetype = '', $charset = _CHARSET) {
 624      global $manager, $CONF;
 625  
 626      if (!headers_sent() ) {
 627          // if content type is application/xhtml+xml, only send it to browsers
 628          // that can handle it (IE6 cannot). Otherwise, send text/html
 629  
 630          // v2.5: For admin area pages, keep sending text/html (unless it's a debug version)
 631          //       application/xhtml+xml still causes too much problems with the javascript implementations
 632  
 633          // v3.3: ($CONF['UsingAdminArea'] && !$CONF['debug']) gets removed,
 634          //       application/xhtml+xml seems to be working, so we're going to use it if we can.
 635          if (
 636                  ($contenttype == 'application/xhtml+xml')
 637              &&  (!stristr(serverVar('HTTP_ACCEPT'), 'application/xhtml+xml') )
 638              ) {
 639              $contenttype = 'text/html';
 640          }
 641          $manager->notify(
 642              'PreSendContentType',
 643              array(
 644                  'contentType' => &$contenttype,
 645                  'charset' => &$charset,
 646                  'pageType' => $pagetype
 647              )
 648          );
 649          // strip strange characters
 650          $contenttype = preg_replace('|[^a-z0-9-+./]|i', '', $contenttype);
 651          $charset = preg_replace('|[^a-z0-9-_]|i', '', $charset);
 652  
 653          if ($charset != '') {
 654              header('Content-Type: ' . $contenttype . '; charset=' . $charset);
 655          } else {
 656              header('Content-Type: ' . $contenttype);
 657          }
 658      }
 659  }
 660  
 661  /**
 662   * Errors before the database connection has been made - moved to
 663   */
 664  /* moved to $DIR_LIBS/sql/*.php handler files
 665  function startUpError($msg, $title) {
 666  
 667  
 668      ?>
 669      <html xmlns="http://www.w3.org/1999/xhtml">
 670          <head><title><?php echo htmlspecialchars($title)?></title></head>
 671  
 672          <body>
 673              <h1><?php echo htmlspecialchars($title)?></h1>
 674              <?php echo $msg?>
 675          </body>
 676      </html>
 677      <?php   exit;
 678  }*/
 679  
 680  /**
 681    * disconnects from SQL server
 682    */
 683  /* moved to $DIR_LIBS/sql/*.php handler files
 684  function sql_disconnect() {
 685      @mysql_close();
 686  }*/
 687  
 688  /**
 689    * executes an SQL query
 690    */
 691  /* moved to $DIR_LIBS/sql/*.php handler files
 692  function sql_query($query) {
 693      global $SQLCount;
 694      $SQLCount++;
 695      $res = mysql_query($query) or print("mySQL error with query $query: " . mysql_error() . '<p />');
 696      return $res;
 697  }*/
 698  
 699  
 700  /**
 701   * Highlights a specific query in a given HTML text (not within HTML tags) and returns it
 702   * @param string $text text to be highlighted
 703   * @param string $expression regular expression to be matched (can be an array of expressions as well)
 704   * @param string $highlight highlight to be used (use \\0 to indicate the matched expression)
 705   * @return string
 706   **/
 707  function highlight($text, $expression, $highlight) {
 708  
 709      if (!$highlight || !$expression)
 710      {
 711          return $text;
 712      }
 713  
 714      if (is_array($expression) && (count($expression) == 0) )
 715      {
 716          return $text;
 717      }
 718  
 719      // add a tag in front (is needed for preg_match_all to work correct)
 720      $text = '<!--h-->' . $text;
 721  
 722      // split the HTML up so we have HTML tags
 723      // $matches[0][i] = HTML + text
 724      // $matches[1][i] = HTML
 725      // $matches[2][i] = text
 726      preg_match_all('/(<[^>]+>)([^<>]*)/', $text, $matches);
 727  
 728      // throw it all together again while applying the highlight to the text pieces
 729      $result = '';
 730  
 731      $count_matches = count($matches[2]);
 732  
 733      for ($i = 0; $i < $count_matches; $i++) {
 734  
 735          if ($i != 0)
 736          {
 737              $result .= $matches[1][$i];
 738          }
 739  
 740          if (is_array($expression) )
 741          {
 742  
 743              foreach ($expression as $regex)
 744              {
 745  
 746                  if ($regex)
 747                  {
 748                      //$matches[2][$i] = @eregi_replace($regex, $highlight, $matches[2][$i]);
 749                      $matches[2][$i] = @preg_replace("#".$regex."#i", $highlight, $matches[2][$i]);
 750                  }
 751  
 752              }
 753  
 754              $result .= $matches[2][$i];
 755  
 756          }
 757          else
 758          {
 759              //$result .= @eregi_replace($expression, $highlight, $matches[2][$i]);
 760              $result .= @preg_replace("#".$expression."#i", $highlight, $matches[2][$i]);
 761          }
 762  
 763      }
 764  
 765      return $result;
 766  
 767  }
 768  
 769  /**
 770   * Parses a query into an array of expressions that can be passed on to the highlight method
 771   */
 772  function parseHighlight($query) {
 773      // TODO: add more intelligent splitting logic
 774  
 775      // get rid of quotes
 776      $query = preg_replace('/\'|"/', '', $query);
 777  
 778      if (!$query) {
 779          return array();
 780      }
 781  
 782      $aHighlight = explode(' ', $query);
 783  
 784      for ($i = 0; $i < count($aHighlight); $i++) {
 785          $aHighlight[$i] = trim($aHighlight[$i]);
 786  
 787          if (strlen($aHighlight[$i]) < 3) {
 788              unset($aHighlight[$i]);
 789          }
 790      }
 791  
 792      if (count($aHighlight) == 1) {
 793          return $aHighlight[0];
 794      } else {
 795          return $aHighlight;
 796      }
 797  }
 798  
 799  /**
 800    * Checks if email address is valid
 801    */
 802  function isValidMailAddress($address) {
 803      // enhancement made in 3.6x based on code by Quandary.
 804      if (preg_match('/^(?!\\.)(?:\\.?[-a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~]+)+@(?!\\.)(?:\\.?(?!-)[-a-zA-Z0-9]+(?<!-)){2,}$/', $address)) {
 805          return 1;
 806      } else {
 807          return 0;
 808      }
 809  }
 810  
 811  
 812  // some helper functions
 813  function getBlogIDFromName($name) {
 814      return quickQuery('SELECT bnumber as result FROM ' . sql_table('blog') . ' WHERE bshortname="' . sql_real_escape_string($name) . '"');
 815  }
 816  
 817  function getBlogNameFromID($id) {
 818      return quickQuery('SELECT bname as result FROM ' . sql_table('blog') . ' WHERE bnumber=' . intval($id) );
 819  }
 820  
 821  function getBlogIDFromItemID($itemid) {
 822      return quickQuery('SELECT iblog as result FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid) );
 823  }
 824  
 825  function getBlogIDFromCommentID($commentid) {
 826      return quickQuery('SELECT cblog as result FROM ' . sql_table('comment') . ' WHERE cnumber=' . intval($commentid) );
 827  }
 828  
 829  function getBlogIDFromCatID($catid) {
 830      return quickQuery('SELECT cblog as result FROM ' . sql_table('category') . ' WHERE catid=' . intval($catid) );
 831  }
 832  
 833  function getCatIDFromName($name) {
 834      return quickQuery('SELECT catid as result FROM ' . sql_table('category') . ' WHERE cname="' . sql_real_escape_string($name) . '"');
 835  }
 836  
 837  function quickQuery($q) {
 838      $res = sql_query($q);
 839      $obj = sql_fetch_object($res);
 840      return $obj->result;
 841  }
 842  
 843  function getPluginNameFromPid($pid) {
 844      $res = sql_query('SELECT pfile FROM ' . sql_table('plugin') . ' WHERE pid=' . intval($pid) );
 845      $obj = sql_fetch_object($res);
 846      return $obj->pfile;
 847  //    return isset($obj->pfile) ? $obj->pfile : false;
 848  }
 849  
 850  function selector() {
 851      global $itemid, $blogid, $memberid, $query, $amount, $archivelist, $maxresults;
 852      global $archive, $skinid, $blog, $memberinfo, $CONF, $member;
 853      global $imagepopup, $catid, $special;
 854      global $manager;
 855  
 856      $actionNames = array('addcomment', 'sendmessage', 'createaccount', 'forgotpassword', 'votepositive', 'votenegative', 'plugin');
 857      $action = requestVar('action');
 858  
 859      if (in_array($action, $actionNames) ) {
 860          global $DIR_LIBS, $errormessage;
 861          include_once ($DIR_LIBS . 'ACTION.php');
 862          $a = new ACTION();
 863          $errorInfo = $a->doAction($action);
 864  
 865          if ($errorInfo) {
 866              $errormessage = $errorInfo['message'];
 867          }
 868      }
 869  
 870      // show error when headers already sent out
 871      if (headers_sent() && $CONF['alertOnHeadersSent']) {
 872  
 873          // try to get line number/filename (extra headers_sent params only exists in PHP 4.3+)
 874          if (function_exists('version_compare') && version_compare('4.3.0', phpversion(), '<=') ) {
 875              headers_sent($hsFile, $hsLine);
 876              $extraInfo = ' in <code>' . $hsFile . '</code> line <code>' . $hsLine . '</code>';
 877          } else {
 878              $extraInfo = '';
 879          }
 880  
 881          startUpError(
 882              '<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>',
 883              'Page headers already sent'
 884          );
 885          exit;
 886      }
 887  
 888      // make is so ?archivelist without blogname or blogid shows the archivelist
 889      // for the default weblog
 890      if (serverVar('QUERY_STRING') == 'archivelist') {
 891          $archivelist = $CONF['DefaultBlog'];
 892      }
 893  
 894      // now decide which type of skin we need
 895      if ($itemid) {
 896          // itemid given -> only show that item
 897          $type = 'item';
 898  
 899          if (!$manager->existsItem($itemid,intval($CONF['allowFuture']),intval($CONF['allowDrafts'])) ) {
 900              doError(_ERROR_NOSUCHITEM);
 901          }
 902  
 903          global $itemidprev, $itemidnext, $catid, $itemtitlenext, $itemtitleprev;
 904  
 905          // 1. get timestamp, blogid and catid for item
 906          $query = 'SELECT itime, iblog, icat FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid);
 907          $res = sql_query($query);
 908          $obj = sql_fetch_object($res);
 909  
 910          // if a different blog id has been set through the request or selectBlog(),
 911          // deny access
 912  
 913  
 914  
 915          if ($blogid && (intval($blogid) != $obj->iblog) ) {
 916              doError(_ERROR_NOSUCHITEM);
 917          }
 918  
 919          // if a category has been selected which doesn't match the item, ignore the
 920          // category. #85
 921          if (($catid != 0) && ($catid != $obj->icat) ) {
 922              $catid = 0;
 923          }
 924  
 925          $blogid = $obj->iblog;
 926          $timestamp = strtotime($obj->itime);
 927  
 928          $b =& $manager->getBlog($blogid);
 929  
 930          if ($b->isValidCategory($catid) ) {
 931              $catextra = ' and icat=' . $catid;
 932          } else {
 933              $catextra = '';
 934          }
 935  
 936          // get previous itemid and title
 937          $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';
 938          $res = sql_query($query);
 939  
 940          $obj = sql_fetch_object($res);
 941  
 942          if ($obj) {
 943              $itemidprev = $obj->inumber;
 944              $itemtitleprev = $obj->ititle;
 945          }
 946  
 947          // get next itemid and title
 948          $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';
 949          $res = sql_query($query);
 950  
 951          $obj = sql_fetch_object($res);
 952  
 953          if ($obj) {
 954              $itemidnext = $obj->inumber;
 955              $itemtitlenext = $obj->ititle;
 956          }
 957  
 958      } elseif ($archive) {
 959          // show archive
 960          $type = 'archive';
 961  
 962          // get next and prev month links ...
 963          global $archivenext, $archiveprev, $archivetype, $archivenextexists, $archiveprevexists;
 964  
 965          // sql queries for the timestamp of the first and the last published item
 966          $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime ASC";
 967          $first_timestamp=quickQuery ($query);
 968          $query = "SELECT UNIX_TIMESTAMP(itime) as result FROM ".sql_table('item')." WHERE idraft=0 ORDER BY itime DESC";
 969          $last_timestamp=quickQuery ($query);
 970  
 971          sscanf($archive, '%d-%d-%d', $y, $m, $d);
 972  
 973          if ($d != 0) {
 974              $archivetype = _ARCHIVETYPE_DAY;
 975              $t = mktime(0, 0, 0, $m, $d, $y);
 976              // one day has 24 * 60 * 60 = 86400 seconds
 977              $archiveprev = strftime('%Y-%m-%d', $t - 86400 );
 978              // check for published items
 979              if ($t > $first_timestamp) {
 980                  $archiveprevexists = true;
 981              }
 982              else {
 983                  $archiveprevexists = false;
 984              }
 985  
 986              // one day later
 987              $t += 86400;
 988              $archivenext = strftime('%Y-%m-%d', $t);
 989              if ($t < $last_timestamp) {
 990                  $archivenextexists = true;
 991              }
 992              else {
 993                  $archivenextexists = false;
 994              }
 995  
 996          } elseif ($m == 0) {
 997              $archivetype = _ARCHIVETYPE_YEAR;
 998              $t = mktime(0, 0, 0, 12, 31, $y - 1);
 999              // one day before is in the previous year
1000              $archiveprev = strftime('%Y', $t);
1001              if ($t > $first_timestamp) {
1002                  $archiveprevexists = true;
1003              }
1004              else {
1005                  $archiveprevexists = false;
1006              }
1007  
1008              // timestamp for the next year
1009              $t = mktime(0, 0, 0, 1, 1, $y + 1);
1010              $archivenext = strftime('%Y', $t);
1011              if ($t < $last_timestamp) {
1012                  $archivenextexists = true;
1013              }
1014              else {
1015                  $archivenextexists = false;
1016              }
1017          } else {
1018              $archivetype = _ARCHIVETYPE_MONTH;
1019              $t = mktime(0, 0, 0, $m, 1, $y);
1020              // one day before is in the previous month
1021              $archiveprev = strftime('%Y-%m', $t - 86400);
1022              if ($t > $first_timestamp) {
1023                  $archiveprevexists = true;
1024              }
1025              else {
1026                  $archiveprevexists = false;
1027              }
1028  
1029              // timestamp for the next month
1030              $t = mktime(0, 0, 0, $m+1, 1, $y);
1031              $archivenext = strftime('%Y-%m', $t);
1032              if ($t < $last_timestamp) {
1033                  $archivenextexists = true;
1034              }
1035              else {
1036                  $archivenextexists = false;
1037              }
1038          }
1039  
1040      } elseif ($archivelist) {
1041          $type = 'archivelist';
1042  
1043          if (is_numeric($archivelist)) {
1044              $blogid = intVal($archivelist);
1045          } else {
1046              $blogid = getBlogIDFromName($archivelist);
1047          }
1048  
1049          if (!$blogid) {
1050              doError(_ERROR_NOSUCHBLOG);
1051          }
1052  
1053      } elseif ($query) {
1054          global $startpos;
1055          $type = 'search';
1056          $query = stripslashes($query);
1057  
1058          if (is_numeric($blogid)) {
1059              $blogid = intVal($blogid);
1060          } else {
1061              $blogid = getBlogIDFromName($blogid);
1062          }
1063  
1064          if (!$blogid) {
1065              doError(_ERROR_NOSUCHBLOG);
1066          }
1067  
1068      } elseif ($memberid) {
1069          $type = 'member';
1070  
1071          if (!MEMBER::existsID($memberid) ) {
1072              doError(_ERROR_NOSUCHMEMBER);
1073          }
1074  
1075          $memberinfo = $manager->getMember($memberid);
1076  
1077      } elseif ($imagepopup) {
1078          // media object (images etc.)
1079          $type = 'imagepopup';
1080  
1081          // TODO: check if media-object exists
1082          // TODO: set some vars?
1083      } else {
1084          // show regular index page
1085          global $startpos;
1086          $type = 'index';
1087      }
1088  
1089      // any type of skin with catid
1090      if ($catid && !$blogid) {
1091          $blogid = getBlogIDFromCatID($catid);
1092      }
1093  
1094      // decide which blog should be displayed
1095      if (!$blogid) {
1096          $blogid = $CONF['DefaultBlog'];
1097      }
1098  
1099      $b =& $manager->getBlog($blogid);
1100      $blog = $b; // references can't be placed in global variables?
1101  
1102      if (!$blog->isValid) {
1103          doError(_ERROR_NOSUCHBLOG);
1104      }
1105  
1106      // set catid if necessary
1107      if ($catid) {
1108          // check if the category is valid
1109          if (!$blog->isValidCategory($catid)) {
1110              doError(_ERROR_NOSUCHCATEGORY);
1111          } else {
1112              $blog->setSelectedCategory($catid);
1113          }
1114      }
1115  
1116      // decide which skin should be used
1117      if ($skinid != '' && ($skinid == 0) ) {
1118          selectSkin($skinid);
1119      }
1120  
1121      if (!$skinid) {
1122          $skinid = $blog->getDefaultSkin();
1123      }
1124  
1125      //$special = requestVar('special'); //get at top of file as global
1126      if (!empty($special) && isValidShortName($special)) {
1127          $type = strtolower($special);
1128      }
1129  
1130      $skin = new SKIN($skinid);
1131  
1132      if (!$skin->isValid) {
1133          doError(_ERROR_NOSUCHSKIN);
1134      }
1135  
1136      // set global skinpart variable so can determine quickly what is being parsed from any plugin or phpinclude
1137      global $skinpart;
1138      $skinpart = $type;
1139  
1140      // parse the skin
1141      $skin->parse($type);
1142  
1143      // check to see we should throw JustPosted event
1144      $blog->checkJustPosted();
1145  }
1146  
1147  /**
1148    * Show error skin with given message. An optional skin-object to use can be given
1149    */
1150  function doError($msg, $skin = '') {
1151      global $errormessage, $CONF, $skinid, $blogid, $manager;
1152  
1153      if ($skin == '') {
1154  
1155          if (SKIN::existsID($skinid) ) {
1156              $skin = new SKIN($skinid);
1157          } elseif ($manager->existsBlogID($blogid) ) {
1158              $blog =& $manager->getBlog($blogid);
1159              $skin = new SKIN($blog->getDefaultSkin() );
1160          } elseif ($CONF['DefaultBlog']) {
1161              $blog =& $manager->getBlog($CONF['DefaultBlog']);
1162              $skin = new SKIN($blog->getDefaultSkin() );
1163          } else {
1164              // this statement should actually never be executed
1165              $skin = new SKIN($CONF['BaseSkin']);
1166          }
1167  
1168      }
1169  
1170      $skinid = $skin->id;
1171      $errormessage = $msg;
1172      $skin->parse('error');
1173      exit;
1174  }
1175  
1176  function getConfig() {
1177      global $CONF;
1178  
1179      $query = 'SELECT * FROM ' . sql_table('config');
1180      $res = sql_query($query);
1181  
1182      while ($obj = sql_fetch_object($res) ) {
1183          $CONF[$obj->name] = $obj->value;
1184      }
1185  }
1186  
1187  // some checks for names of blogs, categories, templates, members, ...
1188  function isValidShortName($name) {
1189  
1190      # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1191      # original eregi: eregi('^[a-z0-9]+$', $name)
1192  
1193      return preg_match('#^[a-z0-9]+$#i', $name);
1194  
1195  }
1196  
1197  function isValidDisplayName($name) {
1198  
1199      # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1200      # original eregi: eregi('^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$', $name)
1201  
1202      return preg_match('#^[a-z0-9]+[a-z0-9 ]*[a-z0-9]+$#i', $name);
1203  
1204  }
1205  
1206  function isValidCategoryName($name) {
1207      return 1;
1208  }
1209  
1210  function isValidTemplateName($name) {
1211  
1212      # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1213      # original eregi: eregi('^[a-z0-9/]+$', $name)
1214  
1215      return preg_match('#^[a-z0-9/]+$#i', $name);
1216  
1217  }
1218  
1219  function isValidSkinName($name) {
1220  
1221      # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
1222      # original eregi: eregi('^[a-z0-9/]+$', $name);
1223  
1224      return preg_match('#^[a-z0-9/]+$#i', $name);
1225  
1226  }
1227  
1228  // add and remove linebreaks
1229  function addBreaks($var) {
1230      return nl2br($var);
1231  }
1232  
1233  function removeBreaks($var) {
1234      return preg_replace("/<br \/>([\r\n])/", "$1", $var);
1235  }
1236  
1237  // shortens a text string to maxlength ($toadd) is what needs to be added
1238  // at the end (end length is <= $maxlength)
1239  function shorten($text, $maxlength, $toadd) {
1240      // 1. remove entities...
1241      $trans = get_html_translation_table(HTML_ENTITIES);
1242  
1243      $trans = array_flip($trans);
1244      $text = strtr($text, $trans);
1245  
1246      // 2. the actual shortening
1247      if (strlen($text) > $maxlength) {
1248          $text = substr($text, 0, $maxlength - strlen($toadd) ) . $toadd;
1249  
1250      }
1251  
1252      return $text;
1253  }
1254  
1255  /**
1256    * Converts a unix timestamp to a mysql DATETIME format, and places
1257    * quotes around it.
1258    */
1259  function mysqldate($timestamp) {
1260      return '"' . date('Y-m-d H:i:s', $timestamp) . '"';
1261  }
1262  
1263  /**
1264    * functions for use in index.php
1265    */
1266  function selectBlog($shortname) {
1267      global $blogid, $archivelist;
1268      $blogid = getBlogIDFromName($shortname);
1269  
1270      // also force archivelist variable, if it is set
1271      if ($archivelist) {
1272          $archivelist = $blogid;
1273      }
1274  }
1275  
1276  function selectSkin($skinname) {
1277      global $skinid;
1278      $skinid = SKIN::getIdFromName($skinname);
1279  }
1280  
1281  /**
1282   * Can take either a category ID or a category name (be aware that
1283   * multiple categories can have the same name)
1284   */
1285  function selectCategory($cat) {
1286      global $catid;
1287      if (is_numeric($cat) ) {
1288          $catid = intval($cat);
1289      } else {
1290          $catid = getCatIDFromName($cat);
1291      }
1292  }
1293  
1294  function selectItem($id) {
1295      global $itemid;
1296      $itemid = intval($id);
1297  }
1298  
1299  // force the use of a language file (warning: can cause warnings)
1300  function selectLanguage($language) {
1301  
1302      global $DIR_LANG;
1303  
1304      # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
1305      # original ereg_replace: preg_replace( '@\\|/@', '', $language) . '.php')
1306      # important note that '\' must be matched with '\\\\' in preg* expressions
1307  
1308      include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');
1309  
1310  }
1311  
1312  function parseFile($filename, $includeMode = 'normal', $includePrefix = '') {
1313      $handler = new ACTIONS('fileparser');
1314      $parser = new PARSER(SKIN::getAllowedActionsForType('fileparser'), $handler);
1315      $handler->parser =& $parser;
1316  
1317      // set IncludeMode properties of parser
1318      PARSER::setProperty('IncludeMode', $includeMode);
1319      PARSER::setProperty('IncludePrefix', $includePrefix);
1320  
1321      if (!file_exists($filename) ) {
1322          doError('A file is missing');
1323      }
1324  
1325      $fsize = filesize($filename);
1326  
1327      if ($fsize <= 0) {
1328          return;
1329      }
1330  
1331      // read file
1332      $fd = fopen ($filename, 'r');
1333      $contents = fread ($fd, $fsize);
1334      fclose ($fd);
1335  
1336      // parse file contents
1337      $parser->parse($contents);
1338  }
1339  
1340  /**
1341    * Outputs a debug message
1342    */
1343  function debug($msg) {
1344      echo '<p><b>' . $msg . "</b></p>\n";
1345  }
1346  
1347  // shortcut
1348  function addToLog($level, $msg) {
1349      ACTIONLOG::add($level, $msg);
1350  }
1351  
1352  // shows a link to help file
1353  function help($id) {
1354      echo helpHtml($id);
1355  }
1356  
1357  function helpHtml($id) {
1358      global $CONF;
1359      return helplink($id) . '<img src="' . $CONF['AdminURL'] . 'documentation/icon-help.gif" width="15" height="15" alt="' . _HELP_TT . '" title="' . _HELP_TT . '" /></a>';
1360  }
1361  
1362  function helplink($id) {
1363      global $CONF;
1364      return '<a href="' . $CONF['AdminURL'] . 'documentation/help.html#'. $id . '" onclick="if (event &amp;&amp; event.preventDefault) event.preventDefault(); return help(this.href);">';
1365  }
1366  
1367  function getMailFooter() {
1368      $message = "\n\n-----------------------------";
1369      $message .=  "\n   Powered by Nucleus CMS";
1370      $message .=  "\n(http://www.nucleuscms.org/)";
1371      return $message;
1372  }
1373  
1374  /**
1375    * Returns the name of the language to use
1376    * preference priority: member - site
1377    * defaults to english when no good language found
1378    *
1379    * checks if file exists, etc...
1380    */
1381  function getLanguageName() {
1382      global $CONF, $member;
1383  
1384      if ($member && $member->isLoggedIn() ) {
1385          // try to use members language
1386          $memlang = $member->getLanguage();
1387  
1388          if (($memlang != '') && (checkLanguage($memlang) ) ) {
1389              return $memlang;
1390          }
1391      }
1392  
1393      // use default language
1394      if (checkLanguage($CONF['Language']) ) {
1395          return $CONF['Language'];
1396      } else {
1397          return 'english';
1398      }
1399  }
1400  
1401  /**
1402    * Includes a PHP file. This method can be called while parsing templates and skins
1403    */
1404  function includephp($filename) {
1405      // make predefined variables global, so most simple scripts can be used here
1406  
1407      // apache (names taken from PHP doc)
1408      global $GATEWAY_INTERFACE, $SERVER_NAME, $SERVER_SOFTWARE, $SERVER_PROTOCOL;
1409      global $REQUEST_METHOD, $QUERY_STRING, $DOCUMENT_ROOT, $HTTP_ACCEPT;
1410      global $HTTP_ACCEPT_CHARSET, $HTTP_ACCEPT_ENCODING, $HTTP_ACCEPT_LANGUAGE;
1411      global $HTTP_CONNECTION, $HTTP_HOST, $HTTP_REFERER, $HTTP_USER_AGENT;
1412      global $REMOTE_ADDR, $REMOTE_PORT, $SCRIPT_FILENAME, $SERVER_ADMIN;
1413      global $SERVER_PORT, $SERVER_SIGNATURE, $PATH_TRANSLATED, $SCRIPT_NAME;
1414      global $REQUEST_URI;
1415  
1416      // php (taken from PHP doc)
1417      global $argv, $argc, $PHP_SELF, $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS;
1418      global $HTTP_POST_FILES, $HTTP_ENV_VARS, $HTTP_SERVER_VARS, $HTTP_SESSION_VARS;
1419  
1420      // other
1421      global $PATH_INFO, $HTTPS, $HTTP_RAW_POST_DATA, $HTTP_X_FORWARDED_FOR;
1422  
1423      if (@file_exists($filename) ) {
1424          include($filename);
1425      }
1426  }
1427  
1428  /**
1429   * Checks if a certain language exists
1430   * @param string $lang
1431   * @return bool
1432   **/
1433  function checkLanguage($lang) {
1434  
1435      global $DIR_LANG;
1436  
1437      # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
1438      # original ereg_replace: ereg_replace( '[\\|/]', '', $lang) . '.php')
1439      # important note that '\' must be matched with '\\\\' in preg* expressions
1440  
1441      return file_exists($DIR_LANG . preg_replace('#[\\\\|/]#', '', $lang) . '.php');
1442  
1443  }
1444  
1445  /**
1446   * Checks if a certain plugin exists
1447   * @param string $plug
1448   * @return bool
1449   **/
1450  function checkPlugin($plug) {
1451  
1452      global $DIR_PLUGINS;
1453  
1454      # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
1455      # original ereg_replace: ereg_replace( '[\\|/]', '', $plug) . '.php')
1456      # important note that '\' must be matched with '\\\\' in preg* expressions
1457  
1458      return file_exists($DIR_PLUGINS . preg_replace('#[\\\\|/]#', '', $plug) . '.php');
1459  
1460  }
1461  
1462  /**
1463    * Centralisation of the functions that generate links
1464    */
1465  function createItemLink($itemid, $extra = '') {
1466      return createLink('item', array('itemid' => $itemid, 'extra' => $extra) );
1467  }
1468  
1469  function createMemberLink($memberid, $extra = '') {
1470      return createLink('member', array('memberid' => $memberid, 'extra' => $extra) );
1471  }
1472  
1473  function createCategoryLink($catid, $extra = '') {
1474      return createLink('category', array('catid' => $catid, 'extra' => $extra) );
1475  }
1476  
1477  function createArchiveListLink($blogid = '', $extra = '') {
1478      return createLink('archivelist', array('blogid' => $blogid, 'extra' => $extra) );
1479  }
1480  
1481  function createArchiveLink($blogid, $archive, $extra = '') {
1482      return createLink('archive', array('blogid' => $blogid, 'archive' => $archive, 'extra' => $extra) );
1483  }
1484  
1485  function createBlogidLink($blogid, $params = '') {
1486      return createLink('blog', array('blogid' => $blogid, 'extra' => $params) );
1487  }
1488  
1489  function createLink($type, $params) {
1490      global $manager, $CONF;
1491  
1492      $generatedURL = '';
1493      $usePathInfo = ($CONF['URLMode'] == 'pathinfo');
1494  
1495      // ask plugins first
1496      $created = false;
1497  
1498      if ($usePathInfo) {
1499          $manager->notify(
1500              'GenerateURL',
1501              array(
1502                  'type' => $type,
1503                  'params' => $params,
1504                  'completed' => &$created,
1505                  'url' => &$url
1506              )
1507          );
1508      }
1509  
1510      // if a plugin created the URL, return it
1511      if ($created) {
1512          return $url;
1513      }
1514  
1515      // default implementation
1516      switch ($type) {
1517          case 'item':
1518              if ($usePathInfo) {
1519                  $url = $CONF['ItemURL'] . '/' . $CONF['ItemKey'] . '/' . $params['itemid'];
1520              } else {
1521                  $url = $CONF['ItemURL'] . '?itemid=' . $params['itemid'];
1522              }
1523              break;
1524  
1525          case 'member':
1526              if ($usePathInfo) {
1527                  $url = $CONF['MemberURL'] . '/' . $CONF['MemberKey'] . '/' . $params['memberid'];
1528              } else {
1529                  $url = $CONF['MemberURL'] . '?memberid=' . $params['memberid'];
1530              }
1531              break;
1532  
1533          case 'category':
1534              if ($usePathInfo) {
1535                  $url = $CONF['CategoryURL'] . '/' . $CONF['CategoryKey'] . '/' . $params['catid'];
1536              } else {
1537                  $url = $CONF['CategoryURL'] . '?catid=' . $params['catid'];
1538              }
1539              break;
1540  
1541          case 'archivelist':
1542              if (!$params['blogid']) {
1543                  $params['blogid'] = $CONF['DefaultBlog'];
1544              }
1545  
1546              if ($usePathInfo) {
1547                  $url = $CONF['ArchiveListURL'] . '/' . $CONF['ArchivesKey'] . '/' . $params['blogid'];
1548              } else {
1549                  $url = $CONF['ArchiveListURL'] . '?archivelist=' . $params['blogid'];
1550              }
1551              break;
1552  
1553          case 'archive':
1554              if ($usePathInfo) {
1555                  $url = $CONF['ArchiveURL'] . '/' . $CONF['ArchiveKey'] . '/'.$params['blogid'].'/' . $params['archive'];
1556              } else {
1557                  $url = $CONF['ArchiveURL'] . '?blogid='.$params['blogid'].'&amp;archive=' . $params['archive'];
1558              }
1559              break;
1560  
1561          case 'blog':
1562              if ($usePathInfo) {
1563                  $url = $CONF['BlogURL'] . '/' . $CONF['BlogKey'] . '/' . $params['blogid'];
1564              } else {
1565                  $url = $CONF['BlogURL'] . '?blogid=' . $params['blogid'];
1566              }
1567              break;
1568      }
1569  
1570      return addLinkParams($url, (isset($params['extra'])? $params['extra'] : null));
1571  }
1572  
1573  function createBlogLink($url, $params) {
1574      global $CONF;
1575      if ($CONF['URLMode'] == 'normal') {
1576          if (strpos($url, '?') === FALSE && is_array($params)) {
1577              $fParam = reset($params);
1578              $fKey   = key($params);
1579              array_shift($params);
1580              $url .= '?' . $fKey . '=' . $fParam;
1581          }
1582      } elseif ($CONF['URLMode'] == 'pathinfo' && substr($url, -1) == '/') {
1583          $url = substr($url, 0, -1);
1584      }
1585      return addLinkParams($url, $params);
1586  }
1587  
1588  function addLinkParams($link, $params) {
1589      global $CONF;
1590  
1591      if (is_array($params) ) {
1592  
1593          if ($CONF['URLMode'] == 'pathinfo') {
1594  
1595              foreach ($params as $param => $value) {
1596                  // change in 3.63 to fix problem where URL generated with extra params mike look like category/4/blogid/1
1597                  // but they should use the URL keys like this: category/4/blog/1
1598                  // if user wants old urls back, set $CONF['NoURLKeysInExtraParams'] = 1; in config.php
1599                  if (isset($CONF['NoURLKeysInExtraParams']) && $CONF['NoURLKeysInExtraParams'] == 1) 
1600                  {
1601                      $link .= '/' . $param . '/' . urlencode($value);
1602                  } else {
1603                      switch ($param) {
1604                          case 'itemid':
1605                              $link .= '/' . $CONF['ItemKey'] . '/' . urlencode($value);
1606                          break;
1607                          case 'memberid':
1608                              $link .= '/' . $CONF['MemberKey'] . '/' . urlencode($value);
1609                          break;
1610                          case 'catid':
1611                              $link .= '/' . $CONF['CategoryKey'] . '/' . urlencode($value);
1612                          break;
1613                          case 'archivelist':
1614                              $link .= '/' . $CONF['ArchivesKey'] . '/' . urlencode($value);
1615                          break;
1616                          case 'archive':
1617                              $link .= '/' . $CONF['ArchiveKey'] . '/' . urlencode($value);
1618                          break;
1619                          case 'blogid':
1620                              $link .= '/' . $CONF['BlogKey'] . '/' . urlencode($value);
1621                          break;
1622                          default:
1623                              $link .= '/' . $param . '/' . urlencode($value);
1624                          break;
1625                      }
1626                  }
1627              }
1628  
1629          } else {
1630  
1631              foreach ($params as $param => $value) {
1632                  $link .= '&amp;' . $param . '=' . urlencode($value);
1633              }
1634  
1635          }
1636      }
1637  
1638      return $link;
1639  }
1640  
1641  /**
1642   * @param $querystr
1643   *        querystring to alter (e.g. foo=1&bar=2&x=y)
1644   * @param $param
1645   *        name of parameter to change (e.g. 'foo')
1646   * @param $value
1647   *        New value for that parameter (e.g. 3)
1648   * @result
1649   *        altered query string (for the examples above: foo=3&bar=2&x=y)
1650   */
1651  function alterQueryStr($querystr, $param, $value) {
1652      $vars = explode('&', $querystr);
1653      $set  = false;
1654  
1655      for ($i = 0; $i < count($vars); $i++) {
1656          $v = explode('=', $vars[$i]);
1657  
1658          if ($v[0] == $param) {
1659              $v[1] = $value;
1660              $vars[$i] = implode('=', $v);
1661              $set = true;
1662              break;
1663          }
1664      }
1665  
1666      if (!$set) {
1667          $vars[] = $param . '=' . $value;
1668      }
1669  
1670      return ltrim(implode('&', $vars), '&');
1671  }
1672  
1673  // passes one variable as hidden input field (multiple fields for arrays)
1674  // @see passRequestVars in varsx.x.x.php
1675  function passVar($key, $value) {
1676      // array ?
1677      if (is_array($value) ) {
1678          for ($i = 0; $i < sizeof($value); $i++) {
1679              passVar($key . '[' . $i . ']', $value[$i]);
1680          }
1681  
1682          return;
1683      }
1684  
1685      // other values: do stripslashes if needed
1686      ?><input type="hidden" name="<?php echo htmlspecialchars($key)?>" value="<?php echo htmlspecialchars(undoMagic($value) )?>" /><?php
1687  }
1688  
1689  /*
1690      Date format functions (to be used from [%date(..)%] skinvars
1691  */
1692  function formatDate($format, $timestamp, $defaultFormat, &$blog) {
1693      // apply blog offset (#42)
1694      $boffset = $blog ? $blog->getTimeOffset() * 3600 : 0;
1695      $offset = date('Z', $timestamp) + $boffset;
1696  
1697      switch ($format) {
1698          case 'rfc822':
1699              if ($offset >= 0) {
1700                  $tz = '+';
1701              } else {
1702                  $tz = '-';
1703                  $offset = -$offset;
1704              }
1705  
1706              $tz .= sprintf("%02d%02d", floor($offset / 3600), round(($offset % 3600) / 60) );
1707              return date('D, j M Y H:i:s ', $timestamp) . $tz;
1708  
1709          case 'rfc822GMT':
1710              $timestamp -= $offset;
1711              return date('D, j M Y H:i:s ', $timestamp) . 'GMT';
1712  
1713          case 'utc':
1714              $timestamp -= $offset;
1715              return date('Y-m-d\TH:i:s\Z', $timestamp);
1716  
1717          case 'iso8601':
1718              if ($offset >= 0) {
1719                  $tz = '+';
1720              } else {
1721                  $tz = '-';
1722                  $offset = -$offset;
1723              }
1724              $tz .= sprintf("%02d:%02d", floor($offset / 3600), round(($offset % 3600) / 60) );
1725              return date('Y-m-d\TH:i:s', $timestamp) . $tz;
1726  
1727          default :
1728              return strftime($format ? $format : $defaultFormat, $timestamp);
1729      }
1730  }
1731  
1732  function checkVars($aVars) {
1733      global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_ENV_VARS, $HTTP_POST_FILES, $HTTP_SESSION_VARS;
1734  
1735      foreach ($aVars as $varName) {
1736  
1737          if (phpversion() >= '4.1.0') {
1738  
1739              if (   isset($_GET[$varName])
1740                  || isset($_POST[$varName])
1741                  || isset($_COOKIE[$varName])
1742                  || isset($_ENV[$varName])
1743                  || isset($_SESSION[$varName])
1744                  || isset($_FILES[$varName])
1745              ) {
1746                  die('Sorry. An error occurred.');
1747              }
1748  
1749          } else {
1750  
1751              if (   isset($HTTP_GET_VARS[$varName])
1752                  || isset($HTTP_POST_VARS[$varName])
1753                  || isset($HTTP_COOKIE_VARS[$varName])
1754                  || isset($HTTP_ENV_VARS[$varName])
1755                  || isset($HTTP_SESSION_VARS[$varName])
1756                  || isset($HTTP_POST_FILES[$varName])
1757              ) {
1758                  die('Sorry. An error occurred.');
1759              }
1760  
1761          }
1762      }
1763  }
1764  
1765  
1766  /**
1767   * Sanitize parameters such as $_GET and $_SERVER['REQUEST_URI'] etc.
1768   * to avoid XSS
1769   */
1770  function sanitizeParams()
1771  {
1772      global $HTTP_SERVER_VARS;
1773  
1774      $array = array();
1775      $str = '';
1776      $frontParam = '';
1777  
1778      // REQUEST_URI of $HTTP_SERVER_VARS
1779      $str =& $HTTP_SERVER_VARS["REQUEST_URI"];
1780      serverStringToArray($str, $array, $frontParam);
1781      sanitizeArray($array);
1782      arrayToServerString($array, $frontParam, $str);
1783  
1784      // QUERY_STRING of $HTTP_SERVER_VARS
1785      $str =& $HTTP_SERVER_VARS["QUERY_STRING"];
1786      serverStringToArray($str, $array, $frontParam);
1787      sanitizeArray($array);
1788      arrayToServerString($array, $frontParam, $str);
1789  
1790      if (phpversion() >= '4.1.0') {
1791          // REQUEST_URI of $_SERVER
1792          $str =& $_SERVER["REQUEST_URI"];
1793          serverStringToArray($str, $array, $frontParam);
1794          sanitizeArray($array);
1795          arrayToServerString($array, $frontParam, $str);
1796  
1797          // QUERY_STRING of $_SERVER
1798          $str =& $_SERVER["QUERY_STRING"];
1799          serverStringToArray($str, $array, $frontParam);
1800          sanitizeArray($array);
1801          arrayToServerString($array, $frontParam, $str);
1802      }
1803  
1804      // $_GET
1805      convArrayForSanitizing($_GET, $array);
1806      sanitizeArray($array);
1807      revertArrayForSanitizing($array, $_GET);
1808  
1809      // $_REQUEST (only GET param)
1810      convArrayForSanitizing($_REQUEST, $array);
1811      sanitizeArray($array);
1812      revertArrayForSanitizing($array, $_REQUEST);
1813  }
1814  
1815  /**
1816   * Check ticket when not checked in plugin's admin page
1817   * to avoid CSRF.
1818   * Also avoid the access to plugin/index.php by guest user.
1819   */
1820  function ticketForPlugin() {
1821  
1822      global $CONF, $DIR_PLUGINS, $member, $ticketforplugin;
1823  
1824      /* initialize */
1825      $ticketforplugin = array();
1826      $ticketforplugin['ticket'] = FALSE;
1827  
1828      /* Check if using plugin's php file. */
1829      if ($p_translated = serverVar('PATH_TRANSLATED') )
1830      {
1831  
1832          if (!file_exists($p_translated) )
1833          {
1834              $p_translated = '';
1835          }
1836  
1837      }
1838  
1839      if (!$p_translated)
1840      {
1841          $p_translated = serverVar('SCRIPT_FILENAME');
1842  
1843          if (!file_exists($p_translated) )
1844          {
1845              header("HTTP/1.0 404 Not Found");
1846              exit('');
1847          }
1848  
1849      }
1850  
1851      $p_translated = str_replace('\\', '/', $p_translated);
1852      $d_plugins = str_replace('\\', '/', $DIR_PLUGINS);
1853  
1854      if (strpos($p_translated, $d_plugins) !== 0)
1855      {
1856          return;// This isn't plugin php file.
1857      }
1858  
1859      /* Solve the plugin php file or admin directory */
1860      $phppath = substr($p_translated, strlen($d_plugins) );
1861      $phppath = preg_replace('#^/#', '', $phppath); // Remove the first "/" if exists.
1862      $path = preg_replace('#^NP_(.*)\.php$#', '$1', $phppath); // Remove the first "NP_" and the last ".php" if exists.
1863      $path = preg_replace('#^([^/]*)/(.*)$#', '$1', $path); // Remove the "/" and beyond.
1864  
1865      /* Solve the plugin name. */
1866      $plugins = array();
1867      $query = 'SELECT `pfile` FROM '.sql_table('plugin');
1868      $res = sql_query($query);
1869  
1870      while($row = sql_fetch_row($res) )
1871      {
1872          $name = substr($row[0], 3);
1873          $plugins[strtolower($name)] = $name;
1874      }
1875  
1876      sql_free_result($res);
1877  
1878      if ($plugins[$path])
1879      {
1880          $plugin_name = $plugins[$path];
1881      }
1882      else if (in_array($path, $plugins))
1883      {
1884          $plugin_name = $path;
1885      }
1886      else
1887      {
1888          header("HTTP/1.0 404 Not Found");
1889          exit('');
1890      }
1891  
1892      /* Return if not index.php */
1893      if ( ($phppath != strtolower($plugin_name) . '/') && ($phppath != strtolower($plugin_name) . '/index.php') )
1894      {
1895          return;
1896      }
1897  
1898      /* Exit if not logged in. */
1899      if ( !$member->isLoggedIn() )
1900      {
1901          exit('You aren\'t logged in.');
1902      }
1903  
1904      global $manager, $DIR_LIBS, $DIR_LANG, $HTTP_GET_VARS, $HTTP_POST_VARS;
1905  
1906      /* Check if this feature is needed (ie, if "$manager->checkTicket()" is not included in the script). */
1907      if (!($p_translated = serverVar('PATH_TRANSLATED') ) )
1908      {
1909          $p_translated = serverVar('SCRIPT_FILENAME');
1910      }
1911  
1912      if ($file = @file($p_translated) )
1913      {
1914          $prevline = '';
1915  
1916          foreach($file as $line)
1917          {
1918  
1919              if (preg_match('/[\$]manager([\s]*)[\-]>([\s]*)checkTicket([\s]*)[\(]/i', $prevline . $line) )
1920              {
1921                  return;
1922              }
1923  
1924              $prevline = $line;
1925  
1926          }
1927  
1928      }
1929  
1930      /* Show a form if not valid ticket */
1931      if ( ( strstr(serverVar('REQUEST_URI'), '?') || serverVar('QUERY_STRING')
1932              || strtoupper(serverVar('REQUEST_METHOD') ) == 'POST')
1933                  && (!$manager->checkTicket() ) )
1934      {
1935  
1936          if (!class_exists('PluginAdmin') )
1937          {
1938              $language = getLanguageName();
1939  
1940              # replaced ereg_replace() below with preg_replace(). ereg* functions are deprecated in PHP 5.3.0
1941              # original ereg_replace: ereg_replace( '[\\|/]', '', $language) . '.php')
1942              # important note that '\' must be matched with '\\\\' in preg* expressions
1943  
1944              include($DIR_LANG . preg_replace('#[\\\\|/]#', '', $language) . '.php');
1945              include ($DIR_LIBS . 'PLUGINADMIN.php');
1946          }
1947  
1948          if (!(function_exists('mb_strimwidth') || extension_loaded('mbstring')))
1949          {
1950  
1951              if (file_exists($DIR_LIBS.'mb_emulator/mb-emulator.php'))
1952              {
1953                  global $mbemu_internals;
1954                  include_once($DIR_LIBS.'mb_emulator/mb-emulator.php');
1955              }
1956  
1957          }
1958  
1959          $oPluginAdmin = new PluginAdmin($plugin_name);
1960          $oPluginAdmin->start();
1961          echo '<p>' . _ERROR_BADTICKET . "</p>\n";
1962  
1963          /* Show the form to confirm action */
1964          // PHP 4.0.x support
1965          $get = (isset($_GET) ) ? $_GET : $HTTP_GET_VARS;
1966          $post = (isset($_POST) ) ? $_POST : $HTTP_POST_VARS;
1967  
1968          // Resolve URI and QUERY_STRING
1969          if ($uri = serverVar('REQUEST_URI') )
1970          {
1971              list($uri, $qstring) = explode('?', $uri);
1972          }
1973          else
1974          {
1975  
1976              if ( !($uri = serverVar('PHP_SELF') ) )
1977              {
1978                  $uri = serverVar('SCRIPT_NAME');
1979              }
1980  
1981              $qstring = serverVar('QUERY_STRING');
1982  
1983          }
1984  
1985          if ($qstring)
1986          {
1987              $qstring = '?' . $qstring;
1988          }
1989  
1990          echo '<p>' . _SETTINGS_UPDATE . ' : ' . _QMENU_PLUGINS . ' <span style="color:red;">' . htmlspecialchars($plugin_name) . "</span> ?</p>\n";
1991  
1992          switch(strtoupper(serverVar('REQUEST_METHOD') ) )
1993          {
1994              case 'POST':
1995                  echo '<form method="POST" action="'.htmlspecialchars($uri.$qstring).'">';
1996                  $manager->addTicketHidden();
1997                  _addInputTags($post);
1998                  break;
1999  
2000              case 'GET':
2001                  echo '<form method="GET" action="'.htmlspecialchars($uri).'">';
2002                  $manager->addTicketHidden();
2003                  _addInputTags($get);
2004  
2005              default:
2006                  break;
2007          }
2008  
2009          echo '<input type="submit" value="' . _YES . '" />&nbsp;&nbsp;&nbsp;&nbsp;';
2010          echo '<input type="button" value="' . _NO . '" onclick="history.back(); return false;" />';
2011          echo "</form>\n";
2012  
2013          $oPluginAdmin->end();
2014          exit;
2015  
2016      }
2017  
2018      /* Create new ticket */
2019      $ticket=$manager->addTicketToUrl('');
2020      $ticketforplugin['ticket']=substr($ticket,strpos($ticket,'ticket=')+7);
2021  }
2022  function _addInputTags(&$keys,$prefix=''){
2023      foreach($keys as $key=>$value){
2024          if ($prefix) $key=$prefix.'['.$key.']';
2025          if (is_array($value)) _addInputTags($value,$key);
2026          else {
2027              if (get_magic_quotes_gpc()) $value=stripslashes($value);
2028              if ($key=='ticket') continue;
2029              echo '<input type="hidden" name="'.htmlspecialchars($key).
2030                  '" value="'.htmlspecialchars($value).'" />'."\n";
2031          }
2032      }
2033  }
2034  
2035  /**
2036   * Convert the server string such as $_SERVER['REQUEST_URI']
2037   * to arry like arry['blogid']=1 and array['page']=2 etc.
2038   */
2039  function serverStringToArray($str, &$array, &$frontParam)
2040  {
2041      // init param
2042      $array = array();
2043      $fronParam = "";
2044  
2045      // split front param, e.g. /index.php, and others, e.g. blogid=1&page=2
2046      if (strstr($str, "?")){
2047          list($frontParam, $args) = preg_split("/\?/", $str, 2);
2048      }
2049      else {
2050          $args = $str;
2051          $frontParam = "";
2052      }
2053  
2054      // If there is no args like blogid=1&page=2, return
2055      if (!strstr($str, "=") && !strlen($frontParam)) {
2056          $frontParam = $str;
2057          return;
2058      }
2059  
2060      $array = explode("&", $args);
2061  }
2062  
2063  /**
2064   * Convert array like array['blogid'] to server string
2065   * such as $_SERVER['REQUEST_URI']
2066   */
2067  function arrayToServerString($array, $frontParam, &$str)
2068  {
2069      if (strstr($str, "?")) {
2070          $str = $frontParam . "?";
2071      } else {
2072          $str = $frontParam;
2073      }
2074      if (count($array)) {
2075          $str .= implode("&", $array);
2076      }
2077  }
2078  
2079  /**
2080   * Sanitize array parameters.
2081   * This function checks both key and value.
2082   * - check key if it inclues " (double quote),  remove from array
2083   * - check value if it includes \ (escape sequece), remove remaining string
2084   */
2085  function sanitizeArray(&$array)
2086  {
2087      $excludeListForSanitization = array('query');
2088  //    $excludeListForSanitization = array();
2089  
2090      foreach ($array as $k => $v) {
2091  
2092          // split to key and value
2093          list($key, $val) = preg_split("/=/", $v, 2);
2094          if (!isset($val)) {
2095              continue;
2096          }
2097  
2098          // when magic quotes is on, need to use stripslashes,
2099          // and then addslashes
2100          if (get_magic_quotes_gpc()) {
2101              $val = stripslashes($val);
2102          }
2103          // note that we must use addslashes here because this function is called before the db connection is made
2104          // and sql_real_escape_string needs a db connection
2105          $val = addslashes($val);
2106  
2107          // if $key is included in exclude list, skip this param
2108          if (!in_array($key, $excludeListForSanitization)) {
2109  
2110              // check value
2111              if (strpos($val, '\\')) {
2112                  list($val, $tmp) = explode('\\', $val);
2113              }
2114  
2115              // remove control code etc.
2116              $val = strtr($val, "\0\r\n<>'\"", "       ");
2117  
2118              // check key
2119              if (preg_match('/\"/i', $key)) {
2120                  unset($array[$k]);
2121                  continue;
2122              }
2123  
2124              // set sanitized info
2125              $array[$k] = sprintf("%s=%s", $key, $val);
2126          }
2127      }
2128  }
2129  
2130  /**
2131   * Convert array for sanitizeArray function
2132   */
2133  function convArrayForSanitizing($src, &$array)
2134  {
2135      $array = array();
2136      foreach ($src as $key => $val) {
2137          if (key_exists($key, $_GET)) {
2138              array_push($array, sprintf("%s=%s", $key, $val));
2139          }
2140      }
2141  }
2142  
2143  /**
2144   * Revert array after sanitizeArray function
2145   */
2146  function revertArrayForSanitizing($array, &$dst)
2147  {
2148      foreach ($array as $v) {
2149          list($key, $val) = preg_split("/=/", $v, 2);
2150          $dst[$key] = $val;
2151      }
2152  }
2153  
2154  /**
2155   * Stops processing the request and redirects to the given URL.
2156   * - no actual contents should have been sent to the output yet
2157   * - the URL will be stripped of illegal or dangerous characters
2158   */
2159  function redirect($url) {
2160      $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:@%*]|i', '', $url);
2161      header('Location: ' . $url);
2162      exit;
2163  }
2164  
2165  /**
2166   * Strip HTML tags from a string
2167   * This function is a bit more intelligent than a regular call to strip_tags(),
2168   * because it also deletes the contents of certain tags and cleans up any
2169   * unneeded whitespace.
2170   */
2171  function stringStripTags ($string) {
2172      $string = preg_replace("/<del[^>]*>.+<\/del[^>]*>/isU", '', $string);
2173      $string = preg_replace("/<script[^>]*>.+<\/script[^>]*>/isU", '', $string);
2174      $string = preg_replace("/<style[^>]*>.+<\/style[^>]*>/isU", '', $string);
2175      $string = str_replace('>', '> ', $string);
2176      $string = str_replace('<', ' <', $string);
2177      $string = strip_tags($string);
2178      $string = preg_replace("/\s+/", " ", $string);
2179      $string = trim($string);
2180      return $string;
2181  }
2182  
2183  /**
2184   * Make a string containing HTML safe for use in a HTML attribute
2185   * Tags are stripped and entities are normalized
2186   */
2187  function stringToAttribute ($string) {
2188      $string = stringStripTags($string);
2189      $string = entity::named_to_numeric($string);
2190      $string = entity::normalize_numeric($string);
2191  
2192      if (strtoupper(_CHARSET) == 'UTF-8') {
2193          $string = entity::numeric_to_utf8($string);
2194      }
2195  
2196      $string = entity::specialchars($string, 'html');
2197      $string = entity::numeric_to_named($string);
2198      return $string;
2199  }
2200  
2201  /**
2202   * Make a string containing HTML safe for use in a XML document
2203   * Tags are stripped, entities are normalized and named entities are
2204   * converted to numeric entities.
2205   */
2206  function stringToXML ($string) {
2207      $string = stringStripTags($string);
2208      $string = entity::named_to_numeric($string);
2209      $string = entity::normalize_numeric($string);
2210  
2211      if (strtoupper(_CHARSET) == 'UTF-8') {
2212          $string = entity::numeric_to_utf8($string);
2213      }
2214  
2215      $string = entity::specialchars($string, 'xml');
2216      return $string;
2217  }
2218  
2219  // START: functions from the end of file BLOG.php
2220  // used for mail notification (html -> text)
2221  function toAscii($html) {
2222      // strip off most tags
2223      $html = strip_tags($html,'<a>');
2224      $to_replace = "/<a[^>]*href=[\"\']([^\"^']*)[\"\'][^>]*>([^<]*)<\/a>/i";
2225      _links_init();
2226      $ascii = preg_replace_callback ($to_replace, '_links_add', $html);
2227      $ascii .= "\n\n" . _links_list();
2228      return strip_tags($ascii);
2229  }
2230  
2231  function _links_init() {
2232     global $tmp_links;
2233     $tmp_links = array();
2234  }
2235  
2236  function _links_add($match) {
2237     global $tmp_links;
2238     array_push($tmp_links, $match[1]);
2239     return $match[2] . ' [' . sizeof($tmp_links) .']';
2240  }
2241  
2242  function _links_list() {
2243     global $tmp_links;
2244     $output = '';
2245     $i = 1;
2246     foreach ($tmp_links as $current) {
2247        $output .= "[$i] $current\n";
2248        $i++;
2249     }
2250     return $output;
2251  }
2252  // END: functions from the end of file BLOG.php
2253  
2254  // START: functions from the end of file ADMIN.php
2255  /**
2256   * @todo document this
2257   */
2258  function encode_desc(&$data)
2259  {
2260      $to_entities = get_html_translation_table(HTML_ENTITIES);
2261  
2262      $from_entities = array_flip($to_entities);
2263  
2264      $data = strtr($data,$from_entities);
2265      $data = strtr($data,$to_entities);
2266  
2267      return $data;
2268  }
2269  
2270  /**
2271   * Returns the Javascript code for a bookmarklet that works on most modern browsers
2272   *
2273   * @param blogid
2274   */
2275  function getBookmarklet($blogid) {
2276      global $CONF;
2277  
2278      // normal
2279      $document = 'document';
2280      $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('";
2281      $bookmarkletline .= $CONF['AdminURL'] . "bookmarklet.php?blogid=$blogid";
2282      $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();";
2283  
2284      return $bookmarkletline;
2285  }
2286  // END: functions from the end of file ADMIN.php
2287  
2288  /**
2289   * Returns a variable or null if not set
2290   *
2291   * @param mixed Variable
2292   * @return mixed Variable
2293   */
2294  function ifset(&$var) {
2295      if (isset($var)) {
2296          return $var;
2297      }
2298  
2299      return null;
2300  }
2301  
2302  /**
2303   * Returns number of subscriber to an event
2304   *
2305   * @param event
2306   * @return number of subscriber(s)
2307   */
2308  function numberOfEventSubscriber($event) {
2309      $query = 'SELECT COUNT(*) as count FROM ' . sql_table('plugin_event') . ' WHERE event=\'' . $event . '\'';
2310      $res = sql_query($query);
2311      $obj = sql_fetch_object($res);
2312      return $obj->count;
2313  }
2314  
2315  /**
2316   * sets $special global variable for use in index.php before selector()
2317   *
2318   * @param String id
2319   * @return nothing
2320   */
2321  function selectSpecialSkinType($id) {
2322      global $special;
2323      $special = strtolower($id);
2324  }
2325  
2326  /**
2327   * cleans filename of uploaded file for writing to file system
2328   *
2329   * @param String str
2330   * @return String cleaned filename ready for use
2331   */
2332  function cleanFileName($str) {
2333      $str = strtolower($str);
2334      $ext_point = strrpos($str,".");
2335      if ($ext_point===false) return false;
2336      $ext = substr($str,$ext_point,strlen($str));
2337      $str = substr($str,0,$ext_point);
2338  
2339      return preg_replace("/[^a-z0-9-]/","_",$str).$ext;
2340  }
2341  
2342  ?>


Generated: Mon May 2 16:14:08 2011 Cross-referenced by PHPXref 0.7.1