示例#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');
 }
 /**
  * delete category
  */
 public function deleteAction()
 {
     if (!SecurityUtil::checkPermission('Categories::', '::', ACCESS_DELETE)) {
         throw new \Zikula\Framework\Exception\ForbiddenException();
     }
     $cid = (int) $this->request->get('cid', 0);
     $dr = (int) $this->request->get('dr', 0);
     $url = System::serverGetVar('HTTP_REFERER');
     if (!$dr) {
         return LogUtil::registerError($this->__('Error! The document root is invalid.'), null, $url);
     }
     if (!$cid) {
         return LogUtil::registerError($this->__('Error! The category ID is invalid.'), null, $url);
     }
     $category = \CategoryUtil::getCategoryByID($cid);
     if (!$category) {
         $msg = $this->__f('Error! Cannot retrieve category with ID %s.', $cid);
         return LogUtil::registerError($msg, null, $url);
     }
     if ($category['is_locked']) {
         //! %1$s is the id, %2$s is the name
         return LogUtil::registerError($this->__f('Notice: The administrator has locked the category \'%2$s\' (ID \'%$1s\'). You cannot edit or delete it.', array($cid, $category['name'])), null, $url);
     }
     CategoryUtil::deleteCategoryByID($cid);
     return $this->redirect($url);
 }
/**
 * User category selector.
 *
 * Available parameters:
 *   - btnText:  If set, the results are assigned to the corresponding variable instead of printed out
 *   - cid:      category ID
 *
 * Example
 * {selector_user_category cid="1" assign="category"}
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return string HTML code of the selector.
 */
function smarty_function_selector_user_category($params, Zikula_View $view)
{
    $field = isset($params['field']) ? $params['field'] : 'id';
    $selectedValue = isset($params['selectedValue']) ? $params['selectedValue'] : 0;
    $defaultValue = isset($params['defaultValue']) ? $params['defaultValue'] : 0;
    $defaultText = isset($params['defaultText']) ? $params['defaultText'] : '';
    $lang = isset($params['lang']) ? $params['lang'] : ZLanguage::getLanguageCode();
    $name = isset($params['name']) ? $params['name'] : 'defautlselectorname';
    $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;
    $submit = isset($params['submit']) ? $params['submit'] : false;
    $multipleSize = isset($params['multipleSize']) ? $params['multipleSize'] : 1;
    $doReplaceRootCat = false;
    $userCats = ModUtil::apiFunc('ZikulaCategoriesModule', 'user', 'getusercategories', array('returnCategory' => 1, 'relative' => $relative));
    $html = CategoryUtil::getSelector_Categories($userCats, $field, $selectedValue, $name, $defaultValue, $defaultText, $submit, $displayPath, $doReplaceRootCat, $multipleSize);
    if ($editLink && $allowUserEdit && UserUtil::isLoggedIn() && SecurityUtil::checkPermission('ZikulaCategoriesModule::', "{$category['id']}::", ACCESS_EDIT)) {
        $url = ModUtil::url('ZikulaCategoriesModule', 'user', 'edituser');
        $html .= "&nbsp;&nbsp;<a href=\"{$url}\">" . __('Edit sub-categories') . '</a>';
    }
    if ($assign) {
        $view->assign($assign, $html);
    } else {
        return $html;
    }
}
示例#4
0
 /**
  * Get the search results
  *
  * @param array $words array of words to search for
  * @param string $searchType AND|OR|EXACT
  * @param array|null $modVars module form vars passed though
  * @return array
  */
 function getResults(array $words, $searchType = 'AND', $modVars = null)
 {
     if (!SecurityUtil::checkPermission($this->name . '::', '::', ACCESS_READ)) {
         return array();
     }
     $qb = $this->entityManager->createQueryBuilder();
     $qb->select('p')->from('Zikula\\PagesModule\\Entity\\PageEntity', 'p');
     $whereExpr = $this->formatWhere($qb, $words, array('p.title', 'p.content'), $searchType);
     $qb->andWhere($whereExpr);
     $pages = $qb->getQuery()->getResult();
     $sessionId = session_id();
     $enableCategorization = ModUtil::getVar($this->name, 'enablecategorization');
     $records = array();
     foreach ($pages as $page) {
         /** @var $page \Zikula\PagesModule\Entity\PageEntity */
         $pagePermissionCheck = SecurityUtil::checkPermission($this->name . '::', $page->getTitle() . '::' . $page->getPageid(), ACCESS_OVERVIEW);
         if ($enableCategorization) {
             $pagePermissionCheck = $pagePermissionCheck && \CategoryUtil::hasCategoryAccess($page->getCategories(), $this->name);
         }
         if (!$pagePermissionCheck) {
             continue;
         }
         $records[] = array('title' => $page->getTitle(), 'text' => $page->getContent(), 'created' => $page->getCr_date(), 'module' => $this->name, 'sesid' => $sessionId, 'url' => RouteUrl::createFromRoute('zikulapagesmodule_user_display', array('urltitle' => $page->getUrltitle())));
     }
     return $records;
 }
示例#5
0
    /**
     * get a specific item
     *
     * @param $args['pageid'] id of example item to get
     *
     * @return mixed item array, or false on failure
     */
    public function get($args)
    {
        // Argument check
        if ((!isset($args['pageid']) || !is_numeric($args['pageid'])) &&
                !isset($args['title'])) {
            return LogUtil::registerArgsError();
        }

        // define the permission filter to apply
        $permFilter   = array();
        $permFilter[] = array('component_left'  => 'Pages',
                'instance_left'   => 'title',
                'instance_right'  => 'pageid',
                'level'           => ACCESS_READ);

        if (isset($args['pageid']) && is_numeric($args['pageid'])) {
            $item = DBUtil::selectObjectByID('pages', $args['pageid'], 'pageid', '', $permFilter);
        } else {
            $item = DBUtil::selectObjectByID('pages', $args['title'], 'urltitle', '', $permFilter);
        }

        // need to do this here as the category expansion code can't know the
        // root category which we need to build the relative path component
        if ($item && isset($args['catregistry']) && $args['catregistry']) {
            ObjectUtil::postProcessExpandedObjectCategories($item, $args['catregistry']);
        }

        if (ModUtil::getVar('Pages', 'enablecategorization') && !empty($item['__CATEGORIES__'])) {
            if (!CategoryUtil::hasCategoryAccess($item['__CATEGORIES__'], 'Pages')) {
                return false;
            }
        }

        return $item;
    }
示例#6
0
 function checkResult(&$item)
 {
     $ok = (SecurityUtil::checkPermission('News::', "$item[cr_uid]::$item[sid]", ACCESS_OVERVIEW));
     if ($this->enablecategorization && $this->enablecategorybasedpermissions) {
         ObjectUtil::expandObjectWithCategories($item, 'news', 'sid');
         $ok = $ok && CategoryUtil::hasCategoryAccess($item['__CATEGORIES__'], 'News');
     }
     return $ok;
 }
示例#7
0
 function checkResult(&$item)
 {
     $ok = SecurityUtil::checkPermission('Pages::', "$item[title]::$item[pageid]", ACCESS_OVERVIEW);
     if ($this->enablecategorization)
     {
         ObjectUtil::expandObjectWithCategories($item, 'pages', 'pageid');
         $ok = $ok && CategoryUtil::hasCategoryAccess($item['__CATEGORIES__'], 'Pages');
     }
     return $ok;
 }
示例#8
0
 /**
  * get all categories for a user
  *
  */
 public function getusercategories($args)
 {
     $args['returnCategory'] = 1;
     $userRootCat = $this->getuserrootcat($args);
     if (!$userRootCat) {
         return LogUtil::registerError($this->__f('Error! The user root node seems to point towards an invalid category: %s.', $userRoot));
     }
     $relative = isset($args['relative']) ? $args['relative'] : false;
     return CategoryUtil::getCategoriesByParentID($userRootCat['id'], '', $relative);
 }
示例#9
0
 function __construct($registryId = null, $parentId = null)
 {
     if (!empty($parentId)) {
         $this->parentId = $parentId;
     } else {
         $parentIdCategory = \CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/Global');
         $this->parentId = $parentIdCategory['id'];
     }
     $this->registryId = $registryId;
     $this->lang = \ZLanguage::getLanguageCode();
 }
示例#10
0
 /**
  * Install the Reviews application.
  *
  * @return boolean True on success, or false.
  */
 public function install()
 {
     // Check if upload directories exist and if needed create them
     try {
         $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
         $controllerHelper->checkAndCreateAllUploadFolders();
     } catch (\Exception $e) {
         return LogUtil::registerError($e->getMessage());
     }
     // create all tables from according entity definitions
     try {
         DoctrineHelper::createSchema($this->entityManager, $this->listEntityClasses());
     } catch (\Exception $e) {
         if (System::isDevelopmentMode()) {
             return LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
         }
         $returnMessage = $this->__f('An error was encountered while creating the tables for the %s extension.', array($this->name));
         if (!System::isDevelopmentMode()) {
             $returnMessage .= ' ' . $this->__('Please enable the development mode by editing the /config/config.php file in order to reveal the error details.');
         }
         return LogUtil::registerError($returnMessage);
     }
     // set up all our vars with initial values
     $this->setVar('enablecategorization', false);
     $this->setVar('pagesize', 10);
     $this->setVar('scoreForUsers', false);
     $this->setVar('addcategorytitletopermalink', false);
     $categoryRegistryIdsPerEntity = array();
     // add default entry for category registry (property named Main)
     include_once 'modules/Reviews/lib/Reviews/Api/Base/Category.php';
     include_once 'modules/Reviews/lib/Reviews/Api/Category.php';
     $categoryApi = new Reviews_Api_Category($this->serviceManager);
     $categoryGlobal = CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/Global');
     $registryData = array();
     $registryData['modname'] = $this->name;
     $registryData['table'] = 'Review';
     $registryData['property'] = $categoryApi->getPrimaryProperty(array('ot' => 'Review'));
     $registryData['category_id'] = $categoryGlobal['id'];
     $registryData['id'] = false;
     if (!DBUtil::insertObject($registryData, 'categories_registry')) {
         LogUtil::registerError($this->__f('Error! Could not create a category registry for the %s entity.', array('review')));
     }
     $categoryRegistryIdsPerEntity['review'] = $registryData['id'];
     // create the default data
     $this->createDefaultData($categoryRegistryIdsPerEntity);
     // register persistent event handlers
     $this->registerPersistentEventHandlers();
     // register hook subscriber bundles
     HookUtil::registerSubscriberBundles($this->version->getHookSubscriberBundles());
     // initialisation successful
     return true;
 }
示例#11
0
 protected function getItems(&$group)
 {
     $items = parent::getItems($group);
     foreach ($items as $item) {
         $cats = CategoryUtil::getSubCategories($item);
         foreach ($cats as $item) {
             if (!in_array($item['id'], $items)) {
                 $items[] = $item['id'];
             }
         }
     }
     return $items;
 }
示例#12
0
 /**
  * Upgrade the MUVideo application from an older version.
  *
  * If the upgrade fails at some point, it returns the last upgraded version.
  *
  * @param integer $oldVersion Version to upgrade from.
  *
  * @return boolean True on success, false otherwise.
  */
 public function upgrade($oldVersion)
 {
     // Upgrade dependent on old version number
     switch ($oldVersion) {
         case '1.0.0':
             // update the database schema
             try {
                 DoctrineHelper::updateSchema($this->entityManager, $this->listEntityClasses());
             } catch (\Exception $e) {
                 if (System::isDevelopmentMode()) {
                     return LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
                 }
                 return LogUtil::registerError($this->__f('An error was encountered while updating tables for the %s extension.', array($this->getName())));
             }
             $categoryRegistryIdsPerEntity = array();
             // add default entry for category registry (property named Main)
             include_once 'modules/MUVideo/lib/MUVideo/Api/Base/Category.php';
             include_once 'modules/MUVideo/lib/MUVideo/Api/Category.php';
             $categoryApi = new MUVideo_Api_Category($this->serviceManager);
             $categoryGlobal = CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/Global');
             $registryData = array();
             $registryData['modname'] = $this->name;
             $registryData['table'] = 'Collection';
             $registryData['property'] = $categoryApi->getPrimaryProperty(array('ot' => 'Collection'));
             $registryData['category_id'] = $categoryGlobal['id'];
             $registryData['id'] = false;
             if (!DBUtil::insertObject($registryData, 'categories_registry')) {
                 LogUtil::registerError($this->__f('Error! Could not create a category registry for the %s entity.', array('collection')));
             }
             $categoryRegistryIdsPerEntity['collection'] = $registryData['id'];
             $registryData = array();
             $registryData['modname'] = $this->name;
             $registryData['table'] = 'Movie';
             $registryData['property'] = $categoryApi->getPrimaryProperty(array('ot' => 'Movie'));
             $registryData['category_id'] = $categoryGlobal['id'];
             $registryData['id'] = false;
             if (!DBUtil::insertObject($registryData, 'categories_registry')) {
                 LogUtil::registerError($this->__f('Error! Could not create a category registry for the %s entity.', array('movie')));
             }
             $categoryRegistryIdsPerEntity['movie'] = $registryData['id'];
             // unregister persistent event handlers
             EventUtil::unregisterPersistentModuleHandlers($this->name);
             // register persistent event handlers
             $this->registerPersistentEventHandlers();
         case '1.1.0':
             // for later updates
     }
     // update successful
     return true;
 }
示例#13
0
 private function _content_setCategoryRoot()
 {
     // load necessary classes
     $rootcat = CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/Global');
     if ($rootcat) {
         // create an entry in the categories registry
         $registry = new Categories_DBObject_Registry();
         $registry->setDataField('modname', 'Content');
         $registry->setDataField('table', 'content_page');
         $registry->setDataField('property', 'Main');
         $registry->setDataField('category_id', $rootcat['id']);
         $registry->insert();
     }
     return true;
 }
/**
 * Retrieve and display the value of a category field (by default, the category's path).
 *
 * Available attributes:
 *  - id        (numeric|string)    if a numeric value is specified, then the
 *                                  category id, if a string is specified, then
 *                                  the category's path.
 *  - idcolumn  (string)            field to use as the unique ID, either 'id',
 *                                  'path', or 'ipath' (optional,
 *                                  default: 'id' if the id attribute is numeric,
 *                                  'path' if the id attribute is not numeric)
 *  - field     (string)            category field to return (optional, default: path)
 *  - html      (boolean)           if set, return HTML (optional, default: false)
 *  - assign    (string)            the name of a template variable to assign the
 *                                  output to, instead of returning it to the template. (optional)
 *
 * Examples:
 *
 * Get the path of category #1 and assign it to the template variable $category:
 *
 * <samp>{category_path id='1' assign='category'}</samp>
 *
 * Get the path of the category with an ipath of '/1/3/28/30' and display it.
 *
 * <samp>{category_path id='/1/3/28/30' idcolumn='ipath' field='path'}</samp>
 *
 * Get the parent_id of the category with a path of
 * '/__SYSTEM__/General/ActiveStatus/Active' and assign it to the template
 * variable $parentid. Then use that template variable to retrieve and display
 * the parent's path.
 *
 * <samp>{category_path id='/__SYSTEM__/General/ActiveStatus/Active' field='parent_id' assign='parentid'}</samp>
 * <samp>{category_path id=$parentid}</samp>
 *
 * Example from a Content module template: get the sort value of the current
 * page's category and assign it to the template variable $catsortvalue:
 *
 * <samp>{category_path id=$page.categoryId field='sort_value' assign='catsortvalue'}</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 void|string The value of the specified category field.
 */
function smarty_function_category_path($params, Zikula_View $view)
{
    $assign = isset($params['assign']) ? $params['assign'] : null;
    $id = isset($params['id']) ? $params['id'] : 0;
    $idcolumn = isset($params['idcolumn']) ? $params['idcolumn'] : (is_numeric($id) ? 'id' : 'path');
    $field = isset($params['field']) ? $params['field'] : 'path';
    $html = isset($params['html']) ? $params['html'] : false;
    if (!$id) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('category_path', 'id')));
    }
    if (!$idcolumn) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('category_path', 'idcolumn')));
    } elseif ($idcolumn != 'id' && $idcolumn != 'path' && $idcolumn != 'ipath') {
        $view->trigger_error(__f('Error! in %1$s: invalid value for the %2$s parameter (%3$s).', array('category_path', 'idcolumn', $idcolumn)));
    }
    if (!$field) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('category_path', 'field')));
    }
    $result = null;
    if ($idcolumn == 'id') {
        $cat = CategoryUtil::getCategoryByID($id);
    } elseif ($idcolumn == 'path' || $idcolumn == 'ipath') {
        $cat = CategoryUtil::getCategoryByPath($id, $idcolumn);
    }
    if ($cat) {
        if (isset($cat[$field])) {
            $result = $cat[$field];
        } else {
            $view->trigger_error(__f('Error! Category [%1$s] does not have the field [%2$s] set.', array($id, $field)));
            return;
        }
    } else {
        $view->trigger_error(__f('Error! Cannot retrieve category with ID %s.', DataUtil::formatForDisplay($id)));
        return;
    }
    if ($assign) {
        $view->assign($params['assign'], $result);
    } else {
        if (isset($html) && is_bool($html) && $html) {
            return DataUtil::formatForDisplayHTML($result);
        } else {
            return DataUtil::formatForDisplay($result);
        }
    }
}
示例#15
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');
    }
示例#16
0
 public function initialize(Zikula_Form_View $view)
 {
     if (!SecurityUtil::checkPermission('Content:page:', '::', ACCESS_EDIT)) {
         throw new Zikula_Exception_Forbidden(LogUtil::getErrorMsgPermission());
     }
     // Include categories only when 2nd category enabled in settings
     $pages = ModUtil::apiFunc('Content', 'Page', 'getPages', array('editing' => true, 'filter' => array('checkActive' => false, 'expandedPageIds' => SessionUtil::getVar('contentExpandedPageIds', array())), 'enableEscape' => true, 'translate' => false, 'includeLanguages' => true, 'includeCategories' => $this->getVar('categoryUsage') < 3, 'orderBy' => 'setLeft'));
     if ($pages === false) {
         return $this->view->registerError(null);
     }
     // Get categories names if enabled
     if ($this->getVar('$categoryUsage') < 4) {
         $lang = ZLanguage::getLanguageCode();
         $categories = array();
         foreach ($pages as $page) {
             $cat = CategoryUtil::getCategoryByID($page['categoryId']);
             $categories[$page['id']] = array();
             $categories[$page['id']][] = isset($cat['display_name'][$lang]) ? $cat['display_name'][$lang] : $cat['name'];
             if (isset($page['categories']) && is_array($page['categories'])) {
                 foreach ($page['categories'] as $pageCat) {
                     $cat = CategoryUtil::getCategoryByID($pageCat['categoryId']);
                     $categories[$page['id']][] = isset($cat['display_name'][$lang]) ? $cat['display_name'][$lang] : $cat['name'];
                 }
             }
         }
         $this->view->assign('categories', $categories);
     }
     PageUtil::setVar('title', $this->__('Page list and content structure'));
     $csssrc = ThemeUtil::getModuleStylesheet('admin', 'admin.css');
     PageUtil::addVar('stylesheet', $csssrc);
     $this->view->assign('pages', $pages);
     $this->view->assign('multilingual', ModUtil::getVar(ModUtil::CONFIG_MODULE, 'multilingual'));
     $this->view->assign('enableVersioning', $this->getVar('enableVersioning'));
     $this->view->assign('language', ZLanguage::getLanguageCode());
     Content_Util::contentAddAccess($this->view, null);
     return true;
 }
示例#17
0
    /**
     * resequence categories
     */
    public function resequence()
    {
        if (!SecurityUtil::checkPermission('Categories::', '::', ACCESS_EDIT)) {
            return LogUtil::registerPermissionError();
        }

        $dr = (int)FormUtil::getPassedValue('dr', 0, 'GET');
        $url = System::serverGetVar('HTTP_REFERER');

        if (!$dr) {
            return LogUtil::registerError($this->__('Error! The document root is invalid.'), null, $url);
        }

        $cats = CategoryUtil::getSubCategories($dr, false, false, false, false);
        $cats = CategoryUtil::resequence($cats, 10);

        $ak = array_keys($cats);
        foreach ($ak as $k) {
            $obj = new Categories_DBObject_Category($cats[$k]);
            $obj->update();
        }

        $this->redirect(System::serverGetVar('HTTP_REFERER'));
    }
示例#18
0
 /**
  * Post-process an object's expanded category data to generate relative paths.
  *
  * @param array   &$obj        The object we wish to post-process.
  * @param array   $rootCatsIDs The root category ID for the relative path creation.
  * @param boolean $includeRoot Whether or not to include the root folder in the relative path (optional) (default=false).
  *
  * @return The object with the additionally expanded category data is altered in place and returned
  */
 public static function postProcessExpandedObjectCategories(&$obj, $rootCatsIDs, $includeRoot = false)
 {
     if (!$obj) {
         throw new \Exception(__f('Invalid object in %s', 'postProcessExpandedObjectCategories'));
     }
     $rootCats = CategoryUtil::getCategoriesByRegistry($rootCatsIDs);
     if (empty($rootCats)) {
         return false;
     }
     // if the function was called to process the object categories
     if (isset($obj['__CATEGORIES__'])) {
         $ak = array_keys($obj['__CATEGORIES__']);
         foreach ($ak as $prop) {
             CategoryUtil::buildRelativePathsForCategory($rootCats[$prop], $obj['__CATEGORIES__'][$prop], $includeRoot);
         }
         self::makeBC($obj['__CATEGORIES__']);
         // else, if the function was called to process the categories array directly
     } else {
         $ak = array_keys($obj);
         foreach ($ak as $prop) {
             CategoryUtil::buildRelativePathsForCategory($rootCats[$prop], $obj[$prop], $includeRoot);
         }
         self::makeBC($obj);
     }
     return;
 }
示例#19
0
文件: User.php 项目: rmaiwald/Reviews
 /**
  * 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);
             */
 }
示例#20
0
 /**
  * Return the HTML code for the values in a given category.
  *
  * @param string  $categoryPath The identifying category path.
  * @param array   $values       The values used to populate the defautl states (optional) (default=array()).
  * @param string  $namePrefix   The path/object prefix to apply to the field name (optional) (default='').
  * @param string  $excludeList  A (string) list of IDs to exclude (optional) (default=null).
  * @param boolean $disabled     Whether or not the checkboxes are to be disabled (optional) (default=false).
  *
  * @return The resulting dropdown data.
  */
 public static function getCheckboxes_CategoryField($categoryPath, $values = array(), $namePrefix = '', $excludeList = null, $disabled = false)
 {
     if (!$categoryPath) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('category', 'HtmlUtil::getCheckboxes_CategoryField')));
     }
     if (!$lang) {
         $lang = ZLanguage::getLanguageCode();
     }
     $cats = CategoryUtil::getSubCategoriesByPath($categoryPath, 'path', false, true, false, true, false, '', 'value');
     foreach ($cats as $k => $v) {
         $val = $k;
         $fname = $val;
         if ($namePrefix) {
             $fname = $namePrefix . '[' . $k . ']';
         }
         if (strpos($excludeList, ',' . $k . ',') === false) {
             $disp = $v['display_name'][$lang];
             if (!$disp) {
                 $disp = $v['name'];
             }
             $html .= "<input type=\"checkbox\" name=\"" . DataUtil::formatForDisplay($fname) . "\" " . ($values[$k] ? ' checked="checked" ' : '') . ($disabled ? ' disabled="disabled" ' : '') . " />&nbsp;&nbsp;&nbsp;&nbsp;" . DataUtil::formatForDisplay($disp) . "<br />";
         }
     }
     return $html;
 }
/**
 * 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;
    }
}
示例#22
0
 public function delete($deleteSubcats = false, $newParentID = 0)
 {
     $objArray = $this->_objData;
     if (!$objArray) {
         return $objArray;
     }
     foreach ($objArray as $k => $obj) {
         if ($deleteSubcats) {
             CategoryUtil::deleteCategoriesByPath($obj['ipath']);
         } elseif ($newParentID) {
             CategoryUtil::moveSubCategoriesByPath($obj['ipath'], $newParentID);
             CategoryUtil::deleteCategoryByID($obj['id']);
         } else {
             exit('Can not delete category while preserving subcategories without specifying a new parent ID');
         }
     }
 }
示例#23
0
 private function _createdefaultcategory($regpath = '/__SYSTEM__/Modules/Global')
 {
     // get the language
     $lang = ZLanguage::getLanguageCode();
     // get the category path for which we're going to insert our place holder category
     $rootcat = CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules');
     $qCat = CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/Ephemerides');
     if (!$qCat) {
         // create placeholder for all our migrated categories
         $cat = new Categories_DBObject_Category();
         $cat->setDataField('parent_id', $rootcat['id']);
         $cat->setDataField('name', 'Ephemerides');
         $cat->setDataField('display_name', array($lang => $this->__('Ephemerides')));
         $cat->setDataField('display_desc', array($lang => $this->__('Ephemerides')));
         if (!$cat->validate('admin')) {
             return false;
         }
         $cat->insert();
         $cat->update();
     }
     // get the category path for which we're going to insert our upgraded categories
     $rootcat = CategoryUtil::getCategoryByPath($regpath);
     if ($rootcat) {
         // create an entry in the categories registry
         $registry = new Categories_DBObject_Registry();
         $registry->setDataField('modname', 'Ephemerides');
         $registry->setDataField('table', 'ephem');
         $registry->setDataField('property', 'Main');
         $registry->setDataField('category_id', $rootcat['id']);
         $registry->insert();
     } else {
         return false;
     }
     return true;
 }
示例#24
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;
         }
     }
 }
示例#25
0
 /**
  * Returns true if the current user can view the event $event.
  * 
  * @param array $eventDate TimeIt_Model_EventDate as an array.
  * @param int   $level     ACCESS_* constant.
  *
  * @return boolean
  */
 public static function canViewEvent(array $eventDate, $level = ACCESS_READ)
 {
     $event = $eventDate['Event'];
     $groups = UserUtil::getGroupsForUser(UserUtil::getVar('uid'));
     // hack: Admins (group id 2 are in group 1(users) to)
     if (in_array(2, $groups)) {
         $groups[] = 1;
     }
     if ($event['group'] == 'all') {
         $groupId = null;
         // group irrelevant
     } else {
         $groupId = explode(',', $event['group']);
     }
     static $calendarCache = array();
     if (!isset($calendarCache[(int) $event['id']])) {
         // get calendar
         $calendarCache[(int) $event['id']] = $eventDate['Calendar'];
     }
     $calendar = $calendarCache[(int) $event['id']];
     // check permissions
     // hierarchy level 1: module itself
     if (!SecurityUtil::checkPermission('TimeIt::', '::', $level)) {
         return false;
     }
     // hierarchy level 2: calendar
     if (!SecurityUtil::checkPermission('TimeIt:Calendar:', $calendar['id'] . '::', $level)) {
         return false;
     }
     // hierarchy level 3: group
     if (!empty($groupId)) {
         $access = false;
         foreach ($groupId as $grpId) {
             if (in_array($grpId, $groups)) {
                 $access = true;
             }
         }
         if (!$access) {
             return false;
         }
     }
     // hierarchy level 5: timeit category permission
     if (count($event['__CATEGORIES__']) > 0) {
         $permissionOk = false;
         foreach ($event['__CATEGORIES__'] as $cat) {
             $cid = $cat;
             if (is_array($cat)) {
                 $cid = $cat['id'];
             }
             $permissionOk = SecurityUtil::checkPermission('TimeIt:Category:', $cid . "::", $level);
             if ($permissionOk) {
                 // user has got permission -> stop permission checks
                 $hasPermission = true;
                 break;
             }
         }
         if (!$hasPermission) {
             return false;
         }
     }
     // hierarchy level 6: zikula category permission
     if (ModUtil::getVar('TimeIt', 'filterByPermission', 0) && !CategoryUtil::hasCategoryAccess($event['__CATEGORIES__'], 'TimeIt', $level)) {
         return false;
     }
     // hierarchy level 7: event
     if (!SecurityUtil::checkPermission('TimeIt::Event', $event['id'] . '::', $level)) {
         return false;
     }
     // hierarchy level 8: contact list
     if (ModUtil::available('ContactList')) {
         // cache
         static $ignored = null;
         if ($ignored == null) {
             $ignored = ModUtil::apiFunc('ContactList', 'user', 'getallignorelist', array('uid' => UserUtil::getVar('uid')));
         }
         if ($calendar['friendCalendar']) {
             $buddys = ModUtil::apiFunc('ContactList', 'user', 'getBuddyList', array('uid' => $event['cr_uid']));
         }
         if ((int) $event['sharing'] == 4 && $event['cr_uid'] != UserUtil::getVar('uid')) {
             $buddyFound = false;
             foreach ($buddys as $buddy) {
                 if ($buddy['uid'] == UserUtil::getVar('uid')) {
                     $buddyFound = true;
                     break;
                 }
             }
             if (!$buddyFound) {
                 return false;
             }
         }
         $ignoredFound = false;
         foreach ($ignored as $ignore) {
             if ($ignore['iuid'] == $obj['cr_uid']) {
                 $ignoredFound = true;
                 break;
             }
         }
         if ($ignoredFound) {
             return false;
         }
     }
     return true;
 }
示例#26
0
    /**
     * Internal function to count categories including subcategories
     *
     * @author Erik Spaan [espaan]
     * @return array
     */
    private function _countcategories($category, $property, $catregistry, $uid)
    {
        // Get the number of articles in this category within this category property
        $news_articlecount = ModUtil::apiFunc('News', 'user', 'countitems', array('status' => 0,
                    'filterbydate' => true,
                    'category' => array($property => $category['id']),
                    'catregistry' => $catregistry));

        $news_totalarticlecount = $news_articlecount;

        // Get the number of articles by the current uid in this category within this category property
        if ($uid > 0) {
            $news_yourarticlecount = ModUtil::apiFunc('News', 'user', 'countitems', array('status' => 0,
                        'filterbydate' => true,
                        'uid' => $uid,
                        'category' => array($property => $category['id']),
                        'catregistry' => $catregistry));
        } else {
            $news_yourarticlecount = 0;
        }

        // Check if this category is a leaf/endnode
        $subcats = CategoryUtil::getCategoriesByParentID($category['id']);
        if (!$category['is_leaf'] && !empty($subcats)) {
            $subcategories = array();
            foreach ($subcats as $cat) {
                $count = $this->_countcategories($cat, $property, $catregistry, $uid);
                // Add the subcategories count to this category
                $news_totalarticlecount += $count['category']['news_totalarticlecount'];
                $news_yourarticlecount += $count['category']['news_yourarticlecount'];
                $subcategories[] = $count;
            }
        } else {
            $subcategories = null;
        }

        $category['news_articlecount'] = $news_articlecount;
        $category['news_totalarticlecount'] = $news_totalarticlecount;
        $category['news_yourarticlecount'] = $news_yourarticlecount;
        // if a category image is available, store it for easy reuse
        if (isset($category['__ATTRIBUTES__']) && isset($category['__ATTRIBUTES__']['topic_image'])) {
            $category['catimage'] = $category['__ATTRIBUTES__']['topic_image'];
        }

        $return = array('category' => $category,
            'subcategories' => $subcategories);

        return $return;
    }
示例#27
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');
 }
示例#28
0
    /**
     * Get registered category for module property.
     *
     * @param string $modname   The module we wish to get the property for.
     * @param string $tablename The tablename for which we wish to get the property for.
     * @param string $property  The property name.
     * @param string $default   The default value to return if the requested value is not set (optional) (default=null).
     *
     * @return array The associative field array of registered categories for the specified module.
     */
    public static function getRegisteredModuleCategory($modname, $tablename, $property, $default = null)
    {
        if (!$modname || !$property) {
            return $default;
        }

        $fArr = self::getRegisteredModuleCategories($modname, $tablename);

        if ($fArr && isset($fArr[$property]) && $fArr[$property]) {
            return $fArr[$property];
        }

        // if we have a path default, we get the ID
        if ($default && !is_integer($default)) {
            $cat = CategoryUtil::getCategoryByPath($default);
            if ($cat) {
                $default = $cat['id'];
            }
        }

        return $default;
    }
示例#29
0
 public function copy($newParentID)
 {
     $data = $this->_objData;
     if (!$data) {
         return $data;
     }
     CategoryUtil::copyCategoriesByPath($data['ipath'], $newParentID);
 }
示例#30
0
 /**
  * Load the parameters.
  *
  * This method is static because it is also called by the
  * CategoryCheckboxList plugin
  *
  * @param object  &$list               The list object (here: $this).
  * @param boolean $includeEmptyElement Whether or not to include an empty null item.
  * @param array   $params              The parameters passed from the Smarty plugin.
  *
  * @return void
  */
 static function loadParameters(&$list, $includeEmptyElement, $params)
 {
     $all = isset($params['all']) ? $params['all'] : false;
     $lang = isset($params['lang']) ? $params['lang'] : ZLanguage::getLanguageCode();
     $list->category = isset($params['category']) ? $params['category'] : 0;
     $list->editLink = isset($params['editLink']) ? $params['editLink'] : true;
     $includeLeaf = isset($params['includeLeaf']) ? $params['includeLeaf'] : true;
     $includeRoot = isset($params['includeRoot']) ? $params['includeRoot'] : false;
     $path = isset($params['path']) ? $params['path'] : '';
     $pathfield = isset($params['pathfield']) ? $params['pathfield'] : 'path';
     $recurse = isset($params['recurse']) ? $params['recurse'] : true;
     $relative = isset($params['relative']) ? $params['relative'] : true;
     $sortField = isset($params['sortField']) ? $params['sortField'] : 'sort_value';
     $catField = isset($params['catField']) ? $params['catField'] : 'id';
     $allCats = array();
     // if we don't have a category-id we see if we can get a category by path
     if (!$list->category && $path) {
         $list->category = CategoryUtil::getCategoryByPath($path, $pathfield);
         $allCats = CategoryUtil::getSubCategoriesForCategory($list->category, $recurse, $relative, $includeRoot, $includeLeaf, $all, null, '', null, $sortField);
     } elseif (is_array($list->category) && isset($list->category['id']) && is_integer($list->category['id'])) {
         // check if we have an actual category object with a numeric ID set
         $allCats = CategoryUtil::getSubCategoriesForCategory($list->category, $recurse, $relative, $includeRoot, $includeLeaf, $all, null, '', null, $sortField);
     } elseif (is_numeric($list->category)) {
         // check if we have a numeric category
         $list->category = CategoryUtil::getCategoryByID($list->category);
         $allCats = CategoryUtil::getSubCategoriesForCategory($list->category, $recurse, $relative, $includeRoot, $includeLeaf, $all, null, '', null, $sortField);
     } elseif (is_string($list->category) && strpos($list->category, '/') === 0) {
         // check if we have a string/path category
         $list->category = CategoryUtil::getCategoryByPath($list->category, $pathfield);
         $allCats = CategoryUtil::getSubCategoriesForCategory($list->category, $recurse, $relative, $includeRoot, $includeLeaf, $all, null, '', null, $sortField);
     }
     if (!$allCats) {
         $allCats = array();
     }
     if ($list->mandatory) {
         $list->addItem(__('Choose one'), null);
     }
     $line = '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -';
     if ($includeEmptyElement) {
         $list->addItem('', null);
     }
     foreach ($allCats as $cat) {
         $cslash = StringUtil::countInstances(isset($cat['ipath_relative']) ? $cat['ipath_relative'] : $cat['ipath'], '/');
         $indent = '';
         if ($cslash > 0) {
             $indent = '| ' . substr($line, 0, $cslash * 2);
         }
         $catName = html_entity_decode(isset($cat['display_name'][$lang]) ? $cat['display_name'][$lang] : $cat['name']);
         $list->addItem($indent . ' ' . $catName, isset($cat[$catField]) ? $cat[$catField] : $cat['id']);
     }
 }