0) { $iDomainId = $aSiteInfo['DomainId']; } $bHasAccess = false; if (!HasLicenseForFeature("DisabledMessageServer")) { $bHasAccess = true; } // Message Server Modules $aModules = array(); $aModules[] = array('object' => new CChannelModule($aSiteInfo), 'edit' => true); $aModules[] = array('object' => new CRssModule($aSiteInfo), 'edit' => false); $aModules[] = array('object' => new CTwitterModule($aSiteInfo), 'edit' => $bHasAccess); $aModules[] = array('object' => new CFacebookModule($aSiteInfo), 'edit' => $bHasAccess); $aModules[] = array('object' => new CMobileWebsiteModule($aSiteInfo), 'edit' => false); $aModules[] = array('object' => new CEmailModule($aSiteInfo), 'edit' => false); $aModules[] = array('object' => new CSmsModule($aSiteInfo), 'edit' => false); $aModules[] = array('object' => new CArchiveModule($aSiteInfo), 'edit' => false); $aModules[] = array('object' => new CIntranetModule($aSiteInfo), 'edit' => false); if (HasLicenseForFeature('Output-Blog', $iDomainId)) { $aModules[] = array('object' => new CBlogModule($aSiteInfo), 'edit' => false); } if (GetConfigVar("EnableBannerModule", "General")) { $aModules[] = array('object' => new CBannerModule($aSiteInfo), 'edit' => false); } // only admin sees all modules if Domains are enabled if (GetSessionValue($g_SessionVars["UserType"]) == CUserTable::USERTYPE_ADMIN) { $aModules[1]['edit'] = true; // Rss $aModules[4]['edit'] = true; // MobileWebsite $aModules[5]['edit'] = $bHasAccess; // Email $aModules[6]['edit'] = $bHasAccess; // Sms $aModules[7]['edit'] = true; // Archive $aModules[8]['edit'] = true; // Intranet $iModNum = 9; if (HasLicenseForFeature('Output-Blog', $iDomainId)) { $aModules[$iModNum]['edit'] = $bHasAccess; // Blog $iModNum++; } if (GetConfigVar("EnableBannerModule", "General")) { $aModules[$iModNum]['edit'] = true; // Banners } } return $aModules; } function SetDefaultCfgTables($iSiteId, $iDomainId) { WriteToLog("ConvertTable :: SetDefaultCfgTables( SiteId $iSiteId )"); global $g_Db; $aRecord = array(); $ArchiveCfgTable = new CArchiveCfgTable($g_Db); if ($ArchiveCfgTable->GetArchiveInfo($aRecord, $iSiteId, $iDomainId) === false) { $ArchiveCfgTable->Insert($iSiteId, '[DataPath]templates\\demo\\archive\\', '[DataPath]templates\\demo\\archive\\message.html', '[DataPath]templates\\demo\\archive\\overview.html', '[InstallationPath]htdocs\\published\\', '[ServerUrl]published/', 1, $iDomainId); } $IntranetCfgTable = new CIntranetCfgTable($g_Db); if ($IntranetCfgTable->GetIntranetInfo($aRecord, $iSiteId, $iDomainId) === false) { $IntranetCfgTable->Insert($iSiteId, '[DataPath]templates\\demo\\intranet\\message.html', '[DataPath]templates\\demo\\intranet\\overview.html', '[InstallationPath]htdocs\\published\\', '[ServerUrl]published/', 1, $iDomainId); } $MobileCfgTable = new CMobileCfgTable($g_Db); if ($MobileCfgTable->GetMobileInfo($aRecord, $iSiteId, $iDomainId) === false) { $MobileCfgTable->Insert($iSiteId, '[DataPath]templates\\demo\\mobile\\', '[InstallationPath]htdocs\\published\\', '[ServerUrl]published/', 1, $iDomainId); } $RssCfgTable = new CRssCfgTable($g_Db); if ($RssCfgTable->GetRssInfo($aRecord, $iSiteId, $iDomainId) === false) { $RssCfgTable->Insert($iSiteId, '[InstallationPath]htdocs\\published\\', '[ServerUrl]published/', 1, 0, 0, $iDomainId); } $EmailCfgTable = new CEmailCfg($g_Db); if ($EmailCfgTable->GetEmailInfo($aRecord, $iSiteId, $iDomainId) === false) { $EmailCfgTable->Insert($iSiteId, '[InstallationPath]htdocs\\published\\', '[ServerUrl]published/', 0, $iDomainId); } $SmsCfgTable = new CSmsCfg($g_Db); if ($SmsCfgTable->GetSmsInfo($aRecord, $iSiteId, $iDomainId) === false) { $SmsCfgTable->Insert($iSiteId, 0, $iDomainId); } } function SetModuleTables($iSiteId, $iDomainId, $iDefaultDomainId = null, $iDefaultSiteId = 0) { global $g_Db, $g_ModuleDirectory; if (!is_numeric($iDefaultDomainId) || $iDefaultDomainId <= 0) { $iDefaultDomainId = $iDomainId; } // the default records for the current domain $aRecord = array(); $strAbsPostfix = ''; $strHttpPostfix = ''; $ArchiveCfgTable = new CArchiveCfgTable($g_Db); if ($ArchiveCfgTable->GetArchiveInfo($aRecord, $iDefaultSiteId, $iDefaultDomainId)) { if ($iSiteId > 0) { $strAbsPostfix = $iSiteId . '\\archive\\'; $strHttpPostfix = $iSiteId . '/archive/'; } $ArchiveCfgTable->Insert($iSiteId, $aRecord['XmlStylePath'], $aRecord['MsgTemplatePath'], $aRecord['OverviewTemplatePath'], $aRecord['TargetPath'] . $strAbsPostfix, $aRecord['HttpLocation'] . $strHttpPostfix, $aRecord['Enabled'], $iDomainId); } $IntranetCfgTable = new CIntranetCfgTable($g_Db); if ($IntranetCfgTable->GetIntranetInfo($aRecord, $iDefaultSiteId, $iDefaultDomainId)) { if ($iSiteId > 0) { $strAbsPostfix = $iSiteId . '\\intranet\\'; $strHttpPostfix = $iSiteId . '/intranet/'; } $IntranetCfgTable->Insert($iSiteId, $aRecord['MsgTemplatePath'], $aRecord['OverviewTemplatePath'], $aRecord['TargetPath'] . $strAbsPostfix, $aRecord['HttpLocation'] . $strHttpPostfix, $aRecord['Enabled'], $iDomainId); } $MobileCfgTable = new CMobileCfgTable($g_Db); if ($MobileCfgTable->GetMobileInfo($aRecord, $iDefaultSiteId, $iDefaultDomainId)) { if ($iSiteId > 0) { $strAbsPostfix = $iSiteId . '\\mobile\\'; $strHttpPostfix = $iSiteId . '/mobile/'; } $MobileCfgTable->Insert($iSiteId, $aRecord['Template'], $aRecord['TargetPath'] . $strAbsPostfix, $aRecord['HttpLocation'] . $strHttpPostfix, $aRecord['Enabled'], $iDomainId); } $RssCfgTable = new CRssCfgTable($g_Db); if ($RssCfgTable->GetRssInfo($aRecord, $iDefaultSiteId, $iDefaultDomainId)) { if ($iSiteId > 0) { $strAbsPostfix = $iSiteId . '\\rss\\index.rss'; $strHttpPostfix = $iSiteId . '/rss/index.rss'; } $RssCfgTable->Insert($iSiteId, $aRecord['TargetPath'] . $strAbsPostfix, $aRecord['HttpLocation'] . $strHttpPostfix, $aRecord['Enabled'], $aRecord['SlideImage'], $aRecord['PubliclyAccessible'], $iDomainId); } $EmailCfgTable = new CEmailCfg($g_Db); if ($EmailCfgTable->GetEmailInfo($aRecord, $iDefaultSiteId, $iDefaultDomainId)) { if ($iSiteId > 0) { $strAbsPostfix = $iSiteId . '\\email\\'; $strHttpPostfix = $iSiteId . '/email/'; } $EmailCfgTable->Insert($iSiteId, $aRecord['TargetPath'] . $strAbsPostfix, $aRecord['HttpLocation'] . $strHttpPostfix, $aRecord['Enabled'], $iDomainId); } $SmsCfgTable = new CSmsCfg($g_Db); if ($SmsCfgTable->GetSmsInfo($aRecord, $iDefaultSiteId, $iDefaultDomainId)) { $SmsCfgTable->Insert($iSiteId, $aRecord['Enabled'], $iDomainId, $aRecord['SmsAseAccountId'], $aRecord['SmsSender']); } $FacebookCfgTable = new CFacebookCfg($g_Db); if ($FacebookCfgTable->GetFacebookInfo($aRecord, $iDefaultSiteId, $iDefaultDomainId)) { $FacebookCfgTable->Insert($iSiteId, $aRecord['Session_key'], $aRecord['Session_secret'], $aRecord['Uid'], $aRecord['FacebookName'], $aRecord['FacebookRights'], $aRecord['FacebookPage'], $aRecord['Enabled'], $iDomainId); } $TwitterCfgTable = new CTwitterCfg($g_Db); if ($TwitterCfgTable->GetTwitterInfo($aRecord, $iDefaultSiteId, $iDefaultDomainId)) { $TwitterCfgTable->Insert($iSiteId, $aRecord['Session_key'], $aRecord['Session_secret'], $aRecord['Uid'], $aRecord['TwitterName'], $aRecord['Enabled'], $iDomainId); } if (HasLicenseForFeature('Output-Blog', $iDefaultDomainId) === false) { WriteToLog('GeneralFunctions :: SetModuleTables(), Blog not Enabled, returning ...'); return; } $BlogCfgTable = new CBlogCfg($g_Db); $aParentBlogInfo = array(); if ($BlogCfgTable->GetBlogInfo($aParentBlogInfo, $iDefaultSiteId, $iDefaultDomainId)) { if ($aParentBlogInfo['Enabled'] == 0 || !is_numeric($aParentBlogInfo['NP_BlogId']) || $aParentBlogInfo['NP_BlogId'] == 0) { WriteToLog("GeneralFunctions :: SetModuleTables(), Parent Blog record found, but not enabled, returning ..."); return; } $aSiteInfo = array(); $SiteTable = new CSiteTable($g_Db); $SiteTable->GetSiteInformation($aSiteInfo, $iSiteId); $strBlogName = (trim($aSiteInfo['Alias']) != '' ? trim($aSiteInfo['Alias']) : trim($aSiteInfo['Name'])); $aBlogParams = array('blogname' => $strBlogName); $aParentBlogParams = array(); if (isset($aParentBlogInfo['Kind_Parameter']) && trim($aParentBlogInfo['Kind_Parameter']) != '') { $aParentBlogParams = unserialize($aParentBlogInfo['Kind_Parameter']); $aBlogParams = array_merge($aParentBlogParams, $aBlogParams); } $strAbsPostfix = ''; $strHttpPostfix = ''; // set enabled and kind in siteinfo $aSiteInfo['BlogEnabled'] = $aParentBlogInfo['Enabled']; $aSiteInfo['BlogKind'] = $aParentBlogInfo['Kind']; if ($iSiteId > 0) { $strAbsPostfix = $iSiteId . '\\blog\\'; $strHttpPostfix = $iSiteId . '/blog/'; } if ($aParentBlogInfo['Enabled'] == 1) { //require_once($g_ModuleDirectory . 'CBlogModule.php'); $aDomainSiteInfo = array( 'DomainId' => $iDefaultDomainId, 'BlogKind' => $aParentBlogInfo['Kind'], 'BlogEnabled' => $aParentBlogInfo['Enabled'] ); $BlogModule = new CBlogModule($aDomainSiteInfo); $iNP_BlogId = $BlogModule->CreateBlog($strBlogName, $aParentBlogInfo['NP_BlogId']); } if (substr($aParentBlogInfo['TargetPath'], -1, 1) != "\\") { $aParentBlogInfo['TargetPath'] .= "\\"; } if (substr($aParentBlogInfo['HttpLocation'], -1, 1) != "/") { $aParentBlogInfo['HttpLocation'] .= "/"; } $aParentBlogInfo['TargetPath'] .= $strAbsPostfix; $aParentBlogInfo['HttpLocation'] .= $strHttpPostfix; $aParentBlogInfo['Kind_Parameter'] = serialize($aBlogParams); $aParentBlogInfo['NP_BlogId'] = $iNP_BlogId; // remove id from record unset($aParentBlogInfo['id']); $BlogCfgTable->Insert($iSiteId, $aParentBlogInfo, $iDomainId); } } function SetChannelConfiguration($iSiteId, $aDomainInfo) { global $g_Db, $g_aChannelCfgs; $iDomainId = $aDomainInfo['id']; if (!isset($g_aChannelCfgs['Sites'][$iSiteId]) || !is_array($g_aChannelCfgs['Sites'][$iSiteId])) { WriteToLog('GeneralFunctions :: SetChannelConfiguration(), No config found for siteid ' . $iSiteId); return; } $ChannelTemplateGroupTable = new CChannelTemplateGroupTable($g_Db); $ChannelCfgForSiteTable = new CChannelCfgForSiteTable($g_Db); $iTemplateGroupId = $ChannelTemplateGroupTable->GetHighestId() + 1; $aConfigVars = $g_aChannelCfgs['Sites'][$iSiteId]; if (isset($aConfigVars['Channel']) && is_array($aConfigVars['Channel'])) { $ChannelTable = new CChannelTable($g_Db); $ChannelTemplateTable = new CChannelTemplateTable($g_Db); $KplChannelTemplateGroup_SiteTable = new CKplChannelTemplateGroup_SiteTable($g_Db); if (isset($aConfigVars['ChannelTemplateGroup']) && is_array($aConfigVars['ChannelTemplateGroup'])) { $aTemplateGroup = array(); $ChannelTemplateGroupTable->Init($aTemplateGroup, array()); unset($aTemplateGroup['id']); $aTemplateGroup = array_merge($aTemplateGroup, $aConfigVars['ChannelTemplateGroup']); $ChannelTemplateGroupTable->Insert($iTemplateGroupId, $aTemplateGroup); } foreach ($aConfigVars['Channel'] AS $strOutput => $aChannels) { $aChannelInfo = array(); if ($ChannelTable->GetChannelInfoBySite($aChannelInfo, $iSiteId, $strOutput) === false) { $ChannelTable->Insert($iSiteId, $aChannels['ChannelName'], $aDomainInfo['Channel_TargetPath'] . $aChannels['TargetPath'], $aDomainInfo['Channel_HttpLocation'] . $aChannels['HttpLocation'], $aChannels['Kind'], $aChannels['PreviewRatio']); } $iChannelId = $ChannelTable->GetLastInsertedId(); if (isset($aConfigVars['ChannelTemplate']) && isset($aConfigVars['ChannelTemplate'][$strOutput])) { $aChannelTemplateRecord = $aConfigVars['ChannelTemplate'][$strOutput]; $ChannelTemplateTable->Insert($iTemplateGroupId, $aChannelTemplateRecord['TemplatePath'], $aChannelTemplateRecord['Kind'], GetConfigVar('DefaultMaxHeadlines', 'General'), $aChannelTemplateRecord['Default']); $iChannelTemplateId = $ChannelTemplateTable->GetLastInsertedId(); } if ($iSiteId > 0) { $KplChannelTemplateGroup_SiteTable->Insert($iSiteId, $iTemplateGroupId, $iChannelTemplateId, $iChannelId); } } if (isset($aConfigVars['ChannelCfg']) && is_array($aConfigVars['ChannelCfg'])) { $aChannelCfgInfo = $aConfigVars['ChannelCfg']; $aChannelCfgInfo["siteid"] = $iSiteId; $aChannelCfgInfo["DefaultTemplateGroup"] = $iTemplateGroupId; $aChannelCfgInfo["DefaultApiTemplateGroup"] = $iTemplateGroupId; $aChannelCfgInfo["DomainId"] = $iDomainId; $ChannelCfgForSiteTable->Save($aChannelCfgInfo); } } } function GetSiteInfo($iPublishSiteId = 0) { global $g_SessionVars; $aSiteInfo = array(); // get correct siteinfo from session //$iSiteId = GetSessionValue($g_SessionVars["ActiveSite"]); $aUserSites = GetSessionValue($g_SessionVars["UserSites"]); if (is_numeric($iPublishSiteId) && $iPublishSiteId > 0 && is_array($aUserSites) && isset($aUserSites[$iPublishSiteId])) { $aSiteInfo = $aUserSites[$iPublishSiteId]; } else { global $g_Db; // schedular started publish, because no siteid in session found $aSiteInformation = array(); $SiteTable = new CSiteTable($g_Db); $SiteTable->GetSiteInformation($aSiteInformation, $iPublishSiteId); if (is_array($aSiteInformation) && isset($aSiteInformation["siteid"])) { $aSiteInfo = $aSiteInformation; } } return $aSiteInfo; } function DomainLevelIsActive() { if (GetConfigVar("EnableDomains", "Server")) { return true; } return false; } function ShowDomainLevel() { global $g_SessionVars; if (DomainLevelIsActive() && GetSessionValue($g_SessionVars["UserType"]) == CUserTable::USERTYPE_ADMIN) { return true; } return false; } function AlertPostMediaEnabled() { global $g_Db; $iDomainId = GetSessionValue("DomainId"); $aDomainInfo = array(); $DomainTable = new CDomainTable($g_Db); $DomainTable->GetDomainInfo($aDomainInfo, $iDomainId); if (is_array($aDomainInfo) && isset($aDomainInfo["AlertPostMediaEnabled"]) && $aDomainInfo["AlertPostMediaEnabled"] == 1 ) { return true; } return false; } function Quit($Msg) { die($Msg); } function Redirect($strUrl, $UserMsg = "", $strDelay = 0, $Return = false) { echo "\n" . "\n" . "Redirect\n" . "\n" . "\n" . "\n" . $UserMsg . "\n" . ""; } function RedirectHeader($Target) { if (ob_get_length() != 0) { die(); } else { header("Location: " . $Target); exit(); } } function GetRemoteContent(&$strContent, $domain = "www.youtube.com", $iPortNr = 80) { WriteToLog(__FUNCTION__ . "(), $domain : $iPortNr"); $http_code = 0; $ch = curl_init(); $timeout = 30; // set to zero for no timeout curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_URL, $domain); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if (strlen(GetConfigVar("ProxyServer", "ProxySettings")) > 2) { $aProxyOpts = GetProxyOptions(); if (is_array($aProxyOpts) && isset($aProxyOpts['ProxyIp'])) { WriteToLog(__FUNCTION__ . "(), Found proxy -> " . $aProxyOpts['ProxyIp']); curl_setopt($ch, CURLOPT_PROXY, $aProxyOpts['ProxyIp']); //your proxy url curl_setopt($ch, CURLOPT_PROXYPORT, $aProxyOpts['ProxyPort']); // your proxy port number if (trim($aProxyOpts['ProxyCredentials']) != '') { curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_PROXYUSERPWD, $aProxyOpts['ProxyCredentials']); //username:pass } curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); } } curl_setopt($ch, CURLOPT_PORT, $iPortNr); // your port number if ($iPortNr == 443) { if (file_exists($cert = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ca-bundle.crt')) { curl_setopt($ch, CURLOPT_CAINFO, $cert); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); } else { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } } $strContent = curl_exec($ch); if (curl_errno($ch) != CURLE_OK) { WriteToLog(__FUNCTION__ . "(), Error :: " . curl_error($ch) . " errornr: [" . curl_errno($ch) . "]"); } else { $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); } //curl_setopt($ch, CURLOPT_VERBOSE, true); curl_close($ch); if ($http_code >= 200 && $http_code < 300) { return true; } WriteToLog(__FUNCTION__ . "(), Domain: $domain HttpCode: [$http_code]"); return false; } function GetProxyOptions() { $aOptions = array(); $strUserPass = ''; $strProxyServer = GetConfigVar("ProxyServer", "ProxySettings"); $strProxyPort = GetConfigVar("ProxyPortNumber", "ProxySettings"); if (trim($strProxyServer) == '') { WriteToLog(__FUNCTION__ . "(), Invalid proxy settings, returning ..."); return $aOptions; } $strProxy = "tcp://" . $strProxyServer . ":" . $strProxyPort; if (GetConfigVar("ProxyRequiresAuthentication", "ProxySettings")) { $strProxyUser = GetConfigVar("ProxyUser", "ProxySettings"); $strProxyPass = GetConfigVar("ProxyPass", "ProxySettings"); $strProxyPass = base64_decode($strProxyPass); $strUserPass = $strProxyUser . ":" . $strProxyPass; } $aOptions = array( 'ProxyIp' => $strProxyServer, 'ProxyPort' => $strProxyPort, 'Proxy' => $strProxy, 'FullAuthProxyUrl' => 'tcp://'. $strUserPass .'@'. $strProxyServer . ':' . $strProxyPort, 'ProxyAuth' => GetConfigVar("ProxyRequiresAuthentication", "ProxySettings"), 'ProxyCredentials' => $strUserPass ); return $aOptions; } /** * Check to see if the server is connected to the web * @param string $domain Domainname (www.domain.com) */ function IsConnected($domain = "www.youtube.com", $iPortNr = 80) { $is_conn = false; try { $connected = @fsockopen($domain, $iPortNr, $errno, $errstr); if ($connected) { $is_conn = true; fclose($connected); } else { WriteToLog("GeneralFunctions :: IsConnected( $domain ), ErrorString: $errstr ( $errno )"); } return $is_conn; } catch (Exception $e) { WriteToLog("GeneralFunctions :: IsConnected( $domain ), Exception " . $e->getMessage()); return $is_conn; } } function IsRemoteFileReadable($strFileName, &$strFileContents = null) { $strResult = ''; $opts = array( 'http' => array( 'method' => "GET", 'header' => "Content-Type: text/xml; charset=utf-8" ) ); $context = stream_context_create($opts); $strResult = @file_get_contents($strFileName, false, $context); if ($strResult !== false) { WriteToLog(__METHOD__ . "(), Successfully read remote XML file"); $strFileContents = $strResult; return true; } WriteToLog(__METHOD__ . '(), Could not read content of remote XML file'); return false; } /** * Try to get configvar from section in session, fallback to db server table * @param string $Key The configvar * @param string $strSection Section that configvar is in (General, Performance, ...) * @return mixed value of the configvar */ function GetConfigVar($Key, $strSection) { global $g_Db; $CServerTable = new CServerTable($g_Db); $aWantedValue = $CServerTable->ReadFromSession($Key, $strSection); if (is_array($aWantedValue) && isset($aWantedValue['value'])) { return $aWantedValue['value']; } else { $aConfig = array(); if ($CServerTable->GetServerKey($aConfig, $Key, $strSection)) { return CastConfigVar($aConfig); } } } /** * Try to set configvar in db server table and in session * @param string $Key The key * @param string $Value The value * @param string $strSection Section that configvar is in (General, Performance, ...) * @return - */ function SetConfigVar($Key, $Value, $strSection) { global $g_TableDirectory, $g_Db; //require_once($g_TableDirectory . "CServerTable.php"); $aSetting = array("Name" => $Key, "Value" => $Value, "Type" => gettype($Value)); $VarValue = $Value; if (gettype($Value) == "array") { $VarValue = serialize($Value); } $aConfig = array(); $CServerTable = new CServerTable($g_Db); $CServerTable->GetServerKey($aConfig, $Key, $strSection); $CServerTable->Update($aSetting["Name"], $VarValue, $aSetting["Type"]); $CServerTable->WriteToSession($aSetting, $strSection); } function GetDomainConfigVar($Key, $strSection, $iDomainId = null) { $iDomainId = ($iDomainId != null) ? $iDomainId : GetDomainId(); $value = null; $aSettingOpts = array(); if (isset($_SESSION["DomainSettings"][$strSection]) && isset($_SESSION["DomainSettings"][$strSection][$Key]) && $iDomainId == GetSessionValue("DomainId")) { $value = $_SESSION["DomainSettings"][$strSection][$Key]["value"]; $aSettingOpts = $_SESSION["DomainSettings"][$strSection][$Key]; } else { global $g_Db; if (is_numeric($iDomainId) && $iDomainId >= 0) { $CDomainTable = new CDomainTable($g_Db); $aSettingOpts = null; if ($CDomainTable->GetDomainSettingValue($aSettingOpts, $iDomainId, $Key, $strSection)) { $value = $aSettingOpts["value"]; } } } //return the server DefaultAlertTemplateGroup when the domain DefaultAlertTemplateGroup is 0 if (($Key != "DefaultAlertTG" || (int)$value != 0) && !is_null($value)) { return CastConfigVar(array("Value" => $value, "Type" => $aSettingOpts["type"])); } else { return GetConfigVar($Key, $strSection); } } function CastConfigVar($aConfigVar) { if (!isset($aConfigVar["Type"]) || !isset($aConfigVar["Value"])) { //WriteToLog("GeneralFunctions :: CastConfigVar, no type or value found ". var_export($aConfigVar, true)); } // initialize our cast var on boolean false $castVar = false; switch ($aConfigVar["Type"]) { case "boolean": { if ($aConfigVar["Value"] == "1") { $castVar = true; } break; } case "integer": { $castVar = intval($aConfigVar["Value"]); break; } case "array": case "string": case "url": default: { $castVar = $aConfigVar["Value"]; break; } } return $castVar; } function GetDomainId($formId = "domainid") { $iDomainId = null; if (GetGetValue($formId) !== false) { $iDomainId = GetGetValue($formId); } elseif (GetPostValue($formId) !== false) { $iDomainId = GetPostValue($formId); } else { $iDomainId = GetSessionValue("DomainId"); } return $iDomainId; } function UpdateSiteInfo($iSiteId) { global $g_SessionVars, $g_Db, $g_TableDirectory; // get correct siteinfo from session $aUserSites = GetSessionValue($g_SessionVars["UserSites"]); if (!is_array($aUserSites)) { WriteToLog("GeneralFunctions :: UpdateSiteInfo(), no UserSites in session"); return; } //require_once($g_TableDirectory . "CSiteTable.php"); // get fresh siteinfo from database, because we don't get info // about enabled modules from siteform $aSiteInfo = array(); $SiteTable = new CSiteTable($g_Db); $SiteTable->GetAllSites($aSiteInfo); SetSessionValue($g_SessionVars["UserSites"], $aSiteInfo); /*if ($SiteTable->GetSiteInformation($aSiteInfo, $iSiteId)) { $aUserSites[$iSiteId] = $aSiteInfo; // insert / update siteinfo in session SetSessionValue($g_SessionVars["UserSites"], $aUserSites); }*/ } function GetAllSites(&$aSiteList) { global $g_Db, $g_SessionVars; $iUserId = GetSessionValue($g_SessionVars['UserId']); $SiteTable = new CSiteTable($g_Db); $aSiteList = array(); if (IsSuperUser($iUserId)) { $SiteTable->GetAllSites($aSiteList); } else { $SiteTable->GetUserSites($aSiteList, $iUserId); } if (count($aSiteList) > 0) { return true; } return false; } /** * Check if user is a superuser (admin or domainAdmin) * @param int $iUserId Unique id of the user * @return bool SuperUser or not */ function IsSuperUser($iUserId) { global $g_SessionVars; if (!is_numeric($iUserId) || $iUserId <= 0) { WriteToLog("GeneralFunctions :: IsSuperUser(), Incorrect UserId [" . $iUserId . "]"); return false; } // first check in session (should be there ;-)) if (GetSessionValue($g_SessionVars["UserId"]) == $iUserId && (GetSessionValue($g_SessionVars["UserType"]) == CUserTable::USERTYPE_ADMIN || GetSessionValue($g_SessionVars["UserType"]) == CUserTable::USERTYPE_DOMAINADMIN) ) { return true; } global $g_Db, $g_TableDirectory; if (GetSessionValue($g_SessionVars["UserType"]) === false) { //require_once($g_TableDirectory . "CUserTable.php"); $UserTable = new CUserTable($g_Db); if ($UserTable->IsSuperUser($iUserId) || $UserTable->IsDomainAdmin($iUserId)) { return true; } } return false; } /** * Check if one of the usersettings options (Manage Server) is checked * @param - * @return bool True if one of the settings is checked */ function CheckUserSettings() { global $g_TableDirectory, $g_Db; // first check if the usersettings are checked if (GetConfigVar("UserSettings", "UserSettings") == "1") { // now check if at least one of the usersettings are checked //require_once($g_TableDirectory . "CServerTable.php"); $aSettings = array(); $CServerTable = new CServerTable($g_Db); $CServerTable->GetServerInformation($aSettings, "UserSettings", "1"); // greater then 1, because usersettings = 1 are also in this array if (count($aSettings) > 1) { return true; } } return false; } function RedirectExitScript($Page, $Reason, $Action) { WriteToLog("GeneralFunctions :: RedirectExitScript()"); global $g_WebPages; CleanSession(); echo "

Authentication error

"; echo "Page: " . $Page . "
"; echo "Reason: " . $Reason . "
"; echo "Action: " . $Action . "
"; echo redirect($g_WebPages["Index"], "", 5); CleanSession(); ScriptExit(); } function GetEnvironmentValue($VarName, $EnvArray) { if (!is_array($EnvArray)) { return false; } if (isset($EnvArray[$VarName])) { return $EnvArray[$VarName]; } else { return false; } } /** * @param string $VarName * @return mixed */ function GetSessionValue($VarName) { // for PHP5: // If the session is started but no variables are present, $_SESSION will not be set. // Therefore the @ is used to suppress this notice. // GetEnvironmentValue has it's own check for this. return GetEnvironmentValue($VarName, @$_SESSION); } function GetPostValue($VarName) { return GetEnvironmentValue($VarName, $_POST); } function GetGetValue($VarName) { return GetEnvironmentValue($VarName, $_GET); } function SetSessionValue($VarName, $Value) { if (is_string($Value)) { $Value = strip_tags(trim($Value)); } $_SESSION[$VarName] = $Value; } function CleanSession() { if (session_id() != '') { // Initialize the session. @session_start(); @session_regenerate_id(true); // Unset all of the session variables. $_SESSION = array(); // Finally, destroy the session. @session_destroy(); } } function ScriptExit() { WriteToLog("GeneralFunctions :: ScriptExit()"); global $g_Log; global $g_Db; if (is_object($g_Log)) { $g_Log->Dtor(); } if (is_object($g_Db)) { $g_Db->Dtor(); } die(); } function GetArrayKeyForValue($Array, $Value) { foreach ($Array as $key => $ArrayValue) { if ($ArrayValue == $Value) { return $key; } } return false; } function CheckSiteLock($iSiteId, &$g_Db) { WriteToLog("GeneralFunctions :: CheckSiteLock ( $iSiteId )"); global $g_Tr; global $g_WebPages; global $g_HttpAlertDirectory; $aSiteInfo = array(); $SiteTable = new CSiteTable($g_Db); $SiteTable->GetSiteInformation($aSiteInfo, $iSiteId); if ($aSiteInfo["Locked"] == 1) { $Page = new CPage(); $Html = new CHtml(); $Page->IsLocked = true; $Page->AddToMeta(""); $Page->AddToBody("

" . $g_Tr->Tr("Alert Message Is Active") . "

"); $Page->AddToBody("

" . $g_Tr->Tr("Publishing is disabled in the Message Server until the Alert Message is cancelled.") . "

" . BrowserEndLine); $Page->AddToBody("
"); $Page->AddToBody($Html->Hyperlink($g_WebPages["MainMenu"], $g_Tr->Tr("Continue to Message Server (editing only) >> ")) . BrowserEndLine . BrowserEndLine); $Page->AddToBody($Html->Hyperlink($g_HttpAlertDirectory, $g_Tr->Tr("Alert Server (password required) >> "))); $Page->AddToBody("
"); $Page->DisplayPage(); ScriptExit(); } } function stri_replace($searchFor, $replaceWith, $string, $offset = 0) { $lsearchFor = strtolower($searchFor); $lstring = strtolower($string); $newPos = strpos($lstring, $lsearchFor, $offset); if (strlen($newPos) == 0) { return ($string); } else { $left = substr($string, 0, $newPos); $right = substr($string, $newPos + strlen($searchFor)); $newStr = $left . $replaceWith . $right; return stri_replace($searchFor, $replaceWith, $newStr, $newPos + strlen($replaceWith)); } } function IsBranchableLocation($Location) { // http, ftp, file if (IsHttpLocation($Location)) { return true; } // mailto if (IsMailtoLocation($Location)) { return true; } // UNC paths if (IsUncLocation($Location)) { return true; } return false; } function IsHttpLocation($Location) { $Location = trim($Location); if (preg_match("/^(http(s?)|ftp|file):\\/\\/.+/i", $Location)) { return true; } return false; } function IsMailtoLocation($Location) { $Location = trim($Location); if (preg_match("/^(mailto):([0-9a-zA-Z\\._-])+[@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*$/i", $Location)) { return true; } return false; } function IsUncLocation($Location) { $Location = trim($Location); if (preg_match("/^((([\\\\][\\\\])|(%))([a-zA-Z0-9%\\.-])+)([\\\\]([[:alnum:]%\\.\\$\\ \\_-])+)+$/i", $Location)) { return true; } return false; } function CleanDirectory($strDirPath, $RmDir = false) { $len = strlen(trim($strDirPath)); if ($len > 0) { if ($strDirPath[$len - 1] != "\\") { $strDirPath .= "\\"; } } if ($len <= 3) { return false; } if (!is_dir($strDirPath)) { return true; } $handle = opendir($strDirPath); if ($handle) { while (false !== ($file = readdir($handle))) { if ($file == "." || $file == "..") { continue; } if (is_dir($strDirPath . $file)) { CleanDirectory($strDirPath . $file . "\\", true); } else { if (is_file($strDirPath . $file)) { chmod($strDirPath . $file, 0777); unlink($strDirPath . $file); } } } closedir($handle); } if ($RmDir) { rmdir($strDirPath); } } function GetServerBaseUrl() { global $g_MsgDirectoryName; global $g_AlertDirectoryName; global $g_BaseUrl; if (strlen($g_BaseUrl) > 0) { return $g_BaseUrl; } $PathFound = false; if (array_key_exists("PATH_INFO", $_SERVER) && trim($_SERVER["PATH_INFO"]) != "") { $PathInfo = $_SERVER["PATH_INFO"]; $PathFound = true; } elseif (array_key_exists("ORIG_PATH_INFO", $_SERVER) && trim($_SERVER["ORIG_PATH_INFO"]) != "") { $PathInfo = $_SERVER["ORIG_PATH_INFO"]; $PathFound = true; } $strProto = "http" . ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "s" : "") . "://"; $HttpPath = $strProto . "[ServerName]"; if ($PathFound) { $PathInfo = pathinfo($PathInfo); if (($PathInfo["dirname"] != "\\") && ($PathInfo["dirname"] != "/")) { $DirPath = $PathInfo["dirname"]; $DirParts = explode("/", $DirPath); $bServerDirMatch = false; foreach ($DirParts AS $DirPart) { if (!empty($DirPart)) { if ((!$bServerDirMatch) && (strtolower($DirPart) != strtolower($g_MsgDirectoryName)) && (strtolower($DirPart) != strtolower($g_AlertDirectoryName))) { $HttpPath .= "/" . $DirPart; } else { $bServerDirMatch = true; } } } } } if (substr($HttpPath, -1, 1) != "/") { $HttpPath .= "/"; } return $HttpPath; } function ResolvePath($Value) { global $g_InstallationPath, $g_DataPath; if (strpos($Value, "[DataPath]") !== false) { return str_replace("[DataPath]", $g_DataPath, $Value); } else { return str_replace("[InstallationPath]", $g_InstallationPath, $Value); } } //TODO: HttpHostUrl wordt nu verplicht te gebruiken. Moet ook duidelijk gemaakt worden aan de gebruikers. (bv. bij de maintance) //deze functie ook verder afwerken (controlles uitvoeren) function ResolveHttp($Value, $iDomainId = null) { if (strpos($Value, "[ServerUrl]") !== false || strpos($Value, "[ServerName]") !== false) { $strServerUrl = GetDomainConfigVar("HttpHostUrl", "General", $iDomainId); if (is_string($strServerUrl) && strlen($strServerUrl) > 5) { $Value = str_replace("[ServerUrl]", $strServerUrl, $Value); } else { $Value = str_replace("[ServerUrl]", GetServerBaseUrl(), $Value); } if (array_key_exists("HTTP_X_FORWARDED_HOST", $_SERVER)) { $Value = str_replace("[ServerName]", $_SERVER["HTTP_X_FORWARDED_HOST"], $Value); } else { if (array_key_exists("HTTP_HOST", $_SERVER)) { $Value = str_replace("[ServerName]", $_SERVER["HTTP_HOST"], $Value); } else { if (array_key_exists("SERVER_NAME", $_SERVER)) { $Value = str_replace("[ServerName]", $_SERVER["SERVER_NAME"], $Value); } else { if (defined("SchedulerPublish") && SchedulerPublish && GetDomainConfigVar("HttpHostUrl", "General", $iDomainId) !== false && GetDomainConfigVar("HttpHostUrl", "General", $iDomainId) != "http://" ) { $HttpPath = GetDomainConfigVar("HttpHostUrl", "General", $iDomainId); $Value = preg_replace("/^http(s?):\/\/+\[ServerName\]/", $HttpPath, $Value); } else { $Value = str_replace("[ServerName]", "", $Value); } } } } } return $Value; } function AddBackwardSlash($strString) { if (!is_string($strString) || empty($strString)) { return false; } if (substr($strString, -1, 1) != "\\") { $strString .= "\\"; } return $strString; } function AddForwardSlash($strString) { if (!is_string($strString) || empty($strString)) { return false; } if (substr($strString, -1, 1) != "/") { $strString .= "/"; } return $strString; } function SetPageUrl() { $strProto = "http" . ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "s" : "") . "://"; $strHttpHost = $_SERVER["HTTP_HOST"]; if (isset($_SERVER["HTTP_X_FORWARDED_HOST"]) && $_SERVER["HTTP_X_FORWARDED_HOST"] != "") { $strHttpHost = $_SERVER["HTTP_X_FORWARDED_HOST"]; } $HttpPath = $strProto . $strHttpHost; $strUrl = ''; $iPos = 0; $strPathInfo = "index.php"; if (isset($_SERVER["SCRIPT_NAME"]) && $_SERVER["SCRIPT_NAME"] != "") { $strPathInfo = $_SERVER["SCRIPT_NAME"]; } else { if (isset($_SERVER["PATH_INFO"]) && $_SERVER["PATH_INFO"] != "") { $strPathInfo = $_SERVER["PATH_INFO"]; } } if (isset($_SERVER["QUERY_STRING"]) && $_SERVER["QUERY_STRING"] != "") { $strPathInfo .= "?" . $_SERVER["QUERY_STRING"]; } $_SESSION["HTTP_PAGEURL"] = $HttpPath . $strPathInfo; if (!isset($_SESSION['CLICK_PATH'])) { $_SESSION['CLICK_PATH'] = array(); $_SESSION['CLICK_PATH'][] = $HttpPath . $strPathInfo; } else { if (is_array($_SESSION['CLICK_PATH']) && count($_SESSION['CLICK_PATH']) > 4) { array_shift($_SESSION['CLICK_PATH']); } $_SESSION['CLICK_PATH'][] = $HttpPath . $strPathInfo; if (isset($_SESSION['CLICK_PATH']) && is_array($_SESSION['CLICK_PATH']) && count($_SESSION['CLICK_PATH']) > 0) { $iPos = count($_SESSION['CLICK_PATH']) - 1; $strUrl = $_SESSION['CLICK_PATH'][$iPos]; $_SESSION['MANAGE_SECTION'] = GetManagementSection($strUrl); if (count($_SESSION['CLICK_PATH']) > 1) { $iPos = count($_SESSION['CLICK_PATH']) - 2; $strUrl = $_SESSION['CLICK_PATH'][$iPos]; $_SESSION['MANAGE_REFERRING_SECTION'] = GetManagementSection($strUrl); } } } //WriteToLog("GeneralFunctions :: SetPageUrl(), ". var_export($_SESSION['CLICK_PATH'], true)); } function GetManagementSection($strUrl) { $strSection = ''; // check if we have a query_string if (strpos($strUrl, '?') === false) { return $strSection; } list($strPath, $strQueryString) = explode('?', $strUrl); $aQueryParams = explode('&', $strQueryString); foreach ($aQueryParams AS $strParams) { list($strKey, $strValue) = explode('=', $strParams); // this is key for management section if ($strKey == 'ms_1') { $strSection = $strValue; } } return $strSection; } function GetPublishLocation($aSiteInfo, $strOutput) { $strHrefUrl = ""; $strHttpLocation = ucfirst($strOutput) . "HttpLocation"; if (isset($aSiteInfo[$strHttpLocation])) { $strHrefUrl = trim($aSiteInfo[$strHttpLocation]); if ($strHrefUrl == "") { $strHrefUrl = "[ServerUrl]published/" . $aSiteInfo['siteid'] . "/" . $strOutput . "/"; } } $strHrefUrl = ResolveHttp($strHrefUrl, $aSiteInfo["DomainId"]); return $strHrefUrl; } function GetFacebookWallUrl($iFacebookId) { if (!isset($iFacebookId) && !is_numeric($iFacebookId)) { return false; } $fbProfileUrl = "http://www.facebook.com/profile.php?id=" . $iFacebookId . "&sk=wall"; return $fbProfileUrl; } function GetTwitterTimelineUrl($strTwitterName) { if (!isset($strTwitterName) && !is_string($strTwitterName)) { return false; } $twProfileUrl = "http://twitter.com/" . $strTwitterName; return $twProfileUrl; } function Maintenance() { global $g_UpgradeInProcess; global $g_ResolvedServerHttpLocation; if ($g_UpgradeInProcess) { if (strlen($g_ResolvedServerHttpLocation) > 0) { header("Location: " . $g_ResolvedServerHttpLocation); exit(); } else { die("The Netpresenter Message Server is offline for maintenance"); } } } function MakeNumericLogical($iNumber, $bHasMax = true) { if (!is_numeric($iNumber)) { $iNumber = 0; } else { if ($iNumber < 0) { $iNumber = 0 - $iNumber; } } if ($bHasMax && $iNumber > 3000) { $iNumber = 3000; } return $iNumber; } class CDirectoryFunctions { function CDirectoryFunctions() { $this->a_Copied = array(); } function CopyDirectory($strSourcePath, $strTargetPath) { $bCopy = true; if (array_key_exists($strSourcePath, $this->a_Copied)) { if ($strTargetPath == $this->a_Copied[$strSourcePath]) { $bCopy = false; } } if ($bCopy) { $this->a_Copied[$strSourcePath] = $strTargetPath; $this->CopyDirectoryExec($strSourcePath, $strTargetPath); } } function CopyDirectoryExec($SourceDirectory, $TargetDirectory) { if (!is_dir($TargetDirectory)) { @mkdir($TargetDirectory); } $handle = @opendir($SourceDirectory); if ($handle) { while (false !== ($file = readdir($handle))) { if ($file == "." || $file == "..") { continue; } if (is_dir($SourceDirectory . $file)) { $this->CopyDirectoryExec($SourceDirectory . $file . "\\", $TargetDirectory . $file . "\\"); } else { if (is_file($SourceDirectory . $file)) { if (file_exists($TargetDirectory . $file)) { chmod($TargetDirectory . $file, 0777); } @copy($SourceDirectory . $file, $TargetDirectory . $file); } } } closedir($handle); } } function mkdirr($pathname) { // Check if directory already exists if (is_dir($pathname) || empty($pathname)) { return true; } // Ensure a file does not already exist with the same name if (is_file($pathname)) { return false; } // Crawl up the directory tree $next_pathname = substr($pathname, 0, strrpos($pathname, DIRECTORY_SEPARATOR)); if ($this->mkdirr($next_pathname)) { if (!file_exists($pathname)) { return @mkdir($pathname, 0777); } } return false; } function rmdirr($pathname) { // recursive function to delete // all subdirectories and contents: if (!is_dir($pathname)) { return false; } $dir_handle = opendir($pathname); while (false !== ($file = readdir($dir_handle))) { if ($file != "." && $file != "..") { if (!is_dir($pathname . "\\" . $file)) { @chmod($pathname . "\\" . $file, 0777); @unlink($pathname . "\\" . $file); } else { $this->rmdirr($pathname . "\\" . $file); } } } closedir($dir_handle); @rmdir($pathname); return true; } function getResolutionDir($ImageWidth, $ImageHeight) { if ($ImageWidth == 'Original' || $ImageHeight == 'Original') { return 'Original\\'; } return $ImageWidth . '_' . $ImageHeight . '\\'; } function DirectoryIsEmpty($pathname) { if (count(glob("$pathname/*")) === 0) { return true; } return false; } } /** * Renames a file or directory. If a file or directory called $newname exists, tries to unlink it first. */ function RenameWithOverwrite($oldname, $newname) { $outcome = true; if (file_exists($newname)) { if (!unlink($newname)) { $outcome = false; } } if (!rename($oldname, $newname)) { $outcome = false; } return $outcome; } function ValidateIntegerValue($iValue) { $aInt = array(); for ($i = 0; $i < 10; $i++) { $aInt[] = "$i"; } $bValueOk = true; if (strlen($iValue) > 0) { $iValue = trim($iValue); $Len = strlen($iValue); for ($i = 0; $i < $Len; $i++) { if (!in_array($iValue[$i], $aInt)) { $bValueOk = false; continue; } } } else { $bValueOk = false; } return $bValueOk; } function MakeNameForPublisher($iLastPublishedUserId) { global $g_Tr, $g_SessionVars, $g_Db; $iUserId = GetSessionValue($g_SessionVars["UserId"]); if (GetSessionValue($g_SessionVars["LastPublishedUser"]) === false || (is_numeric($iUserId) && $iLastPublishedUserId == $iUserId)) { $PublishedUserInfo = array(); $UserTable = new CUserTable($g_Db); $UserTable->GetUserInformation($PublishedUserInfo, $iLastPublishedUserId); if (trim($PublishedUserInfo["FirstName"]) == "" && trim($PublishedUserInfo["LastName"]) == "") { $UserString = $PublishedUserInfo["UserName"]; } else { $UserString = $PublishedUserInfo["FirstName"] . " " . $PublishedUserInfo["LastName"]; } SetSessionValue($g_SessionVars["LastPublishedUser"], $UserString); } return " " . $g_Tr->Tr("by") . " " . GetSessionValue($g_SessionVars["LastPublishedUser"]); } function MakeNameForUser($iUserId) { global $g_Tr, $g_SessionVars, $g_Db; $UserString = "undefined"; if ($iUserId == GetSessionValue($g_SessionVars["UserId"])) { // get userinfo from session if (GetSessionValue($g_SessionVars["FirstName"]) == "" && GetSessionValue($g_SessionVars["LastName"]) == "") { $UserString = GetSessionValue($g_SessionVars["UserName"]); } else { $UserString = GetSessionValue($g_SessionVars["FirstName"]) . " " . GetSessionValue($g_SessionVars["LastName"]); } } else { $PublishedUserInfo = array(); $UserTable = new CUserTable($g_Db); if ($UserTable->GetUserInformation($PublishedUserInfo, $iUserId) !== false) { if (trim($PublishedUserInfo["FirstName"]) == "" && trim($PublishedUserInfo["LastName"]) == "") { $UserString = $PublishedUserInfo["UserName"]; } else { $UserString = $PublishedUserInfo["FirstName"] . " " . $PublishedUserInfo["LastName"]; } } } return $UserString; } function hscForUnicode($str) { return preg_replace("/&(#[0-9]+|[a-z]+);/i", "&$1;", htmlentities($str)); } function ReplaceLatinExtendedChars($myString) { $aLatinExtendedReplacements = array( "�" => "Œ", "�" => "œ", "�" => "Š", "�" => "š", "�" => "Ÿ", "�" => "ƒ", "�" => "–", "�" => "—", "�" => "‘", "�" => "’", "�" => "‚", "�" => "“", "�" => "”", "�" => "„", "�" => "†", "�" => "‡", "�" => "•", "�" => "…", "�" => "‰", "�" => "€", "�" => "™" ); return strtr($myString, $aLatinExtendedReplacements); } function RevertLatinExtendedChars($myString) { $aLatinExtendedReplacements = array( "Œ" => "�", "œ" => "�", "Š" => "�", "š" => "�", "Ÿ" => "�", "ƒ" => "�", "–" => "�", "—" => "�", "‘" => "�", "’" => "�", "‚" => "�", "“" => "�", "”" => "�", "„" => "�", "†" => "�", "‡" => "�", "•" => "�", "…" => "�", "‰" => "�", "€" => "�", "™" => "�" ); return strtr($myString, $aLatinExtendedReplacements); } function GetCOM() { try { $COM = @new COM("NpScriptServer.NpChannelFactory"); } catch (Exception $myException) { FailComLoad($myException->getMessage()); } $RequiredComVersion = RequiredComVersion; $RegisteredComVersionInt = $COM->Version(); if ($RegisteredComVersionInt < $RequiredComVersion) { $Digit1 = $RequiredComVersion >> 24; $Digit2 = ($RequiredComVersion & 0x00FF0000) >> 16; $Digit3 = ($RequiredComVersion & 0x0000FF00) >> 8; $Digit4 = $RequiredComVersion & 0x000000FF; FailComLoad("A newer version of the COM service is required:
Required version: " . $Digit1 . "." . $Digit2 . "." . $Digit3 . "." . $Digit4 . "
Please contact Netpresenter support for a newer version."); } return $COM; } function FailComLoad($Exception) { global $g_HttpImageDirectory; $Html = new CHtml(); die($Html->Image($g_HttpImageDirectory . "icons/warn16.gif", null, null, null, "absmiddle") . "
An error has occured: COM service failed.
Reason: " . $Exception); } function GetShortDateForUser($TimeStamp = null) { global $g_SessionVars; global $g_aUserDateFormats; GetSession($g_SessionVars["DateFormat"], $DateFormat); if (!array_key_exists($DateFormat, $g_aUserDateFormats)) { $DateFormat = UserDateFormat; } return FormatTimestampForUser($g_aUserDateFormats[$DateFormat]["short"], $TimeStamp); } function GetLongDateForUser($TimeStamp = null) { global $g_SessionVars; global $g_aUserDateFormats; $DateFormat = ""; if (isset($g_SessionVars["DateFormat"]) && isset($_SESSION[$g_SessionVars["DateFormat"]])) { GetSession($g_SessionVars["DateFormat"], $DateFormat); } if (!array_key_exists($DateFormat, $g_aUserDateFormats)) { $DateFormat = UserDateFormat; } return FormatTimestampForUser($g_aUserDateFormats[$DateFormat]["long"], $TimeStamp); } function GetTimeForUser($TimeStamp = null, $bForDisplaying = false) { global $g_SessionVars; global $g_aUserTimeFormats; GetSession($g_SessionVars["TimeFormat"], $TimeFormat); if (!array_key_exists($TimeFormat, $g_aUserTimeFormats)) { $TimeFormat = UserTimeFormat; } // for mainview Last Edited info we added boolean bForDisplaying // because timestamp is otherwise formatted to gmt time (for COM object scheduling functions) return FormatTimeStampForUser($g_aUserTimeFormats[$TimeFormat]["short"], $TimeStamp, null, $bForDisplaying); } function FormatTimestampForUser($FormatString, $TimeStamp, $iUserid = null, $bForDisplaying = false) { global $g_aUserDateFormats; global $g_SessionVars; global $g_Tr, $g_Db; global $g_LanguageTimeSettings; if (is_null($iUserid) || !is_numeric($iUserid) || $iUserid <= 0) { $iUserid = GetSessionValue($g_SessionVars["UserId"]); } $UserTimeZone = ""; if (isset($g_SessionVars["TimeZoneInfo"]) && isset($_SESSION[$g_SessionVars["TimeZoneInfo"]])) { $UserTimeZone = GetSessionValue($g_SessionVars["TimeZoneInfo"]); } $ServerTimeZone = new VARIANT(); $TimeZoneName = new VARIANT(); $BiasCurrent = new VARIANT(); $Bias = new VARIANT(); $COM = GetCOM(); $COM->GetCurrentTimeZone($ServerTimeZone, $TimeZoneName, $Bias, $BiasCurrent); if (strcmp($UserTimeZone, "") == 0) { $UserTimeZone = $ServerTimeZone; } if ($TimeStamp == null) { $TimeStamp = time(); } $CalcTimeStamp = $COM->LocalTimeToLocalTime($ServerTimeZone, $TimeStamp, $UserTimeZone); if ($bForDisplaying) { $DateStr = strftime($FormatString, $CalcTimeStamp); } else { $DateStr = gmstrftime($FormatString, $CalcTimeStamp); } return ucfirst($DateStr); } function ExtractNumber($strTab) { $iTabNr = 1; $strTemp = substr($strTab, strlen($iTabNr) - 1); if (is_numeric($strTemp)) { $iTabNr = intval($strTemp); } return $iTabNr; } function GetSnippet($text, $length = 64, $tail = "...") { $text = trim($text); $txtl = mb_strlen($text, 'UTF-8'); if ($txtl > $length) { for ($i = 1; $text[$length - $i] != " "; $i++) { if ($i == $length) { return mb_substr($text, 0, $length, 'UTF-8') . $tail; } } $text = mb_substr($text, 0, $length - $i + 1, 'UTF-8') . $tail; } return $text; } function ShortFilename($filename, $length = 5, $tail = "...") { $filename = trim($filename); if (preg_match("/(.+?)(\\.([^.]*))?$/", $filename, $matches)) { if (isset($matches[2]) && strlen($matches[2]) > 0) { $name = $matches[1]; $ext = $matches[2]; } else { $name = "None"; $ext = ".jpg"; } $namelength = strlen($name); if ($namelength > $length) { for ($i = 1; $name[$length - $i] != " "; $i++) { if ($i == $length) { return substr($name, 0, $length) . $tail . $ext; } } $name = substr($name, 0, $length - $i + 1) . $tail; } $filename = $name . $ext; } return $filename; } function Convert2RGBTextColor($psHexColorString) { $iAlpha = 0; if (strlen($psHexColorString) <= 6) { return $iAlpha; } // Begint de string met een #? if ($psHexColorString{0} == '#') { // knip dat er dan af $psHexColorString = substr($psHexColorString, 1); } // 00 is for the alpha channel (not used, so always non transparant) $psHexColorString = "00" . $psHexColorString; return intval(hexdec($psHexColorString)); } function ConvertHex2RGB($strHexColor) { $aResult = array(); $aResult["R"] = 100; $aResult["G"] = 100; $aResult["B"] = 100; if (preg_match("/[#]?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i", $strHexColor, $aMatches)) { $aResult["R"] = hexdec($aMatches[1]); $aResult["G"] = hexdec($aMatches[2]); $aResult["B"] = hexdec($aMatches[3]); } return $aResult; } function ConvertRGB2Hex($strRed, $strGreen, $strBlue) { // force the passed value to be numeric // use max and min to limit the number to between 0 and 255 // shift the number to make it the correct future hex value $iRed = 0x10000 * max(0, min(255, intval($strRed))); $iGreen = 0x100 * max(0, min(255, intval($strGreen))); $iBlue = max(0, min(255, intval($strBlue))); // convert the combined value to hex and zero-fill to 6 digits return "#" . str_pad(strtoupper(dechex($iRed + $iGreen + $iBlue)), 6, "0", STR_PAD_LEFT); } function DecimalToBinaryArray($number) { $iBinary = decbin($number); if (strlen($iBinary) < 3) { $iBinary = str_pad($iBinary, 3, '0', STR_PAD_LEFT); } $aRetval = array(1 => $iBinary[2], 2 => $iBinary[1], 4 => $iBinary[0]); //WriteToLog("DecimalToBinaryArray: [". var_export($aRetval, true)); return $aRetval; } function IsDefaultImage($needle, $haystack) { foreach ($haystack AS $key => $defItem) { if ($needle == $defItem["file"]) { return true; } } return false; } function GetOnlyFilename($FileName) { $Parts = array(); // check if the filename is base64_encoded if (stristr($FileName, ".") == false) { $FileName = base64_decode($FileName); } $Parts = explode("\\", $FileName); if ($Parts != false) { return $Parts[(count($Parts) - 1)]; } return $FileName; } /* * Check if Message Server has license for the requested feature * * CAUTION : if domainid is not given, the feature access is checked at license level * so be sure to give domainid, unless this is not possible ( superadmin in management, * or not logged in user ) * * @param string $strFeature The requested feature * @param integer $iDomainId The domainid the requested feature has to be checked for * @return bool true if access is granted */ function HasLicenseForFeature($strFeature, $iDomainId = null) { global $g_Db; $ServerTable = new CServerTable($g_Db); $aFeature = $ServerTable->ReadFromSession($strFeature, 'License'); if (is_array($aFeature) && isset($aFeature['value']) && $aFeature['value'] === true) { //WriteToLog("GeneralFunctions :: HasLicenseForFeature(), License for $strFeature is enabled (Domain [$iDomainId])"); // Superadmin has access to multiple domains, so we can not always check domain access if (DomainFeatureExist($strFeature, $iDomainId)) { if (HasDomainLicenseForFeature($strFeature, $iDomainId)) { //WriteToLog("GeneralFunctions :: HasLicenseForFeature(), License for $strFeature at domain $iDomainId"); return true; } return false; } return true; } return false; } function DomainFeatureExist($strFeature, $iDomainId) { global $g_Db; if (!is_numeric($iDomainId) || $iDomainId <= 0) { return false; } $DomainTable = new CDomainTable($g_Db); $aDomainSettings = $DomainTable->GetDomainSettings($iDomainId); foreach ($aDomainSettings AS $strDomainSection => $aDomainFeatureSection) { foreach ($aDomainFeatureSection AS $strName => $aSettingOpts) { if ($strName == $strFeature) { return true; } } } return false; } function HasDomainLicenseForFeature($strFeature, $iDomainId) { global $g_Db; $DomainTable = new CDomainTable($g_Db); $aDomainSettings = $DomainTable->GetDomainSettings($iDomainId); foreach ($aDomainSettings AS $strDomainSection => $aDomainFeatureSection) { foreach ($aDomainFeatureSection AS $strName => $aSettingOpts) { if ($strName == $strFeature) { if ($aSettingOpts["value"] == 1) { //WriteToLog("GeneralFunctions :: HasDomainLicenseForFeature(), Domain has feature $strFeature enabled!"); return true; } } } } //WriteToLog("GeneralFunctions :: HasDomainLicenseForFeature(), $strFeature NOT enabled for Domain $iDomainId"); return false; } function ModifyOutputForDomain($iDomainId, $strName, $iValue) { global $g_aCfgTableLookup, $g_TableDirectory, $g_Db; if(isset($g_aCfgTableLookup[$strName])) { $strTableName = $g_aCfgTableLookup[$strName]; if(class_exists($strTableName)) { // create table object $CTableObject = new $strTableName($g_Db); WriteToLog("GeneralFunctions :: " . __FUNCTION__ . "(), $strTableName => $iValue (for ALL sites in domain " . $iDomainId . ")"); // enable / disable output in [Output]Cfg table $CTableObject->Modify($iDomainId, $iValue); } } } function GetNumberOfAllowedUsers($bAddFreeUser = true) { global $g_SessionVars; $iNumUsers = 0; $strUserType = GetSessionValue($g_SessionVars["UserType"]); if ($strUserType != CUserTable::USERTYPE_ADMIN && DomainLevelIsActive()) { $iNumUsers = GetAllowedUsersForDomain(); } else { list($iNumUsers, $iUnlimitedUsers) = GetAllowedNumberForLicense('Number of Users', $bAddFreeUser); } return intval($iNumUsers); } function GetAllowedUsersForDomain($iDomainId = null) { global $g_Db; $iNumUsers = 0; $iCurDomainId = GetSessionValue("DomainId"); if (is_numeric($iDomainId)) { $iCurDomainId = $iDomainId; } $aDomainInfo = array(); $DomainTable = new CDomainTable($g_Db); $DomainTable->GetDomainInfo($aDomainInfo, $iCurDomainId); if (isset($aDomainInfo["I_G_A_MaxUsers"]) && is_numeric($aDomainInfo["I_G_A_MaxUsers"])) { $iNumUsers += intval($aDomainInfo["I_G_A_MaxUsers"]); } return $iNumUsers; } function GetAllowedNumberForLicense($strNumberField, $bAddFreeUser = true) { global $g_ClassesDirectory, $g_aLicenseMappings, $g_Db; //require($g_ClassesDirectory . "MessageServerDefaults.php"); $iNumUsers = 0; $iUnlimitedUsers = 0; $ServerTable = new CServerTable($g_Db); $aNumberField = $ServerTable->ReadFromSession($strNumberField, 'License'); if (is_array($aNumberField) && isset($aNumberField['value'])) { $iNumUsers = intval($aNumberField['value']); $iUnlimitedUsers = intval($aNumberField['unlimited']); if ($bAddFreeUser && $iNumUsers < $iUnlimitedUsers) { // for administrative purposes add 1 user for free !! $iNumUsers++; } } return array($iNumUsers, $iUnlimitedUsers); } function GetNumberOfAllowedDomains() { global $g_Db; $iNumDomains = 0; $ServerTable = new CServerTable($g_Db); $aDomainField = $ServerTable->ReadFromSession('Number of Domains', 'License'); if (is_array($aDomainField) && isset($aDomainField['value'])) { $iNumDomains = $aDomainField['value']; } return $iNumDomains; } function GetNumberOfAllowedSites() { global $g_Db; $iNumSites = 0; $ServerTable = new CServerTable($g_Db); $aSitesField = $ServerTable->ReadFromSession('Number of Sites', 'License'); if (is_array($aSitesField) && isset($aSitesField['value'])) { $iNumSites = $aSitesField['value']; } return $iNumSites; } function GetUsersFromDB() { global $g_Db, $g_TableDirectory, $g_SessionVars; //require_once($g_TableDirectory . "CUserTable.php"); $UserTable = new CUserTable($g_Db); $iDomainId = null; $iNumUsers = 0; $strUserType = GetSessionValue($g_SessionVars["UserType"]); if ($strUserType != CUserTable::USERTYPE_ADMIN && DomainLevelIsActive()) { $iDomainId = GetSessionValue("DomainId"); WriteToLog("Get Database Users for Domain $iDomainId"); } $iNumUsers = $UserTable->GetUsersForDomain($iDomainId); return intval($iNumUsers); } function DisablePlayerCounter() { return GetConfigVar("DisablePlayerCounter", "General"); } function TimeAgo($datefrom, $dateto = -1) { global $g_Tr; // Defaults and assume if 0 is passed in that // its an error rather than the epoch if ($datefrom <= 0) { return $g_Tr->Tr("A long time ago"); } if ($dateto == -1) { $dateto = time(); } // Calculate the difference in seconds betweeen // the two timestamps $difference = $dateto - $datefrom; // If difference is less than 60 seconds, // seconds is a good interval of choice if ($difference < 60) { $interval = "s"; } // If difference is between 60 seconds and // 60 minutes, minutes is a good interval elseif ($difference >= 60 && $difference < 60 * 60) { $interval = "n"; } // If difference is between 1 hour and 24 hours // hours is a good interval elseif ($difference >= 60 * 60 && $difference < 60 * 60 * 24) { $interval = "h"; } // If difference is between 1 day and 7 days // days is a good interval elseif ($difference >= 60 * 60 * 24 && $difference < 60 * 60 * 24 * 7) { $interval = "d"; } // If difference is between 1 week and 30 days // weeks is a good interval elseif ($difference >= 60 * 60 * 24 * 7 && $difference < 60 * 60 * 24 * 30) { $interval = "ww"; } // If difference is between 30 days and 365 days // months is a good interval, again, the same thing // applies, if the 29th February happens to exist // between your 2 dates, the function will return // the 'incorrect' value for a day elseif ($difference >= 60 * 60 * 24 * 30 && $difference < 60 * 60 * 24 * 365) { $interval = "m"; } // If difference is greater than or equal to 365 // days, return year. This will be incorrect if // for example, you call the function on the 28th April // 2008 passing in 29th April 2007. It will return // 1 year ago when in actual fact (yawn!) not quite // a year has gone by elseif ($difference >= 60 * 60 * 24 * 365) { $interval = "y"; } // Based on the interval, determine the // number of units between the two dates switch ($interval) { case "m": $months_difference = floor($difference / 60 / 60 / 24 / 29); while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom) + ($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) { $months_difference++; } $datediff = $months_difference; // We need this in here because it is possible // to have an 'm' interval and a months // difference of 12 because we are using 29 days // in a month if ($datediff == 12) { $datediff--; } $res = ($datediff == 1) ? $datediff . " " . $g_Tr->Tr("month ago") : $datediff . " " . $g_Tr->Tr("months ago"); break; case "y": $datediff = floor($difference / 60 / 60 / 24 / 365); $res = ($datediff == 1) ? $datediff . " " . $g_Tr->Tr("year ago") : $datediff . " " . $g_Tr->Tr("years ago"); break; case "d": $datediff = floor($difference / 60 / 60 / 24); $res = ($datediff == 1) ? $datediff . " " . $g_Tr->Tr("day ago") : $datediff . " " . $g_Tr->Tr("days ago"); break; case "ww": $datediff = floor($difference / 60 / 60 / 24 / 7); $res = ($datediff == 1) ? $datediff . " " . $g_Tr->Tr("week ago") : $datediff . " " . $g_Tr->Tr("weeks ago"); break; case "h": $datediff = floor($difference / 60 / 60); $res = ($datediff == 1) ? $datediff . " " . $g_Tr->Tr("hour ago") : $datediff . " " . $g_Tr->Tr("hours ago"); break; case "n": $datediff = floor($difference / 60); $res = ($datediff == 1) ? $datediff . " " . $g_Tr->Tr("minute ago") : $datediff . " " . $g_Tr->Tr("minutes ago"); break; case "s": $datediff = $difference; $res = ($datediff == 1) ? $datediff . " " . $g_Tr->Tr("second ago") : $datediff . " " . $g_Tr->Tr("seconds ago"); break; } return $res; } /** * @param $url * @param array $services if a services fails the next service in the array is used * @return bool|string */ function GetTinyUrl($url, $services = array("is.gd", "tinyurl")) { foreach($services as $service) { switch ($service) { case "is.gd": $tinyUrlPath = "https://is.gd/create.php?format=simple&url="; break; case "tinyurl": $tinyUrlPath = "http://tinyurl.com/api-create.php?url="; break; default: $tinyUrlPath = "http://tinyurl.com/api-create.php?url="; } $context = stream_context_create( array( 'http' => array( 'timeout' => 5 ), 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false ) ) ); $fp = @fopen($tinyUrlPath . urlencode($url), 'r', false, $context); if ($fp) { $tinyurl = fgets($fp); if ($tinyurl && !empty($tinyurl)) { $url = $tinyurl; } fclose($fp); return $url; } } return false; } function GetGUID() { return trim(com_create_guid(), '{}'); } function SetBlogCategories($aBlogInfo) { global $g_LibraryDirectory, $g_SessionVars, $g_ClassesDirectory; if (!is_array($aBlogInfo) || !isset($aBlogInfo['NP_BlogId'])) { WriteToLog("GeneralFunctions :: SetBlogCategories(), No (correct) blog info found, returning ..."); return; } if ($aBlogInfo['Enabled'] == 0) { WriteToLog("GeneralFunctions :: SetBlogCategories(), BlogModule not enabled, returning ..."); return; } $iBlogId = $aBlogInfo['NP_BlogId']; $strBlogType = $aBlogInfo['Kind']; $strBlogType = ucfirst(strtolower($strBlogType)); $strBlogClass = 'CBlog' . $strBlogType; // require_once($g_LibraryDirectory . 'blogapi\\' . $strBlogClass . '.php'); $aConnectionParameters = get_PDO_connection_params(); // create module object $CBlogObject = new $strBlogClass($aConnectionParameters); $aResults = array(); $aResponse = array(); $aCategories = array(); if (!is_object($CBlogObject->crud)) { WriteToLog("GeneralFunctions :: SetBlogCategories(), No database object, returning ..."); return; } $aResponse = $CBlogObject->GetCategories($aResults, $iBlogId); if (isset($aResponse['error']) && $aResponse['error'] != '') { WriteToLog('MsgServer/index.php :: SetBlogCategories Error : ' . $aResponse['error']); return; } //WriteToLog("MsgServer/index.php :: SetBlogCategories( $iBlogId ), Result from Blog API ". var_export($aResults, true)); foreach ($aResults AS $aResult) { $aCategory = array(); $aCategory['id'] = $aResult['Id']; $aCategory['name'] = $aResult['Name']; $aCategories[] = $aCategory; } SetSessionValue($g_SessionVars["BlogCategories"], $aCategories); } function explode_trim($str, $delimiter = ',') { if (is_string($delimiter)) { $str = trim(preg_replace('|\\s*(?:' . preg_quote($delimiter) . ')\\s*|', $delimiter, $str)); return explode($delimiter, $str); } return $str; } function CastArrayElements($type, $aArray) { if (is_array($aArray)) { foreach ($aArray as $i => $value) { if (is_array($value)) { $aArray[$i] = CastArrayElements($type, $value); } else { if (settype($value, $type)) { $aArray[$i] = $value; } else { return false; } } } return $aArray; } else { return false; } } function ValidateEmail($mail) { if (filter_var($mail, FILTER_VALIDATE_EMAIL)) { return true; } else { return false; } } function ValidateIP($ip) { if (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { return false; } else { return true; } } /** Check if the end ip address is greater or equal then the start ip address * @param $startIp * @param $endIp * @return bool */ function isValidRangeForIpAddresses($startIp, $endIp) { $startIpLong = ip2long($startIp); $endIpLong = ip2long($endIp); if($endIpLong < $startIpLong){ return false; } return true; } function GetSlideDuration($aSiteInfo) { $iSlideDuration = $aSiteInfo['SiteSlideDuration']; if (!is_numeric($iSlideDuration) || $iSlideDuration < 0) { $iSlideDuration = GetDomainConfigVar('SlideDuration', 'General', $aSiteInfo['DomainId']); } if (!is_numeric($iSlideDuration) || $iSlideDuration < 0) { $iSlideDuration = 0; } return intval($iSlideDuration); } /** * * Returns the version number of Internet Explorer and returns -1 if it's an other browser */ function GetIEVersion() { $VersionMatch = preg_match("/MSIE ([0-9]{1,3}\\.[0-9])/i", $_SERVER['HTTP_USER_AGENT'], $reg); /** * when IE10 is in Compatibility view it sends a useragent with MSI 7.0 as the version. But we can check by the Trident/6.0 that the browser is IE10. */ if (isset($reg[1]) && $reg[1] == "7.0") { $TridentMatch = preg_match("/Trident\\/([6-7])\\.0/i", $_SERVER['HTTP_USER_AGENT'], $aMatches); if ($TridentMatch == 1) { $VersionMatch = 1; $reg[1] = "10.0"; if (isset($aMatches[1]) && $aMatches[1] == "7") { $reg[1] = "11.0"; } } } if ($VersionMatch == 0) { return -1; } else { return floatval($reg[1]); } } /** * Create a valid URI that url_encodes the correct parts. * * @param $uri * An absolute URI. * * @return * An absolute URI with url_encoded path. * */ function CreateValidUri($uri) { $parse_url = parse_url($uri); $strPath = ''; if (isset($parse_url["path"])) { $aEncodedParts = array(); $aPathParts = explode("/", $parse_url["path"]); foreach ($aPathParts AS $strPart) { $aEncodedParts[] = rawurlencode($strPart); } if (count($aEncodedParts) > 0) { $strPath = implode("/", $aEncodedParts); } } $strQuery = ''; if (isset($parse_url["query"])) { $aEncodedParts = array(); $aQueryParts = explode("&", $parse_url["query"]); foreach ($aQueryParts AS $strPart) { list($key, $value) = explode("=", $strPart); $aEncodedParts[] = rawurlencode($key) . "=" . rawurlencode($value); } if (count($aEncodedParts) > 0) { $strQuery = "?" . implode("&", $aEncodedParts); } } // put url back together return ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "") . ((isset($parse_url["user"])) ? rawurlencode($parse_url["user"]) . ((isset($parse_url["pass"])) ? ":" . rawurlencode($parse_url["pass"]) : "") . "@" : "") . ((isset($parse_url["host"])) ? $parse_url["host"] : "") . ((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "") . ($strPath) . ($strQuery) . ((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : ""); } function get_PDO_connection_params() { global $aDbType; global $g_DataPath, $g_InstallationPath; global $DbDatabaseName, $DbUserName, $DbPassword; global $DbServerName; if (func_num_args() == 0) { global $Type; $strType = $Type; } else { // use first arg as database type $strType = func_get_arg(0); } $aConnectionParameters = array( 'type' => '', 'host' => $DbServerName, 'name' => $DbDatabaseName, 'user' => $DbUserName, 'pass' => $DbPassword, 'charset' => 'utf8', 'persistent' => false ); $strSqlPath = $g_InstallationPath . 'blog\\tinymvc\\myfiles\\sql\\'; switch ($strType) { case $aDbType["MsSql"] : $aConnectionParameters['type'] = 'sqlsrv'; $aConnectionParameters['printname'] = 'MSSQL'; $aConnectionParameters['dbtype'] = 'MSSQL'; $aConnectionParameters['dsn'] = 'sqlsrv:Server=' . $aConnectionParameters['host'] . ';Database=' . $aConnectionParameters['name']; $aConnectionParameters['sqlfile'] = $strSqlPath . 'blogext-mssql.sql'; break; case $aDbType["MySql"] : $aConnectionParameters['type'] = 'mysql'; $aConnectionParameters['printname'] = 'MySQL'; $aConnectionParameters['dbtype'] = 'MySQL'; $aConnectionParameters['sqlfile'] = $strSqlPath . 'blogext-mysql.sql'; break; case $aDbType["MsAccess"] : default : // location of msaccess database file $strMsAccessLocation = $g_DataPath . 'NpMsgServer.mdb'; $aConnectionParameters['printname'] = 'MS Access'; $aConnectionParameters['dbtype'] = 'MSAccess'; $aConnectionParameters['type'] = 'access'; $aConnectionParameters['dsn'] = 'odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=' . $strMsAccessLocation; $aConnectionParameters['sqlfile'] = $strSqlPath . 'blogext-msaccess.sql'; break; } return $aConnectionParameters; } function GetMediaInfo($iMediaId) { global $g_TableDirectory, $g_Db, $g_SessionVars; global $g_RssImageResolution, $g_ImageStore, $g_AlertImageStore; //require_once($g_TableDirectory . "CMediaTable.php"); $aMediaInfo = array(); $aRemoteInfo = array(); $aImageInfo = array(); $aResultInfo = array(); $MediaTable = new CMediaTable($g_Db); $MediaTable->GetMediaInfo($aMediaInfo, $iMediaId); if (!is_array($aMediaInfo) || !isset($aMediaInfo['mediatypeId'])) { WriteToLog(__FUNCTION__ . "(), No MediaInfo found for id " . $iMediaId); return $aResultInfo; } switch ($aMediaInfo['mediatype']) { case CMediaTable::TYPE_IMAGE: //require_once($g_TableDirectory . "CImageTable.php"); $DirectoryFunctions = new CDirectoryFunctions(); $ImageTable = new CImageTable($g_Db); $ImageTable->GetImageInfo($aImageInfo, $aMediaInfo['mediatypeId']); $aResultInfo = $aImageInfo; $aResultInfo['kind'] = 'internal'; $aResultInfo['mediatype'] = CMediaTable::TYPE_IMAGE; $aResultInfo['mediaId'] = intval($aImageInfo['imageid']); if ($aImageInfo['Category'] == 'alertimage') { $ImageStoreDirectory = $g_AlertImageStore; } else { $iSiteId = GetSessionValue($g_SessionVars['ActiveSite']); $aSiteInfo = GetSiteInfo($iSiteId); $strImageSiteId = $aImageInfo["siteid"]; if ($strImageSiteId == 0) { $strImageSiteId = "Common"; } $sResolutionDir = $DirectoryFunctions->getResolutionDir($aSiteInfo['ImageWidth'], $aSiteInfo['ImageHeight']); $ImageStoreDirectory = $g_ImageStore . $sResolutionDir . $strImageSiteId . "\\"; } $aResultInfo['url'] = $ImageStoreDirectory . $aImageInfo["SavedFileName"]; $aResultInfo['thumb'] = $ImageStoreDirectory . 'thumbs\\' . $aImageInfo["SavedFileName"]; break; case CMediaTable::TYPE_REMOTE: //require_once($g_TableDirectory . "CRemoteMediaTable.php");e::TYPE_REMOTE: $RemoteMediaTable = new CRemoteMediaTable($g_Db); $RemoteMediaTable->GetRemoteMediaInfo($aRemoteInfo, $aMediaInfo['mediatypeId']); $aResultInfo = $aRemoteInfo; $aResultInfo['kind'] = 'external'; $aResultInfo['mediatype'] = CMediaTable::TYPE_IMAGE; $aResultInfo['url'] = base64_decode($aRemoteInfo['url']); $aResultInfo['thumb'] = base64_decode($aRemoteInfo['thumb']); break; default: WriteToLog("GeneralFunctions :: " . __FUNCTION__ . "(), Implement case statement for mediatype " . $aMediaInfo['mediatype']); } return $aResultInfo; } function GetYoutubeIdFromUrl($strYoutubeUrl) { $u = parse_url($strYoutubeUrl); @parse_str($u['query'], $queryVars); if (isset($u['query']) && isset($queryVars['v'])) { return $queryVars['v']; } else { if (isset($u['fragment'])) { return basename($u['fragment']); } else { if (isset($u['path'])) { $aQuery = explode('&', basename($u['path'])); return $aQuery[0]; } } } return false; } function CamelCaseToDisplayText($camelCase, $splitter = ' ') { return preg_replace('/(?!^)[A-Z]{2,}(?=[A-Z][a-z])|[A-Z][a-z]/', $splitter . '$0', $camelCase); } class multiSort { var $key; //key in your array //runs the sort, and returns sorted array function run($myarray, $key_to_sort, $type_of_sort = '') { $this->key = $key_to_sort; if ($type_of_sort == 'desc') { if (is_string($this->key)) { usort($myarray, array($this, 'myreverse_stringcompare')); } else { usort($myarray, array($this, 'myreverse_compare')); } } else { if (is_string($this->key)) { usort($myarray, array($this, 'mystringcompare')); } else { usort($myarray, array($this, 'mycompare')); } } return $myarray; } //string ascending order function mystringcompare($x, $y) { if (strcasecmp($x[$this->key], $y[$this->key]) == 0) { return 0; } else { if (strcasecmp($x[$this->key], $y[$this->key]) < 0) { return -1; } else { return 1; } } } //string descending order function myreverse_stringcompare($x, $y) { if (strcasecmp($x[$this->key], $y[$this->key]) == 0) { return 0; } else { if (strcasecmp($x[$this->key], $y[$this->key]) > 0) { return -1; } else { return 1; } } } //for ascending order function mycompare($x, $y) { if ($x[$this->key] == $y[$this->key]) { return 0; } else { if ($x[$this->key] < $y[$this->key]) { return -1; } else { return 1; } } } //for descending order function myreverse_compare($x, $y) { if ($x[$this->key] == $y[$this->key]) { return 0; } else { if ($x[$this->key] > $y[$this->key]) { return -1; } else { return 1; } } } } function IsIpInRange($Ip, $StartIp, $StopIp) { $start_dec = ip2long($StartIp); $stop_dec = ip2long($StopIp); $ip_dec = ip2long($Ip); return (($ip_dec >= $start_dec) && ($ip_dec <= $stop_dec)); } function GetDisplayLanguageNames() { global $g_Tr, $g_DisplayLanguageNames; $aDisplayLanguageNames = array(); foreach ($g_DisplayLanguageNames AS $aLanguageName){ $aDisplayLanguageNames[] = $g_Tr->Tr($aLanguageName); } return $aDisplayLanguageNames; } function GetClassBasename($class) { $class = is_object($class) ? get_class($class) : $class; $value = explode('\\', $class); return end($value); } function GetGoogleMapsApiUrl() { global $g_GoogleMapsLanguage, $g_SessionVars; /** * url: https://console.developers.google.com */ $strGoogleMapsAPIKey = "AIzaSyALRKiC1fHOAXzZ8O6xPzxyWitZOFPBRpg"; if (strlen(GetConfigVar("GoogleMapsAPIKey", "General"))>10){ $strGoogleMapsAPIKey = GetConfigVar("GoogleMapsAPIKey", "General"); } $GMv = trim(GetConfigVar("GoogleMapsAPIVersion", "General")); $strGMv = ""; if (is_string($GMv) && !empty($GMv)) { $strGMv = "&v=" . $GMv; } $strGMv .= "&key=$strGoogleMapsAPIKey"; $googleLanguage = $g_GoogleMapsLanguage[GetSessionValue($g_SessionVars["Language"])]; $googleMapsAPIUrl = htmlspecialchars("https://maps.googleapis.com/maps/api/js?libraries=places,geometry" . $strGMv . "&language=" . $googleLanguage); return $googleMapsAPIUrl; } function GetGoogleMapsScriptTag() { $googleMapsAPIUrl = GetGoogleMapsApiUrl(); $googleMapsScriptTag = ''; /*if (IsConnected("maps.googleapis.com", 443)) { $googleMapsScriptTag = << SCRIPT_BLOCK; }*/ return $googleMapsScriptTag; } function GetGoogleChartsLoader() { $googleChartsLoader = ''; /*if (IsConnected("www.gstatic.com", 443)) { $googleChartsLoader = << SCRIPT_BLOCK; }*/ return $googleChartsLoader; } /** * Files older than a week are removed from the temp folders */ function CleanupTempDirectories() { global $g_Tmp, $g_TmpRoot, $g_PublicTmp; $directories = [ $g_Tmp, $g_TmpRoot, $g_PublicTmp ]; $daysAgo = 7; foreach($directories as $directory) { $objects = glob($directory."*"); $now = time(); foreach ($objects as $object) { if ($now - filemtime($object) >= 60 * 60 * 24 * $daysAgo) { if (is_dir($object)) { $DirectoryFunctions = new CDirectoryFunctions(); $DirectoryFunctions->rmdirr($object); } else { unlink($object); } } } } } function CalculateMinutes($number, $unit) { $aPossibleUnits = ['unlimited', 'day', 'hour', 'minute']; if (!in_array($unit, $aPossibleUnits)){ WriteToLog(__FUNCTION__ ."(), Unit must be one of the following values: ". implode(" ", $aPossibleUnits)); return 0; } switch ($unit) { case 'unlimited': $iNumMinutes = 0; break; case 'hour': $iNumMinutes = intval($number) * 60; break; case 'day': $iNumMinutes = intval($number) * 3600; break; default: $iNumMinutes = intval($number); } return $iNumMinutes; } function substr_close_tags($code, $limit = 300) { if ( strlen($code) <= $limit ) { return $code; } $html = substr($code, 0, $limit); preg_match_all( "#<([a-zA-Z]+)#", $html, $result ); foreach($result[1] AS $key => $value) { $value = strtolower($value); WriteToLog('['.$value.']'); if ( $value == 'br' || $value == 'b' ) { unset($result[1][$key]); } } $openedtags = $result[1]; preg_match_all( "##iU", $html, $result ); $closedtags = $result[1]; foreach($closedtags AS $key => $value) { if ( ($k = array_search($value, $openedtags)) === false ) { continue; } else { unset($openedtags[$k]); } } if ( empty($openedtags) ) { if (substr($html, -1) == '<'){ $html = substr($html, 0 , $limit-1); } return $html; } $position = 0; $close_tag = ''; foreach($openedtags AS $key => $value) { $p = strpos($code, (''), $limit); if ( $p === false ) { $code .= (''); } else if ( $p > $position ) { $close_tag = ''; $position = $p; } } if ( $position == 0 ) { return $code; } return substr($code, 0, $position).$close_tag; }