コード例 #1
0
 /**
  * Post constructor hook.
  *
  * @return void
  */
 public function setup()
 {
     $this->view = \Zikula_View::getInstance(self::MODULENAME, false);
     // set caching off
     $this->_em = \ServiceUtil::get('doctrine.entitymanager');
     $this->domain = \ZLanguage::getModuleDomain(self::MODULENAME);
 }
コード例 #2
0
/**
 * render plugin for fetching a particular module object
 *
 * Examples
 *   {selectmodobject module="AutoCustomer" objecttype="customer" id=4 assign="myCustomer"}
 *   {selectmodobject module="AutoCocktails" objecttype="recipe" id=12 assign="myRecipe"}
 *   {selectmodobject recordClass="AutoCocktails_Model_Recipe" id=12 assign="myRecipe"}
 *
 * Parameters:
 *  module      Name of the module storing the desired object (in DBObject mode)
 *  objecttype  Name of object type (in DBObject mode)
 *  recordClass Class name of an doctrine record. (in Doctrine mode)
 *  id          Identifier of desired object
 *  prefix      Optional prefix for class names (defaults to PN) (in DBObject mode)
 *  assign      Name of the returned object
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return void
 */
function smarty_function_selectmodobject($params, Zikula_View $view)
{
    if (isset($params['recordClass']) && !empty($params['recordClass'])) {
        $doctrineMode = true;
    } else {
        // DBObject checks
        if (!isset($params['module']) || empty($params['module'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'module')));
        }
        if (!isset($params['objecttype']) || empty($params['objecttype'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'objecttype')));
        }
        if (!isset($params['prefix'])) {
            $params['prefix'] = 'PN';
        }
        $doctrineMode = false;
    }
    if (!isset($params['id']) || empty($params['id']) || !is_numeric($params['id'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'id')));
    }
    if (!isset($params['assign']) || empty($params['assign'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'assign')));
    }
    // load object depending on mode: doctrine or dbobject
    if (!$doctrineMode) {
        if (!ModUtil::available($params['module'])) {
            $view->trigger_error(__f('Invalid %1$s passed to %2$s.', array('module', 'selectmodobject')));
        }
        ModUtil::dbInfoLoad($params['module']);
        $class = "{$params['module']}_DBObject_" . StringUtil::camelize($params['objecttype']);
        // intantiate object model
        $object = new $class();
        $idField = $object->getIDField();
        // assign object data
        // this performs a new database select operation
        // while the result will be saved within the object, we assign it to a local variable for convenience
        $objectData = $object->get(intval($params['id']), $idField);
        if (!is_array($objectData) || !isset($objectData[$idField]) || !is_numeric($objectData[$idField])) {
            $view->trigger_error(__('Sorry! No such item found.'));
        }
    } else {
        if ($params['recordClass'] instanceof \Doctrine_Record) {
            $objectData = Doctrine_Core::getTable($params['recordClass'])->find($params['id']);
            if ($objectData === false) {
                $view->trigger_error(__('Sorry! No such item found.'));
            }
        } else {
            /** @var $em Doctrine\ORM\EntityManager */
            $em = \ServiceUtil::get('doctrine.entitymanager');
            $result = $em->getRepository($params['recordClass'])->find($params['id']);
            $objectData = $result->toArray();
        }
    }
    $view->assign($params['assign'], $objectData);
}
コード例 #3
0
ファイル: MigrationUtil.php プロジェクト: rmaiwald/core
 public static function loadModuleAnnotations($entityNamespace, $path)
 {
     /** @var $em EntityManager */
     $em = ServiceUtil::get('doctrine.orm.entity_manager');
     /** @var $ORMConfig Configuration */
     $ORMConfig = $em->getConfiguration();
     $annotationDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver(ServiceUtil::get('annotation_reader'), array($path));
     $chain = $ORMConfig->getMetadataDriverImpl();
     // driver chain
     $chain->addDriver($annotationDriver, $entityNamespace);
 }
コード例 #4
0
ファイル: CacheUtil.php プロジェクト: Silwereth/core
 /**
  * Get the location of the local cache directory.
  *
  * @param string $dir The name of the directory to get.
  *
  * @return string Location of the cache directory.
  */
 public static function getLocalDir($dir = null)
 {
     $array = array();
     $tmpDir = ServiceUtil::get('service_container')->getParameter('temp_dir');
     $array[] = DataUtil::formatForOS($tmpDir, true);
     if (!is_null($dir)) {
         $array[] = DataUtil::formatForOS($dir);
     }
     $path = implode('/', $array);
     return $path;
 }
コード例 #5
0
ファイル: CookieUtil.php プロジェクト: Silwereth/core
 /**
  * Get a cookie.
  *
  * @param string  $name    Name of cookie.
  * @param boolean $signed  Override system setting to use signatures.
  * @param boolean $default Default value.
  *
  * @return mixed Cookie value as string or bool false.
  */
 public static function getCookie($name, $signed = true, $default = '')
 {
     $request = \ServiceUtil::get('request');
     if (!$request->cookies->has($name)) {
         return $default;
     }
     $cookie = $request->cookies->get($name);
     if (System::getVar('signcookies') && !$signed == false) {
         return SecurityUtil::checkSignedData($cookie);
     }
     return $cookie;
 }
コード例 #6
0
 protected function getService($name)
 {
     if ($name == 'doctrine.entitymanager') {
         return \ServiceUtil::get($name);
     } else {
         if ($name == 'doctrine.connection') {
             return \ServiceUtil::get('doctrine.entitymanager')->getConnection();
         } else {
             return null;
         }
     }
 }
コード例 #7
0
ファイル: RouteUrl.php プロジェクト: rmaiwald/core
 public function getUrl($ssl = null, $fqUrl = null)
 {
     $router = \ServiceUtil::get('router');
     $fqUrl = is_bool($fqUrl) && $fqUrl ? RouterInterface::ABSOLUTE_URL : RouterInterface::ABSOLUTE_PATH;
     $fragment = !empty($this->fragment) ? '#' . $this->fragment : '';
     $oldScheme = $router->getContext()->getScheme();
     if ($ssl) {
         $router->getContext()->setScheme('https');
     }
     $url = $router->generate($this->route, $this->args, $fqUrl) . $fragment;
     if ($ssl) {
         $router->getContext()->setScheme($oldScheme);
     }
     return $url;
 }
コード例 #8
0
ファイル: JCSSUtil.php プロジェクト: Silwereth/core
 /**
  * Generate a configuration for javascript and return script tag to embed in HTML HEAD.
  *
  * @return string HTML code with script tag
  */
 public static function getJSConfig()
 {
     $return = '';
     $config = array('entrypoint' => System::getVar('entrypoint', 'index.php'), 'baseURL' => System::getBaseUrl(), 'baseURI' => System::getBaseUri() . '/', 'ajaxtimeout' => (int) System::getVar('ajaxtimeout', 5000), 'lang' => ZLanguage::getLanguageCode(), 'sessionName' => session_name(), 'uid' => (int) UserUtil::getVar('uid'));
     $polyfill_features = PageUtil::getVar('polyfill_features');
     // merge in features added via twig
     $featuresFromTwig = ServiceUtil::get('zikula_core.common.theme.pagevars')->get('polyfill_features', []);
     $polyfill_features = array_unique(array_merge($polyfill_features, $featuresFromTwig));
     if (!empty($polyfill_features)) {
         $config['polyfillFeatures'] = implode(' ', $polyfill_features);
     }
     $config = DataUtil::formatForDisplay($config);
     $return .= "<script type=\"text/javascript\">/* <![CDATA[ */ \n";
     if (System::isLegacyMode()) {
         $return .= 'document.location.entrypoint="' . $config['entrypoint'] . '";';
         $return .= 'document.location.pnbaseURL="' . $config['baseURL'] . '"; ';
         $return .= 'document.location.ajaxtimeout=' . $config['ajaxtimeout'] . ";\n";
     }
     $return .= "if (typeof(Zikula) == 'undefined') {var Zikula = {};}\n";
     $return .= "Zikula.Config = " . json_encode($config) . "\n";
     $return .= ' /* ]]> */</script>' . "\n";
     return $return;
 }
コード例 #9
0
ファイル: LogUtil.php プロジェクト: Silwereth/core
 /**
  * Register a failed permission check.
  *
  * This method calls registerError and then logs the failed permission check so that it can be analyzed later.
  *
  * @param string  $url      The URL to redirect to (optional) (default=null).
  * @param boolean $redirect Whether to redirect not logged in users to the login form (default=true).
  *
  * @return false
  */
 public static function registerPermissionError($url = null, $redirect = true)
 {
     $code = 403;
     if (!UserUtil::isLoggedIn() && $redirect) {
         if (is_null($url)) {
             $request = ServiceUtil::get('request');
             $loginArgs = array();
             if ($request->isMethod('GET')) {
                 $loginArgs['returnpage'] = urlencode(System::getCurrentUri());
             }
             $url = ModUtil::url('ZikulaUsersModule', 'user', 'login', $loginArgs);
         }
         $code = null;
     }
     return self::registerError(self::getErrorMsgPermission(), $code, $url);
 }
コード例 #10
0
ファイル: BlockUtil.php プロジェクト: Silwereth/core
 /**
  * Show a block.
  *
  * @param string $modname Module name.
  * @param string $blockname Name of the block.
  * @param array $blockinfo Information parameters.
  * @param null $blockEntity
  * @return mixed Blockinfo array or null.
  */
 public static function show($modname, $blockname, $blockinfo = array(), $blockEntity = null)
 {
     global $blocks_modules;
     $content = '';
     $blockInstance = self::load($modname, $blockname);
     $displayfunc = array($blockInstance, 'display');
     $blockEntity = isset($blockEntity) ? $blockEntity : ServiceUtil::get('doctrine.entitymanager')->find('Zikula\\BlocksModule\\Entity\\BlockEntity', $blockinfo['bid']);
     $instanceArgs = $blockInstance instanceof AbstractBlockController ? $blockEntity->getContent() : $blockinfo;
     if (is_callable($displayfunc)) {
         $content = call_user_func($displayfunc, $instanceArgs);
     }
     if ($blockInstance instanceof AbstractBlockController) {
         // FC blocks require wrapping the content in the theme
         $blockinfo['content'] = $content;
         $content = Zikula_View_Theme::getInstance()->themesidebox($blockinfo);
     }
     return $content;
 }
コード例 #11
0
ファイル: HtmlUtil.php プロジェクト: Silwereth/core
 /**
  * Creates an Entity array selector.
  *
  * @param string  $modname        Module name.
  * @param string  $entity         Doctrine 2 entity classname.
  * @param string  $name           Select field name.
  * @param string  $field          Value field.
  * @param string  $displayField   Display field.
  * @param string  $where          Where clause.
  * @param string  $sort           Sort clause.
  * @param string  $selectedValue  Selected value.
  * @param string  $defaultValue   Value for "default" option.
  * @param string  $defaultText    Text for "default" option.
  * @param string  $allValue       Value for "all" option.
  * @param string  $allText        Text for "all" option.
  * @param string  $displayField2  Second display field.
  * @param boolean $submit         Submit on choose.
  * @param boolean $disabled       Add Disabled attribute to select.
  * @param string  $fieldSeparator Field seperator if $displayField2 is given.
  * @param integer $multipleSize   Size for multiple selects.
  *
  * @return string The rendered output.
  */
 public static function getSelector_EntityArray($modname, $entity, $name, $field = '', $displayField = 'name', $where = '', $sort = '', $selectedValue = '', $defaultValue = 0, $defaultText = '', $allValue = 0, $allText = '', $displayField2 = null, $submit = true, $disabled = false, $fieldSeparator = ', ', $multipleSize = 1)
 {
     if (!$modname) {
         throw new \Exception(__f('Invalid %1$s passed to %2$s.', array('modname', 'HtmlUtil::getSelector_EntityArray')));
     }
     if (!$entity || !class_exists($entity)) {
         throw new \Exception(__f('Invalid %1$s passed to %2$s.', array('entity', 'HtmlUtil::getSelector_EntityArray')));
     }
     if (!SecurityUtil::checkPermission("{$entity}::", '::', ACCESS_OVERVIEW)) {
         return __f('Security check failed for %1$s [%2$s] passed to %3$s.', array('modulename', $modname, 'HtmlUtil::getSelector_EntityArray'));
     }
     /** @var $em \Doctrine\ORM\EntityManager */
     $em = ServiceUtil::get('doctrine.entitymanager');
     $qb = $em->createQueryBuilder();
     $qb->select('e')->from($entity, 'e');
     $dataArray = $qb->getQuery()->getResult();
     // array of Entities
     // @todo does not accommodate $sort or $where
     $data2 = array();
     foreach ($dataArray as $object) {
         $val = $object[$field];
         // relies on entityAccess
         $disp = $object[$displayField];
         if ($displayField2) {
             $disp .= $fieldSeparator . $object[$displayField2];
         }
         $data2[$val] = $disp;
     }
     return self::getSelector_Generic($name, $data2, $selectedValue, $defaultValue, $defaultText, $allValue, $allText, $submit, $disabled, $multipleSize);
 }
コード例 #12
0
 /**
  * Get the IDs of the property registers.
  *
  * @param string $modname       The module name.
  * @param string $entityname    The entity name for which we wish to get the property for.
  *
  * @return array The associative field array of register ids for the specified module.
  */
 public static function getRegisteredModuleCategoriesIds($modname, $entityname)
 {
     if (!$modname || !$entityname) {
         return z_exit(__f("Error! Received invalid specifications %1{$s}, %2{$s}.", array($modname, $entityname)));
     }
     $em = \ServiceUtil::get('doctrine')->getManager();
     $rCategories = $em->getRepository('Zikula\\Core\\Doctrine\\Entity\\CategoryRegistry')->findBy(array('modname' => $modname, 'entityname' => $entityname));
     $fArr = array();
     foreach ($rCategories as $rCategory) {
         $fArr[$rCategory['property']] = $rCategory['id'];
     }
     return $fArr;
 }
コード例 #13
0
ファイル: View.php プロジェクト: Silwereth/core
 /**
  * Constructor.
  *
  * @param Zikula_ServiceManager $serviceManager ServiceManager.
  * @param string                $moduleName     Module name ("zikula" for system plugins).
  * @param integer|null          $caching        Whether or not to cache (Zikula_View::CACHE_*) or use config variable (null).
  */
 public function __construct(Zikula_ServiceManager $serviceManager, $moduleName = '', $caching = null)
 {
     $this->serviceManager = $serviceManager;
     $this->eventManager = $this->serviceManager->get('event_dispatcher');
     $this->request = \ServiceUtil::get('request');
     // set the error reporting level
     $this->error_reporting = isset($GLOBALS['ZConfig']['Debug']['error_reporting']) ? $GLOBALS['ZConfig']['Debug']['error_reporting'] : E_ALL;
     $this->error_reporting &= ~E_USER_DEPRECATED;
     $this->allow_php_tag = true;
     // get variables from input
     $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $type = FormUtil::getPassedValue('type', 'user', 'GETPOST', FILTER_SANITIZE_STRING);
     $func = FormUtil::getPassedValue('func', 'main', 'GETPOST', FILTER_SANITIZE_STRING);
     // set vars based on the module structures
     $this->homepage = PageUtil::isHomepage();
     $this->type = strtolower(!$this->homepage ? $type : System::getVar('starttype'));
     $this->func = strtolower(!$this->homepage ? $func : System::getVar('startfunc'));
     // Initialize the module property with the name of
     // the topmost module. For Hooks, Blocks, API Functions and others
     // you need to set this property to the name of the respective module!
     $this->toplevelmodule = ModUtil::getName();
     if (!$moduleName) {
         $moduleName = $this->toplevelmodule;
     }
     $this->modinfo = ModUtil::getInfoFromName($moduleName);
     $this->module = array($moduleName => $this->modinfo);
     // initialise environment vars
     $this->language = ZLanguage::getLanguageCode();
     $this->baseurl = System::getBaseUrl();
     $this->baseuri = System::getBaseUri();
     // system info
     $this->themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName(UserUtil::getTheme()));
     $this->theme = $theme = $this->themeinfo['directory'];
     $themeBundle = ThemeUtil::getTheme($this->themeinfo['name']);
     //---- Plugins handling -----------------------------------------------
     // add plugin paths
     switch ($this->modinfo['type']) {
         case ModUtil::TYPE_MODULE:
             $mpluginPathNew = "modules/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             $mpluginPath = "modules/" . $this->modinfo['directory'] . "/templates/plugins";
             break;
         case ModUtil::TYPE_SYSTEM:
             $mpluginPathNew = "system/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/templates/plugins";
             break;
         default:
             $mpluginPathNew = "system/" . $this->modinfo['directory'] . "/Resources/views/plugins";
             $mpluginPath = "system/" . $this->modinfo['directory'] . "/templates/plugins";
     }
     // add standard plugin search path
     $this->plugins_dir = array();
     $this->addPluginDir('config/plugins');
     // Official override
     $this->addPluginDir('lib/legacy/viewplugins');
     // Core plugins
     $this->addPluginDir(isset($themeBundle) ? $themeBundle->getRelativePath() . '/plugins' : "themes/{$theme}/plugins");
     // Theme plugins
     $this->addPluginDir('plugins');
     // Smarty core plugins
     $this->addPluginDir($mpluginPathNew);
     // Plugins for current module
     $this->addPluginDir($mpluginPath);
     // Plugins for current module
     // check if the 'type' parameter in the URL is admin or adminplugin
     $legacyControllerType = FormUtil::getPassedValue('lct', 'user', 'GETPOST', FILTER_SANITIZE_STRING);
     if ($type === 'admin' || $type === 'adminplugin' || $legacyControllerType === 'admin') {
         // include plugins of the Admin module to the plugins_dir array
         if (!$this instanceof Zikula_View_Theme) {
             $this->addPluginDir('system/AdminModule/Resources/views/plugins');
         } else {
             $this->load_filter('output', 'admintitle');
         }
     }
     // theme plugins module overrides
     $themePluginsPath = isset($themeBundle) ? $themeBundle->getRelativePath() . '/modules/$moduleName/plugins' : "themes/{$theme}/templates/modules/{$moduleName}/plugins";
     $this->addPluginDir($themePluginsPath);
     //---- Cache handling -------------------------------------------------
     if ($caching && in_array((int) $caching, array(0, 1, 2))) {
         $this->caching = (int) $caching;
     } else {
         $this->caching = (int) ModUtil::getVar('ZikulaThemeModule', 'render_cache');
     }
     $this->compile_id = '';
     $this->cache_id = '';
     // template compilation
     $this->compile_dir = CacheUtil::getLocalDir('view_compiled');
     $this->compile_check = ModUtil::getVar('ZikulaThemeModule', 'render_compile_check');
     $this->force_compile = ModUtil::getVar('ZikulaThemeModule', 'render_force_compile');
     // template caching
     $this->cache_dir = CacheUtil::getLocalDir('view_cache');
     $this->cache_lifetime = ModUtil::getVar('ZikulaThemeModule', 'render_lifetime');
     $this->expose_template = ModUtil::getVar('ZikulaThemeModule', 'render_expose_template') == true ? true : false;
     // register resource type 'z' this defines the way templates are searched
     // during {include file='my_template.tpl'} this enables us to store selected module
     // templates in the theme while others can be kept in the module itself.
     $this->register_resource('z', array('Zikula_View_Resource', 'z_get_template', 'z_get_timestamp', 'z_get_secure', 'z_get_trusted'));
     // set 'z' as default resource type
     $this->default_resource_type = 'z';
     // process some plugins specially when Render cache is enabled
     if (!$this instanceof Zikula_View_Theme && $this->caching) {
         $this->register_nocache_plugins();
     }
     // register the 'nocache' block to allow dynamic zones caching templates
     $this->register_block('nocache', array('Zikula_View_Resource', 'block_nocache'), false);
     // For ajax requests we use the short urls filter to 'fix' relative paths
     if ($this->serviceManager->get('zikula')->getStage() & Zikula_Core::STAGE_AJAX && System::getVar('shorturls')) {
         $this->load_filter('output', 'shorturls');
     }
     // register prefilters
     $this->register_prefilter('z_prefilter_add_literal');
     $this->register_prefilter('z_prefilter_gettext_params');
     //$this->register_prefilter('z_prefilter_notifyfilters');
     // assign some useful settings
     $this->assign('homepage', $this->homepage)->assign('modinfo', $this->modinfo)->assign('module', $moduleName)->assign('toplevelmodule', $this->toplevelmodule)->assign('type', $this->type)->assign('func', $this->func)->assign('lang', $this->language)->assign('themeinfo', $this->themeinfo)->assign('themepath', isset($themeBundle) ? $themeBundle->getRelativePath() : $this->baseurl . 'themes/' . $theme)->assign('baseurl', $this->baseurl)->assign('baseuri', $this->baseuri)->assign('moduleBundle', ModUtil::getModule($moduleName))->assign('themeBundle', $themeBundle);
     if (isset($themeBundle)) {
         $stylePath = $themeBundle->getRelativePath() . "/Resources/public/css";
         $javascriptPath = $themeBundle->getRelativePath() . "/Resources/public/js";
         $imagePath = $themeBundle->getRelativePath() . "/Resources/public/images";
         $imageLangPath = $themeBundle->getRelativePath() . "/Resources/public/images/" . $this->language;
     } else {
         $stylePath = $this->baseurl . "themes/{$theme}/style";
         $javascriptPath = $this->baseurl . "themes/{$theme}/javascript";
         $imagePath = $this->baseurl . "themes/{$theme}/images";
         $imageLangPath = $this->baseurl . "themes/{$theme}/images/" . $this->language;
     }
     $this->assign('stylepath', $stylePath)->assign('scriptpath', $javascriptPath)->assign('imagepath', $imagePath)->assign('imagelangpath', $imageLangPath);
     // for {gt} template plugin to detect gettext domain
     if ($this->modinfo['type'] == ModUtil::TYPE_MODULE) {
         $this->domain = ZLanguage::getModuleDomain($this->modinfo['name']);
     }
     // make render object available to modifiers
     parent::assign('zikula_view', $this);
     // add ServiceManager, EventManager and others to all templates
     parent::assign('serviceManager', $this->serviceManager);
     parent::assign('eventManager', $this->eventManager);
     parent::assign('zikula_core', $this->serviceManager->get('zikula'));
     parent::assign('request', $this->request);
     $modvars = ModUtil::getModvars();
     // Get all modvars from any modules that have accessed their modvars at least once.
     // provide compatibility 'alias' array keys
     // @todo remove after v1.4.0
     if (isset($modvars['ZikulaAdminModule'])) {
         $modvars['Admin'] = $modvars['ZikulaAdminModule'];
     }
     if (isset($modvars['ZikulaBlocksModule'])) {
         $modvars['Blocks'] = $modvars['ZikulaBlocksModule'];
     }
     if (isset($modvars['ZikulaCategoriesModule'])) {
         $modvars['Categories'] = $modvars['ZikulaCategoriesModule'];
     }
     if (isset($modvars['ZikulaExtensionsModule'])) {
         $modvars['Extensions'] = $modvars['ZikulaExtensionsModule'];
     }
     if (isset($modvars['ZikulaGroupsModule'])) {
         $modvars['Groups'] = $modvars['ZikulaGroupsModule'];
     }
     if (isset($modvars['ZikulaMailerModule'])) {
         $modvars['Mailer'] = $modvars['ZikulaMailerModule'];
     }
     if (isset($modvars['ZikulaPageLockModule'])) {
         $modvars['PageLock'] = $modvars['ZikulaPageLockModule'];
     }
     if (isset($modvars['ZikulaPermissionsModule'])) {
         $modvars['Permissions'] = $modvars['ZikulaPermissionsModule'];
     }
     if (isset($modvars['ZikulaSearchModule'])) {
         $modvars['Search'] = $modvars['ZikulaSearchModule'];
     }
     if (isset($modvars['ZikulaSecurityCenterModule'])) {
         $modvars['SecurityCenter'] = $modvars['ZikulaSecurityCenterModule'];
     }
     if (isset($modvars['ZikulaSettingsModule'])) {
         $modvars['Settings'] = $modvars['ZikulaSettingsModule'];
     }
     if (isset($modvars['ZikulaThemeModule'])) {
         $modvars['Theme'] = $modvars['ZikulaThemeModule'];
     }
     if (isset($modvars['ZikulaUsersModule'])) {
         $modvars['Users'] = $modvars['ZikulaUsersModule'];
     }
     // end compatibility aliases
     parent::assign('modvars', $modvars);
     $this->add_core_data();
     // metadata for SEO
     if (!$this->serviceManager->hasParameter('zikula_view.metatags')) {
         $this->serviceManager->setParameter('zikula_view.metatags', new ArrayObject(array()));
     }
     parent::assign('metatags', $this->serviceManager->getParameter('zikula_view.metatags'));
     if (isset($themeBundle) && $themeBundle->isTwigBased()) {
         // correct asset urls when smarty output is wrapped by twig theme
         $this->load_filter('output', 'asseturls');
     }
     $event = new \Zikula\Core\Event\GenericEvent($this);
     $this->eventManager->dispatch('view.init', $event);
 }
コード例 #14
0
ファイル: ModUtil.php プロジェクト: rtznprmpftl/Zikulacore
 /**
  * The delVar method deletes a module variable.
  *
  * Delete a module variables. If the optional name parameter is not supplied all variables
  * for the module 'modname' are deleted.
  *
  * @param string $modname The name of the module.
  * @param string $name    The name of the variable (optional).
  *
  * @return boolean True if successful, false otherwise.
  */
 public static function delVar($modname, $name = '')
 {
     // define input, all numbers and booleans to strings
     if ('ZConfig' !== $modname) {
         $modname = preg_match('/\\w+Module$/', $modname) || !$modname ? $modname : $modname . 'Module';
     }
     $modname = isset($modname) ? (string) $modname : '';
     // validate
     if (!System::varValidate($modname, 'modvar')) {
         return false;
     }
     $val = null;
     if (!isset(self::$modvars[$modname])) {
         return $val;
     }
     if (empty($name)) {
         if (array_key_exists($modname, self::$modvars)) {
             unset(self::$modvars[$modname]);
         }
     } else {
         if (array_key_exists($name, self::$modvars[$modname])) {
             $val = self::$modvars[$modname][$name];
             // we're dealing with an ArrayObject, so we cannot unset() deep keys.
             $array = self::$modvars[$modname];
             unset($array[$name]);
             self::$modvars[$modname] = $array;
         }
     }
     $em = ServiceUtil::get('doctrine')->getEntityManager();
     // if $name is not provided, delete all variables of this module
     // else just delete this specific variable
     if (empty($name)) {
         $dql = "DELETE FROM Zikula\\Core\\Doctrine\\Entity\\ExtensionVar v WHERE v.modname = '{$modname}'";
     } else {
         $dql = "DELETE FROM Zikula\\Core\\Doctrine\\Entity\\ExtensionVar v WHERE v.modname = '{$modname}' AND v.name = '{$name}'";
     }
     $query = $em->createQuery($dql);
     $result = $query->getResult();
     return (bool) $result;
 }
コード例 #15
0
ファイル: System.php プロジェクト: Silwereth/core
 /**
  * Decode the path string into a set of variable/value pairs.
  *
  * This API works in conjunction with the new short urls
  * system to extract a path based variable set into the Get, Post
  * and request superglobals.
  * A sample path is /modname/function/var1:value1.
  *
  * @return void
  */
 public static function queryStringDecode(Request $request)
 {
     if (self::isInstalling()) {
         return;
     }
     // Try to match a route first.
     // Make sure we have the correct request context.
     $requestContext = ServiceUtil::get('router.request_context');
     $requestContext->fromRequest($request);
     /** @var \Symfony\Component\Routing\Matcher\RequestMatcherInterface $router */
     $router = ServiceUtil::get('router');
     try {
         $parameters = $router->matchRequest($request);
         if (!isset($parameters['_zkModule']) || !isset($parameters['_zkType']) || !isset($parameters['_zkFunc'])) {
             // This might be the web profiler or another native bundle.
             return;
         }
         // The following block is needed as long as not every url is a route. To be removed when all legacy routing
         // is removed.
         if ($parameters['_route'] == 'zikularoutesmodule_redirectingcontroller_removetrailingslash') {
             $pathInfo = $request->getPathInfo();
             $requestUri = $request->getRequestUri();
             // Check if url without slash exists. If it doesn't exist, it will throw an exception which is caught
             // by the try->catch below.
             $url = str_replace($pathInfo, rtrim($pathInfo, ' /'), $requestUri);
             $router->match($url);
         }
         $modname = strtolower($parameters['_zkModule']);
         $type = strtolower($parameters['_zkType']);
         $func = strtolower($parameters['_zkFunc']);
         if (isset($parameters['_locale'])) {
             $lang = strtolower($parameters['_locale']);
             $request->query->set('lang', $lang);
             self::queryStringSetVar('lang', $lang);
         }
         $request->attributes->set('_zkModule', $modname);
         $request->attributes->set('_zkType', $type);
         $request->attributes->set('_zkFunc', $func);
         $request->query->set('module', $modname);
         $request->query->set('type', $type);
         $request->query->set('func', $func);
         self::queryStringSetVar('module', $modname);
         self::queryStringSetVar('type', $type);
         self::queryStringSetVar('func', $func);
         return;
     } catch (ResourceNotFoundException $e) {
         // This is an old style url.
     } catch (RouteNotFoundException $e) {
         // This is an old style url.
     } catch (MethodNotAllowedException $e) {
         // this is an old style url.
     }
     // get our base parameters to work out if we need to decode the url
     $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $func = FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING);
     $type = FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING);
     // check if we need to decode the url
     $shorturls = self::getVar('shorturls');
     if ($shorturls && empty($module) && empty($type) && empty($func)) {
         // user language is not set at this stage
         $lang = self::getVar('language_i18n', '');
         $customentrypoint = self::getVar('entrypoint');
         $expectEntrypoint = !self::getVar('shorturlsstripentrypoint');
         $root = empty($customentrypoint) ? 'index.php' : $customentrypoint;
         // check if we hit baseurl, e.g. domain.com/ and if we require the language URL
         // then we should redirect to the language URL.
         if (ZLanguage::isRequiredLangParam() && self::getCurrentUrl() == self::getBaseUrl()) {
             $uri = $expectEntrypoint ? "{$root}/{$lang}" : $lang;
             self::redirect(self::getBaseUrl() . $uri);
             self::shutDown();
         }
         // check if entry point is part of the URL expectation.  If so throw error if it's not present
         // since this URL is technically invalid.
         if ($expectEntrypoint && self::getCurrentUrl() != self::getBaseUrl() && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) !== 0) {
             $protocol = self::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             self::shutDown();
         }
         if (!$expectEntrypoint && self::getCurrentUrl() == self::getBaseUrl() . $root) {
             self::redirect(self::getHomepageUrl(), array(), 302, true);
             self::shutDown();
         }
         if (!$expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) === 0) {
             $protocol = self::serverGetVar('SERVER_PROTOCOL');
             header("{$protocol} 404 Not Found");
             echo __('The requested URL cannot be found');
             self::shutDown();
         }
         // get base path to work out our current url
         $parsedURL = parse_url(self::getCurrentUri());
         // strip any unwanted content from the provided URL
         $tobestripped = array(self::getBaseUri(), "{$root}");
         $path = str_replace($tobestripped, '', $parsedURL['path']);
         $path = trim($path, '/');
         // split the path into a set of argument strings
         $args = explode('/', rtrim($path, '/'));
         // ensure that each argument is properly decoded
         foreach ($args as $k => $v) {
             $args[$k] = urldecode($v);
         }
         $modinfo = null;
         $frontController = $expectEntrypoint ? "{$root}/" : '';
         // if no arguments present
         if (!$args[0] && !isset($_GET['lang']) && !isset($_GET['theme'])) {
             // we are in the homepage, checks if language code is forced
             if (ZLanguage::getLangUrlRule() && $lang) {
                 // and redirect then
                 self::redirect(self::getCurrentUrl() . "/{$lang}", array(), 302, true);
                 self::shutDown();
             }
         } else {
             // check the existing shortURL parameters
             // validation of the first parameter as language code
             if (ZLanguage::isLangParam($args[0]) && in_array($args[0], ZLanguage::getInstalledLanguages())) {
                 // checks if the language is not enforced and this url is passing the default lang
                 if (!ZLanguage::getLangUrlRule() && $lang == $args[0]) {
                     // redirects the passed arguments without the default site language
                     array_shift($args);
                     foreach ($args as $k => $v) {
                         $args[$k] = urlencode($v);
                     }
                     self::redirect(self::getBaseUrl() . $frontController . ($args ? implode('/', $args) : ''), array(), 302, true);
                     self::shutDown();
                 }
                 self::queryStringSetVar('lang', $args[0], $request);
                 array_shift($args);
             } elseif (ZLanguage::getLangUrlRule()) {
                 // if the lang is forced, redirects the passed arguments plus the lang
                 foreach ($args as $k => $v) {
                     $args[$k] = urlencode($v);
                 }
                 $langTheme = isset($_GET['theme']) ? "{$lang}/{$_GET['theme']}" : $lang;
                 self::redirect(self::getBaseUrl() . $frontController . $langTheme . '/' . implode('/', $args), array(), 302, true);
                 self::shutDown();
             }
             // check if there are remaining arguments
             if ($args) {
                 // try the first argument as a module
                 $modinfo = ModUtil::getInfoFromName($args[0]);
                 if ($modinfo) {
                     array_shift($args);
                 }
             }
             // if that fails maybe it's a theme
             if ($args && !$modinfo) {
                 $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($args[0]));
                 if ($themeinfo) {
                     self::queryStringSetVar('theme', $themeinfo['name'], $request);
                     $request->attributes->set('_theme', $themeinfo['name']);
                     // now shift the vars and continue as before
                     array_shift($args);
                     if ($args) {
                         $modinfo = ModUtil::getInfoFromName($args[0]);
                         if ($modinfo) {
                             array_shift($args);
                         }
                     }
                 }
             }
             // if there are parameters (not homepage)
             // try to see if there's a default shortURLs module
             if ($args && !$modinfo) {
                 // add the default module handler into the code
                 $modinfo = ModUtil::getInfoFromName(self::getVar('shorturlsdefaultmodule'));
             }
         }
         // check if there is a module and a custom url handler for it
         // if not decode the url using the default handler
         if ($modinfo && $modinfo['type'] != 0) {
             // prepare the arguments to the module handler
             array_unshift($args, '');
             // support for 1.2- empty parameter due the initial explode
             array_unshift($args, $modinfo['url']);
             // set the REQUEST parameters
             self::queryStringSetVar('module', $modinfo['name'], $request);
             // the user.function name can be the second argument string, set a default
             // later the custom module handler (if exists) must setup a new one if needed
             self::queryStringSetVar('type', 'user', $request);
             if (isset($args[2])) {
                 self::queryStringSetVar('func', $args[2], $request);
             } else {
                 self::queryStringSetVar('func', 'main', $request);
             }
             if (!ModUtil::apiFunc($modinfo['name'], 'user', 'decodeurl', array('vars' => $args))) {
                 // any remaining arguments are specific to the module
                 $argscount = count($args);
                 for ($i = 3; $i < $argscount; $i = $i + 2) {
                     if (isset($args[$i]) && isset($args[$i + 1])) {
                         self::queryStringSetVar($args[$i], urldecode($args[$i + 1]), $request);
                     }
                 }
             }
         }
     }
     $module = ucfirst(FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING));
     $func = ucfirst(FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING));
     $type = ucfirst(FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING));
     $arguments = array();
     if (!$module) {
         // set the start parameters
         $module = self::getVar('startpage');
         $type = self::getVar('starttype');
         $func = self::getVar('startfunc');
         $args = explode(',', self::getVar('startargs'));
         foreach ($args as $arg) {
             if (!empty($arg)) {
                 $argument = explode('=', $arg);
                 $arguments[$argument[0]] = $argument[1];
             }
         }
     } else {
         $arguments = $_GET;
         unset($arguments['module']);
         unset($arguments['type']);
         unset($arguments['func']);
     }
     if ($shorturls) {
         $request->query->replace($_GET);
     }
     $request->attributes->set('_zkModule', strtolower($module));
     // legacy - this is how they are received originally
     $request->attributes->set('_zkType', strtolower($type));
     // legacy - this is how they are received originally
     $request->attributes->set('_zkFunc', strtolower($func));
     // legacy - this is how they are received originally
     $request->attributes->set('_zkArgs', $arguments);
 }
コード例 #16
0
ファイル: HtmlUtil.php プロジェクト: rtznprmpftl/Zikulacore
 /**
  * Creates an entity array selector.
  *
  * @param string  $entity         Entity name.
  * @param string  $name           Select field name.
  * @param string  $field          Value field.
  * @param string  $displayField   Display field.
  * @param string  $where          Where clause.
  * @param string  $sort           Sort clause.
  * @param string  $selectedValue  Selected value.
  * @param string  $defaultValue   Value for "default" option.
  * @param string  $defaultText    Text for "default" option.
  * @param string  $allValue       Value for "all" option.
  * @param string  $allText        Text for "all" option.
  * @param string  $displayField2  Second display field.
  * @param boolean $submit         Submit on choose.
  * @param boolean $disabled       Add Disabled attribute to select.
  * @param string  $fieldSeparator Field seperator if $displayField2 is given.
  * @param integer $multipleSize   Size for multiple selects.
  *
  * @return string The rendered output.
  */
 public static function getSelector_EntityArray($entity, $name, $field, $displayField = 'name', $where = '', $sort = '', $selectedValue = '', $defaultValue = 0, $defaultText = '', $allValue = 0, $allText = '', $displayField2 = null, $submit = true, $disabled = false, $fieldSeparator = ', ', $multipleSize = 1)
 {
     if (!$entity) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('entity', 'HtmlUtil::getSelector_EntityArray')));
     }
     if (!$field) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('field', 'HtmlUtil::getSelector_EntityArray')));
     }
     $em = \ServiceUtil::get('doctrine')->getManager();
     $filters = array();
     if (!empty($where)) {
         $where = explode("=", $where);
         $filters[$where[0]] = $where[1];
     }
     $ordering = array();
     if (!empty($sort)) {
         $sort = explode(" ", $sort);
         $ordering[$sort[0]] = $sort[1];
     }
     $dataArray = $em->getRepository($entity)->findBy($filters, $ordering);
     $data2 = array();
     foreach ($dataArray as $object) {
         if (strpos($field, '->') !== false) {
             $field_exp = explode('->', $field);
             $val = $object[$field_exp[0]][$field_exp[1]];
         } else {
             $val = $object[$field];
         }
         if (strpos($displayField, '->') !== false) {
             $displayField_exp = explode('->', $displayField);
             $disp = $object[$displayField_exp[0]][$displayField_exp[1]];
         } else {
             $disp = $object[$displayField];
         }
         if ($displayField2) {
             if (strpos($displayField2, '->') !== false) {
                 $displayField2_exp = explode('->', $displayField2);
                 $disp2 = $object[$displayField2_exp[0]][$displayField2_exp[1]];
             } else {
                 $disp2 = $object[$displayField2];
             }
             $disp .= $fieldSeparator . $disp2;
         }
         $data2[$val] = $disp;
     }
     return self::getSelector_Generic($name, $data2, $selectedValue, $defaultValue, $defaultText, $allValue, $allText, $submit, $disabled, $multipleSize);
 }
コード例 #17
0
ファイル: ThemeUtil.php プロジェクト: rmaiwald/core
 /**
  * Gets the themes table.
  *
  * Small wrapper function to avoid duplicate sql.
  *
  * @access private
  * @return array Modules table.
  */
 public static function getThemesTable()
 {
     static $themestable;
     if (!isset($themestable) || System::isInstalling()) {
         /** @var $em Doctrine\ORM\EntityManager */
         $em = ServiceUtil::get('doctrine.entitymanager');
         /** @var $array ThemeEntity[] */
         $array = $em->getRepository('ZikulaThemeModule:ThemeEntity')->findAll();
         foreach ($array as $theme) {
             $theme = $theme->toArray();
             $theme['i18n'] = is_dir("themes/{$theme['directory']}/locale") || is_dir("themes/{$theme['directory']}/Resources/locale") ? 1 : 0;
             $themestable[$theme['id']] = $theme;
         }
     }
     return $themestable;
 }
コード例 #18
0
ファイル: SessionUtil.php プロジェクト: planetenkiller/core
 /**
  * Regerate session id.
  *
  * @param boolean $force Force regeneration, default: false.
  *
  * @return void
  */
 public static function regenerate($force = false)
 {
     $storage = ServiceUtil::get('session');
     $storage->migrate();
 }
コード例 #19
0
ファイル: GenericUtil.php プロジェクト: rmaiwald/core
 /**
  * Process the parent of a category
  *
  * @param integer $parent_id The parent_id of the category.
  *
  * @return \Zikula\Module\CategoriesModule\Entity\CategoryEntity the parent entity.
  */
 public static function processCategoryParent($parent_id)
 {
     $em = \ServiceUtil::get('doctrine.entitymanager');
     return $em->getReference('ZikulaCategoriesModule:CategoryEntity', $parent_id);
 }
コード例 #20
0
 /**
  * Rebuild the path field for all categories in the database.
  *
  * Note that field and sourceField go in pairs (that is, if you want sensical results)!.
  *
  * @param string  $field       The field which we wish to populate (optional) (default='path').
  * @param string  $sourceField The field we use to build the path with (optional) (default='name').
  * @param integer $leaf_id     The leaf-category category-id (ie: we'll rebuild the path of this category and all it's parents) (optional) (default=0).
  *
  * @return void
  */
 public static function rebuildPaths($field = 'path', $sourceField = 'name', $leaf_id = 0)
 {
     if ($leaf_id > 0) {
         $cats = self::getParentCategories($leaf_id, 'id');
     } else {
         $cats = self::getCategories('', '', 'id');
     }
     $paths = self::buildPaths($cats, $sourceField);
     if ($cats && $paths) {
         $em = \ServiceUtil::get('doctrine')->getManager();
         foreach ($cats as $k => $v) {
             if ($v[$field] != $paths[$k][$field]) {
                 $dql = "UPDATE Zikula\\Core\\Doctrine\\Entity\\Category c SET c.{$field} = '" . $paths[$k] . "' WHERE c.id = {$k}";
                 $query = $em->createQuery($dql);
                 $query->getResult();
             }
         }
     }
 }
コード例 #21
0
ファイル: CategoryUtil.php プロジェクト: rmaiwald/core
 /**
  * Rebuild the path field for all categories in the database.
  *
  * Note that field and sourceField go in pairs (that is, if you want sensical results)!.
  *
  * @param string  $field       The field which we wish to populate (optional) (default='path').
  * @param string  $sourceField The field we use to build the path with (optional) (default='name').
  * @param integer $leaf_id     The leaf-category category-id (ie: we'll rebuild the path of this category and all it's parents) (optional) (default=0).
  *
  * @return void
  */
 public static function rebuildPaths($field = 'path', $sourceField = 'name', $leaf_id = 0)
 {
     if ($leaf_id > 0) {
         $cats = self::getParentCategories($leaf_id, 'id');
     } else {
         $cats = self::getCategories('', '', 'id');
     }
     $paths = self::buildPaths($cats, $sourceField);
     if ($cats && $paths) {
         $em = \ServiceUtil::get('doctrine.entitymanager');
         foreach ($cats as $k => $v) {
             if (isset($v[$field]) && isset($paths[$k]) && $v[$field] != $paths[$k]) {
                 $dql = "UPDATE Zikula\\Module\\CategoriesModule\\Entity\\CategoryEntity c SET c.{$field} = :path WHERE c.id = :id";
                 $query = $em->createQuery($dql);
                 $query->setParameter('path', $paths[$k]);
                 $query->setParameter('id', $k);
                 $query->getResult();
             }
         }
     }
 }
コード例 #22
0
ファイル: RandomUtil.php プロジェクト: rtznprmpftl/Zikulacore
 /**
  * Return a random user-id.
  *
  * @return string resulting random user-id.
  */
 public static function getUserID()
 {
     $em = \ServiceUtil::get('doctrine')->getManager();
     $dql = "SELECT u.uid FROM UsersModule\\Entity\\User u";
     $query = $em->createQuery($dql);
     $users = $query->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
     $pos = self::getInteger(0, count($users));
     return $users[$pos];
 }
コード例 #23
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');
         if (!$currentUid) {
             $currentUid = 1;
         }
         // get entity manager
         $em = \ServiceUtil::get('doctrine')->getManager();
         $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, 'user' => $em->getReference('UsersModule\\Entity\\User', $currentUid), 'ip' => $ipAddress, 'impact' => $result->getImpact(), 'filters' => serialize($filters), 'date' => new \DateTime("now"));
             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']);
             $obj = new \SecurityCenterModule\Entity\Intrusion();
             $obj->merge($intrusionItem);
             $em->persist($obj);
         }
         $em->flush();
     }
     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('MailerModule')) {
             $args = array();
             $args['fromname'] = $siteName;
             $args['fromaddress'] = $adminmail;
             $args['toname'] = 'Site Administrator';
             $args['toaddress'] = $adminmail;
             $args['subject'] = $mailTitle;
             $args['body'] = $mailBody;
             $rc = ModUtil::apiFunc('MailerModule', '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\Framework\Exception\ForbiddenException(__('Malicious request code / a hacking attempt was detected. Thus this request has been blocked.'), null, $result);
         }
     }
     return;
 }
コード例 #24
0
ファイル: ZLanguage.php プロジェクト: Silwereth/core
 /**
  * Bind module domain.
  *
  * @param string $modName Module name.
  *
  * @return boolean
  */
 public static function bindModuleDomain($modName)
 {
     // system modules are in the zikula domain
     $module = ModUtil::getInfoFromName($modName);
     if (ModUtil::isCore($modName)) {
         return 'zikula';
     }
     $_this = self::getInstance();
     if (!$_this->locale) {
         $request = ServiceUtil::get('request');
         $_this->setup($request);
     }
     $domain = self::getModuleDomain($modName);
     $module = ModUtil::getModule($modName);
     if (null !== $module) {
         $path = $_this->searchOverrides($domain, $module->getPath() . '/Resources/locale');
     } else {
         $path = $_this->searchOverrides($domain, 'modules/' . $modName . '/locale');
     }
     return self::bindDomain($domain, $path);
 }
コード例 #25
0
ファイル: ZLanguage.php プロジェクト: rtznprmpftl/Zikulacore
 /**
  * Fix language to session.
  *
  * @return void
  */
 private function fixLanguageToSession()
 {
     if ($this->langFixSession) {
         ServiceUtil::get('request')->getSession()->set('language', $this->languageCode);
     }
 }
コード例 #26
0
ファイル: AbstractBase.php プロジェクト: Silwereth/core
 /**
  * Constructor.
  *
  * @param Zikula_ServiceManager $serviceManager ServiceManager instance.
  * @param AbstractModule        $bundle
  */
 public function __construct(Zikula_ServiceManager $serviceManager, AbstractModule $bundle = null)
 {
     $this->setContainer($serviceManager);
     $this->dispatcher = $this->getContainer()->get('event_dispatcher');
     $this->eventManager = $this->dispatcher;
     $this->request = \ServiceUtil::get('request');
     $this->entityManager = $this->getContainer()->get('doctrine.entitymanager');
     $this->_configureBase($bundle);
     $this->initialize();
     $this->postInitialize();
 }
コード例 #27
0
ファイル: SystemListeners.php プロジェクト: Silwereth/core
 /**
  * If enabled and logged in, save login name of user in Apache session variable for Apache logs.
  *
  * Implements 'session.require'.
  *
  * @param Zikula_Event $event The event handler.
  *
  * @return void
  */
 public function requireSession(Zikula_Event $event)
 {
     $session = $this->serviceManager->get('session');
     try {
         $request = ServiceUtil::get('request');
         $request->setSession($session);
     } catch (Exception $e) {
         // ignore silently (for CLI)
     }
     try {
         if (!$session->start()) {
             throw new RuntimeException('Failed to start session');
         }
     } catch (Exception $e) {
         // session initialization failed so display templated error
         header('HTTP/1.1 503 Service Unavailable');
         require_once System::getSystemErrorTemplate('sessionfailed.tpl');
         System::shutdown();
     }
 }
コード例 #28
0
 /**
  * Saves value in data object.
  *
  * Called by the render when doing $render->getValues()
  * Uses the group parameter to decide where to store data.
  *
  * @param Zikula_Form_View $view  Reference to Form render object.
  * @param array            &$data Data object.
  *
  * @return void
  */
 function saveValue(Zikula_Form_View $view, &$data)
 {
     if ($this->enableDBUtil && $this->dataBased) {
         if ($this->group == null) {
             $data['__CATEGORIES__'][$this->dataField] = $this->getSelectedValue();
         } else {
             if (!array_key_exists($this->group, $data)) {
                 $data[$this->group] = array();
             }
             $data[$this->group]['__CATEGORIES__'][$this->dataField] = $this->getSelectedValue();
         }
     } else {
         if ($this->enableDoctrine && $this->dataBased) {
             if ($this->group == null) {
                 $data['Categories'][$this->dataField] = array('category_id' => $this->getSelectedValue(), 'reg_property' => $this->dataField);
             } else {
                 if (!array_key_exists($this->group, $data)) {
                     $data[$this->group] = array();
                 }
                 $data[$this->group]['Categories'][$this->dataField] = array('category_id' => $this->getSelectedValue(), 'reg_property' => $this->dataField);
             }
         } else {
             if ($this->doctrine2) {
                 $entity = $view->get_template_vars($this->group);
                 // load category from db
                 $em = ServiceUtil::get('doctrine')->getEntityManager();
                 $category = $em->find('Zikula_Doctrine2_Entity_Category', $this->getSelectedValue());
                 $collection = $em->getClassMetadata(get_class($entity))->getFieldValue($entity, $this->dataField);
                 if (!$collection) {
                     $collection = new \Doctrine\Common\Collections\ArrayCollection();
                     $em->getClassMetadata(get_class($entity))->setFieldValue($entity, $this->dataField, $collection);
                 }
                 if ($collection->containsKey($this->registryId)) {
                     $collection->get($this->registryId)->setCategory($category);
                 } else {
                     $class = $em->getClassMetadata(get_class($entity))->getAssociationTargetClass($this->dataField);
                     $collection->set($this->registryId, new $class($this->registryId, $category, $entity));
                 }
             } else {
                 parent::saveValue($view, $data);
             }
         }
     }
 }
コード例 #29
0
ファイル: UserUtil.php プロジェクト: rtznprmpftl/Zikulacore
 /**
  * Determine if the current session is that of an anonymous user.
  *
  * @return boolean
  */
 public static function isGuestUser()
 {
     return !ServiceUtil::get('request')->getSession()->get('uid', 0);
 }
コード例 #30
0
ファイル: SecurityUtil.php プロジェクト: rmaiwald/core
 /**
  * Get auth info.
  *
  * @param integer $user User Id.
  *
  * @return array Two element array of user and group permissions.
  */
 public static function getAuthInfo($user = null)
 {
     // Empty arrays
     $groupperms = array();
     $uids = array();
     $uids[] = -1;
     // Get user ID
     if (!isset($user)) {
         if (!UserUtil::isLoggedIn()) {
             // Unregistered UID
             $uids[] = 0;
             $vars['Active User'] = '******';
         } else {
             $_uid = (int) UserUtil::getVar('uid');
             if ($_uid) {
                 $uids[] = $_uid;
                 $vars['Active User'] = $_uid;
             }
         }
     } else {
         $uids[] = (int) $user;
         $vars['Active User'] = (int) $user;
     }
     $em = ServiceUtil::get('doctrine.entitymanager');
     // Get all groups that user is in
     $qb = $em->createQueryBuilder();
     $query = $qb->select('g.gid')->from('ZikulaGroupsModule:GroupMembershipEntity', 'g')->where($qb->expr()->in('g.uid', ':uids'))->setParameter('uids', $uids)->getQuery();
     $fldArray = $query->getResult();
     if ($fldArray === false) {
         return $groupperms;
     }
     $usergroups = array();
     $usergroups[] = array('gid' => -1);
     if ($user == 0 || !UserUtil::isLoggedIn()) {
         $usergroups[] = 0;
         // Unregistered GID
     }
     $allgroups = array_merge_recursive($usergroups, $fldArray);
     // Get all group permissions
     $qb = $em->createQueryBuilder();
     $query = $qb->select('p')->from('ZikulaPermissionsModule:PermissionEntity', 'p')->where($qb->expr()->in('p.gid', ':allgroups'))->setParameter('allgroups', $allgroups)->orderBy('p.sequence', 'ASC')->getQuery();
     $objArray = $query->getArrayResult();
     if (!$objArray) {
         return $groupperms;
     }
     foreach ($objArray as $obj) {
         $component = self::_fixsecuritystring($obj['component']);
         $instance = self::_fixsecuritystring($obj['instance']);
         $level = self::_fixsecuritystring($obj['level']);
         // Search/replace of special names
         preg_match_all('/<([^>]+)>/', $instance, $res);
         $size = count($res[1]);
         for ($i = 0; $i < $size; $i++) {
             $instance = preg_replace('/<([^>]+)>/', $vars[$res[1][$i]], $instance, 1);
         }
         $groupperms[] = array('component' => $component, 'instance' => $instance, 'level' => $level);
     }
     // we've now got the permissions info
     $GLOBALS['authinfogathered'][$user] = 1;
     return $groupperms;
 }