/** * transform text to images * * @param string $args['text'] */ function transform($args) { $text = $args['text']; // check the user agent - if it is a bot, return immediately $robotslist = array("ia_archiver", "googlebot", "mediapartners-google", "yahoo!", "msnbot", "jeeves", "lycos"); $useragent = System::serverGetVar('HTTP_USER_AGENT'); for ($cnt = 0; $cnt < count($robotslist); $cnt++) { if (strpos(strtolower($useragent), $robotslist[$cnt]) !== false) { return $text; } } $smilies = $this->getVar('smilie_array'); $remove_inactive = $this->getVar('remove_inactive'); if (is_array($smilies) && count($smilies) > 0) { // sort smilies, see http://code.zikula.org/BBSmile/ticket/1 uasort($smilies, array($this, 'cmp_smiliesort')); $imagepath = System::getBaseUrl() . DataUtil::formatForOS($this->getVar('smiliepath')); $imagepath_auto = System::getBaseUrl() . DataUtil::formatForOS($this->getVar('smiliepath_auto')); $auto_active = $this->getVar('activate_auto'); // pad it with a space so we can distinguish between FALSE and matching the 1st char (index 0). // This is important! $text = ' ' . $text; foreach ($smilies as $smilie) { // check if smilie is active if ($smilie['active'] == 1) { // check if alt is a define $smilie['alt'] = defined($smilie['alt']) ? constant($smilie['alt']) : $smilie['alt']; if ($smilie['type'] == 0) { $text = str_replace($smilie['short'], ' <img src="' . $imagepath . '/' . $smilie['imgsrc'] . '" alt="' . $smilie['alt'] . '" /> ', $text); } else { if ($auto_active == 1) { $text = str_replace($smilie['short'], ' <img src="' . $imagepath_auto . '/' . $smilie['imgsrc'] . '" alt="' . $smilie['alt'] . '" /> ', $text); } } if (!empty($smilie['alias'])) { $aliases = explode(",", trim($smilie['alias'])); if (is_array($aliases) && count($aliases) > 0) { foreach ($aliases as $alias) { if ($smilie['type'] == 0) { $text = str_replace($alias, ' <img src="' . $imagepath . '/' . $smilie['imgsrc'] . '" alt="' . $smilie['alt'] . '" /> ', $text); } else { if ($auto_active == 1) { $text = str_replace($alias, ' <img src="' . $imagepath_auto . '/' . $smilie['imgsrc'] . '" alt="' . $smilie['alt'] . '" /> ', $text); } } } } } } else { // End of if smilie is active $text = str_replace($smilie['short'], '', $text); } } // foreach // Remove our padding from the string.. $text = substr($text, 1); } // End of if smilies is array and not empty return $text; }
/** * This function e-mails the site administrator with an error. */ function send_email() { /* send error reporting email to admin */ $adminmail = System::getVar('adminmail'); $notify_from = System::getVar('notify_from'); $sitename = System::getVar('sitename'); $errortime = date("m/j/Y at g:i a"); $doc = System::serverGetVar('REDIRECT_URL'); $server = System::serverGetVar('HTTP_HOST'); $doc = "http://{$server}{$doc}"; $headers = "ATTN: Fatal Error at {$doc} (" . System::serverGetVar('REDIRECT_STATUS') . ")\n"; $headers .= "From: {$sitename} Error Tools {$adminmail}\n"; $headers .= "X-Sender: <{$notify_from}>\n"; $headers .= "X-Mailer-Version: " . Zikula_Core::VERSION_ID . " " . Zikula_Core::VERSION_NUM . "\n"; $headers .= "X-Priority: 1\n"; $body = "Webmaster, the following item was not found on your website:\n\n"; $body .= " at " . $errortime; $body .= "WEBSITE\n-- " . System::serverGetVar('SERVER_NAME') . ':' . System::serverGetVar('SERVER_PORT') . "\n\n"; $body .= "REASON\n-- " . System::serverGetVar('$REDIRECT_ERRORSOR_NOTES') . "\n\n"; $body .= "PROBLEM URL\n-- {$doc}\n\n"; $body .= "REFERRER\n-- " . System::serverGetVar('HTTP_REFERER') . "\n\n"; $body .= "REQUEST\n-- Host: " . System::serverGetVar('HTTP_HOST') . "\n-- Query String: " . System::serverGetVar('REDIRECT_QUERY_STRING') . "\n"; $body .= "-- Method: " . System::serverGetVar('$REQUEST_METHOD') . "\n\n"; $body .= "USER\n-- Host: " . System::serverGetVar('REMOTE_HOST') . "\n-- IP: " . System::serverGetVar('REMOTE_ADDR') . "\n-- User: "******"\n-- Agent: " . System::serverGetVar('HTTP_USER_AGENT') . "\n-- Cookies: " . System::serverGetVar('HTTP_COOKIE') . "\n\n"; $body .= "Envolution\n-- version: " . Zikula_Core::VERSION_NUM; // Send the mail message. System::mail($adminmail, $headers, $body); }
/** * update category */ public function editAction() { $this->checkCsrfToken(); if (!SecurityUtil::checkPermission('Categories::', '::', ACCESS_ADMIN)) { throw new \Zikula\Framework\Exception\ForbiddenException(); } $args = array(); if ($this->request->request->get('category_copy', null)) { $args['op'] = 'copy'; $args['cid'] = $_POST['category']['id']; return $this->redirect(ModUtil::url('Categories', 'admin', 'op', $args)); } if ($this->request->request->get('category_move', null)) { $args['op'] = 'move'; $args['cid'] = $_POST['category']['id']; return $this->redirect(ModUtil::url('Categories', 'admin', 'op', $args)); } if ($this->request->request->get('category_delete', null)) { $args['op'] = 'delete'; $args['cid'] = $_POST['category']['id']; return $this->redirect(ModUtil::url('Categories', 'admin', 'op', $args)); } if ($this->request->request->get('category_user_edit', null)) { $_SESSION['category_referer'] = System::serverGetVar('HTTP_REFERER'); $args['dr'] = $_POST['category']['id']; return $this->redirect(ModUtil::url('Categories', 'user', 'edit', $args)); } $cat = new Category(); $data = $cat->getDataFromInput(); if (!$cat->validate('admin')) { $category = $this->request->request->get('category', null); $args['cid'] = $category['id']; $args['mode'] = 'edit'; return $this->redirect(ModUtil::url('Categories', 'admin', 'edit', $args)); } $attributes = array(); $values = $this->request->request->get('attribute_value'); foreach ($this->request->request->get('attribute_name') as $index => $name) { if (!empty($name)) { $attributes[$name] = $values[$index]; } } $cat->setDataField('__ATTRIBUTES__', $attributes); // retrieve old category from DB $category = $this->request->request->get('category', null); $oldCat = new Category(DBObject::GET_FROM_DB, $category['id']); // update new category data $cat->update(); // since a name change will change the object path, we must rebuild it here if ($oldCat->_objData['name'] != $cat->_objData['name']) { $obj = $cat->_objData; CategoryUtil::rebuildPaths('path', 'name', $obj['id']); } $msg = __f('Done! Saved the %s category.', $oldCat->_objData['name']); LogUtil::registerStatus($msg); return $this->redirect(ModUtil::url('Categories', 'admin', 'view')); }
/** * Return an array of items to show in the your account panel. * * @return array indexed array of items */ public function getall($args) { $items = array(); // Create an array of links to return if (SecurityUtil::checkPermission('Categories::', '::', ACCESS_EDIT) && $this->getVar('allowusercatedit')) { $referer = System::serverGetVar('HTTP_REFERER'); if (strpos($referer, 'module=Categories') === false) { SessionUtil::setVar('categories_referer', $referer); } $items['0'] = array('url' => ModUtil::url('Categories', 'user', 'edituser'), 'module' => 'Categories', 'title' => $this->__('Categories manager'), 'icon' => 'admin.png'); } // Return the items return $items; }
/** * Display an error * This function displays a generic error form * The template used is based on the error type passed * * @param string $args['type'] error type '404' or 'module' * @param string $args['message'] custom error message * * @return string HTML string */ public function main($args) { $type = FormUtil::getPassedValue('errtype', isset($args['type']) ? $args['type'] : LogUtil::getErrorType(), 'GET'); $exception = isset($args['exception']) ? $args['exception'] : null; $message = isset($args['message']) ? $args['message'] : ''; // perform any error specific tasks $protocol = System::serverGetVar('SERVER_PROTOCOL'); switch ($type) { case 301: header("{$protocol} 301 Moved Permanently"); break; case 403: header("{$protocol} 403 Access Denied"); break; case 404: header("{$protocol} 404 Not Found"); break; case 500: header("{$protocol} 500 Internal Server Error"); default: } // load the stylesheet PageUtil::addVar('stylesheet', 'system/Errors/style/style.css'); $this->view->setCaching(Zikula_View::CACHE_DISABLED); // assign the document info $this->view->assign('reportlevel', System::getVar('reportlevel'))->assign('currenturi', System::getCurrentUri())->assign('localreferer', System::localReferer())->assign('sitename', System::getVar('sitename'))->assign('reportlevel', System::getVar('reportlevel'))->assign('funtext', System::getVar('funtext')); $messages = LogUtil::getErrorMessages(); // show the detailed error message for admins only if (System::isDevelopmentMode() || SecurityUtil::checkPermission('::', '::', ACCESS_ADMIN)) { $message ? $messages[] = $message : null; } $trace = array(); if (System::isDevelopmentMode() && $exception instanceof Exception) { $line = $exception->getLine(); $file = $exception->getFile(); $trace = array(0 => '#0 ' . $this->__f('Exception thrown in %1$s, line %2$s.', array($file, $line))); $trace += explode("\n", $exception->getTraceAsString()); } // assign the list of registered errors // and the trace (if development mode is enabled) $this->view->assign('messages', $messages)->assign('trace', $trace); // return the template output if ($this->view->template_exists($template = "errors_user_{$type}.tpl")) { return $this->view->fetch($template); } else { return $this->view->fetch('errors_user_main.tpl'); } }
/** * Create a new session. * * @param string $sessid The session ID. * @param string $ipaddr The IP address of the host with this session. * * @return boolean */ public static function _createNew($sessid, $ipaddr) { $now = date('Y-m-d H:i:s', time()); $obj = array('sessid' => $sessid, 'ipaddr' => $ipaddr, 'uid' => 0, 'lastused' => $now); $GLOBALS['_ZSession']['obj'] = $obj; $GLOBALS['_ZSession']['new'] = true; // Generate a random number, used for some authentication (using prime numer bounds) //self::setVar('rand', RandomUtil::getString(32, 40, false, true, true, false, true, true, true)); // Initialize the array of random values for modules authentication self::setVar('rand', array()); // write hash of useragent into the session for later validation self::setVar('useragent', sha1(System::serverGetVar('HTTP_USER_AGENT'))); // init status & error message arrays self::setVar('uid', 0); return true; }
/** * Zikula_View function to get module variable * * This function obtains a server-specific variable from the system. * * Note that the results should be handled by the safetext or the safehtml * modifier before being displayed. * * * Available parameters: * - name: The name of the module variable to obtain * - assign: (optional) If set then result will be assigned to this template variable * - default: (optional) The default value to return if the server variable is not set * * Example * {servergetvar name='PHP_SELF'} * * @param array $params All attributes passed to this function from the template. * @param Zikula_View $view Reference to the Zikula_View object. * * @return string The module variable. */ function smarty_function_servergetvar($params, Zikula_View $view) { $assign = isset($params['assign']) ? $params['assign'] : null; $default = isset($params['default']) ? $params['default'] : null; $name = isset($params['name']) ? $params['name'] : null; if (!$name) { $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('System::serverGetVar', 'name'))); return false; } $result = System::serverGetVar($name, $default); if ($assign) { $view->assign($assign, $result); } else { return DataUtil::formatForDisplay($result); } }
/** * Change the status of a block. * * Invert the status of a given block id (collapsed/uncollapsed). * * @return void */ public function changestatus() { $bid = FormUtil::getPassedValue('bid'); $uid = UserUtil::getVar('uid'); $dbtable = DBUtil::getTables(); $column = $dbtable['userblocks_column']; $where = "WHERE {$column['bid']}='" . DataUtil::formatForStore($bid) . "' AND {$column['uid']}='" . DataUtil::formatForStore($uid) . "'"; $active = DBUtil::selectField('userblocks', 'active', $where); $obj = array(); $obj['active'] = $active ? 0 : 1; $where = "WHERE {$column['uid']}='" . DataUtil::formatForStore($uid) . "' AND {$column['bid']}='" . DataUtil::formatForStore($bid) . "'"; $res = DBUtil::updateObject($obj, 'userblocks', $where); if (!$res) { return LogUtil::registerError($this->__('Error! An SQL error occurred.')); } // now lets get back to where we came from $this->redirect(System::serverGetVar('HTTP_REFERER')); }
/** * Change the status of a block. * * Invert the status of a given block id (collapsed/uncollapsed). * * @return void */ public function changestatus() { $bid = FormUtil::getPassedValue('bid'); $uid = UserUtil::getVar('uid'); $entity = $this->name . '_Entity_UserBlock'; $item = $this->entityManager->getRepository($entity)->findOneBy(array('uid' => $uid, 'bid' => $bid)); if ($item['active'] == 1) { $item['active'] = 0; } else { $item['active'] = 1; } $this->entityManager->flush(); // now lets get back to where we came from $this->redirect(System::serverGetVar('HTTP_REFERER')); }
/** * {@inheritdoc} */ public function start() { // create IP finger print $current_ipaddr = ''; $_REMOTE_ADDR = System::serverGetVar('REMOTE_ADDR'); $_HTTP_X_FORWARDED_FOR = System::serverGetVar('HTTP_X_FORWARDED_FOR'); // create the ip fingerprint $current_ipaddr = md5($_REMOTE_ADDR . $_HTTP_X_FORWARDED_FOR); // start session check expiry and ip fingerprint if required if (parent::start()) { // check if session has expired or not $now = time(); $inactive = $now - (int) (System::getVar('secinactivemins') * 60); $daysold = $now - (int) (System::getVar('secmeddays') * 86400); $lastused = $this->getMetadataBag()->getLastUsed(); $rememberme = SessionUtil::getVar('rememberme'); $uid = $this->getBag('attributes')->get('uid'); switch (System::getVar('seclevel')) { case 'Low': // Low security - users stay logged in permanently // no special check necessary break; case 'Medium': // Medium security - delete session info if session cookie has // expired or user decided not to remember themself and inactivity timeout // OR max number of days have elapsed without logging back in if (!$rememberme && $lastused < $inactive || $lastused < $daysold || $uid == '0' && $lastused < $inactive) { $this->expire(); } break; case 'High': default: // High security - delete session info if user is inactive //if ($rememberme && ($lastused < $inactive)) { // see #427 if ($lastused < $inactive) { $this->expire(); } break; } } return true; }
public function start() { $config = array('gc_probability' => System::getVar('gc_probability'), 'gc_divisor' => 10000, 'gc_maxlifetime' => System::getVar('secinactivemins')); $path = System::getBaseUri(); if (empty($path)) { $path = '/'; } elseif (substr($path, -1, 1) != '/') { $path .= '/'; } $config['cookie_path'] = $path; $host = System::serverGetVar('HTTP_HOST'); if (($pos = strpos($host, ':')) !== false) { $host = substr($host, 0, $pos); } // PHP configuration variables // Set lifetime of session cookie $seclevel = System::getVar('seclevel'); switch ($seclevel) { case 'High': // Session lasts duration of browser $lifetime = 0; // Referer check // ini_set('session.referer_check', $host.$path); $config['referer_check'] = $host; break; case 'Medium': // Session lasts set number of days $lifetime = System::getVar('secmeddays') * 86400; break; case 'Low': default: // (Currently set to 1 year) $lifetime = 31536000; break; } $config['cookie_lifetime'] = $lifetime; $this->storage->setOptions($config); return parent::start(); }
/** * Get the user's theme. * * This function will return the current theme for the user. * Order of theme priority: * - page-specific * - category * - user * - system * * @param boolean $force True to ignore the cache. * * @return string the name of the user's theme * @throws RuntimeException If this function was unable to calculate theme name. */ public static function getTheme($force = false) { static $theme; if (isset($theme) && !$force) { return $theme; } if (CookieUtil::getCookie('zikulaMobileTheme') == '1' && ModUtil::getVar('Theme', 'enable_mobile_theme', false)) { $pagetheme = 'Mobile'; } else { if (CookieUtil::getCookie('zikulaMobileTheme') != '2' && ModUtil::getVar('Theme', 'enable_mobile_theme', false)) { include_once "system/Theme/lib/vendor/Mobile_Detect.php"; $detect = new Mobile_Detect(); if ($detect->isMobile()) { $pagetheme = 'Mobile'; } } else { $pagetheme = FormUtil::getPassedValue('theme', null, 'GETPOST'); } } // Page-specific theme $type = FormUtil::getPassedValue('type', null, 'GETPOST'); $qstring = System::serverGetVar('QUERY_STRING'); if (!empty($pagetheme)) { $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($pagetheme)); if ($themeinfo['state'] == ThemeUtil::STATE_ACTIVE && ($themeinfo['user'] || $themeinfo['system'] || $themeinfo['admin'] && $type == 'admin') && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { return self::_getThemeFilterEvent($themeinfo['name'], 'page-specific'); } } // check for an admin theme if (($type == 'admin' || $type == 'adminplugin') && SecurityUtil::checkPermission('::', '::', ACCESS_EDIT)) { $admintheme = ModUtil::getVar('Admin', 'admintheme'); if (!empty($admintheme)) { $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($admintheme)); if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { return self::_getThemeFilterEvent($themeinfo['name'], 'admin-theme'); } } } // set a new theme for the user $newtheme = FormUtil::getPassedValue('newtheme', null, 'GETPOST'); if (!empty($newtheme) && System::getVar('theme_change')) { $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($newtheme)); if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { if (self::isLoggedIn()) { self::setVar('theme', $newtheme); } else { SessionUtil::setVar('theme', $newtheme); } return self::_getThemeFilterEvent($themeinfo['name'], 'new-theme'); } } // User theme if (System::getVar('theme_change') || SecurityUtil::checkPermission('::', '::', ACCESS_ADMIN)) { if (self::isLoggedIn()) { $usertheme = self::getVar('theme'); } else { $usertheme = SessionUtil::getVar('theme'); } $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($usertheme)); if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { return self::_getThemeFilterEvent($themeinfo['name'], 'user-theme'); } } // default site theme $defaulttheme = System::getVar('Default_Theme'); $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($defaulttheme)); if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { return self::_getThemeFilterEvent($themeinfo['name'], 'default-theme'); } if (!System::isInstalling()) { throw new RuntimeException(__('UserUtil::getTheme() is unable to calculate theme name.')); } }
/** * Assign template vars for base theme paths and other useful variables. * * @return void */ private function _base_vars() { // identify the page type $this->pagetype = 'module'; if (stristr(System::serverGetVar('PHP_SELF'), 'admin.php') || strtolower($this->type) == 'admin') { $this->pagetype = 'admin'; } else { $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING); if (empty($module)) { $this->pagetype = 'home'; } } // set some basic class variables from Zikula $this->isloggedin = UserUtil::isLoggedIn(); $this->uid = UserUtil::getVar('uid'); // assign the query string $this->qstring = System::serverGetVar('QUERY_STRING', ''); // assign the current script $this->requesturi = System::getCurrentUri(); // define the cache_id if not set yet if ($this->caching && !$this->cache_id) { // module / type / function / customargs|homepage/startpageargs / uid_X|guest $this->cache_id = $this->toplevelmodule . '/' . $this->type . '/' . $this->func . (!$this->homepage ? $this->_get_customargs() : '/homepage/' . str_replace(',', '/', System::getVar('startargs'))) . '/' . UserUtil::getUidCacheString(); } // assign some basic paths for the engine $this->template_dir = $this->themepath . '/templates'; // default directory for templates $this->themepath = 'themes/' . $this->directory; $theme = ThemeUtil::getTheme($this->name); if (null === $theme) { $this->imagepath = $this->themepath . '/images'; $this->imagelangpath = $this->themepath . '/images/' . $this->language; $this->stylepath = $this->themepath . '/style'; $this->scriptpath = $this->themepath . '/javascript'; } else { $this->imagepath = $this->themepath . '/Resources/public/images'; $this->imagelangpath = $this->themepath . '/Resources/public/images/' . $this->language; $this->stylepath = $this->themepath . '/Resources/public/css'; $this->scriptpath = $this->themepath . '/Resources/public/js'; } // make the base vars available to all templates $this->assign('module', $this->toplevelmodule)->assign('uid', $this->uid)->assign('loggedin', $this->isloggedin)->assign('pagetype', $this->pagetype)->assign('themepath', $this->themepath)->assign('imagepath', $this->imagepath)->assign('imagelangpath', $this->imagelangpath)->assign('stylepath', $this->stylepath)->assign('scriptpath', $this->scriptpath); // load the theme variables $variables = ModUtil::apiFunc('ZikulaThemeModule', 'user', 'getvariables', array('theme' => $this->name)); $this->assign($variables['variables']); }
/** * resequence categories */ public function resequence() { if (!SecurityUtil::checkPermission('Categories::', '::', ACCESS_EDIT)) { return LogUtil::registerPermissionError(); } $dr = (int)FormUtil::getPassedValue('dr', 0, 'GET'); $url = System::serverGetVar('HTTP_REFERER'); if (!$dr) { return LogUtil::registerError($this->__('Error! The document root is invalid.'), null, $url); } $cats = CategoryUtil::getSubCategories($dr, false, false, false, false); $cats = CategoryUtil::resequence($cats, 10); $ak = array_keys($cats); foreach ($ak as $k) { $obj = new Categories_DBObject_Category($cats[$k]); $obj->update(); } $this->redirect(System::serverGetVar('HTTP_REFERER')); }
/** * Get security analyzer data. * * @return array data */ private function _securityanalyzer() { $data = array(); // check for magic_quotes $data['magic_quotes_gpc'] = \DataUtil::getBooleanIniValue('magic_quotes_gpc'); // check for register_globals $data['register_globals'] = \DataUtil::getBooleanIniValue('register_globals'); // check for config.php beeing writable $data['config_php'] = (bool) is_writable('config/config.php'); // check for .htaccess in temp directory $temp_htaccess = false; $tempDir = $GLOBALS['ZConfig']['System']['temp']; if ($tempDir) { // check if we have an absolute path which is possibly not within the document root $docRoot = \System::serverGetVar('DOCUMENT_ROOT'); if (\StringUtil::left($tempDir, 1) == '/' && strpos($tempDir, $docRoot) === false) { // temp dir is outside the webroot, no .htaccess file needed $temp_htaccess = true; } else { if (strpos($tempDir, $docRoot) === false) { $ldir = dirname(__FILE__); $p = strpos($ldir, DIRECTORY_SEPARATOR . 'system'); // we are in system/Admin $b = substr($ldir, 0, $p); $filePath = $b . '/' . $tempDir . '/.htaccess'; } else { $filePath = $tempDir . '/.htaccess'; } $temp_htaccess = (bool) file_exists($filePath); } } else { // already customized, admin should know about what he's doing... $temp_htaccess = true; } $data['temp_htaccess'] = $temp_htaccess; $data['scactive'] = (bool) \ModUtil::available('SecurityCenterModule'); // check for outputfilter $data['useids'] = (bool) (\ModUtil::available('SecurityCenterModule') && System::getVar('useids') == 1); $data['idssoftblock'] = System::getVar('idssoftblock'); return $data; }
/** * Work out the status for a comment * * this function checks for blacklisted proxies and if the user * has already commented * * @author Mark West * @access prviate * @return mixed int 1 to require moderation, 0 for instant submission, 2 for discarding the comment, void error */ private function checksubmitter($uid = null) { // check for open proxies // credit to wordpress for this logic function wp_proxy_check() $ipnum = System::serverGetVar('REMOTE_ADDR'); // set the current uid if not present if (!isset($uid)) { $uid = UserUtil::getVar('uid'); } if ($this->getVar('proxyblacklist') && !empty($ipnum)) { $rev_ip = implode('.', array_reverse(explode('.', $ipnum))); // opm.blitzed.org is appended to use thier proxy lookup service // results of gethostbyname are cached $lookup = $rev_ip.'.opm.blitzed.org'; if ($lookup != gethostbyname($lookup)) { return 2; } } // check if the comment comes from user that we trust // i.e. one who has an approved comment already if (UserUtil::isLoggedIn() && $this->getVar('dontmoderateifcommented')) { $commentedlist = $this->getcommentingusers(); if (is_array($commentedlist) && in_array($uid, $commentedlist)) { return 0; } return 1; } return 0; }
/** * view items * * @param int $startnum the start item id for the pager * @return string HTML output */ public function view($args) { $this->throwForbiddenUnless(SecurityUtil::checkPermission('Pages::', '::', ACCESS_EDIT), LogUtil::getErrorMsgPermission()); // initialize sort array - used to display sort classes and urls $sort = array(); $fields = array('pageid', 'title', 'cr_date'); // possible sort fields foreach ($fields as $field) { $sort['class'][$field] = 'z-order-unsorted'; // default values } // Get parameters from whatever input we need. $startnum = (int)FormUtil::getPassedValue('startnum', isset($args['startnum']) ? $args['startnum'] : null, 'GETPOST'); $language = FormUtil::getPassedValue('language', isset($args['language']) ? $args['language'] : null, 'POST'); $purge = FormUtil::getPassedValue('purge', false, 'GET'); $orderby = FormUtil::getPassedValue('orderby', isset($args['orderby']) ? $args['orderby'] : 'pageid', 'GETPOST'); $original_sdir = FormUtil::getPassedValue('sdir', isset($args['sdir']) ? $args['sdir'] : 1, 'GETPOST'); $this->view->assign('startnum', $startnum); $this->view->assign('orderby', $orderby); $this->view->assign('sdir', $original_sdir); $sdir = $original_sdir ? 0 : 1; //if true change to false, if false change to true // change class for selected 'orderby' field to asc/desc if ($sdir == 0) { $sort['class'][$orderby] = 'z-order-desc'; $orderdir = 'DESC'; } if ($sdir == 1) { $sort['class'][$orderby] = 'z-order-asc'; $orderdir = 'ASC'; } $filtercats = FormUtil::getPassedValue('pages', null, 'GETPOST'); $filtercats_serialized = FormUtil::getPassedValue('filtercats_serialized', false, 'GET'); $filtercats = $filtercats_serialized ? unserialize($filtercats_serialized) : $filtercats; $catsarray = Pages_Util::formatCategoryFilter($filtercats); // complete initialization of sort array, adding urls foreach ($fields as $field) { $sort['url'][$field] = ModUtil::url('Pages', 'admin', 'view', array( 'language' => $language, 'filtercats_serialized' => serialize($filtercats), 'orderby' => $field, 'sdir' => $sdir)); } $this->view->assign('sort', $sort); $this->view->assign('filter_active', (empty($language) && empty($catsarray)) ? false : true); if ($purge) { if (ModUtil::apiFunc('Pages', 'admin', 'purgepermalinks')) { LogUtil::registerStatus($this->__('Purging of the pemalinks was successful')); } else { LogUtil::registerError($this->__('Purging of the pemalinks has failed')); } return System::redirect(strpos(System::serverGetVar('HTTP_REFERER'), 'purge') ? ModUtil::url('Pages', 'admin', 'view') : System::serverGetVar('HTTP_REFERER')); } // get module vars $modvars = $this->getVars(); if ($modvars['enablecategorization']) { $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('Pages', 'pages'); $this->view->assign('catregistry', $catregistry); } $multilingual = System::getVar('multilingual', false); // Get all matching pages $items = ModUtil::apiFunc('Pages', 'user', 'getall', array('startnum' => $startnum, 'numitems' => $modvars['itemsperpage'], 'order' => $orderby, 'orderdir' => $orderdir, 'ignoreml' => ($multilingual ? false : true), 'language' => $language, 'category' => null, 'catfilter' => isset($catsarray) ? $catsarray : null, 'catregistry' => isset($catregistry) ? $catregistry : null)); if (!$items) { $items = array(); } $pages = array(); foreach ($items as $key => $item) { $options = array(); $options[] = array('url' => ModUtil::url('Pages', 'user', 'display', array('pageid' => $item['pageid'])), 'image' => 'kview.png', 'title' => $this->__('View')); if (SecurityUtil::checkPermission('Pages::', "$item[title]::$item[pageid]", ACCESS_EDIT)) { $options[] = array('url' => ModUtil::url('Pages', 'admin', 'modify', array('pageid' => $item['pageid'])), 'image' => 'xedit.png', 'title' => $this->__('Edit')); if (SecurityUtil::checkPermission('Pages::', "$item[title]::$item[pageid]", ACCESS_DELETE)) { $options[] = array('url' => ModUtil::url('Pages', 'admin', 'delete', array('pageid' => $item['pageid'])), 'image' => '14_layer_deletelayer.png', 'title' => $this->__('Delete')); } } // Add the calculated menu options to the item array $item['options'] = $options; $pages[] = $item; } // Assign the items to the template $this->view->assign('pages', $pages); // Assign the default language $this->view->assign('lang', ZLanguage::getLanguageCode()); $this->view->assign('language', $language); // Assign the information required to create the pager $this->view->assign('pager', array( 'numitems' => ModUtil::apiFunc('Pages', 'user', 'countitems', array('catfilter' => isset($catsarray) ? $catsarray : null)), 'itemsperpage' => $modvars['itemsperpage'])); $selectedcategories = array(); if (is_array($filtercats)) { $catsarray = $filtercats['__CATEGORIES__']; foreach ($catsarray as $propname => $propid) { if ($propid > 0) { $selectedcategories[$propname] = $propid; // removes categories set to 'all' } } } $this->view->assign('selectedcategories', $selectedcategories); // Return the output that has been generated by this function return $this->view->fetch('admin/view.tpl'); }
/** * modify block settings * * @param array $blockinfo a blockinfo structure * @return output the bock form */ public function modify($blockinfo) { // Break out options from our content field $vars = BlockUtil::varsFromContent($blockinfo['content']); $blockinfo['content'] = ''; // Defaults if (empty($vars['displaymodules'])) { $vars['displaymodules'] = 0; } // template to use if (empty($vars['template'])) { $vars['template'] = 'blocks_block_extmenu.tpl'; } // create default block variables if (!isset($vars['blocktitles'])) { $vars['blocktitles'] = array(); } if (!isset($vars['links'])) { $vars['links'] = array(); } if (!isset($vars['stylesheet'])) { $vars['stylesheet'] = ''; } if (!isset($vars['menuid'])) { $vars['menuid'] = 0; } $languages = ZLanguage::getInstalledLanguages(); $userlanguage = ZLanguage::getLanguageCode(); // filter out invalid languages foreach ($vars['blocktitles'] as $k => $v) { if (!in_array($k, $languages)) { unset($vars['blocktitles'][$k]); unset($vars['links'][$k]); } } // check if the users wants to add a new link via the "Add current url" link in the block $addurl = FormUtil::getPassedValue('addurl', 0, 'GET'); // or if we come from the normal "edit this block" link $fromblock = FormUtil::getPassedValue('fromblock', null, 'GET'); $redirect = ''; if ($addurl == 1) { // set a marker for redirection later on $newurl = System::serverGetVar('HTTP_REFERER'); $redirect = urlencode($newurl); $newurl = str_replace(System::getBaseUrl(), '', $newurl); if (empty($newurl)) { $newurl = System::getHomepageUrl(); } foreach ($languages as $singlelanguage) { $vars['links'][$singlelanguage][] = array('name' => $this->__('--New link--'), 'url' => $newurl, 'title' => $this->__('--New link--'), 'level' => 0, 'parentid' => null, 'image' => '', 'active' => 1); } } elseif (isset($fromblock)) { $redirect = urlencode(System::serverGetVar('HTTP_REFERER')); } // add new languages to the blocktitles and link arrays // we need to know which language has the most links, this language will be the "master" // for new languages to be added. this ensures that all links for the new language // are prepared. $link_master = array(); foreach ($languages as $lang) { if (isset($vars['links'][$lang]) && count($link_master) < count($vars['links'][$lang])) { $link_master = $vars['links'][$lang]; } } foreach ($languages as $lang) { // create an empty blocktitle string if (!array_key_exists($lang, $vars['blocktitles'])) { $vars['blocktitles'][$lang] = ''; } if (!array_key_exists($lang, $vars['links'])) { $vars['links'][$lang] = $link_master; } } // menuitems are sorted by language per default for easier // access when showing them (which is more often necessary than // editing them), but for editing them we need them sorted by id $menuitems = array(); foreach ($vars['links'] as $lang => $langlinks) { // langlinks now contains an array of links for a certain language // sorted by key=id foreach ($langlinks as $linkid => $link) { // pre zk1.2 check if (!isset($link['id'])) { $link['id'] = $linkid; } $link['errors'] = array(); $this->checkImage($link); $menuitems[$linkid][$lang] = $link; } } $vars['links'] = $menuitems; $this->view->setCaching(Zikula_View::CACHE_DISABLED); // assign the vars $this->view->assign($vars)->assign('languages', $languages)->assign('userlanguage', $userlanguage)->assign('redirect', $redirect)->assign('blockinfo', $blockinfo); // return the output return $this->view->fetch('blocks_block_extmenu_modify.tpl'); }
/** * Create a comment for a specific item * * This is a standard function that is called with the results of the * form supplied by EZComments_user_view to create a new item * * @param $comment the comment (taken from HTTP put) * @param $mod the name of the module the comment is for (taken from HTTP put) * @param $objectid ID of the item the comment is for (taken from HTTP put) * @param $redirect URL to return to (taken from HTTP put) * @param $subject The subject of the comment (if any) (taken from HTTP put) * @param $replyto The ID of the comment for which this an anser to (taken from HTTP put) * @since 0.1 */ public function create($args) { $mod = isset($args['mod']) ? $args['mod'] : FormUtil::getPassedValue('mod', null, 'POST'); $objectid = isset($args['objectid']) ? $args['objectid'] : FormUtil::getPassedValue('objectid', null, 'POST'); $areaid = isset($args['areaid']) ? $args['areaid'] : FormUtil::getPassedValue('areaid', null, 'POST'); $comment = isset($args['comment']) ? $args['comment'] : FormUtil::getPassedValue('comment', null, 'POST'); $subject = isset($args['subject']) ? $args['subject'] : FormUtil::getPassedValue('subject', null, 'POST'); $replyto = isset($args['replyto']) ? $args['replyto'] : FormUtil::getPassedValue('replyto', null, 'POST'); $owneruid = isset($args['owneruid']) ? $args['owneruid'] : FormUtil::getPassedValue('owneruid', null, 'POST'); $redirect = isset($args['redirect']) ? $args['redirect'] : FormUtil::getPassedValue('redirect', null, 'POST'); $useurl = isset($args['useurl']) ? $args['useurl'] : FormUtil::getPassedValue('useurl', null, 'POST'); // check if the user logged in and if we're allowing anon users to // set a name and email address if (!UserUtil::isLoggedIn()) { $anonname = isset($args['anonname']) ? $args['anonname'] : FormUtil::getPassedValue('anonname', null, 'POST'); $anonmail = isset($args['anonmail']) ? $args['anonmail'] : FormUtil::getPassedValue('anonmail', null, 'POST'); $anonwebsite = isset($args['anonwebsite']) ? $args['anonwebsite'] : FormUtil::getPassedValue('anonwebsite', null, 'POST'); } else { $anonname = ''; $anonmail = ''; $anonwebsite = ''; } if (!isset($owneruid) || !($owneruid > 1)) { $owneruid = 0; } $redirect = str_replace('&', '&', base64_decode($redirect)); $redirect = !empty($redirect) ? $redirect : System::serverGetVar('HTTP_REFERER'); $useurl = base64_decode($useurl); // save the submitted data if any error occurs $ezcomment = unserialize(SessionUtil::getVar('ezcomment', 'a:0:{}')); if (isset($ezcomment[$mod][$objectid])) { unset($ezcomment[$mod][$objectid]); } if (!empty($subject)) { $ezcomment[$mod][$objectid]['subject'] = $subject; } if (!empty($comment)) { $ezcomment[$mod][$objectid]['comment'] = $comment; } if (!empty($anonname)) { $ezcomment[$mod][$objectid]['anonname'] = $anonname; } if (!empty($anonmail)) { $ezcomment[$mod][$objectid]['anonmail'] = $anonmail; } if (!empty($anonwebsite)) { $ezcomment[$mod][$objectid]['anonwebsite'] = $anonwebsite; } // Confirm authorisation code // check csrf token SessionUtil::setVar('ezcomment', serialize($ezcomment)); $this->checkCsrfToken(); SessionUtil::delVar('ezcomment'); // and check we've actually got a comment.... if (empty($comment)) { SessionUtil::setVar('ezcomment', serialize($ezcomment)); return LogUtil::registerError($this->__('Error! The comment contains no text.'), null, $redirect . "#commentform_{$mod}_{$objectid}"); } // Check hooked modules for validation $hookvalidators = $this->notifyHooks(new Zikula_ValidationHook('ezcomments.ui_hooks.comments.validate_edit', new Zikula_Hook_ValidationProviders()))->getValidators(); if ($hookvalidators->hasErrors()) { SessionUtil::setVar('ezcomment', serialize($ezcomment)); return LogUtil::registerError($this->__('Error! The hooked content does not validate. Could it possibly be that a captcha code was entered incorrectly?'), null, $redirect . "#commentform_{$mod}_{$objectid}"); } // now parse out the hostname+subfolder from the url for storing in the DB $url = str_replace(System::getBaseUri(), '', $useurl); $id = ModUtil::apiFunc('EZComments', 'user', 'create', array('mod' => $mod, 'objectid' => $objectid, 'areaid' => $areaid, 'url' => $url, 'comment' => $comment, 'subject' => $subject, 'replyto' => $replyto, 'uid' => UserUtil::getVar('uid'), 'owneruid' => $owneruid, 'useurl' => $useurl, 'redirect' => $redirect, 'anonname' => $anonname, 'anonmail' => $anonmail, 'anonwebsite' => $anonwebsite)); if ($id) { // clear respective cache ModUtil::apiFunc('EZComments', 'user', 'clearItemCache', array('id' => $id, 'modname' => $mod, 'objectid' => $objectid, 'url' => $url)); } else { // redirect if it was not successful SessionUtil::setVar('ezcomment', $ezcomment); System::redirect($redirect . "#commentform_{$mod}_{$objectid}"); } // clean/set the session data if (isset($ezcomment[$mod][$objectid])) { unset($ezcomment[$mod][$objectid]); if (empty($ezcomment[$mod])) { unset($ezcomment[$mod]); } } if (empty($ezcomment)) { SessionUtil::delVar('ezcomment'); } else { SessionUtil::setVar('ezcomment', serialize($ezcomment)); } return System::redirect($redirect . '#comment' . $id); }
/** * {@inheritdoc} */ public function start() { $path = System::getBaseUri(); if (empty($path)) { $path = '/'; } elseif (substr($path, -1, 1) != '/') { $path .= '/'; } $host = System::serverGetVar('HTTP_HOST'); if (($pos = strpos($host, ':')) !== false) { $host = substr($host, 0, $pos); } // PHP configuration variables ini_set('session.use_trans_sid', 0); // Stop adding SID to URLs @ini_set('url_rewriter.tags', ''); // some environments dont allow this value to be set causing an error that prevents installation ini_set('session.serialize_handler', 'php'); // How to store data ini_set('session.use_cookies', 1); // Use cookie to store the session ID ini_set('session.auto_start', 1); // Auto-start session ini_set('session.name', SessionUtil::getCookieName()); // Name of our cookie // Set lifetime of session cookie $seclevel = System::getVar('seclevel'); switch ($seclevel) { case 'High': // Session lasts duration of browser $lifetime = 0; // Referer check // ini_set('session.referer_check', $host.$path); ini_set('session.referer_check', $host); break; case 'Medium': // Session lasts set number of days $lifetime = System::getVar('secmeddays') * 86400; break; case 'Low': default: // Session lasts unlimited number of days (well, lots, anyway) // (Currently set to 25 years) $lifetime = 788940000; break; } ini_set('session.cookie_lifetime', $lifetime); // domain and path settings for session cookie // if (System::getVar('intranet') == false) { // Cookie path ini_set('session.cookie_path', $path); // Garbage collection ini_set('session.gc_probability', System::getVar('gc_probability')); ini_set('session.gc_divisor', 10000); ini_set('session.gc_maxlifetime', System::getVar('secinactivemins') * 60); // Inactivity timeout for user sessions ini_set('session.hash_function', 1); // Set custom session handlers ini_set('session.save_handler', 'user'); if (System::getVar('sessionstoretofile')) { ini_set('session.save_path', System::getVar('sessionsavepath')); } session_set_save_handler(array($this, 'open'), array($this, 'close'), array($this, 'read'), array($this, 'write'), array($this, 'destroy'), array($this, 'gc')); // create IP finger print $current_ipaddr = ''; $_REMOTE_ADDR = System::serverGetVar('REMOTE_ADDR'); $_HTTP_X_FORWARDED_FOR = System::serverGetVar('HTTP_X_FORWARDED_FOR'); if (System::getVar('sessionipcheck')) { // feature for future release } // create the ip fingerprint $current_ipaddr = md5($_REMOTE_ADDR . $_HTTP_X_FORWARDED_FOR); // start session check expiry and ip fingerprint if required if (session_start() && isset($GLOBALS['_ZSession']['obj']) && $GLOBALS['_ZSession']['obj']) { // check if session has expired or not $now = time(); $inactive = $now - (int) (System::getVar('secinactivemins') * 60); $daysold = $now - (int) (System::getVar('secmeddays') * 86400); $lastused = strtotime($GLOBALS['_ZSession']['obj']['lastused']); $rememberme = SessionUtil::getVar('rememberme'); $uid = $GLOBALS['_ZSession']['obj']['uid']; $ipaddr = $GLOBALS['_ZSession']['obj']['ipaddr']; // IP check if (System::getVar('sessionipcheck', false)) { if ($ipaddr !== $current_ipaddr) { session_destroy(); return false; } } switch (System::getVar('seclevel')) { case 'Low': // Low security - users stay logged in permanently // no special check necessary break; case 'Medium': // Medium security - delete session info if session cookie has // expired or user decided not to remember themself and inactivity timeout // OR max number of days have elapsed without logging back in if (!$rememberme && $lastused < $inactive || $lastused < $daysold || $uid == '0' && $lastused < $inactive) { $this->expire(); } break; case 'High': default: // High security - delete session info if user is inactive //if ($rememberme && ($lastused < $inactive)) { // see #427 if ($lastused < $inactive) { $this->expire(); } break; } } else { // *must* regenerate new session otherwise the default sessid will be // taken from any session cookie that was submitted (bad bad bad) $this->regenerate(true); SessionUtil::_createNew(session_id(), $current_ipaddr); } if (isset($_SESSION['_ZSession']['obj'])) { unset($_SESSION['_ZSession']['obj']); } return true; }
/** * update category */ public function editAction() { $this->checkCsrfToken(); if (!SecurityUtil::checkPermission('Categories::', '::', ACCESS_ADMIN)) { throw new \Zikula\Framework\Exception\ForbiddenException(); } // get data from post $data = $this->request->request->get('category', null); if (!isset($data['is_locked'])) { $data['is_locked'] = 0; } if (!isset($data['is_leaf'])) { $data['is_leaf'] = 0; } if (!isset($data['status'])) { $data['status'] = 'I'; } $args = array(); if ($this->request->request->get('category_copy', null)) { $args['op'] = 'copy'; $args['cid'] = (int) $data['id']; return $this->redirect(ModUtil::url('Categories', 'admin', 'op', $args)); } if ($this->request->request->get('category_move', null)) { $args['op'] = 'move'; $args['cid'] = (int) $data['id']; return $this->redirect(ModUtil::url('Categories', 'admin', 'op', $args)); } if ($this->request->request->get('category_delete', null)) { $args['op'] = 'delete'; $args['cid'] = (int) $data['id']; return $this->redirect(ModUtil::url('Categories', 'admin', 'op', $args)); } if ($this->request->request->get('category_user_edit', null)) { $_SESSION['category_referer'] = System::serverGetVar('HTTP_REFERER'); $args['dr'] = (int) $data['id']; return $this->redirect(ModUtil::url('Categories', 'user', 'edit', $args)); } $valid = \CategoriesModule\GenericUtil::validateCategoryData($data); if (!$valid) { return $this->redirect(ModUtil::url('Categories', 'admin', 'edit', array('mode' => 'edit', 'cid' => (int) $data['id']))); } // process name $data['name'] = \CategoriesModule\GenericUtil::processCategoryName($data['name']); // process parent $data['parent'] = \CategoriesModule\GenericUtil::processCategoryParent($data['parent_id']); unset($data['parent_id']); // process display names $data['display_name'] = \CategoriesModule\GenericUtil::processCategoryDisplayName($data['display_name'], $data['name']); // get existing category $category = $this->entityManager->find('Zikula\\Core\\Doctrine\\Entity\\Category', $data['id']); $prevCategoryName = $category['name']; // save category $category->merge($data); $this->entityManager->flush(); // process path and ipath $category['path'] = \CategoriesModule\GenericUtil::processCategoryPath($data['parent']['path'], $category['name']); $category['ipath'] = \CategoriesModule\GenericUtil::processCategoryIPath($data['parent']['ipath'], $category['id']); // process category attributes $attrib_names = $this->request->request->get('attribute_name', array()); $attrib_values = $this->request->request->get('attribute_value', array()); \CategoriesModule\GenericUtil::processCategoryAttributes($category, $attrib_names, $attrib_values); $this->entityManager->flush(); // since a name change will change the object path, we must rebuild it here if ($prevCategoryName != $category['name']) { CategoryUtil::rebuildPaths('path', 'name', $category['id']); } $msg = __f('Done! Saved the %s category.', $prevCategoryName); LogUtil::registerStatus($msg); return $this->redirect(ModUtil::url('Categories', 'admin', 'view')); }
/** * Processes a template file using dompdf (LGPL). * * @param Zikula_View $view Reference to view object. * @param string $template Name of template to use. * * @return mixed Output. */ protected function processPdf(Zikula_View $view, $template) { // first the content, to set page vars $output = $view->fetch($template); // make local images absolute $output = str_replace('img src="/', 'img src="' . System::serverGetVar('DOCUMENT_ROOT') . '/', $output); // see http://codeigniter.com/forums/viewthread/69388/P15/#561214 //$output = utf8_decode($output); // then the surrounding $output = $view->fetch('include_pdfheader.tpl') . $output . '</body></html>'; $controllerHelper = new MUVideo_Util_Controller($this->serviceManager); // create name of the pdf output file $fileTitle = $controllerHelper->formatPermalink(System::getVar('sitename')) . '-' . $controllerHelper->formatPermalink(PageUtil::getVar('title')) . '-' . date('Ymd') . '.pdf'; // if ($_GET['dbg'] == 1) die($output); // instantiate pdf object $pdf = new \DOMPDF(); // define page properties $pdf->set_paper('A4'); // load html input data $pdf->load_html($output); // create the actual pdf file $pdf->render(); // stream output to browser $pdf->stream($fileTitle); // prevent additional output by shutting down the system System::shutDown(); return true; }
/** * Generate a module function URL. * * If the module is non-API compliant (type 1) then * a) $func is ignored. * b) $type=admin will generate admin.php?module=... and $type=user will generate index.php?name=... * * @param string $modname The name of the module. * @param string $type The type of function to run. * @param string $func The specific function to run. * @param array $args The array of arguments to put on the URL. * @param boolean|null $ssl Set to constant null,true,false $ssl = true not $ssl = 'true' null - leave the current status untouched, * true - create a ssl url, false - create a non-ssl url. * @param string $fragment The framgment to target within the URL. * @param boolean|null $fqurl Fully Qualified URL. True to get full URL, eg for Redirect, else gets root-relative path unless SSL. * @param boolean $forcelongurl Force ModUtil::url to not create a short url even if the system is configured to do so. * @param boolean|string $forcelang Force the inclusion of the $forcelang or default system language in the generated url. * * @return string Absolute URL for call. */ public static function url($modname, $type = null, $func = null, $args = array(), $ssl = null, $fragment = null, $fqurl = null, $forcelongurl = false, $forcelang = false) { // define input, all numbers and booleans to strings $modname = isset($modname) ? (string) $modname : ''; // note - when this legacy is to be removed, change method signature $type = null to $type making it a required argument. if (!$type) { if (System::isLegacyMode()) { $type = 'user'; LogUtil::log('ModUtil::url() - $type is a required argument, you must specify it explicitly.', E_USER_DEPRECATED); } else { throw new UnexpectedValueException('ModUtil::url() - $type is a required argument, you must specify it explicitly.'); } } // note - when this legacy is to be removed, change method signature $func = null to $func making it a required argument. if (!$func) { if (System::isLegacyMode()) { $func = 'main'; LogUtil::log('ModUtil::url() - $func is a required argument, you must specify it explicitly.', E_USER_DEPRECATED); } else { throw new UnexpectedValueException('ModUtil::url() - $func is a required argument, you must specify it explicitly.'); } } // validate if (!System::varValidate($modname, 'mod')) { return null; } // Remove from 1.4 if (System::isLegacyMode() && $modname == 'Modules') { LogUtil::log(__('Warning! "Modules" module has been renamed to "Extensions". Please update your ModUtil::url() or {modurl} calls with $module = "Extensions".')); $modname = 'Extensions'; } //get the module info $modinfo = self::getInfo(self::getIDFromName($modname)); // set the module name to the display name if this is present if (isset($modinfo['url']) && !empty($modinfo['url'])) { $modname = rawurlencode($modinfo['url']); } $entrypoint = System::getVar('entrypoint'); $host = System::serverGetVar('HTTP_HOST'); if (empty($host)) { return false; } $baseuri = System::getBaseUri(); $https = System::serverGetVar('HTTPS'); $shorturls = System::getVar('shorturls'); $shorturlsstripentrypoint = System::getVar('shorturlsstripentrypoint'); $shorturlsdefaultmodule = System::getVar('shorturlsdefaultmodule'); // Don't encode URLs with escaped characters, like return urls. foreach ($args as $v) { if (!is_array($v)) { if (strpos($v, '%') !== false) { $shorturls = false; break; } } else { foreach ($v as $vv) { if (is_array($vv)) { foreach ($vv as $vvv) { if (!is_array($vvv) && strpos($vvv, '%') !== false) { $shorturls = false; break; } } } elseif (strpos($vv, '%') !== false) { $shorturls = false; break; } } break; } } // Setup the language code to use if (is_array($args) && isset($args['lang'])) { if (in_array($args['lang'], ZLanguage::getInstalledLanguages())) { $language = $args['lang']; } unset($args['lang']); } if (!isset($language)) { $language = ZLanguage::getLanguageCode(); } $language = $forcelang && in_array($forcelang, ZLanguage::getInstalledLanguages()) ? $forcelang : $language; // Only produce full URL when HTTPS is on or $ssl is set $siteRoot = ''; if (isset($https) && $https == 'on' || $ssl != null || $fqurl == true) { $protocol = 'http' . ($https == 'on' && $ssl !== false || $ssl === true ? 's' : ''); $secureDomain = System::getVar('secure_domain'); $siteRoot = $protocol . '://' . ($secureDomain != '' ? $secureDomain : $host . $baseuri) . '/'; } // Only convert type=user. Exclude links that append a theme parameter if ($shorturls && $type == 'user' && $forcelongurl == false) { if (isset($args['theme'])) { $theme = $args['theme']; unset($args['theme']); } // Module-specific Short URLs $url = self::apiFunc($modinfo['name'], 'user', 'encodeurl', array('modname' => $modname, 'type' => $type, 'func' => $func, 'args' => $args)); if (empty($url)) { // depending on the settings, we have generic directory based short URLs: // [language]/[module]/[function]/[param1]/[value1]/[param2]/[value2] // [module]/[function]/[param1]/[value1]/[param2]/[value2] $vars = ''; foreach ($args as $k => $v) { if (is_array($v)) { foreach ($v as $k2 => $w) { if (is_numeric($w) || !empty($w)) { // we suppress '', but allow 0 as value (see #193) $vars .= '/' . $k . '[' . $k2 . ']/' . $w; // &$k[$k2]=$w } } } elseif (is_numeric($v) || !empty($v)) { // we suppress '', but allow 0 as value (see #193) $vars .= "/{$k}/{$v}"; // &$k=$v } } $url = $modname . ($vars || $func != 'main' ? "/{$func}{$vars}" : ''); } if ($modinfo && $shorturlsdefaultmodule && $shorturlsdefaultmodule == $modinfo['name']) { $pattern = '/^' . preg_quote($modinfo['url'], '/') . '\\//'; $url = preg_replace($pattern, '', $url); } if (isset($theme)) { $url = rawurlencode($theme) . '/' . $url; } // add language param to short url if (ZLanguage::isRequiredLangParam() || $forcelang) { $url = "{$language}/" . $url; } if (!$shorturlsstripentrypoint) { $url = "{$entrypoint}/{$url}" . (!empty($query) ? '?' . $query : ''); } else { $url = "{$url}" . (!empty($query) ? '?' . $query : ''); } } else { // Regular stuff $urlargs = "module={$modname}&type={$type}&func={$func}"; // add lang param to URL if (ZLanguage::isRequiredLangParam() || $forcelang) { $urlargs .= "&lang={$language}"; } $url = "{$entrypoint}?{$urlargs}"; if (!is_array($args)) { return false; } else { foreach ($args as $key => $value) { if (is_array($value)) { foreach ($value as $l => $w) { if (is_numeric($w) || !empty($w)) { // we suppress '', but allow 0 as value (see #193) if (is_array($w)) { foreach ($w as $m => $n) { if (is_numeric($n) || !empty($n)) { $n = strpos($n, '%') !== false ? $n : urlencode($n); $url .= "&{$key}" . "[{$l}][{$m}]={$n}"; } } } else { $w = strpos($w, '%') !== false ? $w : urlencode($w); $url .= "&{$key}" . "[{$l}]={$w}"; } } } } elseif (is_numeric($value) || !empty($value)) { // we suppress '', but allow 0 as value (see #193) $w = strpos($value, '%') !== false ? $value : urlencode($value); $url .= "&{$key}={$value}"; } } } } if (isset($fragment)) { $url .= '#' . $fragment; } return $siteRoot . $url; }
/** * Get the user's theme. * * This function will return the current theme for the user. * Order of theme priority: * - page-specific * - category * - user * - system * * @param boolean $force True to ignore the cache. * * @return string the name of the user's theme * @throws RuntimeException If this function was unable to calculate theme name. */ public static function getTheme($force = false) { static $pagetheme; if (isset($pagetheme) && !$force) { return $pagetheme; } /** @var $request Request */ $request = \ServiceUtil::get('request'); $theme = FormUtil::getPassedValue('theme', null, 'GETPOST'); if (!empty($theme) && SecurityUtil::checkPermission('ZikulaThemeModule::ThemeChange', '::', ACCESS_COMMENT)) { // theme passed as parameter takes priority, can be RSS, Atom, Printer or other $pagetheme = $theme; } else { // check for specified alternative site view domain and theme $themedomain = ModUtil::getVar('ZikulaThemeModule', 'alt_theme_domain', ''); if ($themedomain && $_SERVER['SERVER_NAME'] == $themedomain && ModUtil::getVar('ZikulaThemeModule', 'alt_theme_name', '')) { $pagetheme = ModUtil::getVar('ZikulaThemeModule', 'alt_theme_name'); } } // Retrieve required parameters $type = FormUtil::getPassedValue('type', null, 'GETPOST'); $legacyType = FormUtil::getPassedValue('lct', null, 'GETPOST'); if ($type != $legacyType) { // BC support (see #2051 for example) $type = $legacyType; } if (null === $type) { // routing preventing type from being set, get from request attributes $type = $request->get('_zkType'); } // Page-specific theme $qstring = System::serverGetVar('QUERY_STRING'); if (!empty($pagetheme)) { $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($pagetheme)); if ($themeinfo['state'] == ThemeUtil::STATE_ACTIVE && ($themeinfo['user'] || $themeinfo['system'] || $themeinfo['admin'] && $type == 'admin') && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { $pagetheme = $themeinfo['name']; $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'page-specific'); $request->attributes->set('_theme', $themeName); return $themeName; } } // check for an admin theme $adminSections = array('admin', 'adminplugin'); if (in_array($type, $adminSections) && SecurityUtil::checkPermission('::', '::', ACCESS_EDIT)) { $admintheme = ModUtil::getVar('ZikulaAdminModule', 'admintheme'); if (!empty($admintheme)) { $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($admintheme)); if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { $pagetheme = $themeinfo['name']; $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'admin-theme'); $request->attributes->set('_theme', $themeName); return $themeName; } } } // set a new theme for the user $newtheme = FormUtil::getPassedValue('newtheme', null, 'GETPOST'); if (!empty($newtheme) && System::getVar('theme_change')) { $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($newtheme)); if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { if (self::isLoggedIn()) { self::setVar('theme', $newtheme); } else { SessionUtil::setVar('theme', $newtheme); } $pagetheme = $themeinfo['name']; $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'new-theme'); $request->attributes->set('_theme', $themeName); return $themeName; } } // User theme if (System::getVar('theme_change') || SecurityUtil::checkPermission('::', '::', ACCESS_ADMIN)) { if (self::isLoggedIn()) { $usertheme = self::getVar('theme'); } else { $usertheme = SessionUtil::getVar('theme'); } $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($usertheme)); if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { $pagetheme = $themeinfo['name']; $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'user-theme'); $request->attributes->set('_theme', $themeName); return $themeName; } } // default site theme $defaulttheme = System::getVar('Default_Theme'); $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($defaulttheme)); if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) { $pagetheme = $themeinfo['name']; $themeName = self::_getThemeFilterEvent($themeinfo['name'], 'default-theme'); $request->attributes->set('_theme', $themeName); return $themeName; } if (!System::isInstalling()) { throw new RuntimeException(__('UserUtil::getTheme() is unable to calculate theme name.')); } }
/** * edit category for a simple, non-recursive set of categories */ public function edit() { $docroot = FormUtil::getPassedValue('dr', 0); $cid = FormUtil::getPassedValue('cid', 0); $url = ModUtil::url('Categories', 'user', 'edit', array('dr' => $docroot)); if (!SecurityUtil::checkPermission('Categories::category', "ID::$docroot", ACCESS_EDIT)) { return LogUtil::registerPermissionError($url); } $referer = System::serverGetVar('HTTP_REFERER'); if (strpos($referer, 'module=Categories') === false) { SessionUtil::setVar('categories_referer', $referer); } $rootCat = array(); $allCats = array(); $editCat = array(); if (!$docroot) { return LogUtil::registerError($this->__("Error! The URL contains an invalid 'document root' parameter."), null, $url); } if ($docroot == 1) { return LogUtil::registerError($this->__("Error! The root directory cannot be modified in 'user' mode"), null, $url); } if (is_int((int)$docroot) && $docroot > 0) { $rootCat = CategoryUtil::getCategoryByID($docroot); } else { $rootCat = CategoryUtil::getCategoryByPath($docroot); if (!$rootCat) { $rootCat = CategoryUtil::getCategoryByPath($docroot, 'ipath'); } } // now check if someone is trying edit another user's categories $userRoot = $this->getVar('userrootcat', 0); if ($userRoot) { $userRootCat = CategoryUtil::getCategoryByPath($userRoot); if ($userRootCat) { $userRootCatIPath = $userRootCat['ipath']; $rootCatIPath = $rootCat['ipath']; if (strpos($rootCatIPath, $userRootCatIPath) !== false) { if (!SecurityUtil::checkPermission('Categories::category', "ID::$docroot", ACCESS_ADMIN)) { $thisUserRootCategoryName = ModUtil::apiFunc('Categories', 'user', 'getusercategoryname'); $thisUserRootCatPath = $userRootCat['path'] . '/' . $thisUserRootCategoryName; $userRootCatPath = $userRootCat['path']; $rootCatPath = $rootCat['path']; if (strpos($rootCatPath, $userRootCatPath) === false) { //! %s represents the root path (id), passed in the url return LogUtil::registerError($this->__f("Error! It looks like you are trying to edit another user's categories. Only site administrators can do that (%s).", $docroot), null, $url); } } } } } if ($cid) { $editCat = CategoryUtil::getCategoryByID($cid); if ($editCat['is_locked']) { //! %1$s is the id, %2$s is the name return LogUtil::registerError($this->__f('Notice: The administrator has locked the category \'%2$s\' (ID \'%$1s\'). You cannot edit or delete it.', array($cid, $editCat['name'])), null, $url); } } if (!$rootCat) { return LogUtil::registerError($this->__f("Error! Cannot access root directory (%s).", $docroot), null, $url); } if ($editCat && !$editCat['is_leaf']) { return LogUtil::registerError($this->__f('Error! The specified category is not a leaf-level category (%s).', $cid), null, $url); } if ($editCat && !CategoryUtil::isDirectSubCategory($rootCat, $editCat)) { return LogUtil::registerError($this->__f('Error! The specified category is not a child of the document root (%1$s; %2$s).', array($docroot, $cid)), null, $url); } $allCats = CategoryUtil::getSubCategoriesForCategory($rootCat, false, false, false, true, true); $attributes = isset($editCat['__ATTRIBUTES__']) ? $editCat['__ATTRIBUTES__'] : array(); $languages = ZLanguage::getInstalledLanguages(); $this->view->setCaching(Zikula_View::CACHE_DISABLED); return $this->view->assign('rootCat', $rootCat) ->assign('category', $editCat) ->assign('attributes', $attributes) ->assign('allCats', $allCats) ->assign('languages', $languages) ->assign('userlanguage', ZLanguage::getLanguageCode()) ->assign('referer', SessionUtil::getVar('categories_referer')) ->fetch('categories_user_edit.tpl'); }
/** * block configuration */ public function modify($blockinfo) { $vars = BlockUtil::varsFromContent($blockinfo['content']); // set some default vars $vars['isnew'] = empty($vars); $vars['menutree_content'] = isset($vars['menutree_content']) ? $vars['menutree_content'] : array(); $vars['menutree_tpl'] = isset($vars['menutree_tpl']) ? $vars['menutree_tpl'] : ''; $vars['menutree_stylesheet'] = isset($vars['menutree_stylesheet']) ? $vars['menutree_stylesheet'] : ''; $vars['menutree_linkclass'] = isset($vars['menutree_linkclass']) ? $vars['menutree_linkclass'] : false; $vars['menutree_linkclasses'] = isset($vars['menutree_linkclasses']) ? $vars['menutree_linkclasses'] : array(); $vars['menutree_titles'] = isset($vars['menutree_titles']) ? $vars['menutree_titles'] : array(); $vars['menutree_editlinks'] = isset($vars['menutree_editlinks']) ? $vars['menutree_editlinks'] : false; $vars['menutree_stripbaseurl'] = isset($vars['menutree_stripbaseurl']) ? $vars['menutree_stripbaseurl'] : true; $vars['menutree_maxdepth'] = isset($vars['menutree_maxdepth']) ? $vars['menutree_maxdepth'] : 0; $vars['oldlanguages'] = isset($vars['oldlanguages']) ? $vars['oldlanguages'] : array(); $vars['olddefaultanguage'] = isset($vars['olddefaultanguage']) ? $vars['olddefaultanguage'] :''; // get list of languages $vars['languages'] = ZLanguage::getInstalledLanguageNames(); $userlanguage = ZLanguage::getLanguageCode(); // get default langs $vars['defaultanguage'] = !empty($blockinfo['language']) ? $blockinfo['language'] : $userlanguage; // rebuild langs array - default lang has to be first if (isset($vars['languages']) && count($vars['languages']) > 1) { $deflang[$vars['defaultanguage']] = $vars['languages'][$vars['defaultanguage']]; unset($vars['languages'][$vars['defaultanguage']]); $vars['languages'] = array_merge($deflang,$vars['languages']); $vars['multilingual'] = true; } else { $vars['multilingual'] = false; } $langs = array('list' => array_keys($vars['languages']), 'flat' => false); // check if there is allredy content if (empty($vars['menutree_content'])) { // no content - get list of menus to allow import $vars['menutree_menus'] = $this->_get_current_menus($blockinfo['bid']); } else { // are there new langs not present in current menu? // check if there are new languages not present in current menu // if so - need to set reference lang to copy initial menu items data if (count(array_diff($vars['languages'],$vars['oldlanguages'])) > 1) { // fisrt try current default lang if (in_array($vars['defaultanguage'],$vars['oldlanguages'])) { $langs['ref'] = $vars['defaultanguage']; // or user lang } elseif (in_array($userlanguage,$vars['oldlanguages'])) { $langs['ref'] = $userlanguage; // or old default lang } elseif (in_array($vars['olddefaultanguage'],$vars['languages'])) { $langs['ref'] = $vars['olddefaultanguage']; // it must be any language present in old and new lang list } else { $langs['ref'] = current(array_intersect($vars['languages'], $vars['oldlanguages'])); } } } // decode tree array $tree = new Blocks_MenutreeTree(); $tree->setOption('id', 'adm-menutree'.$blockinfo['bid']); $tree->setOption('sortable', true); if (isset($langs)) { $tree->setOption('langs', $langs['list']); } $tree->setOption('stripbaseurl', $vars['menutree_stripbaseurl']); $tree->setOption('maxDepth', $vars['menutree_maxdepth']); $tree->loadArrayData($vars['menutree_content']); $vars['menutree_content'] = $tree->getHTML(); // get all templates and stylesheets. $vars['tpls'] = Blocks_MenutreeUtil::getTemplates(); $vars['styles'] = Blocks_MenutreeUtil::getStylesheets(); $someThemes = $this->__('Only in some themes'); $vars['somethemes'] = isset($vars['tpls'][$someThemes]) || isset($vars['styles'][$someThemes]) ? true : false; // template to use if (empty($vars['menutree_tpl']) || !$this->view->template_exists($vars['menutree_tpl'])) { $vars['menutree_tpl'] = 'menutree/blocks_block_menutree_default.tpl'; } // prepare block titles array foreach (array_keys($vars['languages']) as $lang) { if (!array_key_exists($lang, $vars['menutree_titles'])) { $vars['menutree_titles'][$lang] = ''; } } // for permissions settings get first supported permlevels $vars['permlevels'] = $this->_permlevels(); // check if saved permlevels are correct $vars['menutree_titlesperms'] = !empty($vars['menutree_titlesperms']) ? $vars['menutree_titlesperms'] : 'ACCESS_EDIT'; $vars['menutree_displayperms'] = !empty($vars['menutree_displayperms']) ? $vars['menutree_displayperms'] : 'ACCESS_EDIT'; $vars['menutree_settingsperms'] = !empty($vars['menutree_settingsperms']) ? $vars['menutree_settingsperms'] : 'ACCESS_EDIT'; // check user permissions for settings sections $useraccess = SecurityUtil::getSecurityLevel(SecurityUtil::getAuthInfo(), 'Blocks::', "$blockinfo[bkey]:$blockinfo[title]:$blockinfo[bid]"); $vars['menutree_titlesaccess'] = $useraccess >= constant($vars['menutree_titlesperms']); $vars['menutree_displayaccess'] = $useraccess >= constant($vars['menutree_displayperms']); $vars['menutree_settingsaccess'] = $useraccess >= constant($vars['menutree_settingsperms']); $vars['menutree_adminaccess'] = $useraccess >= ACCESS_ADMIN; $vars['menutree_anysettingsaccess'] = $vars['menutree_adminaccess'] || $vars['menutree_titlesaccess'] || $vars['menutree_displayaccess'] || $vars['menutree_settingsaccess']; // check if the users wants to add a new link via the "Add current url" link in the block $addurl = FormUtil::getPassedValue('addurl', 0, 'GET'); // or if we come from the normal "edit this block" link $fromblock = FormUtil::getPassedValue('fromblock', null, 'GET'); $vars['redirect'] = ''; $vars['menutree_newurl'] = ''; if ($addurl == 1) { // set a marker for redirection later on $newurl = System::serverGetVar('HTTP_REFERER'); $vars['redirect'] = urlencode($newurl); $newurl = str_replace(System::getBaseUrl(), '', $newurl); if (empty($newurl)) { $newurl = System::getHomepageUrl(); } $vars['menutree_newurl'] = $newurl; } elseif (isset($fromblock)) { $vars['redirect'] = urlencode(System::serverGetVar('HTTP_REFERER')); } // Create output object $this->view->setCaching(Zikula_View::CACHE_DISABLED); // assign all block variables $this->view->assign($vars) ->assign('blockinfo', $blockinfo); // Return the output that has been generated by this function return $this->view->fetch('menutree/blocks_block_menutree_modify.tpl'); }
/** * Process results from IDS scan. * * @param IDS_Init $init PHPIDS init object reference. * @param IDS_Report $result The result object from PHPIDS. * * @return void */ private function _processIdsResult(IDS_Init $init, IDS_Report $result) { // $result contains any suspicious fields enriched with additional info // Note: it is moreover possible to dump this information by simply doing //"echo $result", calling the IDS_Report::$this->__toString() method implicitely. $requestImpact = $result->getImpact(); if ($requestImpact < 1) { // nothing to do return; } // update total session impact to track an attackers activity for some time $sessionImpact = SessionUtil::getVar('idsImpact', 0) + $requestImpact; SessionUtil::setVar('idsImpact', $sessionImpact); // let's see which impact mode we are using $idsImpactMode = System::getVar('idsimpactmode', 1); $idsImpactFactor = 1; if ($idsImpactMode == 1) { $idsImpactFactor = 1; } elseif ($idsImpactMode == 2) { $idsImpactFactor = 10; } elseif ($idsImpactMode == 3) { $idsImpactFactor = 5; } // determine our impact threshold values $impactThresholdOne = System::getVar('idsimpactthresholdone', 1) * $idsImpactFactor; $impactThresholdTwo = System::getVar('idsimpactthresholdtwo', 10) * $idsImpactFactor; $impactThresholdThree = System::getVar('idsimpactthresholdthree', 25) * $idsImpactFactor; $impactThresholdFour = System::getVar('idsimpactthresholdfour', 75) * $idsImpactFactor; $usedImpact = ($idsImpactMode == 1) ? $requestImpact : $sessionImpact; // react according to given impact if ($usedImpact > $impactThresholdOne) { // db logging // determine IP address of current user $_REMOTE_ADDR = System::serverGetVar('REMOTE_ADDR'); $_HTTP_X_FORWARDED_FOR = System::serverGetVar('HTTP_X_FORWARDED_FOR'); $ipAddress = ($_HTTP_X_FORWARDED_FOR) ? $_HTTP_X_FORWARDED_FOR : $_REMOTE_ADDR; $currentPage = System::getCurrentUri(); $currentUid = UserUtil::getVar('uid'); $intrusionItems = array(); foreach ($result as $event) { $eventName = $event->getName(); $malVar = explode(".", $eventName, 2); $filters = array(); foreach ($event as $filter) { array_push($filters, array( 'id' => $filter->getId(), 'description' => $filter->getDescription(), 'impact' => $filter->getImpact(), 'tags' => $filter->getTags(), 'rule' => $filter->getRule())); } $tagVal = $malVar[1]; $newIntrusionItem = array( 'name' => array($eventName), 'tag' => $tagVal, 'value' => $event->getValue(), 'page' => $currentPage, 'uid' => $currentUid, 'ip' => $ipAddress, 'impact' => $result->getImpact(), 'filters' => serialize($filters), 'date' => DateUtil::getDatetime() ); if (array_key_exists($tagVal, $intrusionItems)) { $intrusionItems[$tagVal]['name'][] = $newIntrusionItem['name'][0]; } else { $intrusionItems[$tagVal] = $newIntrusionItem; } } // log details to database foreach ($intrusionItems as $tag => $intrusionItem) { $intrusionItem['name'] = implode(", ", $intrusionItem['name']); // create new ZIntrusion instance $obj = new SecurityCenter_DBObject_Intrusion(); // set data $obj->setData($intrusionItem); // save object to db $obj->save(); } } if (System::getVar('idsmail') && ($usedImpact > $impactThresholdTwo)) { // mail admin // prepare mail text $mailBody = __('The following attack has been detected by PHPIDS') . "\n\n"; $mailBody .= __f('IP: %s', $ipAddress) . "\n"; $mailBody .= __f('UserID: %s', $currentUid) . "\n"; $mailBody .= __f('Date: %s', DateUtil::strftime(__('%b %d, %Y'), (time()))) . "\n"; if ($idsImpactMode == 1) { $mailBody .= __f('Request Impact: %d', $requestImpact) . "\n"; } else { $mailBody .= __f('Session Impact: %d', $sessionImpact) . "\n"; } $mailBody .= __f('Affected tags: %s', join(' ', $result->getTags())) . "\n"; $attackedParameters = ''; foreach ($result as $event) { $attackedParameters .= $event->getName() . '=' . urlencode($event->getValue()) . ", "; } $mailBody .= __f('Affected parameters: %s', trim($attackedParameters)) . "\n"; $mailBody .= __f('Request URI: %s', urlencode($currentPage)); // prepare other mail arguments $siteName = System::getVar('sitename'); $adminmail = System::getVar('adminmail'); $mailTitle = __('Intrusion attempt detected by PHPIDS'); if (ModUtil::available('Mailer')) { $args = array(); $args['fromname'] = $siteName; $args['fromaddress'] = $adminmail; $args['toname'] = 'Site Administrator'; $args['toaddress'] = $adminmail; $args['subject'] = $mailTitle; $args['body'] = $mailBody; $rc = ModUtil::apiFunc('Mailer', 'user', 'sendmessage', $args); } else { $headers = "From: $siteName <$adminmail>\n" ."X-Priority: 1 (Highest)"; System::mail($adminmail, $mailTitle, $mailBody, $headers); } } if ($usedImpact > $impactThresholdThree) { // block request if (System::getVar('idssoftblock')) { // warn only for debugging the ruleset LogUtil::registerError(__('Malicious request code / a hacking attempt was detected. This request has NOT been blocked!')); } else { throw new Zikula_Exception_Forbidden(__('Malicious request code / a hacking attempt was detected. Thus this request has been blocked.'), null, $result); } } return; }
/** * view items */ public function view($args) { $this->throwForbiddenUnless(SecurityUtil::checkPermission('Feeds::', "::", ACCESS_EDIT), LogUtil::getErrorMsgPermission()); $startnum = FormUtil::getPassedValue('startnum', isset($args['startnum']) ? $args['startnum'] : null, 'GET'); $property = FormUtil::getPassedValue('feeds_property', isset($args['feeds_property']) ? $args['feeds_property'] : null, 'POST'); $category = FormUtil::getPassedValue("feeds_{$property}_category", isset($args["feeds_{$property}_category"]) ? $args["feeds_{$property}_category"] : null, 'POST'); $clear = FormUtil::getPassedValue('clear', false, 'POST'); $purge = FormUtil::getPassedValue('purge', false, 'GET'); if (!PluginUtil::isAvailable('systemplugin.simplepie')) { LogUtil::registerError($this->__('<strong>Fatal error: The required SimplePie system plugin is not available.</strong><br /><br />Zikula ships with the SimplePie plugin located in the docs/examples/plugins/ExampleSystemPlugin/SimplePie directory. It must be copied (or symlinked) from there and pasted into the /plugins directory. The plugin must then be installed. This is done via the Extensions module. Click on the System Plugins menu item and install the SimplePie plugin.')); } if ($purge) { if (ModUtil::apiFunc('Feeds', 'admin', 'purgepermalinks')) { LogUtil::registerStatus($this->__('Purging of the pemalinks was successful')); } else { LogUtil::registerError($this->__('Purging of the pemalinks has failed')); } return System::redirect(strpos(System::serverGetVar('HTTP_REFERER'), 'purge') ? ModUtil::url('Feeds', 'admin', 'view') : System::serverGetVar('HTTP_REFERER')); } if ($clear) { $property = null; $category = null; } // get module vars for later use $modvars = ModUtil::getVar('Feeds'); if ($modvars['enablecategorization']) { // load the category registry util $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('Feeds', 'feeds'); $properties = array_keys($catregistry); // Validate and build the category filter - mateo if (!empty($property) && in_array($property, $properties) && !empty($category)) { $catFilter = array($property => $category); } // Assign a default property - mateo if (empty($property) || !in_array($property, $properties)) { $property = $properties[0]; } // plan ahead for ML features $propArray = array(); foreach ($properties as $prop) { $propArray[$prop] = $prop; } } // Get all the feeds $items = ModUtil::apiFunc('Feeds', 'user', 'getall', array('startnum' => $startnum, 'numitems' => $modvars['itemsperpage'], 'order' => 'fid', 'category' => isset($catFilter) ? $catFilter : null, 'catregistry' => isset($catregistry) ? $catregistry : null)); $feedsitems = array(); foreach ($items as $item) { if (SecurityUtil::checkPermission('Feeds::', "$item[name]::$item[fid]", ACCESS_READ)) { // Options for the item $options = array(); if (SecurityUtil::checkPermission('Feeds::', "$item[name]::$item[fid]", ACCESS_EDIT)) { $options[] = array('url' => ModUtil::url('Feeds', 'user', 'display', array('fid' => $item['fid'])), 'image' => 'kview.png', 'title' => $this->__('View')); $options[] = array('url' => ModUtil::url('Feeds', 'admin', 'modify', array('fid' => $item['fid'])), 'image' => 'xedit.png', 'title' => $this->__('Edit')); if (SecurityUtil::checkPermission('Feeds::', "$item[name]::$item[fid]", ACCESS_DELETE)) { $options[] = array('url' => ModUtil::url('Feeds', 'admin', 'delete', array('fid' => $item['fid'])), 'image' => '14_layer_deletelayer.png', 'title' => $this->__('Delete')); } } $item['options'] = $options; $feedsitems[] = $item; } } // Assign the items and modvars to the template $this->view->assign('feedsitems', $feedsitems); $this->view->assign($modvars); // Assign the default language $this->view->assign('lang', ZLanguage::getLanguageCode()); // Assign the categories information if enabled if ($modvars['enablecategorization']) { $this->view->assign('catregistry', $catregistry); $this->view->assign('numproperties', count($propArray)); $this->view->assign('properties', $propArray); $this->view->assign('property', $property); $this->view->assign("category", $category); } // Assign the values for the smarty plugin to produce a pager $this->view->assign('pager', array('numitems' => ModUtil::apiFunc('Feeds', 'user', 'countitems', array('category' => isset($catFilter) ? $catFilter : null)), 'itemsperpage' => $modvars['itemsperpage'])); // Return the output that has been generated by this function return $this->view->fetch('admin/view.tpl'); }
/** * Decode the path string into a set of variable/value pairs. * * This API works in conjunction with the new short urls * system to extract a path based variable set into the Get, Post * and request superglobals. * A sample path is /modname/function/var1:value1. * * @return void */ public static function queryStringDecode() { if (self::isInstalling()) { return; } // get our base parameters to work out if we need to decode the url $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING); $func = FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING); $type = FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING); // check if we need to decode the url if (self::getVar('shorturls') && (empty($module) && empty($type) && empty($func))) { // user language is not set at this stage $lang = System::getVar('language_i18n', ''); $customentrypoint = self::getVar('entrypoint'); $expectEntrypoint = !self::getVar('shorturlsstripentrypoint'); $root = empty($customentrypoint) ? 'index.php' : $customentrypoint; // check if we hit baseurl, e.g. domain.com/ and if we require the language URL // then we should redirect to the language URL. if (ZLanguage::isRequiredLangParam() && self::getCurrentUrl() == self::getBaseUrl()) { $uri = $expectEntrypoint ? "{$root}/{$lang}" : "{$lang}"; self::redirect(self::getBaseUrl() . $uri); self::shutDown(); } // check if entry point is part of the URL expectation. If so throw error if it's not present // since this URL is technically invalid. if ($expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) !== 0) { $protocol = System::serverGetVar('SERVER_PROTOCOL'); header("{$protocol} 404 Not Found"); echo __('The requested URL cannot be found'); system::shutDown(); } if (!$expectEntrypoint && self::getCurrentUrl() == self::getBaseUrl() . $root) { self::redirect(self::getHomepageUrl()); self::shutDown(); } if (!$expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) === 0) { $protocol = System::serverGetVar('SERVER_PROTOCOL'); header("{$protocol} 404 Not Found"); echo __('The requested URL cannot be found'); system::shutDown(); } // get base path to work out our current url $parsedURL = parse_url(self::getCurrentUri()); // strip any unwanted content from the provided URL $tobestripped = array(self::getBaseUri(), "{$root}"); $path = str_replace($tobestripped, '', $parsedURL['path']); $path = trim($path, '/'); // split the path into a set of argument strings $args = explode('/', rtrim($path, '/')); // ensure that each argument is properly decoded foreach ($args as $k => $v) { $args[$k] = urldecode($v); } $modinfo = null; $frontController = $expectEntrypoint ? "{$root}/" : ''; // if no arguments present if (!$args[0] && !isset($_GET['lang']) && !isset($_GET['theme'])) { // we are in the homepage, checks if language code is forced if (ZLanguage::getLangUrlRule() && $lang) { // and redirect then $response = new RedirectResponse(self::getCurrentUrl() . "/{$lang}"); $respose->send(); System::shutDown(); } } else { // check the existing shortURL parameters // validation of the first parameter as language code if (ZLanguage::isLangParam($args[0]) && in_array($args[0], ZLanguage::getInstalledLanguages())) { // checks if the language is not enforced and this url is passing the default lang if (!ZLanguage::getLangUrlRule() && $lang == $args[0]) { // redirects the passed arguments without the default site language array_shift($args); foreach ($args as $k => $v) { $args[$k] = urlencode($v); } $response = new RedirectResponse(self::getBaseUrl() . $frontController . ($args ? implode('/', $args) : '')); $respose->send(); System::shutDown(); } self::queryStringSetVar('lang', $args[0]); array_shift($args); } elseif (ZLanguage::getLangUrlRule()) { // if the lang is forced, redirects the passed arguments plus the lang foreach ($args as $k => $v) { $args[$k] = urlencode($v); } $langTheme = isset($_GET['theme']) ? "{$lang}/{$_GET['theme']}" : $lang; $response = new RedirectResponse(self::getBaseUrl() . $frontController . $langTheme . '/' . implode('/', $args)); $response->send(); System::shutDown(); } // check if there are remaining arguments if ($args) { // try the first argument as a module $modinfo = ModUtil::getInfoFromName($args[0]); if ($modinfo) { array_shift($args); } } // if that fails maybe it's a theme if ($args && !$modinfo) { $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($args[0])); if ($themeinfo) { self::queryStringSetVar('theme', $themeinfo['name']); // now shift the vars and continue as before array_shift($args); if ($args) { $modinfo = ModUtil::getInfoFromName($args[0]); if ($modinfo) { array_shift($args); } } } } // if there are parameters (not homepage) // try to see if there's a default shortURLs module if ($args && !$modinfo) { // add the default module handler into the code $modinfo = ModUtil::getInfoFromName(self::getVar('shorturlsdefaultmodule')); } } // check if there is a module and a custom url handler for it // if not decode the url using the default handler if ($modinfo && $modinfo['type'] != 0) { // prepare the arguments to the module handler array_unshift($args, ''); // support for 1.2- empty parameter due the initial explode array_unshift($args, $modinfo['url']); // set the REQUEST parameters self::queryStringSetVar('module', $modinfo['name']); // the user.function name can be the second argument string, set a default // later the custom module handler (if exists) must setup a new one if needed self::queryStringSetVar('type', 'user'); if (isset($args[2])) { self::queryStringSetVar('func', $args[2]); } else { self::queryStringSetVar('func', 'index'); } if (!ModUtil::apiFunc($modinfo['name'], 'user', 'decodeurl', array('vars' => $args))) { // any remaining arguments are specific to the module $argscount = count($args); for ($i = 3; $i < $argscount; $i = $i + 2) { if (isset($args[$i]) && isset($args[$i + 1])) { self::queryStringSetVar($args[$i], urldecode($args[$i + 1])); } } } } } }
/** * Confirm auth key. * * @param string $modname Module name. * @param string $varname Variable name. * * @deprecated since 1.3.0 * * @return boolean */ public static function confirmAuthKey($modname = '', $varname = 'authid') { LogUtil::log(__f('Warning! Static call %1$s is deprecated. Please use %2$s instead.', array('SecurityUtil::confirmAuthKey()', 'SecurityUtil::validateCsrfToken()')), E_USER_DEPRECATED); if (!$varname) { $varname = 'authid'; } $authid = FormUtil::getPassedValue($varname); if (empty($modname)) { $modname = ModUtil::getName(); } // Remove from 1.4 if (System::isLegacyMode() && $modname == 'Modules') { LogUtil::log(__('Warning! "Modules" module has been renamed to "Extensions". Warning! "Modules" module has been renamed to "Extensions". Please update any "confirmAuthKey" calls in PHP or templates.')); $modname = 'ZikulaExtensionsModule'; } // get the module info $modinfo = ModUtil::getInfoFromName($modname); $modname = strtolower($modinfo['name']); // get the array of randomed values per module and check if exists $rand_arr = SessionUtil::getVar('rand'); if (!isset($rand_arr[$modname])) { return false; } else { $rand = $rand_arr[$modname]; } // Regenerate static part of key $key = $rand . $modname; // validate useragent if (System::getVar('sessionauthkeyua')) { $useragent = sha1(System::serverGetVar('HTTP_USER_AGENT')); if (SessionUtil::getVar('useragent') != $useragent) { return false; } } // Test works because timestamp is embedded in authkey and appended // at the end of the authkey, so we can test validity of authid as // well as the number of seconds elapsed since generation. $keyexpiry = (int) System::getVar('keyexpiry'); $timestamp = $keyexpiry > 0 ? substr($authid, 40, strlen($authid)) : ''; $key .= $timestamp; // check build key against authid if (sha1($key) == substr($authid, 0, 40)) { // now test if time expired $elapsedTime = (int) ((int) $timestamp > 0 ? time() - $timestamp : $keyexpiry - 1); if ($elapsedTime < $keyexpiry) { $rand_arr[$modname] = RandomUtil::getString(32, 40, false, true, true, false, true, true, false); SessionUtil::setVar('rand', $rand_arr); return true; } } return false; }