/** * Generates the export * * @param integer $categoryId Category Id * @param boolean $downwards If true, downwards, otherwise upward ordering * @param string $language Language * * @return string */ public function generate($categoryId = 0, $downwards = true, $language = '') { global $PMF_LANG; // Initialize categories $this->category->transform($categoryId); $faqdata = $this->faq->get(FAQ_QUERY_TYPE_EXPORT_XML, $categoryId, $downwards, $language); $version = PMF_Configuration::getInstance()->get('main.currentVersion'); $comment = sprintf('XHTML output by phpMyFAQ %s | Date: %s', $version, PMF_Date::createIsoDate(date("YmdHis"))); $this->xml->startDocument('1.0', 'utf-8'); $this->xml->writeDtd('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'); $this->xml->startElement('html'); $this->xml->writeAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); $this->xml->writeAttribute('xml:lang', $language); $this->xml->writeComment($comment); $this->xml->startElement('head'); $this->xml->writeElement('title', PMF_Configuration::getInstance()->get('main.titleFAQ')); $this->xml->startElement('meta'); $this->xml->writeAttribute('http-equiv', 'Content-Type'); $this->xml->writeAttribute('content', 'application/xhtml+xml; charset=utf-8'); $this->xml->endElement(); $this->xml->endElement(); // </head> $this->xml->startElement('body'); $this->xml->writeAttribute('dir', $PMF_LANG['dir']); if (count($faqdata)) { $lastCategory = 0; foreach ($faqdata as $data) { if ($data['category_id'] != $lastCategory) { $this->xml->writeElement('h1', $this->category->getPath($data['category_id'], ' >> ')); } $this->xml->writeElement('h2', strip_tags($data['topic'])); $this->xml->writeElement('p', $data['content']); $this->xml->writeElement('p', $PMF_LANG['msgAuthor'] . ': ' . $data['author_email']); $this->xml->writeElement('p', $PMF_LANG['msgLastUpdateArticle'] . PMF_Date::createIsoDate($data['lastmodified'])); $lastCategory = $data['category_id']; } } $this->xml->endElement(); // </body> $this->xml->endElement(); // </html> header('Content-type: text/html'); return $this->xml->outputMemory(); }
/** * Return the latest news data * * @param boolean $showArchive Show archived news * @param boolean $active Show active news * @param boolean $forceConfLimit Force to limit in configuration * @return string */ public function getLatestData($showArchive = false, $active = true, $forceConfLimit = false) { $news = array(); $counter = 0; $now = date('YmdHis'); $faqconfig = PMF_Configuration::getInstance(); $query = sprintf("\n SELECT\n *\n FROM\n %sfaqnews\n WHERE\n date_start <= '%s'\n AND \n date_end >= '%s'\n %s\n AND\n lang = '%s'\n ORDER BY\n datum DESC", SQLPREFIX, $now, $now, $active ? "AND active = 'y'" : '', $this->language); $result = $this->db->query($query); if ($faqconfig->get('main.numberOfShownNewsEntries') > 0 && $this->db->num_rows($result) > 0) { while ($row = $this->db->fetch_object($result)) { $counter++; if ($showArchive && $counter > $faqconfig->get('main.numberOfShownNewsEntries') || !$showArchive && !$forceConfLimit && $counter <= $faqconfig->get('main.numberOfShownNewsEntries') || !$showArchive && $forceConfLimit) { $item = array('id' => $row->id, 'lang' => $row->lang, 'date' => $row->datum, 'lang' => $row->lang, 'header' => $row->header, 'content' => $row->artikel, 'authorName' => $row->author_name, 'authorEmail' => $row->author_email, 'dateStart' => $row->date_start, 'dateEnd' => $row->date_end, 'active' => 'y' == $row->active, 'allowComments' => 'y' == $row->comment, 'link' => $row->link, 'linkTitle' => $row->linktitel, 'target' => $row->target); $news[] = $item; } } } return $news; }
/** * Performs a check if an IPv4 or IPv6 address is banned * * @param string $ip IPv4 or IPv6 address * * @return boolean true, if not banned */ public function checkIp($ip) { $bannedList = PMF_Configuration::getInstance()->get('security.bannedIPs'); $bannedIps = explode(' ', $bannedList); foreach ($bannedIps as $ipAddress) { if (0 == strlen($ipAddress)) { continue; } if (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { // Handle IPv4 if ($this->checkForAddrMatchIpv4($ip, $ipAddress)) { return false; } } else { // Handle IPv6 if ($this->checkForAddrMatchIpv6($ip, $ipAddress)) { return false; } } } return true; }
/** * Generates the export * * @param integer $categoryId Category Id * @param boolean $downwards If true, downwards, otherwise upward ordering * @param string $language Language * * @return string */ public function generate($categoryId = 0, $downwards = true, $language = '') { // Initialize categories $this->category->transform($categoryId); $faqdata = $this->faq->get(FAQ_QUERY_TYPE_EXPORT_XML, $categoryId, $downwards, $language); $version = PMF_Configuration::getInstance()->get('main.currentVersion'); $comment = sprintf('XML output by phpMyFAQ %s | Date: %s', $version, PMF_Date::createIsoDate(date("YmdHis"))); $this->xml->startDocument('1.0', 'utf-8', 'yes'); $this->xml->writeComment($comment); $this->xml->startElement('phpmyfaq'); if (count($faqdata)) { foreach ($faqdata as $data) { // Build the <article/> node $this->xml->startElement('article'); $this->xml->writeAttribute('id', $data['id']); $this->xml->writeElement('language', $data['lang']); $this->xml->writeElement('category', $this->category->getPath($data['category_id'], ' >> ')); if (!empty($data['keywords'])) { $this->xml->writeElement('keywords', $data['keywords']); } else { $this->xml->writeElement('keywords'); } $this->xml->writeElement('question', strip_tags($data['topic'])); $this->xml->writeElement('answer', PMF_String::htmlspecialchars($data['content'])); if (!empty($data['author_name'])) { $this->xml->writeElement('author', $data['author_name']); } else { $this->xml->writeElement('author'); } $this->xml->writeElement('data', PMF_Date::createIsoDate($data['lastmodified'])); $this->xml->endElement(); } } $this->xml->endElement(); header('Content-type: text/xml'); return $this->xml->outputMemory(); }
function sendAskedQuestion($username, $usermail, $usercat, $content) { global $PMF_LANG, $faq; $retval = false; $faqconfig = PMF_Configuration::getInstance(); $categoryNode = new PMF_Category_Node(); if ($faqconfig->get('records.enableVisibilityQuestions')) { $visibility = 'N'; } else { $visibility = 'Y'; } $questionData = array('id' => null, 'username' => $username, 'email' => $usermail, 'category_id' => $usercat, 'question' => $content, 'date' => date('YmdHis'), 'is_visible' => $visibility); list($user, $host) = explode("@", $questionData['email']); if (PMF_Filter::filterVar($questionData['email'], FILTER_VALIDATE_EMAIL) != false) { $faqQuestions = new PMF_Faq_Questions(); $faqQuestions->create($questionData); $categoryData = $categoryNode->fetch($questionData['category_id']); $questionMail = "User: "******", mailto:" . $questionData['email'] . "\n" . $PMF_LANG["msgCategory"] . ": " . $categoryData->name . "\n\n" . wordwrap($content, 72); $userId = $categoryData->user_id; $oUser = new PMF_User(); $oUser->getUserById($userId); $userEmail = $oUser->getUserData('email'); $mainAdminEmail = $faqconfig->get('main.administrationMail'); $mail = new PMF_Mail(); $mail->unsetFrom(); $mail->setFrom($questionData['email'], $questionData['username']); $mail->addTo($mainAdminEmail); // Let the category owner get a copy of the message if ($userEmail && $mainAdminEmail != $userEmail) { $mail->addCc($userEmail); } $mail->subject = '%sitename%'; $mail->message = $questionMail; $retval = $mail->send(); } return $retval; }
/** * Tracks the user and log what he did * * @param string $action String User action string * @param integer $id ID * * @return void */ public function userTracking($action, $id = 0) { global $sid, $user, $botBlacklist; $faqconfig = PMF_Configuration::getInstance(); if (!$faqconfig->get('main.enableUserTracking')) { return; } $bots = 0; $agent = $_SERVER['HTTP_USER_AGENT']; $sid = PMF_Filter::filterInput(INPUT_GET, PMF_GET_KEY_NAME_SESSIONID, FILTER_VALIDATE_INT); $sidc = PMF_Filter::filterInput(INPUT_COOKIE, PMF_COOKIE_NAME_SESSIONID, FILTER_VALIDATE_INT); if (!is_null($sidc)) { $sid = $sidc; } if ($action == "old_session") { $sid = null; } foreach ($botBlacklist as $bot) { if (strpos($agent, $bot)) { $bots++; } } if ($bots > 0) { return; } if (!isset($sid)) { $sid = $this->db->nextID(SQLPREFIX . "faqsessions", "sid"); // Sanity check: force the session cookie to contains the current $sid if (!is_null($sidc) && !$sidc != $sid) { self::setCookie($sid); } $query = sprintf("\n INSERT INTO \n %sfaqsessions\n (sid, user_id, ip, time)\n VALUES\n (%d, %d, '%s', %d)", SQLPREFIX, $sid, $user ? $user->getUserId() : -1, $_SERVER["REMOTE_ADDR"], $_SERVER['REQUEST_TIME']); $this->db->query($query); } $data = $sid . ';' . str_replace(';', ',', $action) . ';' . $id . ';' . $_SERVER['REMOTE_ADDR'] . ';' . str_replace(';', ',', $_SERVER['QUERY_STRING']) . ';' . str_replace(';', ',', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '') . ';' . str_replace(';', ',', urldecode($_SERVER['HTTP_USER_AGENT'])) . ';' . $_SERVER['REQUEST_TIME'] . ";\n"; file_put_contents('./data/tracking' . date('dmY'), $data, FILE_APPEND); }
/** * Check on user and group permissions and on duplicate FAQs * * @param array $resultset Array with search results * * @return void */ public function reviewResultset(array $resultset) { $this->setResultset($resultset); $duplicateResults = array(); $currentUserId = $this->user->getUserId(); if ('medium' == PMF_Configuration::getInstance()->get('security.permLevel')) { $currentGroupIds = $this->user->perm->getUserGroups($currentUserId); } foreach ($this->rawResultset as $index => $result) { $permission = false; // check permissions for groups if ('medium' == PMF_Configuration::getInstance()->get('security.permLevel')) { $groupPermission = $this->faq->getPermission('group', $result->id); if (count($groupPermission) && in_array($groupPermission[0], $currentGroupIds)) { $permission = true; } } // check permission for user if ($permission || 'basic' == PMF_Configuration::getInstance()->get('security.permLevel')) { $userPermission = $this->faq->getPermission('user', $result->id); if (in_array(-1, $userPermission) || in_array($this->user->getUserId(), $userPermission)) { $permission = true; } else { $permission = false; } } // check on duplicates if (!isset($duplicateResults[$result->id])) { $duplicateResults[$result->id] = 1; } else { ++$duplicateResults[$result->id]; continue; } if ($permission) { $this->reviewedResultset[] = $result; } } $this->setNumberOfResults($this->reviewedResultset); }
/** * Renders the main navigation * * @param string $legend Text of the HTML Legend element * @param string $img HTML code for the Captcha image * @param string $error Error message * * @return string */ public function renderFieldset($legend, $img, $error = '') { $html = ''; if (PMF_Configuration::getInstance()->get('spam.enableCaptchaCode')) { $html = sprintf('<fieldset><legend>%s</legend>', $legend); $html .= '<div style="text-align:left;">'; if ($error != '') { $html .= '<div class="error">' . $error . '</div>'; } $html .= $img; $html .= ' <input class="inputfield" type="text" name="captcha" id="captcha" value="" size="7" style="vertical-align: top; height: 35px; text-valign: middle; font-size: 20pt;" />'; $html .= '</div></fieldset>'; } return $html; }
$count++; if (!($count % 10)) { ob_flush(); flush(); } } ob_flush(); flush(); print "</div>"; } // Clear the array with the queries unset($query); $query = array(); // Always the last step: Update version number if (version_compare($version, NEWVERSION, '<')) { $oPMFConf = PMF_Configuration::getInstance(); $oPMFConf->update(array('main.currentVersion' => NEWVERSION)); } // optimize tables switch ($DB["type"]) { case 'mssql': case 'sybase': // Get all table names $db->getTableNames(SQLPREFIX); foreach ($db->tableNames as $tableName) { $query[] = 'DBCC DBREINDEX (' . $tableName . ')'; } break; case 'mysql': case 'mysqli': // Get all table names
/** * The footer of the PDF file * * @return void */ public function Footer() { global $PMF_LANG; $faqconfig = PMF_Configuration::getInstance(); $currentTextColor = $this->TextColor; $this->SetTextColor(0, 0, 0); $this->SetY(-25); $this->SetFont('dejavusans', '', 10); $this->Cell(0, 10, $PMF_LANG['ad_gen_page'] . ' ' . $this->PageNo() . ' / ' . $this->getAliasNbPages(), 0, 0, 'C'); $this->SetY(-20); $this->SetFont('dejavusans', 'B', 8); $this->Cell(0, 10, "(c) " . date("Y") . " " . $faqconfig->get('main.metaPublisher') . " <" . $faqconfig->get('main.administrationMail') . ">", 0, 1, "C"); if ($this->enableBookmarks == false) { $this->SetY(-15); $this->SetFont('dejavusans', '', 8); $baseUrl = '/index.php'; if (is_array($this->faq) && !empty($this->faq)) { $baseUrl .= '?action=artikel&cat=' . $this->categories[$this->category]['id']; $baseUrl .= '&id=' . $this->faq['id']; $baseUrl .= '&artlang=' . $this->faq['lang']; } $url = PMF_Link::getSystemScheme() . $_SERVER['HTTP_HOST'] . $baseUrl; $urlObj = new PMF_Link($url); $urlObj->itemTitle = $this->thema; $_url = str_replace('&', '&', $urlObj->toString()); $this->Cell(0, 10, 'URL: ' . $_url, 0, 1, 'C', 0, $_url); } $this->TextColor = $currentTextColor; }
/** * Resolves the PMF markers like e.g. %sitename%. * * @public * @static * @param string $text Text contains PMF markers * @return string */ public static function resolveMarkers($text) { // Available markers: key and resolving value $markers = array('%sitename%' => PMF_Configuration::getInstance()->get('main.titleFAQ')); // Resolve any known pattern return str_replace(array_keys($markers), array_values($markers), $text); }
function printInputFieldByType($key, $type) { global $PMF_LANG; $faqconfig = PMF_Configuration::getInstance(); switch ($type) { case 'area': printf('<textarea name="edit[%s]" cols="60" rows="6" style="width: 500px;">%s</textarea>', $key, str_replace('<', '<', str_replace('>', '>', $faqconfig->get($key)))); printf("<br />\n"); break; case 'input': printf('<input type="text" name="edit[%s]" size="75" value="%s" style="width: 500px;" />', $key, str_replace('"', '"', $faqconfig->get($key))); printf("<br />\n"); break; case 'select': printf('<select name="edit[%s]" size="1" style="width: 500px;">', $key); switch ($key) { case 'main.language': $languages = PMF_Language::getAvailableLanguages(); if (count($languages) > 0) { print PMF_Language::languageOptions(str_replace(array("language_", ".php"), "", $faqconfig->get('main.language')), false, true); } else { print '<option value="language_en.php">English</option>'; } break; case 'records.orderby': print sortingOptions($faqconfig->get($key)); break; case 'records.sortby': printf('<option value="DESC"%s>%s</option>', 'DESC' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['ad_conf_desc']); printf('<option value="ASC"%s>%s</option>', 'ASC' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['ad_conf_asc']); break; case 'main.permLevel': print PMF_Perm::permOptions($faqconfig->get($key)); break; case "main.templateSet": /** * TODO: do get availiable template sets in the PMF_Template */ foreach (new DirectoryIterator('../template') as $item) { if (!$item->isDot() && $item->isDir()) { $selected = PMF_Template::getTplSetName() == $item ? ' selected="selected"' : ''; printf("<option%s>%s</option>", $selected, $item); } } break; case "main.attachmentsStorageType": foreach ($PMF_LANG['att_storage_type'] as $i => $item) { $selected = $faqconfig->get($key) == $i ? ' selected="selected"' : ''; printf('<option value="%d"%s>%s</option>', $i, $selected, $item); } break; } print "</select>\n<br />\n"; break; case 'checkbox': printf('<input type="checkbox" name="edit[%s]" value="true"', $key); if ($faqconfig->get($key)) { print ' checked="checked"'; } print " /><br />\n"; break; case 'print': printf('<input type="hidden" name="edit[%s]" size="80" value="%s" />%s<br />', $key, str_replace('"', '"', $faqconfig->get($key)), $faqconfig->get($key)); break; } }
/** * Constructor * * @param integer $user User * @param array $groups Groups * * @return PMF_Sitemap */ public function __construct($user = null, $groups = null) { global $DB; $this->db = PMF_Db::getInstance(); $this->language = PMF_Language::$language; $this->type = $DB['type']; if (is_null($user)) { $this->user = -1; } else { $this->user = $user; } if (is_null($groups)) { $this->groups = array(-1); } else { $this->groups = $groups; } if (PMF_Configuration::getInstance()->get('security.permLevel') == 'medium') { $this->groupSupport = true; } }
/** * Check on user and group permissions and on duplicate FAQs * * @param array $resultset Array with search results * * @return void */ public function reviewResultset(array $resultset) { $this->setResultset($resultset); $faqUser = new PMF_Faq_User(); $faqGroup = new PMF_Faq_Group(); $duplicateResults = array(); $currentUserId = $this->user->getUserId(); if ('medium' == PMF_Configuration::getInstance()->get('main.permLevel')) { $currentGroupIds = $this->user->perm->getUserGroups($currentUserId); } foreach ($this->rawResultset as $index => $result) { $permission = false; // check permissions for groups if ('medium' == PMF_Configuration::getInstance()->get('main.permLevel')) { $groupPerm = $faqGroup->fetch($result->id); if (count($groupPerm) && in_array($groupPerm->group_id, $currentGroupIds)) { $permission = true; } } // check permission for user if ($permission || 'basic' == PMF_Configuration::getInstance()->get('main.permLevel')) { $userPerm = $faqUser->fetch($result->id); if (-1 == $userPerm->user_id || $this->user->getUserId() == $userPerm->user_id) { $permission = true; } else { $permission = false; } } // check on duplicates if (!isset($duplicateResults[$result->id])) { $duplicateResults[$result->id] = 1; } else { ++$duplicateResults[$result->id]; continue; } if ($permission) { $this->reviewedResultset[] = $result; } } $this->setNumberOfResults($this->reviewedResultset); }
/** * Constructor * * @param PMF_Perm $perm Permission object * @param array $auth Authorization array * @return void */ public function __construct(PMF_Perm $perm = null, array $auth = array()) { $this->db = PMF_Db::getInstance(); if ($perm !== null) { if (!$this->addPerm($perm)) { return false; } } else { $permLevel = PMF_Configuration::getInstance()->get('security.permLevel'); $perm = PMF_Perm::selectPerm($permLevel); if (!$this->addPerm($perm)) { return false; } } // authentication objects // always make a 'local' $auth object (see: $auth_data) $this->auth_container = array(); $authLocal = PMF_Auth::selectAuth($this->auth_data['authSource']['name']); $authLocal->selectEncType($this->auth_data['encType']); $authLocal->setReadOnly($this->auth_data['readOnly']); if (!$this->addAuth($authLocal, $this->auth_data['authSource']['type'])) { return false; } // additionally, set given $auth objects if (count($auth) > 0) { foreach ($auth as $name => $auth_object) { if (!$this->addAuth($auth_object, $name)) { break; } } } // user data object $this->userdata = new PMF_User_UserData(); }
/** * @param $key * @param $type * @return void */ function printInputFieldByType($key, $type) { global $PMF_LANG; $faqconfig = PMF_Configuration::getInstance(); switch ($type) { case 'area': printf('<textarea name="edit[%s]" cols="60" rows="6" style="width: 300px;">%s</textarea>', $key, str_replace('<', '<', str_replace('>', '>', $faqconfig->get($key)))); printf("</p>\n"); break; case 'input': if ('' == $faqconfig->get($key) && 'socialnetworks.twitterAccessTokenKey' == $key) { $value = $_SESSION['access_token']['oauth_token']; } elseif ('' == $faqconfig->get($key) && 'socialnetworks.twitterAccessTokenSecret' == $key) { $value = $_SESSION['access_token']['oauth_token_secret']; } else { $value = str_replace('"', '"', $faqconfig->get($key)); } printf('<input type="text" name="edit[%s]" size="75" value="%s" style="width: 300px;" />', $key, $value); printf("</p>\n"); break; case 'select': printf('<select name="edit[%s]" size="1" style="width: 300px;">', $key); switch ($key) { case 'main.language': $languages = PMF_Language::getAvailableLanguages(); if (count($languages) > 0) { print PMF_Language::languageOptions(str_replace(array('language_', '.php'), '', $faqconfig->get('main.language')), false, true); } else { print '<option value="language_en.php">English</option>'; } break; case 'records.orderby': print sortingOptions($faqconfig->get($key)); break; case 'records.sortby': printf('<option value="DESC"%s>%s</option>', 'DESC' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['ad_conf_desc']); printf('<option value="ASC"%s>%s</option>', 'ASC' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['ad_conf_asc']); break; case 'security.permLevel': print PMF_Perm::permOptions($faqconfig->get($key)); break; case "main.templateSet": /** * TODO: do get available template sets in the PMF_Template */ foreach (new DirectoryIterator('../template') as $item) { if (!$item->isDot() && $item->isDir()) { $selected = PMF_Template::getTplSetName() == $item ? ' selected="selected"' : ''; printf("<option%s>%s</option>", $selected, $item); } } break; case "records.attachmentsStorageType": foreach ($PMF_LANG['att_storage_type'] as $i => $item) { $selected = $faqconfig->get($key) == $i ? ' selected="selected"' : ''; printf('<option value="%d"%s>%s</option>', $i, $selected, $item); } break; case "records.orderingPopularFaqs": printf('<option value="visits"%s>%s</option>', 'visits' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['records.orderingPopularFaqs.visits']); printf('<option value="voting"%s>%s</option>', 'voting' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['records.orderingPopularFaqs.voting']); break; case "search.relevance": printf('<option value="thema,content,keywords"%s>%s</option>', 'thema,content,keywords' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['search.relevance.thema-content-keywords']); printf('<option value="thema,keywords,content"%s>%s</option>', 'thema,keywords,content' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['search.relevance.thema-keywords-content']); printf('<option value="content,thema,keywords"%s>%s</option>', 'content,thema,keywords' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['search.relevance.content-thema-keywords']); printf('<option value="content,keywords,thema"%s>%s</option>', 'content,keywords,thema' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['search.relevance.content-keywords-thema']); printf('<option value="keywords,content,thema"%s>%s</option>', 'keywords,content,thema' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['search.relevance.keywords-content-thema']); printf('<option value="keywords,thema,content"%s>%s</option>', 'keywords,thema,content' == $faqconfig->get($key) ? ' selected="selected"' : '', $PMF_LANG['search.relevance.keywords-thema-content']); break; } print "</select>\n</p>\n"; break; case 'checkbox': printf('<input type="checkbox" name="edit[%s]" value="true"', $key); if ($faqconfig->get($key)) { print ' checked="checked"'; } print " /></p>\n"; break; case 'print': printf('<input type="hidden" name="edit[%s]" size="80" value="%s" />%s</p>', $key, str_replace('"', '"', $faqconfig->get($key)), $faqconfig->get($key)); break; } }
/** * This function checks the provided captcha code * if the captcha code spam protection has been activated from the general PMF configuration. * * @param string $code Captcha Code * @return bool */ public function checkCaptchaCode($code) { if (PMF_Configuration::getInstance()->get('spam.enableCaptchaCode')) { return $this->validateCaptchaCode($code); } else { return true; } }
$userId = PMF_Filter::filterInput(INPUT_POST, 'user_id', FILTER_VALIDATE_INT, 0); $userAction = $defaultUserAction; if ($userId == 0) { $message .= '<p class="error">' . $errorMessages['delUser_noId'] . '</p>'; } else { if (!$user->getUserById($userId)) { $message .= '<p class="error">' . $errorMessages['delUser_noId'] . '</p>'; } if (!$user->deleteUser()) { $message .= '<p class="error">' . $errorMessages['delUser'] . '</p>'; } else { // Move the categories ownership to admin (id == 1) $categoryHelper = new PMF_Category_Helper(); $categoryHelper->moveOwnership($userId, 1); // Remove the user from groups if ('medium' == PMF_Configuration::getInstance()->get('main.permLevel')) { $oPerm = PMF_Perm::selectPerm('medium'); $oPerm->removeFromAllGroups($userId); } $message .= '<p class="success">' . $successMessages['delUser'] . '</p>'; } $userError = $user->error(); if ($userError != "") { $message .= '<p>ERROR: ' . $userError . '</p>'; } } } // save new user if ($userAction == 'addsave') { $user = new PMF_User(); $message = '';
/** * Renders the main navigation * * @param string $legend Text of the HTML Legend element * @param string $img HTML code for the Captcha image * @param string $error Error message * * @return string */ public function renderCaptcha(PMF_Captcha $captcha, $action, $legend, $error = '') { $html = ''; if (PMF_Configuration::getInstance()->get('spam.enableCaptchaCode')) { if ($error != '') { $html .= sprintf('<div class="error">%s</div>', $error); } $html .= sprintf('<div class="captchaInfo">%s:</div>', $legend); $html .= sprintf('<div class="captchaImage">%s', $captcha->printCaptcha($action)); $html .= sprintf('<div class="captchaRefresh"><a href="javascript:;" onclick="refreshCaptcha(\'%s\');">%s</a></div>', $action, 'click to refresh'); $html .= ' ' . sprintf('<input type="text" name="captcha" id="captcha" class="captcha" size="%d" required="required" /><br/>', $captcha->caplength); $html .= '</div>'; } return $html; }
/** * @return string */ public function renderFacebookLikeButton($url) { if (empty($url) || PMF_Configuration::getInstance()->get('socialnetworks.enableFacebookSupport') == false) { return ''; } if ($this->_ssl) { $http = 'https://'; } else { $http = 'http://'; } return sprintf('<iframe src="%sfacebook.com/plugins/like.php?href=%s&layout=standard&show_faces=true&width=250&action=like&font=arial&colorscheme=light&height=30" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:250px; height:30px;" allowTransparency="true"></iframe>', $http, urlencode($url)); }
if (PMF_Configuration::getInstance()->get('main.enableRewriteRules')) { header('Location: ' . PMF_Link::getSystemUri('/index.php') . '/solution_id_' . $inputSearchTerm . '.html'); } else { header('Location: ' . PMF_Link::getSystemUri('/index.php') . '/index.php?solution_id=' . $inputSearchTerm); } exit; } $category->buildTree(); $mostPopularSearchData = $faqSearch->getMostPopularSearches($faqconfig->get('search.numberSearchTerms')); // Set base URL scheme if (PMF_Configuration::getInstance()->get('main.enableRewriteRules')) { $baseUrl = sprintf("%ssearch.html?search=%s&seite=%d%s&searchcategory=%d", PMF_Link::getSystemRelativeUri('index.php'), urlencode($inputSearchTerm), $page, $languages, $inputCategory); } else { $baseUrl = sprintf('%s?%saction=search&search=%s&seite=%d%s&searchcategory=%d', PMF_Link::getSystemRelativeUri(), empty($sids) ? '' : '$sids&', urlencode($inputSearchTerm), $page, $languages, $inputCategory); } // Pagination options $options = array('baseUrl' => $baseUrl, 'total' => $faqSearchResult->getNumberOfResults(), 'perPage' => PMF_Configuration::getInstance()->get('records.numberOfRecordsPerPage'), 'pageParamName' => 'seite', 'nextPageLinkTpl' => '<a href="{LINK_URL}">' . $PMF_LANG['msgNext'] . '</a>', 'prevPageLinkTpl' => '<a href="{LINK_URL}">' . $PMF_LANG['msgPrevious'] . '</a>', 'layoutTpl' => '<p align="center"><strong>{LAYOUT_CONTENT}</strong></p>'); $faqPagination = new PMF_Pagination($options); $faqCategoryHelper = PMF_Helper_Category::getInstance(); $faqCategoryHelper->setCategory($category); $faqSearchHelper = PMF_Helper_Search::getInstance(); $faqSearchHelper->setSearchterm($inputSearchTerm); $faqSearchHelper->setCategory($category); $faqSearchHelper->setPagination($faqPagination); $faqSearchHelper->setPlurals($plr); $faqSearchHelper->setSessionId($sids); if ('' == $searchResult && !is_null($inputSearchTerm)) { $searchResult = $faqSearchHelper->renderSearchResult($faqSearchResult, $page); } $tpl->processTemplate('writeContent', array('msgAdvancedSearch' => $tagSearch ? $PMF_LANG['msgTagSearch'] : $PMF_LANG['msgAdvancedSearch'], 'msgSearch' => $PMF_LANG['msgSearch'], 'searchString' => PMF_String::htmlspecialchars($inputSearchTerm, ENT_QUOTES, 'utf-8'), 'searchOnAllLanguages' => $PMF_LANG['msgSearchOnAllLanguages'], 'checkedAllLanguages' => $allLanguages ? ' checked="checked"' : '', 'selectCategories' => $PMF_LANG['msgSelectCategories'], 'allCategories' => $PMF_LANG['msgAllCategories'], 'printCategoryOptions' => $faqCategoryHelper->renderCategoryOptions($inputCategory), 'writeSendAdress' => '?' . $sids . 'action=search', 'msgSearchWord' => $PMF_LANG['msgSearchWord'], 'printResult' => $searchResult, 'openSearchLink' => $faqSearchHelper->renderOpenSearchLink(), 'msgMostPopularSearches' => $PMF_LANG['msgMostPopularSearches'], 'printMostPopularSearches' => $faqSearchHelper->renderMostPopularSearches($mostPopularSearchData))); $tpl->includeTemplate('writeContent', 'index');
$isNew = true; if (!is_null($faqid)) { $isNew = false; $faqsession->userTracking('save_new_translation_entry', 0); } else { $faqsession->userTracking('save_new_entry', 0); } $isTranslation = false; if (!is_null($faqlanguage)) { $isTranslation = true; $newLanguage = $faqlanguage; } if (PMF_String::substr($contentlink, 7) != "") { $content = $content . "<br />" . $PMF_LANG["msgInfo"] . "<a href=\"http://" . PMF_String::substr($contentlink, 7) . "\" target=\"_blank\">" . $contentlink . "</a>"; } $autoActivate = PMF_Configuration::getInstance()->get('records.defaultActivation'); $newData = array('lang' => $isTranslation == true ? $newLanguage : $LANGCODE, 'thema' => $thema, 'active' => $autoActivate ? FAQ_SQL_ACTIVE_YES : FAQ_SQL_ACTIVE_NO, 'sticky' => 0, 'content' => nl2br($content), 'keywords' => $keywords, 'author' => $username, 'email' => $usermail, 'comment' => FAQ_SQL_YES, 'date' => date('YmdHis'), 'dateStart' => '00000000000000', 'dateEnd' => '99991231235959', 'linkState' => '', 'linkDateCheck' => 0); $categoryNode = new PMF_Category_Node(); $categoryRelation = new PMF_Category_Relations(); $faqRecord = new PMF_Faq_Record(); if ($isNew) { $newData['id'] = null; $categories = $categoryNode->fetchAll($categories['rubrik']); } else { $newData['id'] = $faqid; foreach ($categoryRelation->fetchAll() as $relation) { if ($relation->record_id == $newData['id']) { $categories[] = $relation; } } }
$totUsersOnLine = $usersOnLine[0] + $usersOnLine[1]; $systemUri = PMF_Link::getSystemUri('index.php'); $categoryTree = new PMF_Category_Tree($categoryData); // If it's an ajax request , get the whole tree else get the filtered tree if ($tpl->ajax_active && $tpl->ajax_request == 'ajax_init') { $categoryLayout = new PMF_Category_Layout(new PMF_Category_Tree_Helper($categoryTree)); } else { $categoryLayout = new PMF_Category_Layout(new PMF_Category_Tree_Helper(new PMF_Category_Path($categoryTree, $categoryPath))); } $keywordsArray = array_merge(explode(',', $keywords), explode(',', $faqconfig->get('main.metaKeywords'))); $keywordsArray = array_filter($keywordsArray, 'strlen'); shuffle($keywordsArray); $keywords = implode(',', $keywordsArray); $main_template_vars = array('msgRegisterUser' => '<a href="?' . $sids . 'action=register">' . $PMF_LANG['msgRegisterUser'] . '</a>', 'msgLoginUser' => $PMF_LANG['msgLoginUser'], 'title' => $faqconfig->get('main.titleFAQ') . $title, 'baseHref' => $systemUri, 'version' => $faqconfig->get('main.currentVersion'), 'header' => str_replace('"', '', $faqconfig->get('main.titleFAQ')), 'metaTitle' => str_replace('"', '', $faqconfig->get('main.titleFAQ')), 'metaDescription' => $metaDescription, 'metaKeywords' => $keywords, 'metaPublisher' => $faqconfig->get('main.metaPublisher'), 'metaLanguage' => $PMF_LANG['metaLanguage'], 'metaCharset' => 'utf-8', 'phpmyfaqversion' => $faqconfig->get('main.currentVersion'), 'stylesheet' => $PMF_LANG['dir'] == 'rtl' ? 'style.rtl' : 'style', 'action' => $action, 'dir' => $PMF_LANG['dir'], 'msgCategory' => $PMF_LANG['msgCategory'], 'showCategories' => $categoryLayout->renderNavigation($cat), 'languageBox' => $PMF_LANG['msgLangaugeSubmit'], 'writeLangAdress' => $writeLangAdress, 'switchLanguages' => PMF_Language::selectLanguages($LANGCODE, true), 'userOnline' => $plr->getMsg('plmsgUserOnline', $totUsersOnLine) . $plr->getMsg('plmsgGuestOnline', $usersOnLine[0]) . $plr->getMsg('plmsgRegisteredOnline', $usersOnLine[1]), 'stickyRecordsHeader' => $PMF_LANG['stickyRecordsHeader'], 'copyright' => 'powered by <a href="http://www.phpmyfaq.de" target="_blank">phpMyFAQ</a> ' . $faqconfig->get('main.currentVersion')); if ('main' == $action || 'show' == $action) { if ('main' == $action && PMF_Configuration::getInstance()->get('main.useAjaxSearchOnStartpage')) { $tpl->processBlock('index', 'globalSuggestBox', array('ajaxlanguage' => $LANGCODE)); } else { $tpl->processBlock('index', 'globalSearchBox', array('writeSendAdress' => '?' . $sids . 'action=search', 'searchBox' => $PMF_LANG['msgSearch'], 'categoryId' => $cat === 0 ? '%' : (int) $cat, 'msgSearch' => '<a class="help" href="index.php?' . $sids . 'action=search">' . $PMF_LANG["msgAdvancedSearch"] . '</a>')); } } $stickyRecordsParams = $faq->getStickyRecords(); if (!isset($stickyRecordsParams['error'])) { $tpl->processBlock('index', 'stickyRecordsList', array('stickyRecordsUrl' => $stickyRecordsParams['url'], 'stickyRecordsTitle' => $stickyRecordsParams['title'])); } if ($faqconfig->get('main.enableRewriteRules')) { $links_template_vars = array("faqHome" => $faqconfig->get('main.referenceURL'), "msgSearch" => '<a href="' . $systemUri . 'search.html">' . $PMF_LANG["msgAdvancedSearch"] . '</a>', 'msgAddContent' => '<a href="' . $systemUri . 'addcontent.html">' . $PMF_LANG["msgAddContent"] . '</a>', "msgQuestion" => '<a href="' . $systemUri . 'ask.html">' . $PMF_LANG["msgQuestion"] . '</a>', "msgOpenQuestions" => '<a href="' . $systemUri . 'open.html">' . $PMF_LANG["msgOpenQuestions"] . '</a>', 'msgHelp' => '<a href="' . $systemUri . 'help.html">' . $PMF_LANG["msgHelp"] . '</a>', "msgContact" => '<a href="' . $systemUri . 'contact.html">' . $PMF_LANG["msgContact"] . '</a>', "backToHome" => '<a href="' . $systemUri . 'index.html">' . $PMF_LANG["msgHome"] . '</a>', "allCategories" => '<a href="' . $systemUri . 'showcat.html">' . $PMF_LANG["msgShowAllCategories"] . '</a>', 'showInstantResponse' => '<a href="' . $systemUri . 'instantresponse.html">' . $PMF_LANG['msgInstantResponse'] . '</a>', 'showSitemap' => '<a href="' . $systemUri . 'sitemap/A/' . $LANGCODE . '.html">' . $PMF_LANG['msgSitemap'] . '</a>', 'opensearch' => $systemUri . 'opensearch.html'); } else { $links_template_vars = array("faqHome" => $faqconfig->get('main.referenceURL'), "msgSearch" => '<a href="index.php?' . $sids . 'action=search">' . $PMF_LANG["msgAdvancedSearch"] . '</a>', "msgAddContent" => '<a href="index.php?' . $sids . 'action=add">' . $PMF_LANG["msgAddContent"] . '</a>', "msgQuestion" => '<a href="index.php?' . $sids . 'action=ask">' . $PMF_LANG["msgQuestion"] . '</a>', "msgOpenQuestions" => '<a href="index.php?' . $sids . 'action=open">' . $PMF_LANG["msgOpenQuestions"] . '</a>', "msgHelp" => '<a href="index.php?' . $sids . 'action=help">' . $PMF_LANG["msgHelp"] . '</a>', "msgContact" => '<a href="index.php?' . $sids . 'action=contact">' . $PMF_LANG["msgContact"] . '</a>', "allCategories" => '<a href="index.php?' . $sids . 'action=show">' . $PMF_LANG["msgShowAllCategories"] . '</a>', "backToHome" => '<a href="index.php?' . $sids . '">' . $PMF_LANG["msgHome"] . '</a>', 'showInstantResponse' => '<a href="index.php?' . $sids . 'action=instantresponse">' . $PMF_LANG['msgInstantResponse'] . '</a>', 'showSitemap' => '<a href="index.php?' . $sids . 'action=sitemap&lang=' . $LANGCODE . '">' . $PMF_LANG['msgSitemap'] . '</a>', 'opensearch' => $systemUri . 'opensearch.php'); } //
/** * Adds a new adminlog entry * * @param PMF_User $user PMF_User object * @param string $logText Logged string * * @return boolean */ public function logAdmin(PMF_User $user, $logText = '') { if (PMF_Configuration::getInstance()->get('main.enableAdminLog')) { $query = sprintf("\n INSERT INTO\n %sfaqadminlog\n (id, time, usr, text, ip)\n VALUES \n (%d, %d, %d, '%s', '%s')", SQLPREFIX, $this->db->nextID(SQLPREFIX . 'faqadminlog', 'id'), $_SERVER['REQUEST_TIME'], $user->userdata->get('user_id'), $this->db->escapeString(nl2br($logText)), $_SERVER['REMOTE_ADDR']); return $this->db->query($query); } else { return false; } }
/** * Verifies specified article content and update links_state database entry * * @param string $contents * @param integer $id * @param string $artlang * @param boolean $cron * * @result string HTML text, if $cron is false (default) */ public function verifyArticleURL($contents = '', $id = 0, $artlang = '', $cron = false) { global $PMF_LANG; $faqconfig = PMF_Configuration::getInstance(); if ($faqconfig->get('main.referenceURL') == '') { $output = $PMF_LANG['ad_linkcheck_noReferenceURL']; return $cron ? '' : '<br /><br />' . $output; } if (trim('' == $faqconfig->get('main.referenceURL'))) { $output = $PMF_LANG['ad_linkcheck_noReferenceURL']; return $cron ? '' : '<br /><br />' . $output; } if ($this->isReady() === false) { $output = $PMF_LANG['ad_linkcheck_noAllowUrlOpen']; return $cron ? '' : '<br /><br />' . $output; } // Parse contents and verify URLs $this->parse_string($contents); $result = $this->VerifyURLs($faqconfig->get('main.referenceURL')); $this->markEntry($id, $artlang); // If no URLs found if ($result == false) { $output = sprintf('<h2>%s</h2><br />%s', $PMF_LANG['ad_linkcheck_checkResult'], $PMF_LANG['ad_linkcheck_noLinksFound']); return $cron ? '' : utf8_decode($output); } //uncomment to see the result structure //print str_replace("\n","<br />",PMF_String::htmlspecialchars(print_r($result, true))); $failreasons = $inforeasons = array(); $output = " <h2>" . $PMF_LANG['ad_linkcheck_checkResult'] . "</h2>\n"; $output .= ' <table class="verifyArticleURL">' . "\n"; foreach ($result as $type => $_value) { $output .= " <tr><td><strong>" . PMF_String::htmlspecialchars($type) . "</strong></td></tr>\n"; foreach ($_value as $url => $value) { $_output = ' <td />'; $_output .= ' <td><a href="' . $value['absurl'] . '" target="_blank">' . PMF_String::htmlspecialchars($value['absurl']) . "</a></td>\n"; $_output .= ' <td>'; if (isset($value['redirects']) && $value['redirects'] > 0) { $_redirects = "(" . $value['redirects'] . ")"; } else { $_redirects = ""; } if ($value['valid'] === true) { $_classname = "urlsuccess"; $_output .= '<td class="' . $_classname . '">' . $PMF_LANG['ad_linkcheck_checkSuccess'] . $_redirects . '</td>'; if ($value['reason'] != "") { $inforeasons[] = sprintf($PMF_LANG['ad_linkcheck_openurl_infoprefix'], PMF_String::htmlspecialchars($value['absurl'])) . $value['reason']; } } else { $_classname = "urlfail"; $_output .= '<td class="' . $_classname . '">' . $PMF_LANG['ad_linkcheck_checkFailed'] . '</td>'; if ($value['reason'] != "") { $failreasons[] = $value['reason']; } } $_output .= '</td>'; $output .= ' <tr class="' . $_classname . '">' . "\n" . $_output . "\n"; $output .= " </tr>\n"; } } $output .= " </table>\n"; if (count($failreasons) > 0) { $output .= " <br />\n <strong>" . $PMF_LANG['ad_linkcheck_failReason'] . "</strong>\n <ul>\n"; foreach ($failreasons as $reason) { $output .= " <li>" . $reason . "</li>\n"; } $output .= " </ul>\n"; } if (count($inforeasons) > 0) { $output .= " <br />\n <strong>" . $PMF_LANG['ad_linkcheck_infoReason'] . "</strong>\n <ul>\n"; foreach ($inforeasons as $reason) { $output .= " <li>" . $reason . "</li>\n"; } $output .= " </ul>\n"; } if ($cron) { return ''; } else { return utf8_decode($output); } }
// helper functions => move the fns into the class. require_once PMF_INCLUDE_DIR . '/Linkverifier.php'; // // Set the error handler to our pmf_error_handler() function // set_error_handler('pmf_error_handler'); // // Create a database connection // define('SQLPREFIX', $DB['prefix']); $db = PMF_Db::dbSelect($DB['type']); $db->connect($DB['server'], $DB['user'], $DB['password'], $DB['db']); // // Fetch the configuration // $faqconfig = PMF_Configuration::getInstance(); $faqconfig->getAll(); // // We always need a valid session! // // Avoid any PHP version to move sessions on URLs ini_set('session.use_only_cookies', 1); ini_set('session.use_trans_sid', 0); ini_set('url_rewriter.tags', ''); // // Connect to LDAP server, when LDAP support is enabled // if ($faqconfig->get('main.ldapSupport') && file_exists(PMF_CONFIG_DIR . '/ldap.php')) { require PMF_CONFIG_DIR . '/ldap.php'; require PMF_CONFIG_DIR . '/constants_ldap.php'; } else {
/** * Returns the part of the SQL query with the order by * * The order is calculate by weight depend on the search.relevance order * * @return string */ public function getMatchingOrder() { $config = PMF_Configuration::getInstance()->get('search.relevance'); $list = explode(",", $config); $order = ''; foreach ($list as $field) { $string = 'rel_' . $field . ' DESC'; if (empty($order)) { $order .= $string; } else { $order .= ', ' . $string; } } return $order; }
/** * Builds the PDF delivery for the given faq. * * @param integer $currentCategory The category under which we want the PDF to be created. * @param string $pdfFile The path to the PDF file. Optional, default: pdf/<faq_id>.pdf. * @return mixed */ public function buildPDFFile($currentCategory, $pdfFile = null) { global $PMF_LANG; // Sanity check: stop here if getRecord() has not been called yet if (empty($this->faqRecord)) { return false; } $faqconfig = PMF_Configuration::getInstance(); $category = new PMF_Category(); // Default filename: pdf/<faq_id>.pdf if (empty($pdfFile)) { $pdfFile = 'pdf/' . $this->faqRecord['id'] . '.pdf'; } // Cleanup any file if (file_exists($pdfFile)) { @unlink($pdfFile); } $pdf = new PMF_Export_Pdf($currentCategory, $this->faqRecord['title'], $category->categoryName); $pdf->faq = $this->faqRecord; // Start building PDF... $pdf->Open(); // Set any item $pdf->SetTitle($this->faqRecord['title']); $pdf->SetCreator($faqconfig->get('main.titleFAQ') . ' - powered by phpMyFAQ ' . $faqconfig->get('main.currentVersion')); $pdf->AliasNbPages(); $pdf->AddPage(); $pdf->SetFont('dejavusans', '', 12); $pdf->SetDisplayMode('real'); $pdf->Ln(); $pdf->WriteHTML(str_replace('../', '', $this->faqRecord['content']), true); $pdf->Ln(); $pdf->Ln(); $pdf->SetFont('dejavusans', '', 11); $pdf->Write(5, $PMF_LANG['ad_entry_solution_id'] . ': #' . $this->faqRecord['solution_id']); $pdf->SetAuthor($this->faqRecord['author']); $pdf->Ln(); $pdf->Write(5, $PMF_LANG['msgAuthor'] . ': ' . $this->faqRecord['author']); $pdf->Ln(); $pdf->Write(5, $PMF_LANG['msgLastUpdateArticle'] . $this->faqRecord['date']); // Build it $pdf->Output($pdfFile); // Done? if (!file_exists($pdfFile)) { return false; } return $pdfFile; }
$comment = PMF_Filter::filterInput(INPUT_POST, 'comment', FILTER_SANITIZE_STRIPPED); $message = ''; switch ($type) { case 'news': $id = $newsid; $msgWriteComment = $PMF_LANG['newsWriteComment']; break; case 'faq': default: $id = $faqid; $msgWriteComment = $PMF_LANG['msgWriteComment']; break; } // If e-mail address is set to optional if (!PMF_Configuration::getInstance()->get('main.optionalMailAddress') && is_null($mail)) { $mail = PMF_Configuration::getInstance()->get('main.administrationMail'); } if (!is_null($user) && !is_null($mail) && !is_null($comment) && checkBannedWord(PMF_String::htmlspecialchars($comment)) && IPCheck($_SERVER['REMOTE_ADDR']) && $captcha->checkCaptchaCode($code) && !$faq->commentDisabled($id, $LANGCODE, $type)) { $faqsession->userTracking("save_comment", $id); $commentData = array('record_id' => $id, 'type' => $type, 'username' => $user, 'usermail' => $mail, 'comment' => nl2br($comment), 'date' => $_SERVER['REQUEST_TIME'], 'helped' => ''); if ($faq->addComment($commentData)) { $emailTo = $faqconfig->get('main.administrationMail'); $urlToContent = ''; if ('faq' == $type) { $faq->getRecord($id); if ($faq->faqRecord['email'] != '') { $emailTo = $faq->faqRecord['email']; } $_faqUrl = sprintf('%saction=artikel&cat=%d&id=%d&artlang=%s', $sids, 0, $faq->faqRecord['id'], $faq->faqRecord['lang']); $oLink = new PMF_Link(PMF_Link::getSystemUri() . '?' . $_faqUrl); $oLink->itemTitle = $faq->faqRecord['title'];
/** * Returns the number of anonymous users and registered ones. * These are the numbers of unique users who have perfomed * some activities within the last five minutes * * @param integer $activityTimeWindow Optionally set the time window size in sec. * Default: 300sec, 5 minutes * * @return array */ public function getUsersOnline($activityTimeWindow = 300) { $users = array(0, 0); if (PMF_Configuration::getInstance()->get('main.enableUserTracking')) { $timeNow = $_SERVER['REQUEST_TIME'] - $activityTimeWindow; // Count all sids within the time window // TODO: add a new field in faqsessions in order to find out only sids of anonymous users $query = sprintf("\n SELECT\n count(sid) AS anonymous_users\n FROM\n %sfaqsessions\n WHERE\n user_id = -1\n AND \n time > %d", SQLPREFIX, $timeNow); $result = $this->db->query($query); if (isset($result)) { $row = $this->db->fetchObject($result); $users[0] = $row->anonymous_users; } // Count all faquser records within the time window $query = sprintf("\n SELECT\n count(session_id) AS registered_users\n FROM\n %sfaquser\n WHERE\n session_timestamp > %d", SQLPREFIX, $timeNow); $result = $this->db->query($query); if (isset($result)) { $row = $this->db->fetchObject($result); $users[1] = $row->registered_users; } } return $users; }