コード例 #1
0
ファイル: pnuser.php プロジェクト: tempbottle/FlashChatBridge
function FlashChatBridge_user_showChat()
{
    // perform permission check
    if (!SecurityUtil::checkPermission('FlashChatBridge::', '::', ACCESS_READ)) {
        return LogUtil::registerPermissionError();
    }
    $popup = FormUtil::getPassedValue('popup', false);
    // Security check
    $render =& pnRender::getInstance('FlashChatBridge', false);
    $UserVars = pnUserGetVars(SessionUtil::getVar('uid'));
    $client_type = FormUtil::getPassedValue('client_type', 'standard');
    $settings = pnModGetVar('FlashChatBridge');
    $settings['init_user'] = $UserVars['uname'];
    $settings['init_password'] = $UserVars['pass'];
    if ($settings['autosize'] == 1) {
        $settings['width'] = "100%";
        $settings['height'] = "100%";
    }
    if ($popup) {
        $settings['width'] = "100%";
        $settings['height'] = "100%";
        $render->assign('settings', $settings);
        $chat = $render->fetch("flashchatbridge_user_chat_{$client_type}.htm");
        $render->assign('chat', $chat);
        echo $render->fetch('flashchatbridge_user_popup.htm');
        exit;
    } else {
        $render->assign('settings', $settings);
        return $render->fetch("flashchatbridge_user_chat_{$client_type}.htm");
    }
}
コード例 #2
0
ファイル: Util.php プロジェクト: robbrandt/Content
 public static function contentMainEditExpandAll($belowPageId = null)
 {
     $expandedPageIds = SessionUtil::getVar('contentExpandedPageIds', array());
     foreach (Content_Util::contentMainEditGetPagesList($belowPageId) as $page) {
         $expandedPageIds[$page['id']] = 1;
     }
     SessionUtil::setVar('contentExpandedPageIds', $expandedPageIds);
 }
コード例 #3
0
/**
 * display block
 *
 * @param        array       $blockinfo     a blockinfo structure
 * @return       output      the rendered bock
 */
function FlashChatBridge_Bannerchatblock_display($blockinfo)
{
    if (!SecurityUtil::checkPermission('FlashChatBridge:Bannerchatblock:', "::", ACCESS_READ)) {
        return false;
    }
    if (!pnModAvailable('FlashChatBridge') || !pnUserLoggedIn()) {
        return false;
    }
    $render = pnRender::getInstance('FlashChatBridge', false);
    $UserVars = pnUserGetVars(SessionUtil::getVar('uid'));
    $settings = pnModGetVar('FlashChatBridge');
    $settings['init_user'] = $UserVars['uname'];
    $settings['init_password'] = $UserVars['pass'];
    $settings['width'] = "100%";
    $settings['height'] = "150";
    $render->assign('settings', $settings);
    $blockinfo['content'] = $render->fetch('flashchatbridge_user_chat_banner.htm');
    return pnBlockThemeBlock($blockinfo);
}
コード例 #4
0
/**
 * Content
 *
 * @copyright (C) 2007-2010, Content Development Team
 * @link http://github.com/zikula-modules/Content
 * @license See license.txt
 */
function smarty_function_contenteditthis($params, $view)
{
    $dom = ZLanguage::getModuleDomain('Content');
    $data = $params['data'];
    $type = $params['type'];
    $access = $params['access'];
    if (!$access['pageEditAllowed']) {
        return '';
    }
    $editmode = SessionUtil::getVar('ContentEditMode');
    $vars = $view->get_template_vars();
    if ($vars['preview']) {
        return '';
    }
    $html = '';
    if ($type == 'page') {
        // Unused ...
        $html = '<div class="content-editthis">';
        $url = DataUtil::formatForDisplay(ModUtil::url('Content', 'admin', 'editPage', array('pid' => $data['id'], 'back' => 1)));
        $translateurl = DataUtil::formatForDisplay(ModUtil::url('Content', 'admin', 'translatePage', array('pid' => $data['id'], 'back' => 1)));
        $html .= "<a href=\"{$url}\">" . __("Edit this page", $dom) . "</a>";
        if ($vars['multilingual'] == 1) {
            $html .= "| <a href=\"{$translateurl}\">" . __("Translate this page", $dom) . "</a>";
        }
        $html .= '</div>';
    } elseif ($type == 'content' && $editmode) {
        $html = '<div class="content-editthis">';
        $url = DataUtil::formatForDisplay(ModUtil::url('Content', 'admin', 'editContent', array('cid' => $data['id'], 'back' => 1)));
        $translateurl = DataUtil::formatForDisplay(ModUtil::url('Content', 'admin', 'translateContent', array('cid' => $data['id'], 'back' => 1)));
        $edittext = __f('Edit this: %1$s [ID%2$s]', array($data['title'], $data['id']), $dom);
        $html .= "<a href=\"{$url}\" title=\"" . __("Click to edit this content item", $dom) . "\">" . $edittext . "</a> ";
        if ($vars['multilingual'] == 1) {
            $html .= "<a href=\"{$translateurl}\">" . __("Translate", $dom) . "</a>";
        }
        $html .= '</div>';
    }
    if (isset($params['assign'])) {
        $smarty->assign($params['assign'], $html);
    } else {
        return $html;
    }
}
コード例 #5
0
ファイル: Legacy.php プロジェクト: rmaiwald/core
 /**
  * {@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;
 }
コード例 #6
0
ファイル: User.php プロジェクト: rmaiwald/BBSmile
 /**
  * bbsmiles
  * returns a html snippet with buttons for inserting bbsmiles into a text
  *
  * @param    $args['textfieldid']  id of the textfield for inserting smilies
  */
 public function bbsmiles($args)
 {
     if (!isset($args['textfieldid']) || empty($args['textfieldid'])) {
         return LogUtil::registerArgsError();
     }
     // if we have more than one textarea we need to distinguish them, so we simply use
     // a counter stored in a session var until we find a better solution
     $counter = SessionUtil::getVar('bbsmile_counter', 0);
     $counter++;
     SessionUtil::setVar('bbsmile_counter', $counter);
     $this->view->assign('counter', $counter);
     $this->view->assign('textfieldid', $args['textfieldid']);
     PageUtil::addVar('stylesheet', ThemeUtil::getModuleStylesheet('BBSmile'));
     $templatefile = DataUtil::formatForOS(ModUtil::getName()) . '.tpl';
     if ($this->view->template_exists($templatefile)) {
         return $this->view->fetch($templatefile);
     }
     $this->view->add_core_data();
     return $this->view->fetch('bbsmile_user_bbsmiles.tpl');
 }
コード例 #7
0
/**
 * Zikula_View block to implement group checks in a template.
 *
 * Available attributes:
 *  - gid (numeric) The ID number of the group to be tested.
 *
 * Example:
 * <pre>
 * {checkgroup gid='1'}
 *   do some stuff now we have permission
 * {/checkgroup}
 * </pre>.
 *
 * @param array       $params  All attributes passed to this function from the template.
 * @param string      $content The content between the block tags.
 * @param Zikula_View $view    Reference to the {@link Zikula_View} object.
 *
 * @return string|boolean|void The content of the matching case.
 *                             If the user is a member of the group specified by the gid,
 *                             then the content contained in the block, otherwise null,
 *                             false on error.
 */
function smarty_block_checkgroup($params, $content, Zikula_View $view)
{
    // check if there is something between the tags
    if (is_null($content)) {
        return;
    }
    // check our input
    if (!isset($params['gid'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('smarty_block_checkgroup', 'component')));
        return false;
    }
    $uid = SessionUtil::getVar('uid');
    if (empty($uid)) {
        return;
    }
    if (!ModUtil::apiFunc('Groups', 'user', 'isgroupmember', array('uid' => $uid, 'gid' => $params['gid']))) {
        return;
    }
    return $content;
}
コード例 #8
0
ファイル: Main.php プロジェクト: robbrandt/Content
 public function initialize(Zikula_Form_View $view)
 {
     if (!SecurityUtil::checkPermission('Content:page:', '::', ACCESS_EDIT)) {
         throw new Zikula_Exception_Forbidden(LogUtil::getErrorMsgPermission());
     }
     // Include categories only when 2nd category enabled in settings
     $pages = ModUtil::apiFunc('Content', 'Page', 'getPages', array('editing' => true, 'filter' => array('checkActive' => false, 'expandedPageIds' => SessionUtil::getVar('contentExpandedPageIds', array())), 'enableEscape' => true, 'translate' => false, 'includeLanguages' => true, 'includeCategories' => $this->getVar('categoryUsage') < 3, 'orderBy' => 'setLeft'));
     if ($pages === false) {
         return $this->view->registerError(null);
     }
     // Get categories names if enabled
     if ($this->getVar('$categoryUsage') < 4) {
         $lang = ZLanguage::getLanguageCode();
         $categories = array();
         foreach ($pages as $page) {
             $cat = CategoryUtil::getCategoryByID($page['categoryId']);
             $categories[$page['id']] = array();
             $categories[$page['id']][] = isset($cat['display_name'][$lang]) ? $cat['display_name'][$lang] : $cat['name'];
             if (isset($page['categories']) && is_array($page['categories'])) {
                 foreach ($page['categories'] as $pageCat) {
                     $cat = CategoryUtil::getCategoryByID($pageCat['categoryId']);
                     $categories[$page['id']][] = isset($cat['display_name'][$lang]) ? $cat['display_name'][$lang] : $cat['name'];
                 }
             }
         }
         $this->view->assign('categories', $categories);
     }
     PageUtil::setVar('title', $this->__('Page list and content structure'));
     $csssrc = ThemeUtil::getModuleStylesheet('admin', 'admin.css');
     PageUtil::addVar('stylesheet', $csssrc);
     $this->view->assign('pages', $pages);
     $this->view->assign('multilingual', ModUtil::getVar(ModUtil::CONFIG_MODULE, 'multilingual'));
     $this->view->assign('enableVersioning', $this->getVar('enableVersioning'));
     $this->view->assign('language', ZLanguage::getLanguageCode());
     Content_Util::contentAddAccess($this->view, null);
     return true;
 }
コード例 #9
0
ファイル: ZLanguage.php プロジェクト: projectesIF/Sirius
 /**
  * Constructor.
  */
 public function __construct()
 {
     $this->langSession = SessionUtil::getVar('language', null);
     $this->langSystemDefault = System::getVar('language_i18n', 'en');
     $this->languageCode = $this->langSystemDefault;
     $this->langFixSession = preg_replace('#[^a-z-].#', '', FormUtil::getPassedValue('setsessionlanguage', null, 'POST'));
     $this->multiLingualCapable = System::getVar('multilingual');
     $this->langUrlRule = System::getVar('languageurl', 0);
     $this->langDetect = System::getVar('language_detect', 0);
     $this->setDBCharset();
     $this->setEncoding();
 }
コード例 #10
0
ファイル: UserUtil.php プロジェクト: projectesIF/Sirius
 /**
  * Determine if the current session is that of an anonymous user.
  *
  * @return boolean
  */
 public static function isGuestUser()
 {
     return !SessionUtil::getVar('uid', 0);
 }
コード例 #11
0
ファイル: template.php プロジェクト: nmpetkov/ZphpBB2
 /**
  * Compiles the given string of code, and returns
  * the result in a string.
  * If "do_not_echo" is true, the returned code will not be directly
  * executable, but can be used as part of a variable assignment
  * for use in assign_code_from_handle().
  */
 function compile($code, $do_not_echo = false, $retvar = '')
 {
     // Begin PNphpBB2 Module
     global $board_config, $gen_simple_header;
     if (!defined('PNPHPBB_TEMPLATE') && empty($gen_simple_header) && SessionUtil::getVar('fullpage') == 0) {
         $search = array("'<\\!doctype\\s+.*?>'si", "'<title[^>]*?>.*?</title>'si", "'<head>'i", "'</head>'i", "'<html>'i", "'<html\\s+.*?>'i", "'</html>'i", "'body\\s*{(\\s*[a-zA-Z0-9\\-_]*:\\s*{[a-zA-Z0-9\\-_]*};*)*\\s*}'i", "'/\\*.*?\\*/'i", "'<body\\s+.*?>'si", "'</body\\s+.*?>'si", "'<font.*?>'i", "'</font>'i");
         $replace = array("", "", "", "", "", "", "", "", "", "", "", "", "");
         $code = preg_replace($search, $replace, $code);
     }
     if (!defined(PNPHPBB_TEMPLATE)) {
         $code = str_replace("../templates/", "./modules/ZphpBB2/vendor/phpBB2/templates/", $code);
         $code = str_replace("\"templates/", "\"./modules/ZphpBB2/vendor/phpBB2/templates/", $code);
         $code = str_replace("url(templates", "url(./modules/ZphpBB2/vendor/phpBB2/templates", $code);
         $search = array("'font(?!-).*?\\s*{(\\s*[a-zA-Z0-9\\-_]*\\s*:\\s*{[a-zA-Z0-9\\-_]*};*)*\\s*}'i", "'a:(link|active|visited|hover|).*?{(\\s*[a-zA-Z0-9\\-_]*\\s*:\\s*.*?;)*\\s*}'i", "'<input\\s+type\\s*=\\s*\"?text\"?\\s+name\\s*=\\s*\"?username\"?'i", "'<input\\s+type\\s*=\\s*\"?password\"?\\s+name\\s*=\\s*\"?password\"?'i", "'<input\\s+type\\s*=\\s*\"?checkbox\"?\\s+name\\s*=\\s*\"?autologin\"?'i", "'\\.copyright'i", "'<span\\s+class\\s*=\\s*\"?copyright\"?'i");
         $replace = array("", "", '<input type="text" name="uname"', '<input type="password" name="pass"', '<input type="checkbox" name="rememberme"', "", '<div class="gensmall" align="center"');
         $code = preg_replace($search, $replace, $code);
         if (preg_match("/L_CONFIGURATION_TITLE/i", $code)) {
             $code = preg_replace("'<tr[^>]*>[^<]*(<(?!tr)[^<]*)*(L_SERVER_NAME|L_SERVER_PORT|L_SCRIPT_PATH|L_SITE_NAME|L_SITE_DESCRIPTION|L_ACCT_ACTIVATION|L_VISUAL_CONFIRM|L_ALLOW_AUTOLOGIN|L_AUTOLOGIN_TIME|L_DATE_FORMAT|L_SYSTEM_TIMEZONE|L_ENABLE_GZIP|L_COOKIE_SECURE|L_ALLOW_NAME_CHANGE|L_COPPA_SETTINGS|L_COPPA_FAX|L_COPPA_MAIL|L_DEFAULT_LANGUAGE|L_TIMEZONE).*?</tr>'si", "", $code);
         }
         if (preg_match("/L_REGISTRATION_INFO/i", $code)) {
             //				$code = preg_replace ("'<table[^>]*>[^<]*(<(?!table)[^<]*)*(L_REGISTRATION_INFO).*?</table>'si", "", $code);
             $code = preg_replace("'<tr[^>]*>[^<]*(<(?!tr)[^<]*)*(L_REGISTRATION_INFO|L_ITEMS_REQUIRED|L_USERNAME|L_EMAIL_ADDRESS|L_NEW_PASSWORD|L_CONFIRM_PASSWORD|L_ICQ_NUMBER|L_AIM|L_MESSENGER|L_YAHOO|L_WEBSITE|L_LOCATION|L_OCCUPATION|L_INTERESTS|L_BOARD_LANGUAGE|L_DATE_FORMAT|L_TIMEZONE).*?</tr>'si", "", $code);
         }
     }
     // End PNphpBB2 Module
     // replace \ with \\ and then ' with \'.
     $code = str_replace('\\', '\\\\', $code);
     $code = str_replace('\'', '\\\'', $code);
     // change template varrefs into PHP varrefs
     // This one will handle varrefs WITH namespaces
     $varrefs = array();
     preg_match_all('#\\{(([a-z0-9\\-_]+?\\.)+?)([a-z0-9\\-_]+?)\\}#is', $code, $varrefs);
     $varcount = sizeof($varrefs[1]);
     for ($i = 0; $i < $varcount; $i++) {
         $namespace = $varrefs[1][$i];
         $varname = $varrefs[3][$i];
         $new = $this->generate_block_varref($namespace, $varname);
         $code = str_replace($varrefs[0][$i], $new, $code);
     }
     // This will handle the remaining root-level varrefs
     $code = preg_replace('#\\{([a-z0-9\\-_]*?)\\}#is', '\' . ( ( isset($this->_tpldata[\'.\'][0][\'\\1\']) ) ? $this->_tpldata[\'.\'][0][\'\\1\'] : \'\' ) . \'', $code);
     // Break it up into lines.
     $code_lines = explode("\n", $code);
     $block_nesting_level = 0;
     $block_names = array();
     $block_names[0] = ".";
     // Second: prepend echo ', append ' . "\n"; to each line.
     $line_count = sizeof($code_lines);
     for ($i = 0; $i < $line_count; $i++) {
         $code_lines[$i] = chop($code_lines[$i]);
         if (preg_match('#<!-- BEGIN (.*?) -->#', $code_lines[$i], $m)) {
             $n[0] = $m[0];
             $n[1] = $m[1];
             // Added: dougk_ff7-Keeps templates from bombing if begin is on the same line as end.. I think. :)
             if (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $n)) {
                 $block_nesting_level++;
                 $block_names[$block_nesting_level] = $m[1];
                 if ($block_nesting_level < 2) {
                     // Block is not nested.
                     $code_lines[$i] = '$_' . $n[1] . '_count = ( isset($this->_tpldata[\'' . $n[1] . '.\']) ) ?  sizeof($this->_tpldata[\'' . $n[1] . '.\']) : 0;';
                     $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
                     $code_lines[$i] .= "\n" . '{';
                 } else {
                     // This block is nested.
                     // Generate a namespace string for this block.
                     $namespace = implode('.', $block_names);
                     // strip leading period from root level..
                     $namespace = substr($namespace, 2);
                     // Get a reference to the data array for this block that depends on the
                     // current indices of all parent blocks.
                     $varref = $this->generate_block_data_ref($namespace, false);
                     // Create the for loop code to iterate over this block.
                     $code_lines[$i] = '$_' . $n[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
                     $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
                     $code_lines[$i] .= "\n" . '{';
                 }
                 // We have the end of a block.
                 unset($block_names[$block_nesting_level]);
                 $block_nesting_level--;
                 $code_lines[$i] .= '} // END ' . $n[1];
                 $m[0] = $n[0];
                 $m[1] = $n[1];
             } else {
                 // We have the start of a block.
                 $block_nesting_level++;
                 $block_names[$block_nesting_level] = $m[1];
                 if ($block_nesting_level < 2) {
                     // Block is not nested.
                     $code_lines[$i] = '$_' . $m[1] . '_count = ( isset($this->_tpldata[\'' . $m[1] . '.\']) ) ? sizeof($this->_tpldata[\'' . $m[1] . '.\']) : 0;';
                     $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
                     $code_lines[$i] .= "\n" . '{';
                 } else {
                     // This block is nested.
                     // Generate a namespace string for this block.
                     $namespace = implode('.', $block_names);
                     // strip leading period from root level..
                     $namespace = substr($namespace, 2);
                     // Get a reference to the data array for this block that depends on the
                     // current indices of all parent blocks.
                     $varref = $this->generate_block_data_ref($namespace, false);
                     // Create the for loop code to iterate over this block.
                     $code_lines[$i] = '$_' . $m[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
                     $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
                     $code_lines[$i] .= "\n" . '{';
                 }
             }
         } else {
             if (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $m)) {
                 // We have the end of a block.
                 unset($block_names[$block_nesting_level]);
                 $block_nesting_level--;
                 $code_lines[$i] = '} // END ' . $m[1];
             } else {
                 // We have an ordinary line of code.
                 if (!$do_not_echo) {
                     $code_lines[$i] = 'echo \'' . $code_lines[$i] . '\' . "\\n";';
                 } else {
                     $code_lines[$i] = '$' . $retvar . '.= \'' . $code_lines[$i] . '\' . "\\n";';
                 }
             }
         }
     }
     // Bring it back into a single string of lines of code.
     $code = implode("\n", $code_lines);
     return $code;
 }
コード例 #12
0
ファイル: Filter.php プロジェクト: projectesIF/Sirius
    /**
     * 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;
    }
コード例 #13
0
ファイル: ORM.php プロジェクト: Silwereth/core
 /**
  * {@inheritdoc}
  */
 public function getUserIdValue(ClassMetadata $meta, $field)
 {
     return \SessionUtil::getVar('uid', 0);
 }
コード例 #14
0
ファイル: AdminController.php プロジェクト: rmaiwald/core
 /**
  * @Route("/edit/{cid}/{dr}/{mode}", requirements={"cid" = "^[1-9]\d*$", "dr" = "^[1-9]\d*$", "mode" = "edit|new"})
  * @Method("GET")
  *
  * edit category
  *
  * @param Request $request
  * @param integer $cid
  * @param integer $dr
  * @param string $mode new|edit
  *
  * @return Response symfony response object
  *
  * @throws AccessDeniedException Thrown if the user doesn't have permission to edit or add the category
  */
 public function editAction(Request $request, $cid = 0, $dr = 1, $mode = "new")
 {
     $editCat = '';
     $languages = ZLanguage::getInstalledLanguages();
     // indicates that we're editing
     if ($mode == 'edit') {
         if (!SecurityUtil::checkPermission('ZikulaCategoriesModule::category', '::', ACCESS_EDIT)) {
             throw new AccessDeniedException();
         }
         if (!$cid) {
             $request->getSession()->getFlashBag()->add('error', $this->__('Error! Cannot determine valid \'cid\' for edit mode in \'ZikulaCategoriesModule_admin_edit\'.'));
             return new RedirectResponse($this->get('router')->generate('zikulacategoriesmodule_admin_view', array(), RouterInterface::ABSOLUTE_URL));
         }
         $editCat = CategoryUtil::getCategoryByID($cid);
         if (!$editCat) {
             $request->getSession()->getFlashBag()->add('error', $this->__('Sorry! No such item found.'));
             return new RedirectResponse($this->get('router')->generate('zikulacategoriesmodule_admin_view', array(), RouterInterface::ABSOLUTE_URL));
         }
     } else {
         // new category creation
         if (!SecurityUtil::checkPermission('ZikulaCategoriesModule::category', '::', ACCESS_ADD)) {
             throw new AccessDeniedException();
         }
         // since we inherit the domain settings from the parent, we get
         // the inherited (and merged) object from session
         if (isset($_SESSION['newCategory']) && $_SESSION['newCategory']) {
             $editCat = $_SESSION['newCategory'];
             unset($_SESSION['newCategory']);
             $category = new CategoryEntity();
             // need this for validation info
         } elseif (FormUtil::getValidationErrors()) {
             // if we're back from validation get the posted data from session
             $newCatActionData = \SessionUtil::getVar('newCatActionData');
             \SessionUtil::delVar('newCatActionData');
             $editCat = new CategoryEntity();
             $editCat = $editCat->toArray();
             $editCat = array_merge($editCat, $newCatActionData);
             unset($editCat['path']);
             unset($editCat['ipath']);
             $category = new CategoryEntity();
             // need this for validation info
         } else {
             // someone just pressed 'new' -> populate defaults
             $category = new CategoryEntity();
             $editCat['sort_value'] = '0';
         }
     }
     $allCats = CategoryUtil::getSubCategories($dr, true, true, true, false, true);
     // now remove the categories which are below $editCat ...
     // you should not be able to set these as a parent category as it creates a circular hierarchy (see bug #4992)
     if (isset($editCat['ipath'])) {
         $cSlashEdit = StringUtil::countInstances($editCat['ipath'], '/');
         foreach ($allCats as $k => $v) {
             $cSlashCat = StringUtil::countInstances($v['ipath'], '/');
             if ($cSlashCat >= $cSlashEdit && strpos($v['ipath'], $editCat['ipath']) !== false) {
                 unset($allCats[$k]);
             }
         }
     }
     $selector = CategoryUtil::getSelector_Categories($allCats, 'id', isset($editCat['parent_id']) ? $editCat['parent_id'] : 0, 'category[parent_id]', isset($defaultValue) ? $defaultValue : null, null, 0, null, false, false, true, 1, false, 'form-control');
     $attributes = isset($editCat['__ATTRIBUTES__']) ? $editCat['__ATTRIBUTES__'] : array();
     $this->view->assign('mode', $mode)->assign('category', $editCat)->assign('attributes', $attributes)->assign('languages', $languages)->assign('categorySelector', $selector);
     if ($mode == 'edit') {
         $this->view->assign('haveSubcategories', CategoryUtil::haveDirectSubcategories($cid))->assign('haveLeafSubcategories', CategoryUtil::haveDirectSubcategories($cid, false, true));
     }
     return $this->response($this->view->fetch('Admin/edit.tpl'));
 }
コード例 #15
0
ファイル: Movie.php プロジェクト: robbrandt/MUVideo
 /**
  * Selects a list of objects with a given where clause and pagination parameters.
  *
  * @param string  $where          The where clause to use when retrieving the collection (optional) (default='').
  * @param string  $orderBy        The order-by clause to use when retrieving the collection (optional) (default='').
  * @param integer $currentPage    Where to start selection
  * @param integer $resultsPerPage Amount of items to select
  * @param boolean $useJoins       Whether to include joining related objects (optional) (default=true).
  * @param boolean $slimMode       If activated only some basic fields are selected without using any joins (optional) (default=false).
  *
  * @return Array with retrieved collection and amount of total records affected by this query.
  */
 public function selectWherePaginated($where = '', $orderBy = '', $currentPage = 1, $resultsPerPage = 25, $useJoins = true, $slimMode = false)
 {
     $qb = $this->genericBaseQuery($where, $orderBy, $useJoins, $slimMode);
     $page = $currentPage;
     // check if we have any filters set
     $parameters = $this->getViewQuickNavParameters('', array());
     $hasFilters = false;
     foreach ($parameters as $k => $v) {
         if (!is_numeric($v) && $v != '' || is_numeric($v) && $v > 0) {
             $hasFilters = true;
             break;
         }
     }
     if (!$hasFilters) {
         if ($page > 1 || isset($_GET['pos'])) {
             // store current page in session
             SessionUtil::setVar('MUVideoMoviesCurrentPage', $page);
         } else {
             // restore current page from session
             $page = SessionUtil::getVar('MUVideoMoviesCurrentPage', 1);
             System::queryStringSetVar('pos', $page);
         }
     }
     list($query, $count) = $this->getSelectWherePaginatedQuery($qb, $page, $resultsPerPage);
     $result = $this->retrieveCollectionResult($query, $orderBy, true);
     return array($result, $count);
 }
コード例 #16
0
ファイル: Admin.php プロジェクト: projectesIF/Sirius
    public function viewStats($args) {
        $statsSaved = unserialize(SessionUtil::getVar('statsSaved'));

        $moduleName = (isset($statsSaved['moduleName'])) ? $statsSaved['moduleName'] : '';
        $fromDate = (isset($statsSaved['fromDate'])) ? $statsSaved['fromDate'] : null;
        $toDate = (isset($statsSaved['toDate'])) ? $statsSaved['toDate'] : '';

        $moduleName = FormUtil::getPassedValue('moduleName', isset($args['moduleName']) ? $args['moduleName'] : $moduleName, 'GETPOST');
        $uname = FormUtil::getPassedValue('uname', isset($args['uname']) ? $args['uname'] : $statsSaved['uname'], 'GETPOST');
        $fromDate = FormUtil::getPassedValue('fromDate', isset($args['fromDate']) ? $args['fromDate'] : $fromDate, 'GETPOST');
        $toDate = FormUtil::getPassedValue('toDate', isset($args['toDate']) ? $args['toDate'] : $toDate, 'GETPOST');
        $uid = FormUtil::getPassedValue('uid', isset($args['uid']) ? $args['uid'] : 0, 'GETPOST');

        if ($uid > 0) {
            $uname = UserUtil::getVar('uname', $uid);
        }

        SessionUtil::setVar('statsSaved', serialize(array('uname' => $uname,
                    'moduleName' => $moduleName,
                    'fromDate' => $fromDate,
                    'toDate' => $toDate,
                )));


        if (!SecurityUtil::checkPermission('IWstats::', '::', ACCESS_ADMIN)) {
            throw new Zikula_Exception_Forbidden();
        }

        $uid = 0;
        $rpp = 50;
        $lastDays = 10;
        $nusers = 0;

        if ($uname != null && $uname != '') {
            // get user id from uname
            $uid = UserUtil::getIdFromName($uname);
            if (!$uid) {
                LogUtil::registerError(__f('User \'%s\' not found', array($uname)));
                $uname = '';
            }
        }

        $time = time();

        if ($fromDate != null) {
            $fromDate = mktime(0, 0, 0, substr($fromDate, 3, 2), substr($fromDate, 0, 2), substr($fromDate, 6, 4));
            $fromDate = date('Y-m-d 00:00:00', $fromDate);
            $fromDate = DateUtil::makeTimestamp($fromDate);
            $fromDate = date('d-m-Y', $fromDate);
        } else {
            $fromDate = date('d-m-Y', $time - $lastDays * 24 * 60 * 60);
        }

        if ($toDate != null) {
            $toDate = mktime(0, 0, 0, substr($toDate, 3, 2), substr($toDate, 0, 2), substr($toDate, 6, 4));
            $toDate = date('Y-m-d 00:00:00', $toDate);
            $toDate = DateUtil::makeTimestamp($toDate);
            $toDate = date('d-m-Y', $toDate);
        } else {
            $toDate = date('d-m-Y', $time);
        }

        // get last records
        $records = ModUtil::apiFunc('IWstats', 'user', 'getAllSummary', array('rpp' => -1,
                    'init' => -1,
                    'fromDate' => $fromDate,
                    'toDate' => $toDate,
                ));

        // get all modules
        $modules = ModUtil::apiFunc('Extensions', 'admin', 'listmodules', array('state' => 0));

        foreach ($modules as $module) {
            $modulesNames[$module['id']] = $module['name'];
            $modulesArray[] = array('id' => $module['id'],
                'name' => $module['name']);
        }

        $modulesNames[0] = $this->__('unknown');

        $usersListArray = array();
        $moduleStatsArray = array();
        $userModulesArray = array();
        $userArray = array();
        $moduleArray = array();
        $usersForModule = array();
        $users = array();
        $usersIpCounter = 0;
        $nRecords = 0;
        $userNRecords = 0;
        $usersList = '';
        $userName = '';
        foreach ($records as $record) {
            $nRecords = $nRecords + $record['nrecords'];
            $usersIpCounter = $usersIpCounter + $record['nips'];
            $users = explode('$$', substr($record['users'], 1, -1)); // substr to remove $ in the begining and the end of the string
            foreach ($users as $user) {
                $oneUser = explode('|', $user);

                if (!in_array($oneUser[0], $usersListArray)) {
                    $nusers++;
                    $usersListArray[] = $oneUser[0];
                }
                if ($oneUser[0] == $uid && $uid > 0) {
                    $userInit = '$' . $uid . '|';
                    $userDataPos = strpos($record['users'], $userInit);
                    $subDataPre = substr($record['users'], $userDataPos + strlen($userInit));
                    $userDataPos = strpos($subDataPre, '$');
                    $subDataPre = substr($subDataPre, 0, $userDataPos);
                    $userModules = explode('#', $subDataPre);
                    foreach ($userModules as $module) {
                        $oneModule = explode('=', $module);
                        if (array_key_exists($modulesNames[$oneModule[0]], $userModulesArray)) {
                            $userModulesArray[$modulesNames[$oneModule[0]]] = $oneModule[1];
                        } else {
                            $userModulesArray[$modulesNames[$oneModule[0]]] = $userModulesArray[$modulesNames[$oneModule[0]]] + $oneModule[1];
                        }

                        $userNRecords = $userNRecords + $oneModule[1];
                    }
                }
                if ($moduleName != '') {
                    $moduleId = ModUtil::getIdFromName($moduleName);
                    if ((strpos($oneUser[1], $moduleId . '=') !== false && strpos($oneUser[1], $moduleId . '=') == 0) || strpos($oneUser[1], '#' . $moduleId . '=') !== false) {
                        // get the number of views
                        $pos = strpos($oneUser[1], $moduleId . '=');
                        if ($pos != 0) {
                            $pos = strpos($oneUser[1], '#' . $moduleId . '=');
                        }
                        $preString = substr($oneUser[1], $pos);
                        //print $preString . '<br />';
                        if ($pos != 0) {
                            $preString = substr($preString, 1);
                        }
                        $pos = strpos($preString, '#');
                        $preString = ($pos == 0) ? $preString : substr($preString, 0, $pos);
                        $num = explode('=', $preString);
                        if (!array_key_exists($oneUser[0], $usersForModule)) {
                            $usersForModule[$oneUser[0]] = $num[1];
                            $usersList .= $oneUser[0] . '$$';
                        } else {
                            $usersForModule[$oneUser[0]] = $usersForModule[$oneUser[0]] + $num[1];
                        }
                    }
                }
            }

            $modules = explode('$$', substr($record['modules'], 1, -1)); // substr to remove $ in the begining and the end of the string
            foreach ($modules as $module) {
                $oneModule = explode('|', $module);
                if (isset($modulesNames[$oneModule[0]])) {
                    if (!array_key_exists($modulesNames[$oneModule[0]], $moduleStatsArray)) {
                        $moduleStatsArray[$modulesNames[$oneModule[0]]] = $oneModule[1];
                    } else {
                        $moduleStatsArray[$modulesNames[$oneModule[0]]] = $moduleStatsArray[$modulesNames[$oneModule[0]]] + $oneModule[1];
                    }
                }
            }
        }

        ksort($userModulesArray);

        if ($uid > 0) {
            $userArray = array('nRecords' => $userNRecords,
                'userModulesArray' => $userModulesArray,
            );
        }

        ksort($moduleStatsArray);

        if ($uid > 0) {
            $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
            $userName = ModUtil::func('IWmain', 'user', 'getUserInfo', array('info' => 'ncc',
                        'sv' => $sv,
                        'uid' => $uid));
        }

        if ($moduleName != '') {
            $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
            $users = ModUtil::func('IWmain', 'user', 'getAllUsersInfo', array('info' => 'ncc',
                        'sv' => $sv,
                        'list' => $usersList,
                    ));
            $users[0] = $this->__('Unregistered');
        }

        return $this->view->assign('users', $users)
                        ->assign('nRecords', $nRecords)
                        ->assign('nusers', $nusers)
                        ->assign('userName', $userName)
                        ->assign('usersIpCounter', $usersIpCounter)
                        ->assign('modulesNames', $modulesNames)
                        ->assign('modulesArray', $modulesArray)
                        ->assign('moduleName', $moduleName)
                        ->assign('uname', $uname)
                        ->assign('fromDate', $fromDate)
                        ->assign('toDate', $toDate)
                        ->assign('userArray', $userArray)
                        ->assign('maxDate', date('Ymd', time()))
                        ->assign('usersForModule', $usersForModule)
                        ->assign('moduleStatsArray', $moduleStatsArray)
                        ->fetch('IWstats_admin_stats.htm');
    }
コード例 #17
0
 /**
  * View all blocks.
  *
  * @return string HTML output string.
  */
 public function view()
 {
     // Security check
     if (!SecurityUtil::checkPermission('Blocks::', '::', ACCESS_EDIT)) {
         return LogUtil::registerPermissionError();
     }
     $sfilter = SessionUtil::getVar('filter', array(), '/Blocks');
     $filter = FormUtil::getPassedValue('filter', $sfilter);
     $clear = FormUtil::getPassedValue('clear', 0);
     if ($clear) {
         $filter = array();
         SessionUtil::setVar('filter', $filter, '/Blocks');
     }
     // sort and sortdir GET parameters override filter values
     $sort = isset($filter['sort']) && !empty($filter['sort']) ? strtolower($filter['sort']) : 'bid';
     $sortdir = isset($filter['sortdir']) && !empty($filter['sortdir']) ? strtoupper($filter['sortdir']) : 'ASC';
     $filter['sort'] = FormUtil::getPassedValue('sort', $sort, 'GET');
     $filter['sortdir'] = FormUtil::getPassedValue('sortdir', $sortdir, 'GET');
     if ($filter['sortdir'] != 'ASC' && $filter['sortdir'] != 'DESC') {
         $filter['sortdir'] = 'ASC';
     }
     $filter['blockposition_id'] = isset($filter['blockposition_id']) ? $filter['blockposition_id'] : 0;
     $filter['modid'] = isset($filter['modid']) ? $filter['modid'] : 0;
     $filter['language'] = isset($filter['language']) ? $filter['language'] : '';
     $filter['active_status'] = isset($filter['active_status']) ? $filter['active_status'] : 0;
     // generate an authorisation key for the links
     $token = SecurityUtil::generateCsrfToken($this->serviceManager, true);
     // set some default variables
     $rownum = 1;
     $lastpos = '';
     // Get all blocks
     $blocks = ModUtil::apiFunc('Blocks', 'user', 'getall', $filter);
     // we can easily count the number of blocks using count() rather than
     // calling the api function
     $numrows = count($blocks);
     // create an empty arrow to hold the processed items
     $blockitems = array();
     // get all possible block positions
     $blockspositions = ModUtil::apiFunc('Blocks', 'user', 'getallpositions');
     // build assoc array for easier usage later on
     foreach ($blockspositions as $blocksposition) {
         $allbposarray[$blocksposition['pid']] = $blocksposition['name'];
     }
     // loop round each item calculating the additional information
     $blocksitems = array();
     foreach ($blocks as $key => $block) {
         // set the module that holds the block
         $modinfo = ModUtil::getInfo($block['mid']);
         $block['modname'] = $modinfo['displayname'];
         // set the blocks language
         if (empty($block['language'])) {
             $block['language'] = $this->__('All');
         } else {
             $block['language'] = ZLanguage::getLanguageName($block['language']);
         }
         $thisblockspositions = ModUtil::apiFunc('Blocks', 'user', 'getallblockspositions', array('bid' => $block['bid']));
         $bposarray = array();
         foreach ($thisblockspositions as $singleblockposition) {
             $bposarray[] = $allbposarray[$singleblockposition['pid']];
         }
         $block['positions'] = implode(', ', $bposarray);
         unset($bposarray);
         // calculate what options the user has over this block
         $block['options'] = array();
         if ($block['active']) {
             $block['options'][] = array('url' => ModUtil::url('Blocks', 'admin', 'deactivate', array('bid' => $block['bid'], 'csrftoken' => $token)), 'image' => 'folder_grey.png', 'title' => $this->__f('Deactivate \'%s\'', $block['title']), 'noscript' => true);
         } else {
             $block['options'][] = array('url' => ModUtil::url('Blocks', 'admin', 'activate', array('bid' => $block['bid'], 'csrftoken' => $token)), 'image' => 'folder_green.png', 'title' => $this->__f('Activate \'%s\'', $block['title']), 'noscript' => true);
         }
         $block['options'][] = array('url' => ModUtil::url('Blocks', 'admin', 'modify', array('bid' => $block['bid'])), 'image' => 'xedit.png', 'title' => $this->__f('Edit \'%s\'', $block['title']), 'noscript' => false);
         $block['options'][] = array('url' => ModUtil::url('Blocks', 'admin', 'delete', array('bid' => $block['bid'])), 'image' => '14_layer_deletelayer.png', 'title' => $this->__f('Delete \'%s\'', $block['title']), 'noscript' => false);
         $blocksitems[] = $block;
     }
     $this->view->assign('blocks', $blocksitems);
     // get the block positions
     $items = ModUtil::apiFunc('Blocks', 'user', 'getallpositions');
     // Loop through each returned item adding in the options that the user has over the item
     foreach ($items as $key => $item) {
         if (SecurityUtil::checkPermission('Blocks::', "{$item['name']}::", ACCESS_READ)) {
             $options = array();
             if (SecurityUtil::checkPermission('Blocks::', "{$item['name']}::\$", ACCESS_EDIT)) {
                 $options[] = array('url' => ModUtil::url('Blocks', 'admin', 'modifyposition', array('pid' => $item['pid'])), 'image' => 'xedit.png', 'title' => $this->__f('Edit blockposition \'%s\'', $item['name']));
                 if (SecurityUtil::checkPermission('Blocks::', "{$item['name']}::", ACCESS_DELETE)) {
                     $options[] = array('url' => ModUtil::url('Blocks', 'admin', 'deleteposition', array('pid' => $item['pid'])), 'image' => '14_layer_deletelayer.png', 'title' => $this->__f('Delete blockposition \'%s\'', $item['name']));
                 }
             }
             // Add the calculated menu options to the item array
             $items[$key]['options'] = $options;
         }
     }
     // Assign the items to the template
     ksort($items);
     $this->view->assign('positions', $items);
     $this->view->assign('filter', $filter)->assign('sort', $filter['sort'])->assign('sortdir', $filter['sortdir']);
     // Return the output that has been generated by this function
     return $this->view->fetch('blocks_admin_view.tpl');
 }
コード例 #18
0
ファイル: HookHandlers.php プロジェクト: rmaiwald/EZComments
 /**
  * Display hook for view.
  *
  * Subject is the object being viewed that we're attaching to.
  * args[id] Is the id of the object.
  * args[caller] the module who notified of this event.
  *
  * @param Zikula_Hook $hook The hook.
  *
  * @return void
  */
 public function uiView(Zikula_DisplayHook $hook)
 {
     // work out the input from the hook
     $mod = $hook->getCaller();
     $areaId = $hook->getAreaId();
     $objectid = $hook->getId();
     // first check if the user is allowed to do any comments for this module/objectid
     if (!SecurityUtil::checkPermission('EZComments::', "{$mod}:{$objectid}:", ACCESS_OVERVIEW)) {
         return;
     }
     $subject = array();
     //$hook->getSubject();
     $owneruid = isset($subject['cr_uid']) ? (int) $subject['cr_uid'] : 0;
     $useurl = isset($subject['useurl']) ? $subject['useurl'] : null;
     $ownerUidSession = SessionUtil::delVar('commentOwner', 0);
     if ($ownerUidSession > 0) {
         $owneruid = $ownerUidSession;
     }
     // we may have a comment incoming
     $ezcomment = unserialize(SessionUtil::getVar('ezcomment', 'a:0:{}'));
     $ezcomment = isset($ezcomment[$mod][$objectid]) ? $ezcomment[$mod][$objectid] : null;
     // we may get some input in from the navigation bar
     $order = FormUtil::getPassedValue('order');
     $sortorder = $order == 1 ? 'DESC' : 'ASC';
     $status = 0;
     // check if we're using the pager
     $enablepager = ModUtil::getVar('EZComments', 'enablepager');
     if ($enablepager) {
         $numitems = ModUtil::getVar('EZComments', 'commentsperpage');
         $startnum = FormUtil::getPassedValue('comments_startnum');
         if (!isset($startnum) && !is_numeric($startnum)) {
             $startnum = -1;
         }
     } else {
         $startnum = -1;
         $numitems = -1;
     }
     $params = compact('mod', 'areaId', 'objectid', 'sortorder', 'status', 'numitems', 'startnum');
     $items = ModUtil::apiFunc('EZComments', 'user', 'getall', $params);
     if ($items === false) {
         return LogUtil::registerError($this->__('Internal Error.'), null, 'index.php');
     }
     $items = ModUtil::apiFunc('EZComments', 'user', 'prepareCommentsForDisplay', $items);
     if ($enablepager) {
         $commentcount = ModUtil::apiFunc('EZComments', 'user', 'countitems', compact('mod', 'objectid', 'status'));
     } else {
         $commentcount = count($items);
     }
     // create the output object
     $view = Zikula_View::getInstance('EZComments', false, null, true);
     $view->assign('areaid', $areaId)->assign('comments', $items)->assign('commentcount', $commentcount)->assign('ezcomment', $ezcomment)->assign('ezc_info', compact('mod', 'objectid', 'sortorder', 'status'))->assign('modinfo', ModUtil::getInfo(ModUtil::getIdFromName($mod)))->assign('msgmodule', System::getVar('messagemodule', ''))->assign('prfmodule', System::getVar('profilemodule', ''))->assign('allowadd', SecurityUtil::checkPermission('EZComments::', "{$mod}:{$objectid}:", ACCESS_COMMENT))->assign('loggedin', UserUtil::isLoggedIn());
     $modUrl = $hook->getUrl();
     $redirect = !is_null($modUrl) ? $modUrl->getUrl() : '';
     $view->assign('returnurl', $redirect);
     // encode the url - otherwise we can get some problems out there....
     $redirect = base64_encode($redirect);
     $view->assign('redirect', $redirect);
     $view->assign('objectid', $objectid);
     // assign the user is of the content owner
     $view->assign('owneruid', $owneruid);
     // assign url that should be stored in db and sent in email if it
     // differs from the redirect url
     $view->assign('useurl', $useurl);
     // flag to recognize the main call
     static $mainScreen = true;
     $view->assign('mainscreen', $mainScreen);
     $mainScreen = false;
     // assign the values for the pager
     $view->assign('ezc_pager', array('numitems' => $commentcount, 'itemsperpage' => $numitems));
     // find out which template and stylesheet to use
     $templateset = isset($args['template']) ? $args['template'] : FormUtil::getPassedValue('eztpl');
     $css = isset($args['ezccss']) ? $args['ezccss'] : FormUtil::getPassedValue('ezccss');
     $defaultcss = ModUtil::getVar('EZComments', 'css', 'style.css');
     if (!$view->template_exists(DataUtil::formatForOS($templateset) . '/ezcomments_user_view.tpl')) {
         $templateset = ModUtil::getVar('EZComments', 'template', 'Standard');
     }
     $view->assign('template', $templateset);
     // include stylesheet if there is a style sheet
     $css = $css ? "{$css}.css" : $defaultcss;
     if ($css = ModUtil::apiFunc('EZComments', 'user', 'getStylesheet', array('path' => "{$templateset}/{$css}"))) {
         PageUtil::addVar('stylesheet', $css);
     }
     $template = DataUtil::formatForOS($templateset) . '/ezcomments_user_view.tpl';
     $response = new Zikula_Response_DisplayHook('provider_area.ui_hooks.ezcomments.comments', $view, $template);
     $hook->setResponse($response);
 }
コード例 #19
0
ファイル: random.php プロジェクト: ro0f/Mediashare
function mediashare_randomblock_display($blockinfo)
{
    // Security check
    if (!SecurityUtil::checkPermission('mediashare:randomblock:', "{$blockinfo['title']}::{$blockinfo['bid']}", ACCESS_READ)) {
        return;
    }
    $dom = ZLanguage::getModuleDomain('mediashare');
    // Get variables from content block
    $vars = pnBlockVarsFromContent($blockinfo['content']);
    $sessionVarName = 'mediashare_block_' . $blockinfo['bid'];
    $sessionVars = SessionUtil::getVar($sessionVarName);
    if ($sessionVars == '' || $sessionVars == null) {
        $sessionVars = array();
    }
    if (isset($sessionVars['oldContent']) && isset($sessionVars['lastUpdate'])) {
        $past = time() - $sessionVars['lastUpdate'];
        if ($past < $vars['cacheTime']) {
            // No need to refresh - move old content into real content
            $blockinfo['content'] = $sessionVars['oldContent'];
            return themesideblock($blockinfo);
        }
    }
    if ($vars['type'] == 'album') {
        $randomInfo = pnModAPIFunc('mediashare', 'user', 'getRandomMediaItem', array('albumId' => $vars['albumId'], 'mode' => 'album'));
    } else {
        if ($vars['type'] == 'latest') {
            $randomInfo = pnModAPIFunc('mediashare', 'user', 'getRandomMediaItem', array('latest' => true, 'mode' => 'latest'));
        } else {
            $randomInfo = pnModAPIFunc('mediashare', 'user', 'getRandomMediaItem');
        }
    }
    if ($randomInfo === false) {
        return false;
    }
    $mediaId = $randomInfo['mediaId'];
    $albumId = $randomInfo['albumId'];
    if (empty($mediaId)) {
        return;
    }
    // Get image info
    $mediaInfo = pnModAPIFunc('mediashare', 'user', 'getMediaItem', array('mediaId' => $mediaId));
    // Get album info
    $albumInfo = pnModAPIFunc('mediashare', 'user', 'getAlbum', array('albumId' => $albumId));
    $originalURL = pnModAPIFunc('mediashare', 'user', 'getMediaUrl', array('mediaItem' => $mediaInfo, 'src' => 'originalRef'));
    $previewURL = pnModAPIFunc('mediashare', 'user', 'getMediaUrl', array('mediaItem' => $mediaInfo, 'src' => 'previewRef'));
    $thumbnailURL = pnModAPIFunc('mediashare', 'user', 'getMediaUrl', array('mediaItem' => $mediaInfo, 'src' => 'thumbnailRef'));
    $albumURL = pnModUrl('mediashare', 'user', 'view', array('aid' => $albumId, 'mid' => $mediaId));
    // Create the final HTML by substituting various macros into the user specified HTML code
    $substitutes = array('originalURL' => $originalURL, 'previewURL' => $previewURL, 'thumbnailURL' => $thumbnailURL, 'albumURL' => $albumURL, 'title' => $mediaInfo['title'], 'owner' => __('Unknown', $dom), 'albumTitle' => $albumInfo['title']);
    $html = $vars['html'];
    foreach ($substitutes as $key => $value) {
        $pattern = '${' . $key . '}';
        $html = str_replace($pattern, $value, $html);
    }
    $blockinfo['content'] = $html;
    $sessionVars['oldContent'] = $html;
    $sessionVars['lastUpdate'] = time();
    SessionUtil::setVar($sessionVarName, $sessionVars);
    // ... and return encapsulated in a theme block
    return themesideblock($blockinfo);
}
コード例 #20
0
ファイル: User.php プロジェクト: projectesIF/Sirius
    /**
     * add new item
     *
     * @author Mark West
     * @return string HTML string
     */
    public function newitem($args)
    {
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('News::', '::', ACCESS_COMMENT), LogUtil::getErrorMsgPermission());

        // Any item set for preview will be stored in a session var
        // Once the new article is posted we'll clear the session var.
        $item = array();
        $sess_item = SessionUtil::getVar('newsitem');

        // get the type parameter so we can decide what template to use
        $type = FormUtil::getPassedValue('type', 'user', 'REQUEST');

        // Set the default values for the form. If not previewing an item prior
        // to submission these values will be null but do need to be set
        $item['sid'] = isset($sess_item['sid']) ? $sess_item['sid'] : '';
        $item['__CATEGORIES__'] = isset($sess_item['__CATEGORIES__']) ? $sess_item['__CATEGORIES__'] : array();
        $item['__ATTRIBUTES__'] = isset($sess_item['__ATTRIBUTES__']) ? $sess_item['__ATTRIBUTES__'] : array();
        $item['title'] = isset($sess_item['title']) ? $sess_item['title'] : '';
        $item['urltitle'] = isset($sess_item['urltitle']) ? $sess_item['urltitle'] : '';
        $item['hometext'] = isset($sess_item['hometext']) ? $sess_item['hometext'] : '';
        $item['hometextcontenttype'] = isset($sess_item['hometextcontenttype']) ? $sess_item['hometextcontenttype'] : '';
        $item['bodytext'] = isset($sess_item['bodytext']) ? $sess_item['bodytext'] : '';
        $item['bodytextcontenttype'] = isset($sess_item['bodytextcontenttype']) ? $sess_item['bodytextcontenttype'] : '';
        $item['notes'] = isset($sess_item['notes']) ? $sess_item['notes'] : '';
        $item['displayonindex'] = isset($sess_item['displayonindex']) ? $sess_item['displayonindex'] : 1;
        $item['language'] = isset($sess_item['language']) ? $sess_item['language'] : '';
        $item['allowcomments'] = isset($sess_item['allowcomments']) ? $sess_item['allowcomments'] : 1;
        $item['from'] = isset($sess_item['from']) ? $sess_item['from'] : DateUtil::getDatetime(null, '%Y-%m-%d %H:%M');
        $item['to'] = isset($sess_item['to']) ? $sess_item['to'] : DateUtil::getDatetime(null, '%Y-%m-%d %H:%M');
        $item['tonolimit'] = isset($sess_item['tonolimit']) ? $sess_item['tonolimit'] : 1;
        $item['unlimited'] = isset($sess_item['unlimited']) ? $sess_item['unlimited'] : 1;
        $item['weight'] = isset($sess_item['weight']) ? $sess_item['weight'] : 0;
        $item['pictures'] = isset($sess_item['pictures']) ? $sess_item['pictures'] : 0;
        $item['tempfiles'] = isset($sess_item['tempfiles']) ? $sess_item['tempfiles'] : null;
        $item['temp_pictures'] = isset($sess_item['tempfiles']) ? unserialize($sess_item['tempfiles']) : null;

        $preview = '';
        if (isset($sess_item['action']) && $sess_item['action'] == self::ACTION_PREVIEW) {
            $preview = $this->preview(array('title' => $item['title'],
                        'hometext' => $item['hometext'],
                        'hometextcontenttype' => $item['hometextcontenttype'],
                        'bodytext' => $item['bodytext'],
                        'bodytextcontenttype' => $item['bodytextcontenttype'],
                        'notes' => $item['notes'],
                        'sid' => $item['sid'],
                        'pictures' => $item['pictures'],
                        'temp_pictures' => $item['temp_pictures']));
        }

        // Get the module vars
        $modvars = $this->getVars();

        if ($modvars['enablecategorization']) {
            $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('News', 'news');
            $this->view->assign('catregistry', $catregistry);

            // add article attribute if morearticles is enabled and general setting is zero
            if ($modvars['enablemorearticlesincat'] && $modvars['morearticlesincat'] == 0) {
                $item['__ATTRIBUTES__']['morearticlesincat'] = 0;
            }
        }

        // Assign the default languagecode
        $this->view->assign('lang', ZLanguage::getLanguageCode());

        // Assign the item to the template
        $this->view->assign('item', $item);

        // Assign the content format
        $formattedcontent = ModUtil::apiFunc('News', 'user', 'isformatted', array('func' => 'newitem'));
        $this->view->assign('formattedcontent', $formattedcontent);

        $this->view->assign('accessadd', 0);
        if (SecurityUtil::checkPermission('News::', '::', ACCESS_ADD)) {
            $this->view->assign('accessadd', 1);
            $this->view->assign('accesspicupload', 1);
            $this->view->assign('accesspubdetails', 1);
        } else {
            $this->view->assign('accesspicupload', SecurityUtil::checkPermission('News:pictureupload:', '::', ACCESS_ADD));
            $this->view->assign('accesspubdetails', SecurityUtil::checkPermission('News:publicationdetails:', '::', ACCESS_ADD));
        }

        $this->view->assign('preview', $preview);

        // Return the output that has been generated by this function
        return $this->view->fetch('user/create.tpl');
    }
コード例 #21
0
ファイル: LogUtil.php プロジェクト: Silwereth/core
 /**
  * get the error type.
  *
  * @return int error type.
  */
 public static function getErrorType()
 {
     return (int) SessionUtil::getVar('_ZErrorMsgType');
 }
コード例 #22
0
ファイル: SecurityUtil.php プロジェクト: rmaiwald/core
 /**
  * Generate auth key.
  *
  * @param string $modname Module name.
  *
  * @deprecated since 1.3.0
  *
  * @return string An encrypted key for use in authorisation of operations.
  */
 public static function generateAuthKey($modname = '')
 {
     // Ugly hack for Zikula_Response_Ajax which for BC reasons needs to add authid to response
     // So when this method is called by Zikula_Response_Ajax  or Zikula_Response_Ajax_Error class
     // do not mark it as deprecated.
     $trace = debug_backtrace(false);
     if (!isset($trace[1]['class']) || !in_array($trace[1]['class'], array('Zikula_Response_Ajax', 'Zikula_Response_Ajax_Error'))) {
         LogUtil::log(__f('Warning! Static call %1$s is deprecated. Please use %2$s instead.', array('SecurityUtil::generateAuthKey()', 'SecurityUtil::generateCsrfToken()')), E_USER_DEPRECATED);
     }
     // since we need sessions for authorisation keys we should check
     // if a session exists and if not create one
     SessionUtil::requireSession();
     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".  Please update any generateAuthKey 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 generate the one of the current module if doesn't exist
     $rand_arr = SessionUtil::getVar('rand');
     if (!isset($rand_arr[$modname])) {
         $rand_arr[$modname] = RandomUtil::getString(32, 40, false, true, true, false, true, true, false);
         SessionUtil::setVar('rand', $rand_arr);
     }
     $key = $rand_arr[$modname] . $modname;
     if (System::getVar('keyexpiry') > 0) {
         $timestamp = time();
         $authid = sha1($key . $timestamp) . $timestamp;
     } else {
         $authid = sha1($key);
     }
     // Return encrypted key
     return $authid;
 }
コード例 #23
0
ファイル: User.php プロジェクト: rmaiwald/EZComments
 /**
  * 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('&amp;', '&', 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);
 }
コード例 #24
0
 /**
  * edit category
  */
 public function editAction()
 {
     $cid = $this->request->get('cid', 0);
     $root_id = $this->request->get('dr', 1);
     $mode = $this->request->get('mode', 'new');
     $allCats = '';
     $editCat = '';
     $languages = ZLanguage::getInstalledLanguages();
     // indicates that we're editing
     if ($mode == 'edit') {
         if (!SecurityUtil::checkPermission('Categories::category', "::", ACCESS_ADMIN)) {
             throw new \Zikula\Framework\Exception\ForbiddenException();
         }
         if (!$cid) {
             return LogUtil::registerError($this->__('Error! Cannot determine valid \'cid\' for edit mode in \'Categories_admin_edit\'.'));
         }
         $editCat = CategoryUtil::getCategoryByID($cid);
         if (!$editCat) {
             return LogUtil::registerError($this->__('Sorry! No such item found.'), 404);
         }
     } else {
         // new category creation
         if (!SecurityUtil::checkPermission('Categories::category', '::', ACCESS_ADD)) {
             throw new \Zikula\Framework\Exception\ForbiddenException();
         }
         // since we inherit the domain settings from the parent, we get
         // the inherited (and merged) object from session
         if (isset($_SESSION['newCategory']) && $_SESSION['newCategory']) {
             $editCat = $_SESSION['newCategory'];
             unset($_SESSION['newCategory']);
             $category = new \Zikula\Core\Doctrine\Entity\Category();
             // need this for validation info
         } elseif (FormUtil::getValidationErrors()) {
             $newCatActionData = \SessionUtil::getVar('newCatActionData');
             \SessionUtil::delVar('newCatActionData');
             $editCat = new \Zikula\Core\Doctrine\Entity\Category();
             $editCat = $editCat->toArray();
             $editCat = array_merge($editCat, $newCatActionData);
             unset($editCat['path']);
             unset($editCat['ipath']);
             $category = new \Zikula\Core\Doctrine\Entity\Category();
             // need this for validation info
         } else {
             $category = new \Zikula\Core\Doctrine\Entity\Category();
             $editCat['sort_value'] = '0';
         }
     }
     $reloadOnCatChange = $mode != 'edit';
     $allCats = CategoryUtil::getSubCategories($root_id, true, true, true, false, true);
     // now remove the categories which are below $editCat ...
     // you should not be able to set these as a parent category as it creates a circular hierarchy (see bug #4992)
     if (isset($editCat['ipath'])) {
         $cSlashEdit = StringUtil::countInstances($editCat['ipath'], '/');
         foreach ($allCats as $k => $v) {
             $cSlashCat = StringUtil::countInstances($v['ipath'], '/');
             if ($cSlashCat >= $cSlashEdit && strpos($v['ipath'], $editCat['ipath']) !== false) {
                 unset($allCats[$k]);
             }
         }
     }
     $selector = CategoryUtil::getSelector_Categories($allCats, 'id', isset($editCat['parent_id']) ? $editCat['parent_id'] : 0, 'category[parent_id]', isset($defaultValue) ? $defaultValue : null, null, $reloadOnCatChange);
     $attributes = isset($editCat['__ATTRIBUTES__']) ? $editCat['__ATTRIBUTES__'] : array();
     $this->view->assign('mode', $mode)->assign('category', $editCat)->assign('attributes', $attributes)->assign('languages', $languages)->assign('categorySelector', $selector);
     if ($mode == 'edit') {
         $this->view->assign('haveSubcategories', CategoryUtil::haveDirectSubcategories($cid))->assign('haveLeafSubcategories', CategoryUtil::haveDirectSubcategories($cid, false, true));
     }
     return $this->response($this->view->fetch('Admin/edit.tpl'));
 }
コード例 #25
0
ファイル: User.php プロジェクト: projectesIF/Sirius
    /**
     * Perform the search.
     *
     * @param string $args['g']           query string to search
     * @param bool   $args['firstPage']   is this first search attempt? is so - basic search is performed
     * @param string $args['searchtype']  (optional) search type (default='AND')
     * @param string $args['searchorder'] (optional) search order (default='newest')
     * @param int    $args['numlimit']    (optional) number of items to return (default value based on Search settings, -1 for no limit)
     * @param int    $args['page']        (optional) page number (default=1)
     * @param array  $args['active']      (optional) array of search plugins to search (if empty all plugins are used)
     * @param array  $args['modvar']      (optional) array with extrainfo for search plugins
     *
     * @return array array of items array and result count, or false on failure
     */
    public function search($args)
    {
        // query string and firstPage params are required
        if (!isset($args['q']) || empty($args['q']) || !isset($args['firstPage'])) {
            return LogUtil::registerArgsError();
        }
        $vars = array();
        $vars['q'] = $args['q'];
        $vars['searchtype'] = isset($args['searchtype']) && !empty($args['searchtype']) ? $args['searchtype'] : 'AND';
        $vars['searchorder'] = isset($args['searchorder']) && !empty($args['searchorder']) ? $args['searchorder'] : 'newest';
        $vars['numlimit'] = isset($args['numlimit']) && !empty($args['numlimit']) ? $args['numlimit'] : $this->getVar('itemsperpage', 25);
        $vars['page'] = isset($args['page']) && !empty($args['page']) ? (int)$args['page'] : 1;

        $firstPage = isset($args['firstPage']) ? $args['firstPage'] : false;

        $active = isset($args['active']) && is_array($args['active']) && !empty($args['active']) ? $args['active'] : array();
        $modvar = isset($args['modvar']) && is_array($args['modvar']) && !empty($args['modvar']) ? $args['modvar'] : array();

        // work out row index from page number
        $vars['startnum'] = $vars['numlimit'] > 0 ? (($vars['page'] - 1) * $vars['numlimit']) + 1 : 1;

        // Load database stuff
        ModUtil::dbInfoLoad('Search');
        $dbtable = DBUtil::getTables();
        $userId = (int)UserUtil::getVar('uid');
        $searchTable = $dbtable['search_result'];
        $searchColumn = $dbtable['search_result_column'];

        // Create restriction on result table (so user only sees own results)
        $userResultWhere = "$searchColumn[session] = '" . session_id() . "'";

        // Do all the heavy database stuff on the first page only
        if ($firstPage) {
            // Clear current search result for current user - before showing the first page
            // Clear also older searches from other users.
            $dbDriverName = strtolower(Doctrine_Manager::getInstance()->getCurrentConnection()->getDriverName());
            $where = $userResultWhere;
            if ($dbDriverName == 'pgsql') {
                $where .= " OR $searchColumn[found] + INTERVAL '8 HOUR' < NOW()";
            } else {
                $where .= " OR DATE_ADD($searchColumn[found], INTERVAL 8 HOUR) < NOW()";
            }

            DBUtil::deleteWhere('search_result', $where);

            // get all the search plugins
            $search_modules = ModUtil::apiFunc('Search', 'user', 'getallplugins');

            // Ask active modules to find their items and put them into $searchTable for the current user
            // At the same time convert modules list from numeric index to modname index

            $searchModulesByName = array();
            foreach ($search_modules as $mod) {
                // check we've a valid search plugin
                if (isset($mod['functions']) && (empty($active) || isset($active[$mod['title']]))) {
                    foreach ($mod['functions'] as $contenttype => $function) {
                        if (isset($modvar[$mod['title']])) {
                            $param = array_merge($vars, $modvar[$mod['title']]);
                        } else {
                            $param = $vars;
                        }
                        $searchModulesByName[$mod['name']] = $mod;
                        $ok = ModUtil::apiFunc($mod['title'], 'search', $function, $param);
                        if (!$ok) {
                            LogUtil::registerError($this->__f('Error! \'%1$s\' module returned false in search function \'%2$s\'.', array($mod['title'], $function)));

                            return System::redirect(ModUtil::url('Search', 'user', 'main'));
                        }
                    }
                }
            }

            // Count number of found results
            $resultCount = DBUtil::selectObjectCount('search_result', $userResultWhere);
            SessionUtil::setVar('searchResultCount', $resultCount);
            SessionUtil::setVar('searchModulesByName', $searchModulesByName);
        } else {
            $resultCount = SessionUtil::getVar('searchResultCount');
            $searchModulesByName = SessionUtil::getVar('searchModulesByName');
        }

        // Fetch search result - do sorting and paging in database
        // Figure out what to sort by
        switch ($args['searchorder']) {
            case 'alphabetical':
                $sort = 'title';
                break;
            case 'oldest':
                $sort = 'created';
                break;
            case 'newest':
                $sort = 'created DESC';
                break;
            default:
                $sort = 'title';
                break;
        }

        // Get next N results from the current user's result set
        // The "checker" object is used to:
        // 1) do secondary access control (deprecated more or less)
        // 2) let the modules add "url" to the found (and viewed) items
        $checker = new search_result_checker($searchModulesByName);
        $sqlResult = DBUtil::selectObjectArrayFilter('search_result', $userResultWhere, $sort,
                        $vars['startnum'] - 1, $vars['numlimit'], '',
                        $checker, null);
        // add displayname of modules found
        $cnt = count($sqlResult);
        for ($i = 0; $i < $cnt; $i++) {
            $modinfo = ModUtil::getInfoFromName($sqlResult[$i]['module']);
            $sqlResult[$i]['displayname'] = $modinfo['displayname'];
        }

        $result = array(
                'resultCount' => $resultCount,
                'sqlResult' => $sqlResult
        );

        return $result;
    }
コード例 #26
0
ファイル: User.php プロジェクト: robbrandt/Content
 /**
  * view a page
  *
  * @param int    pid      Page ID
  * @param string name     URL name, alternative for pid
  * @param bool   preview  Display preview
  * @param bool   editmode Flag for enabling/disabling edit mode
  *
  * @return Renderer output
  */
 public function view($args)
 {
     $pageId = isset($args['pid']) ? $args['pid'] : FormUtil::getPassedValue('pid');
     $versionId = isset($args['vid']) ? $args['vid'] : FormUtil::getPassedValue('vid');
     $urlname = isset($args['name']) ? $args['name'] : FormUtil::getPassedValue('name');
     $preview = isset($args['preview']) ? $args['preview'] : FormUtil::getPassedValue('preview');
     $editmode = isset($args['editmode']) ? $args['editmode'] : FormUtil::getPassedValue('editmode', null, 'GET');
     if ($pageId === null && !empty($urlname)) {
         $pageId = ModUtil::apiFunc('Content', 'Page', 'solveURLPath', compact('urlname'));
         System::queryStringSetVar('pid', $pageId);
     }
     if ((bool) $this->getVar('inheritPermissions', false) === true) {
         $this->throwForbiddenUnless(ModUtil::apiFunc('Content', 'page', 'checkPermissionForPageInheritance', array('pageId' => $pageId, 'level' => ACCESS_READ)), LogUtil::getErrorMsgPermission());
     } else {
         $this->throwForbiddenUnless(SecurityUtil::checkPermission('Content:page:', $pageId . '::', ACCESS_READ), LogUtil::getErrorMsgPermission());
     }
     $versionHtml = '';
     $hasEditAccess = false;
     if ((bool) $this->getVar('inheritPermissions', false) === true) {
         $hasEditAccess = ModUtil::apiFunc('Content', 'page', 'checkPermissionForPageInheritance', array('pageId' => $pageId, 'level' => ACCESS_EDIT));
     } else {
         $hasEditAccess = SecurityUtil::checkPermission('Content:page:', $pageId . '::', ACCESS_EDIT);
     }
     if ($versionId !== null && $hasEditAccess) {
         $preview = true;
         $version = ModUtil::apiFunc('Content', 'History', 'getPageVersion', array('id' => $versionId, 'preview' => $preview, 'includeContent' => true));
         $versionData =& $version['data'];
         $page =& $versionData['page'];
         $pageId = $page['id'];
         $action = ModUtil::apiFunc('Content', 'History', 'contentHistoryActionTranslate', $version['action']);
         $translatable = array('revisionNo' => $version['revisionNo'], 'date' => $version['date'], 'action' => $action, 'userName' => $version['userName'], 'ipno' => $version['ipno']);
         $iconSrc = 'images/icons/extrasmall/clock.png';
         $versionHtml = "<p class=\"content-versionpreview\"><img alt=\"\" src=\"{$iconSrc}\"/> " . $this->__f('Version #%1$s - %2$s - %3$s by %4$s from %5$s', $translatable) . "</p>";
     }
     // now get the page up for display
     if ($pageId !== null && $versionId === null) {
         $page = ModUtil::apiFunc('Content', 'Page', 'getPage', array('id' => $pageId, 'preview' => $preview, 'includeContent' => true, 'filter' => array('checkActive' => !($preview && $hasEditAccess))));
     } else {
         if ($versionId === null) {
             return LogUtil::registerArgsError();
         }
     }
     if ($page === false) {
         return false;
     }
     if ($editmode !== null) {
         SessionUtil::setVar('ContentEditMode', $editmode);
     } else {
         $editmode = SessionUtil::getVar('ContentEditMode', null);
     }
     if ($editmode) {
         $this->view->setCaching(false);
     }
     $this->view->setCacheId("{$pageId}|{$versionId}");
     if ($this->view->is_cached('user/page.tpl')) {
         return $this->view->fetch('user/page.tpl');
     }
     // Register a page variable breadcrumbs with the Content page hierarchy as array of array(url, title)
     if ((bool) $this->getVar('registerBreadcrumbs', false) === true) {
         // first include self, then loop over parents until root is reached
         $breadcrumbs[] = array('url' => ModUtil::url('Content', 'user', 'view', array('pid' => $page['id'])), 'title' => $page['title']);
         $loopPageid = $page['parentPageId'];
         while ($loopPageid > 0) {
             $loopPage = ModUtil::apiFunc('Content', 'Page', 'getPage', array('id' => $loopPageid, 'includeContent' => false, 'includeLayout' => false, 'translate' => $this->translateTitles));
             array_unshift($breadcrumbs, array('url' => ModUtil::url('Content', 'user', 'view', array('pid' => $loopPage['id'])), 'title' => $loopPage['title']));
             $loopPageid = $loopPage['parentPageId'];
         }
         PageUtil::registerVar('breadcrumbs', false, $breadcrumbs);
     }
     $multilingual = ModUtil::getVar(ModUtil::CONFIG_MODULE, 'multilingual');
     if ($page['language'] == ZLanguage::getLanguageCode()) {
         $multilingual = false;
     }
     // override the PageVar title if configued in the settings
     if ($this->getVar('overrideTitle')) {
         $pageTitle = html_entity_decode($page['title']);
         PageUtil::setVar('title', $preview ? $this->__("Preview") . ' - ' . $pageTitle : $pageTitle);
     }
     $this->view->assign('page', $page);
     $this->view->assign('preview', $preview);
     $this->view->assign('editmode', $editmode);
     $this->view->assign('multilingual', $multilingual);
     $this->view->assign('enableVersioning', $this->getVar('enableVersioning'));
     // add layout type and column count as page variables to the template
     // columncount can be used via plugin contentcolumncount, since it holds regular expressions that slow down
     $this->view->assign('contentLayoutType', $page['layout']);
     // add access parameters
     Content_Util::contentAddAccess($this->view, $pageId);
     // exclude writers from statistics
     if (!$hasEditAccess && !$preview && !$editmode && $this->getVar('countViews')) {
         // Check against session to see if user was already counted
         if (!SessionUtil::getVar("ContentRead" . $pageId)) {
             SessionUtil::setVar("ContentRead" . $pageId, $pageId);
             DBUtil::incrementObjectFieldByID('content_page', 'views', $pageId);
         }
     }
     return $versionHtml . $this->view->fetch('user/page.tpl');
 }
コード例 #27
0
ファイル: DBObject.php プロジェクト: Silwereth/core
 /**
  * Get the data from the session.
  *
  * @param string  $key                  The access key of the object (optional) (default=null, reverts to $this->_objPath).
  * @param mixed   $default              The default value to return (optional) (default=null).
  * @param string  $path                 The session object input path.
  * @param boolean $autocreate           The autocreate passed to SessionUtil::setVar.
  * @param boolean $overwriteExistingVar The overwriteExistingVar variable passed to SessionUtil::setVar.
  *
  * @return mixed The requested object/value.
  */
 public function getDataFromSession($key = null, $default = null, $path = '', $autocreate = true, $overwriteExistingVar = false)
 {
     if (!$key) {
         $key = $this->_objPath;
     }
     if (!$path) {
         $path = $this->_objSessionPath;
     }
     $obj = SessionUtil::getVar($key, $default, $path, $autocreate, $overwriteExistingVar);
     if ($obj && is_array($obj)) {
         $this->_objData = $obj;
         $this->getDataFromSessionPostProcess();
         return $this->_objData;
     }
     return $default;
 }
コード例 #28
0
ファイル: pnuser.php プロジェクト: ro0f/Mediashare
/**
 * View items in slideshow
 */
function mediashare_user_slideshow($args)
{
    $albumId = mediashareGetIntUrl('aid', $args, 1);
    $mediaId = mediashareGetIntUrl('mid', $args, 0);
    $delay = mediashareGetIntUrl('delay', $args, 5);
    $mode = mediashareGetStringUrl('mode', $args, 'stopped');
    $viewkey = FormUtil::getPassedValue('viewkey');
    $center = isset($args['center']) ? '_center' : '';
    $back = mediashareGetIntUrl('back', $args, 0);
    // Check access to album (media ID won't do a difference if not from this album)
    if (!mediashareAccessAlbum($albumId, mediashareAccessRequirementViewSomething)) {
        return LogUtil::registerPermissionError();
    }
    // Fetch current album
    if (!($album = pnModAPIFunc('mediashare', 'user', 'getAlbum', array('albumId' => $albumId)))) {
        return false;
    }
    if ($album === true) {
        return LogUtil::registerError(__('Unknown album.', $dom));
    }
    // Fetch media items
    if (($items = pnModAPIFunc('mediashare', 'user', 'getMediaItems', array('albumId' => $albumId))) === false) {
        return false;
    }
    // Find current, previous and next items
    if ($mediaId == 0 && count($items) > 0) {
        $mediaId = $items[0]['id'];
    }
    $mediaItem = null;
    if (count($items) > 0) {
        $prevMediaId = $items[count($items) - 1]['id'];
        $nextMediaId = $items[0]['id'];
        foreach ($items as $item) {
            if ($mediaItem != null) {
                // Media-Current item found, so this must be next
                $nextMediaId = $item['id'];
                break;
            }
            if ($item['id'] == $mediaId) {
                $mediaItem = $item;
            } else {
                // Media-item not found, so this must become prev
                $prevMediaId = $item['id'];
            }
        }
    } else {
        $prevMediaId = -1;
        $nextMediaId = -1;
    }
    // Add media display HTML
    $mediadir = pnModAPIFunc('mediashare', 'user', 'getRelativeMediadir');
    for ($i = 0, $cou = count($items); $i < $cou; ++$i) {
        if (!($handler = pnModAPIFunc('mediashare', 'mediahandler', 'loadHandler', array('handlerName' => $items[$i]['mediaHandler'])))) {
            return false;
        }
        $result = $handler->getMediaDisplayHtml($mediadir . $items[$i]['originalRef'], null, null, 'mediaItem', array());
        $items[$i]['html'] = str_replace(array("\r", "\n"), array(' ', ' '), $result);
    }
    $viewUrl = pnModUrl('mediashare', 'user', 'slideshow', array('mid' => $mediaItem['id']));
    if ($back) {
        SessionUtil::setVar('mediashareQuitUrl', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);
    }
    $quitUrl = SessionUtil::getVar('mediashareQuitUrl');
    if ($quitUrl == null) {
        $quitUrl = pnModUrl('mediashare', 'user', 'view', array('aid' => $album['id']));
    }
    // Build the output
    $render =& pnRender::getInstance('mediashare', false);
    $render->assign('viewUrl', $viewUrl);
    $render->assign('mediaId', $mediaId);
    $render->assign('mediaItem', $mediaItem);
    $render->assign('prevMediaId', $prevMediaId);
    $render->assign('nextMediaId', $nextMediaId);
    $render->assign('mediaItems', $items);
    $render->assign('album', $album);
    $render->assign('albumId', $albumId);
    $render->assign('delay', $delay);
    $render->assign('mode', $mode);
    $render->assign('thumbnailSize', pnModGetVar('mediashare', 'thumbnailSize'));
    $render->assign('theme', pnUserGetTheme());
    $render->assign('templateName', "slideshow{$center}.html");
    $render->assign('quitUrl', $quitUrl);
    // Add the access array
    if (!mediashareAddAccess($render, $album)) {
        return false;
    }
    $render->load_filter('output', 'pagevars_notcombined');
    if (pnConfigGetVar('shorturls')) {
        $render->load_filter('output', 'shorturls');
    }
    $render->display('mediashare_user_slideshow.html');
    return true;
}
コード例 #29
0
 /**
  * Get text displayed after actual content.
  * @return string Displayed text
  */
 public function displayEnd()
 {
     $html = '';
     if ($this->addedStyle) {
         $html = '</div>';
         // check for edit mode on and clear the floating elements in that case
         if (SessionUtil::getVar('ContentEditMode')) {
             $html .= '<div style="clear: both"></div>';
         }
     }
     return $html;
 }
コード例 #30
0
ファイル: View.php プロジェクト: Silwereth/core
 /**
  * Add core data to the template.
  *
  * This function adds some basic data to the template depending on the
  * current user and the Zikula settings.  There is no need to call this as it's
  * invoked automatically on instanciation.
  *
  * In legacy mode 'coredata' will contain the module vars, but not when disabled.
  * This is just for BC legacy - to access module vars there is a 'modvars' property
  * assigned to all templates.
  *
  * @return Zikula_View
  */
 public function add_core_data()
 {
     if (!isset($this->serviceManager['zikula_view.coredata'])) {
         $this->serviceManager['zikula_view.coredata'] = new ArrayObject(array());
     }
     $core = $this->serviceManager['zikula_view.coredata'];
     $core['version_num'] = Zikula_Core::VERSION_NUM;
     $core['version_id'] = Zikula_Core::VERSION_ID;
     $core['version_sub'] = Zikula_Core::VERSION_SUB;
     $core['logged_in'] = UserUtil::isLoggedIn();
     $core['language'] = $this->language;
     // add userdata
     $core['user'] = UserUtil::getVars(SessionUtil::getVar('uid'));
     if (System::isLegacyMode()) {
         // add modvars of current modules
         foreach ($this->module as $module => $dummy) {
             if (!empty($module)) {
                 $core[$module] = ModUtil::getVar($module);
             }
         }
         // add mod vars of all modules supplied as parameter
         $modulenames = func_get_args();
         foreach ($modulenames as $modulename) {
             // if the modulename is empty do nothing
             if (!empty($modulename) && !is_array($modulename) && !array_key_exists($modulename, $this->module)) {
                 // check if user wants to have config
                 if ($modulename == ModUtil::CONFIG_MODULE) {
                     $ZConfig = ModUtil::getVar(ModUtil::CONFIG_MODULE);
                     foreach ($ZConfig as $key => $value) {
                         // gather all config vars
                         $core['ZConfig'][$key] = $value;
                     }
                 } else {
                     $core[$modulename] = ModUtil::getVar($modulename);
                 }
             }
         }
         $this->assign('pncore', $core);
     }
     // Module vars
     parent::assign('coredata', $core);
     return $this;
 }