* @package kernel */ namespace Bitweaver; use Bitweaver\Users\BitHybridAuthManager; use Bitweaver\Wiki\BitPage; /** * required setup */ define( 'DEFAULT_PACKAGE', 'kernel' ); define( 'CENTER_COLUMN', 'c' ); define( 'HOMEPAGE_LAYOUT', 'home' ); /** * The global system singleton — `$gBitSystem` — that bootstraps and coordinates bitweaver. * * BitSystem is instantiated once in `setup_inc.php` and is available everywhere as * `$gBitSystem`. It owns six concerns: * * ## 1. Package registry * * Every package self-registers by calling `$gBitSystem->registerPackage()` from its * `bit_setup_inc.php`. Registration defines the `_PKG_PATH`, `_PKG_URL`, `_PKG_NAME` * constants and populates `$mPackages`. `scanPackages()` iterates the web-root directories * and loads each package's setup file; `loadPackage()` loads one by name. * * Package status is stored in kernel_config as `package_`: * - `'y'` active (installed + enabled) * - `'i'` installed but not active * - `'n'` / absent — not installed * * `registerAppMenu()` adds a package's navbar dropdown to `$mAppMenu`, which is rendered * by `kernel/templates/top_bar.tpl`. * * ## 2. Configuration (`kernel_config` table) * * `$mConfig` is a flat string→string hash loaded from `kernel_config` at startup. * Read via `getConfig($name, $default)`, written persistently via `storeConfig($name, $value)`, * transiently via `setConfig()` (in-process only, no DB write). `isFeatureActive($name)` * returns true when the config value is non-empty and not `'n'`. * * ## 3. Display pipeline * * `display($pMid, $browserTitle, $optionsHash)` is the final call on every page. It sets * HTTP headers, loads the theme, assigns Smarty variables, and renders `kernel/html.tpl` * (which pulls in layout columns, modules, and `$pMid` as the centre piece). For non-HTML * output use `outputJson()` or `outputRaw()`. `fatalError()` and `fatalPermission()` both * terminate with `die` after rendering an error template. * * ## 4. Permissions and access control * * `fatalPermission($perm)` redirects unauthenticated users to the login form and shows a * permission-denied message to authenticated users who lack the required permission. * `isFeatureActive()`, `verifyPackage()`, and `verifyFeature()` are convenience guards that * call `fatalError()` when the condition is not met. * * ## 5. Installer and schema registration * * During install, each package's `admin/schema_inc.php` calls the `register*` family of * methods to declare its DB tables, sequences, indexes, constraints, default data, and * permissions. These populate `$mPackages[$pkg]['tables']`, `['defaults']`, etc. * `verifyInstalledPackages()` cross-checks the live DB against the registered schema to * determine what is installed, missing, or needs upgrading. * * ## 6. Utilities * * - **MIME types** — `lookupMimeType()`, `verifyMimeType()`, `verifyFileExtension()` * - **Versioning** — `getVersion()`, `storeVersion()`, `getBitVersion()`, `getLatestUpgradeVersion()` * - **Time/date** — thin wrappers over `$mServerTimestamp` (a BitDate): `getUTCTime()`, * `get_short_date_format()`, etc. * - **Navigation** — `getDefaultPage()`, `getIndexPage()`, `setBrowserTitle()`, * `setPagination()`, `setCanonicalLink()` * * @package kernel */ class BitSystem extends BitSingleton { // Initiate class variables // Essential information about packages public $mPackages = []; // An array of object keys to clear from cache on page destruction private $mClearCacheKeys = []; // Cross Reference Package Directory Name => Package Key used as index into $mPackages public $mPackagesDirNameXref = []; // Contains site style information public $mStyle = []; // Information about package menus used in all menu modules and top bar public $mAppMenu = []; // The currently active page private $mActivePackage; // Modules that need to be inserted during installation public $mInstallModules = []; // Javascript to be added to the attribute public $mOnload = []; // Javascript to be added to the attribute public $mOnunload = []; // Used by packages to register notification events that can be subscribed to. public $mNotifyEvents = []; // Used to store contents of kernel_config public $mConfig; // Used to monitor if ::registerPackage() was called. This is used to determine whether to auto-register a package public $mRegisterCalled; // The name of the package that is currently being processed public $mPackageFileName; // Content classes. public $mContentClasses = []; // Debug HTML to be displayed just after the HTML headers public $mDebugHtml = ""; public $mErrorRep; public $mMimeTypes = []; public $mPermHash = []; public$mRequirements = []; public $mServerTimestamp; public $mTimer; // Output http status public $mHttpStatus = HttpStatusCodes::HTTP_OK; protected static $singleton = null; protected static function getSingleInstance() { return static::$singleton; } // === BitSystem constructor /** * base constructor, auto assigns member db variable * * @access public */ // Constructor receiving a PEAR::Db database object. public function __construct() { global $gBitTimer; // Call DB constructor which will create the database member variable parent::__construct(); $this->mAppMenu = []; if (!isset($gBitTimer)) { $gBitTimer = new BitTimer(); $gBitTimer->start(); } $this->mTimer = $gBitTimer; $this->mServerTimestamp = new BitDate(); $this->loadConfig(); // Critical Preflight Checks $this->checkEnvironment(); $this->mRegisterCalled = false; // Set the separator for PHP generated tags to be & instead of & // This is necessary for XHTML compliance ini_set( "arg_separator.output", "&" ); // Remove automatic quotes added to POST/COOKIE by PHP foreach( $_REQUEST as $k => $v ) { if( !\is_array( $_REQUEST[$k] ) ) { $_REQUEST[$k] = stripslashes( $v ); } } $this->defineTempDir(); } public function __destruct() { parent::__destruct(); // Hopefully gBitSystem is among the last objects destroyed and can force cache purging of any leftover objects that might be in an inconsistent state due to multiple object copies invoked in the same page load foreach( array_keys( $this->mClearCacheKeys ) as $cacheKey ) { // $ret = apcu_delete( $cacheKey ); } } public function __sleep() { return array_merge( parent::__sleep(), [ 'mPackages', 'mPackagesDirNameXref', 'mStyle', 'mAppMenu', 'mInstallModules', 'mOnload', 'mOnunload', 'mNotifyEvents', 'mConfig', 'mRegisterCalled', 'mPackageFileName', 'mContentClasses' ] ); } public function isPurgedFromCache( $pCacheKey ) { return !empty( $this->mClearCacheKeys[$pCacheKey] ); } public function queueClearFromCache( $pCacheKey ): void { $this->mClearCacheKeys[$pCacheKey] = true; } public static function loadFromCache( $pCacheKey, $pContentTypeGuid = null ) { global $gBitTimer; if( $ret = parent::loadFromCache( $pCacheKey ) ) { $ret->setHttpStatus( HttpStatusCodes::HTTP_OK ); if (!isset($gBitTimer)) { $gBitTimer = new BitTimer(); $gBitTimer->start(); } $ret->mTimer = $gBitTimer; $ret->mTimer->start(); $ret->mOnload = []; $ret->mAppMenu = []; $ret->defineTempDir(); $ret->mServerTimestamp = new BitDate(); } return $ret; } /** * Load all preferences and store them in $this->mConfig * * @param $pPackage optionally get preferences only for selected package */ public function loadConfig( $pPackage = null ) { $queryVars = []; $whereClause = ''; if( $pPackage ) { array_push( $queryVars, $pPackage ); $whereClause = ' WHERE `package`=? '; } if ( empty( $this->mConfig ) && !defined( 'BIT_INSTALL' ) ) { $this->mConfig = []; $query = "SELECT `config_name` ,`config_value`, `package` FROM `" . BIT_DB_PREFIX . "kernel_config` " . $whereClause; if( $rs = $this->mDb->query( $query, $queryVars, -1, -1 ) ) { while( $row = $rs->fetchRow() ) { $this->mConfig[$row['config_name']] = $row['config_value']; } } return count( $this->mConfig ); } return 0; } // <<< getConfig /** * Add getConfig / setConfig for more uniform handling of config variables instead of spreading global vars. * easily get the value of any given preference stored in kernel_config * * @param string $pName Perl regular expression * @param string $pDefault only manipulate settings with this value set * @access public **/ public function getConfig( string $pName, string|null $pDefault = null ): string { if( empty( $this->mConfig ) ) { $this->loadConfig(); } return empty( $this->mConfig[$pName] ) ? ($pDefault ?? '') : $this->mConfig[$pName]; } // <<< getConfigMatch /** * retreive a group of config variables * * @param string $pPattern Perl regular expression * @param string $pSelectValue only manipulate settings with this value set * @access public **/ public function getConfigMatch( $pPattern, $pSelectValue = '' ): array { if( empty( $this->mConfig ) ) { $this->loadConfig(); } $matching_keys = preg_grep( $pPattern, array_keys( $this->mConfig )); $new_array = []; foreach( $matching_keys as $key=>$value ) { if ( empty( $pSelectValue ) || ( !empty( $pSelectValue ) && $this->mConfig[$value] == $pSelectValue )) { $new_array[$value] = $this->mConfig[$value]; } } return $new_array; } /** * storeConfigMatch set a group of config variables * * @param string $pPattern Perl regular expression * @param string $pSelectValue only manipulate settings with this value set * @param string $pNewValue New value that should be set for the matching settings (null will remove the entries from the DB) * @param string $pPackage Package for which the settings are * @return void */ public function storeConfigMatch( $pPattern, $pSelectValue = "", $pNewValue = null, $pPackage = null ): void { if( empty( $this->mConfig ) ) { $this->loadConfig(); } $matchingKeys = preg_grep( $pPattern, array_keys( $this->mConfig )); foreach( $matchingKeys as $key => $config_name ) { if( empty( $pSelectValue ) || ( !empty( $pSelectValue ) && $this->mConfig[$config_name] == $pSelectValue )) { $this->storeConfig( $config_name, $pNewValue, $pPackage ); } } } /** * Set a hash value in the mConfig hash. This does *NOT* store the value in * the database. It does no checking for existing or duplicate values. the * main point of this function is to limit direct accessing of the mConfig * hash. I will probably make mConfig private one day. * * @param string Hash key for the mConfig value * @param string Value for the mConfig hash key */ public function setConfig( $pName, $pValue ) { $this->mConfig[$pName] = $pValue; return true; } // <<< storeConfig /** * bitweaver needs lots of settings just to operate. * loadConfig assigns itself the default preferences, then loads just the differences from the database. * In storeConfig (and only when storeConfig is called) we make a second copy of defaults to see if * preferences you are changing is different from the default. * if it is the same, don't store it! * So instead updating the whole prefs table, only updat "delta" of the changes delta from defaults. * * @access public **/ public function storeConfig( $pName, $pValue, $pPackage = '' ) { global $gMultisites; //stop undefined offset error being thrown after packages are installed if( !empty( $this->mConfig )) { // store the pref if we have a value _AND_ it is different from the default if( ( empty( $this->mConfig[$pName] ) || ( $this->mConfig[$pName] != $pValue ))) { // make sure the value doesn't exceede database limitations $pValue = substr( $pValue ?? '', 0, 250 ); // store the preference in multisites, if used if( $this->isPackageActive( 'multisites' ) && BitBase::verifyId( $gMultisites->mMultisiteId ) && isset( $gMultisites->mConfig[$pName] )) { $query = "UPDATE `".BIT_DB_PREFIX."multisite_preferences` SET `config_value`=? WHERE `multisite_id`=? AND `config_name`=?"; $result = $this->mDb->query( $query, [ empty( $pValue ) ? '' : $pValue, $gMultisites->mMultisiteId, $pName ] ); } else { $this->StartTrans(); $query = "DELETE FROM `".BIT_DB_PREFIX."kernel_config` WHERE `config_name`=?"; $result = $this->mDb->query( $query, [ $pName ] ); // make sure only non-empty values get saved, including '0' if( isset( $pValue ) && ( !empty( $pValue ) || is_numeric( $pValue ))) { $query = "INSERT INTO `".BIT_DB_PREFIX."kernel_config`(`config_name`,`config_value`,`package`) VALUES (?,?,?)"; $result = $this->mDb->query( $query, [ $pName, $pValue, strtolower( $pPackage ) ]); } $this->CompleteTrans(); } // Force the ADODB cache to flush $isCaching = $this->mDb->isCachingActive(); $this->mDb->setCaching( false ); $this->loadConfig(); $this->mDb->setCaching( $isCaching ); $this->clearFromCache(); } } $this->setConfig( $pName, $pValue ); return true; } // <<< expungePackageConfig /** * Delete all prefences for the given package * @access public **/ public function expungePackageConfig( $pPackageName ) { if( !empty( $pPackageName ) ) { $query = "DELETE FROM `".BIT_DB_PREFIX."kernel_config` WHERE `package`=?"; $result = $this->mDb->query( $query, [ strtolower( $pPackageName ) ] ); // let's force a reload of the prefs unset( $this->mConfig ); $this->loadConfig(); } } // === hasValidSenderEmail /** * Determines if this site has a legitimate sender address set. * * @param string $pSenderEmail * @access public */ public function hasValidSenderEmail( $pSenderEmail=null ) { if( empty( $pSenderEmail ) ) { $pSenderEmail = $this->getConfig( 'site_sender_email' ); } return !empty( $pSenderEmail ) && !preg_match( '/.*localhost$/', $pSenderEmail ); } // === getErrorEmail /** * Smartly determines where error emails should go * * @access public */ public function getErrorEmail() { if( defined('ERROR_EMAIL') ) { $ret = ERROR_EMAIL; } elseif( $this->getConfig( 'site_sender_email' ) ) { $ret = $this->getConfig( 'site_sender_email' ); } elseif( !empty( $_SERVER['SERVER_ADMIN'] ) ) { $ret = $_SERVER['SERVER_ADMIN']; } else { $ret = 'root@localhost'; } } // === sendEmail /** * centralized function for send emails * * @param array $pMailHash * @access public */ public function sendEmail( $pMailHash ) { $fromEmail = !empty( $pMailHash['from'] ) ? $pMailHash['from'] : $this->getConfig( 'site_sender_email' ); $extraHeaders = "Return-Path: $fromEmail\r\n"; if( $this->getConfig( 'bcc_email' ) ) { $extraHeaders .= "Bcc: ".$this->getConfig( 'bcc_email' )."\r\n"; } if( !empty( $pMailHash['Reply-to'] ) ) { $extraHeaders .= "Reply-to: ".$pMailHash['Reply-to']."\r\n"; } mail($pMailHash['email'], $pMailHash['subject'].' '.$_SERVER["SERVER_NAME"], $pMailHash['body'], "From: ".$fromEmail."\r\nContent-type: text/plain;charset=utf-8\r\n$extraHeaders", ); } /** * Set the http status, most notably for 404 not found for deleted content * * @param $pHttpStatus numerical HTTP status, most typically 404 (not found) or 403 (forbidden) * @access public */ public function setHttpStatus( $pHttpStatus ) { $this->mHttpStatus = $pHttpStatus; } public function outputHeader() { // Add the user to an apache ENV variable so it can be logged, like: // LogFormat "%V %h %l %{USERID}e %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" \"%{Cookie}n\"" combinedcookie global $gBitUser; if( is_object( $gBitUser ) ) { // apache_setenv( 'USERID', $gBitUser->getField('login', '-'), true ); } // see if we have a custom status other than 200 OK header( $_SERVER["SERVER_PROTOCOL"].' '.HttpStatusCodes::getMessageForCode( $this->mHttpStatus ) ); } public function outputJson( $pOutput, $pStatusCode=200 ) { global $gBitSmarty, $gBitThemes; $gBitThemes->setFormatHeader( 'json' ); $this->setHttpStatus( $pStatusCode ); $this->outputHeader(); if( \is_array( $pOutput ) ) { $gBitSmarty->assign( 'jsonHash', $pOutput ); } print $gBitSmarty->fetch( 'bitpackage:kernel/json_output.tpl' ); die; } public function outputRaw( $pOutput, $pStatusCode=200 ) { global $gBitSmarty, $gBitThemes; $gBitThemes->setFormatHeader( 'text' ); $this->setHttpStatus( $pStatusCode ); $this->outputHeader(); if( \is_array( $pOutput ) ) { foreach( $pOutput as $out ) { print "$out\n"; } } else { print $pOutput; } die; } /** * Display the main page template * * @param string $pMid the name of the template for the page content * @param string $pBrowserTitle a string to be displayed in the top browser bar * @param array $pOptionsHash */ public function display( $pMid, $pBrowserTitle = null, $pOptionsHash = [] ) { global $gBitSmarty, $gBitThemes, $gContent; $gBitSmarty->verifyCompileDir(); $this->outputHeader(); if( $this->mHttpStatus != 200 ) { // error_log( "HTTP/1.0 ".HttpStatusCodes::getMessageForCode( $this->mHttpStatus )." http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ); } $gBitThemes->preLoadStyle(); if( file_exists(THEMES_STYLE_PATH."theme_head_inc.tpl") ) { $gBitSmarty->assign( 'theme_head', THEMES_STYLE_PATH."theme_head_inc.tpl" ); } // set the correct headers if it hasn't been done yet if( empty( $gBitThemes->mFormatHeader )) { // display is the last thing we call and therefore we need to set a default $gBitThemes->setFormatHeader( !empty( $pOptionsHash['format'] ) ? $pOptionsHash['format'] : 'html' ); } // set the desired display mode - this lets bitweaver know what type of page we are viewing if( empty( $gBitThemes->mDisplayMode )) { // display is the last thing we call and therefore we need to set a default $gBitThemes->setDisplayMode( !empty( $pOptionsHash['display_mode'] ) ? $pOptionsHash['display_mode'] : 'display' ); } if( $pMid == 'error.tpl' ) { $this->setBrowserTitle( !empty( $pBrowserTitle ) ? $pBrowserTitle : KernelTools::tra( 'Error' ) ); $pMid = 'bitpackage:kernel/error.tpl'; } // only using the default html header will print modules and all the rest of it. if( $gBitThemes->mFormatHeader != 'html' ) { $gBitSmarty->display( $pMid ); return; } if( !empty( $pBrowserTitle )) { $this->setBrowserTitle( $pBrowserTitle ); } // populate meta description with something useful so you are not penalized/ignored by web crawlers if( is_object( $gContent ) && is_a( $gContent, 'LibertyContent' ) ) { if( $desc = $gContent->generateDescription() ) { $desc = preg_replace( '/\s+/', ' ', strip_tags( $desc )); // $gContent->getContentTypeName().': '. $gBitSmarty->assign( 'metaDescription', substr( $desc, 0, 256 ) ); } } $this->preDisplay( $pMid ); $gBitSmarty->assign( 'mid', $pMid ); // Create key for CSP nonce value ... TODO ? this could be the tk ticket value // tk only exists when logged in ;) global $gBitUser; if (empty($_SESSION['csp_nonce'])) { $_SESSION['csp_nonce'] = $gBitUser->mTicket ?? bin2hex(random_bytes(16)); } $gBitSmarty->assign( 'cspNonce', $_SESSION['csp_nonce'] ); // Make sure that the gBitSystem symbol available to templates is correct and up-to-date. print $gBitSmarty->fetch( 'bitpackage:kernel/html.tpl' ); $this->postDisplay( $pMid ); } // === preDisplay /** * Take care of any processing that needs to happen just before the template is displayed * * @param string * @access private */ public function preDisplay( $pMid ) { global $gCenterPieces, $gBitSmarty, $gBitThemes, $gDefaultCenter; $gBitThemes->loadLayout(); // check to see if we are working with a dynamic center area if( $pMid == 'bitpackage:kernel/dynamic.tpl' ) { $gBitSmarty->assign( 'gCenterPieces', $gCenterPieces ); } $gBitThemes->preLoadStyle(); /* @TODO - fetch module php files before rendering tpls. * The basic problem here is center_list and module files are * processed during page rendering, which means code in those * files can not set information before rendering. Kinda sucks. * * So what this does is, this calls on a service function allowing any * package to check if its center or other module file is going to be * called and gives it a chance to set any information for first. * * Remove when TODO is complete. -wjames5 */ global $gBitUser; if( isset( $gBitUser )) { //SMARTY3 $gBitUser->invokeServices( 'module_display_function' ); } // process layout // SMARTY3 require_once( THEMES_PKG_INCLUDE_PATH.'modules_inc.php' ); $gBitThemes->loadStyle(); /* force the session to close *before* displaying. Why? Note this very important comment from http://us4.php.net/exec edwin at bit dot nl 23-Jan-2002 04:47 If you are using sessions and want to start a background process, you might have the following problem: The first time you call your script everything goes fine, but when you call it again and the process is STILL running, your script seems to "freeze" until you kill the process you started the first time. You'll have to call session_write_close(); to solve this problem. It has something to do with the fact that only one script/process can operate at once on a session. (others will be lockedout until the script finishes) I don't know why it somehow seems to be influenced by background processes, but I tried everything and this is the only solution. (i had a perl script that "daemonized" it's self like the example in the perl manuals) Took me a long time to figure out, thanks ian@virtisp.net! :-) ... and a similar issue can happen for very long display times. */ session_write_close(); } // === postDisplay /** * Take care of any processing that needs to happen just after the template is displayed * * @param string * @access private */ public function postDisplay( $pMid ) { } // === setHelpInfo /** * Set the smarty variables needed to display the help link for a page. * * @param string $package Package Name * @param string $context Context of the help within the package * @param string $desc Description of the help link (not the help itself) */ public function setHelpInfo( $package, $context, $desc ) { global $gBitSmarty; $gBitSmarty->assign( 'BitweaverHelpInfo', [ 'URL' => "https://bitweaver.org/wiki/index.php?page=$package$context", 'Desc' => $desc ] ); } // === getPackageStatus /** * find out a packages installation status * @param string $pPackageName the name of the package to test * where the package name is in the form used to index $mPackages * @return string where * 'i' is installed but not active * 'y' is installed and active * 'n' is not installed */ public function getPackageStatus( $pPackageName ) { // A package is installed if // $this->getConfig('package_'.$name) == 'i' // or $this->getConfig('package_'.$name) == 'y' // // A package is installed and active if // _PKG_NAME is defined // and $this->getConfig('package_'.$name) == 'y' $ret = 'n'; if( defined( strtoupper( $pPackageName ).'_PKG_NAME' ) ) { if( $name = strtolower( @constant( strtoupper( $pPackageName ).'_PKG_NAME' ))) { // kernel always active $ret = $name == 'kernel' ? 'y' : $this->getConfig( 'package_'.$name, 'n' ); // During install getConfig() is a no-op; fall back to mPackages state set by verifyInstalledPackages if( $ret == 'n' && defined( 'BIT_INSTALL' ) && !empty( $this->mPackages[$name]['installed'] ) ) { $ret = 'y'; } } } return $ret; } // === isPackageActive /** * check's if a package is active. * @param $pPackageName the name of the package to test * where the package name is in the form used to index $mPackages * See comments in scanPackages for more information * @return bool * @access public */ public function isPackageActive( $pPackageName ) { return $this->getPackageStatus( $pPackageName ) == 'y'; } // === isPackageActiveEarly /** * check if a package is active; but only do this after making sure a package * has had it's bit_setup_inc loaded if possible. This func exists for use in * other packages bit_setup_inc's to avoid dependency on load order and ugly code * @param $pPackageName the name of the package to test * where the package name is in the form used to index $mPackages * See comments in scanPackages for more information * @return bool * @access public */ public function isPackageActiveEarly( $pPackageName ) { $ret = false; $pkgname_l = strtolower( $pPackageName ); if( is_file(BIT_ROOT_PATH.$pkgname_l.'/includes/bit_setup_inc.php') ) { require_once BIT_ROOT_PATH.$pkgname_l.'/includes/bit_setup_inc.php'; $ret = $this->isPackageActive( $pPackageName ); } elseif( $pkgname_l == 'kernel' ) { $ret = true; } return $ret; } // === isPackageInstalled /** * check's if a package is Installed * @param $pPackageName the name of the package to test * where the package name is in the form used to index $mPackages * See comments in scanPackages for more information * @return bool * @access public */ public function isPackageInstalled( $pPackageName ) { $pkgstatus = $this->getPackageStatus( $pPackageName ); return ( $pkgstatus == 'y' ) || ( $pkgstatus == 'i' ); } // === verifyPackage /** * It will verify that the given package is active or it will display the error template and die() * @param $pPackageName the name of the package to test * where the package name is in the form used to index $mPackages * See comments in scanPackages for more information * @return bool * @access public */ public function verifyPackage( $pPackageName ) { if( !$this->isPackageActive( $pPackageName ) ) { $this->fatalError( KernelTools::tra("This package is disabled").": $pPackageName", null, null, HttpStatusCodes::HTTP_NOT_FOUND ); } return true; } // === getPermissionInfo /** * It will get information about a permissions * @param string $pPermission value of a given permission * @param string $pPackageName value of a given package * @return array */ public function getPermissionInfo( $pPermission = '', $pPackageName = '' ) { $ret = null; $bindVars = []; $sql = 'SELECT * FROM `'.BIT_DB_PREFIX.'users_permissions` '; if( !empty( $pPermission ) ) { $sql .= ' WHERE `perm_name`=? '; array_push( $bindVars, $pPermission ); } elseif( !empty( $pPackageName ) ) { $sql .= ' WHERE `package` = ? '; array_push( $bindVars, substr($pPackageName,0,100)); } $ret = $this->mDb->getAssoc( $sql, $bindVars ); return $ret; } // === verifyPermission /** * DEPRECATED - this function has been moved into BitPermUser, use that */ public function verifyPermission( $pPermission, $pMsg = null ) { global $gBitUser; return $gBitUser->verifyPermission( $pPermission, $pMsg ); } // === fatalPermission /** * Interupt code execution and show a permission denied message. * This does not show a big nasty denied message if user is simply not logged in. * This *could* lead to a user seeing a denied message twice, however this is * unlikely as logic permission checks should prevent access to non-permed page REQUEST in the first place * @param $pPermission value of a given permission * @param $pMsg optional additional information to present to user * @return void * @access public */ public function fatalPermission( $pPermission, $pMsg=null ) { global $gBitUser, $gBitSmarty, $gBitThemes; if( !$gBitUser->isRegistered() ) { require_once USERS_PKG_CLASS_PATH.'BitHybridAuthManager.php'; BitHybridAuthManager::loadSingleton(); global $gBitHybridAuthManager; $gBitSmarty->assign( 'hybridProviders', $gBitHybridAuthManager->getEnabledProviders() ); $gBitSmarty->assign( 'template', 'bitpackage:users/login_inc.tpl' ); } else { $title = 'Oops!'; if( empty( $pMsg ) ) { $pMsg = $this->getPermissionDeniedMessage( $pPermission ); } $gBitSmarty->assign( 'fatalTitle', KernelTools::tra( "Permission denied." ) ); } // bit_error_log( "PERMISSION DENIED: $pPermission $pMsg" ); $gBitSmarty->assign( 'msg', KernelTools::tra( $pMsg ) ); $this->setHttpStatus( HttpStatusCodes::HTTP_NOT_FOUND ); $this->display( "error.tpl" ); die; } public function getPermissionDeniedMessage( $pPermission ) { $permDesc = $this->getPermissionInfo( $pPermission ); $ret = "You do not have the required permissions"; if( !empty( $permDesc[$pPermission]['perm_desc'] ) ) { if( preg_match( '/administrator,/i', $permDesc[$pPermission]['perm_desc'] ) ) { $ret .= preg_replace( '/^administrator, can/i', ' to ', $permDesc[$pPermission]['perm_desc'] ); } else { $ret .= preg_replace( '/^can /i', ' to ', $permDesc[$pPermission]['perm_desc'] ); } } return $ret; } /** * This code was duplicated _EVERYWHERE_ so here is an easy template to cut that down. * @param $pFormHash documentation needed * @param $pMsg documentation needed * @return void * @access public */ public function confirmDialog( $pFormHash, $pMsg ) { global $gBitSmarty; if( !empty( $pMsg ) ) { $pageTitle = self::getParameter( $pMsg, 'label', 'Please Confirm' ); if( empty( $pParamHash['cancel_url'] ) ) { $gBitSmarty->assign( 'backJavascript', 'onclick="history.back();"' ); } if( !empty( $pFormHash['input'] ) ) { $gBitSmarty->assign( 'inputFields', $pFormHash['input'] ); unset( $pFormHash['input'] ); } $gBitSmarty->assign( 'msgFields', $pMsg ); $gBitSmarty->assign( 'hiddenFields', $pFormHash ); $this->display( 'bitpackage:kernel/confirm.tpl', $pageTitle, [ 'display_mode' => 'edit' ]); die; } } // === isFeatureActive /** * check's if the specfied feature is active * * @param string $pFeatureName * @return bool */ public function isFeatureActive( $pFeatureName, $setting = '' ) { $ret = false; if( $pFeatureName ) { $featureValue = $this->getConfig($pFeatureName); $ret = empty($setting) ? !empty( $featureValue ) && ( $featureValue != 'n' ) : !empty( $featureValue ) && ( $featureValue == $setting ); } return $ret; } // === verifyFeature /** * It will verify that the given feature is active or it will display the error template and die() * @param $pFeatureName the name of the package to test * @return bool * * @param $pKey hash key */ public function verifyFeature( $pFeatureName ) { if( !$this->isFeatureActive( $pFeatureName ) ) { $this->fatalError( KernelTools::tra("This feature is disabled").": $pFeatureName" ); } return true; } // === registerPackage /** * Define name, location and url DEFINE's * * @param $pKey hash key * @return void * @access public */ public function registerPackage( $pRegisterHash ) { if( !isset( $pRegisterHash['package_name'] )) { $this->fatalError( KernelTools::tra("Package name not set in ")."registerPackage: $this->mPackageFileName" );; } else { $name = $pRegisterHash['package_name']; } if( !isset( $pRegisterHash['package_path'] )) { $this->fatalError( KernelTools::tra("Package path not set in ")."registerPackage: $this->mPackageFileName" );; } else { $path = $pRegisterHash['package_path']; } $this->mRegisterCalled = true; if( empty( $this->mPackages )) { $this->mPackages = []; } $pkgName = str_replace( ' ', '_', strtoupper( $name )); $pkgNameKey = strtolower( $pkgName ); // Some package settings $this->mPackages[$pkgNameKey]['homeable'] = !empty( $pRegisterHash['homeable'] ); $this->mPackages[$pkgNameKey]['required'] = !empty( $pRegisterHash['required_package'] ); $this->mPackages[$pkgNameKey]['service'] = !empty( $pRegisterHash['service'] ) ? $pRegisterHash['service'] : false; $this->mPackages[$pkgNameKey]['status'] = $this->getConfig( 'package_'.$pkgNameKey, 'n'); # y = Active # i = Installed # n (or empty/null) = Not Active and Not Installed // set package installed and active flag $this->mPackages[$pkgNameKey]['active_switch'] = $this->mPackages[$pkgNameKey]['status'] == 'a' || $this->mPackages[$pkgNameKey]['status'] == 'y' ? true : false; // set package installed flag (can be installed but not active) $this->mPackages[$pkgNameKey]['installed'] = $this->mPackages[$pkgNameKey]['status'] == 'i' || $this->mPackages[$pkgNameKey]['status'] == 'y' ? true : false; // Define _PKG_PATH $pkgDefine = $pkgName.'_PKG_PATH'; if( !defined( $pkgDefine )) { $pkgPath = BIT_ROOT_PATH . basename( $path ) . '/'; define( $pkgDefine, $pkgPath ); $arrayHash = [ $pkgName.'_PKG_INCLUDE_PATH' => BIT_ROOT_PATH . basename( $path ) . '/includes/', $pkgName.'_PKG_CLASS_PATH' => BIT_ROOT_PATH . basename( $path ) . '/includes/classes/', $pkgName.'_PKG_ADMIN_PATH' => BIT_ROOT_PATH . basename( $path ) . '/admin/', ]; foreach( $arrayHash as $defName => $defPath ) { if( !defined( $defName )) { define( $defName, is_dir( $defPath ) ? $defPath : $pkgPath ); } } } $this->mPackages[$pkgNameKey]['url'] = BIT_ROOT_URL . basename( $path ) . '/'; $this->mPackages[$pkgNameKey]['path'] = BIT_ROOT_PATH . basename( $path ) . '/'; // Define _PKG_URL $pkgDefine = (string) $pkgName.'_PKG_URL'; if( !defined( $pkgDefine )) { // Force full URI's for offline or exported content (newsletters, etc.) $root = !empty( $_REQUEST['uri_mode'] ) ? BIT_BASE_URI . BIT_ROOT_URL : BIT_ROOT_URL; define( $pkgDefine, $root . basename( $path ) . '/' ); } // Define _PKG_URI $pkgDefine = $pkgName.'_PKG_URI'; if( !defined( $pkgDefine ) && defined( 'BIT_BASE_URI' )) { define( $pkgDefine, BIT_BASE_URI . BIT_ROOT_URL . basename( $path ) . '/' ); } // Define _PKG_NAME $pkgDefine = $pkgName.'_PKG_NAME'; if( !defined( $pkgDefine )) { define( $pkgDefine, $name ); $this->mPackages[$pkgNameKey]['activatable'] = $pRegisterHash['activatable'] ?? true; } $this->mPackages[$pkgNameKey]['name'] = $name; // Define _PKG_DIR $package_dir_name = basename( $path ); $pkgDefine = $pkgName.'_PKG_DIR'; if( !defined( $pkgDefine )) { define( $pkgDefine, $package_dir_name ); } $this->mPackages[$pkgNameKey]['dir'] = $package_dir_name; $this->mPackagesDirNameXref[$package_dir_name] = $pkgNameKey; // Define _PKG_TITLE $pkgDefine = $pkgName.'_PKG_TITLE'; if( !defined( $pkgDefine )) { define( $pkgDefine, ucfirst( constant( $pkgName.'_PKG_DIR' ) ) ); } $this->mPackages[$pkgNameKey]['dir'] = $package_dir_name; // Work around for old versions of IIS that do not support $_SERVER['SCRIPT_FILENAME'] - wolff_borg if( !array_key_exists( 'SCRIPT_FILENAME', $_SERVER )) { //remove double-backslashes and return $_SERVER['SCRIPT_FILENAME'] = str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED'] ); } } public function setActivePackage( $pPkgName ) { $this->mActivePackage = $pPkgName; } public function getActivePackage() { if( empty( $this->mActivePackage ) ) { $this->mActivePackage = 'kernel'; // default to kernel, which has the default layout // Define the package we are currently in // I tried strpos instead of preg_match here, but it didn't like strings that begin with slash?! - spiderr $scriptDir = basename( dirname( $_SERVER['SCRIPT_FILENAME'] ) ); foreach( array_keys( $this->mPackages ) as $pkgNameKey ) { if( $scriptDir == $this->mPackages[$pkgNameKey]['dir'] ) { $this->mActivePackage = $pkgNameKey; if( !defined( 'ACTIVE_PACKAGE' ) ) { define( 'ACTIVE_PACKAGE', $pkgNameKey ); } break; } } } return $this->mActivePackage; } // === registerAppMenu /** * Register global system menu. Due to the startup nature of this method, it need to belong in BitSystem instead of BitThemes, where it would more naturally fit. * * @param $pKey hash key * @return void * @access public */ public function registerAppMenu( $pMenuHash, $pMenuTitle = null, $pTitleUrl = null, $pMenuTemplate = null, $pAdminPanel = false ) { $menuType = !empty( $pMenuHash['menu_type'] ) ? $pMenuHash['menu_type'] : 'bar'; if( \is_array( $pMenuHash ) ) { // shorthand $pkg = $pMenuHash['package_name']; // prepare hash $pMenuHash['style'] = 'display:'.( ( isset( $_COOKIE[$pkg.'menu'] ) && ( $_COOKIE[$pkg.'menu'] == 'o' ) ) ? 'block;' : 'none;' ); $pMenuHash['is_disabled'] = $this->getConfig( 'menu_'.$pkg ) == 'n'; $pMenuHash['menu_title'] = $this->getConfig( $pkg.'_menu_text', !empty( $pMenuHash['menu_title'] ) ? $pMenuHash['menu_title'] : ucfirst( constant( strtoupper( $pkg ).'_PKG_DIR' )), ); $pMenuHash['menu_position'] = $this->getConfig( $pkg.'_menu_position', $pMenuHash['menu_position'] ?? '', ); $this->mAppMenu[$menuType][$pkg] = $pMenuHash; } else { KernelTools::deprecated( 'Please use a menu registration hash instead of individual parameters: $gBitSystem->registerAppMenu( $menuHash )' ); $this->mAppMenu[$menuType][strtolower( $pMenuHash )] = [ 'menu_title' => $pMenuTitle, 'is_disabled' => ( $this->getConfig( 'menu_' . $pMenuHash ) == 'n' ), 'index_url' => $pTitleUrl, 'menu_template' => $pMenuTemplate, 'admin_panel' => $pAdminPanel, 'style' => 'display:' . ( empty( $pMenuTitle ) || ( isset( $_COOKIE[$pMenuHash . 'menu'] ) && ( $_COOKIE[$pMenuHash . 'menu'] == 'o' ) ) ? 'block;' : 'none;' ), ]; } uasort( $this->mAppMenu[$menuType], 'Bitweaver\bit_system_menu_sort' ); } /** * registerNotifyEvent * * @param array $pEventHash * @access public * @return void */ public function registerNotifyEvent( $pEventHash ) { $this->mNotifyEvents = array_merge( $this->mNotifyEvents, $pEventHash ); } // === fatalError /** * If an unrecoverable error has occurred, this method should be invoked. script exist occurs * * @param string $ pMsg error message to be displayed * @param string template file used to display error * @param string error dialog title. default gets site_error_title config, passing '' will result in no title * @return void this function will DIE DIE DIE!!! * @access public */ public function fatalError( $pMsg, $pTemplate=null, $pErrorTitle=null, $pHttpStatus = 200 ) { global $gBitSmarty, $gBitThemes; if( is_null( $pErrorTitle ) ) { $pErrorTitle = $this->getConfig( 'site_error_title', '' ); } if( empty( $pTemplate ) ) { $pTemplate = 'error.tpl'; } $gBitSmarty->assign( 'fatalTitle', KernelTools::tra( $pErrorTitle ) ); $gBitSmarty->assign( 'msg', $pMsg ); // if mHttpStatus is set, we can assume this was an expected fatal, such as a 404 or 403 if( !isset( $this->mHttpStatus ) ) { error_log( "Fatal Error: $pMsg http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ); } $this->setHttpStatus( $pHttpStatus ); if( $gBitThemes->isAjaxRequest() ) { $gBitSmarty->display( 'bitpackage:kernel/'.$pTemplate ); } else { $gBitSmarty->assign( 'metaNoIndex', 1 ); $this->display( $pTemplate ); } die; } // === loadPackage /** * Loads a package * * @param string $ pkgDir = Directory Name of package to load * @param string $ pScanFile file to be looked for * @param string $ autoRegister - true = autoregister any packages that don't register on their own, false = don't * @param string $ pOnce - true = do include_once to load file false = do include to load the file * @return void * @access public */ public function loadPackage( $pPkgDir, $pScanFile, $pAutoRegister=true, $pOnce=true ) { #check if already loaded, loading again won't work with 'include_once' since #no register call will be done, so don't auto register. if( $pAutoRegister && !empty( $this->mPackagesDirNameXref[$pPkgDir] ) ) { $pAutoRegister = false; } $this->mRegisterCalled = false; $scanFile = $pScanFile == 'admin/schema_inc.php' ? BIT_ROOT_PATH.$pPkgDir.'/'.$pScanFile : BIT_ROOT_PATH.$pPkgDir.'/includes/'.$pScanFile; $file_exists = 0; if( file_exists( $scanFile ) ) { $file_exists = 1; global $gBitSystem, $gLibertySystem, $gBitSmarty, $gBitUser, $gBitLanguage; $this->mPackageFileName = $scanFile; if( $pOnce ) { include_once $scanFile; } else { include $scanFile; } } if( ( $file_exists || $pPkgDir == 'kernel' ) && ( $pAutoRegister && !$this->mRegisterCalled ) ) { $pRegisterHash = [ #for auto registered packages Registration Package Name = Package Directory Name 'package_name' => $pPkgDir, 'package_path' => BIT_ROOT_PATH . $pPkgDir . '/', 'activatable' => false, ]; if( $pPkgDir == 'kernel' ) { $pRegisterHash = [ ...$pRegisterHash, 'required_package' => true ]; } $this->registerPackage( $pRegisterHash ); } } // === scanPackages /** * * scan all available packages. This is an *expensive* function. DO NOT call this functionally regularly , or arbitrarily. Failure to comply is punishable by death by jello suffication! * * @param string $ pScanFile file to be looked for * @param string $ pOnce - true = do include_once to load file false = do include to load the file * @param string $ pSelect - empty or 'all' = load all packages, 'installed' = load installed, 'active' = load active, 'x' = load packages with status x * @param string $ autoRegister - true = autoregister any packages that don't register on their own, false = don't * @param string $ fileSystemScan - true = scan file system for packages to load, False = don't * @return void * * Packages have three different names: * The directory name where they reside on disk * The Name they register themselves as when they call registerPackage * The Key for the array $this->mPackages * * Example: * A package in directory 'stars' that registers itself with a name of 'Star Ratings' * would have these three names: * * Directory Name: 'stars' * Registered Name: Star Ratings' * $this->mPackages key: 'star_ratings' * * Of course, its possible for all three names to be the same if the registered name * is all lower case without spaces and is the same as the diretory name. * * Functions that expect a package name as a parameter should make clear which form * of the name they expect. * * @access public */ public function scanPackages( $pScanFile = 'bit_setup_inc.php', $pOnce=true, $pSelect='', $pAutoRegister=true ) { global $gPreScan; if( !empty( $gPreScan ) && \is_array( $gPreScan )) { // gPreScan may hold a list of packages that must be loaded first foreach( $gPreScan as $pkgDir ) { $loadPkgs[] = $pkgDir; } } // load lib configs if( $pkgDir = opendir( BIT_ROOT_PATH )) { while( false !== ( $dirName = readdir( $pkgDir ))) { if( $dirName != '..' && $dirName != '.' && is_dir( BIT_ROOT_PATH . '/' . $dirName ) && $dirName != 'CVS' && preg_match( '/^\w/', $dirName )) { $loadPkgs[] = $dirName; } } } $loadPkgs = array_unique( $loadPkgs ); // load the list of pkgs in the right order foreach( $loadPkgs as $loadPkg ) { $this->loadPackage( $loadPkg, $pScanFile, $pAutoRegister, $pOnce ); } if( !defined( 'BIT_STYLES_PATH' ) && defined( 'THEMES_PKG_PATH' )) { define( 'BIT_STYLES_PATH', THEMES_PKG_PATH.'styles/' ); } if( !defined( 'BIT_STYLES_URL' ) && defined( 'THEMES_PKG_URL' )) { define( 'BIT_STYLES_URL', THEMES_PKG_URL.'styles/' ); } } /** * getSiteTitle * * @access public * @return string name of website */ public function getSiteTitle() { return $this->getConfig( 'site_title' ); } /** * getDefaultPage * * @access public * @return string URL of site homepage */ public function getDefaultPage() { return $this->getIndexPage( $this->getConfig( "bit_index" ) ); } /** * getIndexPage * * Returns the page for the given type * defaults to the site homepage * * @access public * @return string URL of page by index type */ public function getIndexPage( $pIndexType = null ){ global $userlib, $gBitUser, $gBitSystem; $pIndexType = !is_null( $pIndexType )? $pIndexType : $this->getConfig( "bit_index" ); $url = ''; if( $pIndexType == 'role_home') { // See if we have first a user assigned default group id, and second a group default system preference if( !$gBitUser->isRegistered() && ( $role_home = $gBitUser->getRoleHome( ANONYMOUS_TEAM_ID ))) { } elseif( @$this->verifyId( $gBitUser->mInfo['default_role_id'] ) && ( $role_home = $gBitUser->getRoleHome( $gBitUser->mInfo['default_role_id'] ))) { } elseif( $this->getConfig( 'default_home_role' ) && ( $role_home = $gBitUser->getRoleHome( $this->getConfig( 'default_home_role' )))) { } if( !empty( $role_home )) { if( $this->verifyId( $role_home ) ) { $url = BIT_ROOT_URL."index.php".( !empty( $role_home ) ? "?content_id=".$role_home : "" ); } elseif( strpos( $role_home, 'http://' ) === false ){ $url = BIT_ROOT_URL.$role_home; } else { $url = $role_home; } } } elseif( $pIndexType == 'my_page' || $pIndexType == 'my_home' || $pIndexType == 'user_home' ) { // TODO: my_home is deprecated, but was the default for BWR1. remove in DILLINGER - spiderr if( $gBitUser->isRegistered() ) { if( !$gBitUser->isRegistered() ) { $url = USERS_PKG_URL.'signin.php'; } else { if( $pIndexType == 'my_page' ) { $url = $gBitSystem->getConfig( 'users_login_homepage', USERS_PKG_URL.'my.php' ); if( $url != USERS_PKG_URL.'my.php' && strpos( $url, 'http://' ) === false ){ // the safe assumption is that a custom path is a subpath of the site // append the root url unless we have a fully qualified uri $url = BIT_ROOT_URL.$url; } } elseif( $pIndexType == 'user_home' ) { $url = $gBitUser->getDisplayUrl(); } else { $users_homepage = $gBitUser->getPreference( 'users_homepage' ); if( isset( $users_homepage ) && !empty( $users_homepage )) { $home = [ 'title' => $users_homepage]; $url = strpos($users_homepage, '/') === false ? BitPage::getDisplayUrlFromHash( $home ) : $users_homepage; } } } } else { $url = USERS_PKG_URL . 'signin.php'; } } elseif( \in_array( $pIndexType, array_keys( $gBitSystem->mPackages ) ) ) { $work = strtoupper( $pIndexType ).'_PKG_URL'; if (defined("$work")) { $url = constant( $work ); } /* this was commented out with the note that this can send requests to inactive packages - * that should only happen if the admin chooses to point to an inactive pacakge. * commenting this out however completely breaks the custom uri home page feature, so its * turned back on and caviate admin - if the problem is more severe than it seems then * get in touch on irc and we'll work out a better solution than commenting things on and off -wjames5 */ } elseif( !empty( $pIndexType ) ) { $url = BIT_ROOT_URL.$pIndexType; } // if no special case was matched above, default to users' my page if( empty( $url ) ) { if( $this->isPackageActive( 'wiki' ) ) { $url = WIKI_PKG_URL; } elseif( !$gBitUser->isRegistered() ) { $url = USERS_PKG_URL . 'signin.php'; } else { $url = USERS_PKG_URL . 'my.php'; } } if( strpos( $url, 'http://' ) === false ) { $url = preg_replace( "#//#", "/", $url ); } return $url; } // === setOnloadScript /** * add javascript to the attribute * * @param string $pJavascript javascript to be added * @return void * @access public */ public function setOnloadScript( $pJavascript ) { array_push( $this->mOnload, $pJavascript ); } // === setOnunloadScript /** * add javascript to the attribute * * @param string $pJavascript javascript to be added * @return void * @access public */ public function setOnunloadScript( $pJavascript ) { array_push( $this->mOnunload, $pJavascript ); } // === getBrowserTitle /** * get the title of the browser * * @return string title string * @access public */ public function getBrowserTitle() { global $gPageTitle; return $gPageTitle; } // === setBrowserTitle /** * set the title of the browser * * @param string $ pTitle title to be used * @return void * @access public */ public function setBrowserTitle( $pTitle ) { global $gBitSmarty, $gPageTitle; $gPageTitle = $pTitle; $gBitSmarty->assign( 'browserTitle', $pTitle ); $gBitSmarty->assign( 'gPageTitle', $pTitle ); } // === setPagination /** * set the canonical page title * * @param array $pListInfo * @return void */ public function setPagination( $pListInfo ): void { global $gBitSmarty; if( !empty( $pListInfo['total_pages'] ) && !empty( $pListInfo['page_records'] ) ) { $relTags = ""; $baseUrl = $pListInfo['url'] ?? $_SERVER['SCRIPT_URL']; if( !empty( $pListInfo['query_string'] ) ) { $pageUrl = $baseUrl.'?'.$pListInfo['query_string']; } else { $queryString = ''; foreach( [ 'parameters', 'ihash' ] as $paramKey ) { if( !empty( $pListInfo[$paramKey] ) ) { foreach( $pListInfo['parameters'] as $param=>$value ) { if( \is_array( $value ) ) { foreach( $value as $v ) { if( !empty( $v ) ) { $queryString .= $param.'[]='.$v.'&'; } } } elseif( !empty( $value ) ) { $queryString .= $param.'='.$value.'&'; } } } } foreach( [ 'max_records', 'sort_mode', 'find' ] as $paramKey ) { if( !empty( $pListInfo[$paramKey] ) ) { if( \is_array( $pListInfo[$paramKey] ) ) { foreach( $pListInfo[$paramKey] as $v ) { $queryString = $paramKey.'[]='.$v.'&'; } } else { $queryString .= $paramKey.'='.$pListInfo[$paramKey].'&'; } } } $pageUrl = $baseUrl.'?'.preg_replace( '/"/', '%22', $queryString ); } $currentPage = BitBase::getParameter( $pListInfo, 'current_page' ); if( $currentPage > 1 ) { $relTags .= ''; } if( BitBase::getParameter( $pListInfo, 'next_offset' ) > 0 ) { $relTags .= ''; } $gBitSmarty->assign( 'relTags', $relTags ); } } // === setCanonicalLink /** * set the canonical page title * * @param string $ pTitle title to be used * @return void * @access public */ public function setCanonicalLink( $pRelativeUrl ) { global $gBitSmarty; $baseUri = defined( 'CANONICAL_BASE_URI' ) ? CANONICAL_BASE_URI : BIT_BASE_URI; $gBitSmarty->assign( 'canonicalLink', $baseUri.$pRelativeUrl ); } /*static*/ public static function genPass() { $vocales = "aeiou"; $consonantes = "bcdfghjklmnpqrstvwxyz123456789"; $r = ''; for( $i = 0; $i < 8; $i++ ) { if( $i % 2 ) { $r .= $vocales[rand( 0, strlen( $vocales ) - 1 )]; } else { $r .= $consonantes[rand( 0, strlen( $consonantes ) - 1 )]; } } return $r; } // === lookupMimeType /** * given an extension, return the mime type * * @param string $pExtension is the extension of the file or the complete file name * @return string mime type of entry and populates $this->mMimeTypes with existing mime types * @access public */ public function lookupMimeType( $pExtension ) { $this->loadMimeTypes(); if( preg_match( "#\.[0-9a-z]+$#i", $pExtension )) { $pExtension = substr( $pExtension, strrpos( $pExtension, '.' ) + 1 ); } // rfc1341 - mime types are case insensitive. $pExtension = strtolower( $pExtension ); return !empty( $this->mMimeTypes[$pExtension] ) ? $this->mMimeTypes[$pExtension] : 'application/binary'; } // === loadMimeTypes /** * given an extension, return the mime type * * @return void mime type of entry and populates $this->mMimeTypes with existing mime types * @access public */ public function loadMimeTypes() { if( empty( $this->mMimeTypes )) { // use bitweavers mime.types file to ensure everyone has our set unless user forces his own. $mimeFile = defined( 'MIME_TYPES' ) ? MIME_TYPES : KERNEL_PKG_ADMIN_PATH.'mime.types'; $this->mMimeTypes = []; if( $fp = fopen( $mimeFile,"r" ) ) { while( false != ( $line = fgets( $fp, 4096 ) ) ) { if( !preg_match( "/^\s*(?!#)\s*(\S+)\s+(?=\S)(.+)/", $line, $match ) ) { continue; } $tmp = preg_split( "/\s/",trim( $match[2] ) ); foreach( $tmp as $type ) { $this->mMimeTypes[strtolower( $type )] = $match[1]; } } fclose( $fp ); } } } // === verifyFileExtension /** * given a file and optionally desired name, return the correctly extensioned file and mime type * * @param string $pFile is the actual file to inspect for magic numbers to determine type * @param string $pFileName is the desired name the file. This is optional in the even the pFile is non-extensioned, as is the case with file uploads * @return array corrected file name and mime type * @access public */ public function verifyFileExtension( $pFile, $pFileName=null ) { $this->loadMimeTypes(); if( empty( $pFileName ) ) { $pFileName = basename( $pFile ); $ret = $pFile; } else { $ret = $pFileName; } $verifyMime = $this->verifyMimeType( $pFile ); if( strrpos( $pFileName, '.' ) ) { $extension = substr( $pFileName, strrpos( $pFileName, '.' ) + 1 ); $lookupMime = $this->lookupMimeType( $extension ); } else { // extensionless file uploaded, get ready to add an extension $lookupMime = ''; $pFileName .= '.'; } // if $verifyMime turns out to be 'octet-stream' and the lookupMimeType is a video file, we'll allow the video filetype and extenstion // if we don't do this, most uploaded videos are changed to have a '.bin' extenstion which is very annoying. if( $verifyMime == 'application/octet-stream' && preg_match( "/^video/", $lookupMime )) { $verifyMime = $lookupMime; } elseif( $lookupMime != $verifyMime ) { if( $verifyExt = $this->getMimeExtension( $verifyMime ) ) { $ret = substr( $pFileName, 0, strrpos( $pFileName, '.' ) + 1 ).$verifyExt; } } // if we still don't have an extension, we'll simply append a 'bin' if( preg_match( "/\.$/", $pFileName )) { $pFileName .= "bin"; } return [ $ret, $verifyMime ]; } // === verifyMimeType /** * given a file, return the mime type * * @param string $pFile is the extension of the file or the complete file name * @return string mime type of entry and populates $this->mMimeTypes with existing mime types * @access public */ public function verifyMimeType( $pFile ) { $mime = null; if( file_exists( $pFile ) && filesize( $pFile ) ) { if( function_exists( 'finfo_open' ) ) { $finfo = KernelTools::is_windows() && defined( 'PHP_MAGIC_PATH' ) && is_readable( PHP_MAGIC_PATH ) ? finfo_open( FILEINFO_MIME, PHP_MAGIC_PATH ) : finfo_open( FILEINFO_MIME ); $mime = finfo_file( $finfo, $pFile ); } else { if( KernelTools::function_enabled( "escapeshellarg" ) && KernelTools::function_enabled( "exec" )) { $mime = exec( trim( 'file -bi ' . escapeshellarg( $pFile ))); } } if( empty( $mime ) ) { $mime = $this->lookupMimeType( substr( $pFile, strrpos( $pFile, '.' ) + 1 ) ); } if( $len = strpos( $mime, ';' )) { $mime = substr( $mime, 0, $len ); } } return $mime; } public function getMimeExtension( $pMimeType ) { $ret = ''; if( $pMimeType == 'image/jpeg' ) { $ret = 'jpg'; // jpeg has three options, .jpg is the most common } else { $this->loadMimeTypes(); if( !($ret = array_search( $pMimeType, $this->mMimeTypes )) ) { // not present in mMimeTypes, here are some custom types switch( $pMimeType ) { case 'image/bmp': $ret = 'bmp'; break; case 'image/pipeg': $ret = 'jfif'; break; case 'image/vnd.adobe.photoshop': $ret = 'psd'; break; case 'image/x-cmx': $ret = 'cmx'; break; case 'image/x-jps': $ret = 'jps'; break; case 'image/x-freehand': $ret = 'fh'; break; } } } return $ret; } /** * * Prepend $pPath to the include path * \static */ public static function prependIncludePath( $pPath ) { $include_path = get_include_path(); $include_path = !empty($include_path) ? $pPath . PATH_SEPARATOR . $include_path : $pPath; return set_include_path( $include_path ); } /** * * Append $pPath to the include path * \static */ public function appendIncludePath( $pPath ) { $include_path = get_include_path(); if( $include_path ) { $include_path .= PATH_SEPARATOR . $pPath; } else { $include_path = $pPath; } return set_include_path( $include_path ); } private function defineTempDir() { // allow for overridden TEMP_PKG_PATH if( !defined( 'TEMP_PKG_PATH' ) ) { $tempDir = $this->getConfig( 'site_temp_dir', self::getDefaultTempDir() ); if( strrpos( $tempDir, '/' ) + 1 != strlen( $tempDir ) ) { $tempDir .= '/'; } define( 'TEMP_PKG_PATH', $tempDir ); define( 'TEMP_PKG_URL', BIT_ROOT_URL.'temp/' ); if( !file_exists( $tempDir ) ) { mkdir( $tempDir, 0777, true ); } } } public function getDefaultTempDir() { return sys_get_temp_dir().'/bitweaver/'.$_SERVER['SERVER_NAME'].'/'; } /* Check that everything is set up properly * \static */ public function checkEnvironment() { static $checked, $gTempDirs; if( $checked ) { return; } if( empty( $this->mConfig ) ) { $this->loadConfig(); } $errors = ''; $docroot = BIT_ROOT_PATH; $serverSoftware = $_SERVER['SERVER_SOFTWARE'] ?? ''; if( stripos( $serverSoftware, 'nginx' ) !== false ) { $this->setConfig( 'site_server_type', 'nginx' ); } elseif( stripos( $serverSoftware, 'apache' ) !== false ) { // Check if mod_xsendfile is actually loaded if( function_exists( 'apache_get_modules' ) && \in_array( 'mod_xsendfile', apache_get_modules() )) { $this->setConfig( 'site_server_type', 'apache_xsendfile' ); } else { $this->setConfig( 'site_server_type', 'apache' ); } } else { $this->setConfig( 'site_server_type', 'other' ); } $cookie_site = 'bit-user-'.strtolower( preg_replace( "/[^a-zA-Z0-9]/", "", $this->getConfig( 'site_title', 'bitweaver' ))); global $gBitDbHost, $gBitDbUser, $gBitDbPassword; $authCheck = "setConfig( 'site_temp_dir', TEMP_PKG_PATH ); $permFiles[] = TEMP_PKG_PATH; } else { $permFiles[] = $this->getConfig( 'site_temp_dir', self::getDefaultTempDir() ); } $permFiles[] = STORAGE_PKG_PATH; foreach( $permFiles as $file ) { $present = false; // Create directories as needed $target = $file; if( preg_match( '/.*\/$/', $target ) ) { // we have a directory if( !is_dir( $target ) ) { mkdir( $target, 02775, true ); } // Check again and report problems if( !is_dir( $target ) ) { if( !KernelTools::is_windows() ) { $errors .= "

The directory $target does not exist. To create the directory, execute a command such as:

\$ mkdir -m 777 $target
"; } else { $errors .= "

The directory $target does not exist. Create the directory $target before proceeding

"; } } else { $present = true; } } elseif( !file_exists( $target ) ) { if( !KernelTools::is_windows() ) { $errors .= "

The file $target does not exist. To create the file, execute a command such as:

						\$ touch $target
						\$ chmod 777 $target
						
"; } else { $errors .= "

The file $target does not exist. Create a blank file $target before proceeding

"; } } else { $present = true; } // chmod( $target, 02775 ); if( $present && ( !KernelTools::bw_is_writeable( $target ))) { if( !KernelTools::is_windows() ) { $errors .= "

$target is not writeable by $wwwuser. To give $wwwuser write permission, execute a command such as:

\$ chmod 777 $target
"; } else { $errors .= "

$target is not writeable by $wwwuser. Check the security of the file $target before proceeding

"; } } //if (!is_dir("$docroot/$dir")) { // $errors .= "The directory '$docroot$dir' does not exist.\n"; //} else if (!bw_is_writeable("$docroot/$dir")) { // $errors .= "The directory '$docroot$dir' is not writeable by $wwwuser.\n"; //} } if( $errors ) { $PHP_CONFIG_FILE_PATH = PHP_CONFIG_FILE_PATH; ob_start(); phpinfo (INFO_MODULES); $httpd_conf = 'httpd.conf'; if( preg_match( '/Server Root<\/b><\/td>([^<]*) bitweaver setup problems

bitweaver is not properly set up:

$errors
"; if( !$this->isLive() ) { if( !KernelTools::is_windows() ) { print "

Proceed to the installer at ".BIT_ROOT_URL."install/install.php after you run the command."; } else { print "

Proceed to the installer at ".BIT_ROOT_URL."install/install.php after you have corrected the identified problems."; } print "
Consult the bitweaver Technical Documentation if you need more help.

"; } exit; } $checked = true; } /** * isLive returns status of the IS_LIVE constant from config/kernel/config_inc.php * * @access public * @return bool true if IS_LIVE is defined and set to a non empty value, else false */ public function isLive() { return (defined( 'IS_LIVE' ) && IS_LIVE) && !$this->isFeatureActive( 'site_hidden' ); } /** * isIndexed returns if that page should be indexed by search engines * * @access public * @return bool true if page should be indexed by search engines */ public function isIndexed() { return (!defined('SITE_NOINDEX') || !constant('SITE_NOINDEX')) && $this->isLive(); } /** * isTracking returns status of the IS_LIVE constant from config/kernel/config_inc.php * * @access public * @return bool true if IS_LIVE is defined and set to a non empty value, else false */ public function isTracking() { global $gBitUser; return $this->getConfig( 'tracking_debug' ) || ($this->isLive() && !$gBitUser->hasPermission( 'p_users_admin' )); } // {{{=========================== Installer related methods ============================== // Keep these methods in BitSystem that we can call verifyInstalledPackages() and other // mthods without the need for an install/ package to be present. /** * registerSchemaTable * * @param string $pPackage * @param string $pTableName * @param string $pDataDict * @param bool $pRequired * @param array $pTableOptions * @return void */ public function registerSchemaTable( string $pPackage, string $pTableName, string $pDataDict, bool $pRequired = false, ?array $pTableOptions = null ): void { $pPackage = strtolower( $pPackage ); // lower case for uniformity if( !empty( $pTableName ) ) { $this->mPackages[$pPackage]['tables'][$pTableName] = $pDataDict; if( !empty( $pTableOptions ) ) { $this->mPackages[$pPackage]['tables']['options'][$pTableName] = $pTableOptions; } } } /** * registerSchemaConstraints * * @param string $pPackage * @param string $pTableName * @param array $pConstraints * @access public * @return void */ public function registerSchemaConstraints( string $pPackage, string $pTableName, array $pConstraints ): void { $pPackage = strtolower( $pPackage); if( !empty( $pTableName ) ) { $this->mPackages[$pPackage]['constraints'][$pTableName] = $pConstraints; } } /** * registerUserPermissions * * @param string $pPackagedir * @param array $pUserpermissions * @return void */ public function registerUserPermissions( string $pPackagedir, array $pUserpermissions ): void { foreach( $pUserpermissions as $perm ) { $this->mPermHash[$perm[0]] = $perm; $this->mPermHash[$perm[0]]['sql'] = "INSERT INTO `".BIT_DB_PREFIX."users_permissions` (`perm_name`, `perm_desc`, `perm_level`, `package`) VALUES ('$perm[0]', '$perm[1]', '$perm[2]', '$perm[3]')"; $this->registerSchemaDefault( $pPackagedir, "INSERT INTO `".BIT_DB_PREFIX."users_permissions` (`perm_name`, `perm_desc`, `perm_level`, `package`) VALUES ('$perm[0]', '$perm[1]', '$perm[2]', '$perm[3]')", ); } } /** * registerConfig * * @param string $pPackagedir * @param array|string $pPreferences * @access public * @return void */ public function registerConfig( $pPackagedir, $pPreferences ) { foreach( $pPreferences as $pref ) { $this->registerSchemaDefault( $pPackagedir, "INSERT INTO `".BIT_DB_PREFIX."kernel_config`(`package`,`config_name`,`config_value`) VALUES ('$pref[0]', '$pref[1]','$pref[2]')", ); } } /** * registerPreferences * * @param string $pPackagedir * @param array $pPreferences * @access public * @return void */ public function registerPreferences( $pPackagedir, $pPreferences ) { foreach( $pPreferences as $prefHash ) { $this->mPackages[$pPackagedir]['default_prefs'][] = [ 'package' => $prefHash[0], 'name' => $prefHash[1], 'value' => $prefHash[2] ]; } } /** * registerModules * * @param array $pModuleHash * @access public * @return void */ public function registerModules( $pModuleHash ) { $this->mInstallModules = array_merge( $this->mInstallModules, $pModuleHash ); } /** * registerContentObjects * * @param string $pPackageName the package name * @param array $pClassesHash [$className => $pathToClassFile] * @access public */ public function registerContentObjects( $pPackageName, $pClassesHash ) { $this->mContentClasses[$pPackageName] = $pClassesHash; } /** * registerPackageInfo * * @param string $pPackage * @param array $pInfoHash * @access public * @return void */ public function registerPackageInfo( $pPackage, $pInfoHash ) { $pPackage = strtolower( $pPackage ); // lower case for uniformity $this->mPackages[$pPackage]['info'] = !empty( $this->mPackages[$pPackage]['info'] ) ? array_merge( $this->mPackages[$pPackage]['info'], $pInfoHash ) : $pInfoHash; $this->mPackages[$pPackage]['info']['version'] = $this->getVersion( $pPackage ); $upgrade = $this->getLatestUpgradeVersion( $pPackage ); if( !empty( $upgrade ) && version_compare( $upgrade, $this->getVersion( $pPackage ), '>' )) { if( $this->mPackages[$pPackage]['installed'] ) { $this->mPackages[$pPackage]['info']['upgrade'] = $upgrade; } else { $this->mPackages[$pPackage]['info']['version'] = $upgrade; } } } /** * registerSchemaSequences * * @param string $pPackage * @param array $pSeqHash * @access public * @return void */ public function registerSchemaSequences( $pPackage, $pSeqHash ) { $pPackage = strtolower( $pPackage ); // lower case for uniformity $this->mPackages[$pPackage]['sequences'] = $pSeqHash; } /** * registerSchemaIndexes * * @param string $pPackage * @param array $pIndexHash * @access public * @return void */ public function registerSchemaIndexes( $pPackage, $pIndexHash ) { $pPackage = strtolower( $pPackage ); // lower case for uniformity $this->mPackages[$pPackage]['indexes'] = $pIndexHash; } /** * registerSchemaDefault * * @param string $pPackage * @param string|array $pMixedDefaultSql * @return void */ public function registerSchemaDefault( string $pPackage, string|array $pMixedDefaultSql ): void { $pPackage = strtolower( $pPackage ); // lower case for uniformity if( empty( $this->mPackages[$pPackage]['defaults'] ) ) { $this->mPackages[$pPackage]['defaults'] = []; } if( \is_array( $pMixedDefaultSql ) ) { foreach( $pMixedDefaultSql as $def ) { $this->mPackages[$pPackage]['defaults'][] = $def; } } elseif( is_string( $pMixedDefaultSql ) ) { array_push( $this->mPackages[$pPackage]['defaults'], $pMixedDefaultSql ); } } /** * storeVersion will store the version number of a given package * * @param string $pPackage Name of package - if not given, bitweaver_version will be stored * @param string $pVersion Version number * @return bool true on success, false on failure */ public function storeVersion( $pPackage = null, $pVersion = null ): bool { global $gBitSystem; $ret = false; if( !empty( $pVersion ) && $this->validateVersion( $pVersion )) { if( empty( $pPackage )) { $gBitSystem->storeConfig( "bitweaver_version", $pVersion, 'kernel' ); $ret = true; } elseif( !empty( $gBitSystem->mPackages[$pPackage] )) { $gBitSystem->storeConfig( "package_".$pPackage."_version", $pVersion, $pPackage ); $ret = true; } } return $ret; } /** * getVersion will fetch the version number of a given package * * @param string $pPackage Name of package - if not given, bitweaver_version will be stored * @param string $pDefault Version number * @return string version number on success */ public function getVersion( ?string $pPackage = null, $pDefault = BITWEAVER_VERSION ) { global $gBitSystem; $config = empty( $pPackage ) ? 'bitweaver_version' : "package_".$pPackage."_version"; return $gBitSystem->getConfig( $config, $pDefault ); } /** * getLatestUpgradeVersion will fetch the greatest upgrade number for a given package * * @param string $pPackage package we want to fetch the latest version number for * @return string greatest upgrade number for a given package */ public function getLatestUpgradeVersion( string $pPackage ) { $ret = '0.0.0'; if( !empty( $pPackage )) { $dir = constant( strtoupper( $pPackage )."_PKG_PATH" )."admin/upgrades/"; if( is_dir( $dir ) && $upDir = opendir( $dir )) { while( false !== ( $file = readdir( $upDir ))) { if( is_file( $dir.$file )) { $upVersion = str_replace( ".php", "", $file ); // we only want to update $ret if the version of the file is greater than the previous one if( $this->validateVersion( $upVersion ) && version_compare( $ret, $upVersion, "<" )) { $ret = $upVersion; } } } } } return $ret == '0.0.0' ? false : $ret; } /** * registerPackageVersion Holds the package version * * @param string $pPackage * @param string $pVersion * @return void */ public function registerPackageVersion( string $pPackage, string $pVersion ): void { if( !empty( $pPackage ) && $this->validateVersion( $pVersion )) { $pPackage = strtolower( $pPackage ); $this->mPackages[$pPackage]['version'] = $pVersion; } } /** * validateVersion * * @param string $pVersion * @return bool|int returns 1 if the pattern matches given subject, 0 if it does not, or false on failure */ public function validateVersion( string $pVersion ): bool|int { return preg_match( "/^(\d+\.\d+\.\d+)(-dev|-alpha|-beta|-pl|-RC\d+)?$/", $pVersion ); } /** * registerRequirements * * @param string $pPackage * @param array $pReqHash * @return void */ public function registerRequirements( string $pPackage, array $pReqHash ): void { if( !empty( $pPackage ) && $this->verifyRequirements( $pReqHash )) { $pPackage = strtolower( $pPackage ); $this->mRequirements[$pPackage] = $pReqHash; // and we display the info $this->mPackages[$pPackage]['info']['requirements'] = ''; foreach( $pReqHash as $req => $version ) { //$this->mPackages[$req]['is_requirement'] = true; $this->mPackages[$pPackage]['info']['requirements'] .= ''.ucfirst( $req ).''; $max = !empty( $version['max'] ) ? " - ".$version['max'] : ''; if( $version['min'] != '0.0.0' ) { $this->mPackages[$pPackage]['info']['requirements'] .= " (".$version['min'].$max.")"; } $this->mPackages[$pPackage]['info']['requirements'] .= ", "; } // remove trailing , $this->mPackages[$pPackage]['info']['requirements'] = rtrim( trim( $this->mPackages[$pPackage]['info']['requirements'] ), "," ); } } /** * verifyRequirements * * @param array $pReqHash * @access public * @return bool true on success, false on failure */ public function verifyRequirements( &$pReqHash ) { if( !empty( $pReqHash ) && \is_array( $pReqHash )) { foreach( $pReqHash as $pkg => $versions ) { if( empty( $versions['min'] )) { $this->mErrors['version_min'] = "You have to provide a minimum version number for the $pkg requirement. If you just want the required package to be present, please use 0.0.0 as minimum version."; } elseif( !$this->validateVersion( $versions['min'] )) { $this->mErrors['version_min'] = "Please make sure you use a valid minimum version number for the $pkg requirement."; } elseif( !empty( $versions['max'] )) { if( !$this->validateVersion( $versions['max'] )) { $this->mErrors['version_max'] = "Please make sure you use a valid maximum version number for the $pkg requirement."; } elseif( version_compare( $versions['min'], $versions['max'], '>=' )) { $this->mErrors['version_max'] = "Please make sure the maximum version is greater than the minimum version for the $pkg requirement."; } } } } else { $this->mErrors['deps'] = "If you want to register requirements, please do so with a valid requirement hash."; } // since this should only show up when devs are working, we'll simply display the output: if( !empty( $this->mErrors )) { bt(); } return count( $this->mErrors ) == 0; } /** * getRequirements * * @param string $pPackage * @access public * @return array of package requirements */ public function getRequirements( $pPackage ) { $ret = []; if( !empty( $pPackage )) { $pPackage = strtolower( $pPackage ); if( !empty( $this->mRequirements[$pPackage] )) { return $this->mRequirements[$pPackage]; } } return $ret; } /** * calculateRequirements will calculate all requirements and return a hash of the results * * @param boolean $pInstallVersion Use the actual installed version instead of the version that will be in bitweaver after the upgrade * @access public * @return array */ public function calculateRequirements( $pInstallVersion = false ) { $ret = []; // first we gather all version information. foreach( array_keys( $this->mPackages ) as $package ) { if( $this->isPackageInstalled( $package )) { // get the latest upgrade version, since this is the version the package will be at after install if( $pInstallVersion || !$version = $this->getLatestUpgradeVersion( $package )) { $version = $this->getVersion( $package ); } $installed[$package] = $version; if( $this->isPackageActive( $package )) { if( $deps = $this->getRequirements( $package )) { $requirements[$package] = $deps; } $inactive[$package] = false; } else { $inactive[$package] = true; } } } if( !empty( $requirements )) { foreach( $requirements as $package => $deps ) { foreach( $deps as $depPackage => $depVersion ) { $hash = [ 'package' => $package, 'package_version' => $installed[$package], 'requires' => $depPackage, 'required_version' => $depVersion, ]; if( !empty( $installed[$depPackage] )) { $hash['version']['available'] = $installed[$depPackage]; } if( empty( $installed[$depPackage] )) { $hash['result'] = 'missing'; } elseif( version_compare( $depVersion['min'], $installed[$depPackage], '>' )) { $hash['result'] = 'min_dep'; } elseif( !empty( $depVersion['max'] ) && version_compare( $depVersion['max'], $installed[$depPackage], '<' )) { $hash['result'] = 'max_dep'; } elseif( isset( $inactive[$depPackage] ) && $inactive[$depPackage] ) { $hash['result'] = 'inactive'; } else { $hash['result'] = 'ok'; } $ret[] = $hash; } } } return $ret; } /** * drawRequirementsGraph Will draw a requirement graph if PEAR::Image_GraphViz is installed * * @param boolean $pInstallVersion Use the actual installed version instead of the version that will be in bitweaver after the upgrade * @param string $pFormat dot output format * @param string $pCommand dot or neato * @access public * @return string|bool true on success, false on failure */ public function drawRequirementsGraph( $pInstallVersion = false, $pFormat = 'png', $pCommand = 'dot' ) { global $gBitSmarty, $gBitThemes; // only do this if we can load PEAR GraphViz interface if( @include_once UTIL_PKG_INCLUDE_PATH.'pear/Image/GraphViz.php' ) { ksort( $this->mPackages ); $deps = $this->calculateRequirements( $pInstallVersion ); $delKeys = $matches = []; // crazy manipulation of hash to remove duplicate version matches. // we do this that we can use double headed arrows in the graph below. foreach( $deps as $key => $req ) { foreach( $deps as $k => $d ) { if( $req['requires'] == $d['package'] && $req['package'] == $d['requires'] && $req['result'] == 'ok' && $d['result'] == 'ok' ) { $deps[$key]['dir'] = 'both'; $matches[$key] = $k; } } } // get duplicates foreach( $matches as $key => $match ) { unset( $delKeys[$match] ); $delKeys[$key] = $match; } // remove dupes from hash foreach( $delKeys as $key ) { unset( $deps[$key] ); } // start drawing stuff $graph = new \Image_GraphViz( true, $gBitThemes->getGraphvizGraphAttributes(), 'Requirements', true ); $fromattributes = $toattributes = $gBitThemes->getGraphvizNodeAttributes(); foreach( $deps as $node ) { //$fromNode = ucfirst( $node['package'] )."\n".$node['package_version']; //$toNode = ucfirst( $node['requires'] )."\n".$node['required_version']['min']; $fromNode = ucfirst( $node['package'] ); $toNode = ucfirst( $node['requires'] ); switch( $node['result'] ) { case 'max_dep': $edgecolor = 'chocolate3'; $label = 'Maximum version\nexceeded'; $toNode .= "\n".$node['required_version']['min']." - ".$node['required_version']['max']; $toattributes['fillcolor'] = 'khaki'; break; case 'min_dep': $edgecolor = 'crimson'; $label = 'Minimum version\nnot met'; $toNode .= "\n".$node['required_version']['min']; if( !empty( $node['required_version']['max'] )) { $toNode .= " - ".$node['required_version']['max']; } $toattributes['fillcolor'] = 'pink'; break; case 'missing': $edgecolor = 'crimson'; $label = 'Not installed\nor activated'; $toNode .= "\n".$node['required_version']['min']; if( !empty( $node['required_version']['max'] )) { $toNode .= " - ".$node['required_version']['max']; } $toattributes['fillcolor'] = 'pink'; break; default: $edgecolor = ''; $label = ''; $toattributes['fillcolor'] = 'white'; break; } $fromattributes['URL'] = "https://www.bitweaver.org/wiki/".ucfirst( $node['package'] )."Package"; $graph->addNode( $fromNode, $fromattributes ); $toattributes['URL'] = "https://www.bitweaver.org/wiki/".ucfirst( $node['requires'] )."Package"; $graph->addNode( $toNode, $toattributes ); $graph->addEdge( [ $fromNode => $toNode ], $gBitThemes->getGraphvizEdgeAttributes( [ 'dir' => ( !empty( $node['dir'] ) ? $node['dir'] : '' ), 'color' => $edgecolor, 'fontcolor' => $edgecolor, 'label' => $label, ]), ); } if( preg_match( "#(png|gif|jpe?g|bmp|svg|tif)#i", $pFormat )) { $graph->image( $pFormat, $pCommand ); } else { return $graph->fetch( $pFormat, $pCommand ); } } return false; } /** * verifyInstalledPackages scan all available packages * * @param string $ pScanFile file to be looked for * @return array * @access public */ public function verifyInstalledPackages( $pSelect='installed' ) { global $gBitDbType; #load in any admin/schema_inc.php files that exist for each package $this->scanPackages( 'admin/schema_inc.php', true, $pSelect, false ); $ret = []; if( $this->isDatabaseValid() ) { if( strlen( BIT_DB_PREFIX ) > 0 ) { $lastQuote = strrpos( BIT_DB_PREFIX, '`' ); if( $lastQuote != false ) { $lastQuote++; } $prefix = substr( BIT_DB_PREFIX, $lastQuote ); } else { $prefix = ''; } $showTables = $prefix ? $prefix.'%' : false; $unusedTables = []; if( $dbTables = $this->mDb->MetaTables( 'TABLES', false, $showTables ) ) { // make a copy that we can keep track of what tables have been used $unusedTables = $dbTables; foreach( array_keys( $this->mPackages ) as $package ) { // Default to true, &= will false out $this->mPackages[$package]['installed'] = true; if( !empty( $this->mPackages[$package]['tables'] ) ) { $this->mPackages[$package]['db_tables_found'] = true; foreach( array_keys( $this->mPackages[$package]['tables'] ) as $table ) { // painful hardcoded exception for bitcommerce $fullTable = $package == 'bitcommerce' ? $table : $prefix.$table; $tablePresent = \in_array( $fullTable, $dbTables ); if( $tablePresent ) { $ret['present'][$package][] = $table; } else { $ret['missing'][$package][] = $table; // This is a crude but highly effective means of blurting out a very bad situation when an installed package is missing a table if( !$this->isLive() && $this->isPackageActive( $package ) ) { // This needs hiding during install so disabled for now // vd( "Table Missing => $package : $table" ); } } // lets also return the tables that are not in use by bitweaver // this is useful when we want to remove old tables or upgrade tables if(( $key = array_search( $fullTable, $dbTables )) !== false ) { unset( $unusedTables[$key] ); } $this->mPackages[$package]['installed'] &= $tablePresent; $this->mPackages[$package]['db_tables_found'] &= $tablePresent; } } else { $this->mPackages[$package]['db_tables_found'] = false; if( empty( $this->mPackages[$package]['required'] ) ) { $configVal = $this->getConfig( 'package_'.strtolower( $package ) ); if( !$configVal && defined( 'BIT_INSTALL' ) ) { // getConfig() is a no-op during install; query DB directly $configVal = $this->mDb->getOne( "SELECT `config_value` FROM `".BIT_DB_PREFIX."kernel_config` WHERE `config_name`=?", ['package_'.strtolower( $package )] ); } if( !$configVal ) { $this->mPackages[$package]['installed'] = false; } } } $this->mPackages[$package]['active_switch'] = $this->getConfig( 'package_'.strtolower( $package ) ); // During install getConfig() always returns null (BIT_INSTALL blocks config loading), // so skip all storeConfig calls — the installer manages package status itself if( !defined( 'BIT_INSTALL' ) ) { if( !empty( $this->mPackages[$package]['required'] ) && $this->mPackages[$package]['active_switch'] != 'y' ) { // we have a disabled required package. turn it back on! $this->storeConfig( 'package_' . $package, 'y', $package ); $this->mPackages[$package]['active_switch'] = $this->getConfig( 'package_' . $package ); } elseif( !empty( $this->mPackages[$package]['required'] ) && $this->mPackages[$package]['installed'] && $this->getConfig( 'package_'.$package ) != 'i' && $this->getConfig( 'package_'.$package ) != 'y' ) { $this->storeConfig( 'package_' . $package, 'i', $package ); } elseif( !empty( $this->mPackages[$package]['installed'] ) && !$this->isFeatureActive( 'package_'.strtolower( $package ) ) ) { // set package to i if it is installed but not isFeatureActive (common when re-installing packages) $this->storeConfig( 'package_' . $package, 'i', $package ); if( $version = $this->getLatestUpgradeVersion( $package ) ) { $this->storeVersion( $package, $version ); $this->registerPackageVersion( $package, $version ); $this->mPackages[$package]['info']['version'] = $version; unset( $this->mPackages[$package]['info']['upgrade'] ); } } } } } $ret['unused'] = $unusedTables; } return $ret; } // }}} // {{{=========================== Date and time methods ============================== /** * Retrieve a current UTC timestamp * Simple map to BitDate object allowing tidy display elsewhere */ public function getUTCTime() { return $this->mServerTimestamp->getUTCTime(); } /** * Retrieve a current UTC ISO timestamp * Simple map to BitDate object allowing tidy display elsewhere */ public function getUTCTimestamp() { return $this->mServerTimestamp->getUTCTimestamp(); } /** * Retrieves the user's preferred offset for displaying dates. */ public function get_display_offset( $pUser = false ) { return $this->mServerTimestamp->get_display_offset( $pUser ); } /** * Retrieves the user's preferred long date format for displaying dates. */ public function get_long_date_format() { static $site_long_date_format = false; if( !$site_long_date_format ) { $site_long_date_format = $this->getConfig( 'site_long_date_format', '%A, %B %d, %Y' ); } return $site_long_date_format; } /** * Retrieves the user's preferred short date format for displaying dates. */ public function get_short_date_format() { static $site_short_date_format = false; if( !$site_short_date_format ) { $site_short_date_format = $this->getConfig( 'site_short_date_format', '%d %b %Y' ); } return $site_short_date_format; } /** * Retrieves the user's preferred long time format for displaying dates. */ public function get_long_time_format() { static $site_long_time_format = false; if( !$site_long_time_format ) { $site_long_time_format = $this->getConfig( 'site_long_time_format', '%H:%M:%S %Z' ); } return $site_long_time_format; } /** * Retrieves the user's preferred short time format for displaying dates. */ public function get_short_time_format() { static $site_short_time_format = false; if( !$site_short_time_format ) { $site_short_time_format = $this->getConfig( 'site_short_time_format', '%H:%M %Z' ); } return $site_short_time_format; } /** * Retrieves the user's preferred long date/time format for displaying dates. */ public function get_long_datetime_format() { static $long_datetime_format = false; if( !$long_datetime_format ) { $long_datetime_format = $this->getConfig( 'site_long_datetime_format', '%A %d of %B, %Y (%H:%M:%S %Z)' ); } return $long_datetime_format; } /** * Retrieves the user's preferred short date/time format for displaying dates. */ public function get_short_datetime_format() { static $short_datetime_format = false; if( !$short_datetime_format ) { $short_datetime_format = $this->getConfig( 'site_short_datetime_format', '%d %b %Y (%H:%M %Z)' ); } return $short_datetime_format; } /* * Only used in rang_lib.php which needs tidying up to use smarty templates */ public function get_long_datetime( $pTimestamp, $pUser = false ) { return $this->mServerTimestamp->strftime( $this->get_long_datetime_format(), $pTimestamp, $pUser ); } // }}} /** * getBitVersion will fetch the version of bitweaver as set in kernel/config_defaults_inc.php * * @param boolean $pIncludeLevel Return bitweaver version including BIT_LEVEL * @return string bitweaver version set in kernel/config_defaults_inc.php */ public function getBitVersion( $pIncludeLevel = true ) { $ret = BIT_MAJOR_VERSION.".".BIT_MINOR_VERSION.".".BIT_SUB_VERSION; if( $pIncludeLevel && defined( BIT_LEVEL ) && BIT_LEVEL != '' ) { $ret .= '-'.BIT_LEVEL; } return $ret; } /** * checkBitVersion Check for new version of bitweaver * * @return array an array with information on bitweaver version */ public function checkBitVersion() { $local = $this->getBitVersion( false ); $ret['local'] = $local; $ret['compare'] = 0; $ret['release'] = 0; $error['number'] = 0; $error['string'] = $data = ''; // https://www.bitweaver.org/bitversion.txt is no longer available // cache the bitversion.txt file locally and update only once a day // if you don't have a connection to bitweaver.org, you can set a cronjob to 'touch' this file once a day to avoid waiting for a timeout. /* if( !is_file( TEMP_PKG_PATH.'bitversion.txt' ) || ( time() - filemtime( TEMP_PKG_PATH.'bitversion.txt' )) > 86400 ) { if( $h = fopen( TEMP_PKG_PATH.'bitversion.txt', 'w' )) { $data = KernelTools::bit_http_request( 'https://www.bitweaver.org/bitversion.txt' ); if( !preg_match( "/not found/i", $data )) { fwrite( $h, $data ); fclose( $h ); } } } */ if( is_readable( TEMP_PKG_PATH.'bitversion.txt' ) ) { $h = fopen( TEMP_PKG_PATH.'bitversion.txt', 'r' ); if( isset( $h ) ) { $data = fread( $h, 1024 ); fclose( $h ); } // nuke all lines that don't just contain a version number $lines = explode( "\n", $data ); foreach( $lines as $line ) { if( preg_match( "/^\d+\.\d+\.\d+$/", $line ) ) { $versions[] = $line; } } if( !empty( $data ) && !empty( $versions ) && preg_match( "/\d+\.\d+\.\d+/", $versions[0] ) ) { sort( $versions ); foreach( $versions as $version ) { if( preg_match( "/^".BIT_MAJOR_VERSION."\./", $version ) ) { $ret['compare'] = version_compare( $local, $version ); $ret['upgrade'] = $version; $ret['page'] = preg_replace( "/\.\d+$/", "", $version ); } } // check if there have been any major releases $release = explode( '.', array_pop( $versions ) ); if( $release[0] > BIT_MAJOR_VERSION ) { $ret['release'] = implode( '.', $release ); $ret['page'] = $release[0].'.'.$release[1]; } elseif( $release[0] < BIT_MAJOR_VERSION ) { $ret['compare'] = version_compare( $local, $version ); $ret['upgrade'] = $version; } } else { $error['number'] = 1; $error['string'] = KernelTools::tra( 'No version information available. Check your connection to bitweaver.org' ); } } // append any release level $ret['local'] .= ' '.BIT_LEVEL; $ret['error'] = $error; return $ret; } // should be moved somewhere else. unbreaking things for now - 25-JUN-2005 - spiderr // \TODO remove html hardcoded in diff2 public function diff2( $page1, $page2 ) { $page1 = mb_split( "\n", $page1 ); $page2 = mb_split( "\n", $page2 ); $z = new \WikiDiff( $page1, $page2 ); if( $z->isEmpty() ) { $html = '

['.KernelTools::tra("Versions are identical").']

'; } else { //$fmt = new WikiDiffFormatter; $fmt = new \WikiUnifiedDiffFormatter; $html = $fmt->format( $z, $page1 ); } return $html; } /** * getIncludeFiles will get a set of available files with a given filename * * @param array $pPhpFile name of php file * @param array $pTplFile name of tpl file * @return array of includable files */ public function getIncludeFiles( $pPhpFile = null, $pTplFile = null ) { $ret = []; global $gBitSystem; foreach( $gBitSystem->mPackages as $package ) { if( $gBitSystem->isPackageActive( $package['name'] )) { if( !empty( $pPhpFile )) { $php_file = constant( strtoupper( $package['name'] ).'_PKG_INCLUDE_PATH' ).$pPhpFile; if( is_file( $php_file )) { $ret[$package['name']]['php'] = $php_file; } } if( !empty( $pTplFile )) { $tpl_file = $package['path'].'templates/'.$pTplFile; if( is_readable( $tpl_file )) { $ret[$package['name']]['tpl'] = 'bitpackage:'.$package['name'].'/'.$pTplFile; } } } } return $ret; } } /* Function for sorting AppMenu by menu_position */ function bit_system_menu_sort( $a, $b ) { $pa = empty( $a['menu_position'] ) ? 0 : $a['menu_position']; $pb = empty( $b['menu_position'] ) ? 0 : $b['menu_position']; if( $pa == 0 && $pb == 0 ) { return strcmp( $b['menu_title'], $a['menu_title'] ); } return $pa - $pb; }