Exemplo n.º 1
0
    public function main() {
        //Security check!SecurityUtil::checkPermission(
        if (!SecurityUtil::checkPermission('IWbookings::', '::', ACCESS_READ)) {
            LogUtil::registerError($this->__('You are not allowed to administrate the bookings'));
            return false;
        }

        if (ModUtil::getVar('IWbookings', 'NTPtime')) {
            $tOffset = SessionUtil::getVar('timeOffset');
            if (empty($tOffset)) {
                // Calculate time diference between our server and a NTP time server
                $timeOffset = ModUtil::apiFunc('IWbookings', 'user', 'getNTPDate') - DateUtil::makeTimestamp();
                SessionUtil::setVar('timeOffset', $timeOffset);
            }
        }

        //Esborrem les reserva antigues i les reserves d'anul�laci�
        if ((ModUtil::getVar('IWbookings', 'eraseold') == 1) && (SecurityUtil::checkPermission('IWbookings::', '::', ACCESS_ADMIN))) {
            ModUtil::apiFunc('IWbookings', 'user', 'esborra_antigues', array('sid' => -1));
        }

        if (ModUtil::getVar('IWbookings', 'month_panel')) {
            System::redirect(ModUtil::url('IWbookings', 'user', 'assigna', array('sid' => -1,
                        'mensual' => 1)));
        } else {
            System::redirect(ModUtil::url('IWbookings', 'user', 'espais', array('sid' => -1,
                        'mensual' => 0)));
        }

        return true;
    }
Exemplo n.º 2
0
 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);
 }
Exemplo n.º 3
0
 /**
  * Return an array of items to show in the your account panel.
  *
  * @return   array   indexed array of items
  */
 public function getall($args)
 {
     $items = array();
     // Create an array of links to return
     if (SecurityUtil::checkPermission('Categories::', '::', ACCESS_EDIT) && $this->getVar('allowusercatedit')) {
         $referer = System::serverGetVar('HTTP_REFERER');
         if (strpos($referer, 'module=Categories') === false) {
             SessionUtil::setVar('categories_referer', $referer);
         }
         $items['0'] = array('url' => ModUtil::url('Categories', 'user', 'edituser'), 'module' => 'Categories', 'title' => $this->__('Categories manager'), 'icon' => 'admin.png');
     }
     // Return the items
     return $items;
 }
Exemplo n.º 4
0
 /**
  * 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');
 }
Exemplo n.º 5
0
 /**
  * Get the user's theme.
  *
  * This function will return the current theme for the user.
  * Order of theme priority:
  *  - page-specific
  *  - category
  *  - user
  *  - system
  *
  * @param boolean $force True to ignore the cache.
  *
  * @return string           the name of the user's theme
  * @throws RuntimeException If this function was unable to calculate theme name.
  */
 public static function getTheme($force = false)
 {
     static $theme;
     if (isset($theme) && !$force) {
         return $theme;
     }
     if (CookieUtil::getCookie('zikulaMobileTheme') == '1' && ModUtil::getVar('Theme', 'enable_mobile_theme', false)) {
         $pagetheme = 'Mobile';
     } else {
         if (CookieUtil::getCookie('zikulaMobileTheme') != '2' && ModUtil::getVar('Theme', 'enable_mobile_theme', false)) {
             include_once "system/Theme/lib/vendor/Mobile_Detect.php";
             $detect = new Mobile_Detect();
             if ($detect->isMobile()) {
                 $pagetheme = 'Mobile';
             }
         } else {
             $pagetheme = FormUtil::getPassedValue('theme', null, 'GETPOST');
         }
     }
     // Page-specific theme
     $type = FormUtil::getPassedValue('type', null, 'GETPOST');
     $qstring = System::serverGetVar('QUERY_STRING');
     if (!empty($pagetheme)) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($pagetheme));
         if ($themeinfo['state'] == ThemeUtil::STATE_ACTIVE && ($themeinfo['user'] || $themeinfo['system'] || $themeinfo['admin'] && $type == 'admin') && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             return self::_getThemeFilterEvent($themeinfo['name'], 'page-specific');
         }
     }
     // check for an admin theme
     if (($type == 'admin' || $type == 'adminplugin') && SecurityUtil::checkPermission('::', '::', ACCESS_EDIT)) {
         $admintheme = ModUtil::getVar('Admin', 'admintheme');
         if (!empty($admintheme)) {
             $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($admintheme));
             if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
                 return self::_getThemeFilterEvent($themeinfo['name'], 'admin-theme');
             }
         }
     }
     // set a new theme for the user
     $newtheme = FormUtil::getPassedValue('newtheme', null, 'GETPOST');
     if (!empty($newtheme) && System::getVar('theme_change')) {
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($newtheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             if (self::isLoggedIn()) {
                 self::setVar('theme', $newtheme);
             } else {
                 SessionUtil::setVar('theme', $newtheme);
             }
             return self::_getThemeFilterEvent($themeinfo['name'], 'new-theme');
         }
     }
     // User theme
     if (System::getVar('theme_change') || SecurityUtil::checkPermission('::', '::', ACCESS_ADMIN)) {
         if (self::isLoggedIn()) {
             $usertheme = self::getVar('theme');
         } else {
             $usertheme = SessionUtil::getVar('theme');
         }
         $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($usertheme));
         if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
             return self::_getThemeFilterEvent($themeinfo['name'], 'user-theme');
         }
     }
     // default site theme
     $defaulttheme = System::getVar('Default_Theme');
     $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($defaulttheme));
     if ($themeinfo && $themeinfo['state'] == ThemeUtil::STATE_ACTIVE && is_dir('themes/' . DataUtil::formatForOS($themeinfo['directory']))) {
         return self::_getThemeFilterEvent($themeinfo['name'], 'default-theme');
     }
     if (!System::isInstalling()) {
         throw new RuntimeException(__('UserUtil::getTheme() is unable to calculate theme name.'));
     }
 }
Exemplo n.º 6
0
 /**
  * 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');
 }
Exemplo n.º 7
0
/**
 * 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;
}
Exemplo n.º 8
0
    public function upgrade($oldversion) {
        $dom = ZLanguage::getModuleDomain('IWbooks');
        switch ($oldversion) {
            case 0.8:
                $dbconn = & DBConnectionStack::getConnection(true);
                $pntable = & DBUtil::getTables();

                $llibrestable = $pntable['llibres'];
                $llibrescolumn = &$pntable['llibres_column'];

                $sql = "ALTER TABLE $llibrestable
                    CHANGE $llibrescolumn[etapa] $llibrescolumn[etapa] varchar(32) NOT NULL default ''";
                $dbconn->Execute($sql);

                $sql = "ALTER TABLE $llibrestable
                    DROP pn_tipus";
                $dbconn->Execute($sql);

                if ($dbconn->ErrorNo() != 0) {
                    SessionUtil::setVar('errormsg', __('Failed to update the tables', $dom));
                    return false;
                }
                ModUtil::setVar('IWbooks', 'plans', '
PRI#Educació Primària|
ESO#Educació Secundària Obligatòria|
BTE#Batxillerat Tecnològic|
BSO#Batxillerat Social|
BHU#Batxillerat Humanístic|
BCI#Batxillerat Científic|
BAR#Batxillerat Artístic');

                ModUtil::setVar('IWbooks', 'darrer_nivell', '4');
                return IWbooks_upgrade(0.9);

            case 0.9:
                // Codi per a versió 1.0
                $dbconn = & DBConnectionStack::getConnection(true);
                $pntable = & DBUtil::getTables();

                $llibrestable = $pntable['llibres'];
                $llibrescolumn = &$pntable['llibres_column'];

                $sql = "ALTER TABLE $llibrestable
                    ADD pn_observacions varchar(100) NOT NULL,
                    ADD pn_materials text NOT NULL";
                $dbconn->Execute($sql);

                if ($dbconn->ErrorNo() != 0) {
                    SessionUtil::setVar('errormsg', $llibrestable . $oldversion . __('Failed to update the tables', $dom));
                    return false;
                }

                ModUtil::setVar('IWbooks', 'llistar_materials', '1');
                ModUtil::setVar('IWbooks', 'mida_font', '11');
                ModUtil::setVar('IWbooks', 'marca_aigua', '0');

                return IWbooks_upgrade(1.0);

            case 1.0:
                // Codi per a versió 2.0
                ModUtil::delVar('IWbooks', 'darrer_nivell');
                ModUtil::setVar('IWbooks', 'nivells', '
1#1r|
2#2n|
3#3r|
4#4t|
5#5è|
6#6è|
A#P3|
B#P4|
C#P5');


                if (!DBUtil::changeTable('IWbooks')) {
                    return false;
                }
                if (!DBUtil::changeTable('IWbooks_materies')) {
                    return false;
                }

                return IWbooks_upgrade(2.0);

                break;
        }

        // Actualització amb èxit
        return true;
    }
Exemplo n.º 9
0
 /**
  * Return the requested key from input in a safe way.
  *
  * This function is safe to use for recursive arrays and either
  * returns a non-empty string or the (optional) default.
  *
  * This method is based on FormUtil::getPassedValue but array-safe.
  *
  * @param string $key        The field to return.
  * @param mixed  $default    The value to return if the requested field is not found (optional) (default=false).
  * @param string $source     The source field to get a parameter from.
  * @param string $filter     The filter directive to apply.
  * @param array  $args       The filter processing args to apply.
  * @param string $objectType The object access path we're getting; used to assign validation errors .
  *
  * @deprecated since 1.3.0, use request object instead.
  *
  * @return mixed The requested input key or the specified default.
  */
 public static function getPassedValue($key, $default = null, $source = null, $filter = null, array $args = array(), $objectType = null)
 {
     if (!$key) {
         return z_exit(__f('Empty %1$s passed to %2$s.', array('key', 'FormUtil::getPassedValue')));
     }
     $source = strtoupper($source);
     if (!$filter) {
         $filter = FILTER_DEFAULT;
     }
     $args = array();
     $failed = null;
     switch (true) {
         case isset($_REQUEST[$key]) && !isset($_FILES[$key]) && (!$source || $source == 'R' || $source == 'REQUEST'):
             if (is_array($_REQUEST[$key])) {
                 $args['flags'] = FILTER_REQUIRE_ARRAY;
             }
             $value = filter_var($_REQUEST[$key], $filter, $args);
             $failed = $value === false ? $_REQUEST : null;
             break;
         case isset($_GET[$key]) && (!$source || $source == 'G' || $source == 'GET'):
             if (is_array($_GET[$key])) {
                 $args['flags'] = FILTER_REQUIRE_ARRAY;
             }
             $value = filter_var($_GET[$key], $filter, $args);
             $failed = $value === false ? $_GET : null;
             break;
         case isset($_POST[$key]) && (!$source || $source == 'P' || $source == 'POST'):
             if (is_array($_POST[$key])) {
                 $args['flags'] = FILTER_REQUIRE_ARRAY;
             }
             $value = filter_var($_POST[$key], $filter, $args);
             $failed = $value === false ? $_POST : null;
             break;
         case isset($_COOKIE[$key]) && (!$source || $source == 'C' || $source == 'COOKIE'):
             if (is_array($_COOKIE[$key])) {
                 $args['flags'] = FILTER_REQUIRE_ARRAY;
             }
             $value = filter_var($_COOKIE[$key], $filter, $args);
             $failed = $value === false ? $_COOKIE : null;
             break;
         case isset($_FILES[$key]) && ($source == 'F' || $source == 'FILES'):
             if (is_array($_FILES[$key])) {
                 $args['flags'] = FILTER_REQUIRE_ARRAY;
             }
             $value = $_FILES[$key];
             $failed = $value === false ? $_COOKIE : null;
             break;
         case (isset($_GET[$key]) || isset($_POST[$key])) && ($source == 'GP' || $source == 'GETPOST'):
             if (isset($_GET[$key])) {
                 if (is_array($_GET[$key])) {
                     $args['flags'] = FILTER_REQUIRE_ARRAY;
                 }
                 $value = filter_var($_GET[$key], $filter, $args);
                 $failed = $value === false ? $_GET : null;
             }
             if (isset($_POST[$key])) {
                 if (is_array($_POST[$key])) {
                     $args['flags'] = FILTER_REQUIRE_ARRAY;
                 }
                 $value = filter_var($_POST[$key], $filter, $args);
                 $failed = $value === false ? $_POST : null;
             }
             break;
         default:
             if ($source) {
                 static $valid = array('R', 'REQUEST', 'G', 'GET', 'P', 'POST', 'C', 'COOKIE', 'F', 'FILES', 'GP', 'GETPOST');
                 if (!in_array($source, $valid)) {
                     z_exit(__f('Invalid input source [%s] received.', DataUtil::formatForDisplay($source)));
                     return $default;
                 }
             }
             $value = $default;
     }
     if ($failed && $objectType) {
         //SessionUtil::setVar ($key, $failed[$key], "/validationErrors/$objectType");
         SessionUtil::setVar($objectType, $failed[$key], '/validationFailedObjects');
     }
     return $value;
 }
Exemplo n.º 10
0
    /**
     * 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;
    }
Exemplo n.º 11
0
 /**
  * Set the current object data into session.
  *
  * @param array   $data                 The object data.
  * @param string  $key                  The session key.
  * @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 array The session data.
  */
 public function setDataToSession($data = null, $key = null, $path = '', $autocreate = true, $overwriteExistingVar = false)
 {
     if (!$data) {
         $data = $this->_objData;
     }
     if (!$key) {
         $key = $this->_objPath;
     }
     if (!$path) {
         $path = $this->_objSessionPath;
     }
     if (!$this->setDataToSessionPreProcess($data)) {
         return false;
     }
     SessionUtil::setVar($path, $data, $path, $autocreate, $overwriteExistingVar);
     $this->_objData = $data;
     return $this->_objData;
 }
Exemplo n.º 12
0
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);
}
Exemplo n.º 13
0
    /**
     * Compose the user menu depending on which agendas can access
     *
     * @param array $args Agenda identity and mounht and year position
     *
     * @return The user menu
     */
    public function menu($args) {
        // Security check
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('IWagendas::', '::', ACCESS_READ));

        $dia = FormUtil::getPassedValue('dia', isset($args['dia']) ? $args['dia'] : date("d"), 'REQUEST');
        $mes = FormUtil::getPassedValue('mes', isset($args['mes']) ? $args['mes'] : date("m"), 'REQUEST');
        $any = FormUtil::getPassedValue('any', isset($args['any']) ? $args['any'] : date("Y"), 'REQUEST');
        $daid = FormUtil::getPassedValue('daid', isset($args['daid']) ? $args['daid'] : 0, 'REQUEST');
        $llistat = FormUtil::getPassedValue('llistat', isset($args['llistat']) ? $args['llistat'] : null, 'REQUEST');
        $purga = FormUtil::getPassedValue('purga', isset($args['purga']) ? $args['purga'] : null, 'REQUEST');
        $reduced = FormUtil::getPassedValue('reduced', isset($args['reduced']) ? $args['reduced'] : 0, 'POST');

        $odaid = $daid;
        $gdaid = 0;
        if ($daid == 0) {
            $usability = ModUtil::func('IWagendas', 'user', 'getGdataFunctionsUsability');
            if ($usability === true) {
                //if user use gCalendar integration and daid is zero get the gCalendar default
                $defaultCalendar = ModUtil::apiFunc('IWagendas', 'user', 'getGCalendarUserDefault');
                $gdaid = $defaultCalendar['daid'];
            }
        }
        $user = UserUtil::getVar('uid');
        if ($gdaid == 0)
            $gdaid = $daid;
        // If it's a shared agenda, get the data and check the perms
        if ($daid != 0) {
            // Get the agenda data
            $registre = ModUtil::apiFunc('IWagendas', 'user', 'getAgenda', array('daid' => $daid));
            //Comprovem que la consulta anterior ha tornat amb resultats
            if ($registre == false) {
                return SessionUtil::setVar('errormsg', $this->__('Event not found'));
            }
        } else {
            $registre['grup'] = '0';
            $registre['resp'] = '';
            $registre['activa'] = '';
        }
        // Check whether the user can access the agenda
        $te_acces = ModUtil::func('IWagendas', 'user', 'te_acces', array('daid' => $daid,
                    'grup' => $registre['grup'],
                    'resp' => $registre['resp'],
                    'activa' => $registre['activa']));
        // If the user has no access, show an error message and stop execution
        if ($te_acces == 0) {
            LogUtil::registerError($this->__('You are not allowed to administrate the agendas'));
            return System::redirect(ModUtil::url('IWagendas', 'user', 'main'));
        }
        // Pass the name of the agenda to the template
        if ($daid == 0) {
            $this->view->assign('agendaname', $this->__('Personal'));
        } else {
            $this->view->assign('agendaname', $registre['nom_agenda']);
        }
        $this->view->assign('daid', $daid);
        $subsArray = array();
        if (UserUtil::isLoggedIn()) {
            //get the agendas where the user is subscribed
            $subs = ModUtil::apiFunc('IWagendas', 'user', 'getUserSubscriptions');
            foreach ($subs as $sub) {
                array_push($subsArray, $sub['daid']);
            }
        }
        //get all the agendas where the user can access
        $agendas = ModUtil::func('IWagendas', 'user', 'getUserAgendas');
        $color = (isset($agendas[$daid]['color'])) ? $agendas[$daid]['color'] : '';
        $this->view->assign('color', $color);
        $i = 0;
        $ipr = 3;
        $agendasArray = array();
        foreach ($agendas as $agenda) {
            if ($agenda['color'] == '') {
                // Set a default color
                $userColor = '#FFFFFF';
                // Get gCalendar user color
                $pos = strpos($agenda['gColor'], '|' . $user . '$');
                $userColor = ($pos > 0) ? substr($agenda['gColor'], $pos - 7, 7) : '';
                $agenda['color'] = $userColor;
            }
            $newdiv = ($i % $ipr == 0) ? 1 : 0;
            $enddiv = ($i % $ipr == $ipr - 1 || $i == count($agendas) - 1) ? 1 : 0;
            $i++;
            $subs = (!in_array($agenda['daid'], $subsArray)) ? 0 : 1;
            $gCalendar = (isset($agenda['gCalendarId']) && $agenda['gCalendarId'] != '') ? 1 : 0;
            $name = (strlen($agenda['nom_agenda']) > 13) ? mb_strimwidth($agenda['nom_agenda'], 0, 13, '...') : $agenda['nom_agenda'];
            $agendasArray[] = array('nom_agenda' => $name,
                'fullName' => $agenda['nom_agenda'],
                'daid' => $agenda['daid'],
                'color' => $agenda['color'],
                'subs' => $subs,
                'newdiv' => $newdiv,
                'enddiv' => $enddiv,
                'gCalendar' => $gCalendar);
        }
        // Pass the array of agendas to the template
        $this->view->assign('agendas', $agendasArray);
        // Build an array with the months and pass it to the template
        $months = array(array('id' => 1,
                'name' => $this->__('January')),
            array('id' => 2,
                'name' => $this->__('February')),
            array('id' => 3,
                'name' => $this->__('March')),
            array('id' => 4,
                'name' => $this->__('April')),
            array('id' => 5,
                'name' => $this->__('May')),
            array('id' => 6,
                'name' => $this->__('June')),
            array('id' => 7,
                'name' => $this->__('July')),
            array('id' => 8,
                'name' => $this->__('August')),
            array('id' => 9,
                'name' => $this->__('September')),
            array('id' => 10,
                'name' => $this->__('October')),
            array('id' => 11,
                'name' => $this->__('November')),
            array('id' => 12,
                'name' => $this->__('December')));
        $this->view->assign('months', $months);
        // Build an array with the years and pass it to the template
        for ($i = 2000; $i < 2040; $i++) {
            $years[] = array('id' => $i,
                'name' => $i);
        }
        $this->view->assign('years', $years);
        // Set default values: current month and year
        if (!isset($mes))
            $mes = date("m");
        if (!isset($any))
            $any = date("Y");
        $this->view->assign('mes', $mes)
                ->assign('any', $any)
                ->assign('list', $llistat); // This must be a hidden param in the form
        $nombrenotes = 0;
        // Get the info of the agenda select and the month and year selects
        if (UserUtil::isLoggedIn()) {
            // Check whether the user has been subscribed to any agendas
            $this->view->assign('subscriptions', ModUtil::apiFunc('IWagendas', 'user', 'avissubscripcio'));
            // The user has been notified. Remove the notification indicator
            ModUtil::apiFunc('IWagendas', 'user', 'treuavis');
            // The agenda admin must see usage info
            if ($te_acces == 4) {
                $nombrenotes = ModUtil::apiFunc('IWagendas', 'user', 'comptanotes', array('daid' => $daid));
                $maxnotes = ModUtil::getVar('IWagendas', 'maxnotes');
                $avislimits = ModUtil::apiFunc('IWagendas', 'user', 'avislimits', array('daid' => $daid));
                // If the user has achieved the maximum number of notes, increase the counter
                if (($nombrenotes >= $maxnotes) && ($maxnotes != 0)) {
                    ModUtil::apiFunc('IWagendas', 'user', 'pujaavis', array('daid' => $daid,
                        'value' => $avislimits + 1));
                }
                // If the user has accessed main agenda page more than 10 times, show a form inviting to delete notes and reset the variable
                if ($avislimits >= 10 || $purga == 1) {
                    $this->view->assign('dia', $dia)
                            ->assign('purga', true)
                            ->assign('delete_previous', date('d/m/Y', time() - 60 * 24 * 60 * 60), 10, 10);
                    ModUtil::apiFunc('IWagendas', 'user', 'pujaavis', array('daid' => $daid,
                        'value' => 0));
                }
            }
        }
        // Get the options (the user menu)
        if ($te_acces >= 2) {
            if ($daid == 0) {
                // User logged in and is personal agenda or is admin => New annotation
                $user_menu[] = array('url' => DataUtil::formatForDisplay(ModUtil::url('IWagendas', 'user', 'nova', array('mes' => $mes,
                                'any' => $any,
                                'dia' => $dia,
                                'tasca' => 0,
                                'daid' => $gdaid,
                                'odaid' => $odaid))),
                    'text' => $this->__('Insert a new event'));
                // Is personal agenda => Add new task link
                $user_menu[] = array('url' => DataUtil::formatForDisplay(ModUtil::url('IWagendas', 'user', 'nova', array('mes' => $mes,
                                'any' => $any,
                                'dia' => $dia,
                                'tasca' => 1,
                                'daid' => 0))),
                    'text' => $this->__('Add a new task'));
            } else {
                if ((strpos($registre['gAccessLevel'], '$owne|' . $user . '$') !== false || $registre['gCalendarId']) == '') {
                    // User logged in and is personal agenda or is admin => New annotation
                    $user_menu[] = array('url' => DataUtil::formatForDisplay(ModUtil::url('IWagendas', 'user', 'nova', array('mes' => $mes,
                                    'any' => $any,
                                    'dia' => $dia,
                                    'tasca' => 0,
                                    'daid' => $gdaid,
                                    'odaid' => $odaid))),
                        'text' => $this->__('Insert a new event'));
                }
            }
        }
        if ($llistat == '1' ||
                !isset($llistat)) { // Show calendar or list
            $user_menu[] = array('url' => DataUtil::formatForDisplay(ModUtil::url('IWagendas', 'user', 'main', array('mes' => $mes,
                            'any' => $any,
                            'llistat' => -1,
                            'daid' => $daid))),
                'text' => $this->__('Calendar view'));
        } else {
            $user_menu[] = array('url' => DataUtil::formatForDisplay(ModUtil::url('IWagendas', 'user', 'main', array('mes' => $mes,
                            'any' => $any,
                            'llistat' => 1,
                            'daid' => $daid))),
                'text' => $this->__('List view'));
        }
        if ($daid > 0) {
            // Shared agenda
            if ($te_acces == 4 && $registre['gCalendarId'] == '') {
                // User is admin => Link to subscribe everybody who can access
                $user_menu[] = array('url' => DataUtil::formatForDisplay(ModUtil::url('IWagendas', 'user', 'substots', array('mes' => $mes,
                                'any' => $any,
                                'daid' => $daid))),
                    'text' => $this->__('Subscribe automaticaly everybody with access to this agenda'));
            }
        }
        if (ModUtil::func('IWagendas', 'user', 'getGdataFunctionsUsability') === true && ($daid == 0 || $registre['gCalendarId'] != '')) {
            $user_menu[] = array('url' => DataUtil::formatForDisplay(ModUtil::url('IWagendas', 'user', 'removeGCalendarUseVar', array('mes' => $mes,
                            'any' => $any,
                            'daid' => $daid))),
                'text' => $this->__('Refresh'));
        }
        if (ModUtil::getVar('IWagendas', 'calendariescolar') == 1) {
            // Schoolar calendar available => Show link
            $user_menu[] = array('url' => DataUtil::formatForDisplay(ModUtil::url('IWagendas', 'user', 'cescolar', array('mes' => $mes,
                            'any' => $any,
                            'daid' => $daid))),
                'text' => $this->__('School calendar'));
        }
        $width_usage = '';
        $percentage = '';
        if ($te_acces == 4 && ($daid == 0 || (isset($registre['gAccessLevel']) && strpos($registre['gAccessLevel'], '$owne|' . $user . '$') !== false) || (isset($registre['gCalendarId']) && $registre['gCalendarId'] == ''))) {
            // User logged in and is personal agenda or is admin
            $maxnotes = ModUtil::getVar('IWagendas', 'maxnotes');
            if ($maxnotes != 0) { // There's a limit on the amount of annotations
                $percentage = round($nombrenotes * 100 / $maxnotes);
                $width_usage = ($percentage > 100) ? 100 : $percentage;
            }
            $user_menu[] = array('url' => DataUtil::formatForDisplay(ModUtil::url('IWagendas', 'user', 'main', array('mes' => $mes,
                            'any' => $any,
                            'daid' => $daid,
                            'purga' => 1))),
                'text' => $this->__('Delete events previous to given date'));
        }
        $today = array('month' => date('m'),
            'year' => date('Y'));
        return $this->view->assign('number_of_notes', $nombrenotes)
                        ->assign('width_usage', $width_usage)
                        ->assign('percentage', $percentage)
                        ->assign('user_menu', $user_menu)
                        ->assign('reduced', $reduced)
                        ->assign('today', $today)
                        ->fetch('IWagendas_user_menu.htm');
    }
Exemplo n.º 14
0
 /**
  * Perform the search then show the results
  *
  * This function includes all the search plugins, then call every one passing
  * an array that contains the string to search for, the boolean operators.
  *
  * @return string HTML string templated
  */
 public function search()
 {
     // Security check
     if (!SecurityUtil::checkPermission('Search::', '::', ACCESS_READ)) {
         return LogUtil::registerPermissionError();
     }
     // get parameter from HTTP input
     $vars = array();
     $vars['q'] = strip_tags(FormUtil::getPassedValue('q', '', 'REQUEST'));
     $vars['searchtype'] = FormUtil::getPassedValue('searchtype', SessionUtil::getVar('searchtype'), 'REQUEST');
     $vars['searchorder'] = FormUtil::getPassedValue('searchorder', SessionUtil::getVar('searchorder'), 'REQUEST');
     $vars['numlimit'] = $this->getVar('itemsperpage', 25);
     $vars['page'] = (int) FormUtil::getPassedValue('page', 1, 'REQUEST');
     // $firstpage is used to identify the very first result page
     // - and to disable calls to plugins on the following pages
     $vars['firstPage'] = !isset($_REQUEST['page']);
     // The modulename exists in this array as key, if the checkbox was filled
     $vars['active'] = FormUtil::getPassedValue('active', SessionUtil::getVar('searchactive'), 'REQUEST');
     // All formular data from the modules search plugins is contained in:
     $vars['modvar'] = FormUtil::getPassedValue('modvar', SessionUtil::getVar('searchmodvar'), 'REQUEST');
     if (empty($vars['q'])) {
         LogUtil::registerError($this->__('Error! You did not enter any keywords to search for.'));
         $this->redirect(ModUtil::url('Search', 'user', 'form'));
     }
     // set some defaults
     if (!isset($vars['searchtype']) || empty($vars['searchtype'])) {
         $vars['searchtype'] = 'AND';
     } else {
         SessionUtil::setVar('searchtype', $vars['searchtype']);
     }
     if (!isset($vars['searchorder']) || empty($vars['searchorder'])) {
         $vars['searchorder'] = 'newest';
     } else {
         SessionUtil::setVar('searchorder', $vars['searchorder']);
     }
     if (!isset($vars['active']) || !is_array($vars['active']) || empty($vars['active'])) {
         $vars['active'] = array();
     } else {
         SessionUtil::setVar('searchactive', $vars['active']);
     }
     if (!isset($vars['modvar']) || !is_array($vars['modvar']) || empty($vars['modvar'])) {
         $vars['modvar'] = array();
     } else {
         SessionUtil::setVar('searchmodvar', $vars['modvar']);
     }
     /*
     // FIXME: Cannot cache correctly while do not know
     // the parameters passed to the search plugins, and
     // build a complete cache_id
     
     // setup an individual cache
     $lifetime = ModUtil::getVar('Theme', 'render_lifetime');
     $lifetime = $lifetime ? $lifetime : 3600;
     
     $cacheid = md5($vars['q'].'-'.$vars['searchtype'].'-'.$vars['searchorder']).'/'.UserUtil::getGidCacheString().'/page'.$vars['page'];
     
     $this->view->setCaching(Zikula_View::CACHE_INDIVIDUAL)
                ->setCacheLifetime($lifetime)
                ->setCacheId($cacheid);
     
     // check if the contents are cached
     if ($this->view->is_cached('search_user_results.tpl')) {
         return $this->view->fetch('search_user_results.tpl');
     }
     */
     $result = ModUtil::apiFunc('Search', 'user', 'search', $vars);
     // Get number of chars to display in search summaries
     $limitsummary = $this->getVar('limitsummary');
     if (empty($limitsummary)) {
         $limitsummary = 200;
     }
     $this->view->assign('resultcount', $result['resultCount'])->assign('results', $result['sqlResult'])->assign($this->getVars())->assign($vars)->assign('limitsummary', $limitsummary);
     // log the search if on first page
     if ($vars['firstPage']) {
         ModUtil::apiFunc('Search', 'user', 'log', $vars);
     }
     // Return the output that has been generated by this function
     return $this->view->fetch('search_user_results.tpl');
 }
Exemplo n.º 15
0
 /**
  * Fix language to session.
  *
  * @return void
  */
 private function fixLanguageToSession()
 {
     if ($this->langFixSession) {
         SessionUtil::setVar('language', $this->languageCode);
     }
 }
Exemplo n.º 16
0
 /**
  * Get the user permissions for the noteboard
  * @author:     Albert Pérez Monfort (aperezm@xtec.cat)
  * @param:	args	The id of the note
  * 			The string of mached notes by the user
  * @return:	True if success and false otherwise
  */
 public function permisos($args) {
     $uid = FormUtil::getPassedValue('uid', isset($args['uid']) ? $args['uid'] : UserUtil::getVar('uid'), 'POST');
     $sv = FormUtil::getPassedValue('sv', isset($args['sv']) ? $args['sv'] : null, 'POST');
     $requestByCron = false;
     if (!ModUtil::func('IWmain', 'user', 'checkSecurityValue', array('sv' => $sv))) {
         // Security check
         if (!SecurityUtil::checkPermission('IWnoteboard::', '::', ACCESS_READ)) {
             return LogUtil::registerPermissionError();
         }
     } else {
         $requestByCron = true;
     }
     $n_permisos = 0;
     $nivell_permisos = array();
     //if user is not registered have a fixed permissions
     if (!UserUtil::isLoggedIn() && !$requestByCron) {
         $nivell_permisos = array('nivell' => 1,
             'verifica' => 2,
             'potverificar' => false,
             'grups' => array(0));
         //return not registered permissions
         return $nivell_permisos;
     }
     // Arguments needed
     if (!isset($uid) || ($uid != UserUtil::getVar('uid') && !$requestByCron)) {
         SessionUtil::setVar('errormsg', $this->__('Error! Could not do what you wanted. Please check your input.'));
         return $nivell_permisos;
     }
     $myJoin = array();
     $myJoin[] = array('join_table' => 'groups',
         'join_field' => array('gid'),
         'object_field_name' => array('gid'),
         'compare_field_table' => 'gid',
         'compare_field_join' => 'gid');
     $myJoin[] = array('join_table' => 'group_membership',
         'join_field' => array(),
         'object_field_name' => array(),
         'compare_field_table' => 'gid',
         'compare_field_join' => 'gid');
     $pntables = DBUtil::getTables();
     $ccolumn = $pntables['groups_column'];
     $ocolumn = $pntables['group_membership_column'];
     $where = "b.$ocolumn[gid] = a.$ccolumn[gid] AND b.$ocolumn[uid] = $uid";
     $items = DBUtil::selectExpandedObjectArray('groups', $myJoin, $where, '');
     // Check for an error with the database code, and if so set an appropriate
     // error message and return
     if ($items === false) {
         return $nivell_permisos;
     }
     $verifica = 2;
     $potverificar = false;
     $permisosModVar = ModUtil::getVar('IWnoteboard', 'permisos');
     $verificaModVar = ModUtil::getVar('IWnoteboard', 'verifica');
     $quiverificaModVar = ModUtil::getVar('IWnoteboard', 'quiverifica');
     foreach ($items as $item) {
         // get user permissions level
         $permis = substr($permisosModVar, strpos($permisosModVar, '$' . $item['gid'] . '-') + strlen($item['gid']) + 2, 1);
         $verifica = (strpos($verificaModVar, '$' . $item['gid'] . '$') != 0 && $verifica != 1) ? 0 : 1;
         if ($permis > $n_permisos) {
             $n_permisos = $permis;
         }
         if ($quiverificaModVar == $item['gid']) {
             $potverificar = true;
         }
         $grups[] = $item['gid'];
     }
     $nivell_permisos = array('nivell' => $n_permisos,
         'verifica' => $verifica,
         'potverificar' => $potverificar,
         'grups' => $grups);
     return $nivell_permisos;
 }
Exemplo n.º 17
0
/**
 * Set a session variable
 *
 * @deprecated
 * @see SessionUtil::setVar()
 * @param string $name of the session variable to set
 * @param value $value to set the named session variable
 * @return bool true
 */
function pnSessionSetVar($name, $value)
{
    LogUtil::log(__f('Warning! Function %1$s is deprecated. Please use %2$s instead.', array(
        'pnSessionsetVar()',
        'SessionUtil::setVar()')), E_USER_DEPRECATED);
    return SessionUtil::setVar($name, $value);
}
Exemplo n.º 18
0
 /**
  * This method provides a generic item detail view.
  *
  * @param string  $ot           Treated object type.
  * @param string  $tpl          Name of alternative template (for alternative display options, feeds and xml output)
  * @param boolean $raw          Optional way to display a template instead of fetching it (needed for standalone output)
  * @return mixed Output.
  */
 public function display($args)
 {
     // DEBUG: permission check aspect starts
     $this->throwForbiddenUnless(SecurityUtil::checkPermission('MUBoard::', '::', ACCESS_READ));
     // DEBUG: permission check aspect ends
     // parameter specifying which type of objects we are treating
     $objectType = isset($args['ot']) && !empty($args['ot']) ? $args['ot'] : $this->request->getGet()->filter('ot', 'category', FILTER_SANITIZE_STRING);
     $utilArgs = array('controller' => 'user', 'action' => 'display');
     if (!in_array($objectType, MUBoard_Util_Controller::getObjectTypes('controllerAction', $utilArgs))) {
         $objectType = MUBoard_Util_Controller::getDefaultObjectType('controllerAction', $utilArgs);
     }
     $repository = $this->entityManager->getRepository('MUBoard_Entity_' . ucfirst($objectType));
     $idFields = ModUtil::apiFunc($this->name, 'selection', 'getIdFields', array('ot' => $objectType));
     // retrieve identifier of the object we wish to view
     $idValues = MUBoard_Util_Controller::retrieveIdentifier($this->request, $args, $objectType, $idFields);
     $hasIdentifier = MUBoard_Util_Controller::isValidIdentifier($idValues);
     // check for unique permalinks (without id)
     $hasSlug = false;
     $slugTitle = '';
     if ($hasIdentifier === false) {
         $entityClass = 'MUBoard_Entity_' . ucfirst($objectType);
         $objectTemp = new $entityClass();
         $hasSlug = $objectTemp->get_hasUniqueSlug();
         if ($hasSlug) {
             $slugTitle = isset($args['title']) && !empty($args['title']) ? $args['title'] : $this->request->getGet()->filter('title', '', FILTER_SANITIZE_STRING);
             $hasSlug = !empty($slugTitle);
         }
     }
     $hasIdentifier |= $hasSlug;
     $this->throwNotFoundUnless($hasIdentifier, $this->__('Error! Invalid identifier received.'));
     $entity = ModUtil::apiFunc($this->name, 'selection', 'getEntity', array('ot' => $objectType, 'id' => $idValues, 'slug' => $slugTitle));
     $this->throwNotFoundUnless($entity != null, $this->__('No such item.'));
     // we take the children postings of the parent issue
     if ($objectType == 'posting') {
         $postingid = $entity['id'];
         $postingsWhere = 'tbl.parent = \'' . DataUtil::formatForStore($postingid) . '\'';
         $order = ModUtil::getVar($this->name, 'sortingPostings');
         if ($order == 'descending') {
             $sdir = 'desc';
         } else {
             $sdir = 'asc';
         }
         $selectionArgs = array('ot' => 'posting', 'where' => $postingsWhere, 'orderBy' => 'createdDate' . ' ' . $sdir);
         // the current offset which is used to calculate the pagination
         $currentPage = (int) (isset($args['pos']) && !empty($args['pos'])) ? $args['pos'] : $this->request->getGet()->filter('pos', 1, FILTER_VALIDATE_INT);
         // the number of items displayed on a page for pagination
         $resultsPerPage = (int) (isset($args['num']) && !empty($args['num'])) ? $args['num'] : $this->request->getGet()->filter('num', 0, FILTER_VALIDATE_INT);
         if ($resultsPerPage == 0) {
             $csv = (int) (isset($args['usecsv']) && !empty($args['usecsv'])) ? $args['usecsv'] : $this->request->getGet()->filter('usecsvext', 0, FILTER_VALIDATE_INT);
             $resultsPerPage = $csv == 1 ? 999999 : $this->getVar('pagesize', 10);
         }
         $selectionArgs['currentPage'] = $currentPage;
         $selectionArgs['resultsPerPage'] = $resultsPerPage;
         list($entities, $objectCount) = ModUtil::apiFunc($this->name, 'selection', 'getEntitiesPaginated', $selectionArgs);
         // we check if the user may see the form to answer to posting
         $mayEdit = MUBoard_Util_Controller::mayEdit($id);
         $this->view->assign('mayEdit', $mayEdit);
     }
     if ($objectType == 'forum') {
         $forumid = $entity['id'];
         $parentWhere = 'tbl.parent_id IS NULL';
         $parentWhere .= ' AND ';
         $parentWhere .= 'tbl.forum = \'' . DataUtil::formatForStore($forumid) . '\'';
         $order = ModUtil::getVar($this->name, 'sortingPostings');
         if ($order == 'descending') {
             $sdir = 'desc';
         } else {
             $sdir = 'asc';
         }
         $selectionArgs = array('ot' => 'posting', 'where' => $parentWhere, 'orderBy' => 'createdDate' . ' ' . $sdir);
         // the current offset which is used to calculate the pagination
         $currentPage = (int) (isset($args['pos']) && !empty($args['pos'])) ? $args['pos'] : $this->request->getGet()->filter('pos', 1, FILTER_VALIDATE_INT);
         // the number of items displayed on a page for pagination
         $resultsPerPage = (int) (isset($args['num']) && !empty($args['num'])) ? $args['num'] : $this->request->getGet()->filter('num', 0, FILTER_VALIDATE_INT);
         if ($resultsPerPage == 0) {
             $csv = (int) (isset($args['usecsv']) && !empty($args['usecsv'])) ? $args['usecsv'] : $this->request->getGet()->filter('usecsvext', 0, FILTER_VALIDATE_INT);
             $resultsPerPage = $csv == 1 ? 999999 : $this->getVar('pagesize', 10);
         }
         $selectionArgs['currentPage'] = $currentPage;
         $selectionArgs['resultsPerPage'] = $resultsPerPage;
         list($entities, $objectCount) = ModUtil::apiFunc($this->name, 'selection', 'getEntitiesPaginated', $selectionArgs);
     }
     // build ModUrl instance for display hooks
     $currentUrlArgs = array('ot' => $objectType);
     foreach ($idFields as $idField) {
         $currentUrlArgs[$idField] = $idValues[$idField];
     }
     // add a call to the posting
     if ($objectType == 'posting') {
         MUBoard_Util_Model::addView($idValues);
     }
     // get actual time
     $nowtime = DateUtil::getDatetime();
     // set sessionvar with calling time
     SessionUtil::setVar('muboardonline', $nowtime);
     $currentUrlObject = new Zikula_ModUrl($this->name, 'user', 'display', ZLanguage::getLanguageCode(), $currentUrlArgs);
     $type = $this->request->getGet()->filter('type', 'admin', FILTER_SANITIZE_STRING);
     $func = $this->request->getGet()->filter('func', 'view', FILTER_SANITIZE_STRING);
     $editPostings = ModUtil::getVar($this->name, 'editPostings');
     // assign output data to view object.
     $this->view->assign($objectType, $entity)->assign('postings', $entities)->assign('currentUrlObject', $currentUrlObject)->assign('func', $func)->assign('editPostings', $editPostings)->assign($repository->getAdditionalTemplateParameters('controllerAction', $utilArgs));
     $this->view->assign('currentPage', $currentPage)->assign('pager', array('numitems' => $objectCount, 'itemsperpage' => $resultsPerPage));
     $dom = ZLanguage::getModuleDomain($this->name);
     // we set Pagetitle
     $sitename = ModUtil::getVar('ZConfig', 'sitename');
     if ($objectType == 'category') {
         $titletobject = __('Forum - Category: ', $dom);
     }
     if ($objectType == 'forum') {
         $titletobject = __('Forum - Category: ', $dom) . ' ' . $entity['category']['title'] . ' - ' . __('Forum: ', $dom);
     }
     if ($objectType == 'posting') {
         $titletobject = 'Forum: ' . ' ' . $entity['forum']['title'] . ' - ' . __('Issue: ', $dom);
     }
     PageUtil::setVar('title', $sitename . ' - ' . $titletobject . ' ' . $entity['title']);
     // we set description
     if ($objectType == 'category' || $objectType == 'forum') {
         $descriptionobject = $entity['description'];
     }
     if ($objectType == 'posting') {
         $descriptionobject = $entity['text'];
         $descriptionobject = substr($descriptionobject, 0, 160) . '...';
     }
     PageUtil::setVar('description', $descriptionobject);
     // fetch and return the appropriate template
     return MUBoard_Util_View::processTemplate($this->view, 'user', $objectType, 'display', $args);
 }
Exemplo n.º 19
0
 /**
  * Upgrade a module.
  *
  * @param array $args All parameters passed to this function.
  *                      numeric $args['id']                  The module ID.
  *                      boolean $args['interactive_upgrade'] Whether or not to upgrade in interactive mode.
  *
  * @return boolean True on success, false on failure.
  */
 public function upgrade($args)
 {
     // Argument check
     if (!isset($args['id']) || !is_numeric($args['id'])) {
         return LogUtil::registerArgsError();
     }
     // Get module information
     $modinfo = ModUtil::getInfo($args['id']);
     if (empty($modinfo)) {
         return LogUtil::registerError($this->__('Error! No such module ID exists.'));
     }
     switch ($modinfo['state']) {
         case ModUtil::STATE_NOTALLOWED:
             return LogUtil::registerError($this->__f('Error! No permission to upgrade %s.', $modinfo['name']));
             break;
         default:
             if ($modinfo['state'] > 10) {
                 return LogUtil::registerError($this->__f('Error! %s is not compatible with this version of Zikula.', $modinfo['name']));
             }
     }
     $osdir = DataUtil::formatForOS($modinfo['directory']);
     ModUtil::dbInfoLoad($modinfo['name'], $osdir);
     $modpath = $modinfo['type'] == ModUtil::TYPE_SYSTEM ? 'system' : 'modules';
     // load module maintainence functions
     $oomod = ModUtil::isOO($modinfo['name']);
     if ($oomod) {
         ZLoader::addAutoloader($osdir, "{$modpath}/{$osdir}/lib");
     }
     $bootstrap = "{$modpath}/{$osdir}/bootstrap.php";
     if (file_exists($bootstrap)) {
         include_once $bootstrap;
     }
     if ($modinfo['type'] == ModUtil::TYPE_MODULE) {
         if (is_dir("modules/{$osdir}/locale")) {
             ZLanguage::bindModuleDomain($modinfo['name']);
         }
     }
     if (!$oomod && file_exists($file = "{$modpath}/{$osdir}/pninit.php")) {
         if (!(include_once $file)) {
             LogUtil::registerError($this->__f("Error! Could not load a required file: '%s'.", $file));
         }
     }
     if ($oomod) {
         $className = ucwords($modinfo['name']) . '_Installer';
         $reflectionInstaller = new ReflectionClass($className);
         if (!$reflectionInstaller->isSubclassOf('Zikula_AbstractInstaller')) {
             LogUtil::registerError($this->__f("%s must be an instance of Zikula_AbstractInstaller", $className));
         }
         $installer = $reflectionInstaller->newInstanceArgs(array($this->serviceManager));
         $interactiveClass = ucwords($modinfo['name']) . '_Controller_Interactiveinstaller';
         $interactiveController = null;
         if (class_exists($interactiveClass)) {
             $reflectionInteractive = new ReflectionClass($interactiveClass);
             if (!$reflectionInteractive->isSubclassOf('Zikula_Controller_AbstractInteractiveInstaller')) {
                 LogUtil::registerError($this->__f("%s must be an instance of Zikula_Controller_AbstractInteractiveInstaller", $className));
             }
             $interactiveController = $reflectionInteractive->newInstance($this->serviceManager);
         }
     }
     // perform the actual upgrade of the module
     $func = $oomod ? array($installer, 'upgrade') : $modinfo['name'] . '_upgrade';
     $interactive_func = $oomod ? array($interactiveController, 'upgrade') : $modinfo['name'] . '_init_interactiveupgrade';
     // allow bypass of interactive upgrade during a new installation only.
     if (System::isInstalling() && is_callable($interactive_func) && !is_callable($func)) {
         return;
         // return void here
     }
     if (isset($args['interactive_upgrade']) && $args['interactive_upgrade'] == false && is_callable($interactive_func)) {
         if (is_array($interactive_func)) {
             // This must be an OO controller since callable is an array.
             // Because interactive installers extend the Zikula_AbstractController, is_callable will always return true because of the __call()
             // so we must check if the method actually exists by reflection - drak
             if ($reflectionInteractive->hasMethod('upgrade')) {
                 SessionUtil::setVar('interactive_upgrade', true);
                 return call_user_func($interactive_func, array('oldversion' => $modinfo['version']));
             }
         } else {
             // this is enclosed in the else so that if both conditions fail, execution will pass onto the non-interactive execution below.
             SessionUtil::setVar('interactive_upgrade', true);
             return call_user_func($interactive_func, array('oldversion' => $modinfo['version']));
         }
     }
     // non-interactive
     if (is_callable($func)) {
         $result = call_user_func($func, $modinfo['version']);
         if (is_string($result)) {
             if ($result != $modinfo['version']) {
                 // update the last successful updated version
                 $modinfo['version'] = $result;
                 $obj = DBUtil::updateObject($modinfo, 'modules', '', 'id', true);
             }
             return false;
         } elseif ($result != true) {
             return false;
         }
     }
     $modversion['version'] = '0';
     $modversion = Extensions_Util::getVersionMeta($osdir, $modpath);
     $version = $modversion['version'];
     // Update state of module
     $result = $this->setState(array('id' => $args['id'], 'state' => ModUtil::STATE_ACTIVE));
     if ($result) {
         LogUtil::registerStatus($this->__("Done! Module has been upgraded. Its status is now 'Active'."));
     } else {
         return false;
     }
     // Note the changes in the database...
     // Get module database info
     ModUtil::dbInfoLoad('Extensions');
     $obj = array('id' => $args['id'], 'version' => $version);
     DBUtil::updateObject($obj, 'modules');
     // legacy to be removed from 1.4 - remove hooks during upgrade since we cannot rely on
     // module authors to do this - drak
     if ($oomod) {
         $tables = DBUtil::getTables();
         $hooksCol = $tables['hooks_column'];
         $where = "{$hooksCol['smodule']} = '{$modinfo['name']}' OR {$hooksCol['tmodule']} = '{$modinfo['name']}'";
         $hooks = DBUtil::selectObjectArray('hooks', $where);
         if ($hooks) {
             foreach ($hooks as $hook) {
                 DBUtil::deleteObject($hook, 'hooks');
             }
             LogUtil::registerStatus($this->__f("NOTICE! Legacy hook configurations for %s have been removed.", $modinfo['name']));
         }
     }
     // Upgrade succeeded, issue event.
     $event = new Zikula_Event('installer.module.upgraded', null, $modinfo);
     $this->eventManager->notify($event);
     // Success
     return true;
 }
Exemplo n.º 20
0
 /**
  * Input data processing called by handleCommand method.
  *
  * @param Zikula_Form_View $view The form view instance.
  * @param array            $args Additional arguments.
  *
  * @return array form data after processing.
  */
 public function fetchInputData(Zikula_Form_View $view, &$args)
 {
     // fetch posted data input values as an associative array
     $formData = $this->view->getValues();
     // we want the array with our field values
     $entityData = $formData[$this->objectTypeLower];
     unset($formData[$this->objectTypeLower]);
     // get treated entity reference from persisted member var
     $entity = $this->entityRef;
     if ($args['commandName'] != 'cancel') {
         if (count($this->uploadFields) > 0) {
             $entityData = $this->handleUploads($entityData, $entity);
             if ($entityData == false) {
                 return false;
             }
         }
         if (count($this->listFields) > 0) {
             foreach ($this->listFields as $listField => $multiple) {
                 if (!$multiple) {
                     continue;
                 }
                 if (is_array($entityData[$listField])) {
                     $values = $entityData[$listField];
                     $entityData[$listField] = '';
                     if (count($values) > 0) {
                         $entityData[$listField] = '###' . implode('###', $values) . '###';
                     }
                 }
             }
         }
     } else {
         // remove fields for form options to prevent them being merged into the entity object
         if (count($this->uploadFields) > 0) {
             foreach ($this->uploadFields as $uploadField => $isMandatory) {
                 if (isset($entityData[$uploadField . 'DeleteFile'])) {
                     unset($entityData[$uploadField . 'DeleteFile']);
                 }
             }
         }
     }
     if (isset($entityData['repeatCreation'])) {
         if ($this->mode == 'create') {
             $this->repeatCreateAction = $entityData['repeatCreation'];
         }
         unset($entityData['repeatCreation']);
     }
     if (isset($entityData['additionalNotificationRemarks'])) {
         SessionUtil::setVar($this->name . 'AdditionalNotificationRemarks', $entityData['additionalNotificationRemarks']);
         unset($entityData['additionalNotificationRemarks']);
     }
     // search for relationship plugins to update the corresponding data
     $entityData = $this->writeRelationDataToEntity($view, $entity, $entityData);
     // assign fetched data
     $entity->merge($entityData);
     // we must persist related items now (after the merge) to avoid validation errors
     // if cascades cause the main entity becoming persisted automatically, too
     $this->persistRelationData($view);
     // save updated entity
     $this->entityRef = $entity;
     // return remaining form data
     return $formData;
 }
Exemplo n.º 21
0
    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');
    }
Exemplo n.º 22
0
 /**
  *
  */
 public static function modifyPostings($userid)
 {
     $view = new Zikula_Request_Http();
     $postingid = $view->query->filter('id', 0, FILTER_SANITIZE_STRING);
     $postingids = SessionUtil::getVar('muboardpostingids');
     if (count($postingids) > 0 && is_array($postingids)) {
         if (in_array($postingid, $postingids)) {
             $pos = array_search($postingid, $postingids);
             unset($postingids[$pos]);
         }
     }
     if (count($postingids) > 0) {
         SessionUtil::setVar('muboardpostingids', $postingids);
     } else {
         SessionUtil::delVar('muboardpostingids');
     }
 }
Exemplo n.º 23
0
 /**
  * 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);
 }
Exemplo n.º 24
0
    /**
     * edit category for a simple, non-recursive set of categories
     */
    public function edit()
    {
        $docroot = FormUtil::getPassedValue('dr', 0);
        $cid = FormUtil::getPassedValue('cid', 0);
        $url = ModUtil::url('Categories', 'user', 'edit', array('dr' => $docroot));

        if (!SecurityUtil::checkPermission('Categories::category', "ID::$docroot", ACCESS_EDIT)) {
            return LogUtil::registerPermissionError($url);
        }

        $referer = System::serverGetVar('HTTP_REFERER');
        if (strpos($referer, 'module=Categories') === false) {
            SessionUtil::setVar('categories_referer', $referer);
        }

        $rootCat = array();
        $allCats = array();
        $editCat = array();

        if (!$docroot) {
            return LogUtil::registerError($this->__("Error! The URL contains an invalid 'document root' parameter."), null, $url);
        }
        if ($docroot == 1) {
            return LogUtil::registerError($this->__("Error! The root directory cannot be modified in 'user' mode"), null, $url);
        }

        if (is_int((int)$docroot) && $docroot > 0) {
            $rootCat = CategoryUtil::getCategoryByID($docroot);
        } else {
            $rootCat = CategoryUtil::getCategoryByPath($docroot);
            if (!$rootCat) {
                $rootCat = CategoryUtil::getCategoryByPath($docroot, 'ipath');
            }
        }

        // now check if someone is trying edit another user's categories
        $userRoot = $this->getVar('userrootcat', 0);
        if ($userRoot) {
            $userRootCat = CategoryUtil::getCategoryByPath($userRoot);
            if ($userRootCat) {
                $userRootCatIPath = $userRootCat['ipath'];
                $rootCatIPath = $rootCat['ipath'];
                if (strpos($rootCatIPath, $userRootCatIPath) !== false) {
                    if (!SecurityUtil::checkPermission('Categories::category', "ID::$docroot", ACCESS_ADMIN)) {
                        $thisUserRootCategoryName = ModUtil::apiFunc('Categories', 'user', 'getusercategoryname');
                        $thisUserRootCatPath = $userRootCat['path'] . '/' . $thisUserRootCategoryName;
                        $userRootCatPath = $userRootCat['path'];
                        $rootCatPath = $rootCat['path'];
                        if (strpos($rootCatPath, $userRootCatPath) === false) {
                            //! %s represents the root path (id), passed in the url
                            return LogUtil::registerError($this->__f("Error! It looks like you are trying to edit another user's categories. Only site administrators can do that (%s).", $docroot), null, $url);
                        }
                    }
                }
            }
        }

        if ($cid) {
            $editCat = CategoryUtil::getCategoryByID($cid);
            if ($editCat['is_locked']) {
                //! %1$s is the id, %2$s is the name
                return LogUtil::registerError($this->__f('Notice: The administrator has locked the category \'%2$s\' (ID \'%$1s\'). You cannot edit or delete it.', array($cid, $editCat['name'])), null, $url);
            }
        }

        if (!$rootCat) {
            return LogUtil::registerError($this->__f("Error! Cannot access root directory (%s).", $docroot), null, $url);
        }
        if ($editCat && !$editCat['is_leaf']) {
            return LogUtil::registerError($this->__f('Error! The specified category is not a leaf-level category (%s).', $cid), null, $url);
        }
        if ($editCat && !CategoryUtil::isDirectSubCategory($rootCat, $editCat)) {
            return LogUtil::registerError($this->__f('Error! The specified category is not a child of the document root (%1$s; %2$s).', array($docroot, $cid)), null, $url);
        }

        $allCats = CategoryUtil::getSubCategoriesForCategory($rootCat, false, false, false, true, true);

        $attributes = isset($editCat['__ATTRIBUTES__']) ? $editCat['__ATTRIBUTES__'] : array();

        $languages = ZLanguage::getInstalledLanguages();

        $this->view->setCaching(Zikula_View::CACHE_DISABLED);

        return $this->view->assign('rootCat', $rootCat)
                    ->assign('category', $editCat)
                    ->assign('attributes', $attributes)
                    ->assign('allCats', $allCats)
                    ->assign('languages', $languages)
                    ->assign('userlanguage', ZLanguage::getLanguageCode())
                    ->assign('referer', SessionUtil::getVar('categories_referer'))
                    ->fetch('categories_user_edit.tpl');
    }
Exemplo n.º 25
0
 /**
  * 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);
 }
Exemplo n.º 26
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');
 }
Exemplo n.º 27
0
    /**
     * 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;
    }
Exemplo n.º 28
0
    /**
     * This is a standard function that is called with the results of the
     * form supplied by News_admin_newitem() or News_user_newitem to create
     * a new item.
     *
     * @author Mark West
     * @param string 'title' the title of the news item
     * @param string 'language' the language of the news item
     * @param string 'hometext' the summary text of the news item
     * @param int 'hometextcontenttype' the content type of the summary text
     * @param string 'bodytext' the body text of the news item
     * @param int 'bodytextcontenttype' the content type of the body text
     * @param string 'notes' any administrator notes
     * @param int 'published_status' the published status of the item
     * @param int 'displayonindex' display the article on the index page
     * @return bool true
     */
    public function create($args)
    {
        // Get parameters from whatever input we need
        $story = FormUtil::getPassedValue('story', isset($args['story']) ? $args['story'] : null, 'POST');
        $files = News_ImageUtil::reArrayFiles(FormUtil::getPassedValue('news_files', null, 'FILES'));

        // Create the item array for processing
        $item = array(
            'title' => $story['title'],
            'urltitle' => isset($story['urltitle']) ? $story['urltitle'] : '',
            '__CATEGORIES__' => isset($story['__CATEGORIES__']) ? $story['__CATEGORIES__'] : null,
            '__ATTRIBUTES__' => isset($story['attributes']) ? News_Util::reformatAttributes($story['attributes']) : null,
            'language' => isset($story['language']) ? $story['language'] : '',
            'hometext' => isset($story['hometext']) ? $story['hometext'] : '',
            'hometextcontenttype' => $story['hometextcontenttype'],
            'bodytext' => isset($story['bodytext']) ? $story['bodytext'] : '',
            'bodytextcontenttype' => $story['bodytextcontenttype'],
            'notes' => $story['notes'],
            'displayonindex' => isset($story['displayonindex']) ? $story['displayonindex'] : 0,
            'allowcomments' => isset($story['allowcomments']) ? $story['allowcomments'] : 0,
            'from' => isset($story['from']) ? $story['from'] : null,
            'tonolimit' => isset($story['tonolimit']) ? $story['tonolimit'] : null,
            'to' => isset($story['to']) ? $story['to'] : null,
            'unlimited' => isset($story['unlimited']) && $story['unlimited'] ? true : false,
            'weight' => isset($story['weight']) ? $story['weight'] : 0,
            'action' => isset($story['action']) ? $story['action'] : self::ACTION_PREVIEW,
            'sid' => isset($story['sid']) ? $story['sid'] : null,
            'tempfiles' => isset($story['tempfiles']) ? $story['tempfiles'] : null,
            'del_pictures' => isset($story['del_pictures']) ? $story['del_pictures'] : null,
        );

        // convert user times to server times (TZ compensation) refs #181
        //  can't do the below because values are YYYY-MM-DD HH:MM:SS and DateUtil value is in seconds.
        // $item['from'] = $item['from'] + DateUtil::getTimezoneUserDiff();
        // $item['to'] = $item['to'] + DateUtil::getTimezoneUserDiff();
        // Disable the non accessible fields for non editors
        if (!SecurityUtil::checkPermission('News::', '::', ACCESS_ADD)) {
            $item['notes'] = '';
            $item['displayonindex'] = 1;
            $item['allowcomments'] = 1;
            $item['from'] = null;
            $item['tonolimit'] = true;
            $item['to'] = null;
            $item['unlimited'] = true;
            $item['weight'] = 0;
            if ($item['action'] > self::ACTION_SUBMIT) {
                $item['action'] = self::ACTION_PREVIEW;
            }
        }

        // Validate the input
        $validationerror = News_Util::validateArticle($item);
        // check hooked modules for validation
        $sid = isset($item['sid']) ? $item['sid'] : null;
        $hookvalidators = $this->notifyHooks(new Zikula_ValidationHook('news.ui_hooks.articles.validate_edit', new Zikula_Hook_ValidationProviders()))->getValidators();
        if ($hookvalidators->hasErrors()) {
            $validationerror .= $this->__('Error! Hooked content does not validate.') . "\n";
        }

        // get all module vars
        $modvars = $this->getVars();

        if (isset($files) && $modvars['picupload_enabled']) {
            list($files, $item) = News_ImageUtil::validateImages($files, $item);
        } else {
            $item['pictures'] = 0;
        }

        // story was previewed with uploaded pics
        if (isset($item['tempfiles'])) {
            $tempfiles = unserialize($item['tempfiles']);
            // delete files if requested
            if (isset($item['del_pictures'])) {
                foreach ($tempfiles as $key => $file) {
                    if (in_array($file['name'], $item['del_pictures'])) {
                        unset($tempfiles[$key]);
                        News_ImageUtil::removePreviewImages(array($file));
                    }
                }
            }
            $files = array_merge($files, $tempfiles);
            $item['pictures'] += count($tempfiles);
        }

        // if the user has selected to preview the article we then route them back
        // to the new function with the arguments passed here
        if ($item['action'] == self::ACTION_PREVIEW || $validationerror !== false) {
            // log the error found if any
            if ($validationerror !== false) {
                LogUtil::registerError(nl2br($validationerror));
            }
            if ($item['pictures'] > 0) {
                $tempfiles = News_ImageUtil::tempStore($files);
                $item['tempfiles'] = serialize($tempfiles);
            }
            // back to the referer form
            SessionUtil::setVar('newsitem', $item);
            $this->redirect(ModUtil::url('News', 'user', 'newitem'));
        } else {
            // As we're not previewing the item let's remove it from the session
            SessionUtil::delVar('newsitem');
        }

        // Confirm authorization code.
        $this->checkCsrfToken();

        if (!isset($item['sid']) || empty($item['sid'])) {
            // Create the news story
            $sid = ModUtil::apiFunc('News', 'user', 'create', $item);
            if ($sid != false) {
                // Success
                LogUtil::registerStatus($this->__('Done! Created new article.'));
                // Let any hooks know that we have created a new item
                $this->notifyHooks(new Zikula_ProcessHook('news.ui_hooks.articles.process_edit', $sid, new Zikula_ModUrl('News', 'User', 'display', ZLanguage::getLanguageCode(), array('sid' => $sid))));
                $this->notify($item); // send notification email
            } else {
                // fail! story not created
                throw new Zikula_Exception_Fatal($this->__('Story not created for unknown reason (Api failure).'));
                return false;
            }
        } else {
            // update the draft
            $result = ModUtil::apiFunc('News', 'admin', 'update', $item);
            if ($result) {
                LogUtil::registerStatus($this->__('Story Updated.'));
            } else {
                // fail! story not updated
                throw new Zikula_Exception_Fatal($this->__('Story not updated for unknown reason (Api failure).'));
                return false;
            }
        }

        // clear respective cache
        ModUtil::apiFunc('News', 'user', 'clearItemCache', $item);

        if (isset($files) && $modvars['picupload_enabled']) {
            $resized = News_ImageUtil::resizeImages($sid, $files); // resize and move the uploaded pics
            if (isset($item['tempfiles'])) {
                News_ImageUtil::removePreviewImages($tempfiles); // remove any preview images
            }
            LogUtil::registerStatus($this->_fn('%1$s out of %2$s picture was uploaded and resized.', '%1$s out of %2$s pictures were uploaded and resized.', $item['pictures'], array($resized, $item['pictures'])));
            if (($item['action'] >= self::ACTION_SAVEDRAFT) && ($resized <> $item['pictures'])) {
                LogUtil::registerStatus($this->_fn('Article now has draft status, since the picture was not uploaded.', 'Article now has draft status, since not all pictures were uploaded.', $item['pictures'], array($resized, $item['pictures'])));
            }
        }

        // release pagelock
        if (ModUtil::available('PageLock')) {
            ModUtil::apiFunc('PageLock', 'user', 'releaseLock', array('lockName' => "Newsnews{$item['sid']}"));
        }

        if ($item['action'] == self::ACTION_SAVEDRAFT_RETURN) {
            SessionUtil::setVar('newsitem', $item);
            $this->redirect(ModUtil::url('News', 'user', 'newitem'));
        }
        $this->redirect(ModUtil::url('News', 'user', 'view'));
    }
Exemplo n.º 29
0
//
$userdata = session_pagestart($user_ip, PAGE_INDEX);
init_userprefs($userdata);
//
// End session management
//
// Begin PNphpBB2 Module - Minimize/Maximize Mod
if (isset($_GET['minmax']) || isset($_POST['minmax']) && $board_config['pnphpbb2_allow_full_page'] == 1) {
    $fullpage = intval(isset($_POST['minmax']) ? $_POST['minmax'] : $_GET['minmax']);
    SessionUtil::setVar('fullpage', $fullpage == 1 ? 1 : 0);
}
// End PNphpBB2 Module - Minimize/Maximize Mod
// Begin PNphpBB2 Module - Sub-Category/forum switch mod
if (isset($_GET['subforum']) || isset($_POST['subforum']) && $board_config['pnphpbb2_allow_sub_change'] == 1) {
    $subforum = isset($_POST['subforum']) ? $_POST['subforum'] : $_GET['subforum'];
    SessionUtil::setVar('subforum', $subforum);
}
// End PNphpBB2 Module - Sub-Category/forum switch mod
$viewcat = !empty($_GET[POST_CAT_URL]) && is_numeric($_GET[POST_CAT_URL]) ? $_GET[POST_CAT_URL] : -1;
if (isset($_GET['mark']) || isset($_POST['mark'])) {
    $mark_read = isset($_POST['mark']) ? $_POST['mark'] : $_GET['mark'];
} else {
    $mark_read = '';
}
//
// Handle marking posts
//
if ($mark_read == 'forums') {
    // Begin PNphpBB2 Categories Hierarchie Mod
    if ($viewcat < 0) {
        // End PNphpBB2 Categories Hierarchie Mod
Exemplo n.º 30
0
 /**
  * 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;
 }