Esempio n. 1
0
 /**
  * View list of categories
  *
  * @return Renderer
  */
 public function categoriesList($args)
 {
     $this->throwForbiddenUnless(SecurityUtil::checkPermission('Content:page:', '::', ACCESS_READ), LogUtil::getErrorMsgPermission());
     $mainCategoryId = CategoryRegistryUtil::getRegisteredModuleCategory('Content', 'content_page', $this->getVar('categoryPropPrimary'), 30);
     // 30 == /__SYSTEM__/Modules/Global
     $categories = CategoryUtil::getCategoriesByParentID($mainCategoryId);
     $rootCategory = CategoryUtil::getCategoryByID($mainCategoryId);
     $this->view->assign('rootCategory', $rootCategory);
     $this->view->assign('categories', $categories);
     $this->view->assign('lang', ZLanguage::getLanguageCode());
     // Count the numer of pages in a specific category
     $pagecount = array();
     foreach ($categories as $category) {
         $pagecount[$category['id']] = ModUtil::apiFunc('Content', 'Page', 'getPageCount', array('filter' => array('category' => $category['id'])));
     }
     $this->view->assign('pagecount', $pagecount);
     // Register a page variable breadcrumbs with the Content page hierarchy as array of array(url, title)
     if ((bool) $this->getVar('registerBreadcrumbs', false) === true) {
         // first include self, then loop over parents until root is reached
         $modInfo = $this->getModInfo();
         $breadcrumbs[] = array('url' => ModUtil::url('Content', 'user', 'sitemap'), 'title' => $modInfo['displayname'] . ' ' . $this->__('Categories'));
         PageUtil::registerVar('breadcrumbs', false, $breadcrumbs);
     }
     return $this->view->fetch('user/main.tpl');
 }
Esempio n. 2
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);
    }
Esempio n. 3
0
 /**
  * Setup form.
  *
  * @param Zikula_Form_View $view Current Zikula_Form_View instance.
  *
  * @return boolean
  */
 public function initialize(Zikula_Form_View $view)
 {
     // load and assign registred categories
     $categories = CategoryRegistryUtil::getRegisteredModuleCategories('ExampleDoctrine', 'User', 'id');
     $view->assign('registries', $categories);
     $id = FormUtil::getPassedValue('id', null, "GET", FILTER_SANITIZE_NUMBER_INT);
     if ($id) {
         // load user with id
         $user = $this->entityManager->find('ExampleDoctrine_Entity_User', $id);
         if ($user) {
             // switch to edit mode
             $this->_id = $id;
         } else {
             return LogUtil::registerError($this->__f('User with id %s not found', $id));
         }
     } else {
         $user = new ExampleDoctrine_Entity_User();
     }
     $userData = $user->toArray();
     // overwrite attributes array entry with a form compitable format
     $field1 = $user->getAttributes()->get('field1') ? $user->getAttributes()->get('field1')->getValue() : '';
     $field2 = $user->getAttributes()->get('field2') ? $user->getAttributes()->get('field2')->getValue() : '';
     $userData['attributes'] = array('field1' => $field1, 'field2' => $field2);
     // assign current values to form fields
     $view->assign('user', $user)->assign('meta', $user->getMetadata() != null ? $user->getMetadata()->toArray() : array())->assign($userData);
     $this->_user = $user;
     return true;
 }
Esempio n. 4
0
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->add('title', 'text')->add('urltitle', 'text', array('required' => false, 'label' => __('PermaLink URL title')))->add($builder->create('metadescription', 'textarea', array('required' => false))->addModelTransformer(new NullToEmptyTransformer()))->add($builder->create('metakeywords', 'textarea', array('required' => false))->addModelTransformer(new NullToEmptyTransformer()))->add('content')->add('displaywrapper', 'checkbox', array('required' => false, 'label' => __('Display additional information')))->add('displaytitle', 'checkbox', array('required' => false, 'label' => __('Display page title')))->add('displaycreated', 'checkbox', array('required' => false, 'label' => __('Display page creation date')))->add('displayupdated', 'checkbox', array('required' => false, 'label' => __('Display page update date')))->add('displaytextinfo', 'checkbox', array('required' => false, 'label' => __('Display page text statistics')))->add('displayprint', 'checkbox', array('required' => false, 'label' => __('Display page print link')))->add($builder->create('language', 'choice', array('choices' => \ZLanguage::getInstalledLanguageNames(), 'required' => false, 'placeholder' => __('All')))->addModelTransformer(new NullToEmptyTransformer()))->add('obj_status', 'checkbox', array('required' => false, 'label' => __('Page is active')))->add('save', 'submit', array('label' => 'Create Page'));
     $entityCategoryRegistries = \CategoryRegistryUtil::getRegisteredModuleCategories('ZikulaPagesModule', 'PageEntity', 'id');
     foreach ($entityCategoryRegistries as $registryId => $parentCategoryId) {
         $builder->add('categories', new CategoryType($registryId, $parentCategoryId), array('multiple' => true));
     }
 }
Esempio n. 5
0
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->prependClientTransformer(new CategoriesCollectionTransformer($options['entityCategoryClass']))->addEventSubscriber(new CategoriesMergeCollectionListener());
     $registries = \CategoryRegistryUtil::getRegisteredModuleCategories($options['module'], $options['entity'], 'id');
     foreach ($registries as $registryId => $categoryId) {
         $builder->add('registry_' . $registryId, 'entity', array('class' => 'ZikulaCategoriesModule:CategoryEntity', 'property' => 'name', 'query_builder' => function (EntityRepository $repo) use($categoryId) {
             //TODO: (move to)/use own entity repository after CategoryUtil migration
             return $repo->createQueryBuilder('e')->where('e.parent = :parentId')->setParameter('parentId', (int) $categoryId);
         }));
     }
 }
Esempio n. 6
0
 public function initialize(Zikula_Form_View $view)
 {
     $this->pageId = (int) FormUtil::getPassedValue('pid', isset($this->args['pid']) ? $this->args['pid'] : -1);
     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' => true, 'filter' => array('checkActive' => false), 'enableEscape' => false, 'translate' => false, 'includeContent' => true, 'includeCategories' => true));
     if ($page === false) {
         return $this->view->registerError(null);
     }
     // load the category registry util
     $mainCategory = CategoryRegistryUtil::getRegisteredModuleCategory('Content', 'content_page', $this->getVar('categoryPropPrimary'), 30);
     $secondCategory = CategoryRegistryUtil::getRegisteredModuleCategory('Content', 'content_page', $this->getVar('categoryPropSecondary'));
     $multilingual = ModUtil::getVar(ModUtil::CONFIG_MODULE, 'multilingual');
     if ($page['language'] == ZLanguage::getLanguageCode()) {
         $multilingual = false;
     }
     PageUtil::setVar('title', $this->__("Edit page") . ' : ' . $page['title']);
     $pagelayout = ModUtil::apiFunc('Content', 'Layout', 'getLayout', array('layout' => $page['layout']));
     if ($pagelayout === false) {
         return $this->view->registerError(null);
     }
     $layouts = ModUtil::apiFunc('Content', 'Layout', 'getLayouts');
     if ($layouts === false) {
         return $this->view->registerError(null);
     }
     $layoutTemplate = $page['layoutEditTemplate'];
     $this->view->assign('layoutTemplate', $layoutTemplate);
     $this->view->assign('mainCategory', $mainCategory);
     $this->view->assign('secondCategory', $secondCategory);
     $this->view->assign('page', $page);
     $this->view->assign('multilingual', $multilingual);
     $this->view->assign('layouts', $layouts);
     $this->view->assign('pagelayout', $pagelayout);
     $this->view->assign('enableVersioning', $this->getVar('enableVersioning'));
     $this->view->assign('categoryUsage', $this->getVar('categoryUsage'));
     Content_Util::contentAddAccess($this->view, $this->pageId);
     if (!$this->view->isPostBack() && FormUtil::getPassedValue('back', 0)) {
         $this->backref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
     }
     if ($this->backref != null) {
         $returnUrl = $this->backref;
     } else {
         $returnUrl = ModUtil::url('Content', 'admin', 'main');
     }
     ModUtil::apiFunc('PageLock', 'user', 'pageLock', array('lockName' => "contentPage{$this->pageId}", 'returnUrl' => $returnUrl));
     return true;
 }
Esempio n. 7
0
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if (empty($options['entityCategoryClass']) || empty($options['module']) || empty($options['entity'])) {
         throw new \InvalidArgumentException('empty argument!');
     }
     $registries = \CategoryRegistryUtil::getRegisteredModuleCategories($options['module'], $options['entity'], 'id');
     foreach ($registries as $registryId => $categoryId) {
         $builder->add('registry_' . $registryId, 'entity', ['required' => $options['required'], 'multiple' => $options['multiple'], 'class' => 'ZikulaCategoriesModule:CategoryEntity', 'property' => 'name', 'query_builder' => function (EntityRepository $repo) use($categoryId) {
             //TODO: (move to)/use own entity repository after CategoryUtil migration
             return $repo->createQueryBuilder('e')->where('e.parent = :parentId')->setParameter('parentId', (int) $categoryId);
         }]);
     }
     $builder->addViewTransformer(new CategoriesCollectionTransformer($options), true);
     $builder->addEventSubscriber(new CategoriesMergeCollectionListener());
 }
Esempio n. 8
0
 /**
  * import the categories provided
  */
 private function importCategories()
 {
     $rootCatId = CategoryRegistryUtil::getRegisteredModuleCategory('Content', 'content_page', ModUtil::getVar('Content', 'categoryPropPrimary'));
     $rootCatObj = CategoryUtil::getCategoryById($rootCatId);
     $this->categoryPathMap[$this->rootCategoryLocalId] = $rootCatObj['path'];
     $this->categoryMap[$this->rootCategoryLocalId] = (int) $rootCatId;
     $oldCategories = $this->getCategories();
     foreach ($oldCategories as $oldCategory) {
         if (isset($this->categoryPathMap[$oldCategory['pid']])) {
             $id = CategoryUtil::createCategory($this->categoryPathMap[$oldCategory['pid']], $oldCategory['title'], null, $oldCategory['title'], $oldCategory['title']);
             $catObj = CategoryUtil::getCategoryById($id);
             $this->categoryPathMap[$oldCategory['id']] = $catObj['path'];
             $this->categoryMap[$oldCategory['id']] = (int) $id;
         }
     }
 }
Esempio n. 9
0
 public function prepare(&$groups)
 {
     if (!self::$filter) {
         $filter = array('__META__' => array('module' => 'TimeIt'));
         $items = $this->getItems($groups);
         // load the categories system
         if (!($class = Loader::loadClass('CategoryRegistryUtil'))) {
             z_exit('Unable to load class [CategoryRegistryUtil] ...');
         }
         $properties = CategoryRegistryUtil::getRegisteredModuleCategories('TimeIt', 'TimeIt_events');
         foreach ($properties as $prop => $catid) {
             $filter[$prop] = $items;
         }
         self::$filter = DBUtil::generateCategoryFilterWhere('TimeIt_events', false, $filter);
     }
 }
Esempio n. 10
0
    /**
     * View list of categories
     *
     * @return Renderer
     */
    public function categories($args)
    {
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('Content:page:', '::', ACCESS_READ), LogUtil::getErrorMsgPermission());

        $mainCategoryId = CategoryRegistryUtil::getRegisteredModuleCategory('Content', 'content_page', $this->getVar('categoryPropPrimary'), 30); // 30 == /__SYSTEM__/Modules/Global
        $categories = CategoryUtil::getCategoriesByParentID($mainCategoryId);
        $rootCategory = CategoryUtil::getCategoryByID($mainCategoryId);

        $this->view->assign('rootCategory', $rootCategory);
        $this->view->assign('categories', $categories);
        $this->view->assign('lang', ZLanguage::getLanguageCode());
        
        // Count the numer of pages in a specific category
        $pagecount = array();
        foreach ($categories as $category) {
            $pagecount[$category['id']] = ModUtil::apiFunc('Content', 'Page', 'getPageCount', array ('filter' => array('category' => $category['id'])));
        }
        $this->view->assign('pagecount', $pagecount);
        
        return $this->view->fetch('user/main.tpl');
    }
Esempio n. 11
0
 /**
  * modify block settings
  *
  * @author       The Zikula Development Team
  * @param        array       $blockinfo     a blockinfo structure
  * @return       output      the bock form
  */
 public function modify($blockinfo)
 {
     // Get current content
     $vars = BlockUtil::varsFromContent($blockinfo['content']);
     // Defaults
     if (!isset($vars['hourfrom'])) {
         $vars['hourfrom'] = -1;
     }
     if (!isset($vars['hourto'])) {
         $vars['hourto'] = -1;
     }
     if (!isset($vars['monfrom'])) {
         $vars['monfrom'] = -1;
     }
     if (!isset($vars['monto'])) {
         $vars['monto'] = -1;
     }
     if (!isset($vars['mdayfrom'])) {
         $vars['mdayfrom'] = -1;
     }
     if (!isset($vars['mdayto'])) {
         $vars['mdayto'] = -1;
     }
     if (!isset($vars['wdayfrom'])) {
         $vars['wdayfrom'] = -1;
     }
     if (!isset($vars['wdayto'])) {
         $vars['wdayto'] = -1;
     }
     if (!isset($vars['cache_time'])) {
         $vars['cache_time'] = 120;
     }
     if (!isset($vars['cache_dir'])) {
         $vars['cache_dir'] = 'any_cache';
     }
     if (!isset($vars['ballooncolor'])) {
         $vars['ballooncolor'] = 'grey';
     }
     $ballooncolor = $vars['ballooncolor'];
     $this->view->assign('balloonselected' . $ballooncolor, 'selected="selected"');
     if (!isset($vars['enablefacebookshare'])) {
         $vars['enablefacebookshare'] = false;
     }
     // Create output object
     $this->view->caching = false;
     // Select categories only if enabled for the module
     $enablecategorization = ModUtil::getVar($this->name, 'enablecategorization');
     if ($enablecategorization) {
         // load the categories system
         if (!Loader::loadClass('CategoryRegistryUtil')) {
             return LogUtil::registerError(__f('Error! Could not load [%s] class.'), 'CategoryRegistryUtil');
         }
         // Get the registrered categories for the module
         $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories($this->name, 'quotes');
         $this->view->assign('catregistry', $catregistry);
     }
     $this->view->assign('enablecategorization', $enablecategorization);
     $this->view->assign($vars);
     // assign the block vars
     if (!isset($vars['category']) || !is_array($vars['category'])) {
         $vars['category'] = array();
     }
     $this->view->assign('category', $vars['category']);
     $this->view->assign('hours', range(0, 23));
     $this->view->assign('months', range(1, 12));
     $this->view->assign('wdays', range(1, 7));
     $this->view->assign('mdays', range(1, 31));
     // return the output
     return $this->view->fetch('quotes_block_quote_modify.tpl');
 }
Esempio n. 12
0
    /**
     * display available categories in News
     *
     * @author Erik Spaan [espaan]
     * @return string HTML string
     */
    public function categorylist($args)
    {
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('News::', '::', ACCESS_OVERVIEW), LogUtil::getErrorMsgPermission());

        $enablecategorization = $this->getVar('enablecategorization');
        if (UserUtil::isLoggedIn()) {
            $uid = UserUtil::getVar('uid');
        } else {
            $uid = 0;
        }

        if ($enablecategorization) {
            // Get the categories registered for News
            $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('News', 'news');
            $properties = array_keys($catregistry);
            $propertiesdata = array();
            foreach ($properties as $property) {
                $rootcat = CategoryUtil::getCategoryByID($catregistry[$property]);
                if (!empty($rootcat)) {
                    $rootcat['path'] .= '/';
                    // Get all categories in this category property
                    $catcount = $this->_countcategories($rootcat, $property, $catregistry, $uid);
                    $rootcat['news_articlecount'] = $catcount['category']['news_articlecount'];
                    $rootcat['news_totalarticlecount'] = $catcount['category']['news_totalarticlecount'];
                    $rootcat['news_yourarticlecount'] = $catcount['category']['news_yourarticlecount'];
                    $rootcat['subcategories'] = $catcount['subcategories'];
                    // Store data per property for listing in the overview
                    $propertiesdata[] = array('name' => $property,
                        'category' => $rootcat);
                }
            }
            // Assign property & category related vars
            $this->view->assign('propertiesdata', $propertiesdata);
        }

        // Assign the config vars
        $this->view->assign('enablecategorization', $enablecategorization);
        $this->view->assign('shorturls', System::getVar('shorturls', false));
        $this->view->assign('lang', ZLanguage::getLanguageCode());
        $this->view->assign('catimagepath', $this->getVar('catimagepath'));

        // Return the output that has been generated by this function
        return $this->view->fetch('user/categorylist.tpl');
    }
Esempio n. 13
0
    /**
     * display item
     *
     * @param $args array Arguments array.
     *
     * @return string html string
     */
    public function display($args)
    {
        $pageid   = FormUtil::getPassedValue('pageid', isset($args['pageid']) ? $args['pageid'] : null, 'REQUEST');
        $title    = FormUtil::getPassedValue('title', isset($args['title']) ? $args['title'] : null, 'REQUEST');
        $page     = FormUtil::getPassedValue('page', isset($args['page']) ? $args['page'] : null, 'REQUEST');
        $objectid = FormUtil::getPassedValue('objectid', isset($args['objectid']) ? $args['objectid'] : null, 'REQUEST');
        if (!empty($objectid)) {
            $pageid = $objectid;
        }

        // Validate the essential parameters
        if ((empty($pageid) || !is_numeric($pageid)) && empty($title)) {
            return LogUtil::registerArgsError();
        }
        if (!empty($title)) {
            unset($pageid);
        }

        // Set the default page number
        if (empty($page) || $page < 1 || !is_numeric($page)) {
            $page = 1;
        }

        $accesslevel = ACCESS_READ;
        if (SecurityUtil::checkPermission('Pages::', "::", ACCESS_COMMENT)) {
            $accesslevel = ACCESS_COMMENT;
        }
        if (SecurityUtil::checkPermission('Pages::', "::", ACCESS_EDIT)) {
            $accesslevel = ACCESS_EDIT;
        }

        // Regardless of caching, we need to increment the read count and set the cache ID
        if (isset($pageid)) {
            $this->view->setCacheId($pageid.'|'.$page.'_a'.$accesslevel);
            $incrementresult = ModUtil::apiFunc('Pages', 'user', 'incrementreadcount', array('pageid' => $pageid));
        } else {
            $this->view->setCacheId($title.'|'.$page.'_a'.$accesslevel);
            $incrementresult = ModUtil::apiFunc('Pages', 'user', 'incrementreadcount', array('title' => $title));
        }
        if ($incrementresult === false) {
            return LogUtil::registerError($this->__('No such page found.'), 404);
        }

        // get the categories registered for the Pages
        $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('Pages', 'pages');

        // Get the page
        if (isset($pageid)) {
            $params = array('pageid' => $pageid, 'catregistry' => (isset($catregistry)) ? $catregistry : null);
            $item = ModUtil::apiFunc('Pages', 'user', 'get', $params);
        } else {
            $params = array('title' => $title, 'catregistry' => (isset($catregistry)) ? $catregistry : null);
            $item = ModUtil::apiFunc('Pages', 'user', 'get', $params);
            System::queryStringSetVar('pageid', $item['pageid']);
            $pageid = $item['pageid'];
        }
        
        // determine which template to render this page with
        // A specific template may exist for this page (based on page id)
        if (isset($pageid) && $this->view->template_exists('user/display_' . $pageid . '.tpl')) {
            $template = 'user/display_' . $pageid . '.tpl';
        } else {
            $template = 'user/display.tpl';
        }

        // check if the contents are cached.
        if ($this->view->is_cached($template)) {
            return $this->view->fetch($template);
        }

        // The return value of the function is checked here
        if ($item === false) {
            return LogUtil::registerError($this->__('No such page found.'), 404);
        }

        // Explode the review into an array of seperate pages
        $allpages = explode('<!--pagebreak-->', $item['content'] );

        // validates that the requested page exists
        if (!isset($allpages[$page-1])) {
            return LogUtil::registerError($this->__('No such page found.'), 404);
        }

        // Set the item bodytext to be the required page
        // nb arrays start from zero pages from one
        $item['content'] = trim($allpages[$page-1]);
        $numitems = count($allpages);
        unset($allpages);

        // Display Admin Edit Link
        if (SecurityUtil::checkPermission('Pages::Page', "{$item['title']}::{$item['pageid']}", ACCESS_EDIT)) {
            $item['displayeditlink'] = true;
        } else {
            $item['displayeditlink'] = false;                
        }

        // Assign details of the item.
        $this->view->assign('item', $item);

        $this->view->assign('lang', ZLanguage::getLanguageCode());

        // Now lets assign the informatation to create a pager for the review
        $pager =  array('numitems' => $numitems, 'itemsperpage' => 1);
        $this->view->assign('pager', $pager);

        return $this->view->fetch($template);
    }
Esempio n. 14
0
    /**
     * get a specific item
     * @author Mark West
     * @param $args['sid'] id of news item to get
     * @return mixed item array, or false on failure
     */
    public function get($args)
    {
        // optional arguments
        if (isset($args['objectid'])) {
            $args['sid'] = $args['objectid'];
        }

        // Argument check
        if ((!isset($args['sid']) || !is_numeric($args['sid'])) &&
                !isset($args['title'])) {
            return LogUtil::registerArgsError();
        }

        // Check for caching of the DBUtil calls (needed for AJAX editing)
        if (!isset($args['SQLcache'])) {
            $args['SQLcache'] = true;
        }

        // form a date using some ofif present...
        // step 1 - convert month name into
        if (isset($args['monthname']) && !empty($args['monthname'])) {
            $months = explode(' ', $this->__('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'));
            $keys = array_flip($months);
            $args['monthnum'] = $keys[ucfirst($args['monthname'])] + 1;
        }

        // step 2 - convert to a timestamp and back to a db format
        if (isset($args['year']) && !empty($args['year']) && isset($args['monthnum']) &&
                !empty($args['monthnum']) && isset($args['day']) && !empty($args['day'])) {
            // use PHP strftime directly, since DateUtil translates dateformat strings, which is not ok in this case
            $timestring = strftime('%Y-%m-%d', mktime(0, 0, 0, $args['monthnum'], $args['day'], $args['year']));
        }

        $permFilter = array();
        $permFilter[] = array('realm' => 0,
                'component_left'   => 'News',
                'component_middle' => '',
                'component_right'  => '',
                'instance_left'    => 'cr_uid',
                'instance_middle'  => '',
                'instance_right'   => 'sid',
                'level'            => ACCESS_READ);

        if (isset($args['sid']) && is_numeric($args['sid'])) {
            $item = DBUtil::selectObjectByID('news', $args['sid'], 'sid', null, $permFilter, null, $args['SQLcache']);
        } elseif (isset($timestring)) {
            $tables = DBUtil::getTables();
            $col = $tables['news_column'];
            $where = "{$col['urltitle']} = '".DataUtil::formatForStore($args['title'])."' AND {$col['from']} LIKE '{$timestring}%'";
            $item = DBUtil::selectObject('news', $where, null, $permFilter, null, $args['SQLcache']);
        } else {
            $item = DBUtil::selectObjectByID('news', $args['title'], 'urltitle', null, $permFilter, null, $args['SQLcache']);
        }

        if (empty($item))
            return false;

        // Sanity check for the published status if required
        if (isset($args['status'])) {
            if ($item['published_status'] != $args['status']) {
                return false;
            }
        }
        
        // process the relative paths of the categories
        if ($this->getVar('enablecategorization') && !empty($item['__CATEGORIES__'])) {
            static $registeredCats;
            if (!isset($registeredCats)) {
                $registeredCats  = CategoryRegistryUtil::getRegisteredModuleCategories('News', 'news');
            }
            ObjectUtil::postProcessExpandedObjectCategories($item['__CATEGORIES__'], $registeredCats);
            if (!CategoryUtil::hasCategoryAccess($item['__CATEGORIES__'], 'News')) {
                return false;
            }
        }

        return $item;
    }
/**
 * Category selector.
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return string
 */
function smarty_function_selector_category($params, Zikula_View $view)
{
    $categoryRegistryModule = isset($params['categoryRegistryModule']) ? $params['categoryRegistryModule'] : '';
    $categoryRegistryTable = isset($params['categoryRegistryTable']) ? $params['categoryRegistryTable'] : '';
    $categoryRegistryProperty = isset($params['categoryRegistryProperty']) ? $params['categoryRegistryProperty'] : '';
    $category = isset($params['category']) ? $params['category'] : 0;
    $path = isset($params['path']) ? $params['path'] : '';
    $pathfield = isset($params['pathfield']) ? $params['pathfield'] : 'path';
    $field = isset($params['field']) ? $params['field'] : 'id';
    $fieldIsAttribute = isset($params['fieldIsAttribute']) ? $params['fieldIsAttribute'] : null;
    $selectedValue = isset($params['selectedValue']) ? $params['selectedValue'] : 0;
    $defaultValue = isset($params['defaultValue']) ? $params['defaultValue'] : 0;
    $defaultText = isset($params['defaultText']) ? $params['defaultText'] : '';
    $allValue = isset($params['allValue']) ? $params['allValue'] : 0;
    $allText = isset($params['allText']) ? $params['allText'] : '';
    $name = isset($params['name']) ? $params['name'] : 'defaultselectorname';
    $submit = isset($params['submit']) ? $params['submit'] : false;
    $recurse = isset($params['recurse']) ? $params['recurse'] : true;
    $relative = isset($params['relative']) ? $params['relative'] : true;
    $includeRoot = isset($params['includeRoot']) ? $params['includeRoot'] : false;
    $includeLeaf = isset($params['includeLeaf']) ? $params['includeLeaf'] : true;
    $all = isset($params['all']) ? $params['all'] : false;
    $displayPath = isset($params['displayPath']) ? $params['displayPath'] : false;
    $attributes = isset($params['attributes']) ? $params['attributes'] : null;
    $assign = isset($params['assign']) ? $params['assign'] : null;
    $editLink = isset($params['editLink']) ? $params['editLink'] : true;
    $multipleSize = isset($params['multipleSize']) ? $params['multipleSize'] : 1;
    $sortField = isset($params['sortField']) ? $params['sortField'] : 'sort_value';
    $doReplaceRootCat = isset($params['doReplaceRootCat']) ? $params['doReplaceRootCat'] : null;
    $cssClass = isset($params['cssClass']) ? $params['cssClass'] : '';
    if (isset($params['lang'])) {
        $lang = $params['lang'];
        $oldLocale = ZLanguage::getLocale();
        ZLanguage::setLocale($lang);
    } else {
        $lang = ZLanguage::getLanguageCode();
    }
    if (!$category && !$path && $categoryRegistryModule && $categoryRegistryTable && $categoryRegistryProperty) {
        $category = CategoryRegistryUtil::getRegisteredModuleCategory($categoryRegistryModule, $categoryRegistryTable, $categoryRegistryProperty);
    }
    // if we don't have a category-id we see if we can get a category by path
    if (!$category && $path) {
        $category = CategoryUtil::getCategoryByPath($path, $pathfield);
    } elseif (is_numeric($category)) {
        // check if we have a numeric category
        $category = CategoryUtil::getCategoryByID($category);
    } elseif (is_string($category) && strpos($category, '/') === 0) {
        // check if we have a string/path category
        $category = CategoryUtil::getCategoryByPath($category, $pathfield);
    }
    static $catCache;
    if (!$catCache) {
        $catCache = array();
    }
    $cacheKey = "{$category['id']}||{$recurse}|{$relative}|{$includeRoot}|{$includeLeaf}|{$all}|||{$attributes}|{$sortField}";
    if (!isset($catCache[$cacheKey])) {
        $catCache[$cacheKey] = CategoryUtil::getSubCategoriesForCategory($category, $recurse, $relative, $includeRoot, $includeLeaf, $all, '', '', $attributes, $sortField);
    }
    $html = CategoryUtil::getSelector_Categories($catCache[$cacheKey], $field, $selectedValue, $name, $defaultValue, $defaultText, $allValue, $allText, $submit, $displayPath, $doReplaceRootCat, $multipleSize, $fieldIsAttribute, $cssClass, $lang);
    if ($editLink && !empty($category) && SecurityUtil::checkPermission('ZikulaCategoriesModule::', "{$category['id']}::", ACCESS_EDIT)) {
        $url = DataUtil::formatForDisplay(ModUtil::url('ZikulaCategoriesModule', 'user', 'edit', array('dr' => $category['id'])));
        $html .= "&nbsp;&nbsp;<a href=\"{$url}\"><img src=\"" . System::getBaseUrl() . "images/icons/extrasmall/xedit.png\" title=\"" . __('Edit sub-category') . '" alt="' . __('Edit sub-category') . '" /></a>';
    }
    if (isset($params['lang'])) {
        // Reset language again.
        ZLanguage::setLocale($oldLocale);
    }
    if ($assign) {
        $view->assign($assign, $html);
    } else {
        return $html;
    }
}
Esempio n. 16
0
    /**
     * view items
     *
     * @param int $startnum the start item id for the pager
     * @return string HTML output
     */
    public function view($args)
    {
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('Pages::', '::', ACCESS_EDIT), LogUtil::getErrorMsgPermission());

        // initialize sort array - used to display sort classes and urls
        $sort = array();
        $fields = array('pageid', 'title', 'cr_date'); // possible sort fields
        foreach ($fields as $field) {
            $sort['class'][$field] = 'z-order-unsorted'; // default values
        }
        
        // Get parameters from whatever input we need.
        $startnum = (int)FormUtil::getPassedValue('startnum', isset($args['startnum']) ? $args['startnum'] : null, 'GETPOST');
        $language = FormUtil::getPassedValue('language', isset($args['language']) ? $args['language'] : null, 'POST');
        $purge = FormUtil::getPassedValue('purge', false, 'GET');
        $orderby = FormUtil::getPassedValue('orderby', isset($args['orderby']) ? $args['orderby'] : 'pageid', 'GETPOST');
        $original_sdir = FormUtil::getPassedValue('sdir', isset($args['sdir']) ? $args['sdir'] : 1, 'GETPOST');

        $this->view->assign('startnum', $startnum);
        $this->view->assign('orderby', $orderby);
        $this->view->assign('sdir', $original_sdir);

        $sdir = $original_sdir ? 0 : 1; //if true change to false, if false change to true
        // change class for selected 'orderby' field to asc/desc
        if ($sdir == 0) {
            $sort['class'][$orderby] = 'z-order-desc';
            $orderdir = 'DESC';
        }
        if ($sdir == 1) {
            $sort['class'][$orderby] = 'z-order-asc';
            $orderdir = 'ASC';
        }
        $filtercats = FormUtil::getPassedValue('pages', null, 'GETPOST');
        $filtercats_serialized = FormUtil::getPassedValue('filtercats_serialized', false, 'GET');
        $filtercats = $filtercats_serialized ? unserialize($filtercats_serialized) : $filtercats;
        $catsarray = Pages_Util::formatCategoryFilter($filtercats);

        // complete initialization of sort array, adding urls
        foreach ($fields as $field) {
            $sort['url'][$field] = ModUtil::url('Pages', 'admin', 'view', array(
                'language' => $language,
                'filtercats_serialized' => serialize($filtercats),
                'orderby' => $field,
                'sdir' => $sdir));
        }
        $this->view->assign('sort', $sort);

        $this->view->assign('filter_active', (empty($language) && empty($catsarray)) ? false : true);

        if ($purge) {
            if (ModUtil::apiFunc('Pages', 'admin', 'purgepermalinks')) {
                LogUtil::registerStatus($this->__('Purging of the pemalinks was successful'));
            } else {
                LogUtil::registerError($this->__('Purging of the pemalinks has failed'));
            }
            return System::redirect(strpos(System::serverGetVar('HTTP_REFERER'), 'purge') ? ModUtil::url('Pages', 'admin', 'view') : System::serverGetVar('HTTP_REFERER'));
        }

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

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

        $multilingual = System::getVar('multilingual', false);

        // Get all matching pages
        $items = ModUtil::apiFunc('Pages', 'user', 'getall',
                array('startnum' => $startnum,
                'numitems' => $modvars['itemsperpage'],
                'order'    => $orderby,
                'orderdir' => $orderdir,
                'ignoreml' => ($multilingual ? false : true),
                'language' => $language,
                'category' => null,
                'catfilter' => isset($catsarray) ? $catsarray : null,
                'catregistry'  => isset($catregistry) ? $catregistry : null));

        if (!$items) {
            $items = array();
        }

        $pages = array();
        foreach ($items as $key => $item)
        {
            $options = array();
            $options[] = array('url'   => ModUtil::url('Pages', 'user', 'display', array('pageid' => $item['pageid'])),
                    'image' => 'kview.png',
                    'title' => $this->__('View'));

            if (SecurityUtil::checkPermission('Pages::', "$item[title]::$item[pageid]", ACCESS_EDIT)) {
                $options[] = array('url'   => ModUtil::url('Pages', 'admin', 'modify', array('pageid' => $item['pageid'])),
                        'image' => 'xedit.png',
                        'title' => $this->__('Edit'));

                if (SecurityUtil::checkPermission('Pages::', "$item[title]::$item[pageid]", ACCESS_DELETE)) {
                    $options[] = array('url'   => ModUtil::url('Pages', 'admin', 'delete', array('pageid' => $item['pageid'])),
                            'image' => '14_layer_deletelayer.png',
                            'title' => $this->__('Delete'));
                }
            }

            // Add the calculated menu options to the item array
            $item['options'] = $options;
            $pages[] = $item;
        }

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

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

        // Assign the information required to create the pager
        $this->view->assign('pager', array(
            'numitems' => ModUtil::apiFunc('Pages', 'user', 'countitems', array('catfilter' => isset($catsarray) ? $catsarray : null)),
            'itemsperpage' => $modvars['itemsperpage']));

        $selectedcategories = array();
        if (is_array($filtercats)) {
            $catsarray = $filtercats['__CATEGORIES__'];
            foreach ($catsarray as $propname => $propid) {
                if ($propid > 0) {
                    $selectedcategories[$propname] = $propid; // removes categories set to 'all'
                }
            }
        }
        $this->view->assign('selectedcategories', $selectedcategories);
        
        // Return the output that has been generated by this function
        return $this->view->fetch('admin/view.tpl');
    }
Esempio n. 17
0
    /**
     * view items
     */
    public function view($args)
    {
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('Feeds::', "::", ACCESS_EDIT), LogUtil::getErrorMsgPermission());

        $startnum = FormUtil::getPassedValue('startnum', isset($args['startnum']) ? $args['startnum'] : null, 'GET');
        $property = FormUtil::getPassedValue('feeds_property', isset($args['feeds_property']) ? $args['feeds_property'] : null, 'POST');
        $category = FormUtil::getPassedValue("feeds_{$property}_category", isset($args["feeds_{$property}_category"]) ? $args["feeds_{$property}_category"] : null, 'POST');
        $clear = FormUtil::getPassedValue('clear', false, 'POST');
        $purge = FormUtil::getPassedValue('purge', false, 'GET');

        if (!PluginUtil::isAvailable('systemplugin.simplepie')) {
            LogUtil::registerError($this->__('<strong>Fatal error: The required SimplePie system plugin is not available.</strong><br /><br />Zikula ships with the SimplePie plugin located in the docs/examples/plugins/ExampleSystemPlugin/SimplePie directory. It must be copied (or symlinked) from there and pasted into the /plugins directory. The plugin must then be installed. This is done via the Extensions module. Click on the System Plugins menu item and install the SimplePie plugin.'));
        }

        if ($purge) {
            if (ModUtil::apiFunc('Feeds', 'admin', 'purgepermalinks')) {
                LogUtil::registerStatus($this->__('Purging of the pemalinks was successful'));
            } else {
                LogUtil::registerError($this->__('Purging of the pemalinks has failed'));
            }
            return System::redirect(strpos(System::serverGetVar('HTTP_REFERER'), 'purge') ? ModUtil::url('Feeds', 'admin', 'view') : System::serverGetVar('HTTP_REFERER'));
        }
        if ($clear) {
            $property = null;
            $category = null;
        }

        // get module vars for later use
        $modvars = ModUtil::getVar('Feeds');

        if ($modvars['enablecategorization']) {
            // load the category registry util
            $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('Feeds', 'feeds');
            $properties = array_keys($catregistry);

            // Validate and build the category filter - mateo
            if (!empty($property) && in_array($property, $properties) && !empty($category)) {
                $catFilter = array($property => $category);
            }

            // Assign a default property - mateo
            if (empty($property) || !in_array($property, $properties)) {
                $property = $properties[0];
            }

            // plan ahead for ML features
            $propArray = array();
            foreach ($properties as $prop) {
                $propArray[$prop] = $prop;
            }
        }

        // Get all the feeds
        $items = ModUtil::apiFunc('Feeds', 'user', 'getall', array('startnum' => $startnum,
                    'numitems' => $modvars['itemsperpage'],
                    'order' => 'fid',
                    'category' => isset($catFilter) ? $catFilter : null,
                    'catregistry' => isset($catregistry) ? $catregistry : null));

        $feedsitems = array();
        foreach ($items as $item) {
            if (SecurityUtil::checkPermission('Feeds::', "$item[name]::$item[fid]", ACCESS_READ)) {
                // Options for the item
                $options = array();

                if (SecurityUtil::checkPermission('Feeds::', "$item[name]::$item[fid]", ACCESS_EDIT)) {
                    $options[] = array('url' => ModUtil::url('Feeds', 'user', 'display', array('fid' => $item['fid'])),
                        'image' => 'kview.png',
                        'title' => $this->__('View'));

                    $options[] = array('url' => ModUtil::url('Feeds', 'admin', 'modify', array('fid' => $item['fid'])),
                        'image' => 'xedit.png',
                        'title' => $this->__('Edit'));

                    if (SecurityUtil::checkPermission('Feeds::', "$item[name]::$item[fid]", ACCESS_DELETE)) {
                        $options[] = array('url' => ModUtil::url('Feeds', 'admin', 'delete', array('fid' => $item['fid'])),
                            'image' => '14_layer_deletelayer.png',
                            'title' => $this->__('Delete'));
                    }
                }
                $item['options'] = $options;
                $feedsitems[] = $item;
            }
        }

        // Assign the items and modvars to the template
        $this->view->assign('feedsitems', $feedsitems);
        $this->view->assign($modvars);

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

        // Assign the categories information if enabled
        if ($modvars['enablecategorization']) {
            $this->view->assign('catregistry', $catregistry);
            $this->view->assign('numproperties', count($propArray));
            $this->view->assign('properties', $propArray);
            $this->view->assign('property', $property);
            $this->view->assign("category", $category);
        }

        // Assign the values for the smarty plugin to produce a pager
        $this->view->assign('pager', array('numitems' => ModUtil::apiFunc('Feeds', 'user', 'countitems', array('category' => isset($catFilter) ? $catFilter : null)),
            'itemsperpage' => $modvars['itemsperpage']));

        // Return the output that has been generated by this function
        return $this->view->fetch('admin/view.tpl');
    }
Esempio n. 18
0
    /**
     * modify block settings
     *
     * @author       The Zikula Development Team
     * @param        array       $blockinfo     a blockinfo structure
     * @return       output      the bock form
     */
    public function modify($blockinfo)
    {
        // Break out options from our content field
        $vars = BlockUtil::varsFromContent($blockinfo['content']);

        // Defaults
        if (empty($vars['storiestype'])) {
            $vars['storiestype'] = 2;
        }
        if (empty($vars['limit'])) {
            $vars['limit'] = 10;
        }
        if (empty($vars['category'])) {
            $vars['category'] = null;
        }

        // Create output object
        $this->view->setCaching(false);

        $mainCat = CategoryRegistryUtil::getRegisteredModuleCategory('News', 'news', 'Main', 30); // 30 == /__SYSTEM__/Modules/Global
        $this->view->assign('mainCategory', $mainCat);
        $this->view->assign('category', $vars['category']);
        $this->view->assign(ModUtil::getVar('News'));

        // assign the block vars
        $this->view->assign($vars);

        $this->view->assign('dom');

        // Return the output that has been generated by this function
        return $this->view->fetch('block/stories_modify.tpl');
    }
Esempio n. 19
0
 /**
  * Displays all available events.
  *
  * @return string HTML Code
  */
 public function view()
 {
     // check object type
     $objectType = FormUtil::getPassedValue('ot', 'event', 'GET');
     $this->throwNotFoundUnless(in_array($objectType, TimeIt_Util::getObjectTypes('view')), $this->__f('Unkown object type %s.', DataUtil::formatForDisplay($objectType)));
     // load filter
     $filter = TimeIt_Filter_Container::getFilterFormGETPOST($objectType);
     $this->view->assign('modvars', ModUtil::getVar('TimeIt'));
     // vars
     $tpl = null;
     $theme = null;
     $domain = $this->serviceManager->getService('timeit.manager.' . $objectType);
     // load the data
     if ($objectType == 'event') {
         $calendarId = (int) FormUtil::getPassedValue('cid', ModUtil::getVar('TimeIt', 'defaultCalendar'), 'GETPOST');
         $calendar = $this->serviceManager->getService('timeit.manager.calendar')->getObject($calendarId);
         $this->throwNotFoundIf(empty($calendar), $this->__f('Calendar [%s] not found.', $calendarId));
         $year = (int) FormUtil::getPassedValue('year', date("Y"), 'GETPOST');
         $month = (int) FormUtil::getPassedValue('month', date("n"), 'GETPOST');
         $day = (int) FormUtil::getPassedValue('day', date("j"), 'GETPOST');
         $tpl = FormUtil::getPassedValue('viewType', FormUtil::getPassedValue('viewtype', $calendar['config']['defaultView'], 'GETPOST'), 'GETPOST');
         $firstDayOfWeek = (int) FormUtil::getPassedValue('firstDayOfWeek', -1, 'GETPOST');
         $theme = FormUtil::getPassedValue('template', $calendar['config']['defaultTemplate'], 'GETPOST');
         // backward compatibility
         if ($theme == 'default') {
             $theme = 'table';
         }
         // check for a valid $tpl
         if ($tpl != 'year' && $tpl != 'month' && $tpl != 'week' && $tpl != 'day') {
             $tpl = $calendar['config']['defaultView'];
         }
         $tpl = 'month';
         $theme = 'table';
         $this->view->assign('template', $theme);
         $this->view->assign('viewed_day', $day);
         $this->view->assign('viewed_month', $month);
         $this->view->assign('viewed_year', $year);
         $this->view->assign('viewType', $tpl);
         $this->view->assign('calendar', $calendar);
         $this->view->assign('viewed_date', DateUtil::getDatetime(mktime(0, 0, 0, $month, $day, $year), DATEONLYFORMAT_FIXED));
         $this->view->assign('date_today', DateUtil::getDatetime(null, DATEONLYFORMAT_FIXED));
         $this->view->assign('month_startDate', DateUtil::getDatetime(mktime(0, 0, 0, $month, 1, $year), DATEONLYFORMAT_FIXED));
         $this->view->assign('month_endDate', DateUtil::getDatetime(mktime(0, 0, 0, $month, DateUtil::getDaysInMonth($month, $year), $year), DATEONLYFORMAT_FIXED));
         $this->view->assign('filter_obj_url', $filter->toURL());
         $this->view->assign('firstDayOfWeek', $firstDayOfWeek);
         $this->view->assign('selectedCats', array());
         $categories = CategoryRegistryUtil::getRegisteredModuleCategories('TimeIt', 'TimeIt_events');
         foreach ($categories as $property => $cid) {
             $cat = CategoryUtil::getCategoryByID($cid);
             if (isset($cat['__ATTRIBUTES__']['calendarid']) && !empty($cat['__ATTRIBUTES__']['calendarid'])) {
                 if ($cat['__ATTRIBUTES__']['calendarid'] != $calendar['id']) {
                     unset($categories[$property]);
                 }
             }
         }
         $this->view->assign('categories', $categories);
         // load event data
         switch ($tpl) {
             case 'year':
                 $objectData = $domain->getYearEvents($year, $calendar['id'], $firstDayOfWeek);
                 break;
             case 'month':
                 $objectData = $domain->getMonthEvents($year, $month, $day, $calendar['id'], $firstDayOfWeek, $filter);
                 break;
             case 'week':
                 $objectData = $domain->getWeekEvents($year, $month, $day, $calendar['id'], $filter);
                 break;
             case 'day':
                 $objectData = $domain->getDayEvents($year, $month, $day, $calendar['id'], $filter);
                 break;
         }
     }
     // assign the data
     $this->view->assign('objectArray', $objectData);
     // render the html
     return $this->_renderTemplate($this->view, $objectType, 'user', 'view', $theme, $tpl, 'table');
 }
Esempio n. 20
0
 /**
  * decode custom url string
  *
  * @author Philipp Niethammer
  * @return bool true if succeded false otherwise
  */
 public function decodeurl($args)
 {
     $suffix = $this->getVar('shorturlsuffix');
     $supportedfunctions = array('main', 'list', 'view', 'subpages', 'sitemap', 'extlist', 'categoriesList', 'pagelist');
     $argsnum = count($args['vars']);
     if (!isset($args['vars'][2]) || empty($args['vars'][2])) {
         System::queryStringSetVar('func', 'sitemap');
         return true;
     }
     if (in_array($args['vars'][2], $supportedfunctions)) {
         return false;
     }
     $lastarg = end($args['vars']);
     $urlname = '';
     if (substr($lastarg, strlen($lastarg) - strlen($suffix)) == $suffix) {
         for ($i = 2; $i < $argsnum; $i++) {
             if (!empty($urlname)) {
                 $urlname .= '/';
             }
             $urlname .= $args['vars'][$i];
         }
         if (($suffixLen = strlen($suffix)) > 0) {
             $urlname = substr($urlname, 0, -$suffixLen);
         }
         System::queryStringSetVar('func', 'view');
         System::queryStringSetVar('name', $urlname);
         return true;
     }
     if (!isset($args['vars'][3]) || empty($args['vars'][3])) {
         $mainCategory = CategoryRegistryUtil::getRegisteredModuleCategory('Content', 'content_page', $this->getVar('categoryPropPrimary'), 30);
         // 30 == /__SYSTEM__/Modules/Global
         //$cats = CategoryUtil::getCategoriesByParentID($mainCategory);
         $cats = CategoryUtil::getSubCategories($mainCategory);
         foreach ($cats as $cat) {
             if ($args['vars'][2] == $cat['name'] || $args['vars'][2] == DataUtil::formatForURL($cat['name'])) {
                 System::queryStringSetVar('func', 'listpages');
                 System::queryStringSetVar('cat', $cat['id']);
                 return true;
             }
         }
     }
     for ($i = 2; $i < $argsnum; $i++) {
         if (!empty($urlname)) {
             $urlname .= '/';
         }
         $urlname .= $args['vars'][$i];
     }
     System::queryStringSetVar('func', 'subpages');
     System::queryStringSetVar('name', $urlname);
     return true;
 }
 /**
  * create the category tree
  *
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException If Root category not found.
  * @throws \Exception
  *
  * @return boolean
  */
 private function createCategoryTree()
 {
     // create category
     \CategoryUtil::createCategory('/__SYSTEM__/Modules', $this->bundle->getName(), null, $this->__('Gallery'), $this->__('Gallery categories'));
     // create subcategory
     \CategoryUtil::createCategory('/__SYSTEM__/Modules/KaikmediaGalleryModule', 'Category1', null, $this->__('Category 1'), $this->__('Initial sub-category created on install'), array('color' => '#99ccff'));
     \CategoryUtil::createCategory('/__SYSTEM__/Modules/KaikmediaGalleryModule', 'Category2', null, $this->__('Category 2'), $this->__('Initial sub-category created on install'), array('color' => '#cceecc'));
     // get the category path to insert Pages categories
     $rootcat = \CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/KaikmediaGalleryModule');
     if ($rootcat) {
         // create an entry in the categories registry to the Main property
         if (!\CategoryRegistryUtil::insertEntry($this->bundle->getName(), 'AlbumEntity', 'Main', $rootcat['id'])) {
             throw new \Exception('Cannot insert Category Registry entry.');
         }
     } else {
         throw new NotFoundHttpException('Root category not found.');
     }
     return true;
 }
Esempio n. 22
0
 /**
  * Insert a categorization data object.
  *
  * @param array   $obj            The object we wish to store categorization data for.
  * @param string  $tablename      The object's tablename.
  * @param string  $idcolumn       The object's idcolumn (optional) (default='id').
  * @param boolean $wasUpdateQuery True after an update and false after an insert.
  *
  * @return The result from the category data insert operation
  */
 public static function storeObjectCategories($obj, $tablename, $idcolumn = 'id', $wasUpdateQuery = true)
 {
     if (!$obj) {
         throw new \Exception(__f('Invalid %1$s passed to %2$s.', array('object', __CLASS__ . '::' . __FUNCTION__)));
     }
     if (!$tablename) {
         throw new \Exception(__f('Invalid %1$s passed to %2$s.', array('tablename', __CLASS__ . '::' . __FUNCTION__)));
     }
     if (!$idcolumn) {
         throw new \Exception(__f('Invalid %1$s passed to %2$s.', array('idcolumn', __CLASS__ . '::' . __FUNCTION__)));
     }
     if (!ModUtil::dbInfoLoad('ZikulaCategoriesModule')) {
         return false;
     }
     if (!isset($obj['__CATEGORIES__']) || !is_array($obj['__CATEGORIES__']) || !$obj['__CATEGORIES__']) {
         return false;
     }
     if ($wasUpdateQuery) {
         self::deleteObjectCategories($obj, $tablename, $idcolumn);
     }
     // ensure that we don't store duplicate object mappings
     $values = array();
     foreach ($obj['__CATEGORIES__'] as $k => $v) {
         if (isset($values[$v])) {
             unset($obj['__CATEGORIES__'][$k]);
         } else {
             $values[$v] = 1;
         }
     }
     // cache category id arrays to improve performance with DBUtil::(insert|update)ObjectArray()
     static $modTableCategoryIDs = array();
     // Get the ids of the categories properties of the object
     $modname = isset($obj['__META__']['module']) ? $obj['__META__']['module'] : ModUtil::getName();
     $reg_key = $modname . '_' . $tablename;
     if (!isset($modTableCategoryIDs[$reg_key])) {
         $modTableCategoryIDs[$reg_key] = CategoryRegistryUtil::getRegisteredModuleCategoriesIds($modname, $tablename);
     }
     $reg_ids = $modTableCategoryIDs[$reg_key];
     $cobj = array();
     $cobj['table'] = $tablename;
     $cobj['obj_idcolumn'] = $idcolumn;
     $res = true;
     foreach ($obj['__CATEGORIES__'] as $prop => $cat) {
         // if there's all the data and the Registry exists
         // the category is mapped
         if ($cat && $prop && isset($reg_ids[$prop])) {
             $cobj['id'] = '';
             $cobj['modname'] = $modname;
             $cobj['obj_id'] = $obj[$idcolumn];
             $cobj['category_id'] = $cat;
             $cobj['reg_id'] = $reg_ids[$prop];
             $res = DBUtil::insertObject($cobj, 'categories_mapobj');
         }
     }
     $dbtables = DBUtil::getTables();
     if (isset($dbtables[$tablename])) {
         DBUtil::flushCache($tablename);
     }
     return (bool) $res;
 }
Esempio n. 23
0
    /**
     * Fill some variables before the editing of the plugin parameters
     */
    public function startEditing()
    {
        // Get the News categorization setting
        $enablecategorization = ModUtil::getVar('News', 'enablecategorization');
        // Select categories only if enabled for the News module, otherwise selector will not be shown in modify template
        if ($enablecategorization) {
            // Get the registrered categories for the News module
            $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('News', 'news');
            $this->view->assign('catregistry', $catregistry);
        }
        $this->view->assign('enablecategorization', $enablecategorization);

        $showoptions = array(
            array('value' => 1, 'text' => $this->__('Show all news articles')),
            array('value' => 2, 'text' => $this->__('Show only articles set for index page listing')),
            array('value' => 3, 'text' => $this->__('Show only articles not set for index page listing'))
        );

        $statusoptions = array(
            array('value' => 0, 'text' => $this->__('Published')),
            array('value' => 1, 'text' => $this->__('Rejected')),
            array('value' => 2, 'text' => $this->__('Pending Review')),
            array('value' => 3, 'text' => $this->__('Archived')) /* ,
                  array('value' => 4, 'text' => $this->__('Draft')) */
        );

        $orderoptions = array(
            array('value' => 0, 'text' => $this->__('News publisher setting')),
            array('value' => 1, 'text' => $this->__('Number of pageviews')),
            array('value' => 2, 'text' => $this->__('Article weight')),
            array('value' => 3, 'text' => $this->__('Random'))
        );

        $this->view->assign('showoptions', $showoptions);
        $this->view->assign('statusoptions', $statusoptions);
        $this->view->assign('orderoptions', $orderoptions);
    }
Esempio n. 24
0
 /**
  * Get the categories registered for the Pages
  *
  * @return array
  */
 private function getCategories()
 {
     $categoryRegistry = \CategoryRegistryUtil::getRegisteredModuleCategories('ZikulaPagesModule', 'PageEntity');
     $properties = array_keys($categoryRegistry);
     $propertiesdata = array();
     foreach ($properties as $property) {
         $rootcat = CategoryUtil::getCategoryByID($categoryRegistry[$property]);
         if (!empty($rootcat)) {
             $rootcat['path'] .= '/';
             // add this to make the relative paths of the subcategories with ease - mateo
             $subcategories = CategoryUtil::getCategoriesByParentID($rootcat['id']);
             foreach ($subcategories as $k => $category) {
                 $subcategories[$k]['count'] = $this->countItems(array('category' => $category['id'], 'property' => $property));
             }
             $propertiesdata[] = array('name' => $property, 'rootcat' => $rootcat, 'subcategories' => $subcategories);
         }
     }
     return array($properties, $propertiesdata);
 }
Esempio n. 25
0
 /**
  * view items
  *
  * @return string HTML output
  */
 public function view()
 {
     // Security check
     if (!SecurityUtil::checkPermission('Reviews::', '::', ACCESS_OVERVIEW)) {
         return LogUtil::registerPermissionError();
     }
     $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
     // parameter specifying which type of objects we are treating
     $objectType = $this->request->query->filter('ot', 'review', FILTER_SANITIZE_STRING);
     $utilArgs = array('controller' => 'user', 'action' => 'view');
     if (!in_array($objectType, $controllerHelper->getObjectTypes('controllerAction', $utilArgs))) {
         $objectType = $controllerHelper->getDefaultObjectType('controllerAction', $utilArgs);
     }
     $this->throwForbiddenUnless(SecurityUtil::checkPermission($this->name . ':' . ucwords($objectType) . ':', '::', ACCESS_READ), LogUtil::getErrorMsgPermission());
     $entityClass = $this->name . '_Entity_' . ucwords($objectType);
     $repository = $this->entityManager->getRepository($entityClass);
     $repository->setControllerArguments(array());
     $viewHelper = new Reviews_Util_View($this->serviceManager);
     // parameter for used sorting field
     $sort = $this->request->query->filter('sort', '', FILTER_SANITIZE_STRING);
     if (empty($sort) || !in_array($sort, $repository->getAllowedSortingFields())) {
         $sort = $repository->getDefaultSortingField();
     }
     // parameter for used sort order
     $sdir = $this->request->query->filter('sortdir', '', FILTER_SANITIZE_STRING);
     $sdir = strtolower($sdir);
     if ($sdir != 'asc' && $sdir != 'desc') {
         $sdir = 'asc';
     }
     // convenience vars to make code clearer
     $currentUrlArgs = array('ot' => $objectType);
     $where = '';
     // we check for letter
     $letter = $this->request->query->filter('letter', NULL);
     if ($letter != NULL) {
         $where = 'tbl.title LIKE \'' . DataUtil::formatForStore($letter) . '%\'';
     }
     $selectionArgs = array('ot' => $objectType, 'where' => $where, 'orderBy' => $sort . ' ' . $sdir);
     $showOwnEntries = (int) $this->request->query->filter('own', $this->getVar('showOnlyOwnEntries', 0), FILTER_VALIDATE_INT);
     $showAllEntries = (int) $this->request->query->filter('all', 0, FILTER_VALIDATE_INT);
     if (!$showAllEntries) {
         $csv = (int) $this->request->query->filter('usecsvext', 0, FILTER_VALIDATE_INT);
         if ($csv == 1) {
             $showAllEntries = 1;
         }
     }
     $this->view->assign('showOwnEntries', $showOwnEntries)->assign('showAllEntries', $showAllEntries);
     if ($showOwnEntries == 1) {
         $currentUrlArgs['own'] = 1;
     }
     if ($showAllEntries == 1) {
         $currentUrlArgs['all'] = 1;
     }
     // prepare access level for cache id
     $accessLevel = ACCESS_READ;
     $component = 'Reviews:' . ucwords($objectType) . ':';
     $instance = '::';
     if (SecurityUtil::checkPermission($component, $instance, ACCESS_COMMENT)) {
         $accessLevel = ACCESS_COMMENT;
     }
     if (SecurityUtil::checkPermission($component, $instance, ACCESS_EDIT)) {
         $accessLevel = ACCESS_EDIT;
     }
     $templateFile = $viewHelper->getViewTemplate($this->view, 'user', $objectType, 'view', array());
     $cacheId = 'view|ot_' . $objectType . '_sort_' . $sort . '_' . $sdir;
     $resultsPerPage = 0;
     if ($showAllEntries == 1) {
         // set cache id
         $this->view->setCacheId($cacheId . '_all_1_own_' . $showOwnEntries . '_' . $accessLevel);
         // if page is cached return cached content
         if ($this->view->is_cached($templateFile)) {
             return $viewHelper->processTemplate($this->view, 'user', $objectType, 'view', array(), $templateFile);
         }
         // retrieve item list without pagination
         $entities = ModUtil::apiFunc($this->name, 'selection', 'getEntities', $selectionArgs);
     } else {
         // the current offset which is used to calculate the pagination
         $currentPage = (int) $this->request->query->filter('pos', 1, FILTER_VALIDATE_INT);
         // the number of items displayed on a page for pagination
         $resultsPerPage = (int) $this->request->query->filter('num', 0, FILTER_VALIDATE_INT);
         if ($resultsPerPage == 0) {
             $resultsPerPage = $this->getVar('pagesize', 10);
         }
         // set cache id
         $this->view->setCacheId($cacheId . '_amount_' . $resultsPerPage . '_page_' . $currentPage . '_own_' . $showOwnEntries . '_' . $accessLevel);
         // if page is cached return cached content
         if ($this->view->is_cached($templateFile)) {
             return $viewHelper->processTemplate($this->view, 'user', $objectType, 'view', array(), $templateFile);
         }
         // retrieve item list with pagination
         $selectionArgs['currentPage'] = $currentPage;
         $selectionArgs['resultsPerPage'] = $resultsPerPage;
         list($entities, $objectCount) = ModUtil::apiFunc($this->name, 'selection', 'getEntitiesPaginated', $selectionArgs);
         $this->view->assign('currentPage', $currentPage)->assign('pager', array('numitems' => $objectCount, 'itemsperpage' => $resultsPerPage));
     }
     foreach ($entities as $k => $entity) {
         $entity->initWorkflow();
     }
     // build ModUrl instance for display hooks
     $currentUrlObject = new Zikula_ModUrl($this->name, 'user', 'view', ZLanguage::getLanguageCode(), $currentUrlArgs);
     // assign the object data, sorting information and details for creating the pager
     $this->view->assign('items', $entities)->assign('sort', $sort)->assign('sdir', $sdir)->assign('pageSize', $resultsPerPage)->assign('currentUrlObject', $currentUrlObject)->assign('shorturls', System::getVar('shorturls'))->assign($repository->getAdditionalTemplateParameters('controllerAction', $utilArgs));
     $modelHelper = new Reviews_Util_Model($this->serviceManager);
     $this->view->assign('canBeCreated', $modelHelper->canBeCreated($objectType));
     // fetch and return the appropriate template
     return $viewHelper->processTemplate($this->view, 'user', $objectType, 'view', array(), $templateFile);
     ///////////////////////Alter Code
     // Get parameters from whatever input we need
     $cat = (string) FormUtil::getPassedValue('cat', isset($args['cat']) ? $args['cat'] : null, 'GET');
     $prop = (string) FormUtil::getPassedValue('prop', isset($args['prop']) ? $args['prop'] : null, 'GET');
     $letter = (string) FormUtil::getPassedValue('letter', null, 'REQUEST');
     $page = (int) FormUtil::getPassedValue('page', isset($args['page']) ? $args['page'] : 1, 'GET');
     // get all module vars for later use
     $modvars = ModUtil::getVar('Reviews');
     // defaults and input validation
     if (!is_numeric($page) || $page < 0) {
         $page = 1;
     }
     $startnum = ($page - 1) * $modvars['itemsperpage'] + 1;
     // check if categorisation is enabled
     if ($modvars['enablecategorization']) {
         // get the categories registered for Reviews
         $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('Reviews', 'reviews');
         $properties = array_keys($catregistry);
         // validate the property
         // and build the category filter - mateo
         if (!empty($properties) && in_array($prop, $properties)) {
             // if the property and the category are specified
             // means that we'll list the reviews that belongs to that category
             if (!empty($cat)) {
                 if (!is_numeric($cat)) {
                     $rootCat = CategoryUtil::getCategoryByID($catregistry[$prop]);
                     $cat = CategoryUtil::getCategoryByPath($rootCat['path'] . '/' . $cat);
                 } else {
                     $cat = CategoryUtil::getCategoryByID($cat);
                 }
                 if (!empty($cat) && isset($cat['path'])) {
                     // include all it's subcategories and build the filter
                     $categories = categoryUtil::getCategoriesByPath($cat['path'], '', 'path');
                     $catstofilter = array();
                     foreach ($categories as $category) {
                         $catstofilter[] = $category['id'];
                     }
                     $catFilter = array($prop => $catstofilter);
                 } else {
                     LogUtil::registerError($this->__('Invalid category passed.'));
                 }
             }
         }
     }
     // Get all matching reviews
     /*$items = ModUtil::apiFunc('Reviews', 'user', 'getall',
                     array('startnum' => $startnum,
                     'numitems' => $modvars['itemsperpage'],
                     'letter'   => $letter,
                     'category' => isset($catFilter) ? $catFilter : null,
                     'catregistry' => isset($catregistry) ? $catregistry : null));
     
             // assign all the necessary template variables
             $this->view->assign('items', $items);
             $this->view->assign('category', $cat);
             $this->view->assign('lang', ZLanguage::getLanguageCode());
             $this->view->assign($modvars);
             $this->view->assign('shorturls', System::getVar('shorturls'));
             $this->view->assign('shorturlstype', System::getVar('shorturlstype'));
     
             // Assign the values for the smarty plugin to produce a pager
             $this->view->assign('pager', array('numitems' => ModUtil::apiFunc('Reviews', 'user', 'countitems',
                     array('letter' => $letter,
                     'category' => isset($catFilter) ? $catFilter : null)),
                     'itemsperpage' => $modvars['itemsperpage']));
     
             // fetch and return the appropriate template
             return $viewHelper->processTemplate($this->view, 'user', $objectType, 'view', array(), $templateFile);
             */
 }
Esempio n. 26
0
 /**
  * Edit Ephemeride
  * @author The Zikula Development Team
  * @param 'eid' Ephemeride id to delete
  * @param 'confirm' Delete confirmation
  * @return mixed HTML string if confirm is null, true otherwise
  */
 public function modify($args)
 {
     // get parameters from whatever input we need.
     $eid = FormUtil::getPassedValue('eid', isset($args['eid']) ? $args['eid'] : null, 'GET');
     $objectid = FormUtil::getPassedValue('objectid', isset($args['objectid']) ? $args['objectid'] : null, 'GET');
     $delcache = FormUtil::getPassedValue('delcache', isset($args['delcache']) ? $args['delcache'] : null, 'GET');
     // check to see if we have been passed $objectid, the generic item identifier.
     if (!empty($objectid)) {
         $eid = $objectid;
     }
     // get the item
     $item = ModUtil::apiFunc($this->name, 'user', 'get', array('eid' => $eid));
     if (!$item) {
         return DataUtil::formatForDisplayHTML($this->__('No such Ephemeride found.'));
     }
     // calulate date for use in template
     $item['date'] = $item['yid'] . '-' . $item['mid'] . '-' . $item['did'];
     // security check
     if (!SecurityUtil::checkPermission($this->name . '::', "::{$eid}", ACCESS_EDIT)) {
         return LogUtil::registerPermissionError();
     }
     // get all module vars
     $modvars = ModUtil::getVar($this->name);
     if ($modvars['enablecategorization']) {
         // load the category registry util
         $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories($this->name, 'ephem');
         $this->view->assign('catregistry', $catregistry);
     }
     // assign the item and module vars
     $this->view->assign($item);
     $this->view->assign($modvars);
     $this->view->assign('delcache', $delcache);
     // return the output that has been generated by this function
     return $this->view->fetch('ephemerides_admin_modify.tpl');
 }
Esempio n. 27
0
    /**
     * display block
     *
     * @author       The Zikula Development Team
     * @param        array       $blockinfo     a blockinfo structure
     * @return       output      the rendered bock
     */
    public function display($blockinfo)
    {
        // security check
        if (!SecurityUtil::checkPermission('Pastblock::', "$blockinfo[bid]::", ACCESS_READ)) {
            return;
        }

        // get the number of stories shown on the frontpage
        $storyhome = $this->getVar('storyhome', 10);

        // Break out options from our content field
        $vars = BlockUtil::varsFromContent($blockinfo['content']);

        // Defaults
        if (empty($vars['limit'])) {
            $vars['limit'] = 10;
        }

        if ($this->getVar('enablecategorization')) {
            $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('News', 'news');
        }
        // call the API
        $articles = ModUtil::apiFunc('News', 'user', 'getall', array(
                    'displayonindex' => 1,
                    'order' => 'from',
                    'status' => News_Api_User::STATUS_PUBLISHED,
                    'startnum' => $storyhome + 1,
                    'numitems' => $vars['limit'],
                    'catregistry' => isset($catregistry) ? $catregistry : null));

        if (($articles === false) || (empty($articles))) {
            return;
        }

        // loop round the return articles grouping by date
        $count        = 0;
        $news         = array();
        $newscumul    = array();
        $limitreached = false;
        foreach ($articles as $article)
        {
            $info  = ModUtil::apiFunc('News', 'user', 'getArticleInfo', $article);
            $links = ModUtil::apiFunc('News', 'user', 'getArticleLinks', $info);
            if (SecurityUtil::checkPermission('News::', "$info[cr_uid]::$info[sid]", ACCESS_READ)) {
                $preformat['title'] = "<a href=\"$links[fullarticle]\">$info[title]</a>";
            } else {
                $preformat['title'] = $info['title'];
            }

            $daydate = DateUtil::formatDatetime(strtotime($info['from']), '%Y-%m-%d');

            // Reset the time
            if (!isset($currentday)) {
                $currentday = $daydate;
            }

            // If it's a different date, save the cumul and continue
            if ($currentday != $daydate) {
                $news[$currentday] = $newscumul;
                $newscumul = array();
                $currentday = $daydate;
            }
            $newscumul[] = array('info'      => $info,
                    'links'     => $links,
                    'preformat' => $preformat);
        }

        if (!isset($news[$currentday])) {
            $news[$currentday] = $newscumul;
        }

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

        if (empty($blockinfo['title'])) {
            //! default past block title
            $blockinfo['title'] = $this->__('Past articles');
        }

        $blockinfo['content'] = $this->view->fetch('block/past.tpl');

        return BlockUtil::themeBlock($blockinfo);
    }
Esempio n. 28
0
    /**
     * modify a news entry (incl. delete) via ajax
     *
     * @author Frank Schummertz
     * @param 'sid'   int the story id
     * @param 'page'   int the story page
     * @return string HTML string
     */
    public function modify()
    {
        $this->checkAjaxToken();

        $sid = $this->request->getPost()->get('sid');
        $page = $this->request->getPost()->get('page', 1);

        // Get the news article
        $item = ModUtil::apiFunc('News', 'User', 'get', array('sid' => $sid));
        if ($item == false) {
            throw new Zikula_Exception_NotFound($this->__('Error! No such article found.'));
        }

        // Security check
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('News::', "{$item['cr_uid']}::$sid", ACCESS_EDIT));

        // Get the format types. 'home' string is bits 0-1, 'body' is bits 2-3.
        $item['hometextcontenttype'] = ($item['format_type'] % 4);
        $item['bodytextcontenttype'] = (($item['format_type'] / 4) % 4);

        // Set the publishing date options.
        if (!isset($item['to'])) {
            if (DateUtil::getDatetimeDiff_AsField($item['from'], $item['cr_date'], 6) >= 0 && is_null($item['to'])) {
                $item['unlimited'] = 1;
                $item['tonolimit'] = 1;
            } elseif (DateUtil::getDatetimeDiff_AsField($item['from'], $item['cr_date'], 6) < 0 && is_null($item['to'])) {
                $item['unlimited'] = 0;
                $item['tonolimit'] = 1;
            }
        } else {
            $item['unlimited'] = 0;
            $item['tonolimit'] = 0;
        }

        Zikula_AbstractController::configureView();
        $this->view->setCaching(false);

        $modvars = $this->getVars();

        if ($modvars['enablecategorization']) {
            $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('News', 'news');
            $this->view->assign('catregistry', $catregistry);
        }
        
        $this->view->assign('accessadd', 0);
        if (SecurityUtil::checkPermission('News::', '::', ACCESS_ADD)) {
            $this->view->assign('accessadd', 1);
            $this->view->assign('accesspicupload', 1);
            $this->view->assign('accesspubdetails', 1);
        } else {
            $this->view->assign('accesspicupload', SecurityUtil::checkPermission('News:pictureupload:', '::', ACCESS_ADD));
            $this->view->assign('accesspubdetails', SecurityUtil::checkPermission('News:publicationdetails:', '::', ACCESS_ADD));
        }

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

        // Assign the current page
        $this->view->assign('page', $page);

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

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

        //lock the page so others cannot edit it
        if (ModUtil::available('PageLock')) {
            $returnUrl = ModUtil::url('News', 'admin', 'view');
            ModUtil::apiFunc('PageLock', 'user', 'pageLock',
                            array('lockName' => "Newsnews{$item['sid']}",
                                'returnUrl' => $returnUrl));
        }

        // Return the output that has been generated by this function
        return new Zikula_Response_Ajax(array('result' => $this->view->fetch('ajax/modify.tpl')));
    }
Esempio n. 29
0
 public function categories()
 {
     $this->throwForbiddenUnless(SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_READ), LogUtil::getErrorMsgPermission());
     $this->view->setCacheId('main');
     if ($this->view->is_cached('user/main.tpl')) {
         return $this->view->fetch('user/main.tpl');
     }
     // Create output object
     $enablecategorization = ModUtil::getVar('AddressBook', 'enablecategorization');
     if ($enablecategorization) {
         // get the categories registered for the AddressBook
         $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('AddressBook', 'addressbook_address');
         $properties = array_keys($catregistry);
         $propertiesdata = array();
         foreach ($properties as $property) {
             $rootcat = CategoryUtil::getCategoryByID($catregistry[$property]);
             if (!empty($rootcat)) {
                 $rootcat['path'] .= '/';
                 // add this to make the relative paths of the subcategories with ease - mateo
                 $subcategories = CategoryUtil::getCategoriesByParentID($rootcat['id']);
                 $propertiesdata[] = array('name' => $property, 'rootcat' => $rootcat, 'subcategories' => $subcategories);
             }
         }
         // Assign some useful vars to customize the main
         $this->view->assign('properties', $properties);
         $this->view->assign('propertiesdata', $propertiesdata);
     }
     return $this->view->fetch('user_categories.tpl');
 }
Esempio n. 30
0
 /**
  * Build a list of objects which are mapped to the specified categories.
  *
  * @param string  $tablename      Treated table reference.
  * @param string  $categoryFilter The category list to use for filtering.
  * @param boolean $returnArray    Whether or not to return an array (optional) (default=false).
  *
  * @return mixed The resulting string or array.
  */
 private static function _generateCategoryFilter($tablename, $categoryFilter, $returnArray = false)
 {
     if (!$categoryFilter) {
         return '';
     }
     if (!ModUtil::dbInfoLoad('ZikulaCategoriesModule')) {
         return '';
     }
     // check the meta data
     if (isset($categoryFilter['__META__']['module'])) {
         $modname = $categoryFilter['__META__']['module'];
     } else {
         $modname = ModUtil::getName();
     }
     // check operator to use
     // when it's AND, the where contains subqueries
     if (isset($categoryFilter['__META__']['operator']) && in_array(strtolower($categoryFilter['__META__']['operator']), array('and', 'or'))) {
         $op = strtoupper($categoryFilter['__META__']['operator']);
     } else {
         $op = 'OR';
     }
     unset($categoryFilter['__META__']);
     // get the properties IDs in the category register
     $propids = CategoryRegistryUtil::getRegisteredModuleCategoriesIds($modname, $tablename);
     // build the where clause
     $n = 1;
     // subquery counter
     $catmapobjtbl = 'categories_mapobj';
     $where = array();
     foreach ($categoryFilter as $property => $category) {
         $prefix = '';
         if ($op == 'AND') {
             $prefix = "table{$n}.";
         }
         // this allows to have an array of categories IDs
         if (is_array($category)) {
             $wherecat = array();
             foreach ($category as $cat) {
                 $wherecat[] = "{$prefix}category_id='" . DataUtil::formatForStore($cat) . "'";
             }
             $wherecat = '(' . implode(' OR ', $wherecat) . ')';
             // if there's only one category ID
         } else {
             $wherecat = "{$prefix}category_id='" . DataUtil::formatForStore($category) . "'";
         }
         // process the where depending of the operator
         if ($op == 'AND') {
             $where[] = "obj_id IN (SELECT {$prefix}obj_id FROM {$catmapobjtbl} table{$n} WHERE {$prefix}reg_id = '" . DataUtil::formatForStore($propids[$property]) . "' AND {$wherecat})";
         } else {
             $where[] = "(reg_id='" . DataUtil::formatForStore($propids[$property]) . "' AND {$wherecat})";
         }
         $n++;
     }
     $where = "tablename='" . DataUtil::formatForStore($tablename) . "' AND (" . implode(" {$op} ", $where) . ')';
     // perform the query
     $objIds = DBUtil::selectFieldArray('categories_mapobj', 'obj_id', $where);
     // this ensures that we return an empty set if no objects are mapped to the requested categories
     if (!$objIds) {
         $objIds[] = -1;
     }
     if ($returnArray) {
         return $objIds;
     }
     return implode(',', $objIds);
 }