Ejemplo n.º 1
0
 public function display($blockinfo)
 {
     // security check
     $this->throwForbiddenUnless(SecurityUtil::checkPermission('Content:menublock:', "{$blockinfo['title']}::", ACCESS_READ), LogUtil::getErrorMsgPermission());
     // Break out options from our content field
     $vars = BlockUtil::varsFromContent($blockinfo['content']);
     // --- Setting of the Defaults
     if (!isset($vars['usecaching'])) {
         $vars['usecaching'] = false;
     }
     if (!isset($vars['root'])) {
         $vars['root'] = 0;
     }
     $this->view->setCacheId($blockinfo['bid']);
     $this->view->setCaching($vars['usecaching']);
     if (!$vars['usecaching'] || $vars['usecaching'] && !$this->view->is_cached('block/menu.tpl')) {
         $options = array('orderBy' => 'setLeft', 'makeTree' => true, 'filter' => array());
         if ($vars['root'] > 0) {
             $options['filter']['superParentId'] = $vars['root'];
         }
         // checkInMenu, checkActive is done implicitely
         $options['filter']['checkInMenu'] = true;
         $pages = ModUtil::apiFunc('Content', 'Page', 'getPages', $options);
         if ($pages === false) {
             return false;
         }
         $this->view->assign('subPages', $pages);
     }
     $blockinfo['content'] = $this->view->fetch('block/menu.tpl');
     return BlockUtil::themeBlock($blockinfo);
 }
Ejemplo n.º 2
0
 function __destruct()
 {
     if ($this->fp != null) {
         fclose($this->fp);
         LogUtil::$logger = null;
     }
 }
Ejemplo n.º 3
0
/**
 * Example:
 * {secauthaction comp="Stories::" inst=".*" level="ACCESS_ADMIN" assign="auth"}
 *
 * true/false will be returned.
 *
 * This file is a plugin for Zikula_View, the Zikula implementation of Smarty
 * @param        array       $params      All attributes passed to this function from the template
 * @param        object      &$smarty     Reference to the Smarty object
 * @return       boolean     authorized?
 */
function smarty_function_secauthaction($params, &$smarty)
{
    LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated, please use {%2$s} instead.', array('secauthaction', 'checkpermission')), E_USER_DEPRECATED);

    $assign = isset($params['assign']) ? $params['assign'] : null;
    $comp   = isset($params['comp'])   ? $params['comp']   : null;
    $inst   = isset($params['inst'])   ? $params['inst']   : null;
    $level  = isset($params['level'])  ? $params['level']  : null;

    if (!$comp) {
        $smarty->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('smarty_function_secauthaction', 'comp')));
        return false;
    }

    if (!$inst) {
        $smarty->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('smarty_function_secauthaction', 'inst')));
        return false;
    }

    if (!$level) {
        $smarty->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('smarty_function_secauthaction', 'level')));
        return false;
    }

    $result = SecurityUtil::checkPermission($comp, $inst, constant($level));

    if ($assign) {
        $smarty->assign($assign, $result);
    } else {
        return $result;
    }
}
Ejemplo n.º 4
0
    public function Install() {
        // Checks if module IWmain is installed. If not returns error
        $modid = ModUtil::getIdFromName('IWmain');
        $modinfo = ModUtil::getInfo($modid);

        if ($modinfo['state'] != 3) {
            return LogUtil::registerError($this->__('Module IWmain is needed. You have to install the IWmain module before installing it.'));
        }

        // Check if the version needed is correct
        $versionNeeded = '2.0';
        if (!ModUtil::func('IWmain', 'admin', 'checkVersion', array('version' => $versionNeeded))) {
            return false;
        }

        // create module tables
        $tables = array('IWstats', 'IWstats_summary');
        foreach ($tables as $table) {
            if (!DBUtil::createTable($table)) {
                return false;
            }
        }

        // create several indexes for IWstats table
        $table = DBUtil::getTables();
        $c = $table['IWstats_column'];
        if (!DBUtil::createIndex($c['moduleid'], 'IWstats', 'moduleid')) {
            return false;
        }
        if (!DBUtil::createIndex($c['uid'], 'IWstats', 'uid')) {
            return false;
        }
        if (!DBUtil::createIndex($c['ip'], 'IWstats', 'ip')) {
            return false;
        }
        if (!DBUtil::createIndex($c['ipForward'], 'IWstats', 'ipForward')) {
            return false;
        }
        if (!DBUtil::createIndex($c['ipClient'], 'IWstats', 'ipClient')) {
            return false;
        }
        if (!DBUtil::createIndex($c['userAgent'], 'IWstats', 'userAgent')) {
            return false;
        }
        if (!DBUtil::createIndex($c['isadmin'], 'IWstats', 'isadmin')) {
            return false;
        }

        // Set up config variables
        $this->setVar('skippedIps', '')
                ->setVar('modulesSkipped', '')
                ->setVar('deleteFromDays', 90)
                ->setVar('keepDays', 90);

        // create the system init hook
        EventUtil::registerPersistentModuleHandler('IWstats', 'core.postinit', array('IWstats_Listeners', 'coreinit'));

        // Initialisation successful
        return true;
    }
Ejemplo n.º 5
0
 public function initialize(Zikula_Form_View $view)
 {
     $this->pageId = FormUtil::getPassedValue('pid', isset($this->args['pid']) ? $this->args['pid'] : null);
     $offset = (int) FormUtil::getPassedValue('offset');
     if ((bool) $this->getVar('inheritPermissions', false) === true) {
         if (!ModUtil::apiFunc('Content', 'page', 'checkPermissionForPageInheritance', array('pageId' => $this->pageId, 'level' => ACCESS_EDIT))) {
             throw new Zikula_Exception_Forbidden(LogUtil::getErrorMsgPermission());
         }
     } else {
         if (!SecurityUtil::checkPermission('Content:page:', $this->pageId . '::', ACCESS_EDIT)) {
             throw new Zikula_Exception_Forbidden(LogUtil::getErrorMsgPermission());
         }
     }
     $page = ModUtil::apiFunc('Content', 'Page', 'getPage', array('id' => $this->pageId, 'editing' => false, 'filter' => array('checkActive' => false), 'enableEscape' => true, 'translate' => false, 'includeContent' => false, 'includeCategories' => false));
     if ($page === false) {
         return $this->view->registerError(null);
     }
     $versionscnt = ModUtil::apiFunc('Content', 'History', 'getPageVersionsCount', array('pageId' => $this->pageId));
     $versions = ModUtil::apiFunc('Content', 'History', 'getPageVersions', array('pageId' => $this->pageId, 'offset' => $offset));
     if ($versions === false) {
         return $this->view->registerError(null);
     }
     $this->view->assign('page', $page);
     $this->view->assign('versions', $versions);
     Content_Util::contentAddAccess($this->view, $this->pageId);
     // Assign the values for the smarty plugin to produce a pager
     $this->view->assign('numitems', $versionscnt);
     PageUtil::setVar('title', $this->__("Page history") . ' : ' . $page['title']);
     if (!$this->view->isPostBack() && FormUtil::getPassedValue('back', 0)) {
         $this->backref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
     }
     return true;
 }
Ejemplo n.º 6
0
    /**
     * Vetos (denies) a login attempt, and forces the user to change his password.
     *
     * This handler is triggered by the 'user.login.veto' event.  It vetos (denies) a
     * login attempt if the users's account record is flagged to force the user to change
     * his password maintained by the Users module. If the user does not maintain a
     * password on his Users account (e.g., he registered with and logs in with a Google
     * Account or an OpenID, and never established a Users password), then this handler
     * will not trigger a change of password.
     *
     * @param Zikula_Event $event The event that triggered this handler.
     *
     * @return void
     */
    public static function forcedPasswordChangeListener(Zikula_Event $event)
    {
        $userObj = $event->getSubject();

        $userMustChangePassword = UserUtil::getVar('_Users_mustChangePassword', $userObj['uid'], false);

        if ($userMustChangePassword && ($userObj['pass'] != Users_Constant::PWD_NO_USERS_AUTHENTICATION)) {
            $event->stop();
            $event->setData(array(
                'redirect_func'  => array(
                    'modname'   => self::$modname,
                    'type'      => 'user',
                    'func'      => 'changePassword',
                    'args'      => array(
                        'login'     => true,
                    ),
                    'session'   => array(
                        'var'       => 'Users_Controller_User_changePassword',
                        'namespace' => 'Zikula_Users',
                    )
                ),
            ));

            LogUtil::registerError(__("Your log-in request was not completed. You must change your web site account's password first."));
        }
    }
Ejemplo n.º 7
0
    /**
     * Desinstal·lació del mòdul Cataleg
     * 
     * @return bool true si ha anat tot bé, false en qualsevol altre cas.
     */
    public function uninstall()
    {
        if (!SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_ADMIN)) {
            return LogUtil::registerPermissionError();
        }
        // Esborrar taules del mòdul          
        if (!DBUtil::dropTable('cataleg')||
            !DBUtil::dropTable('cataleg_eixos')||
            !DBUtil::dropTable('cataleg_prioritats')||
            !DBUtil::dropTable('cataleg_unitatsImplicades')||
            !DBUtil::dropTable('cataleg_subprioritats')|| 
            !DBUtil::dropTable('cataleg_activitats')||               
            !DBUtil::dropTable('cataleg_activitatsZona')||   
            !DBUtil::dropTable('cataleg_unitats')||
            !DBUtil::dropTable('cataleg_responsables')||
            !DBUtil::dropTable('cataleg_contactes')||
            !DBUtil::dropTable('cataleg_auxiliar')||
            !DBUtil::dropTable('cataleg_centresActivitat')||
	    !DBUtil::dropTable('cataleg_centres')||
            !DBUtil::dropTable('cataleg_gestioActivitatDefaults')||
            !DBUtil::dropTable('cataleg_importTaules')||
            !DBUtil::dropTable('cataleg_importAssign')||
            !DBUtil::dropTable('cataleg_gtafEntities')||
            !DBUtil::dropTable('cataleg_gtafGroups')
            ) 
        return false;
        //Esborrar variables del mòdul
        $this->delVars();
        // unregister hook handlers
        HookUtil::unregisterSubscriberBundles($this->version->getHookSubscriberBundles());
        return true;
    }
Ejemplo n.º 8
0
    public function install() {
        if (!SecurityUtil::checkPermission('IWdocmanager::', '::', ACCESS_ADMIN)) {
            return LogUtil::registerPermissionError();
        }
        // Checks if module IWmain is installed. If not returns error
        if (!ModUtil::available('IWmain')) {
            return LogUtil::registerError(__('Module IWmain is required. You have to install the IWmain module previously to install it.'));
        }

        // Check if the version needed is correct
        $versionNeeded = '3.0.0';
        if (!ModUtil::func('IWmain', 'admin', 'checkVersion', array('version' => $versionNeeded))) {
            return false;
        }

        if (!DBUtil::createTable('IWdocmanager'))
            return false;
        if (!DBUtil::createTable('IWdocmanager_categories'))
            return false;

        //Create indexes
        $table = DBUtil::getTables();
        $c = $table['IWdocmanager_column'];
        DBUtil::createIndex($c['author'], 'IWdocmanager', 'author');
        DBUtil::createIndex($c['categoryId'], 'IWdocmanager', 'categoryId');

        //Create module vars
        $this->setVar('documentsFolder', 'documents')
                ->setVar('notifyMail', '')
                ->setVar('editTime', '45')
                ->setVar('deleteTime', '20');

        return true;
    }
Ejemplo n.º 9
0
 public function install()
 {
     \DoctrineHelper::createSchema($this->entityManager, static::getEntities());
     $this->createLicenses();
     $temporaryUploadCollection = new CollectionEntity();
     $temporaryUploadCollection->setTitle($this->__('Temporary Upload Collection'))->setDescription($this->__('This collection is needed as temporary storage for uploaded files. Do not edit or delete!'));
     $this->entityManager->persist($temporaryUploadCollection);
     $exampleCollection = new CollectionEntity();
     $exampleCollection->setTitle($this->__('Example collection'))->setDescription($this->__('Edit or delete this example collection'));
     $this->entityManager->persist($exampleCollection);
     $this->entityManager->flush();
     if ($temporaryUploadCollection->getId() != CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID) {
         \LogUtil::registerError($this->__('The id of the generated "temporary upload collection" must be 1, but has a different value. This should not have happened. Please report this error.'));
     }
     \HookUtil::registerProviderBundles($this->version->getHookProviderBundles());
     \HookUtil::registerSubscriberBundles($this->version->getHookSubscriberBundles());
     $this->setVar('descriptionEscapingStrategyForCollection', 'text');
     $this->setVar('descriptionEscapingStrategyForMedia', 'text');
     $this->setVar('defaultCollectionTemplate', 'cards');
     $this->setVar('slugEditable', true);
     $this->setVar('lastNewVersionCheck', 0);
     $this->setVar('newVersionAvailable', false);
     $this->createUploadDir();
     return true;
 }
 /**
  * Ensure we are in an interactive session.
  *
  * @return void
  */
 public function preDispatch()
 {
     $this->throwForbiddenUnless(\SecurityUtil::checkPermission($this->getName() . '::', '::', \ACCESS_ADMIN), \LogUtil::getErrorMsgPermission());
     $session = $this->request->getSession();
     $check = (bool) ($session->get('interactive_init') || $session->get('interactive_upgrade') || $session->get('interactive_remove'));
     $this->throwForbiddenUnless($check, $this->__('This doesnt appear to be an interactive session.'));
 }
Ejemplo n.º 11
0
/**
 * Update operation.
 * @param object $entity The treated object.
 * @param array  $params Additional arguments.
 *
 * @return bool False on failure or true if everything worked well.
 */
function Reviews_operation_update(&$entity, $params)
{
    $dom = ZLanguage::getModuleDomain('Reviews');
    // initialise the result flag
    $result = false;
    $objectType = $entity['_objectType'];
    $currentState = $entity['workflowState'];
    // get attributes read from the workflow
    if (isset($params['nextstate']) && !empty($params['nextstate'])) {
        // assign value to the data object
        $entity['workflowState'] = $params['nextstate'];
        if ($params['nextstate'] == 'archived') {
            // bypass validator (for example an end date could have lost it's "value in future")
            $entity['_bypassValidation'] = true;
        }
    }
    // get entity manager
    $serviceManager = ServiceUtil::getManager();
    $entityManager = $serviceManager->getService('doctrine.entitymanager');
    // save entity data
    try {
        //$this->entityManager->transactional(function($entityManager) {
        $entityManager->persist($entity);
        $entityManager->flush();
        //});
        $result = true;
    } catch (\Exception $e) {
        LogUtil::registerError($e->getMessage());
    }
    // return result of this operation
    return $result;
}
Ejemplo n.º 12
0
/**
 * Zikula_View function to check for the availability of a module
 *
 * This function calls ModUtil::isHooked to determine if two Zikula modules are
 * hooked together. True is returned if the modules are hooked, false otherwise.
 * The result can also be assigned to a template variable.
 *
 * Available parameters:
 *   - tmodname:  The well-known name of the hook module
 *   - smodname:  The well-known name of the calling module
 *   - assign:    The name of a variable to which the results are assigned
 *
 * Examples
 *   {modishooked tmodname='Ratings' smodname='News'}
 *
 *   {modishooked tmodname='bar' smodname='foo' assign='barishookedtofoo'}
 *   {if $barishookedtofoo}.....{/if}
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @see    function.modishooked.php::smarty_function_modishooked()
 *
 * @return boolean True if the module is available; false otherwise.
 */
function smarty_function_modishooked($params, $view)
{
    LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated.', array('modishooked')), E_USER_DEPRECATED);

    $assign   = isset($params['assign'])   ? $params['assign']   : null;
    $smodname = isset($params['smodname']) ? $params['smodname'] : null;
    $tmodname = isset($params['tmodname']) ? $params['tmodname'] : null;

    if (!$tmodname) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('modishooked', 'tmodname')));
        return false;
    }

    if (!$smodname) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('modishooked', 'smodname')));
        return false;
    }

    $result = ModUtil::isHooked($tmodname, $smodname);

    if ($assign) {
        $view->assign($params['assign'], $result);
    } else {
        return $result;
    }
}
Ejemplo n.º 13
0
 function updateMemcache()
 {
     // ignore_user_abort();
     //set_time_limit(0);
     //$interval=3600; //(seconds)
     require_once 'model/Feed.php';
     require_once 'lib/BitMemCache.php';
     require_once 'lib/RssReader.php';
     $feed = new Feed();
     $feeds = $feed->getFeeds();
     $logger = LogUtil::getLogger();
     //do{
     include "config/site.php";
     foreach ($feeds as $feed) {
         $url = $feed['url'];
         $mem = new BitMemCache();
         $reader = new RssReader();
         $rss = $reader->fetch($url);
         if (!$rss) {
         } else {
             if ($mem->init()) {
                 $mem->set($url, json_encode($rss));
                 $logger->info("update memcache {$url}");
             }
         }
     }
     //  sleep($interval);
     //}while($memcache);
 }
Ejemplo n.º 14
0
/**
 * Obtain and display a configuration variable from the Zikula system.
 *
 * Available attributes:
 *  - name      (string)    The name of the configuration variable to obtain
 *  - html      (bool)      If set, the output is prepared for display by
 *                          DataUtil::formatForDisplayHTML instead of
 *                          DataUtil::formatForDisplay
 *  - assign    (string)    the name of a template variable to assign the
 *                          output to, instead of returning it to the template. (optional)
 *
 * <i>Note that if the the result is assigned to a template variable, it is not
 * prepared for display by either DataUtil::formatForDisplayHTML or
 * DataUtil::formatForDisplay. If it is to be displayed, the safetext
 * modifier should be used.</i>
 *
 * Examples:
 *
 * <samp><p>Welcome to {configgetvar name='sitename'}!</p></samp>
 *
 * <samp>{configgetvar name='sitename' assign='thename'}</samp><br>
 * <samp><p>Welcome to {$thename|safetext}!</p></samp>
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the {@link Zikula_View} object.
 *
 * @return mixed The value of the configuration variable.
 */
function smarty_function_configgetvar($params, $view)
{
    LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated.', array('configgetvar')), E_USER_DEPRECATED);

    $name      = isset($params['name'])    ? $params['name']    : null;
    $default   = isset($params['default']) ? $params['default'] : null;
    $html      = isset($params['html'])    ? $params['html']    : null;
    $assign    = isset($params['assign'])  ? $params['assign']  : null;

    if (!$name) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('configgetvar', 'name')));
        return false;
    }

    $result = System::getVar($name, $default);

    if ($assign) {
        $view->assign($assign, $result);
    } else {
        if (is_bool($html) && $html) {
            return DataUtil::formatForDisplayHTML($result);
        } else {
            return DataUtil::formatForDisplay($result);
        }
    }
}
Ejemplo n.º 15
0
 /**
  * display items for a day
  *
  * @param $args array Arguments array.
  *
  * @return string html string
  */
 public function display($args)
 {
     $eid = FormUtil::getPassedValue('eid', isset($args['eid']) ? $args['eid'] : null, 'REQUEST');
     $objectid = FormUtil::getPassedValue('objectid', isset($args['objectid']) ? $args['objectid'] : null, 'REQUEST');
     if (!empty($objectid)) {
         $eid = $objectid;
     }
     if (!isset($args['eid']) and !empty($eid)) {
         $args['eid'] = $eid;
     }
     // Chek permissions
     $this->throwForbiddenUnless(SecurityUtil::checkPermission('Ephemerides::', '::', ACCESS_READ), LogUtil::getErrorMsgPermission());
     // check if the contents are cached.
     $template = 'ephemerides_user_display.tpl';
     if ($this->view->is_cached($template)) {
         return $this->view->fetch($template);
     }
     // get items
     if (isset($args['eid']) and $args['eid'] > 0) {
         $items = ModUtil::apiFunc($this->name, 'user', 'getall', $args);
     } else {
         $items = ModUtil::apiFunc($this->name, 'user', 'gettoday', $args);
     }
     $this->view->assign('items', $items);
     return $this->view->fetch($template);
 }
Ejemplo n.º 16
0
/**
 * Example:
 * {securityutil_checkpermission component='Users::' instance='.*' level='ACCESS_ADMIN' assign='auth'}
 *
 * true/false will be returned.
 *
 * This file is a plugin for Zikula_View, the Zikula implementation of Smarty
 * @param        array       $params      All attributes passed to this function from the template
 * @param        object      $smarty      Reference to the Smarty object
 * @return       boolean     authorized?
 */
function smarty_function_securityutil_checkpermission($params, $smarty)
{
    LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated, please use {%2$s} instead.', array('securityutil_checkpermission', 'checkpermission')), E_USER_DEPRECATED);

    if (!isset($params['component'])) {
        $smarty->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('securityutil_checkpermission', 'component')));
        return false;
    }

    if (!isset($params['instance'])) {
        $smarty->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('securityutil_checkpermission', 'instance')));
        return false;
    }

    if (!isset($params['level'])) {
        $smarty->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('securityutil_checkpermission', 'level')));
        return false;
    }

    $result = SecurityUtil::checkPermission($params['component'], $params['instance'], constant($params['level']));

    if (isset($params['assign'])) {
        $smarty->assign($params['assign'], $result);
    } else {
        return $result;
    }
}
Ejemplo n.º 17
0
 /**
  * get token from db
  */
 public static function getWxTokenFromDB()
 {
     // 因为在wxindex.php里面已经引用过inc.db.php,所以这里是能拿到db的
     global $db;
     $tokenObj = $db->fetch($db->query("SELECT * FROM wx_token where id = 1"));
     if ($tokenObj) {
         // 如果不为空
         $tokenFromDB = $tokenObj['token'];
         $updatetime = $tokenObj['updatetime'];
         $currenttime = DateUtil::getCurrentTime();
         /*$days=floor((strtotime($currenttime)-strtotime($updatetime))/86400);
         		$hour=floor((strtotime($currenttime)-strtotime($updatetime))%86400/3600);
         		$minute=floor((strtotime($currenttime)-strtotime($updatetime))%86400/60);
         		$second=floor((strtotime($currenttime)-strtotime($updatetime))%86400%60);
         		
         		$seconds = $days * 24 + $hour * 60 + $minute * 60 + $second;*/
         $seconds = DateUtil::getTimeInterval($currenttime, $updatetime);
         LogUtil::logs("getWxTokenFromDB=====> " . $seconds, getLogFile("/business.log"));
         if ($seconds >= 6000) {
             // 如果当前操作时间的间隔已经大于或等于6500秒了
             //LogUtil::logs("WxUtil getWxTokenFromDB  :已超时,重新获取token", getLogFile('/business.log'));
             return self::initWxTokenToDB();
         }
         //LogUtil::logs("WxUtil getWxTokenFromDB  :未超时,使用数据库token", getLogFile('/business.log'));
         return $tokenFromDB;
     }
     //LogUtil::logs("WxUtil self getWxTokenFromDB  :数据库不存在token,初始化token", getLogFile('/business.log'));
     return self::initWxTokenToDB();
 }
Ejemplo n.º 18
0
    /**
     * Updates a group in the database
     *
     * @param gid the group id.
     * @param gtype the group type.
     * @param state the group state.
     * @param nbumax the maximum of users.
     * @param name the group name.
     * @param description the group description.
     *
     * @return Zikula_Response_Ajax
     */
    public function updategroup($args)
    {
        $this->checkAjaxToken();

        $gid = $this->request->request->get('gid');
        $gtype = $this->request->request->get('gtype', 9999);
        $state = $this->request->request->get('state');
        $nbumax = $this->request->request->get('nbumax', 9999);
        $name = $this->request->request->get('name');
        $description = $this->request->request->get('description');

        $this->throwForbiddenUnless(SecurityUtil::checkPermission('Groups::', $gid . '::', ACCESS_EDIT));

        if (empty($name)) {
            return new Zikula_Response_Ajax(array('result' => false, 'error' => true, 'gid' => $gid, 'message' => $this->__('Error! The group name is missing.')));
        }

        if (preg_match("/[\n\r\t\x0B]/", $name)) {
            $name = trim(preg_replace("/[\n\r\t\x0B]/", "", $name));
        }
        if (preg_match("/[\n\r\t\x0B]/", $description)) {
            $description = trim(preg_replace("/[\n\r\t\x0B]/", "", $description));
        }

        // Pass to API
        $res = ModUtil::apiFunc('Groups',
                        'admin',
                        'update',
                        array('gid' => $gid,
                                'name' => $name,
                                'gtype' => $gtype,
                                'state' => $state,
                                'nbumax' => $nbumax,
                                'description' => $description));

        if ($res == false) {
            // check for sessionvar
            $msgs = LogUtil::getStatusMessagesText();
            if (!empty($msgs)) {
                // return with msg, but not via Zikula_Exception_Fatal
                return new Zikula_Response_Ajax(array('result' => false, 'error' => true, 'gid' => $gid, 'message' => $msgs));
            }
        }

        // Setting various defines
        $groupsCommon = new Groups_Helper_Common();
        $typelabel = $groupsCommon->gtypeLabels();
        $statelabel = $groupsCommon->stateLabels();

        // Using uncached query here as it was returning the unupdated group
        $group = DBUtil::selectObjectByID('groups', $gid, 'gid', null, null, null, false);

        // get group member count
        $group['nbuser'] = ModUtil::apiFunc('Groups', 'user', 'countgroupmembers', array('gid' => $gid));

        $group['statelbl'] = $statelabel[$group['state']];
        $group['gtypelbl'] = $typelabel[$group['gtype']];

        return new Zikula_Response_Ajax($group);
    }
Ejemplo n.º 19
0
    public function handleCommand(Zikula_Form_View $view, &$args)
    {
        if ($args['commandName'] == 'save') {
            if (!$this->view->isValid()) {
                return false;
            }

            $data = $this->view->getValues();

            if (!ModUtil::setVars('Content', $data['config'])) {
                return $this->view->setErrorMsg($this->__('Failed to set configuration variables'));
            }
            if ($data['config']['categoryUsage'] < 4) {
                // load the category registry util
                $mainCategory = CategoryRegistryUtil::getRegisteredModuleCategory('Content', 'content_page', $data['config']['categoryPropPrimary']);
                if (!$mainCategory) {
                    return LogUtil::registerError($this->__('Main category property does not exist.'));
                }
                if ($data['config']['categoryUsage'] < 3) {
                    $secondCategory = CategoryRegistryUtil::getRegisteredModuleCategory('Content', 'content_page', $data['config']['categoryPropSecondary']);
                    if (!$secondCategory) {
                        return LogUtil::registerError($this->__('Second category property does not exist.'));
                    }
                }
            }
            LogUtil::registerStatus($this->__('Done! Saved module configuration.'));
        } else if ($args['commandName'] == 'cancel') {
        }

        $url = ModUtil::url('Content', 'admin', 'main');

        return $this->view->redirect($url);
    }
Ejemplo n.º 20
0
 /**
  * Create or edit record.
  *
  * @return string|boolean Output.
  */
 public function edit()
 {
     if (!SecurityUtil::checkPermission('ExampleDoctrine::', '::', ACCESS_ADD)) {
         return LogUtil::registerPermissionError(ModUtil::url('ExampleDoctrine', 'user', 'index'));
     }
     $id = $this->request->query->getInt('id');
     if ($id) {
         // load user with id
         $user = $this->entityManager->find('ExampleDoctrine_Entity_User', $id);
         if (!$user) {
             return LogUtil::registerError($this->__f('User with id %s not found', $id));
         }
     } else {
         $user = new ExampleDoctrine_Entity_User();
     }
     /* @var $form Symfony\Component\Form\Form */
     $form = $this->serviceManager->getService('symfony.formfactory')->create(new ExampleDoctrine_Form_UserType(), $user);
     if ($this->request->getMethod() == 'POST') {
         $form->bindRequest($this->request);
         if ($form->isValid()) {
             $data = $form->getData();
             $this->entityManager->persist($data);
             $this->entityManager->flush();
             return $this->redirect(ModUtil::url('ExampleDoctrine', 'user', 'view'));
         }
     }
     return $this->view->assign('form', $form->createView())->fetch('exampledoctrine_user_edit.tpl');
 }
Ejemplo n.º 21
0
 /**
  *
  */
 public function moduleSearch($args)
 {
     $dom = ZLanguage::getModuleDomain('MUBoard');
     $searchsubmit = $this->request->getPost()->filter('searchsubmit', 'none', FILTER_SANITIZE_STRING);
     $searchoptions = $this->request->getPost()->filter('searchoptions', 'all', FILTER_SANITIZE_STRING);
     $searchplace = $this->request->getPost()->filter('searchplace', 'title', FILTER_SANITIZE_STRING);
     $resultorder = $this->request->getPost()->filter('resultorder', 'none', FILTER_SANITIZE_STRING);
     $kind = $this->request->query->filter('kind', 'none', FILTER_SANITIZE_STRING);
     // user has not entered a string and there is 'none' as kind of search
     if ($searchsubmit == 'none' && $kind == 'none') {
         // return search form template
         return $this->searchRedirect();
     } else {
         if ($searchsubmit != 'none' && $kind == 'none') {
             $searchstring = $this->request->getPost()->filter('searchstring', '', FILTER_SANITIZE_STRING);
             if ($searchstring == '') {
                 $url = ModUtil::url($this->name, 'search', 'modulesearch');
                 return LogUtil::registerError(__('You have to enter a string!', $dom), null, $url);
             } else {
                 $args['searchstring'] = $searchstring;
                 $args['searchoptions'] = $searchoptions;
                 $args['searchplace'] = $searchplace;
                 $args['resultorder'] = $resultorder;
                 $args['kind'] = $kind;
             }
         }
         if ($searchsubmit == 'none' && $kind != 'none') {
             $args['kind'] = $kind;
         }
     }
     return ModUtil::apiFunc($this->name, 'search', 'moduleSearch', $args);
 }
Ejemplo n.º 22
0
 /**
  * Dispatch a module view request.
  *
  * @return mixed
  */
 public function dispatch()
 {
     if (!SecurityUtil::checkPermission('Extensions::', '::', ACCESS_ADMIN)) {
         return LogUtil::registerPermissionError();
     }
     // Get input.
     $moduleName = $this->request->getGet()->filter('_module', null, FILTER_SANITIZE_STRING);
     $pluginName = $this->request->getGet()->filter('_plugin', null, FILTER_SANITIZE_STRING);
     $action = $this->request->getGet()->filter('_action', null, FILTER_SANITIZE_STRING);
     // Load plugins.
     if (!$moduleName) {
         $type = 'SystemPlugin';
         PluginUtil::loadAllSystemPlugins();
     } else {
         $type = 'ModulePlugin';
         PluginUtil::loadAllModulePlugins();
     }
     if ($moduleName) {
         $serviceId = PluginUtil::getServiceId("{$type}_{$moduleName}_{$pluginName}_Plugin");
     } else {
         $serviceId = PluginUtil::getServiceId("{$type}_{$pluginName}_Plugin");
     }
     $this->throwNotFoundUnless($this->serviceManager->hasService($serviceId));
     $this->plugin = $this->serviceManager->getService($serviceId);
     // Sanity checks.
     $this->throwNotFoundUnless($this->plugin->isInstalled(), __f('Plugin "%s" is not installed', $this->plugin->getMetaDisplayName()));
     $this->throwForbiddenUnless($this->plugin instanceof Zikula_Plugin_ConfigurableInterface, __f('Plugin "%s" is not configurable', $this->plugin->getMetaDisplayName()));
     $this->pluginController = $this->plugin->getConfigurationController();
     $this->throwNotFoundUnless($this->pluginController->getReflection()->hasMethod($action));
     return $this->pluginController->{$action}();
 }
Ejemplo n.º 23
0
 function handleCommand(Zikula_Form_View $view, &$args)
 {
     if ($args['commandName'] == 'cancel') {
         $url = ModUtil::url('Scribite', 'admin', 'main');
         return $view->redirect($url);
     } else {
         if ($args['commandName'] == 'restore') {
             $classname = 'ModulePlugin_Scribite_' . $this->editor . '_Plugin';
             if (method_exists($classname, 'getDefaults')) {
                 $defaults = $classname::getDefaults();
                 if (!empty($defaults)) {
                     ModUtil::setVars("moduleplugin.scribite." . strtolower($this->editor), $defaults);
                     LogUtil::registerStatus('Defaults succesfully restored.');
                 }
             }
             return true;
         }
     }
     // check for valid form
     if (!$view->isValid()) {
         return false;
     }
     $data = $view->getValues();
     ModUtil::setVars("moduleplugin.scribite." . strtolower($this->editor), $data);
     LogUtil::registerStatus($this->__('Done! Module configuration updated.'));
     return true;
 }
Ejemplo n.º 24
0
 public function Install() {
     // Checks if module IWmain is installed. If not returns error
     $modid = ModUtil::getIdFromName('IWmain');
     $modinfo = ModUtil::getInfo($modid);
     if ($modinfo['state'] != 3) {
         return LogUtil::registerError($this->$this->__('Module IWmain is needed. You have to install the IWmain module before installing it.'));
     }
     // Check if the version needed is correct
     $versionNeeded = '3.0.0';
     if (!ModUtil::func('IWmain', 'admin', 'checkVersion', array('version' => $versionNeeded))) {
         return false;
     }
     // Create module table
     if (!DBUtil::createTable('IWusers'))
         return false;
     if (!DBUtil::createTable('IWusers_friends'))
         return false;
     // Create the index
     if (!DBUtil::createIndex('iw_uid', 'IWusers', 'uid'))
         return false;
     if (!DBUtil::createIndex('iw_uid', 'IWusers_friends', 'uid'))
         return false;
     if (!DBUtil::createIndex('iw_fid', 'IWusers_friends', 'fid'))
         return false;
     //Create module vars
     $this->setVar('friendsSystemAvailable', 1)
             ->setVar('invisibleGroupsInList', '$')
             ->setVar('usersCanManageName', 0)
             ->setVar('allowUserChangeAvatar', '1')
             ->setVar('allowUserSetTheirSex', '0')
             ->setVar('allowUserDescribeTheirSelves', '1')
             ->setVar('avatarChangeValidationNeeded', '1')
             ->setVar('usersPictureFolder', 'photos');
     return true;
 }
Ejemplo n.º 25
0
/**
 * Check if an array element (subscript) is set.
 *
 * Available attributes:
 *  - array         (array)     an array template variable
 *  - field         (string)    the value of a key in the array specified above
 *  - returnValue   (bool|int)  if set, then the contents of the array element
 *                              $array[$field] is returned if it is set, otherwise false is returned
 *  - assign        (string)    (optional) if provided, a template variable with
 *                              the specified name is set with the return value,
 *                              instead of returning the value to the template
 *
 * Examples:
 *
 *  Return true to the template if the template variable $myarray['arraykey']
 *  is set, otherwise return false to the template:
 *
 *  <samp>{array_field_isset array=$myarray field='arraykey'}</samp>
 *
 *  Return the value of the template variable $myarray['arraykey'] to the
 *  template if it is set, otherwise return false to the template:
 *
 *  <samp>{array_field_isset array=$myarray field='arraykey' returnValue=1}</samp>
 *
 *  Assign true to the template variable $myValue if the template variable
 *  $myarray['arraykey'] is set, otherwise set $myValue to false:
 *
 *  <samp>{array_field_isset array=$myarray field='arraykey' assign='myValue'}</samp>
 *
 *  Assign the value of the template variable $myarray['arraykey'] to the
 *  template variable $myValue if it is set, otherwise assign false to $myValue:
 *
 *  <samp>{array_field_isset array=$myarray field='arraykey' returnValue=1 assign='myValue'}</samp>
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the {@link Zikula_View} object.
 *
 * @return boolean|mixed if returnValue is not set, then returns true if the array
 *                       element is set, otherwise false; if returnValue is set,
 *                       then returns the value of the array element if it is set,
 *                       otherwise false.
 */
function smarty_function_array_field_isset($params, Zikula_View $view)
{
    LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated, please use {%2$s} instead.', array('array_field_isset returnValue=1 ...', 'array_field ...')), E_USER_DEPRECATED);

    $array       = isset($params['array'])       ? $params['array']        : null;
    $field       = isset($params['field'])       ? $params['field']        : null;
    $returnValue = isset($params['returnValue']) ? $params['returnValue']  : null;
    $assign      = isset($params['assign'])      ? $params['assign']       : null;

    if ($array === null) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('array_field_isset', 'array')));
        return false;
    }

    if ($field === null) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('array_field_isset', 'field')));
        return false;
    }

    $result = isset($array[$field]);
    if ($result && $returnValue) {
        $result = $array[$field];
    }

    if ($assign) {
        $view->assign($assign, $result);
    } else {
        return $result;
    }
}
Ejemplo n.º 26
0
    public function initialize(Zikula_Form_View $view)
    {
        $this->pageId = FormUtil::getPassedValue('pid', isset($this->args['pid']) ? $this->args['pid'] : null);

        if (!SecurityUtil::checkPermission('Content:page:', '::', ACCESS_ADD)) {
            throw new Zikula_Exception_Forbidden(LogUtil::getErrorMsgPermission());
        }
        if (!SecurityUtil::checkPermission('Content:page:', $this->pageId . '::', ACCESS_EDIT)) {
            throw new Zikula_Exception_Forbidden(LogUtil::getErrorMsgPermission());
        }

        $page = ModUtil::apiFunc('Content', 'Page', 'getPage', array('id' => $this->pageId, 'filter' => array('checkActive' => false), 'includeContent' => false));
        if ($page === false) {
            throw new Zikula_Exception_Fatal($this->__('Page not found'));
        }

        // Only allow subpages if edit access on parent page
        if (!SecurityUtil::checkPermission('Content:page:', $page['id'] . '::', ACCESS_EDIT)) {
            throw new Zikula_Exception_Forbidden(LogUtil::getErrorMsgPermission());
        }

        PageUtil::setVar('title', $this->__('Clone page') . ' : ' . $page['title']);

        $this->view->assign('page', $page);
        Content_Util::contentAddAccess($this->view, $this->pageId);

        return true;
    }
Ejemplo n.º 27
0
/**
 * Zikula_View function to create  manual link.
 *
 * This function creates a manual link from some parameters.
 *
 * Available parameters:
 *   - manual:    name of manual file, manual.html if not set
 *   - chapter:   an anchor in the manual file to jump to
 *   - newwindow: opens the manual in a new window using javascript
 *   - width:     width of the window if newwindow is set, default 600
 *   - height:    height of the window if newwindow is set, default 400
 *   - title:     name of the new window if newwindow is set, default is modulename
 *   - class:     class for use in the <a> tag
 *   - assign:    if set, the results ( array('url', 'link') are assigned to the corresponding variable instead of printed out
 *
 * Example
 * {manuallink newwindow=1 width=400 height=300 title=rtfm }
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return string|void
 */
function smarty_function_manuallink($params, Zikula_View $view)
{
    LogUtil::log(__f('Warning! Template plugin {%1$s} is deprecated.', array('manuallink')), E_USER_DEPRECATED);
    $userlang = ZLanguage::transformFS(ZLanguage::getLanguageCode());
    $stdlang = System::getVar('language_i18n');
    $title = isset($params['title']) ? $params['title'] : 'Manual';
    $manual = isset($params['manual']) ? $params['manual'] : 'manual.html';
    $chapter = isset($params['chapter']) ? '#' . $params['chapter'] : '';
    $class = isset($params['class']) ? 'class="' . $params['class'] . '"' : '';
    $width = isset($params['width']) ? $params['width'] : 600;
    $height = isset($params['height']) ? $params['height'] : 400;
    $modname = ModUtil::getName();
    $possibleplaces = array("modules/{$modname}/docs/{$userlang}/manual/{$manual}", "modules/{$modname}/docs/{$stdlang}/manual/{$manual}", "modules/{$modname}/docs/en/manual/{$manual}", "modules/{$modname}/docs/{$userlang}/{$manual}", "modules/{$modname}/docs/{$stdlang}/{$manual}", "modules/{$modname}/docs/lang/en/{$manual}");
    foreach ($possibleplaces as $possibleplace) {
        if (file_exists($possibleplace)) {
            $url = $possibleplace . $chapter;
            break;
        }
    }
    if (isset($params['newwindow'])) {
        $link = "<a {$class} href='#' onclick=\"window.open( '" . DataUtil::formatForDisplay($url) . "' , '" . DataUtil::formatForDisplay($modname) . "', 'status=yes,scrollbars=yes,resizable=yes,width={$width},height={$height}'); picwin.focus();\">" . DataUtil::formatForDisplayHTML($title) . "</a>";
    } else {
        $link = "<a {$class} href=\"" . DataUtil::formatForDisplay($url) . "\">" . DataUtil::formatForDisplayHTML($title) . "</a>";
    }
    if (isset($params['assign'])) {
        $ret = array('url' => $url, 'link' => $link);
        $view->assign($params['assign'], $ret);
        return;
    } else {
        return $link;
    }
}
Ejemplo n.º 28
0
 function delete()
 {
     // security check
     if (!SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_ADMIN)) {
         return LogUtil::registerPermissionError();
     }
     $ot = FormUtil::getPassedValue('ot', 'categories', 'GETPOST');
     $id = (int) FormUtil::getPassedValue('id', 0, 'GETPOST');
     $url = ModUtil::url('AddressBook', 'admin', 'view', array('ot' => $ot));
     $class = 'AddressBook_DBObject_' . ucfirst($ot);
     if (!class_exists($class)) {
         return z_exit(__f('Error! Unable to load class [%s]', $ot));
     }
     $object = new $class();
     $data = $object->get($id);
     if (!$data) {
         LogUtil::registerError(__f('%1$s with ID of %2$s doesn\'\\t seem to exist', array($ot, $id)));
         return System::redirect($url);
     }
     $object->delete();
     if ($ot == "customfield") {
         $sql = "ALTER TABLE addressbook_address DROP adr_custom_" . $id;
         try {
             DBUtil::executeSQL($sql, -1, -1, true, true);
         } catch (Exception $e) {
         }
     }
     LogUtil::registerStatus($this->__('Done! Item deleted.'));
     return System::redirect($url);
 }
Ejemplo n.º 29
0
/**
 * Implement permissions checks in a template.
 *
 * Available attributes:
 *  - component (string) The component to be tested, e.g., 'ModuleName::'
 *  - instance  (string) The instance to be tested, e.g., 'name::1'
 *  - level     (int)    The level of access required, e.g., ACCESS_READ
 *
 * Example:
 * <pre>
 * {secauthaction_block component='News::' instance='1::' level=ACCESS_COMMENT}
 *   do some stuff now that we have permission
 * {/secauthaction_block}
 * </pre>.
 *
 * @param array  $params  All attributes passed to this function from the template.
 * @param string $content The content between the block tags.
 * @param Smarty &$smarty Reference to the {@link Zikula_View} object.
 *
 * @return mixed The content of the block, if the user has the specified
 *               access level for the component and instance, otherwise null;
 *               false on an error.
 *
 * @deprecated See {@link smarty_block_securityutil_checkpermission_block}.
 */
function smarty_block_secauthaction_block($params, $content, &$smarty)
{
    LogUtil::log(__f('Warning! Template block {%1$s} is deprecated, please use {%2$s} instead.', array('secauthaction_block', 'checkpermissionblock')), E_USER_DEPRECATED);
    if (is_null($content)) {
        return;
    }

    // check our input
    if (!isset($params['component'])) {
        $smarty->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('smarty_block_secauthaction_block', 'component')));
        return false;
    }
    if (!isset($params['instance'])) {
        $smarty->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('smarty_block_secauthaction_block', 'instance')));
        return false;
    }
    if (!isset($params['level'])) {
        $smarty->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('smarty_block_secauthaction_block', 'level')));
        return false;
    }

    if (!SecurityUtil::checkPermission($params['component'], $params['instance'], constant($params['level']))) {
        return;
    }

    return $content;
}
Ejemplo n.º 30
0
    /**
     * Update the configuration values
     * @author: Sara Arjona Téllez (sarjona@xtec.cat)
     * @params	The config values from the form
     * @return	Thue if success
     */
    public function confupdate($args) {
        $skins = FormUtil::getPassedValue('skins', isset($args['skins']) ? $args['skins'] : null, 'POST');
        $langs = FormUtil::getPassedValue('langs', isset($args['langs']) ? $args['langs'] : null, 'POST');
        $maxdelivers = FormUtil::getPassedValue('maxdelivers', isset($args['maxdelivers']) ? $args['maxdelivers'] : null, 'POST');
        $basedisturl = FormUtil::getPassedValue('basedisturl', isset($args['basedisturl']) ? $args['basedisturl'] : null, 'POST');

        // Security check
        if (!SecurityUtil::checkPermission('IWqv::', "::", ACCESS_ADMIN)) {
            throw new Zikula_Exception_Forbidden();
        }

        // Confirm authorisation code
        $this->checkCsrfToken();

        if (isset($skins))
            ModUtil::setVar('IWqv', 'skins', $skins);
        if (isset($langs))
            ModUtil::setVar('IWqv', 'langs', $langs);
        if (isset($maxdelivers))
            ModUtil::setVar('IWqv', 'maxdelivers', $maxdelivers);
        if (isset($basedisturl))
            ModUtil::setVar('IWqv', 'basedisturl', $basedisturl);

        LogUtil::registerStatus($this->__f('Done! %1$s updated.', $this->__('settings')));
        return System::redirect(ModUtil::url('IWqv', 'admin', 'main'));
    }